forked from superdesk/superdesk-planning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.ts
776 lines (695 loc) · 24.3 KB
/
api.ts
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
import {get, isEqual, cloneDeep, pickBy, has, find, every, take} from 'lodash';
import {planningApi} from '../../superdeskApi';
import {ISearchSpikeState, IEventSearchParams, IEventItem, IPlanningItem, IEventTemplate} from '../../interfaces';
import {appConfig} from 'appConfig';
import {
EVENTS,
POST_STATE,
MAIN,
TO_BE_CONFIRMED_FIELD,
} from '../../constants';
import * as selectors from '../../selectors';
import {
eventUtils,
getErrorMessage,
isExistingItem,
isValidFileInput,
isPublishedItemId,
isTemporaryId,
gettext,
getTimeZoneOffset,
} from '../../utils';
import planningApis from '../planning/api';
import eventsUi from './ui';
import main from '../main';
import {eventParamsToSearchParams} from '../../utils/search';
/**
* Action dispatcher to load a series of recurring events into the local store.
* This does not update the list of visible Events
* @param {string} rid
* @param {string} spikeState
* @param {int} page - The page number to fetch
* @param {int} maxResults - The number to events per page
* @param {boolean} loadToStore - To load events into store
*/
const loadEventsByRecurrenceId = (
rid: string,
spikeState: ISearchSpikeState = 'both',
page: number = 1,
maxResults: number = 25,
loadToStore: boolean = true
) => (
(dispatch) => (
planningApi.events.search({
recurrence_id: rid,
spike_state: spikeState,
page: page,
max_results: maxResults,
only_future: false,
include_killed: true,
})
.then((items) => {
if (loadToStore) {
dispatch(self.receiveEvents(items));
}
return Promise.resolve(items);
}, (error) => (
Promise.reject(error)
))
)
);
/**
* Action dispatcher to mark an Event as spiked using the API.
* @param {Array} events - An Array of Events to be spiked
*/
const spike = (events) => (
(dispatch, getState, {api}) => {
let eventsToSpike = (Array.isArray(events) ? events : [events]);
return Promise.all(
eventsToSpike.map((event) => {
event.update_method = get(event, 'update_method.value', EVENTS.UPDATE_METHODS[0].value);
return api.update(
'events_spike',
event,
{update_method: event.update_method}
);
})
)
.then(
() => Promise.resolve(eventsToSpike),
(error) => (Promise.reject(error))
);
}
);
const unspike = (events) => (
(dispatch, getState, {api}) => {
let eventsToUnspike = (Array.isArray(events) ? events : [events]);
return Promise.all(
eventsToUnspike.map((event) => {
event.update_method = get(event, 'update_method.value', EVENTS.UPDATE_METHODS[0].value);
return api.update(
'events_unspike',
event,
{update_method: event.update_method}
);
})
)
.then(
() => Promise.resolve(eventsToUnspike),
(error) => (Promise.reject(error))
);
}
);
// Action Dispatcher for query the api for events
function query(
params: IEventSearchParams = {},
storeTotal = false
) {
return (dispatch, getState) => {
let itemIds = [];
if (params.ids) {
const chunkSize = EVENTS.FETCH_IDS_CHUNK_SIZE;
if (params.ids.length <= chunkSize) {
itemIds = params.ids;
} else {
// chunk the requests
const requests = [];
for (let i = 0; i < Math.ceil(params.ids.length / chunkSize); i++) {
const args = {
// eslint-disable-next-line no-undef
...params,
ids: params.ids.slice(i * chunkSize, (i + 1) * chunkSize),
};
requests.push(dispatch(self.query(args)));
}
// flatten responses and return a response-like object
return Promise.all(requests).then((responses) => (
Array.prototype.concat.apply([], responses)
));
}
}
return planningApi.events.search(eventParamsToSearchParams({
...params,
itemIds: itemIds,
filter_id: params.filter_id || selectors.main.currentSearchFilterId(getState()),
}))
.then((response) => {
if (storeTotal) {
dispatch(main.setTotal(MAIN.FILTERS.EVENTS, response._meta?.total ?? 0));
}
return response._items;
}, (error) => Promise.reject(error));
};
}
/**
* Action Dispatcher to re-fetch the current list of events
* It achieves this by performing a fetch using the params from
* the store value `events.lastRequestParams`
*/
const refetch = (skipEvents = []) => (
(dispatch, getState) => {
const prevParams = selectors.main.lastRequestParams(getState());
const promises = [];
for (let i = 1; i <= prevParams.page; i++) {
const params = {
...prevParams,
page: i,
};
dispatch(eventsUi.requestEvents(params));
promises.push(dispatch(self.query(params, true)));
}
return Promise.all(promises)
.then((responses) => {
let events = Array.prototype.concat.apply([], responses);
dispatch(self.receiveEvents(events, skipEvents));
return Promise.resolve(events);
}, (error) => (Promise.reject(error)));
}
);
function loadEventDataForAction(
event: IEventItem,
loadPlanning: boolean = true,
post: boolean = false,
loadEvents: boolean = true,
loadEveryRecurringPlanning: boolean = false
): Promise<IEventItem & {
_recurring: Array<IEventItem>;
_post: boolean;
_events: Array<IEventItem>;
_originalEvent: IEventItem;
_plannings: Array<IPlanningItem>;
_relatedPlannings: Array<IPlanningItem>;
}> {
return planningApi.combined.getRecurringEventsAndPlanningItems(event, loadPlanning, loadEvents)
.then((items) => ({
...event,
_recurring: items.events,
_post: post,
_events: [],
_originalEvent: event,
_plannings: items.plannings,
_relatedPlannings: loadEveryRecurringPlanning ?
items.plannings :
items.plannings.filter(
(item) => item.event_item === event._id
),
}));
}
/**
* Action dispatcher to load all Planning items associated with an Event
* @param {object} event - The Event to load Planning items for
* @return Array of Planning items loaded
*/
const loadAssociatedPlannings = (event) => (
(dispatch) => {
if (get(event, 'planning_ids.length', 0) === 0) {
return Promise.resolve([]);
}
return dispatch(planningApis.loadPlanningByEventId(event._id));
}
);
/**
* Action dispatcher to get a single Event
* If the Event is already stored in the Redux store, then return that
* Otherwise fetch the Event from the server and optionally
* save the Event in the Redux store
* @param {string} eventId - The ID of the Event to retrieve
* @param {boolean} saveToStore - If true, save the Event in the Redux store
*/
function getEvent(eventId: IEventItem['_id'], saveToStore: boolean = true) {
return (dispatch, getState) => {
const events = selectors.events.storedEvents(getState());
if (events?.[eventId] != undefined) {
return Promise.resolve(events[eventId]);
}
return dispatch(self.silentlyFetchEventsById([eventId], 'both', saveToStore))
.then((items) => items[0]);
};
}
/**
* Action to receive the list of Events and store them in the store
* @param {Array} events - An array of Event items
* @return object
*/
const receiveEvents = (events, skipEvents: Array<any> = []) => ({
type: EVENTS.ACTIONS.ADD_EVENTS,
payload: get(skipEvents, 'length', 0) > 0 ?
events.filter((e) => !skipEvents.includes(e._id)) : events,
receivedAt: Date.now(),
});
/**
* Action Dispatcher to fetch events from the server,
* and add them to the store without adding them to the events list
* @param {Array, string} ids - Either an array of Event IDs or a single Event ID to fetch
* @param {string} spikeState - Event's spiked state (SPIKED, NOT_SPIKED or BOTH)
* @param {boolean} saveToStore - If true, save the Event in the Redux store
* @return arrow function
*/
function silentlyFetchEventsById(
ids: Array<IEventItem['_id']>,
spikeState: ISearchSpikeState = 'draft',
saveToStore: boolean = true
) {
return (dispatch) => (
planningApi.events.getByIds(
ids.filter((v, i, a) => (a.indexOf(v) === i)),
spikeState
)
.then((items) => {
if (saveToStore && items.length > 0) {
dispatch(self.receiveEvents(items));
}
return items;
})
);
}
/**
* Action Dispatcher to fetch a single event using its ID
* and add or update the Event in the Redux Store
* @param {string} eventId - The ID of the Event to fetch
* @param {boolean} force - Force using the API instead of Redux store
* @param {boolean} saveToStore - If true, save the Event item in the Redux store
* @param {boolean} loadPlanning - If true, load associated Planning items as well
*/
const fetchById = (eventId, {force = false, saveToStore = true, loadPlanning = true} = {}) => (
(dispatch, getState) => {
// Test if the Event item is already loaded into the store
// If so, return that instance instead
const storedEvents = selectors.events.storedEvents(getState());
let promise;
if (isPublishedItemId(eventId)) {
return Promise.resolve({});
}
if (has(storedEvents, eventId) && !force) {
promise = Promise.resolve(storedEvents[eventId]);
} else {
promise = planningApi.events.getById(eventId)
.then((event) => {
if (saveToStore) {
dispatch(self.receiveEvents([event]));
}
return Promise.resolve(event);
}, (error) => Promise.reject(error));
}
return promise.then((event) => {
if (loadPlanning) {
return dispatch(self.loadAssociatedPlannings(event))
.then(
() => Promise.resolve(event),
(error) => Promise.reject(error)
);
}
return Promise.resolve(event);
}, (error) => Promise.reject(error));
}
);
const cancelEvent = (original, updates) => (
(dispatch, getState, {api}) => (
api.update(
'events_cancel',
original,
{
update_method: get(updates, 'update_method.value', EVENTS.UPDATE_METHODS[0].value),
reason: get(updates, 'reason', undefined),
}
)
)
);
const rescheduleEvent = (original, updates) => (
(dispatch, getState, {api}) => (
api.update(
'events_reschedule',
original,
{
update_method: get(updates, 'update_method.value', EVENTS.UPDATE_METHODS[0].value),
dates: updates.dates,
reason: get(updates, 'reason', null),
}
)
)
);
const postponeEvent = (original, updates) => (
(dispatch, getState, {api}) => (
api.update(
'events_postpone',
original,
{
update_method: get(updates, 'update_method.value', EVENTS.UPDATE_METHODS[0].value),
reason: get(updates, 'reason', undefined),
}
)
)
);
/**
* Set event.pubstatus usable and post event.
*
* @param {Object} original - The original event item
* @param {Object} updates - The updates to the item
*/
const post = (original, updates) => (
(dispatch, getState, {api}) => (
api.save('events_post', {
event: original._id,
etag: original._etag,
pubstatus: get(updates, 'pubstatus', POST_STATE.USABLE),
update_method: get(updates, 'update_method.value', EVENTS.UPDATE_METHODS[0].value),
}).then(
() => dispatch(self.fetchById(original._id, {force: true})),
(error) => Promise.reject(error)
)
)
);
/**
* Set event.pubstatus canceled and post event.
*
* @param {Object} original - The original event item
* @param {Object} updates - The updates to the item
*/
const unpost = (original, updates) => (
(dispatch, getState, {api}) => (
api.save('events_post', {
event: original._id,
etag: original._etag,
pubstatus: get(updates, 'pubstatus', POST_STATE.CANCELLED),
update_method: get(updates, 'update_method.value', EVENTS.UPDATE_METHODS[0].value),
}).then(
() => dispatch(self.fetchById(original._id, {force: true})),
(error) => Promise.reject(error)
)
)
);
const updateEventTime = (original, updates) => (
(dispatch, getState, {api}) => {
if (get(updates, TO_BE_CONFIRMED_FIELD)) {
return dispatch(main.saveAndUnlockItem(original, {
[TO_BE_CONFIRMED_FIELD]: true,
update_method: get(updates, 'update_method'),
}, true));
}
return api.update(
'events_update_time',
original,
{
update_method: get(updates, 'update_method.value', EVENTS.UPDATE_METHODS[0].value),
dates: updates.dates,
[TO_BE_CONFIRMED_FIELD]: false,
}
);
}
);
const markEventCancelled = (eventId, etag, reason, occurStatus, cancelledItems, actionedDate) => ({
type: EVENTS.ACTIONS.MARK_EVENT_CANCELLED,
payload: {
event_id: eventId,
etag: etag,
reason: reason,
occur_status: occurStatus,
cancelled_items: cancelledItems,
actionedDate: actionedDate,
},
});
function markEventPostponed(event: IEventItem, reason: string, actionedDate: string) {
return (dispatch) => {
planningApi.locks.setItemAsUnlocked({
item: event._id,
type: event.type,
recurrence_id: event.recurrence_id,
etag: event._etag,
from_ingest: false,
user: event.lock_user,
lock_session: event.lock_session,
});
dispatch({
type: EVENTS.ACTIONS.MARK_EVENT_POSTPONED,
payload: {
event: event,
reason: reason,
actionedDate: actionedDate,
},
});
};
}
const markEventHasPlannings = (event, planning) => ({
type: EVENTS.ACTIONS.MARK_EVENT_HAS_PLANNINGS,
payload: {
event_item: event,
planning_item: planning,
},
});
/**
* Action Dispatcher to fetch event history from the server
* This will add the history of action on that event in event history list
* @param {object} eventId - Query parameters to send to the server
* @return arrow function
*/
const fetchEventHistory = (eventId) => (
(dispatch, getState, {api}) => (
// Query the API and sort by created
api('events_history').query({
where: {event_id: eventId},
max_results: 200,
sort: '[(\'_created\', 1)]',
})
.then((data) => (Promise.resolve(data._items))
)
));
const uploadFiles = (event) => (
(dispatch, getState, {upload}) => {
const clonedEvent = cloneDeep(event);
// If no files, do nothing
if (get(clonedEvent, 'files.length', 0) === 0) {
return Promise.resolve([]);
}
// Calculate the files to upload
const filesToUpload = clonedEvent.files.filter(
(f) => isValidFileInput(f)
);
if (filesToUpload.length < 1) {
return Promise.resolve([]);
}
return Promise.all(filesToUpload.map((file) => (
upload.start({
method: 'POST',
url: appConfig.server.url + '/events_files/',
headers: {'Content-Type': 'multipart/form-data'},
data: {media: [file]},
arrayKey: '',
})
)))
.then((results) => {
const files = results.map((res) => res.data);
if (get(files, 'length', 0) > 0) {
dispatch({
type: 'RECEIVE_FILES',
payload: files,
});
}
return Promise.resolve(files);
}, (error) => Promise.reject(error));
}
);
const save = (original, updates) => (
(dispatch) => {
let promise;
if (original) {
promise = Promise.resolve(original);
} else if (isExistingItem(updates)) {
promise = dispatch(
self.fetchById(updates._id, {saveToStore: false, loadPlanning: false})
);
} else {
promise = Promise.resolve({});
}
return promise.then((originalEvent) => {
const originalItem = eventUtils.modifyForServer(cloneDeep(originalEvent), true);
// clone the updates as we're going to modify it
let eventUpdates = eventUtils.modifyForServer(
cloneDeep(updates),
true
);
originalItem.location = originalItem.location ? [originalItem.location] : null;
// remove all properties starting with _
// and updates that are the same as original
eventUpdates = pickBy(eventUpdates, (v, k) => (
(k === TO_BE_CONFIRMED_FIELD || k === '_planning_item' || !k.startsWith('_')) &&
!isEqual(eventUpdates[k], originalItem[k])
));
if (get(originalItem, 'lock_action') === EVENTS.ITEM_ACTIONS.EDIT_EVENT.lock_action &&
!isTemporaryId(originalItem._id)
) {
delete eventUpdates.dates;
}
eventUpdates.update_method = get(eventUpdates, 'update_method.value') ||
EVENTS.UPDATE_METHODS[0].value;
return originalEvent?._id != null ?
planningApi.events.update(originalItem, eventUpdates) :
planningApi.events.create(eventUpdates);
});
}
);
const updateRepetitions = (original, updates) => (
(dispatch, getState, {api}) => (
api.update(
'events_update_repetitions',
original,
{dates: updates.dates}
)
)
);
const fetchEventFiles = (event) => (
(dispatch, getState, {api}) => {
if (!eventUtils.shouldFetchFilesForEvent(event)) {
return Promise.resolve();
}
const filesInStore = selectors.general.files(getState());
if (every(event.files, (f) => f in filesInStore)) {
return Promise.resolve();
}
return api('events_files').query(
{
where: {$and: [{_id: {$in: event.files}}]},
}
)
.then((data) => {
if (get(data, '_items.length')) {
dispatch({
type: 'RECEIVE_FILES',
payload: get(data, '_items'),
});
}
return Promise.resolve();
});
}
);
const removeFile = (file) => (
(dispatch, getState, {api, notify}) => (
api('events_files').remove(file)
.then(() => {
dispatch({
type: 'REMOVE_FILE',
payload: file._id,
});
}, (err) => {
notify.error(
getErrorMessage(err, gettext('Failed to remove the file from event.'))
);
return Promise.reject(err);
})
)
);
const fetchCalendars = () => (
(dispatch, getState, {vocabularies}) => (
vocabularies.getVocabularies()
.then((vocabularies) => {
const vocab = find(vocabularies, {_id: 'event_calendars'});
const calendars = get(vocab, 'items') || [];
dispatch(self.receiveCalendars(calendars));
return Promise.resolve(calendars);
}, (error) => Promise.reject(error))
)
);
const receiveCalendars = (calendars) => ({
type: EVENTS.ACTIONS.RECEIVE_CALENDARS,
payload: calendars,
});
const fetchEventTemplates = () => (dispatch, getState, {api}) => {
api('recent_events_template').query()
.then((res) => {
dispatch({type: EVENTS.ACTIONS.RECEIVE_EVENT_TEMPLATES, payload: res._items});
});
};
const createEventTemplate = (itemId) => (dispatch, getState, {api, modal, notify}) => {
modal.prompt(gettext('Template name')).then((templateName) => {
api('events_template').query({
where: {
template_name: {
$regex: templateName,
$options: 'i',
},
},
})
.then((res) => {
const doSave = () => {
api('events_template').save({
template_name: templateName,
based_on_event: itemId,
})
.then(() => {
dispatch(fetchEventTemplates());
dispatch(getEventsRecentTemplates());
}, (error) => {
notify.error(
getErrorMessage(error, gettext('Failed to save the event template'))
);
return Promise.reject(error);
});
};
const templateAlreadyExists = res._meta.total !== 0;
if (templateAlreadyExists) {
modal.confirm(gettext(
'Template already exists. Do you want to overwrite it?'
))
.then(() => {
api.remove(res._items[0], {}, 'events_template').then(doSave);
});
} else {
doSave();
}
});
});
};
const RECENT_EVENTS_TEMPLATES_KEY = 'events_templates:recent';
const addEventRecentTemplate = (field: string, templateId: IEventTemplate['_id']) => (
(dispatch, getState, {preferencesService}) => preferencesService.get()
.then((result = {}) => {
result[RECENT_EVENTS_TEMPLATES_KEY] = result[RECENT_EVENTS_TEMPLATES_KEY] || {};
result[RECENT_EVENTS_TEMPLATES_KEY][field] = result[RECENT_EVENTS_TEMPLATES_KEY][field] || [];
result[RECENT_EVENTS_TEMPLATES_KEY][field] = result[RECENT_EVENTS_TEMPLATES_KEY][field].filter(
(i) => i !== templateId);
result[RECENT_EVENTS_TEMPLATES_KEY][field].unshift(templateId);
return preferencesService.update(result);
})
);
const getEventsRecentTemplates = () => (
(dispatch, getState, {preferencesService}) => preferencesService.get()
.then((result) => {
const templates = take(result?.[RECENT_EVENTS_TEMPLATES_KEY]?.['templates'], 5);
dispatch({type: EVENTS.ACTIONS.EVENT_RECENT_TEMPLATES, payload: templates});
})
);
// eslint-disable-next-line consistent-this
const self = {
loadEventsByRecurrenceId,
spike,
unspike,
query,
refetch,
receiveEvents,
silentlyFetchEventsById,
cancelEvent,
markEventCancelled,
markEventHasPlannings,
rescheduleEvent,
updateEventTime,
markEventPostponed,
postponeEvent,
loadEventDataForAction,
getEvent,
loadAssociatedPlannings,
post,
fetchEventHistory,
unpost,
uploadFiles,
save,
fetchById,
updateRepetitions,
fetchCalendars,
receiveCalendars,
fetchEventFiles,
removeFile,
fetchEventTemplates,
createEventTemplate,
addEventRecentTemplate,
getEventsRecentTemplates,
};
export default self;