@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
@@ -1,302 +1,463 @@
1
- import i18n, { i18nTranslations } from '@jsb188/app/i18n/index.ts';
2
- import { SCHEDULE_RULE_KIND_ENUMS } from '../constants/schedule.ts';
1
+ import {
2
+ SCHEDULE_COVERAGE_DIAGNOSTIC_CODE_ENUMS,
3
+ SCHEDULE_COVERAGE_MAX_VIOLATIONS,
4
+ SCHEDULE_RULE_KIND_ENUMS,
5
+ } from '../constants/schedule.ts';
3
6
  import type {
4
- CoverageAssignmentInput,
5
- CoverageDemandInput,
7
+ CoverageAvailabilityInput,
6
8
  CoverageDiagnosticObj,
7
9
  CoverageEvaluationInput,
8
- CoverageOccurrenceInput,
9
10
  CoverageResourceInput,
10
- CoverageSlotInput,
11
+ CoverageRoleInput,
12
+ CoverageShiftInput,
11
13
  CoverageTimeOffInput,
12
14
  CoverageViolationObj,
13
- ScheduleSlotPredicateObj,
15
+ ScheduleEffectiveRule,
16
+ ScheduleStaffingRequirementConfigObj,
14
17
  } from '../types/schedule.d.ts';
18
+ import { compareScheduleIds } from './ids.ts';
19
+ import {
20
+ addScheduleDays,
21
+ getScheduleLocalDate,
22
+ getScheduleLocalInterval,
23
+ getScheduleWeekday,
24
+ listScheduleDates,
25
+ toScheduleTimeMs,
26
+ } from './localTime.ts';
15
27
  import { getQualificationExpiryMs } from './resource.ts';
16
- import { compareScheduleIds } from './rule.ts';
17
- import { getSlotPredicateMissing } from './slot.ts';
28
+ import {
29
+ getCoverageViolationIdentity,
30
+ getCoverageViolationKey,
31
+ stableStringify,
32
+ } from './violation.ts';
33
+
34
+ /**
35
+ * Private machinery of coverage.ts: input normalization, the sweep cursor,
36
+ * staffing-window expansion, the raw-finding collector and the post-merge
37
+ * pipeline (merge, clip, combine by key, sort). Nothing outside coverage.ts
38
+ * imports this file.
39
+ */
40
+
41
+ // One live seat with its instants read once
42
+ export interface CoverageSeat {
43
+ shift: CoverageShiftInput;
44
+ start: number;
45
+ end: number;
46
+ }
47
+
48
+ // One stretch in which an assigned seat counts its assignee as present
49
+ export interface CoveragePresence {
50
+ seat: CoverageSeat;
51
+ personId: string;
52
+ roomId: string | null; // the seat's location when it is a known SPACE
53
+ }
18
54
 
19
55
  export interface SweepInterval<T> {
20
56
  startTime: number;
21
57
  endTime: number;
22
58
  value: T;
23
59
  }
