@jsb188/schedule 1.1.11

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 (60) hide show
  1. package/package.json +61 -0
  2. package/src/constants/schedule.ts +549 -0
  3. package/src/css.d.ts +7 -0
  4. package/src/libs/gantt-geometry.ts +771 -0
  5. package/src/libs/gantt-histogram.ts +124 -0
  6. package/src/libs/gantt-keyboard.ts +113 -0
  7. package/src/libs/gantt-state.ts +57 -0
  8. package/src/libs/gantt-url.ts +63 -0
  9. package/src/modules/Gantt.helpers.ts +138 -0
  10. package/src/modules/Gantt.tsx +719 -0
  11. package/src/types/schedule.d.ts +1149 -0
  12. package/src/ui/ActivityFormUI.tsx +133 -0
  13. package/src/ui/GanttEditorsUI.tsx +102 -0
  14. package/src/ui/GanttHistogramUI.tsx +236 -0
  15. package/src/ui/GanttUI.tsx +792 -0
  16. package/src/ui/ProjectFormUI.tsx +273 -0
  17. package/src/ui/ProjectMobileListUI.tsx +80 -0
  18. package/src/ui/ProjectToolbarUI.tsx +54 -0
  19. package/src/ui/RelationshipListUI.tsx +176 -0
  20. package/src/ui/ScheduleRunUI.tsx +173 -0
  21. package/src/ui/ScheduleSettingsUI.tsx +420 -0
  22. package/src/utils/coverage.helpers.ts +679 -0
  23. package/src/utils/coverage.ts +630 -0
  24. package/src/utils/cpm.helpers.ts +674 -0
  25. package/src/utils/cpm.ts +907 -0
  26. package/src/utils/cpmLeveling.helpers.ts +564 -0
  27. package/src/utils/cpmLeveling.ts +367 -0
  28. package/src/utils/defaults.ts +8 -0
  29. package/src/utils/eligibility.ts +457 -0
  30. package/src/utils/planCsv.ts +344 -0
  31. package/src/utils/predecessorText.ts +96 -0
  32. package/src/utils/recurrence.ts +616 -0
  33. package/src/utils/request.ts +153 -0
  34. package/src/utils/resource.ts +182 -0
  35. package/src/utils/rule.ts +216 -0
  36. package/src/utils/run.ts +43 -0
  37. package/src/utils/series.ts +161 -0
  38. package/src/utils/slot.ts +208 -0
  39. package/src/utils/workTime.ts +1382 -0
  40. package/tests/coverage.fixtures.ts +111 -0
  41. package/tests/coverage.test.ts +503 -0
  42. package/tests/cpm.bench.test.ts +154 -0
  43. package/tests/cpm.test.ts +354 -0
  44. package/tests/cpmCorrectness.test.ts +327 -0
  45. package/tests/cpmLeveling.test.ts +471 -0
  46. package/tests/eligibility.test.ts +320 -0
  47. package/tests/gantt-geometry.test.ts +367 -0
  48. package/tests/gantt-histogram.test.ts +78 -0
  49. package/tests/gantt-keyboard.test.ts +69 -0
  50. package/tests/helpers/cpmFixtures.ts +101 -0
  51. package/tests/projectInputs.test.ts +165 -0
  52. package/tests/recurrence.test.ts +68 -0
  53. package/tests/request.test.ts +99 -0
  54. package/tests/resource.test.ts +95 -0
  55. package/tests/rule.test.ts +98 -0
  56. package/tests/series.test.ts +120 -0
  57. package/tests/workTime.test.ts +1007 -0
  58. package/tests/workTimeContracts.test.ts +111 -0
  59. package/tsconfig.json +13 -0
  60. package/vitest.config.ts +8 -0
