@jsb188/schedule 1.1.11 → 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 (62) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +34 -14
  3. package/src/constants/schedule.ts +710 -306
  4. package/src/modules/Gantt.helpers.ts +11 -30
  5. package/src/modules/Gantt.tsx +46 -181
  6. package/src/types/schedule.d.ts +1827 -456
  7. package/src/ui/ProjectFormUI.tsx +8 -31
  8. package/src/ui/ScheduleSettingsUI.tsx +21 -23
  9. package/src/utils/autofill.ts +469 -0
  10. package/src/utils/availability.ts +167 -0
  11. package/src/utils/candidates.ts +447 -0
  12. package/src/utils/coverage.helpers.ts +509 -554
  13. package/src/utils/coverage.ts +1121 -526
  14. package/src/utils/cpm.helpers.ts +27 -29
  15. package/src/utils/cpm.ts +53 -41
  16. package/src/utils/cpmLeveling.helpers.ts +89 -16
  17. package/src/utils/cpmLeveling.ts +28 -26
  18. package/src/utils/cycle.ts +325 -0
  19. package/src/utils/demand.ts +239 -0
  20. package/src/utils/eligibility.ts +553 -400
  21. package/src/utils/ids.ts +47 -0
  22. package/src/utils/laborRules.ts +740 -0
  23. package/src/utils/localTime.ts +312 -0
  24. package/src/utils/offer.ts +300 -0
  25. package/src/utils/planCsv.ts +73 -19
  26. package/src/utils/predicate.ts +111 -0
  27. package/src/utils/request.ts +212 -114
  28. package/src/utils/resource.ts +412 -112
  29. package/src/utils/rule.ts +697 -163
  30. package/src/utils/rulePresets.ts +116 -0
  31. package/src/utils/run.ts +0 -8
  32. package/src/utils/scheduleText.ts +4074 -0
  33. package/src/utils/shiftChange.ts +279 -0
  34. package/src/utils/standing.ts +730 -0
  35. package/src/utils/template.ts +619 -0
  36. package/src/utils/violation.ts +184 -0
  37. package/src/utils/workTime.ts +341 -120
  38. package/src/utils/defaults.ts +0 -8
  39. package/src/utils/recurrence.ts +0 -616
  40. package/src/utils/series.ts +0 -161
  41. package/src/utils/slot.ts +0 -208
  42. package/tests/coverage.fixtures.ts +0 -111
  43. package/tests/coverage.test.ts +0 -503
  44. package/tests/cpm.bench.test.ts +0 -154
  45. package/tests/cpm.test.ts +0 -354
  46. package/tests/cpmCorrectness.test.ts +0 -327
  47. package/tests/cpmLeveling.test.ts +0 -471
  48. package/tests/eligibility.test.ts +0 -320
  49. package/tests/gantt-geometry.test.ts +0 -367
  50. package/tests/gantt-histogram.test.ts +0 -78
  51. package/tests/gantt-keyboard.test.ts +0 -69
  52. package/tests/helpers/cpmFixtures.ts +0 -101
  53. package/tests/projectInputs.test.ts +0 -165
  54. package/tests/recurrence.test.ts +0 -68
  55. package/tests/request.test.ts +0 -99
  56. package/tests/resource.test.ts +0 -95
  57. package/tests/rule.test.ts +0 -98
  58. package/tests/series.test.ts +0 -120
  59. package/tests/workTime.test.ts +0 -1007
  60. package/tests/workTimeContracts.test.ts +0 -111
  61. package/tsconfig.json +0 -13
  62. package/vitest.config.ts +0 -8
