File size: 2,383 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
import { translate } from 'i18n-calypso';
import {
	HOSTING_WP_VERSION_REQUEST,
	HOSTING_WP_VERSION_SET_REQUEST,
	HOSTING_WP_VERSION_SET,
} from 'calypso/state/action-types';
import { composeAnalytics, recordTracksEvent } from 'calypso/state/analytics/actions';
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, successNotice } from 'calypso/state/notices/actions';

const updateNoticeId = 'hosting-wp-version';

const getWpVersion = ( action ) =>
	http(
		{
			method: 'GET',
			path: `/sites/${ action.siteId }/hosting/wp-version`,
			apiNamespace: 'wpcom/v2',
			body: {},
		},
		action
	);

const getWpVersionSuccess = ( action, version ) => {
	return {
		type: HOSTING_WP_VERSION_SET,
		siteId: action.siteId,
		version,
	};
};

const updateWpVersion = ( action ) =>
	http(
		{
			method: 'POST',
			path: `/sites/${ action.siteId }/hosting/wp-version`,
			apiNamespace: 'wpcom/v2',
			body: {
				version: action.version,
			},
		},
		action
	);

export const hostingWpVersionUpdateTracking = ( version, result ) =>
	composeAnalytics(
		recordTracksEvent( 'calypso_hosting_configuration_wp_version_update', {
			result,
			version,
		} )
	);

const updateWpVersionSuccess = ( action ) => {
	return [
		hostingWpVersionUpdateTracking( action.version, true ),
		{
			type: HOSTING_WP_VERSION_SET,
			siteId: action.siteId,
			version: action.version,
		},
		successNotice(
			translate( 'WordPress version successfully set to %(version)s.', {
				args: {
					version: action.version,
				},
			} ),
			{
				id: updateNoticeId,
				showDismiss: false,
				duration: 5000,
			}
		),
	];
};

const updateWpVersionError = ( action ) => {
	return [
		hostingWpVersionUpdateTracking( action.version, false ),
		errorNotice( translate( 'Failed to set WordPress version.' ), {
			id: updateNoticeId,
		} ),
	];
};

registerHandlers( 'state/data-layer/wpcom/sites/hosting/wp-version.js', {
	[ HOSTING_WP_VERSION_SET_REQUEST ]: [
		dispatchRequest( {
			fetch: updateWpVersion,
			onSuccess: updateWpVersionSuccess,
			onError: updateWpVersionError,
		} ),
	],
	[ HOSTING_WP_VERSION_REQUEST ]: [
		dispatchRequest( {
			fetch: getWpVersion,
			onSuccess: getWpVersionSuccess,
		} ),
	],
} );