@jsb188/schedule 1.1.12 → 1.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +33 -14
  3. package/src/constants/schedule.ts +710 -306
  4. package/src/types/schedule.d.ts +1827 -456
  5. package/src/ui/ScheduleSettingsUI.tsx +21 -23
  6. package/src/utils/autofill.ts +469 -0
  7. package/src/utils/availability.ts +167 -0
  8. package/src/utils/candidates.ts +447 -0
  9. package/src/utils/coverage.helpers.ts +509 -554
  10. package/src/utils/coverage.ts +1121 -526
  11. package/src/utils/cpm.helpers.ts +27 -29
  12. package/src/utils/cpm.ts +53 -41
  13. package/src/utils/cpmLeveling.helpers.ts +89 -16
  14. package/src/utils/cpmLeveling.ts +28 -26
  15. package/src/utils/cycle.ts +325 -0
  16. package/src/utils/demand.ts +239 -0
  17. package/src/utils/eligibility.ts +553 -400
  18. package/src/utils/ids.ts +47 -0
  19. package/src/utils/laborRules.ts +740 -0
  20. package/src/utils/localTime.ts +312 -0
  21. package/src/utils/offer.ts +300 -0
  22. package/src/utils/planCsv.ts +73 -19
  23. package/src/utils/predicate.ts +111 -0
  24. package/src/utils/request.ts +212 -114
  25. package/src/utils/resource.ts +412 -112
  26. package/src/utils/rule.ts +697 -163
  27. package/src/utils/rulePresets.ts +116 -0
  28. package/src/utils/run.ts +0 -8
  29. package/src/utils/scheduleText.ts +4074 -0
  30. package/src/utils/shiftChange.ts +279 -0
  31. package/src/utils/standing.ts +730 -0
  32. package/src/utils/template.ts +619 -0
  33. package/src/utils/violation.ts +184 -0
  34. package/src/utils/workTime.ts +341 -120
  35. package/src/utils/defaults.ts +0 -8
  36. package/src/utils/recurrence.ts +0 -616
  37. package/src/utils/series.ts +0 -161
  38. package/src/utils/slot.ts +0 -208
  39. package/tests/coverage.fixtures.ts +0 -111
  40. package/tests/coverage.test.ts +0 -503
  41. package/tests/cpm.bench.test.ts +0 -154
  42. package/tests/cpm.test.ts +0 -354
  43. package/tests/cpmCorrectness.test.ts +0 -327
  44. package/tests/cpmLeveling.test.ts +0 -471
  45. package/tests/eligibility.test.ts +0 -320
  46. package/tests/gantt-geometry.test.ts +0 -367
  47. package/tests/gantt-histogram.test.ts +0 -78
  48. package/tests/gantt-keyboard.test.ts +0 -69
  49. package/tests/helpers/cpmFixtures.ts +0 -101
  50. package/tests/projectInputs.test.ts +0 -165
  51. package/tests/recurrence.test.ts +0 -68
  52. package/tests/request.test.ts +0 -99
  53. package/tests/resource.test.ts +0 -95
  54. package/tests/rule.test.ts +0 -98
  55. package/tests/series.test.ts +0 -120
  56. package/tests/workTime.test.ts +0 -1007
  57. package/tests/workTimeContracts.test.ts +0 -111
  58. package/tsconfig.json +0 -13
  59. package/vitest.config.ts +0 -8
@@ -1,457 +1,610 @@
1
- import { SCHEDULE_ELIGIBILITY_REASON_ENUMS } from '../constants/schedule.ts';
1
+ import {
2
+ SCHEDULE_ELIGIBILITY_REASON_ENUMS,
3
+ SCHEDULE_PERSON_RULE_KINDS,
4
+ } from '../constants/schedule.ts';
2
5
  import type {
3
- CoverageAssignmentInput,
4
- CoverageDemandInput,
5
- CoverageEvaluationInput,
6
- CoverageExternalAssignmentInput,
7
- CoverageOccurrenceInput,
8
6
  CoverageResourceInput,
9
- CoverageRuleInput,
10
- CoverageTimeOffInput,
7
+ CoverageShiftInput,
11
8
  CoverageViolationObj,
9
+ ScheduleEffectiveRule,
10
+ ScheduleEffectiveRuleIndex,
11
+ ScheduleEligibilityConfigObj,
12
+ ScheduleEligibilityContext,
12
13
  ScheduleEligibilityReasonEnum,
14
+ ScheduleEligibilityReasonObj,
15
+ ScheduleEligibilityResult,
13
16
  ScheduleRuleSeverityEnum,
14
- ScheduleWorkCalendarDef,
17
+ ScheduleShiftFindingsInput,
18
+ ScheduleSwapEligibilityResult,
15
19
  } from '../types/schedule.d.ts';
16
- import { evaluateScheduleCoverage } from './coverage.ts';
20
+ import { expandScheduleAvailability } from './availability.ts';
21
+ import { evaluatePersonRules } from './laborRules.ts';
22
+ import { getScheduleLocalDate, toScheduleTimeMs } from './localTime.ts';
23
+ import { getQualificationExpiryMs } from './resource.ts';
17
24
  import {
18
- coverageTime,
19
- fillOccurrenceSlots,
20
- normalizeCoverageInput,
21
- stableStringify,
22
- } from './coverage.helpers.ts';
23
- import { getMaxActorWindowDays } from './rule.ts';
24
- import { getSlotPredicateMissing } from './slot.ts';
25
+ getEffectiveScheduleRules,
26
+ resolveEffectiveScheduleRules,
27
+ } from './rule.ts';
28
+ import { diffCoverageViolations, stableStringify } from './violation.ts';
25
29
 
