-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
1914 lines (1748 loc) · 56.8 KB
/
main.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
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
990
991
992
993
994
995
996
997
998
999
1000
/*
GLOBAL SETTINGS
*/
const ARC_APP_DEBUG_MODE: boolean = true
/*
Shared with the other file
*/
export enum ModStatus {
UNFREE,
FREE,
DROP_IN,
BOOKED,
MATCHED,
FREE_PREF,
DROP_IN_PREF,
}
export enum SchedulingReference {
BOOKING,
MATCHING,
}
export function schedulingTutorIndex(
tutorRecords: TableInfo.RecCollection<'tutors'>,
bookingRecords: TableInfo.RecCollection<'bookings'>,
matchingRecords: TableInfo.RecCollection<'matchings'>
) {
const tutorIndex: {
[id: number]: {
id: number
modStatus: ModStatus[]
refs: [SchedulingReference, number][]
isInMod: boolean
}
} = {}
for (const tutor of Object.values(tutorRecords)) {
tutorIndex[tutor.id] = {
id: tutor.id,
modStatus: Array(20).fill(ModStatus.UNFREE),
refs: [],
isInMod: false,
}
const index = tutorIndex[tutor.id]
const st = index.modStatus
for (const mod of tutor.mods) {
st[mod - 1] = ModStatus.FREE
index.isInMod = true
}
for (const mod of tutor.dropInMods) {
st[mod - 1] = ModStatus.DROP_IN
index.isInMod = true
}
for (const mod of tutor.modsPref) {
switch (st[mod - 1]) {
case ModStatus.FREE:
case ModStatus.UNFREE:
st[mod - 1] = ModStatus.FREE_PREF
break
case ModStatus.DROP_IN:
st[mod - 1] = ModStatus.DROP_IN_PREF
break
default:
throw new Error()
}
}
}
for (const booking of Object.values(bookingRecords)) {
if (booking.status !== "ignore" && booking.status !== "rejected") {
if (booking.mod !== undefined) {
tutorIndex[booking.tutor].isInMod = true
tutorIndex[booking.tutor].modStatus[booking.mod - 1] = ModStatus.BOOKED
}
tutorIndex[booking.tutor].refs.push([
SchedulingReference.BOOKING,
booking.id,
])
}
}
for (const matching of Object.values(matchingRecords)) {
if (matching.mod !== undefined) {
tutorIndex[matching.tutor].isInMod = true
tutorIndex[matching.tutor].modStatus[matching.mod - 1] = ModStatus.MATCHED
tutorIndex[matching.tutor].refs.push([
SchedulingReference.MATCHING,
matching.id,
])
}
}
return tutorIndex
}
/*
/END
*/
/*
UTILITIES
*/
function roundDownToDay(utcTime: number) {
const tzOffset = new Date(utcTime).getTimezoneOffset() * 60 * 1000
return utcTime - (utcTime % (24 * 60 * 60 * 1000)) + tzOffset
}
function formatAttendanceModDataString(mod: number, minutes: number) {
return `${Number(mod)} ${Number(minutes)}`
}
function onlyKeepUnique<T>(arr: T[]): T[] {
const x = {}
for (let i = 0; i < arr.length; ++i) {
x[JSON.stringify(arr[i])] = arr[i]
}
const result = []
for (const key of Object.getOwnPropertyNames(x)) {
result.push(x[key])
}
return result
}
// polyfill of the typical Object.values()
function Object_values<T>(o: ObjectMap<T>): T[] {
const result: T[] = []
for (const i of Object.getOwnPropertyNames(o)) {
result.push(o[i])
}
return result
}
function recordCollectionToArray<T extends TableInfo.KeyType>(r: TableInfo.RecCollection<T>): TableInfo.Rec<T>[] {
const x = []
for (const i of Object.getOwnPropertyNames(r)) {
x.push(r[i])
}
return x
}
// This function converts mod numbers (ie. 11) into A-B-day strings (ie. 1B).
function stringifyMod(mod: number) {
if (1 <= mod && mod <= 10) {
return String(mod) + "A"
} else if (11 <= mod && mod <= 20) {
return String(mod - 10) + "B"
}
throw new Error(`mod ${mod} isn't serializable`)
}
function stringifyError(error: any): string {
if (error instanceof Error) {
return JSON.stringify(error, Object.getOwnPropertyNames(error))
}
try {
return JSON.stringify(error)
} catch (unusedError) {
return String(error)
}
}
type ObjectMap<T> = {
[key: string]: T
}
enum FieldType {
BOOLEAN,
NUMBER,
STRING,
DATE,
JSON,
}
/*
Spec: tables
MUST have IO carefully linked to
Google Sheets API
processClientAsk
MUST have ability to cache tables
new table
what you need to perform the operations
IO (Google Sheets API)
key
sheetName
MUST have serializeRecord
JS object into an array of raw cell data.
a way to configure tables from start to finish
TABLE_INFO_MASTER_ARRAY
TODO: special format for forms
TODO: a way to lock tables from write
isWriteAllowed
*/
namespace TableInfo {
export type KeyType = keyof TableInfo.InfoType;
type LiteralString<T> = T extends string ? (string extends T ? never : T) : never;
function StringField<T>(key: LiteralString<T>) {
return [FieldType.STRING, key] as const;
}
function NumberField<T>(key: LiteralString<T>) {
return [FieldType.NUMBER, key] as const;
}
function DateField<T>(key: LiteralString<T>) {
return [FieldType.DATE, key] as const
}
function BooleanField<T>(key: LiteralString<T>) {
return [FieldType.BOOLEAN, key] as const
}
function JsonField<T>(key: LiteralString<T>) {
return [FieldType.JSON, key] as const
}
const arrayOfIdAndDate = [NumberField('id'), DateField('date')] as const;
const arrayOfDate = [DateField('date')] as const;
export type ParseRecordType<T extends KeyType> = {
[U in (InfoType[T]['fields'][number]) as U[1]]: ParseFieldType<U[0]>
}
/*
// PRACTICE CODE
// https://github.com/Microsoft/TypeScript/issues/27272
type Generic<T> = { something: T }
type Union = {a: 1} | {b: 1} | {c: 1}
type Fancy<T> = T extends T ? Generic<T> : never;
type UnionOfGeneric = Fancy<Union>
*/
export type Rec<T extends KeyType> = ParseRecordType<T>
export type RecCollection<T extends KeyType> = {
[id: number]: Rec<T>
}
export type ParseFieldType<T extends FieldType> =
FieldType.STRING extends T ? string
: FieldType.NUMBER extends T ? number
: FieldType.DATE extends T ? number
: FieldType.BOOLEAN extends T ? boolean
: FieldType.JSON extends T ? any
: never
export type FieldsType = InfoType[KeyType]['fields'];
const basicStudentConfig = [
StringField('friendlyFullName'),
StringField('firstName'),
StringField('lastName'),
NumberField('grade'),
NumberField('studentId'),
StringField('email'),
StringField('phone'),
StringField('contactPref'),
StringField('homeroom'),
StringField('homeroomTeacher'),
StringField('attendanceAnnotation'),
JsonField("attendance"),
] as const;
// This type has been problematic in the clasp compiler so we have extracted it from the method.
type ReformatType = { readonly [U in ((typeof tableInfoData)[number]) as U[0]]: {
readonly key: U[0],
readonly sheetName: U[1],
readonly fields: (true extends U[3] ? [...(typeof arrayOfDate), ...U[2]] : [...(typeof arrayOfIdAndDate), ...U[2]]),
readonly isForm: true extends U[3] ? true : false
} }
function reformat(x: typeof tableInfoData): ReformatType {
return Object.fromEntries(x.map((y) => [y[0], {
key: y[0],
sheetName: y[1],
fields: y[3] == true ? [...arrayOfDate, ...y[2]] : [...arrayOfIdAndDate, ...y[2]],
isForm: !!y[3]
}])) as any;
}
const tableInfoData = [
[
"studentInfo",
"$student-info",
basicStudentConfig
],
[
"tutors",
"$tutors",
[
NumberField('studentInfo'),
JsonField("mods"),
JsonField("modsPref"),
StringField("subjectList"),
JsonField("dropInMods"),
StringField("afterSchoolAvailability"),
NumberField("additionalHours"),
],
],
["learners", "$learners", [NumberField("studentInfo")]],
[
"requests",
"$requests",
[
NumberField("learner"),
JsonField("mod"),
StringField("subject"),
StringField("annotation"),
NumberField("step"),
JsonField("chosenBookings"),
],
],
[
"requestSubmissions",
"$request-submissions",
[
...basicStudentConfig,
JsonField("mods"),
StringField("subject"),
BooleanField("isSpecial"),
StringField("annotation"),
StringField("status"),
],
],
[
"bookings",
"$bookings",
[
NumberField("request"),
NumberField("tutor"),
NumberField("mod"),
StringField("status"),
],
],
[
"matchings",
"$matchings",
[
NumberField("learner"),
NumberField("tutor"),
StringField("subject"),
NumberField("mod"),
StringField("annotation"),
],
],
[
"attendanceLog",
"$attendance-log",
[
NumberField("id"),
DateField("date"),
DateField("dateOfAttendance"), // rounded to nearest day
StringField("validity"), // filled with an error message if the form entry was typed wrong
NumberField("mod"),
// one of these ID fields will be left as -1 (blank).
NumberField("tutor"),
NumberField("learner"),
NumberField("minutesForTutor"),
NumberField("minutesForLearner"),
StringField("presenceForTutor"),
StringField("presenceForLearner"),
// used for reset purposes
StringField("markForReset"),
],
],
[
"attendanceDays",
"$attendance-days",
[
NumberField("id"),
DateField("date"),
DateField("dateOfAttendance"),
StringField("abDay"),
// we add a functionality to reset a day's attendance absences
StringField("status"), // upcoming, finished, finalized, unreset, reset
],
],
[
'requestForm',
'$request-form',
[
StringField('firstName'),
StringField('lastName'),
StringField('friendlyFullName'),
NumberField('studentId'),
StringField('grade'),
StringField('subject'),
StringField('modDataA1To5'),
StringField('modDataB1To5'),
StringField('modDataA6To10'),
StringField('modDataB6To10'),
StringField('homeroom'),
StringField('homeroomTeacher'),
StringField('email'),
StringField('phone'),
StringField('contactPref'),
StringField('iceCreamQuestion')
],
true
],
[
'specialRequestForm',
'$special-request-form',
[
StringField('teacherName'),
StringField('teacherEmail'),
StringField('numLearners'),
StringField('subject'),
StringField('tutoringDateInformation'),
NumberField('room'),
StringField('abDay'),
NumberField('mod1To10'),
StringField('studentNames'),
StringField('additionalInformation')
],
true
],
[
'attendanceForm',
'$attendance-form',
[
DateField('dateOfAttendance'), // optional in the form
NumberField('mod1To10'),
NumberField('studentId'),
StringField('presence')
],
true,
],
[
'tutorRegistrationForm',
'$tutor-registration-form',
[
StringField('firstName'),
StringField('lastName'),
StringField('friendlyName'),
StringField('friendlyFullName'),
NumberField('studentId'),
StringField('grade'),
StringField('email'),
StringField('phone'),
StringField('contactPref'),
StringField('homeroom'),
StringField('homeroomTeacher'),
StringField('afterSchoolAvailability'),
StringField('modDataA1To5'),
StringField('modDataB1To5'),
StringField('modDataA6To10'),
StringField('modDataB6To10'),
StringField('modDataPrefA1To5'),
StringField('modDataPrefB1To5'),
StringField('modDataPrefA6To10'),
StringField('modDataPrefB6To10'),
StringField('subjects0'),
StringField('subjects1'),
StringField('subjects2'),
StringField('subjects3'),
StringField('subjects4'),
StringField('subjects5'),
StringField('subjects6'),
StringField('subjects7'),
StringField('iceCreamQuestion'),
NumberField('numberGuessQuestion')
],
true
],
[
// this table is merged into the JSON of tutor.fields.attendance
// the table will get quite large, so we will hand-archive it from time to time
// ASSUMPTION: (thus...) the table DOESN'T contain all of the attendance data. Some of it
// will be archived somewhere else. The JSON will be merged with the attendance log.
'attendanceLog',
'$attendance-log',
[
DateField('dateOfAttendance'), // rounded to nearest day
StringField('validity'), // filled with an error message if the form entry was typed wrong
NumberField('mod'),
// one of these ID fields will be left as -1 (blank).
NumberField('tutor'),
NumberField('learner'),
NumberField('minutesForTutor'),
NumberField('minutesForLearner'),
StringField('presenceForTutor'),
StringField('presenceForLearner'),
// used for reset purposes
StringField('markForReset')
]
],
[
'attendanceDays',
'$attendance-days',
[
DateField('dateOfAttendance'),
StringField('abDay'),
// we add a functionality to reset a day's attendance absences
StringField('status') // upcoming, finished, finalized, unreset, reset
],
],
[
'operationLog',
'$operation-log',
[
JsonField('args')
]
]
] as const;
export const info = reformat(tableInfoData);
export type InfoType = typeof info;
// You have to include the "T extends T" thing because this forces Typescript to consider EVERY ITEM IN THE UNION
type FilterBetweenNonFormAndForm<T extends InfoType[keyof InfoType], U> = T extends T ? (U extends T['isForm'] ? T : never) : never;
export type NonFormInfoType = FilterBetweenNonFormAndForm<InfoType[keyof InfoType], false>;
export type FormInfoType = FilterBetweenNonFormAndForm<InfoType[keyof InfoType], true>;
}
/*
Spec: GlobalId
Date.now() is the number of milliseconds since the UNIX epoch and that is the global ID.
*/
namespace GlobalId {
let globalId = -1
export function getNextGlobalId() {
const now = Date.now()
if (now <= globalId) {
++globalId
} else {
globalId = now
}
return globalId
}
}
/*
Spec: TableIOInfo
primarily for caching
*/
namespace TableIO {
export function retrieveAllRecords<T extends TableInfo.KeyType>(key: T, sheet: GoogleAppsScript.Spreadsheet.Sheet): { [id: string]: TableInfo.ParseRecordType<T> } {
type MakeUnion<U extends TableInfo.InfoType[TableInfo.KeyType]> = U extends U ? U : never;
type MakeUnion2<U extends TableInfo.KeyType> = U extends U ? TableInfo.ParseRecordType<U> : never;
// https://stackoverflow.com/questions/50870423/discriminated-union-of-generic-type
// We use types to make info into a union so that the Discriminated Union works right
const info: MakeUnion<TableInfo.InfoType[TableInfo.KeyType]> = TableInfo.info[key]
if (info.isForm === true) {
const raw = sheet.getDataRange().getValues()
const res: { [id: string]: TableInfo.ParseRecordType<T> } = {}
for (let i = 1; i < raw.length; ++i) {
const rec: MakeUnion2<typeof info['key']> = parseRecord<typeof info['key']>(raw[i], info.key)
res[String(rec.date)] = rec as TableInfo.ParseRecordType<T>
}
return res
} else if (info.isForm === false) {
const raw = sheet.getDataRange().getValues()
const res: { [id: string]: TableInfo.ParseRecordType<T> } = {}
for (let i = 1; i < raw.length; ++i) {
const rec: MakeUnion2<typeof info['key']> = parseRecord<typeof info['key']>(raw[i], info.key)
res[String(rec.id)] = rec as TableInfo.ParseRecordType<T>
}
return res
} else {
throw 'Error';
}
}
export function parseRecord<T extends TableInfo.KeyType>(raw: any[], key: T): TableInfo.ParseRecordType<T> {
const rec = {}
const fields = TableInfo.info[key].fields;
for (let i = 0; i < fields.length; ++i) {
const field = fields[i]
// this accounts for blanks in the last field
rec[field[1]] = Parsing.parseField(
raw[i] === undefined ? "" : raw[i],
field[0]
)
}
return rec as any;
}
}
class Table<T extends TableInfo.KeyType> {
static cache: { [U in TableInfo.KeyType]?: GoogleAppsScript.Spreadsheet.Sheet } = {};
key: T
sheetName: TableInfo.InfoType[T]['sheetName']
sheet: GoogleAppsScript.Spreadsheet.Sheet
isWriteAllowed: boolean
fields: TableInfo.InfoType[T]['fields']
constructor(key: T) {
this.key = key
this.sheetName = TableInfo.info[key].sheetName;
// In the best case, you would use the ??= operator, but there appears to be a clasp compiler bug here. So here is a workaround.
// use of ??= operator -- only if the left-hand side is undefined/null, assign it to the right-hand side
if (Table.cache[key] === undefined) {
Table.cache[key] = SpreadsheetApp.getActive().getSheetByName(
this.sheetName);
}
this.sheet = Table.cache[key];
}
static readAllRecords<T extends TableInfo.KeyType>(key: T): TableInfo.RecCollection<T> {
return new Table(key).readAllRecords()
}
readAllRecords() {
return TableIO.retrieveAllRecords(
this.key,
this.sheet
)
}
serializeRecord(record: TableInfo.Rec<T>): any[] {
return (this.fields as any[]).map((field) =>
Parsing.serializeField(record[field[1]], field[0])
)
}
createRecord(record: TableInfo.Rec<T>): TableInfo.Rec<T> {
this.checkWritePermission()
if (record['date'] === -1) {
record['date'] = Date.now()
}
if (record['id'] === -1) {
record['id'] = GlobalId.getNextGlobalId()
}
this.sheet.appendRow(this.serializeRecord(record))
return record
}
getRowById(id: number): number {
// because the first row is headers, we ignore it and start from the second row
const mat: any[][] = this.sheet
.getRange(2, 1, this.sheet.getLastRow() - 1)
.getValues()
let rowNum = -1
for (let i = 0; i < mat.length; ++i) {
const cell: number = mat[i][0]
if (typeof cell !== "number") {
throw new Error(
`id at location ${String(i)} is not a number in table ${String(
this.key
)}`
)
}
if (cell === id) {
if (rowNum !== -1) {
throw new Error(
`duplicate ID ${String(id)} in table ${String(this.key)}`
)
}
rowNum = i + 2 // i = 0 <=> second row (rows are 1-indexed)
}
}
if (rowNum == -1) {
throw new Error(
`ID ${String(id)} not found in table ${String(this.key)}`
)
}
return rowNum
}
updateRecord(editedRecord: TableInfo.Rec<T>, rowNum?: number): void {
this.checkWritePermission()
if (rowNum === undefined) {
rowNum = this.getRowById(editedRecord['id'])
}
this.sheet
.getRange(rowNum, 1, 1, this.sheet.getLastColumn())
.setValues([this.serializeRecord(editedRecord)])
}
updateAllRecords(editedRecords: TableInfo.Rec<T>[]): void {
this.checkWritePermission()
if (this.sheet.getLastRow() === 1) {
return // the sheet is empty, and trying to select it will result in an error
}
// because the first row is headers, we ignore it and start from the second row
const mat: any[][] = this.sheet
.getRange(2, 1, this.sheet.getLastRow() - 1)
.getValues()
let idRowMap: ObjectMap<number> = {}
for (let i = 0; i < mat.length; ++i) {
idRowMap[String(mat[i][0])] = i + 2 // i = 0 <=> second row (rows are 1-indexed)
}
for (const r of editedRecords) {
this.updateRecord(r, idRowMap[String(r['id'])])
}
}
deleteRecord(id: number): void {
this.checkWritePermission()
this.sheet.deleteRow(this.getRowById(id))
}
rebuildSheetHeadersIfNeeded() {
this.checkWritePermission()
const col = this.sheet.getLastColumn()
this.sheet.getRange(1, 1, 1, col === 0 ? 1 : col).clearContent()
this.sheet
.getRange(1, 1, 1, this.fields.length)
.setValues([(this.fields as any[]).map((x) => x[1])])
}
checkWritePermission(): void {
if (!this.isWriteAllowed) {
throw new Error()
}
}
}
/*
IMPORTANT EVENT HANDLERS
(CODE THAT DOES ALL THE USER ACTIONS NECESSARY IN THE BACKEND)
(ALSO CODE THAT HANDLES SERVER-CLIENT INTERACTIONS)
*/
function doGet() {
return HtmlService.createHtmlOutputFromFile("index")
.setTitle("ARC App")
.setFaviconUrl(
"https://arc-app-frontend-server.netlify.com/dist/favicon.ico"
)
}
/*
processClientAsk
Spec:
MUST call 'tryThis many times
if none of them work, throw an error
args[0]: top level
args[1]: second level
args[2]: third level
there are exceptions to 'tryThis
*/
function processClientAsk(args: any[]): any {
function tryThis(arg: number, key: string, then: () => any) {
if (args[arg] === key) return then()
}
tryThis(0, "command", () => {
tryThis(1, "syncDataFromForms", onSyncForms)
tryThis(1, "recalculateAttendance", onRecalculateAttendance)
tryThis(1, "generateSchedule", onGenerateSchedule)
tryThis(1, "syncDataFromForms", onSyncForms)
tryThis(1, "retrieveMultiple", () => onRetrieveMultiple(args[2]))
})
// might throw
const table = new Table(args[0])
tryThis(1, "retrieveAll", () => Table.readAllRecords(args[2]))
tryThis(1, "update", () => table.updateRecord(args[2]))
tryThis(1, "create", () => table.createRecord(args[2]))
tryThis(1, "delete", () => table.deleteRecord(args[2]))
throw new Error("error-?")
}
// this is the MAIN ENTRYPOINT that the client uses to ask the server for data.
function onClientAsk(args: any[]): string {
let returnValue = {
error: true,
val: null,
message: "Mysterious error",
}
try {
returnValue = {
error: false,
val: processClientAsk(args),
message: null,
}
} catch (err) {
returnValue = {
error: true,
val: null,
message: stringifyError(err),
}
}
// If you send a too-big object, Google Apps Script doesn't let you do it, and null is returned. But if you stringify it, you're fine.
return JSON.stringify(returnValue)
}
function debugClientApiTest() {
try {
const ui = SpreadsheetApp.getUi()
const response = ui.prompt("Enter args as JSON array")
ui.alert(
JSON.stringify(onClientAsk(JSON.parse(response.getResponseText())))
)
} catch (err) {
Logger.log(stringifyError(err))
throw err
}
}
// This is a useful debug. It rewrites all the sheet headers to what the app thinks the sheet headers "should" be.
function debugHeaders() {
try {
// TODO!
throw new Error()
} catch (err) {
Logger.log(stringifyError(err))
throw err
}
}
// This is a utility designed for onSyncForms().
// Syncs between the formTable and the actualTable that we want to associate with it.
// Basically, we use formRecordToActualRecord() to convert form records to actual records.
// Then the actual records go in the actualTable.
// But we only do this for form records that have dates that don't exist as IDs in actualTable.
// (Remember that a form date === a record ID.)
// There is NO DELETING RECORDS! No matter what!
function doFormSync<T extends TableInfo.KeyType, U extends TableInfo.KeyType>(
formTable: Table<T>,
actualTable: Table<U>,
processFormRecord: (formRecord: TableInfo.Rec<T>) => void
): number {
const actualRecords = actualTable.readAllRecords()
const formRecords = formTable.readAllRecords()
let numOfThingsSynced = 0
// create an index of actualdata >> date.
// Then iterate over all formdata and find the ones that are missing from the index.
const index: { [date: string]: TableInfo.Rec<U> } = {}
for (const idKey of Object.getOwnPropertyNames(actualRecords)) {
const record: TableInfo.Rec<U> = actualRecords[idKey] as any
const dateIndexKey = String(record['date'])
index[dateIndexKey] = record
}
for (const idKey of Object.getOwnPropertyNames(formRecords)) {
const record: TableInfo.Rec<T> = formRecords[idKey] as any
const dateIndexKey = String(record['date'])
if (index[dateIndexKey] === undefined) {
processFormRecord(record)
++numOfThingsSynced
}
}
return numOfThingsSynced
}
const MINUTES_PER_MOD = 38
function onRetrieveMultiple(resourceNames: TableInfo.KeyType[]) {
const result = {}
for (const resourceName of resourceNames) {
result[resourceName] = Table.readAllRecords(resourceName)
}
return result
}
function uiSyncForms() {
try {
const result = onSyncForms()
SpreadsheetApp.getUi().alert(
`Finished sync! ${result as number} new form submits found.`
)
} catch (err) {
Logger.log(stringifyError(err))
throw err
}
}
namespace Parsing {
/*
Spec: field parsing
Dates are treated as numbers.
*/
export function parseField<T extends FieldType>(x: any, fieldType: T): TableInfo.ParseFieldType<T> {
switch (fieldType) {
case FieldType.BOOLEAN:
return (x === "true" || x === true ? true : false) as TableInfo.ParseFieldType<T>
case FieldType.NUMBER:
return Number(x) as TableInfo.ParseFieldType<T>
case FieldType.STRING:
return String(x) as TableInfo.ParseFieldType<T>
case FieldType.DATE:
if (x === "" || x === -1) {
return -1 as TableInfo.ParseFieldType<T>
} else {
return Number(x) as TableInfo.ParseFieldType<T>
}
case FieldType.JSON:
return JSON.parse(x) as TableInfo.ParseFieldType<T>
}
}
export function serializeField(x: any, fieldType: FieldType): any {
switch (fieldType) {
case FieldType.BOOLEAN:
return x ? true : false
case FieldType.NUMBER:
return Number(x)
case FieldType.STRING:
return String(x)
case FieldType.DATE:
if (x === -1 || x === "") {
return ""
} else {
return new Date(x)
}
case FieldType.JSON:
return JSON.stringify(x)
}
}
export function contactPref(s: string) {
if (s === "Phone") return "phone"
if (s === "Email") return "email"
return "either"
}
export function grade(g: string) {
if (g === "Freshman") return 9
if (g === "Sophomore") return 10
if (g === "Junior") return 11
if (g === "Senior") return 12
return 0
}
export function modInfo(abDay: string, mod1To10: number): number {
if (abDay.toLowerCase().charAt(0) === "a") {
return mod1To10
}
if (abDay.toLowerCase().charAt(0) === "b") {
return mod1To10 + 10
}
throw new Error(`${String(abDay)} does not start with A or B`)
}
export function modData(modData: string[]): number[] {
function doParse(d: string) {
return d
.split(",")
.map((x) => x.trim())
.filter((x) => x !== "" && x !== "None")
.map((x) => parseInt(x))
}
const mA15: number[] = doParse(modData[0])
const mB15: number[] = doParse(modData[1]).map((x) => x + 10)
const mA60: number[] = doParse(modData[2])
const mB60: number[] = doParse(modData[3]).map((x) => x + 10)
return mA15.concat(mA60).concat(mB15).concat(mB60)
}
}
// The main "sync forms" function that's crammed with form data formatting.
function onSyncForms(): number {
// tables
const tutors = Table.readAllRecords("tutors")
const matchings = Table.readAllRecords("matchings")
const attendanceDays = Table.readAllRecords("attendanceDays")
const studentInfo = Table.readAllRecords('studentInfo');
const attendanceDaysIndex = {}
for (const day of Object_values(attendanceDays)) {
attendanceDaysIndex[day.dateOfAttendance] = day.abDay
}
function processRequestFormRecord(r: TableInfo.Rec<"requestForm">) {
new Table('requestSubmissions').createRecord({
// student info
friendlyFullName: r.friendlyFullName,
firstName: r.firstName,
lastName: r.lastName,
grade: Parsing.grade(r.grade),
studentId: r.studentId,
email: r.email,
phone: r.phone,
contactPref: r.contactPref,