24
- export interface CoverageOccurrence extends CoverageOccurrenceInput {
25
- start: number;
26
- end: number;
27
- roomKnown: boolean;
60
+
61
+ // A finding before its identity and key are attached
62
+ export type CoverageFinding = Omit<CoverageViolationObj, 'key' | 'identity'>;
63
+
64
+ export interface CoverageRawCollector {
65
+ violations: CoverageViolationObj[];
66
+ capped: boolean;
28
67
  }
29
- export interface TimelineEntry {
30
- occurrenceId: string;
31
- start: number;
32
- end: number;
33
- own: boolean;
34
- kind: 'SHIFT' | 'EVENT';
68
+
69
+ export interface CoverageDiagnosticCollector {
70
+ byKey: Map<string, CoverageDiagnosticObj>;
35
71
  }
72
+
73
+ // The normalized snapshot every evaluator reads
36
74
  export interface CoverageContext {
75
+ input: CoverageEvaluationInput;
37
76
  from: number;
38
77
  to: number;
39
- input: CoverageEvaluationInput;
40
- occurrences: CoverageOccurrence[];
41
78
  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[];
79
+ rolesById: Map<string, CoverageRoleInput>;
80
+ ownSeats: CoverageSeat[]; // live seats of input.calendarId from `shifts`, by id
81
+ externalSeats: CoverageSeat[]; // live assigned seats from `external` not in ownSeats, by id
82
+ seatsByPerson: Map<string, CoverageSeat[]>; // own + external, by start then id
83
+ timeOffByPerson: Map<string, CoverageTimeOffInput[]>;
84
+ availabilityByPerson: Map<string, CoverageAvailabilityInput[]>;
85
+ diagnostics: CoverageDiagnosticCollector;
47
86
  }
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>;
87
+
88
+ /*
89
+ * Create an empty diagnostic collector (deduplicated by content).
90
+ */
91
+ export function createCoverageDiagnostics(): CoverageDiagnosticCollector {
92
+ return { byKey: new Map() };
82
93
  }
83
94
 
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);
95
+ /*
96
+ * Add a diagnostic once: two diagnostics with the same content are one.
97
+ */
98
+ export function addCoverageDiagnostic(
99
+ collector: CoverageDiagnosticCollector,
100
+ diagnostic: CoverageDiagnosticObj,
101
+ ): void {
102
+ const key = stableStringify(diagnostic);
103
+ if (!collector.byKey.has(key)) collector.byKey.set(key, diagnostic);
87
104
  }
88
105
 
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]),
106
+ /*
107
+ * Return the collected diagnostics ordered by code (enum order), rule,
108
+ * resource, seat and detail.
109
+ */
110
+ export function getSortedCoverageDiagnostics(
111
+ collector: CoverageDiagnosticCollector,
112
+ ): CoverageDiagnosticObj[] {
113
+ return [...collector.byKey.values()].sort(
114
+ (a, b) =>
115
+ SCHEDULE_COVERAGE_DIAGNOSTIC_CODE_ENUMS.indexOf(a.code) -
116
+ SCHEDULE_COVERAGE_DIAGNOSTIC_CODE_ENUMS.indexOf(b.code) ||
117
+ compareScheduleIds(a.ruleId ?? '', b.ruleId ?? '') ||
118
+ compareScheduleIds(a.resourceId ?? '', b.resourceId ?? '') ||
119
+ compareScheduleIds(a.shiftId ?? '', b.shiftId ?? '') ||
120
+ compareCodeUnits(stableStringify(a.detail), stableStringify(b.detail)),
97
121
  );
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',
122
+ }
123
+
124
+ /*
125
+ * Compare two strings by code unit (locale-independent).
126
+ */
127
+ export function compareCodeUnits(a: string, b: string): number {
128
+ return a < b ? -1 : a > b ? 1 : 0;
129
+ }
130
+
131
+ /*
132
+ * Round a child count to two decimals, the precision demand is stored at, so
133
+ * summed fractional quantities compare exactly.
134
+ */
135
+ export function roundCoverageQuantity(value: number): number {
136
+ return Math.round(value * 100) / 100;
137
+ }
138
+
139
+ /*
140
+ * Index resources and roles by id (the first row of a duplicated id wins, in
141
+ * id order, so the result does not depend on input order).
142
+ */
143
+ export function indexCoverageCatalogs(input: CoverageEvaluationInput): {
144
+ resourcesById: Map<string, CoverageResourceInput>;
145
+ rolesById: Map<string, CoverageRoleInput>;
146
+ } {
147
+ const resourcesById = new Map<string, CoverageResourceInput>();
148
+ for (const resource of [...input.resources].sort((a, b) =>
149
+ compareScheduleIds(a.id, b.id),
150
+ ))
151
+ if (!resourcesById.has(resource.id))
152
+ resourcesById.set(resource.id, resource);
153
+
154
+ const rolesById = new Map<string, CoverageRoleInput>();
155
+ for (const role of [...input.roles].sort((a, b) =>
156
+ compareScheduleIds(a.id, b.id),
157
+ ))
158
+ if (!rolesById.has(role.id)) rolesById.set(role.id, role);
159
+
160
+ return { resourcesById, rolesById };
161
+ }
162
+
163
+ /*
164
+ * Check that a referenced resource exists, reporting UNKNOWN_RESOURCE (once
165
+ * per id) when it does not.
166
+ */
167
+ function isKnownCoverageResource(
168
+ resourceId: string,
169
+ resourcesById: ReadonlyMap<string, CoverageResourceInput>,
170
+ diagnostics: CoverageDiagnosticCollector,
171
+ ): boolean {
172
+ if (resourcesById.has(resourceId)) return true;
173
+ addCoverageDiagnostic(diagnostics, {
174
+ code: 'UNKNOWN_RESOURCE',
175
+ ruleId: null,
176
+ resourceId,
177
+ shiftId: null,
178
+ detail: {},
179
+ });
180
+ return false;
181
+ }
182
+
183
+ /*
184
+ * Read a seat's instants; null when either is unreadable or the seat is
185
+ * empty (such a row can never be present).
186
+ */
187
+ function toCoverageSeat(shift: CoverageShiftInput): CoverageSeat | null {
188
+ const start = toScheduleTimeMs(shift.startAt);
189
+ const end = toScheduleTimeMs(shift.endAt);
190
+ return end > start ? { shift, start, end } : null;
191
+ }
192
+
193
+ /*
194
+ * Normalize the seat lists: `shifts` rows of the evaluated calendar that are
195
+ * not CANCELED become own seats; `external` rows that are live, assigned and
196
+ * not already own become external seats. Unknown locations and assignees,
197
+ * and unknown roles on own seats, are reported (the seat is kept: an unknown
198
+ * assignee never counts, an unknown role only skips qualification checks).
199
+ */
200
+ export function normalizeCoverageSeats(
201
+ input: CoverageEvaluationInput,
202
+ resourcesById: ReadonlyMap<string, CoverageResourceInput>,
203
+ rolesById: ReadonlyMap<string, CoverageRoleInput>,
204
+ diagnostics: CoverageDiagnosticCollector,
205
+ ): { ownSeats: CoverageSeat[]; externalSeats: CoverageSeat[] } {
206
+ const ownSeats: CoverageSeat[] = [];
207
+ const seen = new Set<string>();
208
+ for (const shift of [...input.shifts].sort((a, b) =>
209
+ compareScheduleIds(a.id, b.id),
210
+ )) {
211
+ if (
212
+ shift.calendarId !== input.calendarId ||
213
+ shift.status === 'CANCELED' ||
214
+ seen.has(shift.id)
215
+ )
216
+ continue;
217
+ const seat = toCoverageSeat(shift);
218
+ if (!seat) continue;
219
+ seen.add(shift.id);
220
+ ownSeats.push(seat);
221
+ if (shift.locationResourceId !== null)
222
+ isKnownCoverageResource(
223
+ shift.locationResourceId,
224
+ resourcesById,
225
+ diagnostics,
226
+ );
227
+ if (shift.assigneeResourceId !== null)
228
+ isKnownCoverageResource(
229
+ shift.assigneeResourceId,
230
+ resourcesById,
231
+ diagnostics,
232
+ );
233
+ if (shift.roleId !== null && !rolesById.has(shift.roleId))
234
+ addCoverageDiagnostic(diagnostics, {
235
+ code: 'UNKNOWN_ROLE',
106
236
  ruleId: null,
107
- resourceId: id,
108
- occurrenceId: null,
109
- demandId: null,
110
- detail: {},
237
+ resourceId: null,
238
+ shiftId: null,
239
+ detail: { roleId: shift.roleId },
111
240
  });
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
241
  }
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),
242
+
243
+ const externalSeats: CoverageSeat[] = [];
244
+ for (const shift of [...input.external].sort((a, b) =>
245
+ compareScheduleIds(a.id, b.id),
246
+ )) {
247
+ if (
248
+ shift.status === 'CANCELED' ||
249
+ shift.assigneeResourceId === null ||
250
+ seen.has(shift.id)
166
251
  )
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),
252
+ continue;
253
+ const seat = toCoverageSeat(shift);
254
+ if (!seat) continue;
255
+ seen.add(shift.id);
256
+ if (
257
+ isKnownCoverageResource(
258
+ shift.assigneeResourceId,
259
+ resourcesById,
260
+ diagnostics,
261
+ )
173
262
  )
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);
263
+ externalSeats.push(seat);
193
264
  }
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
- }
265
+
266
+ return { ownSeats, externalSeats };
267
+ }
268
+
269
+ /*
270
+ * Group assigned seats (own and external) by assignee, each list ordered by
271
+ * start then id. Seats of unknown people are left out.
272
+ */
273
+ export function groupCoverageSeatsByPerson(
274
+ seats: CoverageSeat[],
275
+ resourcesById: ReadonlyMap<string, CoverageResourceInput>,
276
+ ): Map<string, CoverageSeat[]> {
277
+ const byPerson = new Map<string, CoverageSeat[]>();
278
+ for (const seat of seats) {
279
+ const personId = seat.shift.assigneeResourceId;
280
+ if (personId === null || !resourcesById.has(personId)) continue;
281
+ const list = byPerson.get(personId) ?? [];
282
+ list.push(seat);
283
+ byPerson.set(personId, list);
207
284
  }
208
- for (const resource of resourcesById.values()) {
209
- for (const qualification of resource.config.qualifications ?? []) {
285
+ for (const list of byPerson.values())
286
+ list.sort(
287
+ (a, b) => a.start - b.start || compareScheduleIds(a.shift.id, b.shift.id),
288
+ );
289
+ return byPerson;
290
+ }
291
+
292
+ /*
293
+ * Group per-person rows (time off, availability) by resourceId in id order,
294
+ * reporting and dropping rows of unknown people.
295
+ */
296
+ export function groupCoverageRowsByPerson<
297
+ T extends { id: string; resourceId: string },
298
+ >(
299
+ rows: T[],
300
+ resourcesById: ReadonlyMap<string, CoverageResourceInput>,
301
+ diagnostics: CoverageDiagnosticCollector,
302
+ ): Map<string, T[]> {
303
+ const byPerson = new Map<string, T[]>();
304
+ for (const row of [...rows].sort((a, b) => compareScheduleIds(a.id, b.id))) {
305
+ if (!isKnownCoverageResource(row.resourceId, resourcesById, diagnostics))
306
+ continue;
307
+ const list = byPerson.get(row.resourceId) ?? [];
308
+ list.push(row);
309
+ byPerson.set(row.resourceId, list);
310
+ }
311
+ return byPerson;
312
+ }
313
+
314
+ /*
315
+ * Keep the demand rows whose room is known, reporting the others.
316
+ */
317
+ export function filterKnownDemandRows<T extends { resourceId: string }>(
318
+ rows: T[],
319
+ resourcesById: ReadonlyMap<string, CoverageResourceInput>,
320
+ diagnostics: CoverageDiagnosticCollector,
321
+ ): T[] {
322
+ return rows.filter((row) =>
323
+ isKnownCoverageResource(row.resourceId, resourcesById, diagnostics),
324
+ );
325
+ }
326
+
327
+ /*
328
+ * Report every qualification whose expiresAt cannot be read (the engine
329
+ * treats it as expired, never as "never expires").
330
+ */
331
+ export function collectQualificationExpiryDiagnostics(
332
+ resourcesById: ReadonlyMap<string, CoverageResourceInput>,
333
+ diagnostics: CoverageDiagnosticCollector,
334
+ ): void {
335
+ for (const resource of resourcesById.values())
336
+ for (const qualification of resource.config?.qualifications ?? [])
210
337
  if (
211
338
  qualification.expiresAt != null &&
212
339
  !Number.isFinite(Date.parse(qualification.expiresAt))
213
340
  )
214
- diagnostics.push({
341
+ addCoverageDiagnostic(diagnostics, {
215
342
  code: 'QUALIFICATION_EXPIRY_INVALID',
216
343
  ruleId: null,
217
344
  resourceId: resource.id,
218
- occurrenceId: null,
219
- demandId: null,
220
- detail: {
221
- key: qualification.key,
222
- expiresAt: qualification.expiresAt,
223
- },
345
+ shiftId: null,
346
+ detail: { key: qualification.key },
224
347
  });
225
- }
348
+ }
349
+
350
+ /*
351
+ * Index each resource's qualification expiries by key (null = never
352
+ * expires; an unreadable expiry reads as already expired).
353
+ */
354
+ export function indexQualificationExpiries(
355
+ resourcesById: ReadonlyMap<string, CoverageResourceInput>,
356
+ ): Map<string, Map<string, number | null>> {
357
+ const byResource = new Map<string, Map<string, number | null>>();
358
+ for (const resource of resourcesById.values()) {
359
+ const expiries = new Map<string, number | null>();
360
+ for (const qualification of resource.config?.qualifications ?? [])
361
+ expiries.set(qualification.key, getQualificationExpiryMs(qualification));
362
+ byResource.set(resource.id, expiries);
226
363
  }
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
- ]),
364
+ return byResource;
365
+ }
366
+
367
+ /*
368
+ * List the local dates a window can draw local intervals from: the day
369
+ * before the window's first local date (cross-midnight spills) through the
370
+ * local date of its end.
371
+ */
372
+ export function getCoverageLocalDates(
373
+ from: number,
374
+ to: number,
375
+ timeZone: string,
376
+ ): { fromDate: string; toDate: string; dates: string[] } {
377
+ const fromDate = addScheduleDays(
378
+ getScheduleLocalDate(new Date(from), timeZone),
379
+ -1,
238
380
  );
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
- };
381
+ const toDate = getScheduleLocalDate(new Date(to), timeZone);
382
+ return { fromDate, toDate, dates: listScheduleDates(fromDate, toDate) };
251
383
  }
