All files / api getSalesData.js

93.47% Statements 86/92
76.66% Branches 46/60
100% Functions 13/13
93.33% Lines 84/90

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293                                1x 14x 14x                 14x     1x                           8x               1x 14x   5x   3x   3x   3x           3x               1x 5x 5x   5x 1x   4x 1x     3x 3x 1x     2x     1x 1x                   1x                         1x 5x 5x       5x 5x     1x 3x 3x       3x   3x 3x 2x                       1x                       1x 3x         1x     2x 1x                     1x 1x                           1x 3x 3x       3x 3x 3x 3x 3x 3x     1x 2x 2x 1x     1x 1x 1x 1x 1x   1x 1x 1x                               1x             1x 14x   14x 14x                 14x   14x 1x     13x   13x       8x           13x 13x 13x     13x     14x        
import { getData } from '../utils/api';
import { __, _n, sprintf } from '@wordpress/i18n';
import { formatCurrency, formatCurrencyCompact, formatPercentage } from '../utils/formatting';
import { resolveChangeIndicator } from '../utils/changeIndicator';
 
/**
 * Get top performers
 *
 * @param { Object } args           - The arguments object.
 * @param { string } args.startDate - The start date for the data range.
 * @param { string } args.endDate   - The end date for the data range.
 * @param { string } args.range     - The range of data to retrieve.
 * @param { Object } args.filters   - Additional filters to apply to the data.
 *
 * @return {Promise<*>} The formatted number of live visitors.
 */
const getSales = async( args ) => {
	const { startDate, endDate, range, filters } = args;
	const { data } = await getData(
		'ecommerce/sales',
		startDate,
		endDate,
		range,
		{
			filters
		}
	);
	return transformSalesData( data );
};
 
const metricFields = {
	'conversion-rate': 'conversion_rate',
	'abandonment-rate': 'abandoned_rate',
	'average-order': 'average_order_value',
	'revenue': 'total_revenue'
};
 
/**
 * Get the value for a metric key from a period's data.
 *
 * @param {string} key  The metric key.
 * @param {Object} data The current or previous data object.
 * @return {number} The metric value.
 */
const getMetricValue = ( key, data ) => data[ metricFields[ key ] ] ?? 0;
 
/**
 * Get the default subtitle for a metric key.
 *
 * @param {string} key The metric key.
 * @return {string} The default subtitle.
 */
const getDefaultSubtitle = ( key ) => {
	switch ( key ) {
		case 'conversion-rate':
			return __( 'No conversion data available', 'burst-statistics' );
		case 'abandonment-rate':
			return __( 'No cart data available', 'burst-statistics' );
		case 'average-order':
			return __( 'No order data available', 'burst-statistics' );
		case 'revenue':
			return __( 'No revenue data available', 'burst-statistics' );
		default:
			return __( 'No data available', 'burst-statistics' );
	}
};
 
const gcd = ( a, b ) => ( 0 === b ? a : gcd( b, a % b ) );
 
/**
 * Get the conversion-rate subtitle describing the visitor-to-conversion ratio.
 *
 * @param {Object} current The current data object.
 * @return {string} The subtitle.
 */
const getConversionSubtitle = ( current ) => {
	const totalVisitors = parseInt( current.visitors );
	const totalConverted = parseInt( current.total_converted );
 
	if ( 0 >= totalVisitors || isNaN( totalVisitors ) ) {
		return __( 'No visitors in this period', 'burst-statistics' );
	}
	if ( 0 >= totalConverted || isNaN( totalConverted ) ) {
		return __( 'No conversions yet', 'burst-statistics' );
	}
 
	const roundedRatio = Math.round( totalVisitors / totalConverted );
	if ( 1 >= roundedRatio ) {
		return __( 'All visitors converted', 'burst-statistics' );
	}
 
	if ( 5 >= roundedRatio ) {
 
		// Small ratio — show "X of Y visitors convert"
		const divisor = gcd( totalConverted, totalVisitors );
		return sprintf(
 
			/* translators: 1: converted visitors, 2: total visitors */
			__( '%1$d of %2$d visitors convert', 'burst-statistics' ),
			Math.round( totalConverted / divisor ),
			Math.round( totalVisitors / divisor )
		);
	}
 
	// Larger ratios — use "1 in X visitors convert"
	return sprintf(
		_n(
 
			// translators: 1: ratio of visitors per conversion.
			'1 in %d visitor converts',
			'1 in %d visitors convert',
			roundedRatio,
			'burst-statistics'
		),
		roundedRatio
	);
};
 
