-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
1739 lines (1635 loc) · 50.6 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
/** @OnlyCurrentDoc */
// TODO:
// - List of saturdays worked
// - A way to get list of problems (aka where we have scheduled someone who hasnt doodled)
// - More summaries of days worked etc (sparkline?)
// - Ability to rerun doodle
// - Dedup entries in poll
function flatten<T>(a: T[][]): T[] {
const empty: T[] = [];
return empty.concat(...a);
}
function findIndex<T>(a: T[], pred: (elem: T) => boolean): number | undefined {
const l = a.length;
for (let ndx = 0; ndx < l; ndx++) {
if (pred(a[ndx])) {
return ndx;
}
}
return undefined;
}
function find<T>(a: T[], pred: (elem: T) => boolean): T | undefined {
const ndx = findIndex(a, pred);
if (ndx !== undefined) {
return a[ndx];
}
return undefined;
}
function assertDate(v: unknown): Date {
if (v instanceof Date) {
return v;
}
throw Error(`Expected a date, got ${v}`);
}
function cellAsString(v: unknown): string {
if (typeof v === "string") {
return v;
}
return String(v);
}
namespace Shift {
export interface T {
start: number;
stop: number;
}
export function equal(s1: T, s2: T): boolean {
return s1.start === s2.start && s1.stop === s2.stop;
}
}
namespace DateUtils {
export function copy(d: Date): Date {
return new Date(d.getTime());
}
export function nextDay(d: Date): Date {
const c = copy(d);
c.setDate(d.getDate() + 1);
return c;
}
/// Add the given number of days
export function addDays(d: Date, n: number): Date {
const c = copy(d);
c.setDate(d.getDate() + n);
return c;
}
export function isWeekend(d: Date): boolean {
const w = d.getDay();
return w === 6 || w === 0;
}
/// Monday is 0, Tuesday 1, ... Sunday is 6
export function dayOfWeekStartingMonday(d: Date): number {
const w = d.getDay();
if (w === 0) {
return 6;
} else {
return w - 1;
}
}
function truncToDay(d: Date): Date {
return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}
/** Compare the passed in Date objects as Dates (independently of timezone and
* ignoring anything with finer granularity than a day).
*/
export function inRangeInclusive(d: Date, low: Date, upp: Date): boolean {
const dt = truncToDay(d);
const lt = truncToDay(low);
const ut = truncToDay(upp);
return lt.getTime() <= dt.getTime() && dt.getTime() <= ut.getTime();
}
/** Compare the passed in Date objects as Dates (independently of timezone
* and ignoring anything with finer granularity than a day).
*/
export function equal(d1: Date, d2: Date): boolean {
return truncToDay(d1).getTime() === truncToDay(d2).getTime();
}
/** Call f once for each day in the range lower - upper (inclusive).
*/
export function forEachDay(
lower: Date,
upper: Date,
f: (d: Date, counter: number) => void
): void {
let d = lower;
let n = 0;
while (d <= upper) {
f(d, n);
n++;
d = nextDay(d);
}
}
export function mondayStartingWeekContaining(d: Date): Date {
const res = copy(d);
while (res.getDay() !== 1) {
res.setDate(res.getDate() - 1);
}
return res;
}
export function diff(bigger: Date, smaller: Date): number {
return Math.round(
(bigger.getTime() - smaller.getTime()) / (1000 * 60 * 60 * 24)
);
}
const isoRegex = /\d{4}-\d{2}-\d{2}/;
/*** Parse a date in extended iso format */
export function parseISODate(s: string): Date | undefined {
const r = isoRegex.exec(s);
if (r !== null) {
return new Date(s);
}
return undefined;
}
export function toISODate(d: Date): string {
const s = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
return Utilities.formatDate(d, s, "YYYY-MM-dd");
}
export function max(a: Date, b: Date): Date {
if (a.getTime() >= b.getTime()) {
return a;
}
return b;
}
export function min(a: Date, b: Date): Date {
if (a.getTime() <= b.getTime()) {
return a;
}
return b;
}
export const germanWeekDayNames = [
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag",
"Sontag",
];
}
namespace DoodleParser {
// TODO: parse the year from the sheet
const year = 2019;
const germanMonthNames = (() => {
const res: Record<string, number> = {};
[
"Januar",
"Februar",
"März",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember",
].forEach((name, ndx) => {
res[name] = ndx;
});
return res;
})();
interface ICell {
column: number;
lastColumn: number;
value: any;
}
// Given a row of potentially merged cells, return an array of column and value objects
// (column being the column of the first cell and value the value in that cell)
function parseMergedRow(
sheet: GoogleAppsScript.Spreadsheet.Sheet,
row: number,
column: number,
lastColumn: number
): ICell[] {
const result = [];
const ranges = sheet
.getRange(row, column, 1, lastColumn - column)
.getMergedRanges();
ranges.sort((a, b) => a.getColumn() - b.getColumn());
let last = column - 1;
if (ranges.length === 0) {
for (let c = last + 1; c <= lastColumn; c++) {
result.push({
column: c,
lastColumn: c,
value: sheet.getRange(row, c).getValue(),
});
}
}
// TODO: handle single cells at beginning or end
ranges.forEach((r) => {
// the merged cells aren't in the array returned by getMergedRanges, so
// we need to get them in another way.
for (let c = last + 1; c < r.getColumn(); c++) {
result.push({
column: c,
lastColumn: c,
value: sheet.getRange(row, c).getValue(),
});
}
result.push({
column: r.getColumn(),
lastColumn: r.getLastColumn(),
value: r.getValue(),
});
last = r.getLastColumn();
});
return result;
}
function betweenInclusive(x: number, low: number, high: number) {
return low <= x && x <= high;
}
const monthAndYearRegex = /^([^ ]+) ([0-9]+)$/;
const timeRegex = /^([0-9]+):([0-9]+) – ([0-9]+):([0-9]+)$/;
const dayRegex = /^([^ ]+) ([0-9]+)$/;
interface IShift {
year: number;
month: number;
day: number;
timeStartHour: number;
timeStartMinute: number;
timeEndHour: number;
timeEndMinute: number;
}
function forEachShift(
monthAndYears: any[],
days: any[],
times: any[],
f: (shift: IShift, column: number) => void
): void {
let month = 0;
let day = 0;
let time = 0;
const lastColumn = monthAndYears[monthAndYears.length - 1].lastColumn;
for (let column = monthAndYears[0].column; column <= lastColumn; column++) {
if (
!betweenInclusive(
column,
monthAndYears[month].column,
monthAndYears[month].lastColumn
)
) {
month++;
}
if (!betweenInclusive(column, days[day].column, days[day].lastColumn)) {
day++;
}
if (
!betweenInclusive(column, times[time].column, times[time].lastColumn)
) {
time++;
}
let r = monthAndYearRegex.exec(monthAndYears[month].value);
if (r == null) {
throw Error("Failed to parse month and year in doodle");
}
const monthValue = germanMonthNames[r[1]];
const year2 = Number(r[2]);
r = dayRegex.exec(days[day].value);
if (r == null) {
throw Error("Failed to parse day in doodle");
}
const dayValue = Number(r[2]);
// Parser would be more robust if this lookup failed with an error message as well
r = timeRegex.exec(times[time].value);
if (r == null) {
throw Error("Failed to parse time in doodle");
}
const timeStartHour = Number(r[1]);
const timeStartMinute = Number(r[2]);
const timeEndHour = Number(r[3]);
const timeEndMinute = Number(r[4]);
f(
{
year: year2,
month: monthValue,
day: dayValue,
timeStartHour,
timeStartMinute,
timeEndHour,
timeEndMinute,
},
column
);
}
}
export interface Entry {
employee: string;
date: Date;
/** minutes since beginning of day. */
start: number;
/** minutes since beginning of day. */
stop: number;
}
/** Parse the doodle sheet (which must be called Umfrage) and return a list of entries found.
* Throws an error if it couldn't parse an entry.
*/
export function parse(
employees: Record<string, EmployeeSheet.Employee>
): Entry[] {
const ss = SpreadsheetApp.getActive();
const doodle = ss.getSheetByName("Umfrage");
const monthAndYears = parseMergedRow(doodle, 4, 2, doodle.getLastColumn());
const days = parseMergedRow(doodle, 5, 2, doodle.getLastColumn());
const times = parseMergedRow(doodle, 6, 2, doodle.getLastColumn());
const valuesAndMore = doodle
.getRange(7, 1, doodle.getLastRow() - 6, doodle.getLastColumn() - 1)
.getValues();
const summaryRow = findIndex(valuesAndMore, (row) => row[0] === "Anzahl");
if (summaryRow === undefined) {
throw Error("Konnte die Anzahl Zeile nicht finden");
}
const values = valuesAndMore.slice(undefined, summaryRow);
const result: Entry[] = [];
forEachShift(monthAndYears, days, times, (d, c) => {
// NOTE: forEachShift column is absolute column on sheet (with 1 being A)
// But values array is 0 based
for (const row of values) {
const parsedName = row[0].toString();
if (!(parsedName in employees)) {
throw Error(`Unbekannter Mitarbeiter ${parsedName}`);
}
const employee = employees[parsedName].handle;
const ok = row[c - 1] === "OK";
if (ok) {
const date = new Date(d.year, d.month, d.day);
const start = d.timeStartHour * 60 + d.timeStartMinute;
const stop = d.timeEndHour * 60 + d.timeEndMinute;
result.push({ employee, date, start, stop });
}
}
});
return result;
}
}
namespace SlotParser {
/** A slot contains a list of items. */
export type Item =
| { kind: "default"; name: string }
| {
kind: "specified";
name: string;
start: number;
stop: number;
duration: number;
};
const shortOfDayRegex = RegExp("^[0-9]{1,2}$");
const ofDayRegex = RegExp("^([0-9]{1,2}):([0-9]{2})$");
/** Parse a time of day and return it as minutes since midnight.
* Understood formats:
* hh (0 - 23, with optional leading 0)
* hh:mm
*
* Returns undefined if the string couldn't be parsed.
*/
function parseTimeOfDay(s: string): number | undefined {
const m1 = shortOfDayRegex.exec(s);
if (m1 !== null) {
return Number(s) * 60;
}
const m2 = ofDayRegex.exec(s);
if (m2 !== null) {
return Number(m2[1]) * 60 + Number(m2[2]);
}
return undefined;
}
/** Parse a time range and return start time, stop time (in minutes since midnight) and
* duration (in minutes).
*/
export function parseTimeRange(
s: string
): { start: number; stop: number; duration: number } | undefined {
const parts = s.split("-");
if (parts.length !== 2) {
return undefined;
}
const start = parseTimeOfDay(parts[0]);
const stop = parseTimeOfDay(parts[1]);
if (start !== undefined && stop !== undefined) {
return { start, stop, duration: stop - start };
}
return undefined;
}
function parseItem(s: string): Item {
const m = s.split(" ");
if (m.length === 2) {
const range = parseTimeRange(m[1]);
if (range === undefined) {
throw Error(`Verstehe die angegebene Zeitspanne ${m[1]} nicht`);
}
return {
kind: "specified",
name: m[0],
...range,
};
} else {
return { kind: "default", name: s };
}
}
const commentRegex = /(^|[^0-9])-[^0-9]/;
/** Parse the value of a slot. Throws an error if the input is invalid. */
export function parse(slot: string): Item[] {
const startOfComment = slot.search(commentRegex);
let slotWithoutComment = "";
if (startOfComment === -1) {
slotWithoutComment = slot;
} else {
slotWithoutComment = slot.slice(undefined, startOfComment);
}
const employees = slotWithoutComment
.split(",")
.map((s) => s.trim())
.filter((s) => s !== "");
return employees.map((e) => parseItem(e));
}
/** Given the textual representation of a slot remove all occurrences of any
* of the given employees.
* TODO: Deal with names in comments.
*/
export function removeEmployees(slot: string, employees: string[]): string {
const names = employees.join("|");
const interestingItemRegex = RegExp(
`(\\b(${names})\\b( +[0-9-:]+)? *,?)`,
"g"
);
const res = slot.replace(interestingItemRegex, "").trim();
if (res.length > 0 && res[res.length - 1] === ",") {
return res.substr(0, res.length - 1);
} else {
return res;
}
}
}
namespace SheetUtils {
export function autoResizeColumns(
sheet: GoogleAppsScript.Spreadsheet.Sheet,
startColumn: number,
numColumns: number,
minWidthPixels?: number
) {
sheet.autoResizeColumns(startColumn, numColumns);
if (minWidthPixels) {
for (let c = startColumn; c < startColumn + numColumns; c++) {
if (sheet.getColumnWidth(c) < minWidthPixels) {
sheet.setColumnWidth(c, minWidthPixels);
}
}
}
}
}
namespace Locations {
export interface Location {
name: string;
ndx: number;
}
const theList: Location[] = [
{ name: "Marktgasse" },
{ name: "Ammergasse" },
{ name: "Collegiumsgasse" },
{ name: "Buero" },
{ name: "Online" },
{ name: "Extras" },
].map((e, ndx) => ({ ndx, ...e }));
const planner: Location[] = [{ name: "Unverplant", ndx: theList.length }];
const doodle: Location[] = [{ name: "Doodle", ndx: theList.length + 1 }];
const theListWithPlanner: Location[] = theList.concat(planner);
const theListWithPlannerAndDoodle: Location[] = theListWithPlanner.concat(
doodle
);
/** Return the given Location, raises an error if there is no such location. */
export function byName(name: string): Location {
const res = find(theListWithPlannerAndDoodle, (l) => l.name === name);
if (res === undefined) {
throw Error(`Unbekannter Arbeitsplatz: ${name}`);
}
return res;
}
export function getDoodle(): Location {
return doodle[0];
}
export function getPlanner(): Location {
return planner[0];
}
export function all(
mode:
| "include-planner-and-doodle"
| "exclude-planner-and-doodle"
| "include-planner-exclude-doodle"
| "only-doodle"
| "only-planner"
): Location[] {
switch (mode) {
case "include-planner-exclude-doodle":
return theListWithPlanner;
case "include-planner-and-doodle":
return theListWithPlannerAndDoodle;
case "exclude-planner-and-doodle":
return theList;
case "only-doodle":
return doodle;
case "only-planner":
return planner;
}
}
}
namespace EmployeeSheet {
function getSheet(): GoogleAppsScript.Spreadsheet.Sheet {
return SpreadsheetApp.getActive().getSheetByName("Mitarbeiter");
}
/** Copy list of employees from employees sheet to the given Range.
* Returns the number of employees.
*/
export function copyEmployees(
dst: GoogleAppsScript.Spreadsheet.Range,
transposed?: "transposed"
): number {
const trueIfTransposed = transposed !== undefined;
const employeeSheet = getSheet();
// TODO: check if copyTo is the function to use.
const src = employeeSheet.getRange(2, 1, employeeSheet.getLastRow(), 1);
src.copyTo(
dst,
SpreadsheetApp.CopyPasteType.PASTE_VALUES,
trueIfTransposed
);
return employeeSheet.getLastRow() - 1;
}
export interface Employee {
handle: string; // aka "andi"
alias?: string; // aka "Der Boss"
defaultLocation?: string; // aka "Collegiumsgasse"
}
/** Return a dictionary from both names and aliases to */
export function get(): Record<string, Employee> {
const employeeSheet = getSheet();
const src = employeeSheet
.getRange(2, 1, employeeSheet.getLastRow(), 3)
.getValues();
const res: Record<string, Employee> = {};
src.forEach((row) => {
const handle = String(row[0]);
const alias = row[1] !== "" ? String(row[1]) : undefined;
const defaultLocation = row[2] !== "" ? String(row[2]) : undefined;
const employee = { handle, alias, defaultLocation };
if (alias !== undefined) {
res[alias] = employee;
}
res[handle] = employee;
});
return res;
}
}
/** Responsible for the initial setup of all the sheets */
namespace SheetLayouter {
const EMPLOYEE_COLUMNS = 3;
const INDEX_COLUMN = EMPLOYEE_COLUMNS + 2;
const FIRST_ENTRY_COLUMN = INDEX_COLUMN + 2;
const FIRST_ENTRY_ROW = 5;
const ROWS_PER_ENTRY = 2;
const COLUMNS_PER_ENTRY = 2;
const FROM_DATE_ROW = 1;
const UNTIL_DATE_ROW = FROM_DATE_ROW + 1;
const DATE_COLUMN = FIRST_ENTRY_COLUMN;
const WEEKEND_COLOR = "#FFF2CC";
const DOODLE_COLOR = "#5B95F9";
function columnLetter(n: number): string {
const res = [];
while (n > 0) {
const digit = n % 26;
if (digit === 0) {
res.push("Z");
n = Math.floor(n / 26 - 1);
} else {
res.push(String.fromCharCode("A".charCodeAt(0) + digit - 1));
n = Math.floor(n / 26);
}
}
res.reverse();
return res.join("");
}
function a1(row: number, column: number, sheetName?: string): string {
const cell = columnLetter(column) + String(row);
if (sheetName !== undefined) {
return "'" + sheetName + "'!" + cell;
}
return cell;
}
function a1Range(
row1: number,
column1: number,
row2: number,
column2: number,
sheetName?: string
): string {
return a1(row1, column1, sheetName) + ":" + a1(row2, column2);
}
function getReferencesToSlotsForNthDay(
scheduleSheetName: string,
n: number,
mode: "exclude-planner-and-doodle" | "only-doodle"
): string {
return Locations.all(mode)
.map((loc) => {
const whole = a1(
FIRST_ENTRY_ROW + n * ROWS_PER_ENTRY,
FIRST_ENTRY_COLUMN + loc.ndx * COLUMNS_PER_ENTRY,
scheduleSheetName
);
const firstHalf = a1(
FIRST_ENTRY_ROW + n * ROWS_PER_ENTRY + 1,
FIRST_ENTRY_COLUMN + loc.ndx * COLUMNS_PER_ENTRY,
scheduleSheetName
);
const secondHalf = a1(
FIRST_ENTRY_ROW + n * ROWS_PER_ENTRY + 1,
FIRST_ENTRY_COLUMN + loc.ndx * COLUMNS_PER_ENTRY + 1,
scheduleSheetName
);
return `${whole};${firstHalf};${secondHalf}`;
})
.join(";");
}
function countEmployeesFormula(slot: string): string {
return `IF(ISBLANK(${slot});0;LEN(${slot})-LEN(REGEXREPLACE(${slot};","; ""))+1)`;
}
/** Count number of employees available in the first and second half of the day as per doodle */
function countAvailableEmployeesFormula(
nthDay: number
): { firstHalf: string; secondHalf: string } {
const doodle = Locations.all("only-doodle")[0];
const whole = a1(
FIRST_ENTRY_ROW + nthDay * ROWS_PER_ENTRY,
FIRST_ENTRY_COLUMN + doodle.ndx * COLUMNS_PER_ENTRY
);
const firstHalf = a1(
FIRST_ENTRY_ROW + nthDay * ROWS_PER_ENTRY + 1,
FIRST_ENTRY_COLUMN + doodle.ndx * COLUMNS_PER_ENTRY
);
const secondHalf = a1(
FIRST_ENTRY_ROW + nthDay * ROWS_PER_ENTRY + 1,
FIRST_ENTRY_COLUMN + doodle.ndx * COLUMNS_PER_ENTRY + 1
);
const wholeFormula = countEmployeesFormula(whole);
return {
firstHalf: `=${countEmployeesFormula(firstHalf)}+${wholeFormula}`,
secondHalf: `=${countEmployeesFormula(secondHalf)}+${wholeFormula}`,
};
}
/** Return the range of dates displayed. */
function getDates(
sheet: GoogleAppsScript.Spreadsheet.Sheet
): { from: Date; until: Date } {
const [[fromV], [untilV]] = sheet
.getRange(FROM_DATE_ROW, DATE_COLUMN, 2, 1)
.getValues();
const from = assertDate(fromV);
const until = assertDate(untilV);
return { from, until };
}
function getDefaultTimeRanges(
sheet: GoogleAppsScript.Spreadsheet.Sheet
): {
whole: { start: number; stop: number; duration: number };
firstHalf: { start: number; stop: number; duration: number };
secondHalf: { start: number; stop: number; duration: number };
} {
const [[wholeCell], [first], [second]] = sheet
.getRange(1, 2, 3, 1)
.getValues();
const whole = SlotParser.parseTimeRange(String(wholeCell))!;
whole.duration = whole.duration - 60;
return {
whole,
firstHalf: SlotParser.parseTimeRange(String(first))!,
secondHalf: SlotParser.parseTimeRange(String(second))!,
};
}
const saturdayTimeRange = {
start: 9 * 60 + 45,
stop: 16 * 60,
duration: 6 * 60 + 15,
};
const sundayTimeRange = {
start: 13 * 60,
stop: 18 * 60,
duration: 5 * 60 * 1.5,
};
function setupComputationSheet(
sheet: GoogleAppsScript.Spreadsheet.Sheet,
scheduleSheet: GoogleAppsScript.Spreadsheet.Sheet,
fromDate: Date,
toDate: Date,
mode: "exclude-planner-and-doodle" | "only-doodle"
): void {
const scheduleSheetName = scheduleSheet.getName();
sheet.clear();
sheet.clearConditionalFormatRules();
sheet.setFrozenRows(1 + 1 + 7);
sheet.setFrozenColumns(2);
const numDays = DateUtils.diff(toDate, fromDate) + 1;
const numEmployees = EmployeeSheet.copyEmployees(
sheet.getRange(1, 3),
"transposed"
);
sheet.getRange(1, 2, 1, numEmployees).setFontWeight("bold");
// Range starting at the first row of data (aka row[0] = row of fromDate)
const theRange = sheet.getRange(
2,
1,
numDays + 1 + 7, // +1 for the row of sums + 7 for the number of weekday counters
numEmployees + 1 + 1 // + 1 for the date + 1 for the weekday
);
const cells = theRange.getValues();
const employees = a1(1, 3) + ":" + a1(1, 3 + numEmployees - 1);
const defaults = getDefaultTimeRanges(scheduleSheet);
const times = `${defaults.whole.duration};${defaults.firstHalf.duration};${
defaults.secondHalf.duration
}`;
const saturdayTimes = `${saturdayTimeRange.duration};${
saturdayTimeRange.duration
};${saturdayTimeRange.duration}`;
const sundayTimes = `${sundayTimeRange.duration};${
sundayTimeRange.duration
};${sundayTimeRange.duration}`;
DateUtils.forEachDay(fromDate, toDate, (date, nth) => {
const row = nth + 1 + 7; // to skip the sum row and the weekday counters
const slots = getReferencesToSlotsForNthDay(scheduleSheetName, nth, mode);
let timesWeekdaySpecific = "";
const wd = date.getDay();
if (wd === 6) {
timesWeekdaySpecific = saturdayTimes;
} else if (wd === 0) {
timesWeekdaySpecific = sundayTimes;
} else {
timesWeekdaySpecific = times;
}
cells[row][0] = date;
cells[row][1] = `=WEEKDAY(${a1(row + 2, 1)};3)`;
cells[
row
][2] = `=SCHEDULECOUNT(${employees};${timesWeekdaySpecific};${slots})`;
});
const weekdayColumn = a1Range(2 + 1 + 7, 2, 2 + 1 + 7 + numDays - 1, 2);
for (let wd = 0; wd < 7; wd++) {
cells[1 + wd][1] = DateUtils.germanWeekDayNames[wd];
}
for (let e = 0; e < numEmployees; e++) {
const thatColumn = a1Range(
2 + 1 + 7,
2 + 1 + e,
2 + 1 + 7 + numDays - 1,
2 + 1 + e
);
cells[0][e + 2] = `=SUM(${thatColumn})`;
for (let wd = 0; wd < 7; wd++) {
cells[1 + wd][
e + 2
] = `=COUNTIFS(${weekdayColumn};ROW()-3;${thatColumn};">0")`;
}
}
theRange.setValues(cells);
}
export interface Slot {
date: Date;
location: number;
shiftKind: number;
row: number;
column: number;
}
/** Return the range of all the entries for the given day. Result is undefined if the passed
* in date is not on the sheet.
*/
export function rangeOfEntriesOfDay(
scheduleSheet: GoogleAppsScript.Spreadsheet.Sheet,
date: Date,
mode: "include-planner-exclude-doodle"
): {
range: GoogleAppsScript.Spreadsheet.Range;
row: number;
column: number;
} {
const dates = getDates(scheduleSheet);
const offset = DateUtils.diff(date, dates.from) * ROWS_PER_ENTRY;
const row = FIRST_ENTRY_ROW + offset;
const columns = Locations.all(mode).length * COLUMNS_PER_ENTRY;
return {
range: scheduleSheet.getRange(
row,
FIRST_ENTRY_COLUMN,
ROWS_PER_ENTRY,
columns
),
row,
column: FIRST_ENTRY_COLUMN,
};
}
/** Convert the position of a cell to the address of the relevant slot, if there
* is one at that position.
*/
export function cellToSlot(
scheduleSheet: GoogleAppsScript.Spreadsheet.Sheet,
mode: "include-planner-exclude-doodle",
cell: { row: number; column: number }
): undefined | Slot {
const dates = getDates(scheduleSheet);
const numDays = DateUtils.diff(dates.until, dates.from) + 1;
const rows = numDays * ROWS_PER_ENTRY;
const columns = Locations.all(mode).length * COLUMNS_PER_ENTRY;
if (
FIRST_ENTRY_ROW <= cell.row &&
cell.row < FIRST_ENTRY_ROW + rows &&
FIRST_ENTRY_COLUMN <= cell.column &&
cell.column < FIRST_ENTRY_COLUMN + columns
) {
const date = DateUtils.addDays(
dates.from,
Math.floor((cell.row - FIRST_ENTRY_ROW) / ROWS_PER_ENTRY)
);
const row0or1 = (cell.row - FIRST_ENTRY_ROW) % 2;
let shiftKind = 0;
if (row0or1 === 1) {
if ((cell.column - FIRST_ENTRY_COLUMN) % COLUMNS_PER_ENTRY === 0) {
shiftKind = 1;
} else {
shiftKind = 2;
}
}
const location = Math.floor(
(cell.column - FIRST_ENTRY_COLUMN) / COLUMNS_PER_ENTRY
);
return { date, location, shiftKind, ...cell };
}
return undefined;
}
/** (Re-)create the formulas on the sheets. Called both initially
* when the sheets are first populated and also on user demand when
* the user updated the employee list. For the latter reason it must
* not touch any user data on the sheets.
* The date range passed in MUST match the date range on the schedule
* sheet.
*/
export function updateFormulas({
scheduleSheet,
doodleSheet,
workSheet,
fromDate,
toDate,
}: {
scheduleSheet: GoogleAppsScript.Spreadsheet.Sheet;
doodleSheet: GoogleAppsScript.Spreadsheet.Sheet;
workSheet: GoogleAppsScript.Spreadsheet.Sheet;
fromDate: Date;
toDate: Date;
}): void {
// Setup the sheet summing up the working minutes
setupComputationSheet(
workSheet,
scheduleSheet,
fromDate,
toDate,
"exclude-planner-and-doodle"
);
// Setup the sheet summing up the doodled minutes
setupComputationSheet(
doodleSheet,
scheduleSheet,
fromDate,
toDate,
"only-doodle"
);
// setup pane on the left that shows computations.
scheduleSheet
.getRange(FIRST_ENTRY_ROW, 1, 1, 2)
.setValues([["Mitarbeiter", "h"]])
.setFontWeight("bold");
const numEmployees = EmployeeSheet.copyEmployees(
scheduleSheet.getRange(FIRST_ENTRY_ROW + 1, 1)
);
const a = [];
const workSheetName = workSheet.getName();
const yMax = Math.ceil((DateUtils.diff(toDate, fromDate) + 1) / 7);
for (let e = 0; e < numEmployees; e++) {
const weekdaysWorked = a1Range(3, 3 + e, 3 + 7 - 1, 3 + e, workSheetName);
a[e] = [
`=${a1(2, 3 + e, workSheetName)}/60`,
`=SPARKLINE(${weekdaysWorked}; {"charttype"\\"column";"ymax"\\${yMax}})`,
];
}
scheduleSheet
.getRange(FIRST_ENTRY_ROW + 1, 2, numEmployees, 2)
.setValues(a);
const existingBandings = scheduleSheet
.getRange(FIRST_ENTRY_ROW, 1)
.getBandings();
existingBandings.forEach((b) => b.remove());
scheduleSheet
.getRange(FIRST_ENTRY_ROW, 1, numEmployees + 1, 3)
.applyRowBanding(SpreadsheetApp.BandingTheme.BLUE);
}
/** The initial setup of a sheet. Intended to be called exactly once for each sheet
* (immediately after creation of the sheet).
*/
export function setup(
scheduleSheet: GoogleAppsScript.Spreadsheet.Sheet,
workSheet: GoogleAppsScript.Spreadsheet.Sheet,
doodleSheet: GoogleAppsScript.Spreadsheet.Sheet,
fromDate: Date,
toDate: Date
): void {
function columnOfEntry(location: Locations.Location) {
return FIRST_ENTRY_COLUMN + location.ndx * COLUMNS_PER_ENTRY;
}
scheduleSheet.clear();
scheduleSheet.clearConditionalFormatRules();
scheduleSheet.setHiddenGridlines(true);
scheduleSheet.setFrozenRows(FIRST_ENTRY_ROW - 2);