@@ -0,0 +1,679 @@
1
+ import i18n, { i18nTranslations } from '@jsb188/app/i18n/index.ts';
2
+ import { SCHEDULE_RULE_KIND_ENUMS } from '../constants/schedule.ts';
3
+ import type {
4
+ CoverageAssignmentInput,
5
+ CoverageDemandInput,
6
+ CoverageDiagnosticObj,
7
+ CoverageEvaluationInput,
8
+ CoverageOccurrenceInput,
9
+ CoverageResourceInput,
10
+ CoverageSlotInput,
11
+ CoverageTimeOffInput,
12
+ CoverageViolationObj,
13
+ ScheduleSlotPredicateObj,
14
+ } from '../types/schedule.d.ts';
15
+ import { getQualificationExpiryMs } from './resource.ts';
16
+ import { compareScheduleIds } from './rule.ts';
17
+ import { getSlotPredicateMissing } from './slot.ts';
18
+
19
+ export interface SweepInterval<T> {
20
+ startTime: number;
21
+ endTime: number;
22
+ value: T;
23
+ }
24
+ export interface CoverageOccurrence extends CoverageOccurrenceInput {
25
+ start: number;
26
+ end: number;
27
+ roomKnown: boolean;
28
+ }
29
+ export interface TimelineEntry {
30
+ occurrenceId: string;
31
+ start: number;
32
+ end: number;
33
+ own: boolean;
34
+ kind: 'SHIFT' | 'EVENT';
35
+ }
36
+ export interface CoverageContext {
37
+ from: number;
38
+ to: number;
39
+ input: CoverageEvaluationInput;
40
+ occurrences: CoverageOccurrence[];
41
+ resourcesById: Map<string, CoverageResourceInput>;
42
+ demand: CoverageDemandInput[];
43
+ timeOff: CoverageTimeOffInput[];
44
+ timeline: Map<string, TimelineEntry[]>;
45
+ operatingIntervals: Array<{ startAt: number; endAt: number }>;
46
+ diagnostics: CoverageDiagnosticObj[];
47
+ }
48
+ export interface AssigneeStanding {
49
+ personId: string;
50
+ occurrence: CoverageOccurrence;
51
+ assignment: CoverageAssignmentInput;
52
+ placedSlotKey: string | null;
53
+ slotUnknown: boolean;
54
+ predicateMissing: {
55
+ roles: string[];
56
+ tags: string[];
57
+ qualifications: string[];
58
+ };
59
+ expired: Array<{ key: string; expiresAt: string }>;
60
+ onTimeOff: string[];
61
+ overlapping: string[];
62
+ retired: boolean;
63
+ notLabor: boolean;
64
+ }
65
+ export interface SlotFill {
66
+ filled: Map<string, number>;
67
+ placed: Map<string, string[]>;
68
+ surplus: string[];
69
+ standings: AssigneeStanding[];
70
+ }
71
+ export interface SegmentState {
72
+ start: number;
73
+ end: number;
74
+ isOpen: boolean;
75
+ centerBlocked: boolean;
76
+ blockedRooms: Set<string>;
77
+ shifts: CoverageOccurrence[];
78
+ presenceByRoom: Map<string, Map<string, AssigneeStanding>>;
79
+ centerPresence: Map<string, AssigneeStanding>;
80
+ demandByRoom: Map<string, Map<string, number>>;
81
+ fills: Map<string, SlotFill>;
82
+ }
83
+
84
+ /* Convert supported date input to epoch milliseconds. */
85
+ export function coverageTime(value: Date | string): number {
86
+ return value instanceof Date ? value.getTime() : Date.parse(value);
87
+ }
88
+
89
+ /* Normalize references once, retaining room-less shifts and reporting malformed references. */
90
+ export function normalizeCoverageInput(
91
+ input: CoverageEvaluationInput,
92
+ ): CoverageContext {
93
+ const resourcesById = new Map(
94
+ [...input.resources]
95
+ .sort((a, b) => compareScheduleIds(a.id, b.id))
96
+ .map((resource) => [resource.id, resource]),
97
+ );
98
+ const diagnostics: CoverageDiagnosticObj[] = [];
99
+ const unknown = new Set<string>();
100
+ /* Report each missing resource once, independently of how many rows refer to it. */
101
+ const known = (id: string): boolean => {
102
+ if (resourcesById.has(id)) return true;
103
+ if (!unknown.has(id))
104
+ diagnostics.push({
105
+ code: 'UNKNOWN_RESOURCE',
106
+ ruleId: null,
107
+ resourceId: id,
108
+ occurrenceId: null,
109
+ demandId: null,
110
+ detail: {},
111
+ });
112
+ unknown.add(id);
113
+ return false;
114
+ };
115
+ const seen = new Set<string>();
116
+ const occurrences: CoverageOccurrence[] = [];
117
+ for (const raw of input.occurrences) {
118
+ if (seen.has(raw.id)) continue;
119
+ seen.add(raw.id);
120
+ const start = coverageTime(raw.startAt);
121
+ const end = coverageTime(raw.endAt);
122
+ if (!(end > start)) continue;
123
+ const roomKnown = raw.resourceId === null || known(raw.resourceId);
124
+ const assignments = new Map<string, CoverageAssignmentInput>();
125
+ for (const assignment of [...raw.assignments].sort((a, b) =>
126
+ compareScheduleIds(a.id ?? '', b.id ?? ''),
127
+ )) {
128
+ if (
129
+ !known(assignment.resourceId) ||
130
+ assignments.has(assignment.resourceId)
131
+ )
132
+ continue;
133
+ assignments.set(assignment.resourceId, assignment);
134
+ if (
135
+ assignment.slotKey !== null &&
136
+ !raw.slots.some((slot) => slot.key === assignment.slotKey)
137
+ )
138
+ diagnostics.push({
139
+ code: 'UNKNOWN_SLOT_KEY',
140
+ ruleId: null,
141
+ resourceId: assignment.resourceId,
142
+ occurrenceId: raw.id,
143
+ demandId: null,
144
+ detail: { slotKey: assignment.slotKey },
145
+ });
146
+ }
147
+ occurrences.push({
148
+ ...raw,
149
+ start,
150
+ end,
151
+ roomKnown,
152
+ assignments: [...assignments.values()].sort((a, b) =>
153
+ compareScheduleIds(a.resourceId, b.resourceId),
154
+ ),
155
+ slots: [...raw.slots].sort(
156
+ (a, b) => a.ordinal - b.ordinal || a.key.localeCompare(b.key),
157
+ ),
158
+ });
159
+ }
160
+ occurrences.sort((a, b) => compareScheduleIds(a.id, b.id));
161
+ const demand = input.demand
162
+ .filter(
163
+ (row) =>
164
+ known(row.resourceId) &&
165
+ coverageTime(row.endAt) > coverageTime(row.startAt),
166
+ )
167
+ .sort((a, b) => compareScheduleIds(a.id, b.id));
168
+ const timeOff = input.timeOff
169
+ .filter(
170
+ (row) =>
171
+ known(row.resourceId) &&
172
+ coverageTime(row.endAt) > coverageTime(row.startAt),
173
+ )
174
+ .sort((a, b) => compareScheduleIds(a.id, b.id));
175
+ const entries = new Map<string, Map<string, TimelineEntry>>();
176
+ for (const row of [...input.external].sort((a, b) =>
177
+ compareScheduleIds(a.occurrenceId, b.occurrenceId),
178
+ )) {
179
+ if (!known(row.resourceId)) continue;
180
+ const start = coverageTime(row.startAt);
181
+ const end = coverageTime(row.endAt);
182
+ if (!(end > start)) continue;
183
+ const list = entries.get(row.resourceId) ?? new Map();
184
+ if (!list.has(row.occurrenceId))
185
+ list.set(row.occurrenceId, {
186
+ occurrenceId: row.occurrenceId,
187
+ start,
188
+ end,
189
+ own: false,
190
+ kind: row.kind,
191
+ });
192
+ entries.set(row.resourceId, list);
193
+ }
194
+ for (const occurrence of occurrences) {
195
+ if (occurrence.kind === 'BLOCK') continue;
196
+ for (const assignment of occurrence.assignments) {
197
+ const list = entries.get(assignment.resourceId) ?? new Map();
198
+ list.set(occurrence.id, {
199
+ occurrenceId: occurrence.id,
200
+ start: occurrence.start,
201
+ end: occurrence.end,
202
+ own: true,
203
+ kind: occurrence.kind,
204
+ });
205
+ entries.set(assignment.resourceId, list);
206
+ }
207
+ }
208
+ for (const resource of resourcesById.values()) {
209
+ for (const qualification of resource.config.qualifications ?? []) {
210
+ if (
211
+ qualification.expiresAt != null &&
212
+ !Number.isFinite(Date.parse(qualification.expiresAt))
213
+ )
214
+ diagnostics.push({
215
+ code: 'QUALIFICATION_EXPIRY_INVALID',
216
+ ruleId: null,
217
+ resourceId: resource.id,
218
+ occurrenceId: null,
219
+ demandId: null,
220
+ detail: {
221
+ key: qualification.key,
222
+ expiresAt: qualification.expiresAt,
223
+ },
224
+ });
225
+ }
226
+ }
227
+ const timeline = new Map(
228
+ [...entries]
229
+ .sort(([a], [b]) => compareScheduleIds(a, b))
230
+ .map(([personId, rows]) => [
231
+ personId,
232
+ [...rows.values()].sort(
233
+ (a, b) =>
234
+ a.start - b.start ||
235
+ compareScheduleIds(a.occurrenceId, b.occurrenceId),
236
+ ),
237
+ ]),
238
+ );
239
+ return {
240
+ input,
241
+ from: coverageTime(input.window.from),
242
+ to: coverageTime(input.window.to),
243
+ resourcesById,
244
+ occurrences,
245
+ demand,
246
+ timeOff,
247
+ timeline,
248
+ operatingIntervals: [],
249
+ diagnostics,
250
+ };
251
+ }
252
+
253
+ /* Collect every instant at which a segment-local staffing fact can change. */
254
+ export function collectSegmentBoundaries(ctx: CoverageContext): number[] {
255
+ const boundaries = new Set([ctx.from, ctx.to]);
256
+ /* Retain only interior boundaries so all intervals are clipped to the requested window. */
257
+ const add = (time: number): void => {
258
+ if (time > ctx.from && time < ctx.to) boundaries.add(time);
259
+ };
260
+ for (const row of ctx.occurrences) {
261
+ add(row.start);
262
+ add(row.end);
263
+ }
264
+ for (const row of [...ctx.demand, ...ctx.timeOff]) {
265
+ add(coverageTime(row.startAt));
266
+ add(coverageTime(row.endAt));
267
+ }
268
+ for (const rows of ctx.timeline.values())
269
+ for (const row of rows) {
270
+ add(row.start);
271
+ add(row.end);
272
+ }
273
+ for (const person of ctx.resourcesById.values())
274
+ for (const qualification of person.config.qualifications ?? []) {
275
+ const expiry = getQualificationExpiryMs(qualification);
276
+ if (expiry !== null) add(expiry);
277
+ }
278
+ for (const interval of ctx.operatingIntervals) {
279
+ add(interval.startAt);
280
+ add(interval.endAt);
281
+ }
282
+ return [...boundaries].sort((a, b) => a - b);
283
+ }
284
+
285
+ /* Sort interval families once before admitting and evicting active sweep members. */
286
+ export function getSortedSweepIntervals<T>(
287
+ items: T[],
288
+ getInterval: (item: T) => { startAt: number; endAt: number },
289
+ ): SweepInterval<T>[] {
290
+ return items
291
+ .map((value) => {
292
+ const interval = getInterval(value);
293
+ return { startTime: interval.startAt, endTime: interval.endAt, value };
294
+ })
295
+ .filter((row) => row.endTime > row.startTime)
296
+ .sort((a, b) => a.startTime - b.startTime || a.endTime - b.endTime);
297
+ }
298
+
299
+ /* Advance one sorted family to the exact half-open membership at segmentStart. */
300
+ export function advanceSweepCursor<T>(
301
+ intervals: SweepInterval<T>[],
302
+ cursor: number,
303
+ segmentStart: number,
304
+ active: Set<SweepInterval<T>>,
305
+ ): number {
306
+ for (const interval of active)
307
+ if (interval.endTime <= segmentStart) active.delete(interval);
308
+ while (
309
+ cursor < intervals.length &&
310
+ intervals[cursor].startTime <= segmentStart
311
+ ) {
312
+ const interval = intervals[cursor++];
313
+ if (interval.endTime > segmentStart) active.add(interval);
314
+ }
315
+ return cursor;
316
+ }
317
+
318
+ /* Evaluate one person's validity for a predicate at an exact segment boundary. */
319
+ export function getAssigneeStanding(
320
+ person: CoverageResourceInput,
321
+ occurrence: CoverageOccurrence,
322
+ assignment: CoverageAssignmentInput,
323
+ predicate: ScheduleSlotPredicateObj | null,
324
+ start: number,
325
+ end: number,
326
+ ctx: CoverageContext,
327
+ activeTimeOff?: CoverageTimeOffInput[],
328
+ ): AssigneeStanding {
329
+ const required = new Set(predicate?.qualifications ?? []);
330
+ const expired = (person.config.qualifications ?? [])
331
+ .filter(
332
+ (q) =>
333
+ required.has(q.key) &&
334
+ getQualificationExpiryMs(q) !== null &&
335
+ getQualificationExpiryMs(q)! <= start,
336
+ )
337
+ .map((q) => ({ key: q.key, expiresAt: q.expiresAt! }))
338
+ .sort((a, b) => a.key.localeCompare(b.key));
339
+ const overlapping = (ctx.timeline.get(person.id) ?? [])
340
+ .filter(
341
+ (row) =>
342
+ row.occurrenceId !== occurrence.id &&
343
+ row.start < end &&
344
+ row.end > start &&
345
+ (!row.own ||
346
+ row.kind === 'EVENT' ||
347
+ compareScheduleIds(row.occurrenceId, occurrence.id) < 0),
348
+ )
349
+ .map((row) => row.occurrenceId)
350
+ .sort(compareScheduleIds);
351
+ return {
352
+ personId: person.id,
353
+ occurrence,
354
+ assignment,
355
+ placedSlotKey: assignment.slotKey,
356
+ slotUnknown:
357
+ assignment.slotKey !== null &&
358
+ !occurrence.slots.some((slot) => slot.key === assignment.slotKey),
359
+ predicateMissing: getSlotPredicateMissing(person.config, predicate),
360
+ expired,
361
+ onTimeOff: (activeTimeOff ?? ctx.timeOff)
362
+ .filter(
363
+ (row) =>
364
+ row.resourceId === person.id &&
365
+ coverageTime(row.startAt) < end &&
366
+ coverageTime(row.endAt) > start,
367
+ )
368
+ .map((row) => row.id)
369
+ .sort(compareScheduleIds),
370
+ overlapping,
371
+ retired:
372
+ person.retiredAt !== null &&
373
+ coverageTime(person.retiredAt) <= occurrence.end,
374
+ notLabor: person.kind !== 'LABOR',
375
+ };
376
+ }
377
+
378
+ /* Count only active LABOR whose required keys and qualifications are valid. */
379
+ export function isCountableStanding(standing: AssigneeStanding): boolean {
380
+ return (
381
+ !standing.notLabor &&
382
+ !standing.retired &&
383
+ !standing.expired.length &&
384
+ !standing.onTimeOff.length &&
385
+ !Object.values(standing.predicateMissing).some((list) => list.length)
386
+ );
387
+ }
388
+
389
+ /* Place pinned and then most-constrained unslotted people at most once each. */
390
+ export function fillOccurrenceSlots(
391
+ occurrence: CoverageOccurrence,
392
+ ctx: CoverageContext,
393
+ start = occurrence.start,
394
+ end = start + 1,
395
+ activeTimeOff?: CoverageTimeOffInput[],
396
+ ): SlotFill {
397
+ const filled = new Map(occurrence.slots.map((slot) => [slot.key, 0]));
398
+ const placed = new Map(
399
+ occurrence.slots.map((slot) => [slot.key, [] as string[]]),
400
+ );
401
+ const standings: AssigneeStanding[] = [];
402
+ const surplus: string[] = [];
403
+ const unslotted: Array<{
404
+ assignment: CoverageAssignmentInput;
405
+ bySlot: Map<string, AssigneeStanding>;
406
+ }> = [];
407
+ /* Build a predicate-specific standing without changing caller-owned assignments. */
408
+ const standingFor = (
409
+ assignment: CoverageAssignmentInput,
410
+ slot: CoverageSlotInput | null,
411
+ ): AssigneeStanding => {
412
+ const standing = getAssigneeStanding(
413
+ ctx.resourcesById.get(assignment.resourceId)!,
414
+ occurrence,
415
+ assignment,
416
+ slot?.predicate ?? null,
417
+ start,
418
+ end,
419
+ ctx,
420
+ activeTimeOff,
421
+ );
422
+ standing.placedSlotKey = slot?.key ?? null;
423
+ return standing;
424
+ };
425
+ for (const assignment of occurrence.assignments) {
426
+ if (!ctx.resourcesById.has(assignment.resourceId)) continue;
427
+ const slot = occurrence.slots.find(
428
+ (slot) => slot.key === assignment.slotKey,
429
+ );
430
+ if (!slot) {
431
+ unslotted.push({
432
+ assignment,
433
+ bySlot: new Map(
434
+ occurrence.slots.map((slot) => [
435
+ slot.key,
436
+ standingFor(assignment, slot),
437
+ ]),
438
+ ),
439
+ });
440
+ continue;
441
+ }
442
+ const standing = standingFor(assignment, slot);
443
+ standings.push(standing);
444
+ if (isCountableStanding(standing)) {
445
+ filled.set(slot.key, filled.get(slot.key)! + 1);
446
+ placed.get(slot.key)!.push(assignment.resourceId);
447
+ }
448
+ }
449
+ unslotted.sort(
450
+ (a, b) =>
451
+ [...a.bySlot.values()].filter(isCountableStanding).length -
452
+ [...b.bySlot.values()].filter(isCountableStanding).length ||
453
+ compareScheduleIds(a.assignment.resourceId, b.assignment.resourceId),
454
+ );
455
+ for (const item of unslotted) {
456
+ const slot = occurrence.slots.find(
457
+ (slot) =>
458
+ filled.get(slot.key)! < slot.requiredCount &&
459
+ isCountableStanding(item.bySlot.get(slot.key)!),
460
+ );
461
+ if (slot) {
462
+ filled.set(slot.key, filled.get(slot.key)! + 1);
463
+ placed.get(slot.key)!.push(item.assignment.resourceId);
464
+ standings.push(item.bySlot.get(slot.key)!);
465
+ } else {
466
+ // A person who holds the right keys but has an expired certificate still needs the expiry violation.
467
+ const attempted = occurrence.slots.find(
468
+ (slot) =>
469
+ filled.get(slot.key)! < slot.requiredCount &&
470
+ !Object.values(item.bySlot.get(slot.key)!.predicateMissing).some(
471
+ (list) => list.length,
472
+ ),
473
+ );
474
+ standings.push(
475
+ attempted
476
+ ? item.bySlot.get(attempted.key)!
477
+ : standingFor(item.assignment, null),
478
+ );
479
+ surplus.push(item.assignment.resourceId);
480
+ }
481
+ }
482
+ standings.sort((a, b) => compareScheduleIds(a.personId, b.personId));
483
+ return { filled, placed, surplus, standings };
484
+ }
485
+
486
+ /* Build room demand, distinct presence and per-shift slot fills for one constant segment. */
487
+ export function buildSegmentState(
488
+ start: number,
489
+ end: number,
490
+ activeOccurrences: Iterable<SweepInterval<CoverageOccurrence>>,
491
+ activeDemand: Iterable<SweepInterval<CoverageDemandInput>>,
492
+ activeTimeOff: Iterable<SweepInterval<CoverageTimeOffInput>>,
493
+ isOpen: boolean,
494
+ ctx: CoverageContext,
495
+ ): SegmentState {
496
+ const occurrences = [...activeOccurrences]
497
+ .map((row) => row.value)
498
+ .sort((a, b) => compareScheduleIds(a.id, b.id));
499
+ const timeOff = [...activeTimeOff].map((row) => row.value);
500
+ const state: SegmentState = {
501
+ start,
502
+ end,
503
+ isOpen,
504
+ centerBlocked: false,
505
+ blockedRooms: new Set(),
506
+ shifts: occurrences.filter((row) => row.kind === 'SHIFT'),
507
+ presenceByRoom: new Map(),
508
+ centerPresence: new Map(),
509
+ demandByRoom: new Map(),
510
+ fills: new Map(),
511
+ };
512
+ for (const occurrence of occurrences) {
513
+ if (occurrence.kind === 'BLOCK' && occurrence.roomKnown) {
514
+ if (occurrence.resourceId === null) state.centerBlocked = true;
515
+ else state.blockedRooms.add(occurrence.resourceId);
516
+ }
517
+ }
518
+ for (const shift of state.shifts) {
519
+ const fill = fillOccurrenceSlots(shift, ctx, start, end, timeOff);
520
+ state.fills.set(shift.id, fill);
521
+ for (const standing of fill.standings) {
522
+ if (
523
+ !state.centerPresence.has(standing.personId) &&
524
+ (shift.resourceId === null || shift.roomKnown)
525
+ )
526
+ state.centerPresence.set(standing.personId, standing);
527
+ if (
528
+ !shift.resourceId ||
529
+ !shift.roomKnown ||
530
+ ctx.resourcesById.get(shift.resourceId)?.kind !== 'SPACE'
531
+ )
532
+ continue;
533
+ const presence = state.presenceByRoom.get(shift.resourceId) ?? new Map();
534
+ if (!presence.has(standing.personId))
535
+ presence.set(standing.personId, standing);
536
+ state.presenceByRoom.set(shift.resourceId, presence);
537
+ }
538
+ }
539
+ for (const { value: demand } of activeDemand) {
540
+ if (ctx.resourcesById.get(demand.resourceId)?.kind !== 'SPACE') continue;
541
+ const quantities = state.demandByRoom.get(demand.resourceId) ?? new Map();
542
+ quantities.set(
543
+ demand.key,
544
+ (quantities.get(demand.key) ?? 0) + demand.quantity,
545
+ );
546
+ state.demandByRoom.set(demand.resourceId, quantities);
547
+ }
548
+ return state;
549
+ }
550
+
551
+ /* Serialize nested diagnostic details independently of object insertion order. */
552
+ export function stableStringify(value: unknown): string {
553
+ if (value === null || typeof value !== 'object')
554
+ return JSON.stringify(value) ?? 'null';
555
+ if (value instanceof Date) return JSON.stringify(value.toISOString());
556
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
557
+ return `{${Object.entries(value)
558
+ .sort(([a], [b]) => a.localeCompare(b))
559
+ .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`)
560
+ .join(',')}}`;
561
+ }
562
+
563
+ /* Identify one staffing problem without its changing degree or stretch start. */
564
+ export function getCoverageViolationIdentity(
565
+ violation: Pick<
566
+ CoverageViolationObj,
567
+ 'kind' | 'ruleId' | 'occurrenceId' | 'resourceId' | 'slotKey' | 'code'
568
+ >,
569
+ ): string {
570
+ return [
571
+ violation.kind,
572
+ violation.ruleId ?? '',
573
+ violation.occurrenceId ?? '',
574
+ violation.resourceId ?? '',
575
+ violation.slotKey ?? '',
576
+ violation.code ?? '',
577
+ ].join('|');
578
+ }
579
+
580
+ /* Derive the persisted natural key from identity and the clipped stretch start. */
581
+ export function getCoverageViolationKey(
582
+ violation: Pick<CoverageViolationObj, 'identity' | 'startAt'>,
583
+ ): string {
584
+ return `${violation.identity}|${violation.startAt.toISOString()}`;
585
+ }
586
+
587
+ /* Join adjacent stretches only when identity, detail, severity and degree agree. */
588
+ export function mergeAdjacentCoverageViolations(
589
+ raw: CoverageViolationObj[],
590
+ ): CoverageViolationObj[] {
591
+ const result: CoverageViolationObj[] = [];
592
+ const open = new Map<string, CoverageViolationObj>();
593
+ for (const violation of [...raw].sort(
594
+ (a, b) =>
595
+ a.startAt.getTime() - b.startAt.getTime() ||
596
+ a.identity.localeCompare(b.identity),
597
+ )) {
598
+ const mergeKey = `${violation.identity}|${violation.severity}|${violation.degree}|${stableStringify(violation.detail)}`;
599
+ const previous = open.get(mergeKey);
600
+ if (previous && previous.endAt.getTime() === violation.startAt.getTime())
601
+ previous.endAt = violation.endAt;
602
+ else {
603
+ const copy = { ...violation };
604
+ open.set(mergeKey, copy);
605
+ result.push(copy);
606
+ }
607
+ }
608
+ return result;
609
+ }
610
+
611
+ /* Clip violations and refresh their natural keys after clipping changes the start. */
612
+ export function clipCoverageViolationsToWindow(
613
+ violations: CoverageViolationObj[],
614
+ from: number,
615
+ to: number,
616
+ ): CoverageViolationObj[] {
617
+ return violations
618
+ .map((violation) => {
619
+ const clipped = {
620
+ ...violation,
621
+ startAt: new Date(Math.max(from, violation.startAt.getTime())),
622
+ endAt: new Date(Math.min(to, violation.endAt.getTime())),
623
+ };
624
+ clipped.key = getCoverageViolationKey(clipped);
625
+ return clipped;
626
+ })
627
+ .filter((violation) => violation.endAt > violation.startAt);
628
+ }
629
+
630
+ /* Apply stable presentation ordering independently of input row order. */
631
+ export function sortCoverageViolations(
632
+ violations: CoverageViolationObj[],
633
+ ): CoverageViolationObj[] {
634
+ return [...violations].sort(
635
+ (a, b) =>
636
+ a.startAt.getTime() - b.startAt.getTime() ||
637
+ SCHEDULE_RULE_KIND_ENUMS.indexOf(a.kind) -
638
+ SCHEDULE_RULE_KIND_ENUMS.indexOf(b.kind) ||
639
+ compareScheduleIds(a.resourceId ?? '', b.resourceId ?? '') ||
640
+ compareScheduleIds(a.occurrenceId ?? '', b.occurrenceId ?? '') ||
641
+ (a.slotKey ?? '').localeCompare(b.slotKey ?? '') ||
642
+ (a.code ?? '').localeCompare(b.code ?? ''),
643
+ );
644
+ }
645
+
646
+ /* Render a translated message at the caller boundary, keeping names out of engine identities. */
647
+ export function formatCoverageViolationMessage(
648
+ violation: CoverageViolationObj,
649
+ names: {
650
+ resource: (id: string) => string;
651
+ occurrence: (id: string) => string;
652
+ slotLabel: (occurrenceId: string, slotKey: string) => string;
653
+ timeZone: string;
654
+ },
655
+ ): string {
656
+ const suffix =
657
+ violation.kind === 'OPERATING_HOURS'
658
+ ? `_${String(violation.detail.scope).toLowerCase()}`
659
+ : violation.code
660
+ ? `_${violation.code.toLowerCase()}`
661
+ : '';
662
+ const key = `${violation.kind.toLowerCase()}${suffix}` as string;
663
+ return i18n.t(`schedule.violation.${key}`, {
664
+ _: i18nTranslations.schedule.en.violation[key],
665
+ ...violation.detail,
666
+ resource: violation.resourceId ? names.resource(violation.resourceId) : '',
667
+ occurrence: violation.occurrenceId
668
+ ? names.occurrence(violation.occurrenceId)
669
+ : '',
670
+ slot:
671
+ violation.occurrenceId && violation.slotKey
672
+ ? names.slotLabel(violation.occurrenceId, violation.slotKey)
673
+ : '',
674
+ startAt: violation.startAt.toLocaleString('en', {
675
+ timeZone: names.timeZone,
676
+ }),
677
+ endAt: violation.endAt.toLocaleString('en', { timeZone: names.timeZone }),
678
+ });
679
+ }