@jsb188/schedule 1.1.12 → 1.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +33 -14
  3. package/src/constants/schedule.ts +710 -306
  4. package/src/types/schedule.d.ts +1827 -456
  5. package/src/ui/ScheduleSettingsUI.tsx +21 -23
  6. package/src/utils/autofill.ts +469 -0
  7. package/src/utils/availability.ts +167 -0
  8. package/src/utils/candidates.ts +447 -0
  9. package/src/utils/coverage.helpers.ts +509 -554
  10. package/src/utils/coverage.ts +1121 -526
  11. package/src/utils/cpm.helpers.ts +27 -29
  12. package/src/utils/cpm.ts +53 -41
  13. package/src/utils/cpmLeveling.helpers.ts +89 -16
  14. package/src/utils/cpmLeveling.ts +28 -26
  15. package/src/utils/cycle.ts +325 -0
  16. package/src/utils/demand.ts +239 -0
  17. package/src/utils/eligibility.ts +553 -400
  18. package/src/utils/ids.ts +47 -0
  19. package/src/utils/laborRules.ts +740 -0
  20. package/src/utils/localTime.ts +312 -0
  21. package/src/utils/offer.ts +300 -0
  22. package/src/utils/planCsv.ts +73 -19
  23. package/src/utils/predicate.ts +111 -0
  24. package/src/utils/request.ts +212 -114
  25. package/src/utils/resource.ts +412 -112
  26. package/src/utils/rule.ts +697 -163
  27. package/src/utils/rulePresets.ts +116 -0
  28. package/src/utils/run.ts +0 -8
  29. package/src/utils/scheduleText.ts +4074 -0
  30. package/src/utils/shiftChange.ts +279 -0
  31. package/src/utils/standing.ts +730 -0
  32. package/src/utils/template.ts +619 -0
  33. package/src/utils/violation.ts +184 -0
  34. package/src/utils/workTime.ts +341 -120
  35. package/src/utils/defaults.ts +0 -8
  36. package/src/utils/recurrence.ts +0 -616
  37. package/src/utils/series.ts +0 -161
  38. package/src/utils/slot.ts +0 -208
  39. package/tests/coverage.fixtures.ts +0 -111
  40. package/tests/coverage.test.ts +0 -503
  41. package/tests/cpm.bench.test.ts +0 -154
  42. package/tests/cpm.test.ts +0 -354
  43. package/tests/cpmCorrectness.test.ts +0 -327
  44. package/tests/cpmLeveling.test.ts +0 -471
  45. package/tests/eligibility.test.ts +0 -320
  46. package/tests/gantt-geometry.test.ts +0 -367
  47. package/tests/gantt-histogram.test.ts +0 -78
  48. package/tests/gantt-keyboard.test.ts +0 -69
  49. package/tests/helpers/cpmFixtures.ts +0 -101
  50. package/tests/projectInputs.test.ts +0 -165
  51. package/tests/recurrence.test.ts +0 -68
  52. package/tests/request.test.ts +0 -99
  53. package/tests/resource.test.ts +0 -95
  54. package/tests/rule.test.ts +0 -98
  55. package/tests/series.test.ts +0 -120
  56. package/tests/workTime.test.ts +0 -1007
  57. package/tests/workTimeContracts.test.ts +0 -111
  58. package/tsconfig.json +0 -13
  59. package/vitest.config.ts +0 -8