const applyConversionRate = ( entry, current ) => {
	entry.icon = 'mouse-pointer-click';
	Iif ( ! current ) {
		return;
	}
 
	entry.value = formatPercentage( current.conversion_rate ?? 0 );
	entry.subtitle = getConversionSubtitle( current );
};
 
const applyAbandonmentRate = ( entry, current ) => {
	entry.icon = 'shopping-cart';
	Iif ( ! current ) {
		return;
	}
 
	entry.value = formatPercentage( current.abandoned_rate ?? 0 );
 
	const totalAbandoned = parseInt( current.total_abandoned, 10 );
	if ( 0 < totalAbandoned ) {
		entry.subtitle = sprintf(
			_n(
 
				// translators: 1: total abandoned carts.
				'%d cart was abandoned',
				'%d carts were abandoned',
				totalAbandoned,
				'burst-statistics'
			),
			totalAbandoned
		);
	} else {
		entry.subtitle = __( 'No carts were abandoned', 'burst-statistics' );
	}
};
 
/**
 * Get the average-order subtitle comparing against the previous period.
 *
 * @param {Object} current  The current data object.
 * @param {Object} previous The previous data object.
 * @param {string} currency The currency code.
 * @return {string} The subtitle.
 */
const getAverageOrderSubtitle = ( current, previous, currency ) => {
	if (
		! previous ||
		null === previous.average_order_value ||
		previous.average_order_value === undefined
	) {
		return __( 'No previous period data', 'burst-statistics' );
	}
 
	if ( previous.average_order_value < current.average_order_value ) {
		return sprintf(
			__(
 
				// translators: 1: previous average order value.
				'Up from %s last period',
				'burst-statistics'
			),
			formatCurrencyCompact( currency, previous.average_order_value )
		);
	}
 
	Eif ( previous.average_order_value > current.average_order_value ) {
		return sprintf(
			__(
 
				// translators: 1: previous average order value.
				'Down from %s last period',
				'burst-statistics'
			),
			formatCurrencyCompact( currency, previous.average_order_value )
		);
	}
 
	return __( 'No change from last period', 'burst-statistics' );
};
 
const applyAverageOrder = ( entry, current, previous ) => {
	entry.icon = 'receipt';
	Iif ( ! current ) {
		return;
	}
 
	const avg = current.average_order_value ?? 0;
	const currency = current.currency ?? 'USD';
	entry.value = formatCurrencyCompact( currency, avg );
	entry.exactValue = avg;
	entry.tooltipText = formatCurrency( currency, avg );
	entry.subtitle = getAverageOrderSubtitle( current, previous, currency );
};
 
const applyRevenue = ( entry, current ) => {
	entry.icon = 'banknote';
	if ( ! current ) {
		return;
	}
 
	const total = current.total_revenue ?? 0;
	const currency = current.currency ?? 'USD';
	entry.value = formatCurrencyCompact( currency, total );
	entry.exactValue = total;
	entry.tooltipText = formatCurrency( currency, total );
 
	const totalOrders = parseInt( current.total_orders );
	if ( 0 < totalOrders ) {
		entry.subtitle = sprintf(
			_n(
 
				// translators: 1: total successful orders.
				'%d successful order',
				'%d successful orders',
				totalOrders,
				'burst-statistics'
			),
			totalOrders
		);
	} else E{
		entry.subtitle = __( 'No orders in this period', 'burst-statistics' );
	}
};
 
const metricAppliers = {
	'conversion-rate': applyConversionRate,
	'abandonment-rate': applyAbandonmentRate,
	'average-order': applyAverageOrder,
	'revenue': applyRevenue
};
 
const transformSalesData = ( data ) => {
	const transformed = {};
 
	Object.entries( data ).forEach( ([ key, metric ]) => {
		const entry = {
			title: metric.label,
			value: '-',
			exactValue: null,
			subtitle: getDefaultSubtitle( key ),
			changeStatus: null,
			change: null,
			tooltipText: null
		};
		transformed[key] = entry;
 
		if ( ! metric || ! metric.label ) {
			return;
		}
 
		const { current, previous, rate_change } = metric;
 
		const indicator = resolveChangeIndicator({
			rateChange: rate_change,
			current,
			previous,
			getValue: ( periodData ) => getMetricValue( key, periodData ),
 
			// For abandonment rate, higher is bad, so statuses flip.
			invertPolarity: 'abandonment-rate' === key,
			noData: { change: '0%', changeStatus: 'positive' }
		});
		Eif ( indicator ) {
			entry.change = indicator.change;
			entry.changeStatus = indicator.changeStatus;
		}
 
		metricAppliers[key]?.( entry, current, previous );
	});
 
	return transformed;
};
 
export default getSales;