File size: 5,742 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { formatCurrency, formatNumber } from '@automattic/number-formatters';
import { translate } from 'i18n-calypso';
import { find } from 'lodash';
import moment from 'moment'; // No localization needed in this file.
import qs from 'qs';
import { UNITS } from './constants';

/**
 * Calculate a date as the first date in each block of periods counting back from today. The number
 * of periods in a block is determined in the UNITS constants config.
 * @param {string} date - Date to calculate from
 * @param {string} unit - Unit to use in calculation
 * @returns {string} - YYYY-MM-DD format of the date to be queried
 */
export function getStartDate( date, unit ) {
	const unitConfig = UNITS[ unit ];
	const today = moment();
	const startDate = moment( date ); // Defaults to today if startDate undefined
	const duration = moment.duration( today - startDate )[ unitConfig.durationFn ]();
	const validDuration = duration > 0 ? duration : 0;
	const unitQuantity = unitConfig.quantity;
	const periods = Math.floor( validDuration / unitQuantity ) * unitQuantity;
	return today.subtract( periods, unitConfig.label ).format( 'YYYY-MM-DD' );
}

/**
 * Given a startDate query parameter, determine which date to send the backend on a request for data.
 * @param {Object} context - Object supplied by page function
 * @returns {string} - YYYY-MM-DD format of the date to be queried
 */
export function getQueryDate( context ) {
	const { unit } = context.params;
	return getStartDate( context.query.startDate, unit );
}

/**
 * Given a full date YYYY-MM-DD and unit ('day', 'week', 'month', 'year') return a shortened
 * and contextually relevant date.
 * @param {string} date - string date in YYYY-MM-DD format
 * @param {string} unit - string representing unit required for API eg. ('day', 'week', 'month', 'year')
 * @returns {string} - as required by the API, eg for unit 'week', '2017-W27' isoWeek returned
 */
export function getUnitPeriod( date, unit ) {
	return moment( date ).format( UNITS[ unit ].format );
}

/**
 * Given a full date YYYY-MM-DD and unit ('day', 'week', 'month', 'year') return the last date
 * for the period formatted as YYYY-MM-DD
 * @param {string} date - string date in YYYY-MM-DD format
 * @param {string} unit - string representing unit required for API eg. ('day', 'week', 'month', 'year')
 * @returns {string} - YYYY-MM-DD format of the date to be queried
 */
export function getEndPeriod( date, unit ) {
	return unit === 'week'
		? moment( date ).endOf( 'isoWeek' ).format( 'YYYY-MM-DD' )
		: moment( date ).endOf( unit ).format( 'YYYY-MM-DD' );
}

/**
 * Given a value and format option of 'text', 'number' and 'currency' return a formatted value.
 * @param {(string|number)} value - string or number to be formatted
 * @param {string} format - string of 'text', 'number' or 'currency'
 * @param {string} [code] - optional currency code
 * @param {number} [decimals] - optional number of decimal places
 * @returns {string|number} - formatted number or string value
 */
export function formatValue( value, format, code, decimals ) {
	switch ( format ) {
		case 'currency':
			return formatCurrency( value, code );
		case 'number':
			return formatNumber( value, { ...( typeof decimals === 'number' && { decimals } ) } );
		case 'percent':
			return translate( '%(percentage)s%% ', { args: { percentage: value }, context: 'percent' } );
		case 'text':
		default:
			return value;
	}
}

/**
 * Given a date, return the delta object for a specific stat
 * @param {Array} deltas - an array of delta objects
 * @param {string} selectedDate - string of date in 'YYYY-MM-DD'
 * @param {string} stat - string of stat to be referenced
 * @returns {Array} - array of delta objects matching selectedDate
 */
export function getDelta( deltas, selectedDate, stat ) {
	const selectedDeltas = find( deltas, ( item ) => item.period === selectedDate );
	return ( selectedDeltas && selectedDeltas[ stat ] ) || [];
}

/**
 * Given a unit and basedate, generate the queries needed for QuerySiteStats and getSiteStatsNormalizedData.
 * An optional overrides object can be passed to change values. Currently accepted:
 * orderQuery, topEarnersQuery, visitorQuery.
 * @param {string} unit - unit/period format for the data provided
 * @param {string} baseDate - string of date in 'YYYY-MM-DD'
 * @param {Object} overrides - Object of query overrides. Example: { orderQuery: { quantity: 1 }
 * @returns {Object}
 */
export function getQueries( unit, baseDate, overrides = {} ) {
	const baseQuery = { unit };

	const orderQuery = {
		...baseQuery,
		date: getUnitPeriod( baseDate, unit ),
		quantity: UNITS[ unit ].quantity,
		...( overrides.orderQuery || {} ),
	};

	const topListQuery = {
		...baseQuery,
		date: getUnitPeriod( baseDate, unit ),
		limit: 10,
		...( overrides.topListQuery || {} ),
	};

	const visitorQuery = {
		...baseQuery,
		date: baseDate,
		quantity: UNITS[ unit ].quantity,
		...( overrides.visitorQuery || {} ),
	};

	return {
		orderQuery,
		topListQuery,
		visitorQuery,
	};
}

/**
 * Create the common Store Stats url ending used for links to widgets and lists. Url query parameters
 * persist from view to view (ie, startDate) and should be reflected in the url.
 * Url's have this basic shape:
 *
 * /store/stats/<page>/<unit>/<slug>?param1=1&param2=2
 *
 * this util is for constructing the /<unit>/<slug>?param1=1&param2=2
 * @param {string} unit - day, week, month, or year
 * @param {string} slug - site slug
 * @param {Object} urlQuery - url query params represented as an object
 * @returns {string} - widget path url portion
 */
export function getWidgetPath( unit, slug, urlQuery ) {
	const query = qs.stringify( urlQuery, { addQueryPrefix: true } );
	return `/${ unit }/${ slug }${ query }`;
}