@@ -0,0 +1,619 @@
1
+ import {
2
+ SCHEDULE_LABEL_MAX_LENGTH,
3
+ SCHEDULE_NOTE_MAX_LENGTH,
4
+ SCHEDULE_ROTATION_MAX_WEEKS,
5
+ SCHEDULE_SHIFT_MAX_DURATION_MINUTES,
6
+ } from '../constants/schedule.ts';
7
+ import type {
8
+ ScheduleShiftSpec,
9
+ ScheduleShiftStateObj,
10
+ ScheduleTemplateItemInput,
11
+ ScheduleTemplateItemSpec,
12
+ ScheduleTemplateRotationObj,
13
+ } from '../types/schedule.d.ts';
14
+ import { compareScheduleIds } from './ids.ts';
15
+ import {
16
+ addScheduleDays,
17
+ getScheduleDaysBetween,
18
+ getScheduleLocalClockTime,
19
+ getScheduleLocalDate,
20
+ getScheduleLocalInstant,
21
+ getScheduleLocalInterval,
22
+ getScheduleWeekStart,
23
+ getScheduleWeekday,
24
+ isScheduleDateKey,
25
+ listScheduleDates,
26
+ normalizeScheduleClockTime,
27
+ parseScheduleClockTime,
28
+ toScheduleTimeMs,
29
+ } from './localTime.ts';
30
+ import {
31
+ getScheduleId,
32
+ getUnknownScheduleKey,
33
+ isScheduleRecord,
34
+ isScheduleWeekday,
35
+ validateScheduleClockTimesInput,
36
+ } from './resource.ts';
37
+
38
+ /**
39
+ * Templates, copy week and the standing schedule (IMPLEMENTATION §1.2,
40
+ * §1.12).
41
+ *
42
+ * - A template item is one seat of one rotation week: weekday, wall-clock
43
+ * start and end (an end at or before the start ends the next day), role,
44
+ * location, optional fixed person, unpaid break and label.
45
+ * - A calendar week's rotation week comes from getRotationWeek only: whole
46
+ * weeks from the pay week that holds the rotation anchor, with a true
47
+ * modulo so weeks before the anchor work. Weeks start on the
48
+ * organization's payWeekStart.
49
+ * - Seats are placed with utils/localTime.ts: wall-clock bounds on their local
50
+ * date in the calendar zone, a bound inside a spring-forward gap moving
51
+ * forward. A seat that comes out invalid on a DST day is left out.
52
+ */
53
+
54
+ const FILE_CONSTANTS = {
55
+ minuteMs: 60_000,
56
+ dayMinutes: 1440,
57
+ itemKeys: [
58
+ 'week',
59
+ 'weekday',
60
+ 'startTime',
61
+ 'endTime',
62
+ 'roleId',
63
+ 'locationResourceId',
64
+ 'assigneeResourceId',
65
+ 'unpaidBreakMinutes',
66
+ 'label',
67
+ ],
68
+ itemIdKeys: ['roleId', 'locationResourceId', 'assigneeResourceId'] as const,
69
+ };
70
+
71
+ /*
72
+ * Check that a rotation length is a whole number of weeks from 1 to
73
+ * SCHEDULE_ROTATION_MAX_WEEKS.
74
+ */
75
+ function isScheduleRotationWeeks(value: unknown): value is number {
76
+ return (
77
+ Number.isInteger(value) &&
78
+ (value as number) >= 1 &&
79
+ (value as number) <= SCHEDULE_ROTATION_MAX_WEEKS
80
+ );
81
+ }
82
+
83
+ /*
84
+ * Return the rotation week (1 = week A) of the pay week that contains `date`
85
+ * (weeks start on payWeekStart): ((whole weeks from the pay week containing
86
+ * rotationAnchor) mod rotationWeeks) + 1 with a true modulo, so weeks before
87
+ * the anchor work. The week holding the anchor is week A whatever weekday the
88
+ * anchor falls on, so a later payWeekStart change keeps most of each week's
89
+ * days in the same rotation week. The only rotation arithmetic in the
90
+ * system. A rotation of several weeks with no anchor (the DDL forbids it) or
91
+ * a malformed date throws a RangeError.
92
+ */
93
+ export function getRotationWeek(
94
+ date: string,
95
+ rotation: ScheduleTemplateRotationObj,
96
+ payWeekStart: number,
97
+ ): number {
98
+ const { rotationWeeks, rotationAnchor } = rotation;
99
+ if (!isScheduleRotationWeeks(rotationWeeks))
100
+ throw new RangeError(`Invalid rotationWeeks: ${rotationWeeks}`);
101
+ if (rotationWeeks === 1) return 1;
102
+ if (!isScheduleDateKey(rotationAnchor) || !isScheduleDateKey(date))
103
+ throw new RangeError(
104
+ `A ${rotationWeeks}-week rotation needs a valid anchor and date`,
105
+ );
106
+ const weeks =
107
+ getScheduleDaysBetween(
108
+ getScheduleWeekStart(rotationAnchor, payWeekStart),
109
+ getScheduleWeekStart(date, payWeekStart),
110
+ ) / 7;
111
+ return (((weeks % rotationWeeks) + rotationWeeks) % rotationWeeks) + 1;
112
+ }
113
+
114
+ /*
115
+ * Validate a template's rotation: `rotationWeeks` 1..
116
+ * SCHEDULE_ROTATION_MAX_WEEKS (default 1) and `rotationAnchor` (any date of
117
+ * week A, stored as the first day of its pay week), required when the
118
+ * rotation has several weeks.
119
+ */
120
+ export function validateScheduleTemplateRotation(
121
+ input: unknown,
122
+ payWeekStart: number,
123
+ ): {
124
+ rotation?: ScheduleTemplateRotationObj;
125
+ error?: string;
126
+ } {
127
+ if (!isScheduleRecord(input))
128
+ return { error: 'A template rotation must be an object.' };
129
+ const unknown = getUnknownScheduleKey(input, [
130
+ 'rotationWeeks',
131
+ 'rotationAnchor',
132
+ ]);
133
+ if (unknown) return { error: `Unknown rotation field: ${unknown}.` };
134
+
135
+ const rotationWeeks = input.rotationWeeks ?? 1;
136
+ if (!isScheduleRotationWeeks(rotationWeeks))
137
+ return {
138
+ error: `rotationWeeks must be a whole number from 1 to ${SCHEDULE_ROTATION_MAX_WEEKS}.`,
139
+ };
140
+ const rotationAnchor = input.rotationAnchor ?? null;
141
+ if (rotationAnchor !== null && !isScheduleDateKey(rotationAnchor))
142
+ return { error: 'rotationAnchor must be a date (YYYY-MM-DD).' };
143
+ if (rotationWeeks > 1 && rotationAnchor === null)
144
+ return {
145
+ error:
146
+ 'A rotation of several weeks needs rotationAnchor: a date in week A.',
147
+ };
148
+ return {
149
+ rotation: {
150
+ rotationWeeks,
151
+ rotationAnchor:
152
+ rotationAnchor === null
153
+ ? null
154
+ : getScheduleWeekStart(rotationAnchor, payWeekStart),
155
+ },
156
+ };
157
+ }
158
+
159
+ /*
160
+ * Return the wall-clock length of a local window in minutes: an end at or
161
+ * before the start ends the next day, so equal times are 1440.
162
+ */
163
+ function getScheduleClockSpanMinutes(
164
+ startTime: string,
165
+ endTime: string,
166
+ ): number {
167
+ const start = parseScheduleClockTime(startTime) ?? 0;
168
+ const end = parseScheduleClockTime(endTime) ?? 0;
169
+ return end > start ? end - start : end - start + FILE_CONSTANTS.dayMinutes;
170
+ }
171
+
172
+ /*
173
+ * Validate an optional label: null, or a string trimmed to at most
174
+ * SCHEDULE_LABEL_MAX_LENGTH characters (an empty one becomes null).
175
+ */
176
+ function validateScheduleLabelInput(value: unknown): {
177
+ label?: string | null;
178
+ error?: string;
179
+ } {
180
+ if (value == null) return { label: null };
181
+ if (
182
+ typeof value !== 'string' ||
183
+ value.trim().length > SCHEDULE_LABEL_MAX_LENGTH
184
+ )
185
+ return {
186
+ error: `A label must be text of at most ${SCHEDULE_LABEL_MAX_LENGTH} characters.`,
187
+ };
188
+ return { label: value.trim() || null };
189
+ }
190
+
191
+ /*
192
+ * Validate one template item write: `week` 1..rotationWeeks (default 1),
193
+ * `weekday` 0..6, wall-clock times normalized to 'HH:mm', role / location /
194
+ * assignee ids or null, `unpaidBreakMinutes` a whole number of minutes
195
+ * (default 0) below the item's wall-clock length, and an optional label.
196
+ */
197
+ export function validateScheduleTemplateItem(
198
+ input: unknown,
199
+ rotationWeeks: number,
200
+ ): { item?: ScheduleTemplateItemSpec; error?: string } {
201
+ if (!isScheduleRecord(input))
202
+ return { error: 'A template item must be an object.' };
203
+ const unknown = getUnknownScheduleKey(input, FILE_CONSTANTS.itemKeys);
204
+ if (unknown) return { error: `Unknown template item field: ${unknown}.` };
205
+
206
+ const week = input.week ?? 1;
207
+ if (
208
+ !Number.isInteger(week) ||
209
+ (week as number) < 1 ||
210
+ (week as number) > rotationWeeks
211
+ )
212
+ return {
213
+ error: `The item's rotation week must be a whole number from 1 to ${rotationWeeks}.`,
214
+ };
215
+ if (!isScheduleWeekday(input.weekday))
216
+ return {
217
+ error: "The item's weekday must be 0 (Sunday) to 6 (Saturday).",
218
+ };
219
+ const { times, error } = validateScheduleClockTimesInput(input);
220
+ if (!times) return { error };
221
+
222
+ const ids = {
223
+ roleId: null,
224
+ locationResourceId: null,
225
+ assigneeResourceId: null,
226
+ } as Record<(typeof FILE_CONSTANTS.itemIdKeys)[number], string | null>;
227
+ for (const key of FILE_CONSTANTS.itemIdKeys) {
228
+ if (input[key] == null) continue;
229
+ ids[key] = getScheduleId(input[key]);
230
+ if (!ids[key]) return { error: `Invalid ${key}.` };
231
+ }
232
+
233
+ const unpaidBreakMinutes = input.unpaidBreakMinutes ?? 0;
234
+ if (
235
+ !Number.isInteger(unpaidBreakMinutes) ||
236
+ (unpaidBreakMinutes as number) < 0 ||
237
+ (unpaidBreakMinutes as number) >=
238
+ getScheduleClockSpanMinutes(times.startTime, times.endTime)
239
+ )
240
+ return {
241
+ error:
242
+ 'The unpaid break must be a whole number of minutes, 0 or more, and shorter than the shift.',
243
+ };
244
+ const label = validateScheduleLabelInput(input.label);
245
+ if (label.error) return { error: label.error };
246
+
247
+ return {
248
+ item: {
249
+ week: week as number,
250
+ weekday: input.weekday,
251
+ startTime: times.startTime,
252
+ endTime: times.endTime,
253
+ roleId: ids.roleId,
254
+ locationResourceId: ids.locationResourceId,
255
+ assigneeResourceId: ids.assigneeResourceId,
256
+ unpaidBreakMinutes: unpaidBreakMinutes as number,
257
+ label: label.label!,
258
+ },
259
+ };
260
+ }
261
+
262
+ /*
263
+ * Check a seat about to be written and return an English error, or null when
264
+ * it is valid: it ends after it starts, lasts at most
265
+ * SCHEDULE_SHIFT_MAX_DURATION_MINUTES, is longer than its unpaid break, and
266
+ * its label and note fit their columns. Every seat write (template, copy,
267
+ * manual) shares this rule.
268
+ */
269
+ export function validateScheduleShiftSpec(
270
+ spec: Pick<
271
+ ScheduleShiftSpec,
272
+ 'startAt' | 'endAt' | 'unpaidBreakMinutes' | 'label' | 'note'
273
+ >,
274
+ ): string | null {
275
+ const startMs = toScheduleTimeMs(spec.startAt);
276
+ const endMs = toScheduleTimeMs(spec.endAt);
277
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs))
278
+ return 'A shift needs a valid start and end.';
279
+ if (endMs <= startMs) return 'A shift must end after it starts.';
280
+ if (
281
+ endMs - startMs >
282
+ SCHEDULE_SHIFT_MAX_DURATION_MINUTES * FILE_CONSTANTS.minuteMs
283
+ )
284
+ return `A shift can be at most ${SCHEDULE_SHIFT_MAX_DURATION_MINUTES / 60} hours long.`;
285
+ if (!Number.isInteger(spec.unpaidBreakMinutes) || spec.unpaidBreakMinutes < 0)
286
+ return 'The unpaid break must be a whole number of minutes, 0 or more.';
287
+ if (startMs + spec.unpaidBreakMinutes * FILE_CONSTANTS.minuteMs >= endMs)
288
+ return 'The unpaid break must be shorter than the shift.';
289
+ if (spec.label != null && spec.label.length > SCHEDULE_LABEL_MAX_LENGTH)
290
+ return `A shift label can be at most ${SCHEDULE_LABEL_MAX_LENGTH} characters.`;
291
+ if (spec.note != null && spec.note.length > SCHEDULE_NOTE_MAX_LENGTH)
292
+ return `A shift note can be at most ${SCHEDULE_NOTE_MAX_LENGTH} characters.`;
293
+ return null;
294
+ }
295
+
296
+ /*
297
+ * Order seat specs by shiftDate, startAt, then provenance ids, so every
298
+ * expansion is deterministic.
299
+ */
300
+ function compareScheduleShiftSpecs(
301
+ a: ScheduleShiftSpec,
302
+ b: ScheduleShiftSpec,
303
+ ): number {
304
+ if (a.shiftDate !== b.shiftDate) return a.shiftDate < b.shiftDate ? -1 : 1;
305
+ const byStart = a.startAt.getTime() - b.startAt.getTime();
306
+ if (byStart) return byStart;
307
+ return (
308
+ compareScheduleIds(a.templateItemId ?? '', b.templateItemId ?? '') ||
309
+ compareScheduleIds(a.copiedFromShiftId ?? '', b.copiedFromShiftId ?? '')
310
+ );
311
+ }
312
+
313
+ /*
314
+ * Group template items by `week:weekday`, the lookup key of an expansion.
315
+ */
316
+ function groupTemplateItemsByDay(
317
+ items: ScheduleTemplateItemInput[],
318
+ ): Map<string, ScheduleTemplateItemInput[]> {
319
+ const byDay = new Map<string, ScheduleTemplateItemInput[]>();
320
+ for (const item of items) {
321
+ const key = `${item.week}:${item.weekday}`;
322
+ byDay.set(key, [...(byDay.get(key) ?? []), item]);
323
+ }
324
+ return byDay;
325
+ }
326
+
327
+ /*
328
+ * Place one template item on a local date as a seat spec (its weekday is not
329
+ * checked: the caller picks the date); null when its times are malformed or
330
+ * the placed seat fails validateScheduleShiftSpec (a DST corner, such as an
331
+ * end that a spring-forward gap moved before the start). The one placement
332
+ * of an item: expansion, the standing-seat matcher and THIS_AND_FUTURE use
333
+ * it.
334
+ */
335
+ export function placeScheduleTemplateItem(
336
+ item: ScheduleTemplateItemInput,
337
+ date: string,
338
+ timeZone: string,
339
+ ): ScheduleShiftSpec | null {
340
+ const interval = getScheduleLocalInterval(
341
+ date,
342
+ item.startTime,
343
+ item.endTime,
344
+ timeZone,
345
+ );
346
+ if (!interval) return null;
347
+ const spec: ScheduleShiftSpec = {
348
+ templateItemId: item.id,
349
+ copiedFromShiftId: null,
350
+ shiftDate: date,
351
+ startAt: interval.startAt,
352
+ endAt: interval.endAt,
353
+ roleId: item.roleId,
354
+ locationResourceId: item.locationResourceId,
355
+ assigneeResourceId: item.assigneeResourceId,
356
+ unpaidBreakMinutes: item.unpaidBreakMinutes,
357
+ label: item.label,
358
+ note: null,
359
+ };
360
+ return validateScheduleShiftSpec(spec) ? null : spec;
361
+ }
362
+
363
+ /*
364
+ * Expand template items into seat specs for every local date in
365
+ * [fromDate, toDate]: each date takes the items of its week's rotation week
366
+ * (weeks start on payWeekStart) and of its weekday. shiftDate is the date,
367
+ * times are placed in the calendar zone, and seats invalid on a DST day are
368
+ * left out. Sorted by shiftDate, startAt, templateItemId.
369
+ */
370
+ export function expandScheduleTemplateItems(args: {
371
+ rotation: ScheduleTemplateRotationObj;
372
+ items: ScheduleTemplateItemInput[];
373
+ fromDate: string;
374
+ toDate: string;
375
+ timeZone: string;
376
+ payWeekStart: number;
377
+ }): ScheduleShiftSpec[] {
378
+ const itemsByDay = groupTemplateItemsByDay(args.items);
379
+ const specs: ScheduleShiftSpec[] = [];
380
+ for (const date of listScheduleDates(args.fromDate, args.toDate)) {
381
+ const week = getRotationWeek(date, args.rotation, args.payWeekStart);
382
+ for (const item of itemsByDay.get(`${week}:${getScheduleWeekday(date)}`) ??
383
+ []) {
384
+ const spec = placeScheduleTemplateItem(item, date, args.timeZone);
385
+ if (spec) specs.push(spec);
386
+ }
387
+ }
388
+ return specs.sort(compareScheduleShiftSpecs);
389
+ }
390
+
391
+ /*
392
+ * Check whether a local date falls in the seven days starting on weekStart.
393
+ */
394
+ function isScheduleDateInWeek(date: string, weekStart: string): boolean {
395
+ const offset = getScheduleDaysBetween(weekStart, date);
396
+ return offset >= 0 && offset <= 6;
397
+ }
398
+
399
+ /*
400
+ * Move an instant by whole calendar days in a zone, keeping its wall-clock
401
+ * time (a time inside a spring-forward gap moves forward).
402
+ */
403
+ function moveScheduleInstantByDays(
404
+ at: Date | string,
405
+ days: number,
406
+ timeZone: string,
407
+ ): Date {
408
+ return getScheduleLocalInstant(
409
+ addScheduleDays(getScheduleLocalDate(at, timeZone), days),
410
+ parseScheduleClockTime(getScheduleLocalClockTime(at, timeZone)) ?? 0,
411
+ timeZone,
412
+ );
413
+ }
414
+
415
+ /*
416
+ * Build the seat specs that copy one week onto another (copy week): every
417
+ * non-canceled seat whose shiftDate is in the source week moves by the whole
418
+ * days between the two week starts, keeping its wall-clock start and end and
419
+ * the end's day offset (a 48 h seat stays 48 h of wall clock). Role,
420
+ * location, break, label and note are kept; the assignee only with
421
+ * includeAssignees. A copy that fails validateScheduleShiftSpec (a 48 h seat
422
+ * stretched past the cap by a DST change) is left out: the caller can tell by
423
+ * its missing copiedFromShiftId.
424
+ */
425
+ export function getCopyWeekShiftSpecs(args: {
426
+ shifts: ScheduleShiftStateObj[];
427
+ sourceWeekStart: string;
428
+ targetWeekStart: string;
429
+ timeZone: string;
430
+ includeAssignees: boolean;
431
+ }): ScheduleShiftSpec[] {
432
+ const days = getScheduleDaysBetween(
433
+ args.sourceWeekStart,
434
+ args.targetWeekStart,
435
+ );
436
+ return args.shifts
437
+ .filter(
438
+ (shift) =>
439
+ shift.status !== 'CANCELED' &&
440
+ isScheduleDateInWeek(shift.shiftDate, args.sourceWeekStart),
441
+ )
442
+ .map(
443
+ (shift): ScheduleShiftSpec => ({
444
+ templateItemId: null,
445
+ copiedFromShiftId: shift.id,
446
+ shiftDate: addScheduleDays(shift.shiftDate, days),
447
+ startAt: moveScheduleInstantByDays(shift.startAt, days, args.timeZone),
448
+ endAt: moveScheduleInstantByDays(shift.endAt, days, args.timeZone),
449
+ roleId: shift.roleId,
450
+ locationResourceId: shift.locationResourceId,
451
+ assigneeResourceId: args.includeAssignees
452
+ ? shift.assigneeResourceId
453
+ : null,
454
+ unpaidBreakMinutes: shift.unpaidBreakMinutes,
455
+ label: shift.label,
456
+ note: shift.note,
457
+ }),
458
+ )
459
+ .filter((spec) => !validateScheduleShiftSpec(spec))
460
+ .sort(compareScheduleShiftSpecs);
461
+ }
462
+
463
+ /*
464
+ * Turn a seat into a template item of rotation week `week` (THIS_AND_FUTURE):
465
+ * the weekday of its shiftDate, its local start and end clock times in the
466
+ * calendar zone, role, location, assignee, break and label. Null when the
467
+ * seat is longer than one day of wall clock, or its wall-clock end does not
468
+ * follow its start (a seat inside a fall-back hour), since an item cannot
469
+ * express either.
470
+ */
471
+ export function getTemplateItemSpecFromShift(
472
+ shift: ScheduleShiftStateObj,
473
+ week: number,
474
+ timeZone: string,
475
+ ): ScheduleTemplateItemSpec | null {
476
+ const startTime = getScheduleLocalClockTime(shift.startAt, timeZone);
477
+ const endTime = getScheduleLocalClockTime(shift.endAt, timeZone);
478
+ const days = getScheduleDaysBetween(
479
+ getScheduleLocalDate(shift.startAt, timeZone),
480
+ getScheduleLocalDate(shift.endAt, timeZone),
481
+ );
482
+ if (
483
+ days > 1 ||
484
+ (days === 1 && endTime > startTime) ||
485
+ (days === 0 && endTime <= startTime)
486
+ )
487
+ return null;
488
+ return {
489
+ week,
490
+ weekday: getScheduleWeekday(shift.shiftDate),
491
+ startTime,
492
+ endTime,
493
+ roleId: shift.roleId,
494
+ locationResourceId: shift.locationResourceId,
495
+ assigneeResourceId: shift.assigneeResourceId,
496
+ unpaidBreakMinutes: shift.unpaidBreakMinutes,
497
+ label: shift.label,
498
+ };
499
+ }
500
+
501
+ /*
502
+ * Order template item specs by week, weekday, start and end time.
503
+ */
504
+ function compareTemplateItemSpecs(
505
+ a: ScheduleTemplateItemSpec,
506
+ b: ScheduleTemplateItemSpec,
507
+ ): number {
508
+ return (
509
+ a.week - b.week ||
510
+ a.weekday - b.weekday ||
511
+ (a.startTime < b.startTime ? -1 : a.startTime > b.startTime ? 1 : 0) ||
512
+ (a.endTime < b.endTime ? -1 : a.endTime > b.endTime ? 1 : 0)
513
+ );
514
+ }
515
+
516
+ /*
517
+ * Build a template from published weeks (saveScheduleWeeksAsTemplate,
518
+ * set_standing_shifts fromWeeks): each date names the pay week that contains
519
+ * it (weeks start on payWeekStart), the n-th week becomes rotation week n and
520
+ * the first week's start is the anchor. Every non-canceled seat whose
521
+ * shiftDate falls in one of the weeks becomes an item; seats an item cannot
522
+ * express (longer than a day) are skipped and listed. A list that is empty,
523
+ * longer than SCHEDULE_ROTATION_MAX_WEEKS, names one week twice or holds a
524
+ * malformed date throws a RangeError.
525
+ */
526
+ export function buildTemplateItemsFromWeeks(args: {
527
+ shifts: ScheduleShiftStateObj[];
528
+ weekStarts: string[];
529
+ timeZone: string;
530
+ payWeekStart: number;
531
+ }): {
532
+ rotation: ScheduleTemplateRotationObj;
533
+ items: ScheduleTemplateItemSpec[];
534
+ skippedShiftIds: string[];
535
+ } {
536
+ if (!args.weekStarts.every(isScheduleDateKey))
537
+ throw new RangeError('weekStarts must be dates (YYYY-MM-DD)');
538
+ const weekStarts = args.weekStarts.map((date) =>
539
+ getScheduleWeekStart(date, args.payWeekStart),
540
+ );
541
+ if (
542
+ !isScheduleRotationWeeks(weekStarts.length) ||
543
+ new Set(weekStarts).size !== weekStarts.length
544
+ )
545
+ throw new RangeError(
546
+ `weekStarts must name 1 to ${SCHEDULE_ROTATION_MAX_WEEKS} distinct weeks`,
547
+ );
548
+
549
+ const items: Array<{ spec: ScheduleTemplateItemSpec; shiftId: string }> = [];
550
+ const skippedShiftIds: string[] = [];
551
+ for (const shift of args.shifts) {
552
+ if (shift.status === 'CANCELED') continue;
553
+ const index = weekStarts.findIndex((weekStart) =>
554
+ isScheduleDateInWeek(shift.shiftDate, weekStart),
555
+ );
556
+ if (index < 0) continue;
557
+ const spec = getTemplateItemSpecFromShift(shift, index + 1, args.timeZone);
558
+ if (spec) items.push({ spec, shiftId: shift.id });
559
+ else skippedShiftIds.push(shift.id);
560
+ }
561
+
562
+ return {
563
+ rotation: {
564
+ rotationWeeks: weekStarts.length,
565
+ rotationAnchor: weekStarts[0],
566
+ },
567
+ items: items
568
+ .sort(
569
+ (a, b) =>
570
+ compareTemplateItemSpecs(a.spec, b.spec) ||
571
+ compareScheduleIds(a.shiftId, b.shiftId),
572
+ )
573
+ .map((item) => item.spec),
574
+ skippedShiftIds: skippedShiftIds.sort(compareScheduleIds),
575
+ };
576
+ }
577
+
578
+ /*
579
+ * Plan a change of rotation length: growing copies the week-1 items (week A)
580
+ * into every new week, so the new weeks start identical (times normalized to
581
+ * 'HH:mm'); shrinking deletes the items of weeks beyond toWeeks. Lengths
582
+ * outside 1..
583
+ * SCHEDULE_ROTATION_MAX_WEEKS throw a RangeError.
584
+ */
585
+ export function resizeTemplateRotation(args: {
586
+ items: ScheduleTemplateItemInput[];
587
+ fromWeeks: number;
588
+ toWeeks: number;
589
+ }): { create: ScheduleTemplateItemSpec[]; deleteItemIds: string[] } {
590
+ const { fromWeeks, toWeeks } = args;
591
+ if (!isScheduleRotationWeeks(fromWeeks) || !isScheduleRotationWeeks(toWeeks))
592
+ throw new RangeError(`Invalid rotation resize ${fromWeeks} -> ${toWeeks}`);
593
+
594
+ if (toWeeks < fromWeeks)
595
+ return {
596
+ create: [],
597
+ deleteItemIds: args.items
598
+ .filter((item) => item.week > toWeeks)
599
+ .map((item) => item.id)
600
+ .sort(compareScheduleIds),
601
+ };
602
+
603
+ const weekA = args.items
604
+ .filter((item) => item.week === 1)
605
+ .sort(
606
+ (a, b) =>
607
+ compareTemplateItemSpecs(a, b) || compareScheduleIds(a.id, b.id),
608
+ );
609
+ const create: ScheduleTemplateItemSpec[] = [];
610
+ for (let week = fromWeeks + 1; week <= toWeeks; week++)
611
+ for (const { id: _id, ...item } of weekA)
612
+ create.push({
613
+ ...item,
614
+ week,
615
+ startTime: normalizeScheduleClockTime(item.startTime) ?? item.startTime,
616
+ endTime: normalizeScheduleClockTime(item.endTime) ?? item.endTime,
617
+ });
618
+ return { create, deleteItemIds: [] };
619
+ }