File size: 2,400 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
import { processQueryParams } from 'calypso/my-sites/stats/hooks/utils';
import { STATS_UTM_METRICS_REQUEST, STATS_UTM_TOP_POSTS_REQUEST } from 'calypso/state/action-types';
import { registerHandlers } from 'calypso/state/data-layer/handler-registry';
import { http } from 'calypso/state/data-layer/wpcom-http/actions';
import { dispatchRequest } from 'calypso/state/data-layer/wpcom-http/utils';
import {
	receiveMetrics,
	receiveMetricsByPost,
	requestMetricsFail,
	receiveTopPosts,
} from 'calypso/state/stats/utm-metrics/actions';
import type { AnyAction } from 'redux';

export const fetch = ( action: AnyAction ) => {
	const { siteId, utmParam, postId, query = {} } = action;
	const processedQuery = processQueryParams( query );

	return [
		http(
			{
				method: 'GET',
				path: `/sites/${ siteId }/stats/utm/${ utmParam }`,
				apiVersion: '1.1',
				query: {
					max: processedQuery.max,
					date: processedQuery.date,
					days: processedQuery.days,
					start_date: processedQuery.start_date || '',
					post_id: postId || '',
					// Only query top posts if postId is not provided or 0.
					query_top_posts: ! postId ? true : false,
				},
			},
			action
		),
	];
};

export const fetchTopPosts = ( action: AnyAction ) => {
	const { siteId, utmParam, paramValues } = action;

	return [
		http(
			{
				method: 'GET',
				path: `/sites/${ siteId }/stats/utm/${ utmParam }/top_posts`,
				apiVersion: '1.1',
				query: {
					utm_param_values: paramValues,
					max: 10,
					// Today's date in yyyy-mm-dd format.
					date: new Date().toISOString().split( 'T' )[ 0 ],
					days: 7,
				},
			},
			action
		),
	];
};

registerHandlers( 'state/data-layer/wpcom/sites/stats/utm-metrics/index.js', {
	[ STATS_UTM_METRICS_REQUEST ]: [
		dispatchRequest( {
			fetch,
			onSuccess: ( { siteId, postId, siteSlug, utmParam }: AnyAction, data: object ) => {
				if ( postId ) {
					return receiveMetricsByPost( siteId, postId, data );
				}

				return receiveMetrics( siteId, data, siteSlug, utmParam );
			},
			onError: ( { siteId }: AnyAction ) => requestMetricsFail( siteId ),
			// fromApi,
		} ),
	],
	[ STATS_UTM_TOP_POSTS_REQUEST ]: [
		dispatchRequest( {
			fetch: fetchTopPosts,
			onSuccess: ( { siteId, paramValues, siteSlug }: AnyAction, data: object ) =>
				receiveTopPosts( siteId, paramValues, data, siteSlug ),
			onError: () => null,
		} ),
	],
} );

export default {};