@@ -0,0 +1,730 @@
1
+ import {
2
+ SCHEDULE_REPEAT_ALTERNATING_RUN,
3
+ SCHEDULE_REPEAT_COVER_RUN,
4
+ SCHEDULE_STANDING_FIELD_GROUP_ENUMS,
5
+ } from '../constants/schedule.ts';
6
+ import type {
7
+ ScheduleShiftSpec,
8
+ ScheduleShiftStateObj,
9
+ ScheduleStandingFieldGroupEnum,
10
+ ScheduleStandingItemEditObj,
11
+ ScheduleStandingRepeatObj,
12
+ ScheduleStandingSeatLinkObj,
13
+ ScheduleStandingSeatValuesObj,
14
+ ScheduleTemplateItemInput,
15
+ ScheduleTemplateItemSpec,
16
+ ScheduleTemplateRotationObj,
17
+ } from '../types/schedule.d.ts';
18
+ import { compareScheduleIds } from './ids.ts';
19
+ import {
20
+ addScheduleDays,
21
+ getScheduleWeekStart,
22
+ getScheduleWeekday,
23
+ normalizeScheduleClockTime,
24
+ toScheduleTimeMs,
25
+ } from './localTime.ts';
26
+ import {
27
+ getRotationWeek,
28
+ getTemplateItemSpecFromShift,
29
+ placeScheduleTemplateItem,
30
+ } from './template.ts';
31
+
32
+ /**
33
+ * The standing schedule kept current (IMPLEMENTATION §1.12).
34
+ *
35
+ * - A seat "made from" a standing item is linked to it (`templateItemId`),
36
+ * or an unlinked live seat the matcher pairs with it: the item placed on
37
+ * the seat's shiftDate (of its rotation week and weekday) gives exactly
38
+ * its start, end, role and location. Every reader of an item's seats uses
39
+ * this one rule.
40
+ * - A THIS_AND_FUTURE change rewrites the item, then carries each changed
41
+ * field group (HOURS, ROLE, LOCATION, BREAK, LABEL) to the item's later
42
+ * seats that still hold the item's old value; a seat changed by hand keeps
43
+ * its own. PERSON is the server's (assign), not this module's.
44
+ * - Repeat detection reads an item's last published seats: someone else
45
+ * holding it three times running, or two people alternating.
46
+ * - Pure and deterministic: ties by compareScheduleIds.
47
+ */
48
+
49
+ // One standing item's published seat, as repeat detection reads it
50
+ type ScheduleRepeatSeat = {
51
+ shiftDate: string;
52
+ assigneeResourceId: string | null;
53
+ };
54
+
55
+ // The field groups a later seat may take from the item, in enum order
56
+ type ScheduleStandingSeatGroup = Exclude<
57
+ ScheduleStandingFieldGroupEnum,
58
+ 'PERSON'
59
+ >;
60
+
61
+ const FILE_CONSTANTS = {
62
+ // The seat field of each one-field group (HOURS is start and end)
63
+ groupFields: {
64
+ ROLE: 'roleId',
65
+ LOCATION: 'locationResourceId',
66
+ BREAK: 'unpaidBreakMinutes',
67
+ LABEL: 'label',
68
+ } as const,
69
+ };
70
+
71
+ /*
72
+ * The pairing key of a placed seat: its exact start and end (ms), role and
73
+ * location.
74
+ */
75
+ function getStandingSeatSignature(
76
+ seat: Pick<ScheduleShiftStateObj, 'roleId' | 'locationResourceId'> & {
77
+ startAt: Date | string;
78
+ endAt: Date | string;
79
+ },
80
+ ): string {
81
+ return [
82
+ toScheduleTimeMs(seat.startAt),
83
+ toScheduleTimeMs(seat.endAt),
84
+ seat.roleId ?? '',
85
+ seat.locationResourceId ?? '',
86
+ ].join('|');
87
+ }
88
+
89
+ /*
90
+ * The key of one occurrence of an item: the item and the pay week of a date
91
+ * (an item falls once in each pay week of its rotation week).
92
+ */
93
+ function getStandingWeekKey(
94
+ itemId: string,
95
+ date: string,
96
+ payWeekStart: number,
97
+ ): string {
98
+ return `${itemId}|${getScheduleWeekStart(date, payWeekStart)}`;
99
+ }
100
+
101
+ /*
102
+ * The date an item's weekday falls on in the pay week of a date: the week
103
+ * start plus the weekday's offset from payWeekStart.
104
+ */
105
+ function getStandingItemDateInWeek(
106
+ weekday: number,
107
+ date: string,
108
+ payWeekStart: number,
109
+ ): string {
110
+ return addScheduleDays(
111
+ getScheduleWeekStart(date, payWeekStart),
112
+ (weekday - payWeekStart + 7) % 7,
113
+ );
114
+ }
115
+
116
+ /*
117
+ * Check whether a seat's link to an item still holds: the seat's
118
+ * pay week is in the item's rotation week. A link made before the rotation,
119
+ * its anchor or the item's week changed is stale: the seat is nobody's seat
120
+ * until the matcher pairs it again. The weekday does not matter (a seat moved
121
+ * by hand within its week stays the item's seat for that week).
122
+ */
123
+ export function isScheduleStandingLinkCurrent(args: {
124
+ item: Pick<ScheduleTemplateItemInput, 'week'>;
125
+ shiftDate: string;
126
+ rotation: ScheduleTemplateRotationObj;
127
+ payWeekStart: number;
128
+ }): boolean {
129
+ return (
130
+ getRotationWeek(args.shiftDate, args.rotation, args.payWeekStart) ===
131
+ args.item.week
132
+ );
133
+ }
134
+
135
+ /*
136
+ * The standing item a seat's link names while it holds: null when the seat
137
+ * is unlinked, linked to an item that is not one of `itemsById`, or stale.
138
+ */
139
+ export function getScheduleStandingLinkedItemId(args: {
140
+ seat: { templateItemId: string | null; shiftDate: string };
141
+ itemsById: ReadonlyMap<string, ScheduleTemplateItemInput>;
142
+ rotation: ScheduleTemplateRotationObj;
143
+ payWeekStart: number;
144
+ }): string | null {
145
+ const itemId = args.seat.templateItemId ?? null;
146
+ const item = itemId ? args.itemsById.get(itemId) : undefined;
147
+ if (!item) return null;
148
+ const current = isScheduleStandingLinkCurrent({
149
+ item,
150
+ shiftDate: args.seat.shiftDate,
151
+ rotation: args.rotation,
152
+ payWeekStart: args.payWeekStart,
153
+ });
154
+ return current ? item.id : null;
155
+ }
156
+
157
+ /*
158
+ * Group items by `week:weekday`, each list by id.
159
+ */
160
+ function groupStandingItemsByDay(
161
+ items: ScheduleTemplateItemInput[],
162
+ ): Map<string, ScheduleTemplateItemInput[]> {
163
+ const byDay = new Map<string, ScheduleTemplateItemInput[]>();
164
+ for (const item of [...items].sort((a, b) =>
165
+ compareScheduleIds(a.id, b.id),
166
+ )) {
167
+ const key = `${item.week}:${item.weekday}`;
168
+ byDay.set(key, [...(byDay.get(key) ?? []), item]);
169
+ }
170
+ return byDay;
171
+ }
172
+
173
+ // What the matcher reads from the seats: the occurrences already held and
174
+ // the seats it may pair
175
+ type StandingSeatSplit = {
176
+ taken: Set<string>; // getStandingWeekKey of every current link (any status)
177
+ candidates: ScheduleShiftStateObj[]; // live, unlinked or linked stale
178
+ };
179
+
180
+ /*
181
+ * Split the seats the matcher reads: a seat currently linked to one of the
182
+ * items holds that item's occurrence in its pay week (any status, wherever
183
+ * in the week it sits); a live seat that is unlinked, or whose link to one of
184
+ * the items is stale, is a candidate. Seats linked to other items are
185
+ * neither.
186
+ */
187
+ function splitStandingSeats(args: {
188
+ seats: ScheduleShiftStateObj[];
189
+ itemsById: ReadonlyMap<string, ScheduleTemplateItemInput>;
190
+ rotation: ScheduleTemplateRotationObj;
191
+ payWeekStart: number;
192
+ }): StandingSeatSplit {
193
+ const split: StandingSeatSplit = { taken: new Set(), candidates: [] };
194
+ for (const seat of args.seats) {
195
+ const linkedId = getScheduleStandingLinkedItemId({ ...args, seat });
196
+ if (linkedId) {
197
+ split.taken.add(
198
+ getStandingWeekKey(linkedId, seat.shiftDate, args.payWeekStart),
199
+ );
200
+ continue;
201
+ }
202
+ const linkedElsewhere =
203
+ !!seat.templateItemId && !args.itemsById.has(seat.templateItemId);
204
+ if (!linkedElsewhere && seat.status !== 'CANCELED')
205
+ split.candidates.push(seat);
206
+ }
207
+ return split;
208
+ }
209
+
210
+ /*
211
+ * Group the free items of one date by the signature of their placement on
212
+ * it: the items of the date's rotation week and weekday whose occurrence in
213
+ * that pay week no linked seat holds, by id.
214
+ */
215
+ function getFreeStandingItemsBySignature(args: {
216
+ date: string;
217
+ itemsByDay: Map<string, ScheduleTemplateItemInput[]>;
218
+ rotation: ScheduleTemplateRotationObj;
219
+ payWeekStart: number;
220
+ timeZone: string;
221
+ taken: Set<string>;
222
+ }): Map<string, ScheduleTemplateItemInput[]> {
223
+ const { date } = args;
224
+ const week = getRotationWeek(date, args.rotation, args.payWeekStart);
225
+ const bySignature = new Map<string, ScheduleTemplateItemInput[]>();
226
+ for (const item of args.itemsByDay.get(
227
+ `${week}:${getScheduleWeekday(date)}`,
228
+ ) ?? []) {
229
+ if (args.taken.has(getStandingWeekKey(item.id, date, args.payWeekStart)))
230
+ continue;
231
+ const spec = placeScheduleTemplateItem(item, date, args.timeZone);
232
+ if (!spec) continue;
233
+ const signature = getStandingSeatSignature(spec);
234
+ bySignature.set(signature, [...(bySignature.get(signature) ?? []), item]);
235
+ }
236
+ return bySignature;
237
+ }
238
+
239
+ /*
240
+ * Group the candidate seats by date and signature, each list by id.
241
+ */
242
+ function groupStandingCandidateSeats(
243
+ seats: ScheduleShiftStateObj[],
244
+ ): Map<string, Map<string, ScheduleShiftStateObj[]>> {
245
+ const byDate = new Map<string, Map<string, ScheduleShiftStateObj[]>>();
246
+ for (const seat of [...seats].sort((a, b) =>
247
+ compareScheduleIds(a.id, b.id),
248
+ )) {
249
+ const bySignature = byDate.get(seat.shiftDate) ?? new Map();
250
+ const signature = getStandingSeatSignature(seat);
251
+ bySignature.set(signature, [...(bySignature.get(signature) ?? []), seat]);
252
+ byDate.set(seat.shiftDate, bySignature);
253
+ }
254
+ return byDate;
255
+ }
256
+
257
+ /*
258
+ * Pair the seats and items of one (date, signature): first each seat (by id)
259
+ * with the first free item (by id) whose fixed person holds it, then the
260
+ * remaining seats with the remaining items, both by id.
261
+ */
262
+ function pairStandingSeatsWithItems(
263
+ seats: ScheduleShiftStateObj[],
264
+ items: ScheduleTemplateItemInput[],
265
+ ): ScheduleStandingSeatLinkObj[] {
266
+ const free = [...items];
267
+ const links: ScheduleStandingSeatLinkObj[] = [];
268
+ const rest: ScheduleShiftStateObj[] = [];
269
+ for (const seat of seats) {
270
+ const index = seat.assigneeResourceId
271
+ ? free.findIndex(
272
+ (item) => item.assigneeResourceId === seat.assigneeResourceId,
273
+ )
274
+ : -1;
275
+ if (index < 0) {
276
+ rest.push(seat);
277
+ continue;
278
+ }
279
+ links.push({ shiftId: seat.id, templateItemId: free[index].id });
280
+ free.splice(index, 1);
281
+ }
282
+ for (let index = 0; index < Math.min(rest.length, free.length); index++)
283
+ links.push({ shiftId: rest[index].id, templateItemId: free[index].id });
284
+ return links;
285
+ }
286
+
287
+ /*
288
+ * Pair live seats that are unlinked (or whose link went stale) with the
289
+ * standing items they were made from: for each seat's
290
+ * shiftDate, the items of that date's rotation week and weekday whose
291
+ * placement on it has the seat's exact start, end, role and location (break
292
+ * and label do not matter). An item's occurrence in a pay week already held
293
+ * by a seat currently linked to it (any status) is taken. Per (date,
294
+ * signature), a seat held by an item's fixed person pairs with that item
295
+ * first; the rest pair by id. Ordered by shift id.
296
+ */
297
+ export function matchScheduleSeatsToTemplateItems(args: {
298
+ items: ScheduleTemplateItemInput[];
299
+ rotation: ScheduleTemplateRotationObj;
300
+ payWeekStart: number;
301
+ timeZone: string;
302
+ seats: ScheduleShiftStateObj[];
303
+ }): ScheduleStandingSeatLinkObj[] {
304
+ const itemsById = new Map(args.items.map((item) => [item.id, item]));
305
+ const itemsByDay = groupStandingItemsByDay(args.items);
306
+ const split = splitStandingSeats({ ...args, itemsById });
307
+ const links: ScheduleStandingSeatLinkObj[] = [];
308
+ for (const [date, seatsBySignature] of groupStandingCandidateSeats(
309
+ split.candidates,
310
+ )) {
311
+ const itemsBySignature = getFreeStandingItemsBySignature({
312
+ date,
313
+ itemsByDay,
314
+ rotation: args.rotation,
315
+ payWeekStart: args.payWeekStart,
316
+ timeZone: args.timeZone,
317
+ taken: split.taken,
318
+ });
319
+ for (const [signature, seats] of seatsBySignature)
320
+ links.push(
321
+ ...pairStandingSeatsWithItems(
322
+ seats,
323
+ itemsBySignature.get(signature) ?? [],
324
+ ),
325
+ );
326
+ }
327
+ return links.sort((a, b) => compareScheduleIds(a.shiftId, b.shiftId));
328
+ }
329
+
330
+ /*
331
+ * Keep the expanded seats of a standing schedule that no seat holds yet: an
332
+ * item's occurrence in a pay week is held by a seat
333
+ * currently linked to it in that week (any status, moved by hand to another
334
+ * day or not) or by a seat the matcher pairs with it.
335
+ */
336
+ export function getScheduleStandingMissingSpecs(args: {
337
+ specs: ScheduleShiftSpec[];
338
+ items: ScheduleTemplateItemInput[];
339
+ rotation: ScheduleTemplateRotationObj;
340
+ payWeekStart: number;
341
+ seats: ScheduleShiftStateObj[];
342
+ links: ScheduleStandingSeatLinkObj[];
343
+ }): ScheduleShiftSpec[] {
344
+ const itemsById = new Map(args.items.map((item) => [item.id, item]));
345
+ const { taken } = splitStandingSeats({ ...args, itemsById });
346
+ const seatDates = new Map(
347
+ args.seats.map((seat) => [seat.id, seat.shiftDate]),
348
+ );
349
+ for (const link of args.links) {
350
+ const date = seatDates.get(link.shiftId);
351
+ if (date)
352
+ taken.add(
353
+ getStandingWeekKey(link.templateItemId, date, args.payWeekStart),
354
+ );
355
+ }
356
+ return args.specs.filter(
357
+ (spec) =>
358
+ !spec.templateItemId ||
359
+ !taken.has(
360
+ getStandingWeekKey(
361
+ spec.templateItemId,
362
+ spec.shiftDate,
363
+ args.payWeekStart,
364
+ ),
365
+ ),
366
+ );
367
+ }
368
+
369
+ /*
370
+ * The standing item a seat would become (THIS_AND_FUTURE on a seat with no
371
+ * item): its rotation week, weekday, local clock times, role, location,
372
+ * assignee (the fixed person), break and label. NOT_STANDING when an item
373
+ * cannot express it (longer than a day, or inside a fall-back hour).
374
+ */
375
+ export function getScheduleStandingItemFromSeat(args: {
376
+ seat: ScheduleShiftStateObj;
377
+ rotation: ScheduleTemplateRotationObj;
378
+ payWeekStart: number;
379
+ timeZone: string;
380
+ }): { item: ScheduleTemplateItemSpec } | { error: 'NOT_STANDING' } {
381
+ const item = getTemplateItemSpecFromShift(
382
+ args.seat,
383
+ getRotationWeek(args.seat.shiftDate, args.rotation, args.payWeekStart),
384
+ args.timeZone,
385
+ );
386
+ return item ? { item } : { error: 'NOT_STANDING' };
387
+ }
388
+
389
+ /*
390
+ * Compare two optional values the way a seat column does (undefined and
391
+ * null are the same empty value).
392
+ */
393
+ function isSameStandingValue(a: unknown, b: unknown): boolean {
394
+ return (a ?? null) === (b ?? null);
395
+ }
396
+
397
+ /*
398
+ * Check whether a placed seat has exactly a seat's start and end.
399
+ */
400
+ function hasStandingSeatHours(
401
+ spec: Pick<ScheduleShiftStateObj, 'startAt' | 'endAt'> | null,
402
+ seat: Pick<ScheduleShiftStateObj, 'startAt' | 'endAt'>,
403
+ ): boolean {
404
+ return (
405
+ !!spec &&
406
+ toScheduleTimeMs(spec.startAt) === toScheduleTimeMs(seat.startAt) &&
407
+ toScheduleTimeMs(spec.endAt) === toScheduleTimeMs(seat.endAt)
408
+ );
409
+ }
410
+
411
+ /*
412
+ * Place an item on its own weekday in a seat's pay week. Null when it cannot
413
+ * be placed there (a DST corner).
414
+ */
415
+ function placeStandingItemInSeatWeek(args: {
416
+ seat: Pick<ScheduleShiftStateObj, 'shiftDate'>;
417
+ item: ScheduleTemplateItemInput;
418
+ payWeekStart: number;
419
+ timeZone: string;
420
+ }): ScheduleShiftSpec | null {
421
+ return placeScheduleTemplateItem(
422
+ args.item,
423
+ getStandingItemDateInWeek(
424
+ args.item.weekday,
425
+ args.seat.shiftDate,
426
+ args.payWeekStart,
427
+ ),
428
+ args.timeZone,
429
+ );
430
+ }
431
+
432
+ /*
433
+ * Check whether a seat holds an item's value of one field group. HOURS: the
434
+ * item placed on its own weekday of the seat's pay week gives the seat's
435
+ * exact start and end (a seat moved by hand to another day does not).
436
+ */
437
+ function hasStandingItemValue(args: {
438
+ group: ScheduleStandingSeatGroup;
439
+ seat: ScheduleShiftStateObj;
440
+ item: ScheduleTemplateItemInput;
441
+ payWeekStart: number;
442
+ timeZone: string;
443
+ }): boolean {
444
+ if (args.group === 'HOURS')
445
+ return hasStandingSeatHours(placeStandingItemInSeatWeek(args), args.seat);
446
+ const field = FILE_CONSTANTS.groupFields[args.group];
447
+ return isSameStandingValue(args.seat[field], args.item[field]);
448
+ }
449
+
450
+ /*
451
+ * The field groups a THIS_AND_FUTURE update changes on the item, in enum
452
+ * order (never PERSON): those whose value differs between the target seat
453
+ * before and after, and those the edit named (`groups`) whose value on the
454
+ * target now differs from the item's (making a one-off permanent: the
455
+ * target already holds the value, the item does not).
456
+ */
457
+ function getChangedStandingGroups(args: {
458
+ item: ScheduleTemplateItemInput;
459
+ before: ScheduleShiftStateObj;
460
+ after: ScheduleShiftStateObj;
461
+ groups: ScheduleStandingFieldGroupEnum[];
462
+ payWeekStart: number;
463
+ timeZone: string;
464
+ }): ScheduleStandingFieldGroupEnum[] {
465
+ const { before, after } = args;
466
+ return SCHEDULE_STANDING_FIELD_GROUP_ENUMS.filter(
467
+ (group): group is ScheduleStandingSeatGroup => {
468
+ if (group === 'PERSON') return false;
469
+ const moved =
470
+ group === 'HOURS'
471
+ ? !hasStandingSeatHours(before, after)
472
+ : !isSameStandingValue(
473
+ before[FILE_CONSTANTS.groupFields[group]],
474
+ after[FILE_CONSTANTS.groupFields[group]],
475
+ );
476
+ return (
477
+ moved ||
478
+ (args.groups.includes(group) &&
479
+ !hasStandingItemValue({ ...args, group, seat: after }))
480
+ );
481
+ },
482
+ );
483
+ }
484
+
485
+ /*
486
+ * Copy an item without its id, its clock times as 'HH:mm'.
487
+ */
488
+ function toStandingItemSpec(
489
+ item: ScheduleTemplateItemInput,
490
+ ): ScheduleTemplateItemSpec {
491
+ const { id: _id, ...spec } = item;
492
+ return {
493
+ ...spec,
494
+ startTime: normalizeScheduleClockTime(item.startTime) ?? item.startTime,
495
+ endTime: normalizeScheduleClockTime(item.endTime) ?? item.endTime,
496
+ };
497
+ }
498
+
499
+ /*
500
+ * The item after a THIS_AND_FUTURE update of one of its seats: the groups
501
+ * that changed on the target (HOURS: start/end; ROLE; LOCATION; BREAK;
502
+ * LABEL), or that the edit named (`groups`) and the item does not hold, are
503
+ * taken from `after` (HOURS: its weekday and clock times), every other group
504
+ * from the item itself (the target may be a one-off). `week` and the fixed
505
+ * person never change here. STANDING_MOVE_WEEK when `after` is in another
506
+ * pay week than `before`; NOT_STANDING when the new hours are not
507
+ * expressible as an item.
508
+ */
509
+ export function getScheduleStandingItemEdit(args: {
510
+ item: ScheduleTemplateItemInput;
511
+ before: ScheduleShiftStateObj;
512
+ after: ScheduleShiftStateObj;
513
+ groups?: ScheduleStandingFieldGroupEnum[];
514
+ payWeekStart: number;
515
+ timeZone: string;
516
+ }):
517
+ | ScheduleStandingItemEditObj
518
+ | { error: 'NOT_STANDING' | 'STANDING_MOVE_WEEK' } {
519
+ const { item, before, after } = args;
520
+ if (
521
+ getScheduleWeekStart(before.shiftDate, args.payWeekStart) !==
522
+ getScheduleWeekStart(after.shiftDate, args.payWeekStart)
523
+ )
524
+ return { error: 'STANDING_MOVE_WEEK' };
525
+ const changed = getChangedStandingGroups({
526
+ ...args,
527
+ groups: args.groups ?? [],
528
+ });
529
+ const next = toStandingItemSpec(item);
530
+ if (changed.includes('HOURS')) {
531
+ const hours = getTemplateItemSpecFromShift(after, item.week, args.timeZone);
532
+ if (!hours) return { error: 'NOT_STANDING' };
533
+ next.weekday = hours.weekday;
534
+ next.startTime = hours.startTime;
535
+ next.endTime = hours.endTime;
536
+ }
537
+ if (changed.includes('ROLE')) next.roleId = after.roleId;
538
+ if (changed.includes('LOCATION'))
539
+ next.locationResourceId = after.locationResourceId;
540
+ if (changed.includes('BREAK'))
541
+ next.unpaidBreakMinutes = after.unpaidBreakMinutes;
542
+ if (changed.includes('LABEL')) next.label = after.label;
543
+ return { item: next, changed };
544
+ }
545
+
546
+ /*
547
+ * The values one later seat of an item takes from a THIS_AND_FUTURE change,
548
+ * group by group over `changed` (PERSON is the server's): a
549
+ * group applies when the seat still has the item's old value (HOURS: the old
550
+ * item placed on its own weekday of the seat's pay week gives its exact
551
+ * start and end, so a seat moved by hand to another day keeps its day; the
552
+ * new times are the new item placed on the new weekday of that week). A seat
553
+ * that already has the new value is left alone (neither applied nor kept: a
554
+ * replay); any other value is the seat's own and is kept. HOURS is kept too
555
+ * when the new item cannot be placed in that week.
556
+ */
557
+ export function getScheduleStandingLaterSeatValues(args: {
558
+ seat: ScheduleShiftStateObj;
559
+ before: ScheduleTemplateItemInput;
560
+ after: ScheduleTemplateItemSpec;
561
+ changed: ScheduleStandingFieldGroupEnum[];
562
+ payWeekStart: number;
563
+ timeZone: string;
564
+ }): {
565
+ values: ScheduleStandingSeatValuesObj;
566
+ applied: ScheduleStandingFieldGroupEnum[];
567
+ kept: ScheduleStandingFieldGroupEnum[];
568
+ } {
569
+ const { seat, before, after } = args;
570
+ const values: ScheduleStandingSeatValuesObj = {};
571
+ const applied: ScheduleStandingFieldGroupEnum[] = [];
572
+ const kept: ScheduleStandingFieldGroupEnum[] = [];
573
+ const groups = SCHEDULE_STANDING_FIELD_GROUP_ENUMS.filter(
574
+ (group): group is ScheduleStandingSeatGroup =>
575
+ group !== 'PERSON' && args.changed.includes(group),
576
+ );
577
+ const place = {
578
+ seat,
579
+ payWeekStart: args.payWeekStart,
580
+ timeZone: args.timeZone,
581
+ };
582
+ for (const group of groups) {
583
+ if (group === 'HOURS') {
584
+ const next = placeStandingItemInSeatWeek({
585
+ ...place,
586
+ item: { ...after, id: before.id },
587
+ });
588
+ if (hasStandingSeatHours(next, seat)) continue;
589
+ if (next && hasStandingItemValue({ ...place, group, item: before })) {
590
+ values.startAt = next.startAt;
591
+ values.endAt = next.endAt;
592
+ applied.push(group);
593
+ } else kept.push(group);
594
+ continue;
595
+ }
596
+ const field = FILE_CONSTANTS.groupFields[group];
597
+ if (isSameStandingValue(seat[field], after[field])) continue;
598
+ if (isSameStandingValue(seat[field], before[field])) {
599
+ Object.assign(values, { [field]: after[field] });
600
+ applied.push(group);
601
+ } else kept.push(group);
602
+ }
603
+ return { values, applied, kept };
604
+ }
605
+
606
+ /*
607
+ * One seat per date, latest first (on a date with two, a held seat before
608
+ * an open one, then by assignee id).
609
+ */
610
+ function getLatestRepeatSeats(
611
+ seats: ScheduleRepeatSeat[],
612
+ ): ScheduleRepeatSeat[] {
613
+ const sorted = [...seats].sort(
614
+ (a, b) =>
615
+ (a.shiftDate < b.shiftDate ? 1 : a.shiftDate > b.shiftDate ? -1 : 0) ||
616
+ Number(a.assigneeResourceId === null) -
617
+ Number(b.assigneeResourceId === null) ||
618
+ compareScheduleIds(
619
+ a.assigneeResourceId ?? '',
620
+ b.assigneeResourceId ?? '',
621
+ ),
622
+ );
623
+ return sorted.filter(
624
+ (seat, index) =>
625
+ index === 0 || sorted[index - 1].shiftDate !== seat.shiftDate,
626
+ );
627
+ }
628
+
629
+ /*
630
+ * COVER: the latest seats were held by one person other than the fixed
631
+ * person at least SCHEDULE_REPEAT_COVER_RUN times running (an open seat or
632
+ * anyone else ends the run).
633
+ */
634
+ function getStandingCoverRepeat(
635
+ itemId: string,
636
+ fixedId: string,
637
+ seats: ScheduleRepeatSeat[],
638
+ ): ScheduleStandingRepeatObj | null {
639
+ const holder = seats[0]?.assigneeResourceId ?? null;
640
+ if (holder === null || holder === fixedId) return null;
641
+ let count = 0;
642
+ while (count < seats.length && seats[count].assigneeResourceId === holder)
643
+ count++;
644
+ return count >= SCHEDULE_REPEAT_COVER_RUN
645
+ ? { kind: 'COVER', itemId, resourceIds: [holder], count }
646
+ : null;
647
+ }
648
+
649
+ /*
650
+ * ALTERNATING: the latest SCHEDULE_REPEAT_ALTERNATING_RUN seats were all
651
+ * held, by two people taking turns. The one who held it second latest is due
652
+ * next, so they come first (week A is the next period's week).
653
+ */
654
+ function getStandingAlternatingRepeat(
655
+ itemId: string,
656
+ seats: ScheduleRepeatSeat[],
657
+ ): ScheduleStandingRepeatObj | null {
658
+ const run = seats
659
+ .slice(0, SCHEDULE_REPEAT_ALTERNATING_RUN)
660
+ .map((seat) => seat.assigneeResourceId);
661
+ if (run.length < SCHEDULE_REPEAT_ALTERNATING_RUN || run.includes(null))
662
+ return null;
663
+ const [latest, previous] = run as string[];
664
+ const alternates = run.every(
665
+ (holder, index) => holder === (index % 2 ? previous : latest),
666
+ );
667
+ if (!alternates || latest === previous) return null;
668
+ return {
669
+ kind: 'ALTERNATING',
670
+ itemId,
671
+ resourceIds: [previous, latest],
672
+ count: SCHEDULE_REPEAT_ALTERNATING_RUN,
673
+ };
674
+ }
675
+
676
+ /*
677
+ * Order items by week, weekday, start time, then id.
678
+ */
679
+ function compareRepeatItems(
680
+ a: Pick<ScheduleTemplateItemInput, 'id' | 'week' | 'weekday' | 'startTime'>,
681
+ b: Pick<ScheduleTemplateItemInput, 'id' | 'week' | 'weekday' | 'startTime'>,
682
+ ): number {
683
+ const startA = normalizeScheduleClockTime(a.startTime) ?? a.startTime;
684
+ const startB = normalizeScheduleClockTime(b.startTime) ?? b.startTime;
685
+ return (
686
+ a.week - b.week ||
687
+ a.weekday - b.weekday ||
688
+ (startA < startB ? -1 : startA > startB ? 1 : 0) ||
689
+ compareScheduleIds(a.id, b.id)
690
+ );
691
+ }
692
+
693
+ /*
694
+ * Detect what has started to repeat on the standing items with a fixed
695
+ * person, over each item's published seats before the period (§1.12):
696
+ * someone else held it SCHEDULE_REPEAT_COVER_RUN times running (COVER), or,
697
+ * with no rotation of two or more weeks, two people alternated over the
698
+ * last SCHEDULE_REPEAT_ALTERNATING_RUN (ALTERNATING). COVER reads only the
699
+ * seats on or after an item's `coverSince` date (when its fixed person was
700
+ * last set), so the previous fixed person's history never reads as covering
701
+ * for the new one. Ordered by item week, weekday, start, then id.
702
+ */
703
+ export function detectScheduleStandingRepeats(args: {
704
+ items: Array<
705
+ Pick<
706
+ ScheduleTemplateItemInput,
707
+ 'id' | 'week' | 'weekday' | 'startTime' | 'assigneeResourceId'
708
+ >
709
+ >;
710
+ seatsByItem: Record<string, ScheduleRepeatSeat[]>;
711
+ rotationWeeks: number;
712
+ coverSince?: Record<string, string>;
713
+ }): ScheduleStandingRepeatObj[] {
714
+ const repeats: ScheduleStandingRepeatObj[] = [];
715
+ for (const item of [...args.items].sort(compareRepeatItems)) {
716
+ if (!item.assigneeResourceId) continue;
717
+ const seats = getLatestRepeatSeats(args.seatsByItem[item.id] ?? []);
718
+ const since = args.coverSince?.[item.id] ?? null;
719
+ const coverSeats = since
720
+ ? seats.filter((seat) => seat.shiftDate >= since)
721
+ : seats;
722
+ const repeat =
723
+ getStandingCoverRepeat(item.id, item.assigneeResourceId, coverSeats) ??
724
+ (args.rotationWeeks === 1
725
+ ? getStandingAlternatingRepeat(item.id, seats)
726
+ : null);
727
+ if (repeat) repeats.push(repeat);
728
+ }
729
+ return repeats;
730
+ }