-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
989 lines (883 loc) · 27.5 KB
/
index.js
File metadata and controls
989 lines (883 loc) · 27.5 KB
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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
import fetch from "cross-fetch";
import AwesomeDebouncePromise from "awesome-debounce-promise";
import { batch } from "react-redux";
import { parsePhoneNumberFromString } from "libphonenumber-js";
import getCsrf from "../components/csrf";
import { MIN_FETCH_INTERVAL } from "../constants/sync_constants";
import { PATH_REGISTRATION_SCHEDULE_NAME } from "../constants/constants";
import { buildCourseSearchRequest } from "../util.ts";
export const UPDATE_SEARCH = "UPDATE_SEARCH";
export const UPDATE_SEARCH_REQUEST = "UPDATE_SEARCH_REQUEST";
export const UPDATE_COURSE_INFO_SUCCESS = "UPDATE_COURSE_INFO_SUCCESS";
export const UPDATE_COURSE_INFO_REQUEST = "UPDATE_COURSE_INFO_REQUEST";
export const UPDATE_SCROLL_POS = "UPDATE_SCROLL_POS";
export const UPDATE_SECTIONS = "UPDATE_SECTIONS";
export const OPEN_SECTION_INFO = "OPEN_SECTION_INFO";
export const OPEN_MODAL = "OPEN_MODAL";
export const CLOSE_MODAL = "CLOSE_MODAL";
export const COURSE_SEARCH_ERROR = "COURSE_SEARCH_ERROR";
export const COURSE_SEARCH_LOADING = "COURSE_SEARCH_LOADING";
export const COURSE_SEARCH_SUCCESS = "COURSE_SEARCH_SUCCESS";
export const LOAD_REQUIREMENTS = "LOAD_REQUIREMENTS";
export const ADD_SCHOOL_REQ = "ADD_SCHOOL_REQ";
export const REM_SCHOOL_REQ = "REM_SCHOOL_REQ";
export const UPDATE_SEARCH_TEXT = "UPDATE_SEARCH_TEXT";
export const UPDATE_RANGE_FILTER = "UPDATE_RANGE_FILTER";
export const UPDATE_CHECKBOX_FILTER = "UPDATE_CHECKBOX_FILTER";
export const UPDATE_BUTTON_FILTER = "UPDATE_BUTTON_FILTER";
export const CLEAR_FILTER = "CLEAR_FILTER";
export const CLEAR_ALL = "CLEAR_ALL";
export const UPDATE_SEARCH_FILTER = "UPDATE_SEARCH_FILTER";
export const SECTION_INFO_SEARCH_ERROR = "SECTION_INFO_SEARCH_ERROR";
export const SECTION_INFO_SEARCH_LOADING = "SECTION_INFO_SEARCH_LOADING";
export const SECTION_INFO_SEARCH_SUCCESS = "SECTION_INFO_SEARCH_SUCCESS";
export const ADD_CART_ITEM = "ADD_CART_ITEM";
export const REMOVE_CART_ITEM = "REMOVE_CART_ITEM";
export const CHANGE_SORT_TYPE = "CHANGE_SORT_TYPE";
export const REGISTER_ALERT_ITEM = "REGISTER_ALERT_ITEM";
export const REACTIVATE_ALERT_ITEM = "REACTIVATE_ALERT_ITEM";
export const DEACTIVATE_ALERT_ITEM = "DEACTIVATE_ALERT_ITEM";
export const DELETE_ALERT_ITEM = "DELETE_ALERT_ITEM";
export const UPDATE_CONTACT_INFO = "UPDATE_CONTACT_INFO";
export const MARK_ALERTS_SYNCED = "MARK_ALERTS_SYNCED";
export const TOGGLE_CHECK = "TOGGLE_CHECK";
export const REMOVE_SCHED_ITEM = "REMOVE_SCHED_ITEM";
export const CLEAR_ALL_SCHEDULE_DATA = "CLEAR_ALL_SCHEDULE_DATA";
export const CREATE_CART_ON_FRONTEND = "CREATE_CART_ON_FRONTEND";
export const CREATE_SCHEDULE_ON_FRONTEND = "CREATE_SCHEDULE_ON_FRONTEND";
export const DELETE_SCHEDULE_ON_FRONTEND = "DELETE_SCHEDULE_ON_FRONTEND";
export const CHANGE_MY_SCHEDULE = "CHANGE_MY_SCHEDULE";
export const RENAME_SCHEDULE = "RENAME_SCHEDULE";
export const CLEAR_SCHEDULE = "CLEAR_SCHEDULE";
export const UPDATE_SCHEDULES_ON_FRONTEND = "UPDATE_SCHEDULES_ON_FRONTEND";
export const MARK_SCHEDULE_SYNCED = "MARK_SCHEDULE_SYNCED";
export const MARK_CART_SYNCED = "MARK_CART_SYNCED";
export const DELETION_ATTEMPTED = "DELETION_ATTEMPTED";
export const SET_STATE_READ_ONLY = "SET_STATE_READ_ONLY";
export const SET_PRIMARY_SCHEDULE_ID_ON_FRONTEND =
"SET_PRIMARY_SCHEDULE_ID_ON_FRONTEND";
export const ADD_BREAK_ITEM = "ADD_BREAK_ITEM";
export const ADD_BREAK = "ADD_BREAK";
export const TOGGLE_BREAK = "TOGGLE_BREAK";
export const REMOVE_BREAK = "REMOVE_BREAK";
export const doAPIRequest = (path, options = {}) =>
fetch(`/api${path}`, options);
export const renameSchedule = (oldName, newName) => ({
type: RENAME_SCHEDULE,
oldName,
newName,
});
export const changeMySchedule = (scheduleName) => ({
type: CHANGE_MY_SCHEDULE,
scheduleName,
});
export const createCartOnFrontend = (cartId, cartSections) => ({
type: CREATE_CART_ON_FRONTEND,
cartId,
cartSections,
});
export const markScheduleSynced = (scheduleName) => ({
scheduleName,
type: MARK_SCHEDULE_SYNCED,
});
export const markCartSynced = () => ({
type: MARK_CART_SYNCED,
});
export const addCartItem = (section) => ({
type: ADD_CART_ITEM,
section,
});
export const removeSchedItem = (id, type) => ({
type: REMOVE_SCHED_ITEM,
itemType: type,
id,
});
export const updateSearch = (searchResults) => ({
type: UPDATE_SEARCH,
searchResults,
});
const updateSearchRequest = () => ({
type: UPDATE_SEARCH_REQUEST,
});
export const updateSections = (sections) => ({
type: UPDATE_SECTIONS,
sections,
});
export const updateSectionInfo = (sectionInfo) => ({
type: OPEN_SECTION_INFO,
sectionInfo,
});
const updateCourseInfoRequest = () => ({
type: UPDATE_COURSE_INFO_REQUEST,
});
export const updateCourseInfo = (course) => ({
type: UPDATE_COURSE_INFO_SUCCESS,
course,
});
export const updateScrollPos = (scrollPos = 0) => ({
type: UPDATE_SCROLL_POS,
scrollPos,
});
export const createScheduleOnFrontend = (
scheduleName,
scheduleId,
scheduleSections,
scheduleBreaks
) => ({
type: CREATE_SCHEDULE_ON_FRONTEND,
scheduleName,
scheduleId,
scheduleSections,
scheduleBreaks,
});
export const clearAllScheduleData = () => ({ type: CLEAR_ALL_SCHEDULE_DATA });
export const openModal = (modalKey, modalProps, modalTitle) => ({
type: OPEN_MODAL,
modalKey,
modalProps,
modalTitle,
});
export const closeModal = () => ({
type: CLOSE_MODAL,
});
export const clearSchedule = () => ({
type: CLEAR_SCHEDULE,
});
export const setPrimaryScheduleIdOnFrontend = (scheduleId) => ({
scheduleId,
type: SET_PRIMARY_SCHEDULE_ID_ON_FRONTEND,
});
export const addBreakItem = (name, days, timeRange, breakId) => ({
type: ADD_BREAK_ITEM,
name,
days,
timeRange,
id: breakId,
});
export const toggleBreak = (breakItem) => ({
type: TOGGLE_BREAK,
breakItem,
});
export const removeBreakFrontend = (breakId) => ({
type: REMOVE_BREAK,
id: breakId,
});
export const checkForDefaultSchedules = (schedulesFromBackend) => (
dispatch
) => {
if (!schedulesFromBackend.find((acc, { name }) => acc || name === "cart")) {
dispatch(createScheduleOnBackend("cart"));
}
// if the user doesn't have an initial schedule, create it
if (
schedulesFromBackend.length === 0 ||
(schedulesFromBackend.length === 1 &&
schedulesFromBackend[0].name === "cart")
) {
dispatch(createScheduleOnBackend("Schedule"));
}
};
export const loadRequirements = () => (dispatch) =>
doAPIRequest("/base/current/requirements/").then(
(response) =>
response.json().then(
(data) => {
const obj = {
SAS: [],
SEAS: [],
WH: [],
NURS: [],
};
const selObj = {};
data.forEach((element) => {
obj[element.school].push(element);
selObj[element.id] = 0;
});
dispatch({
type: LOAD_REQUIREMENTS,
obj,
selObj,
});
},
(error) => {
// eslint-disable-next-line no-console
console.log(error);
}
),
(error) => {
// eslint-disable-next-line no-console
console.log(error);
}
);
export function fetchCourseSearch(filterData) {
return (dispatch) => {
dispatch(updateSearchRequest());
debouncedAdvancedCourseSearch(
dispatch,
buildCourseSearchRequest(filterData)
)
// debouncedCourseSearch(dispatch, filterData)
.then((res) => res.json())
.then((res) => res.filter((course) => course.num_sections > 0))
.then((res) =>
batch(() => {
dispatch(updateScrollPos());
dispatch(updateSearch(res));
if (res.length === 1)
dispatch(fetchCourseDetails(res[0].id));
})
)
.catch((error) => dispatch(courseSearchError(error)));
};
}
function advancedCourseSearch(_, searchData) {
const empty = searchData.filters.children.length === 0;
return doAPIRequest(
`/base/current/search/courses/?search=${searchData.query}`,
{
method: empty ? "GET" : "POST",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
body: empty ? null : JSON.stringify(searchData.filters),
}
);
}
const debouncedAdvancedCourseSearch = AwesomeDebouncePromise(
advancedCourseSearch,
500
);
export function updateSearchText(s) {
return {
type: UPDATE_SEARCH_TEXT,
s,
};
}
function buildSectionInfoSearchUrl(searchData) {
return `/base/current/courses/${searchData.param}/`;
}
export function courseSearchError(error) {
return {
type: COURSE_SEARCH_ERROR,
error,
};
}
export function sectionInfoSearchError(error) {
return {
type: SECTION_INFO_SEARCH_ERROR,
error,
};
}
export function addSchoolReq(reqID) {
return {
type: ADD_SCHOOL_REQ,
reqID,
};
}
export function remSchoolReq(reqID) {
return {
type: REM_SCHOOL_REQ,
reqID,
};
}
export function updateRangeFilter(field, values) {
return {
type: UPDATE_RANGE_FILTER,
field,
values,
};
}
export function updateCheckboxFilter(field, value, toggleState) {
return {
type: UPDATE_CHECKBOX_FILTER,
field,
value,
toggleState,
};
}
export function updateButtonFilter(field, value) {
return {
type: UPDATE_BUTTON_FILTER,
field,
value,
};
}
export function clearFilter(propertyName) {
return {
type: CLEAR_FILTER,
propertyName,
};
}
export function updateSearchFilter(path, filters) {
return {
type: UPDATE_SEARCH_FILTER,
filters,
};
}
export const deletionAttempted = (scheduleName) => ({
type: DELETION_ATTEMPTED,
scheduleName,
});
export const deleteScheduleOnFrontend = (scheduleName) => ({
type: DELETE_SCHEDULE_ON_FRONTEND,
scheduleName,
});
export function clearAll() {
return {
type: CLEAR_ALL,
};
}
export const updateSchedulesOnFrontend = (schedulesFromBackend) => ({
type: UPDATE_SCHEDULES_ON_FRONTEND,
schedulesFromBackend,
});
export const setStateReadOnly = (readOnly) => ({
type: SET_STATE_READ_ONLY,
readOnly,
});
export function courseSearchLoading() {
return {
type: COURSE_SEARCH_LOADING,
};
}
export function courseSearchSuccess(items) {
return {
type: COURSE_SEARCH_SUCCESS,
items,
};
}
export const toggleCheck = (course) => ({
type: TOGGLE_CHECK,
course,
});
export const removeCartItem = (sectionId) => ({
type: REMOVE_CART_ITEM,
sectionId,
});
export const registerAlertFrontend = (alert) => ({
type: REGISTER_ALERT_ITEM,
alert,
});
export const reactivateAlertFrontend = (sectionId) => ({
type: REACTIVATE_ALERT_ITEM,
sectionId,
});
export const deactivateAlertFrontend = (sectionId) => ({
type: DEACTIVATE_ALERT_ITEM,
sectionId,
});
export const deleteAlertFrontend = (sectionId) => ({
type: DELETE_ALERT_ITEM,
sectionId,
});
export const updateContactInfoFrontend = (contactInfo) => ({
type: UPDATE_CONTACT_INFO,
contactInfo,
});
export const addBreakFrontend = (breakItem) => ({
type: ADD_BREAK,
breakItem,
});
export const toggleBreakFrontend = (breakItem) => ({
type: TOGGLE_BREAK,
breakItem,
});
export const markAlertsSynced = () => ({
type: MARK_ALERTS_SYNCED,
});
export const changeSortType = (sortMode) => ({
type: CHANGE_SORT_TYPE,
sortMode,
});
let lastFetched = 0;
/**
* Ensure that fetches don't happen too frequently by requiring that it has been 250ms
* since the last rate-limited fetch.
* @param url The url to fetch
* @param init The init to apply to the url
* @returns {Promise<unknown>}
*/
const rateLimitedFetch = (url, init) =>
new Promise((resolve, reject) => {
// Wraps the fetch in a new promise that conditionally rejects if
// the required amount of time has not elapsed
const now = Date.now();
if (now - lastFetched > MIN_FETCH_INTERVAL) {
doAPIRequest(url, init)
.then((result) => {
resolve(result);
})
.catch((err) => {
reject(err);
});
lastFetched = now;
} else {
reject(new Error("minDelayNotElapsed"));
}
});
export const deduplicateCourseMeetings = (course) => {
const deduplicatedCourse = {
...course,
sections: course.sections.map((section) => {
const meetings = [];
section.meetings.forEach((meeting) => {
const exists = meetings.some(
(existingMeeting) =>
existingMeeting.day === meeting.day &&
existingMeeting.start === meeting.start &&
existingMeeting.end === meeting.end
);
if (!exists) {
meetings.push(meeting);
}
});
return { ...section, meetings };
}),
};
return deduplicatedCourse;
};
export function fetchCourseDetails(courseId) {
return (dispatch) => {
dispatch(updateCourseInfoRequest());
doAPIRequest(`/base/current/courses/${courseId}/?include_location=True`)
.then((res) => res.json())
.then((data) => deduplicateCourseMeetings(data))
.then((course) => dispatch(updateCourseInfo(course)))
.catch((error) => dispatch(sectionInfoSearchError(error)));
};
}
const convertToTimeString = (decimalHour) => {
const hours24 = Math.floor(decimalHour);
const minutes = Math.round((decimalHour - hours24) * 60);
const period = hours24 >= 12 ? "PM" : "AM";
const hours12 = hours24 % 12 === 0 ? 12 : hours24 % 12;
const paddedMinutes = minutes.toString().padStart(2, "0");
return `${hours12}:${paddedMinutes} ${period}`;
};
function convertToHHMM(decimalHour) {
const hours = Math.floor(decimalHour);
const minutes = Math.round((decimalHour - hours) * 60);
return hours * 100 + minutes;
}
export const createBreakBackend = (name, days, timeRange) => (dispatch) => {
doAPIRequest("/plan/breaks/", {
method: "POST",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
body: JSON.stringify({
name,
location_string: "BREAK",
meetings: [
{
days: days.join(""),
begin_time_24: convertToHHMM(timeRange[0]),
end_time_24: convertToHHMM(timeRange[1]),
begin_time: convertToTimeString(timeRange[0]),
end_time: convertToTimeString(timeRange[1]),
},
],
}),
})
.then((res) => res.json())
.then((breakData) => {
dispatch(fetchBreaks(breakData.break_id));
});
};
export const removeBreakBackend = (breakId) => (dispatch) => {
doAPIRequest(`/plan/breaks/${breakId}/`, {
method: "DELETE",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
})
.then(() => {
dispatch(removeBreakFrontend(breakId));
})
.catch((error) => {
// eslint-disable-next-line no-console
console.log(error);
});
};
/**
* Pulls schedules from the backend
* @param onComplete The function to call when initialization has been completed (with the schedules
* from the backend)
* @returns {Function}
*/
export const fetchBackendSchedules = (onComplete) => (dispatch) => {
doAPIRequest("/plan/schedules/")
.then((res) => res.json())
.then((data) => data.map((course) => deduplicateCourseMeetings(course)))
.then((schedules) => {
onComplete(schedules);
})
// eslint-disable-next-line no-console
.catch((error) => console.log(error, "Not logged in"));
};
/**
* Updates a schedule on the backend
* Skips if the id is not yet initialized for the schedule
* Once the schedule has been updated, the schedule is marked as updated locally
* @param name The name of the schedule
* @param schedule The schedule object
*/
export const updateScheduleOnBackend = (name, schedule) => (dispatch) => {
const updatedScheduleObj = {
...schedule,
name,
sections: schedule.sections,
breaks: (schedule.breaks ?? []).map((breakItem) => {
return { ...breakItem.break, checked: breakItem.checked };
}),
};
doAPIRequest(`/plan/schedules/${schedule.id}/`, {
method: "PUT",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
body: JSON.stringify(updatedScheduleObj),
})
.then(() => {
if (name === "cart") {
dispatch(markCartSynced());
} else {
dispatch(markScheduleSynced(name));
}
})
.catch(() => {});
};
export function fetchSectionInfo(searchData) {
return (dispatch) =>
doAPIRequest(buildSectionInfoSearchUrl(searchData)).then(
(response) =>
response.json().then(
(json) => {
const info = {
id: json.id,
description: json.description,
crosslistings: json.crosslistings,
};
const { sections } = json;
dispatch(updateCourseInfo(sections, info));
},
(error) => dispatch(sectionInfoSearchError(error))
),
(error) => dispatch(sectionInfoSearchError(error))
);
}
/**
* Creates a schedule on the backend
* @param name The name of the schedule
* @param sections The list of sections for the schedule
* @returns {Function}
*/
export const createScheduleOnBackend = (name, sections = [], breaks = []) => (
dispatch
) => {
const scheduleObj = {
name,
sections,
breaks,
};
doAPIRequest("/plan/schedules/", {
method: "POST",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
body: JSON.stringify(scheduleObj),
})
.then((response) => response.json())
.then(({ id }) => {
dispatch(createScheduleOnFrontend(name, id, sections, breaks));
})
// eslint-disable-next-line no-console
.catch((error) => console.log(error));
};
export const deleteScheduleOnBackend = (user, scheduleName, scheduleId) => (
dispatch
) => {
if (
scheduleName === "cart" ||
scheduleName === PATH_REGISTRATION_SCHEDULE_NAME
) {
return;
}
dispatch(deletionAttempted(scheduleName));
rateLimitedFetch(`/plan/schedules/${scheduleId}/`, {
method: "DELETE",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
})
.then(() => {
dispatch(deleteScheduleOnFrontend(scheduleName));
dispatch(findOwnPrimarySchedule(user));
dispatch(
fetchBackendSchedules((schedulesFromBackend) => {
dispatch(checkForDefaultSchedules(schedulesFromBackend));
})
);
})
// eslint-disable-next-line no-console
.catch((error) => console.log(error));
};
export const findOwnPrimarySchedule = (user) => (dispatch) => {
doAPIRequest("/plan/primary-schedules/").then((res) =>
res
.json()
.then((schedules) => {
return schedules.find(
(sched) => sched.user.username === user.username
);
})
.then((foundSched) => {
dispatch(
setPrimaryScheduleIdOnFrontend(foundSched?.schedule.id)
);
})
// eslint-disable-next-line no-console
.catch((error) => console.log(error))
);
};
export const setCurrentUserPrimarySchedule = (user, scheduleId) => (
dispatch
) => {
const scheduleIdObj = {
schedule_id: scheduleId,
};
const init = {
method: "POST",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
body: JSON.stringify(scheduleIdObj),
};
doAPIRequest("/plan/primary-schedules/", init)
.then(() => {
dispatch(findOwnPrimarySchedule(user));
})
// eslint-disable-next-line no-console
.catch((error) => console.log(error));
};
export const registerAlertItem = (sectionId) => (dispatch) => {
const registrationObj = {
section: sectionId,
auto_resubscribe: true,
close_notification: false,
};
const init = {
method: "POST",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
body: JSON.stringify(registrationObj),
};
doAPIRequest("/alert/registrations/", init)
.then((res) => res.json())
.then((data) => {
dispatch(
registerAlertFrontend({
...registrationObj,
id: data.id,
cancelled: false,
status: "C",
})
);
});
};
export const reactivateAlertItem = (sectionId, alertId) => (dispatch) => {
const updateObj = {
resubscribe: true,
};
const init = {
method: "PUT",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
body: JSON.stringify(updateObj),
};
doAPIRequest(`/alert/registrations/${alertId}/`, init).then((res) => {
if (res.ok) {
dispatch(reactivateAlertFrontend(sectionId));
}
});
};
export const deactivateAlertItem = (sectionId, alertId) => (dispatch) => {
const updateObj = {
cancelled: true,
};
const init = {
method: "PUT",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
body: JSON.stringify(updateObj),
};
doAPIRequest(`/alert/registrations/${alertId}/`, init).then((res) => {
if (res.ok) {
dispatch(deactivateAlertFrontend(sectionId));
}
});
};
export const deleteAlertItem = (sectionId, alertId) => (dispatch) => {
const updateObj = {
deleted: true,
};
const init = {
method: "PUT",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
body: JSON.stringify(updateObj),
};
doAPIRequest(`/alert/registrations/${alertId}/`, init).then((res) => {
if (res.ok) {
dispatch(deleteAlertFrontend(sectionId));
}
});
};
export const fetchAlerts = () => (dispatch) => {
const init = {
method: "GET",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
};
doAPIRequest("/alert/registrations/", init)
.then((res) => res.json())
.then((alerts) => {
alerts.forEach((alert) => {
dispatch(
registerAlertFrontend({
id: alert.id,
section: alert.section,
cancelled: alert.cancelled,
auto_resubscribe: alert.auto_resubscribe,
close_notification: alert.close_notification,
status: alert.section_status,
})
);
});
})
// eslint-disable-next-line no-console
.catch((error) => console.log(error));
};
export const fetchContactInfo = () => (dispatch) => {
fetch("/accounts/me/", {
method: "GET",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
})
.then((res) => res.json())
.then((data) => {
dispatch(
updateContactInfoFrontend({
email: data.profile.email,
phone: data.profile.phone,
})
);
})
// eslint-disable-next-line no-console
.catch((error) => console.log(error));
};
export const updateContactInfo = (contactInfo) => (dispatch) => {
const profile = {
email: contactInfo.email,
phone:
parsePhoneNumberFromString(contactInfo.phone, "US")?.number ?? "",
};
fetch("/accounts/me/", {
method: "PATCH",
credentials: "include",
mode: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": getCsrf(),
},
body: JSON.stringify({
profile,
}),
}).then((res) => {
if (!res.ok) {
throw new Error(JSON.stringify(res));
} else {
dispatch(updateContactInfoFrontend(profile));
}
});
};
export const fetchBreaks = (breakId = null) => (dispatch) => {
doAPIRequest("/plan/breaks/")
.then((res) => res.json())
.then((breaks) => {
breaks.forEach((breakItem) => {
dispatch(addBreakFrontend(breakItem));
});
return breaks;
})
.then((breaks) => {
if (breakId !== null) {
dispatch(
toggleBreakFrontend(
breaks.find((breakItem) => breakItem.id === breakId)
)
);
}
})
// eslint-disable-next-line no-console
.catch((error) => console.log(error));
};