26
- export interface EligibilityReason {
27
- code: ScheduleEligibilityReasonEnum;
28
- severity: ScheduleRuleSeverityEnum;
29
- ruleId: string | null;
30
- detail: Record<string, unknown>;
31
- startAt: Date | null;
32
- endAt: Date | null;
33
- }
34
- export interface ShiftEligibilityContext {
35
- calendarId: string;
36
- now: Date;
37
- resources: CoverageResourceInput[];
38
- assignmentsOfResource: CoverageExternalAssignmentInput[];
39
- timeOff: CoverageTimeOffInput[];
40
- rules: CoverageRuleInput[];
41
- requireOpenSlot?: boolean;
42
- // A swap exchanges the exact outgoing seat, including an explicit surplus seat.
43
- preserveUnslotted?: boolean;
30
+ /**
31
+ * Eligibility: one person x one seat (IMPLEMENTATION §1.4).
32
+ *
33
+ * - Hard checks, always BLOCK whatever the ELIGIBILITY rule's severity: a
34
+ * PERSON, not retired, a current member; holds the seat's role; holds every
35
+ * required qualification of that role, unexpired at seat start; no approved
36
+ * time off and no other live seat overlapping.
37
+ * - Soft: an UNAVAILABLE availability window overlapping the seat, at the
38
+ * ELIGIBILITY rule's config.unavailable severity (default WARN).
39
+ * - Person rules (MAX_HOURS, MIN_REST, MAX_CONSECUTIVE_DAYS, SHIFT_LENGTH) by
40
+ * simulation: the person's timeline before and after the change, every
41
+ * calendar included; findings the change introduces or worsens become
42
+ * reasons at the rule's severity, even when they land on another seat.
43
+ *
44
+ * A context describes one candidate for one seat's calendar: calendarId,
45
+ * timeZone and rules are those of the seat the candidate would hold; the
46
+ * timeline, time off and availability are the candidate's.
47
+ */
48
+
49
+ const FILE_CONSTANTS = {
50
+ personTimelineKinds: SCHEDULE_PERSON_RULE_KINDS.filter(
51
+ (kind) => kind !== 'ELIGIBILITY',
52
+ ),
53
+ };
54
+
55
+ /*
56
+ * Build one reason; null bounds mean the whole seat.
57
+ */
58
+ function buildEligibilityReason(
59
+ code: ScheduleEligibilityReasonEnum,
60
+ severity: ScheduleRuleSeverityEnum,
61
+ ruleId: string | null,
62
+ detail: Record<string, unknown>,
63
+ startMs: number | null = null,
64
+ endMs: number | null = null,
65
+ ): ScheduleEligibilityReasonObj {
66
+ return {
67
+ code,
68
+ severity,
69
+ ruleId,
70
+ detail,
71
+ startAt: startMs === null ? null : new Date(startMs),
72
+ endAt: endMs === null ? null : new Date(endMs),
73
+ };
44
74
  }
45
- export interface ShiftEligibilityResult {
46
- eligible: boolean;
47
- slotKey: string | null;
48
- reasons: EligibilityReason[];
75
+
76
+ /*
77
+ * Return the overlap of two half-open intervals, or null when they do not
78
+ * overlap.
79
+ */
80
+ function getIntervalOverlap(
81
+ startMs: number,
82
+ endMs: number,
83
+ otherStartMs: number,
84
+ otherEndMs: number,
85
+ ): [number, number] | null {
86
+ const from = Math.max(startMs, otherStartMs);
87
+ const to = Math.min(endMs, otherEndMs);
88
+ return to > from ? [from, to] : null;
49
89
  }
50
- export interface AssignmentChange {
51
- add: Array<{
52
- occurrenceId: string;
53
- resourceId: string;
54
- slotKey: string | null;
55
- }>;
56
- remove: Array<{ occurrenceId: string; resourceId: string }>;
90
+
91
+ /*
92
+ * Sort reasons: BLOCK first, then SCHEDULE_ELIGIBILITY_REASON_ENUMS order,
93
+ * then start (whole-seat reasons first), then their content.
94
+ */
95
+ function sortEligibilityReasons(
96
+ reasons: ScheduleEligibilityReasonObj[],
97
+ ): ScheduleEligibilityReasonObj[] {
98
+ return reasons.sort((a, b) => {
99
+ const order =
100
+ Number(b.severity === 'BLOCK') - Number(a.severity === 'BLOCK') ||
101
+ SCHEDULE_ELIGIBILITY_REASON_ENUMS.indexOf(a.code) -
102
+ SCHEDULE_ELIGIBILITY_REASON_ENUMS.indexOf(b.code) ||
103
+ (a.startAt?.getTime() ?? Number.NEGATIVE_INFINITY) -
104
+ (b.startAt?.getTime() ?? Number.NEGATIVE_INFINITY);
105
+ if (order) return order;
106
+ const left = stableStringify(a);
107
+ const right = stableStringify(b);
108
+ return left < right ? -1 : left > right ? 1 : 0;
109
+ });
57
110
  }
58
111
 
59
- /* Add one hypothetical assignment using copy-on-write for only the touched occurrence. */
60
- export function withSimulatedAssignment(
61
- snapshot: CoverageEvaluationInput,
62
- occurrenceId: string,
63
- assignment: CoverageAssignmentInput,
64
- ): CoverageEvaluationInput {
65
- return {
66
- ...snapshot,
67
- occurrences: snapshot.occurrences.map((occurrence) =>
68
- occurrence.id === occurrenceId
69
- ? {
70
- ...occurrence,
71
- assignments: [...occurrence.assignments, assignment],
72
- }
73
- : occurrence,
74
- ),
75
- };
112
+ /*
113
+ * Membership and lifecycle findings: retired before the seat ends (from the
114
+ * retirement on; an unreadable retiredAt counts from the seat start) and not
115
+ * a current member.
116
+ */
117
+ function getResourceFindings(
118
+ input: ScheduleShiftFindingsInput,
119
+ startMs: number,
120
+ endMs: number,
121
+ ): ScheduleEligibilityReasonObj[] {
122
+ const { resource, rule } = input;
123
+ const findings: ScheduleEligibilityReasonObj[] = [];
124
+ if (resource.retiredAt != null) {
125
+ const retiredMs = toScheduleTimeMs(resource.retiredAt);
126
+ const fromMs = Number.isFinite(retiredMs) ? retiredMs : startMs;
127
+ if (fromMs < endMs)
128
+ findings.push(
129
+ buildEligibilityReason(
130
+ 'RESOURCE_RETIRED',
131
+ 'BLOCK',
132
+ rule.ruleId,
133
+ {},
134
+ Math.max(startMs, fromMs),
135
+ endMs,
136
+ ),
137
+ );
138
+ }
139
+ if (!resource.isMember)
140
+ findings.push(
141
+ buildEligibilityReason('NOT_MEMBER', 'BLOCK', rule.ruleId, {}),
142
+ );
143
+ return findings;
76
144
  }
77
145
 
78
- /* Remove one person's assignment without mutating the source snapshot. */
79
- export function withoutAssignment(
80
- snapshot: CoverageEvaluationInput,
81
- occurrenceId: string,
82
- resourceId: string,
83
- ): CoverageEvaluationInput {
84
- return {
85
- ...snapshot,
86
- occurrences: snapshot.occurrences.map((occurrence) =>
87
- occurrence.id === occurrenceId
88
- ? {
89
- ...occurrence,
90
- assignments: occurrence.assignments.filter(
91
- (assignment) => assignment.resourceId !== resourceId,
92
- ),
93
- }
94
- : occurrence,
95
- ),
96
- };
146
+ /*
147
+ * Role findings: the seat's role not held, and the role's required
148
+ * qualifications missing or expired at seat start (an unparsable expiry is
149
+ * expired). A role missing from the catalog skips the qualification checks.
150
+ */
151
+ function getRoleFindings(
152
+ input: ScheduleShiftFindingsInput,
153
+ startMs: number,
154
+ ): ScheduleEligibilityReasonObj[] {
155
+ const { shift, resource, rolesById, rule } = input;
156
+ if (shift.roleId === null) return [];
157
+ const findings: ScheduleEligibilityReasonObj[] = [];
158
+ if (!resource.roleIds.includes(shift.roleId))
159
+ findings.push(
160
+ buildEligibilityReason('ROLE_MISSING', 'BLOCK', rule.ruleId, {
161
+ roleId: shift.roleId,
162
+ }),
163
+ );
164
+ const role = rolesById.get(shift.roleId);
165
+ if (!role) return findings;
166
+ const held = new Map(
167
+ (resource.config?.qualifications ?? []).map((item) => [item.key, item]),
168
+ );
169
+ const required = [...new Set(role.requiredQualifications)].sort();
170
+ const missing = required.filter((key) => !held.has(key));
171
+ const expired = required.filter((key) => {
172
+ const qualification = held.get(key);
173
+ if (!qualification) return false;
174
+ const expiryMs = getQualificationExpiryMs(qualification);
175
+ return expiryMs !== null && expiryMs <= startMs;
176
+ });
177
+ if (missing.length)
178
+ findings.push(
179
+ buildEligibilityReason('QUALIFICATION_MISSING', 'BLOCK', rule.ruleId, {
180
+ keys: missing,
181
+ }),
182
+ );
183
+ if (expired.length)
184
+ findings.push(
185
+ buildEligibilityReason('QUALIFICATION_EXPIRED', 'BLOCK', rule.ruleId, {
186
+ keys: expired,
187
+ }),
188
+ );
189
+ return findings;
97
190
  }
98
191
 
99
- /* Apply all removals before additions so swaps cannot temporarily double-book a seat. */
100
- export function simulateAssignmentChange(
101
- snapshot: CoverageEvaluationInput,
102
- change: AssignmentChange,
103
- ): CoverageEvaluationInput {
104
- let result = snapshot;
105
- for (const removal of change.remove)
106
- result = withoutAssignment(
107
- result,
108
- removal.occurrenceId,
109
- removal.resourceId,
192
+ /*
193
+ * TIME_OFF: one finding per approved time off of the person overlapping the
194
+ * seat, over the overlap (detail.allDay marks a whole-day time off, so the
195
+ * texts name the day off rather than the seat's hours).
196
+ */
197
+ function getTimeOffFindings(
198
+ input: ScheduleShiftFindingsInput,
199
+ startMs: number,
200
+ endMs: number,
201
+ ): ScheduleEligibilityReasonObj[] {
202
+ const findings: ScheduleEligibilityReasonObj[] = [];
203
+ for (const timeOff of input.timeOff) {
204
+ if (timeOff.resourceId !== input.resource.id) continue;
205
+ const overlap = getIntervalOverlap(
206
+ startMs,
207
+ endMs,
208
+ toScheduleTimeMs(timeOff.startAt),
209
+ toScheduleTimeMs(timeOff.endAt),
110
210
  );
111
- for (const addition of change.add)
112
- result = withSimulatedAssignment(result, addition.occurrenceId, {
113
- id: null,
114
- resourceId: addition.resourceId,
115
- slotKey: addition.slotKey,
116
- });
117
- return result;
211
+ if (overlap)
212
+ findings.push(
213
+ buildEligibilityReason(
214
+ 'TIME_OFF',
215
+ 'BLOCK',
216
+ input.rule.ruleId,
217
+ timeOff.allDay
218
+ ? { timeOffId: timeOff.id, allDay: true }
219
+ : { timeOffId: timeOff.id },
220
+ ...overlap,
221
+ ),
222
+ );
223
+ }
224
+ return findings;
118
225
  }
119
226
 
120
- /* Compare problem identities and maximum degree, allowing improving stretches to move. */
121
- export function diffCoverageViolations(
122
- before: CoverageViolationObj[],
123
- after: CoverageViolationObj[],
124
- ): {
125
- introduced: CoverageViolationObj[];
126
- worsened: CoverageViolationObj[];
127
- resolved: CoverageViolationObj[];
128
- } {
129
- const prior = new Map<string, number>();
130
- const next = new Map<string, number>();
131
- for (const violation of before)
132
- prior.set(
133
- violation.identity,
134
- Math.max(prior.get(violation.identity) ?? -Infinity, violation.degree),
227
+ /*
228
+ * OVERLAP: one finding per other live seat of the person overlapping the
229
+ * seat, over the overlap.
230
+ */
231
+ function getOverlapFindings(
232
+ input: ScheduleShiftFindingsInput,
233
+ startMs: number,
234
+ endMs: number,
235
+ ): ScheduleEligibilityReasonObj[] {
236
+ const findings: ScheduleEligibilityReasonObj[] = [];
237
+ const seen = new Set<string>();
238
+ for (const other of input.otherShifts) {
239
+ if (
240
+ other.id === input.shift.id ||
241
+ seen.has(other.id) ||
242
+ other.status === 'CANCELED' ||
243
+ other.assigneeResourceId !== input.resource.id
244
+ )
245
+ continue;
246
+ seen.add(other.id);
247
+ const overlap = getIntervalOverlap(
248
+ startMs,
249
+ endMs,
250
+ toScheduleTimeMs(other.startAt),
251
+ toScheduleTimeMs(other.endAt),
135
252
  );
136
- for (const violation of after)
137
- next.set(
138
- violation.identity,
139
- Math.max(next.get(violation.identity) ?? -Infinity, violation.degree),
253
+ if (overlap)
254
+ findings.push(
255
+ buildEligibilityReason(
256
+ 'OVERLAP',
257
+ 'BLOCK',
258
+ input.rule.ruleId,
259
+ { otherShiftId: other.id },
260
+ ...overlap,
261
+ ),
262
+ );
263
+ }
264
+ return findings;
265
+ }
266
+
267
+ /*
268
+ * UNAVAILABLE: one finding per UNAVAILABLE window occurrence of the person
269
+ * overlapping the seat, over the overlap, at the ELIGIBILITY rule's
270
+ * config.unavailable severity. PREFERRED windows are ignored.
271
+ */
272
+ function getUnavailableFindings(
273
+ input: ScheduleShiftFindingsInput,
274
+ startMs: number,
275
+ endMs: number,
276
+ ): ScheduleEligibilityReasonObj[] {
277
+ const windows = input.availability.filter(
278
+ (window) =>
279
+ window.resourceId === input.resource.id && window.kind === 'UNAVAILABLE',
280
+ );
281
+ if (!windows.length) return [];
282
+ const severity = (input.rule.config as ScheduleEligibilityConfigObj)
283
+ .unavailable;
284
+ const findings: ScheduleEligibilityReasonObj[] = [];
285
+ for (const interval of expandScheduleAvailability({
286
+ windows,
287
+ from: new Date(startMs),
288
+ to: new Date(endMs),
289
+ })) {
290
+ if (interval.kind !== 'UNAVAILABLE') continue;
291
+ const overlap = getIntervalOverlap(
292
+ startMs,
293
+ endMs,
294
+ interval.startAt.getTime(),
295
+ interval.endAt.getTime(),
140
296
  );
141
- return {
142
- introduced: after.filter((violation) => !prior.has(violation.identity)),
143
- worsened: after.filter(
144
- (violation) =>
145
- prior.has(violation.identity) &&
146
- next.get(violation.identity)! > prior.get(violation.identity)!,
147
- ),
148
- resolved: before.filter((violation) => !next.has(violation.identity)),
149
- };
297
+ if (overlap)
298
+ findings.push(
299
+ buildEligibilityReason(
300
+ 'UNAVAILABLE',
301
+ severity,
302
+ input.rule.ruleId,
303
+ { availabilityId: interval.availabilityId },
304
+ ...overlap,
305
+ ),
306
+ );
307
+ }
308
+ return findings;
150
309
  }
151
310
 
152
- /* Present stable, deduplicated reasons with blocking facts before warnings. */
311
+ /*
312
+ * The structural findings of one person holding one seat (§1.4): NOT_PERSON
313
+ * (returned alone), RESOURCE_RETIRED, NOT_MEMBER, ROLE_MISSING,
314
+ * QUALIFICATION_MISSING, QUALIFICATION_EXPIRED, TIME_OFF and OVERLAP at
315
+ * BLOCK; UNAVAILABLE at the rule's config.unavailable. No person rules and no
316
+ * seat-state checks. Every finding carries the ELIGIBILITY rule's id.
317
+ */
318
+ export function getShiftEligibilityFindings(
319
+ input: ScheduleShiftFindingsInput,
320
+ ): ScheduleEligibilityReasonObj[] {
321
+ if (input.resource.kind !== 'PERSON')
322
+ return [
323
+ buildEligibilityReason('NOT_PERSON', 'BLOCK', input.rule.ruleId, {}),
324
+ ];
325
+ const startMs = toScheduleTimeMs(input.shift.startAt);
326
+ const endMs = toScheduleTimeMs(input.shift.endAt);
327
+ return sortEligibilityReasons([
328
+ ...getResourceFindings(input, startMs, endMs),
329
+ ...getRoleFindings(input, startMs),
330
+ ...getTimeOffFindings(input, startMs, endMs),
331
+ ...getOverlapFindings(input, startMs, endMs),
332
+ ...getUnavailableFindings(input, startMs, endMs),
333
+ ]);
334
+ }
335
+
336
+ /*
337
+ * Dedupe and sort reasons; eligible when none is BLOCK.
338
+ */
153
339
  function finishEligibility(
154
- slotKey: string | null,
155
- reasons: EligibilityReason[],
156
- ): ShiftEligibilityResult {
157
- const unique = new Map<string, EligibilityReason>();
340
+ reasons: ScheduleEligibilityReasonObj[],
341
+ ): ScheduleEligibilityResult {
342
+ const unique = new Map<string, ScheduleEligibilityReasonObj>();
158
343
  for (const reason of reasons) unique.set(stableStringify(reason), reason);
159
- const sorted = [...unique.values()].sort(
160
- (a, b) =>
161
- Number(b.severity === 'BLOCK') - Number(a.severity === 'BLOCK') ||
162
- SCHEDULE_ELIGIBILITY_REASON_ENUMS.indexOf(a.code) -
163
- SCHEDULE_ELIGIBILITY_REASON_ENUMS.indexOf(b.code) ||
164
- (a.startAt?.getTime() ?? 0) - (b.startAt?.getTime() ?? 0),
165
- );
344
+ const sorted = sortEligibilityReasons([...unique.values()]);
166
345
  return {
167
346
  eligible: !sorted.some((reason) => reason.severity === 'BLOCK'),
168
- slotKey,
169
347
  reasons: sorted,
170
348
  };
171
349
  }
172
350
 
173
- /* Map the coverage engine's assignment and aggregate violations to picker reasons. */
174
- function violationToReason(
351
+ /*
352
+ * Seat-state reasons for the seat a person would hold: canceled, ended by
353
+ * `now` (on the given end), and already held by this person.
354
+ */
355
+ function getSeatStateReasons(
356
+ shift: CoverageShiftInput,
357
+ endAt: Date | string,
358
+ now: Date | string,
359
+ alreadyAssigned: boolean,
360
+ ): ScheduleEligibilityReasonObj[] {
361
+ const reasons: ScheduleEligibilityReasonObj[] = [];
362
+ if (shift.status === 'CANCELED')
363
+ reasons.push(buildEligibilityReason('SHIFT_CANCELED', 'BLOCK', null, {}));
364
+ if (toScheduleTimeMs(endAt) <= toScheduleTimeMs(now))
365
+ reasons.push(buildEligibilityReason('SHIFT_ENDED', 'BLOCK', null, {}));
366
+ if (alreadyAssigned)
367
+ reasons.push(buildEligibilityReason('ALREADY_ASSIGNED', 'BLOCK', null, {}));
368
+ return reasons;
369
+ }
370
+
371
+ /*
372
+ * Resolve the context's rules for one candidate (diagnostics are ignored
373
+ * here: evaluation reports them).
374
+ */
375
+ function resolveCandidateRules(
376
+ context: ScheduleEligibilityContext,
377
+ resource: CoverageResourceInput,
378
+ ): ScheduleEffectiveRuleIndex {
379
+ return resolveEffectiveScheduleRules(
380
+ context.rules,
381
+ context.calendarId,
382
+ new Map([[resource.id, resource]]),
383
+ null,
384
+ ).index;
385
+ }
386
+
387
+ /*
388
+ * Turn one introduced or worsened person-rule finding into a reason; its
389
+ * detail names the breaking seat, which may be another seat.
390
+ */
391
+ function getPersonRuleReason(
175
392
  violation: CoverageViolationObj,
176
- occurrence: CoverageOccurrenceInput,
177
- ): EligibilityReason | null {
178
- let code: ScheduleEligibilityReasonEnum;
179
- if (violation.kind === 'ELIGIBILITY' && violation.code)
180
- code =
181
- violation.code === 'QUALIFICATION_EXPIRED' &&
182
- violation.startAt.getTime() > coverageTime(occurrence.startAt)
183
- ? 'QUALIFICATION_EXPIRES_DURING_SHIFT'
184
- : (violation.code as ScheduleEligibilityReasonEnum);
185
- else if (violation.kind === 'ACTOR_WINDOW_AGGREGATE')
186
- code = violation.code === 'HOURS' ? 'WINDOW_HOURS_EXCEEDED' : 'MIN_REST';
187
- else return null;
393
+ ): ScheduleEligibilityReasonObj {
188
394
  return {
189
- code,
395
+ code: violation.kind as ScheduleEligibilityReasonEnum,
190
396
  severity: violation.severity,
191
397
  ruleId: violation.ruleId,
192
- detail:
193
- violation.kind === 'ACTOR_WINDOW_AGGREGATE'
194
- ? { ...violation.detail, occurrenceId: violation.occurrenceId }
195
- : violation.detail,
398
+ detail: { ...violation.detail, shiftId: violation.shiftId },
196
399
  startAt: violation.startAt,
197
400
  endAt: violation.endAt,
198
401
  };
199
402
  }
200
403
 
201
- /* Resolve a candidate seat, then use coverage simulation as the source of policy eligibility. */
202
- export function evaluateShiftEligibility(args: {
203
- occurrence: CoverageOccurrenceInput;
204
- slotKey: string | null;
404
+ /*
405
+ * Simulate the person rules on the timeline before and after a change and
406
+ * return the findings it introduces or worsens, as reasons.
407
+ */
408
+ function getPersonRuleReasons(args: {
205
409
  resource: CoverageResourceInput;
206
- context: ShiftEligibilityContext;
207
- }): ShiftEligibilityResult {
208
- const { occurrence, resource, context } = args;
209
- const resources = new Map(
210
- context.resources.map((person) => [person.id, person]),
211
- );
212
- if (
213
- occurrence.assignments.some(
214
- (assignment) => !resources.has(assignment.resourceId),
215
- )
216
- )
217
- throw new Error('SCHEDULE_ELIGIBILITY_CONTEXT_INCOMPLETE');
218
- resources.set(resource.id, resource);
219
- const reasons: EligibilityReason[] = [];
220
- /* Add structural reasons that cannot be represented by a persisted coverage violation. */
221
- const reason = (
222
- code: ScheduleEligibilityReasonEnum,
223
- severity: ScheduleRuleSeverityEnum = 'BLOCK',
224
- detail: Record<string, unknown> = {},
225
- ): void => {
226
- reasons.push({
227
- code,
228
- severity,
229
- ruleId: null,
230
- detail,
231
- startAt: null,
232
- endAt: null,
410
+ context: ScheduleEligibilityContext;
411
+ index: ScheduleEffectiveRuleIndex;
412
+ before: CoverageShiftInput[];
413
+ after: CoverageShiftInput[];
414
+ }): ScheduleEligibilityReasonObj[] {
415
+ const { resource, context, index } = args;
416
+ const rules: ScheduleEffectiveRule[] =
417
+ FILE_CONSTANTS.personTimelineKinds.flatMap((kind) =>
418
+ getEffectiveScheduleRules(index, kind, resource.id),
419
+ );
420
+ if (!rules.length) return [];
421
+ // Every seat may carry a finding: the change can break a rule on another seat
422
+ const evaluate = (timeline: CoverageShiftInput[]) =>
423
+ evaluatePersonRules({
424
+ resourceId: resource.id,
425
+ timeline,
426
+ anchorShiftIds: null,
427
+ rules,
428
+ timeZone: context.timeZone,
429
+ payWeekStart: context.payWeekStart,
233
430
  });
234
- };
235
- if (resource.kind !== 'LABOR') reason('NOT_LABOR');
236
- if (
237
- resource.retiredAt != null &&
238
- coverageTime(resource.retiredAt) <= coverageTime(occurrence.endAt)
239
- )
240
- reason('RESOURCE_RETIRED');
241
- if (occurrence.kind !== 'SHIFT') reason('OCCURRENCE_NOT_SHIFT');
242
- if (coverageTime(occurrence.endAt) <= context.now.getTime())
243
- reason('OCCURRENCE_ENDED');
244
- if (
245
- occurrence.assignments.some(
246
- (assignment) => assignment.resourceId === resource.id,
247
- )
248
- )
249
- reason('ALREADY_ASSIGNED');
250
- const windowDays = Math.max(1, getMaxActorWindowDays(context.rules));
251
- // Earlier assignments remain timeline evidence; only the target and later anchors can worsen.
252
- const snapshot: CoverageEvaluationInput = {
253
- calendarId: context.calendarId,
254
- window: {
255
- from: occurrence.startAt,
256
- to: new Date(coverageTime(occurrence.endAt) + windowDays * 86_400_000),
257
- },
258
- timeZone: 'UTC',
259
- operatingHours: null,
260
- occurrences: [occurrence],
261
- external: context.assignmentsOfResource.filter(
262
- (row) => row.occurrenceId !== occurrence.id,
263
- ),
264
- resources: [...resources.values()],
265
- demand: [],
431
+ const diff = diffCoverageViolations(
432
+ evaluate(args.before),
433
+ evaluate(args.after),
434
+ );
435
+ return [...diff.introduced, ...diff.worsened].map(getPersonRuleReason);
436
+ }
437
+
438
+ /*
439
+ * Judge one person holding `seat` (already carrying them as assignee and the
440
+ * simulated hours): seat-state reasons, structural findings against the
441
+ * other seats of `after`, and the person rules from `before` to `after`.
442
+ */
443
+ function evaluatePersonSeat(args: {
444
+ seat: CoverageShiftInput;
445
+ resource: CoverageResourceInput;
446
+ context: ScheduleEligibilityContext;
447
+ before: CoverageShiftInput[];
448
+ after: CoverageShiftInput[];
449
+ stateReasons: ScheduleEligibilityReasonObj[];
450
+ }): ScheduleEligibilityResult {
451
+ const { seat, resource, context } = args;
452
+ const index = resolveCandidateRules(context, resource);
453
+ const findings = getShiftEligibilityFindings({
454
+ shift: seat,
455
+ resource,
456
+ rolesById: new Map(context.roles.map((role) => [role.id, role])),
457
+ otherShifts: args.after.filter((shift) => shift.id !== seat.id),
266
458
  timeOff: context.timeOff,
267
- rules: context.rules.filter(
268
- (rule) =>
269
- rule.kind === 'ELIGIBILITY' || rule.kind === 'ACTOR_WINDOW_AGGREGATE',
459
+ availability: context.availability,
460
+ rule: getEffectiveScheduleRules(index, 'ELIGIBILITY', resource.id)[0],
461
+ });
462
+ const personRules =
463
+ resource.kind === 'PERSON'
464
+ ? getPersonRuleReasons({
465
+ resource,
466
+ context,
467
+ index,
468
+ before: args.before,
469
+ after: args.after,
470
+ })
471
+ : [];
472
+ return finishEligibility([...args.stateReasons, ...findings, ...personRules]);
473
+ }
474
+
475
+ /*
476
+ * Drop the seats with the given ids from a timeline.
477
+ */
478
+ function withoutShifts(
479
+ timeline: CoverageShiftInput[],
480
+ shiftIds: string[],
481
+ ): CoverageShiftInput[] {
482
+ return timeline.filter((shift) => !shiftIds.includes(shift.id));
483
+ }
484
+
485
+ /*
486
+ * A copy of a seat held by one person.
487
+ */
488
+ function asHeldBy(
489
+ shift: CoverageShiftInput,
490
+ resourceId: string,
491
+ ): CoverageShiftInput {
492
+ return { ...shift, assigneeResourceId: resourceId };
493
+ }
494
+
495
+ /*
496
+ * Can `resource` be assigned to `shift`? Seat state (canceled, ended,
497
+ * already theirs), the structural findings, and the person rules simulated
498
+ * from their timeline without the seat to the timeline with it.
499
+ */
500
+ export function evaluateShiftEligibility(args: {
501
+ shift: CoverageShiftInput;
502
+ resource: CoverageResourceInput;
503
+ context: ScheduleEligibilityContext;
504
+ }): ScheduleEligibilityResult {
505
+ const { shift, resource, context } = args;
506
+ const seat = asHeldBy(shift, resource.id);
507
+ const before = withoutShifts(context.timeline, [shift.id]);
508
+ return evaluatePersonSeat({
509
+ seat,
510
+ resource,
511
+ context,
512
+ before,
513
+ after: [...before, seat],
514
+ stateReasons: getSeatStateReasons(
515
+ shift,
516
+ shift.endAt,
517
+ context.now,
518
+ shift.assigneeResourceId === resource.id,
270
519
  ),
271
- options: { anchorExternal: true },
520
+ });
521
+ }
522
+
523
+ /*
524
+ * Can `resource` keep `shift` with new hours? Seat state on the new end, the
525
+ * structural findings on the retimed seat (shiftDate recomputed in the
526
+ * context's zone), and the person rules from the old hours to the new.
527
+ */
528
+ export function evaluateRetimeEligibility(args: {
529
+ shift: CoverageShiftInput;
530
+ startAt: Date | string;
531
+ endAt: Date | string;
532
+ resource: CoverageResourceInput;
533
+ context: ScheduleEligibilityContext;
534
+ }): ScheduleEligibilityResult {
535
+ const { shift, resource, context } = args;
536
+ const seat: CoverageShiftInput = {
537
+ ...asHeldBy(shift, resource.id),
538
+ startAt: args.startAt,
539
+ endAt: args.endAt,
540
+ shiftDate: getScheduleLocalDate(args.startAt, context.timeZone),
272
541
  };
273
- const normalized = normalizeCoverageInput(snapshot);
274
- const normalizedOccurrence = normalized.occurrences[0];
275
- if (!normalizedOccurrence)
276
- return finishEligibility(args.slotKey, [
277
- ...reasons,
278
- {
279
- code: 'OCCURRENCE_ENDED',
280
- severity: 'BLOCK',
281
- ruleId: null,
282
- detail: { invalidInterval: true },
283
- startAt: null,
284
- endAt: null,
285
- },
286
- ]);
287
- const fill = fillOccurrenceSlots(normalizedOccurrence, normalized);
288
- const slots = normalizedOccurrence.slots;
289
- /* Qualification keys select a seat while expiry is evaluated over the entire shift by the sweep. */
290
- const matches = (slot: (typeof slots)[number]): boolean =>
291
- !Object.values(
292
- getSlotPredicateMissing(resource.config, slot.predicate),
293
- ).some((keys) => keys.length);
294
- let slot =
295
- context.preserveUnslotted && args.slotKey === null
296
- ? undefined
297
- : args.slotKey !== null
298
- ? slots.find((slot) => slot.key === args.slotKey)
299
- : (slots.find(
300
- (slot) =>
301
- (fill.filled.get(slot.key) ?? 0) < slot.requiredCount &&
302
- matches(slot),
303
- ) ?? slots.find(matches));
304
- if (args.slotKey !== null && !slot)
305
- reason('SLOT_UNKNOWN', 'BLOCK', { slotKey: args.slotKey });
306
- else if (!slot && !context.preserveUnslotted)
307
- reason('NO_MATCHING_SLOT', context.requireOpenSlot ? 'BLOCK' : 'WARN');
308
- if (slot && (fill.filled.get(slot.key) ?? 0) >= slot.requiredCount)
309
- reason('SLOT_FULL', context.requireOpenSlot ? 'BLOCK' : 'WARN', {
310
- slotKey: slot.key,
311
- });
312
- if (reasons.some((item) => item.severity === 'BLOCK'))
313
- return finishEligibility(slot?.key ?? null, reasons);
314
- // Freeze current greedy placements so adding a candidate cannot reshuffle existing people's seats.
315
- const placements = new Map(
316
- fill.standings.map((standing) => [
317
- standing.personId,
318
- standing.placedSlotKey,
319
- ]),
320
- );
321
- const stableOccurrence = {
322
- ...occurrence,
323
- assignments: occurrence.assignments.map((assignment) =>
324
- assignment.slotKey === null && placements.get(assignment.resourceId)
325
- ? { ...assignment, slotKey: placements.get(assignment.resourceId)! }
326
- : assignment,
542
+ const rest = withoutShifts(context.timeline, [shift.id]);
543
+ return evaluatePersonSeat({
544
+ seat,
545
+ resource,
546
+ context,
547
+ before: [...rest, asHeldBy(shift, resource.id)],
548
+ after: [...rest, seat],
549
+ stateReasons: getSeatStateReasons(shift, args.endAt, context.now, false),
550
+ });
551
+ }
552
+
553
+ /*
554
+ * One side of a swap: the person gives up their seat and takes the other's.
555
+ * Overlap ignores the outgoing seat, so a same-time swap is fine.
556
+ */
557
+ function evaluateSwapSide(
558
+ side: {
559
+ shift: CoverageShiftInput;
560
+ resource: CoverageResourceInput;
561
+ context: ScheduleEligibilityContext;
562
+ },
563
+ incoming: CoverageShiftInput,
564
+ ): ScheduleEligibilityResult {
565
+ const { shift: outgoing, resource, context } = side;
566
+ const seat = asHeldBy(incoming, resource.id);
567
+ const rest = withoutShifts(context.timeline, [outgoing.id, incoming.id]);
568
+ return evaluatePersonSeat({
569
+ seat,
570
+ resource,
571
+ context,
572
+ before: [...rest, asHeldBy(outgoing, resource.id)],
573
+ after: [...rest, seat],
574
+ stateReasons: getSeatStateReasons(
575
+ incoming,
576
+ incoming.endAt,
577
+ context.now,
578
+ false,
327
579
  ),
328
- };
329
- const beforeSnapshot = { ...snapshot, occurrences: [stableOccurrence] };
330
- const before = evaluateScheduleCoverage(beforeSnapshot).violations;
331
- const after = evaluateScheduleCoverage(
332
- withSimulatedAssignment(beforeSnapshot, occurrence.id, {
333
- id: null,
334
- resourceId: resource.id,
335
- slotKey: slot?.key ?? null,
336
- }),
337
- ).violations;
338
- const diff = diffCoverageViolations(before, after);
339
- for (const violation of [...diff.introduced, ...diff.worsened]) {
340
- if (violation.resourceId !== resource.id) continue;
341
- const mapped = violationToReason(violation, occurrence);
342
- if (mapped) reasons.push(mapped);
343
- }
344
- return finishEligibility(slot?.key ?? null, reasons);
580
+ });
345
581
  }
346
582
 
347
- /* Check both swap directions after each outgoing person has vacated the exchanged seat. */
583
+ /*
584
+ * Can two people trade seats? Each side is judged taking the other's seat
585
+ * with its own context (the person's timeline, time off and availability,
586
+ * for the incoming seat's calendar). Eligible when both sides are.
587
+ */
348
588
  export function evaluateSwapEligibility(args: {
349
- a: {
350
- occurrence: CoverageOccurrenceInput;
589
+ requester: {
590
+ shift: CoverageShiftInput;
351
591
  resource: CoverageResourceInput;
352
- context: ShiftEligibilityContext;
592
+ context: ScheduleEligibilityContext;
353
593
  };
354
- b: {
355
- occurrence: CoverageOccurrenceInput;
594
+ counterparty: {
595
+ shift: CoverageShiftInput;
356
596
  resource: CoverageResourceInput;
357
- context: ShiftEligibilityContext;
597
+ context: ScheduleEligibilityContext;
358
598
  };
359
- }): {
360
- eligible: boolean;
361
- slotKeys: { a: string | null; b: string | null };
362
- reasons: { a: EligibilityReason[]; b: EligibilityReason[] };
363
- } {
364
- const { a, b } = args;
365
- const aSeat = a.occurrence.assignments.find(
366
- (assignment) => assignment.resourceId === a.resource.id,
367
- );
368
- const bSeat = b.occurrence.assignments.find(
369
- (assignment) => assignment.resourceId === b.resource.id,
599
+ }): ScheduleSwapEligibilityResult {
600
+ const requester = evaluateSwapSide(args.requester, args.counterparty.shift);
601
+ const counterparty = evaluateSwapSide(
602
+ args.counterparty,
603
+ args.requester.shift,
370
604
  );
371
- if (!aSeat || !bSeat) throw new Error('SCHEDULE_SWAP_ASSIGNMENT_MISSING');
372
- for (const context of [a.context, b.context]) {
373
- const ids = new Set(context.resources.map((resource) => resource.id));
374
- if (
375
- [...a.occurrence.assignments, ...b.occurrence.assignments].some(
376
- (assignment) => !ids.has(assignment.resourceId),
377
- )
378
- )
379
- throw new Error('SCHEDULE_ELIGIBILITY_CONTEXT_INCOMPLETE');
380
- }
381
- const occurrences = new Set([a.occurrence.id, b.occurrence.id]);
382
- const aResult = evaluateShiftEligibility({
383
- occurrence: {
384
- ...b.occurrence,
385
- assignments: b.occurrence.assignments.filter(
386
- (assignment) => assignment.resourceId !== b.resource.id,
387
- ),
388
- },
389
- slotKey: bSeat.slotKey,
390
- resource: a.resource,
391
- context: {
392
- ...a.context,
393
- preserveUnslotted: bSeat.slotKey === null,
394
- calendarId: b.context.calendarId,
395
- rules: b.context.rules,
396
- assignmentsOfResource: a.context.assignmentsOfResource.filter(
397
- (row) => !occurrences.has(row.occurrenceId),
398
- ),
399
- },
400
- });
401
- const bResult = evaluateShiftEligibility({
402
- occurrence: {
403
- ...a.occurrence,
404
- assignments: a.occurrence.assignments.filter(
405
- (assignment) => assignment.resourceId !== a.resource.id,
406
- ),
407
- },
408
- slotKey: aSeat.slotKey,
409
- resource: b.resource,
410
- context: {
411
- ...b.context,
412
- preserveUnslotted: aSeat.slotKey === null,
413
- calendarId: a.context.calendarId,
414
- rules: a.context.rules,
415
- assignmentsOfResource: b.context.assignmentsOfResource.filter(
416
- (row) => !occurrences.has(row.occurrenceId),
417
- ),
418
- },
419
- });
420
605
  return {
421
- eligible: aResult.eligible && bResult.eligible,
422
- slotKeys: { a: aResult.slotKey, b: bResult.slotKey },
423
- reasons: { a: aResult.reasons, b: bResult.reasons },
424
- };
425
- }
426
-
427
- /* Show newly introduced and worsened room coverage when a manager considers a drop. */
428
- export function evaluateDropImpact(args: {
429
- occurrence: CoverageOccurrenceInput;
430
- resourceId: string;
431
- context: {
432
- calendarId: string;
433
- roomOccurrences: CoverageOccurrenceInput[];
434
- demand: CoverageDemandInput[];
435
- timeOff: CoverageTimeOffInput[];
436
- rules: CoverageRuleInput[];
437
- resources: CoverageResourceInput[];
438
- operatingHours: ScheduleWorkCalendarDef | null;
439
- timeZone: string;
440
- };
441
- }): { introduced: CoverageViolationObj[]; worsened: CoverageViolationObj[] } {
442
- const { occurrence, resourceId, context } = args;
443
- const snapshot: CoverageEvaluationInput = {
444
- ...context,
445
- window: { from: occurrence.startAt, to: occurrence.endAt },
446
- occurrences: context.roomOccurrences.some((row) => row.id === occurrence.id)
447
- ? context.roomOccurrences
448
- : [...context.roomOccurrences, occurrence],
449
- external: [],
606
+ eligible: requester.eligible && counterparty.eligible,
607
+ requester,
608
+ counterparty,
450
609
  };
451
- const before = evaluateScheduleCoverage(snapshot).violations;
452
- const after = evaluateScheduleCoverage(
453
- withoutAssignment(snapshot, occurrence.id, resourceId),
454
- ).violations;
455
- const { introduced, worsened } = diffCoverageViolations(before, after);
456
- return { introduced, worsened };
457
610
  }