252
384
 
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);
385
+ /*
386
+ * Place every weekly window of every effective STAFFING_REQUIREMENT rule on
387
+ * the local dates whose weekday matches, clipped to the window (unsorted).
388
+ * The value is the rule's position in `rules`.
389
+ */
390
+ export function expandStaffingWindows(
391
+ rules: ScheduleEffectiveRule[],
392
+ dates: string[],
393
+ timeZone: string,
394
+ from: number,
395
+ to: number,
396
+ ): SweepInterval<number>[] {
397
+ const intervals: SweepInterval<number>[] = [];
398
+ rules.forEach((rule, ruleIndex) => {
399
+ const { windows } = rule.config as ScheduleStaffingRequirementConfigObj;
400
+ for (const date of dates) {
401
+ const weekday = getScheduleWeekday(date);
402
+ for (const window of windows) {
403
+ if (window.weekday !== weekday) continue;
404
+ const placed = getScheduleLocalInterval(
405
+ date,
406
+ window.start,
407
+ window.end,
408
+ timeZone,
409
+ );
410
+ if (!placed) continue;
411
+ const startTime = Math.max(from, placed.startAt.getTime());
412
+ const endTime = Math.min(to, placed.endAt.getTime());
413
+ if (endTime > startTime)
414
+ intervals.push({ startTime, endTime, value: ruleIndex });
415
+ }
277
416
  }
278
- for (const interval of ctx.operatingIntervals) {
279
- add(interval.startAt);
280
- add(interval.endAt);
417
+ });
418
+ return intervals;
419
+ }
420
+
421
+ /*
422
+ * Return the parts of [start, end) not covered by any blocked interval.
423
+ */
424
+ export function subtractCoverageIntervals(
425
+ start: number,
426
+ end: number,
427
+ blocked: Array<{ start: number; end: number }>,
428
+ ): Array<{ start: number; end: number }> {
429
+ const parts: Array<{ start: number; end: number }> = [];
430
+ let cursor = start;
431
+ for (const interval of [...blocked].sort(
432
+ (a, b) => a.start - b.start || a.end - b.end,
433
+ )) {
434
+ if (interval.end <= cursor) continue;
435
+ if (interval.start >= end) break;
436
+ if (interval.start > cursor)
437
+ parts.push({ start: cursor, end: interval.start });
438
+ cursor = Math.max(cursor, interval.end);
439
+ if (cursor >= end) break;
281
440
  }
282
- return [...boundaries].sort((a, b) => a - b);
441
+ if (cursor < end) parts.push({ start: cursor, end });
442
+ return parts;
283
443
  }
284
444
 
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 },
445
+ /*
446
+ * Sort one interval family once (by start, then end) so the sweep can admit
447
+ * and evict members with a cursor. Empty intervals are dropped.
448
+ */
449
+ export function sortSweepIntervals<T>(
450
+ intervals: SweepInterval<T>[],
289
451
  ): SweepInterval<T>[] {
290
- return items
291
- .map((value) => {
292
- const interval = getInterval(value);
293
- return { startTime: interval.startAt, endTime: interval.endAt, value };
294
- })
452
+ return intervals
295
453
  .filter((row) => row.endTime > row.startTime)
296
454
  .sort((a, b) => a.startTime - b.startTime || a.endTime - b.endTime);
297
455
  }
