File size: 1,736 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
import { translate } from 'i18n-calypso';
import {
	SITE_INTRO_OFFER_RECEIVE,
	SITE_INTRO_OFFER_REQUEST,
	SITE_INTRO_OFFER_REQUEST_FAILURE,
	SITE_INTRO_OFFER_REQUEST_SUCCESS,
} 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 { errorNotice } from 'calypso/state/notices/actions';

const fetchIntroOffers = ( action: { siteId: number | 'none'; currency: string | undefined } ) => {
	return http(
		{
			method: 'GET',
			path: '/introductory-offers',
			apiNamespace: 'wpcom/v2',
			query: {
				site: typeof action.siteId === 'number' && action.siteId > 0 ? action.siteId : undefined,
				currency:
					typeof action.currency === 'string' && action.currency.length > 0
						? action.currency
						: undefined,
			},
		},
		action
	);
};

const onUpdateSuccess = ( action: { siteId: number | 'none' }, response: unknown ) => {
	return [
		{
			type: SITE_INTRO_OFFER_REQUEST_SUCCESS,
			siteId: action.siteId,
		},
		{
			type: SITE_INTRO_OFFER_RECEIVE,
			siteId: action.siteId,
			payload: response,
		},
	];
};

const onUpdateError = ( action: { siteId: number | 'none' } ) => {
	return [
		{
			type: SITE_INTRO_OFFER_REQUEST_FAILURE,
			siteId: action.siteId,
		},
		errorNotice(
			translate( 'Error loading introductory discounts. Some displayed prices may be incorrect.' )
		),
	];
};

registerHandlers( 'state/data-layer/wpcom/intro-offers/index.js', {
	[ SITE_INTRO_OFFER_REQUEST ]: [
		dispatchRequest( {
			fetch: fetchIntroOffers,
			onSuccess: onUpdateSuccess,
			onError: onUpdateError,
		} ),
	],
} );