File size: 4,812 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
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
import { useQuery, UseQueryResult, type QueryObserverOptions } from '@tanstack/react-query';
import { useCallback } from 'react';
import wpcomRequest from 'wpcom-proxy-request';
import { useLocalizedMoment } from 'calypso/components/localized-moment';
import { useSelector } from 'calypso/state';
import getSites from 'calypso/state/selectors/get-sites';
import type { SiteDetails } from '@automattic/data-stores';
import type { SiteSlug } from 'calypso/types';

type LastRunStatus =
	| 'in-progress'
	| 'success'
	| 'failure'
	| 'failure-and-rollback'
	| 'failure-and-rollback-fail'
	| null;

export type ScheduleUpdates = {
	id: string;
	hook?: string;
	interval: number;
	timestamp: number;
	schedule: 'weekly' | 'daily';
	args: string[];
	last_run_status: LastRunStatus;
	last_run_timestamp: number | null;
	health_check_paths?: string[];
	active: boolean;
};

export type MultisiteSiteDetails = SiteDetails & {
	active: boolean;
	last_run_status: LastRunStatus;
	last_run_timestamp: number | null;
};

export type MultisiteSchedulesUpdates = Omit<
	ScheduleUpdates,
	'active' | 'last_run_status' | 'last_run_timestamp'
> & {
	schedule_id: string;
	sites: MultisiteSiteDetails[];
};

export type MultisiteSchedulesUpdatesResponse = {
	sites: { [ site_id: string ]: { [ scheduleId: string ]: ScheduleUpdates } };
};

export const useUpdateScheduleQuery = (
	siteSlug: SiteSlug,
	isEligibleForFeature: boolean,
	queryOptions: Partial< QueryObserverOptions< ScheduleUpdates[], Error > > = {}
): UseQueryResult< ScheduleUpdates[] > => {
	const select = ( data: ScheduleUpdates[] ) => {
		return data.sort( ( a, b ) => {
			if ( a.timestamp === undefined || b.timestamp === undefined ) {
				return 0;
			}
			// Sort other objects based on timestamp
			return a.timestamp - b.timestamp;
		} );
	};

	return useQuery( {
		queryKey: [ 'schedule-updates', siteSlug ],
		queryFn: () =>
			wpcomRequest< { [ key: string ]: ScheduleUpdates } >( {
				path: `/sites/${ siteSlug }/update-schedules`,
				apiNamespace: 'wpcom/v2',
				method: 'GET',
			} ).then( ( response ) =>
				Object.keys( response ).map( ( id ) => ( {
					...response[ id ],
					id,
				} ) )
			),
		enabled: !! siteSlug && isEligibleForFeature,
		retry: false,
		select,
		refetchOnWindowFocus: false,
		...queryOptions,
	} );
};

export const useMultisiteUpdateScheduleQuery = (
	isEligibleForFeature: boolean,
	queryOptions = {}
): UseQueryResult< MultisiteSchedulesUpdates[] > => {
	const moment = useLocalizedMoment();

	const sites = useSelector( getSites );
	const retrieveSite = useCallback(
		( siteId: number ) => {
			return sites.find( ( site ) => site?.ID === siteId );
		},
		[ sites ]
	);

	const generateId = useCallback(
		( scheduleId: string, timestamp: number, schedule: 'weekly' | 'daily', interval: number ) => {
			// get hh:mm from timestamp using moment
			const tm = moment( timestamp * 1000 );
			const time = tm.format( 'HH:mm' );
			return `${ scheduleId }-${ schedule }-${ interval }-${ time }`;
		},
		[]
	);

	return useQuery< MultisiteSchedulesUpdatesResponse, Error, MultisiteSchedulesUpdates[] >( {
		queryKey: [ 'multisite-schedules-update' ],
		queryFn: () =>
			wpcomRequest< MultisiteSchedulesUpdatesResponse >( {
				path: '/hosting/update-schedules',
				apiNamespace: 'wpcom/v2',
				method: 'GET',
			} ),
		enabled: isEligibleForFeature,
		retry: false,
		select: ( data ) => {
			const result: MultisiteSchedulesUpdates[] = [];

			for ( const site_id in data.sites ) {
				for ( const scheduleId in data.sites[ site_id ] ) {
					const {
						timestamp,
						schedule,
						args,
						interval,
						last_run_timestamp,
						last_run_status,
						active,
					} = data.sites[ site_id ][ scheduleId ];

					const id = generateId( scheduleId, timestamp, schedule, interval );

					const existingSchedule = result.find(
						( item ) =>
							generateId( item.schedule_id, item.timestamp, item.schedule, item.interval ) === id
					);

					const site = retrieveSite( parseInt( site_id, 10 ) ) as SiteDetails;
					if ( existingSchedule ) {
						existingSchedule.sites.push( {
							...site,
							active,
							last_run_status,
							last_run_timestamp,
						} );
					} else {
						result.push( {
							id,
							schedule_id: scheduleId,
							timestamp,
							schedule,
							args,
							interval,
							sites: [
								{
									...site,
									active,
									last_run_status,
									last_run_timestamp,
								},
							],
						} );
					}
				}
			}

			// sort by schedule (daily/weekly) then timestamp
			result.sort( ( a, b ) => {
				if ( a.schedule === b.schedule ) {
					return a.timestamp - b.timestamp;
				}
				return a.schedule.localeCompare( b.schedule );
			} );

			return result;
		},
		refetchOnWindowFocus: false,
		...queryOptions,
	} );
};