298
456
 
299
- /* Advance one sorted family to the exact half-open membership at segmentStart. */
457
+ /*
458
+ * Advance one sorted family to its exact half-open membership at a segment
459
+ * start: evict members that ended, admit members that started.
460
+ */
300
461
  export function advanceSweepCursor<T>(
301
462
  intervals: SweepInterval<T>[],
302
463
  cursor: number,
@@ -305,286 +466,70 @@ export function advanceSweepCursor<T>(
305
466
  ): number {
306
467
  for (const interval of active)
307
468
  if (interval.endTime <= segmentStart) active.delete(interval);
308
- while (
309
- cursor < intervals.length &&
310
- intervals[cursor].startTime <= segmentStart
311
- ) {
312
- const interval = intervals[cursor++];
469
+ let next = cursor;
470
+ while (next < intervals.length && intervals[next].startTime <= segmentStart) {
471
+ const interval = intervals[next++];
313
472
  if (interval.endTime > segmentStart) active.add(interval);
314
473
  }
315
- return cursor;
474
+ return next;
316
475
  }
317
476
 
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',
477
+ /*
478
+ * Collect the sweep boundaries: the window edges plus every interval edge
479
+ * and extra instant strictly inside the window, ascending.
480
+ */
481
+ export function collectSweepBoundaries(
482
+ from: number,
483
+ to: number,
484
+ families: Array<Array<SweepInterval<unknown>>>,
485
+ instants: Iterable<number>,
486
+ ): number[] {
487
+ const boundaries = new Set([from, to]);
488
+ /* Keep only interior instants: every stretch is clipped to the window. */
489
+ const add = (time: number): void => {
490
+ if (time > from && time < to) boundaries.add(time);
375
491
  };
492
+ for (const family of families)
493
+ for (const interval of family) {
494
+ add(interval.startTime);
495
+ add(interval.endTime);
496
+ }
497
+ for (const instant of instants) add(instant);
498
+ return [...boundaries].sort((a, b) => a - b);
376
499
  }
377
500
 
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
- );
501
+ /*
502
+ * Create an empty raw-finding collector.
503
+ */
504
+ export function createCoverageRawCollector(): CoverageRawCollector {
505
+ return { violations: [], capped: false };
387
506
  }
388
507
 
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
- }
508
+ /*
509
+ * Add one raw finding (identity attached, key filled after clipping). Empty
510
+ * stretches are ignored; past SCHEDULE_COVERAGE_MAX_VIOLATIONS the
511
+ * collector is marked capped and drops the finding.
512
+ */
513
+ export function pushCoverageViolation(
514
+ collector: CoverageRawCollector,
515
+ finding: CoverageFinding,
516
+ ): void {
517
+ if (!(finding.endAt.getTime() > finding.startAt.getTime())) return;
518
+ if (collector.violations.length >= SCHEDULE_COVERAGE_MAX_VIOLATIONS) {
519
+ collector.capped = true;
520
+ return;
481
521
  }
482
- standings.sort((a, b) => compareScheduleIds(a.personId, b.personId));
483
- return { filled, placed, surplus, standings };
522
+ collector.violations.push({
523
+ ...finding,
524
+ identity: getCoverageViolationIdentity(finding),
525
+ key: '',
526
+ });
484
527
  }
485
528
 
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. */
529
+ /*
530
+ * Join adjacent stretches only when identity, severity, degree and detail
531
+ * all agree (a change of degree starts a new stretch).
532
+ */
588
533
  export function mergeAdjacentCoverageViolations(
589
534
  raw: CoverageViolationObj[],
590
535
  ): CoverageViolationObj[] {
@@ -593,7 +538,7 @@ export function mergeAdjacentCoverageViolations(
593
538
  for (const violation of [...raw].sort(
594
539
  (a, b) =>
595
540
  a.startAt.getTime() - b.startAt.getTime() ||
596
- a.identity.localeCompare(b.identity),
541
+ compareCodeUnits(a.identity, b.identity),
597
542
  )) {
598
543
  const mergeKey = `${violation.identity}|${violation.severity}|${violation.degree}|${stableStringify(violation.detail)}`;
599
544
  const previous = open.get(mergeKey);
@@ -608,7 +553,10 @@ export function mergeAdjacentCoverageViolations(
608
553
  return result;
609
554
  }
610
555
 
611
- /* Clip violations and refresh their natural keys after clipping changes the start. */
556
+ /*
557
+ * Clip violations to the window and refresh their keys (clipping can move
558
+ * the start); stretches left empty are dropped.
559
+ */
612
560
  export function clipCoverageViolationsToWindow(
613
561
  violations: CoverageViolationObj[],
614
562
  from: number,
@@ -627,7 +575,48 @@ export function clipCoverageViolationsToWindow(
627
575
  .filter((violation) => violation.endAt > violation.startAt);
628
576
  }
629
577
 
630
- /* Apply stable presentation ordering independently of input row order. */
578
+ /*
579
+ * Make keys unique: violations that share a key (same identity and start)
580
+ * become one, keeping the highest degree (ties: the smallest detail), the
581
+ * latest end, and BLOCK when any of them blocks.
582
+ */
583
+ export function combineCoverageViolationsByKey(
584
+ violations: CoverageViolationObj[],
585
+ ): CoverageViolationObj[] {
586
+ const byKey = new Map<string, CoverageViolationObj>();
587
+ for (const violation of violations) {
588
+ const kept = byKey.get(violation.key);
589
+ if (!kept) {
590
+ byKey.set(violation.key, violation);
591
+ continue;
592
+ }
593
+ const winner =
594
+ violation.degree > kept.degree ||
595
+ (violation.degree === kept.degree &&
596
+ compareCodeUnits(
597
+ stableStringify(violation.detail),
598
+ stableStringify(kept.detail),
599
+ ) < 0)
600
+ ? violation
601
+ : kept;
602
+ byKey.set(violation.key, {
603
+ ...winner,
604
+ endAt: new Date(
605
+ Math.max(kept.endAt.getTime(), violation.endAt.getTime()),
606
+ ),
607
+ severity:
608
+ kept.severity === 'BLOCK' || violation.severity === 'BLOCK'
609
+ ? 'BLOCK'
610
+ : winner.severity,
611
+ });
612
+ }
613
+ return [...byKey.values()];
614
+ }
615
+
616
+ /*
617
+ * Order violations for presentation and storage: start, kind (enum order),
618
+ * subject, seat, code, then rule and key, independently of input order.
619
+ */
631
620
  export function sortCoverageViolations(
632
621
  violations: CoverageViolationObj[],
633
622
  ): CoverageViolationObj[] {
@@ -637,43 +626,9 @@ export function sortCoverageViolations(
637
626
  SCHEDULE_RULE_KIND_ENUMS.indexOf(a.kind) -
638
627
  SCHEDULE_RULE_KIND_ENUMS.indexOf(b.kind) ||
639
628
  compareScheduleIds(a.resourceId ?? '', b.resourceId ?? '') ||
640
- compareScheduleIds(a.occurrenceId ?? '', b.occurrenceId ?? '') ||
641
- (a.slotKey ?? '').localeCompare(b.slotKey ?? '') ||
642
- (a.code ?? '').localeCompare(b.code ?? ''),
629
+ compareScheduleIds(a.shiftId ?? '', b.shiftId ?? '') ||
630
+ compareCodeUnits(a.code ?? '', b.code ?? '') ||
631
+ compareScheduleIds(a.ruleId ?? '', b.ruleId ?? '') ||
632
+ compareCodeUnits(a.key, b.key),
643
633
  );
644
634
  }
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
- }