assignment-user-matcher 1.8.0 → 1.10.0

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 (165) hide show
  1. package/README.md +240 -12
  2. package/dist/index.d.ts +3 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +23 -1
  5. package/dist/matcher.class.d.ts +44 -2
  6. package/dist/matcher.class.d.ts.map +1 -1
  7. package/dist/matcher.class.js +393 -4
  8. package/dist/queries/pagination.d.ts +5 -1
  9. package/dist/queries/pagination.d.ts.map +1 -1
  10. package/dist/queries/pagination.js +14 -3
  11. package/dist/schedule/policy.d.ts +35 -0
  12. package/dist/schedule/policy.d.ts.map +1 -0
  13. package/dist/schedule/policy.js +62 -0
  14. package/dist/scheduling/constraints/availability.d.ts +44 -0
  15. package/dist/scheduling/constraints/availability.d.ts.map +1 -0
  16. package/dist/scheduling/constraints/availability.js +142 -0
  17. package/dist/scheduling/constraints/consecutive.d.ts +25 -0
  18. package/dist/scheduling/constraints/consecutive.d.ts.map +1 -0
  19. package/dist/scheduling/constraints/consecutive.js +215 -0
  20. package/dist/scheduling/constraints/constraint.d.ts +35 -0
  21. package/dist/scheduling/constraints/constraint.d.ts.map +1 -0
  22. package/dist/scheduling/constraints/constraint.js +97 -0
  23. package/dist/scheduling/constraints/contract.d.ts +21 -0
  24. package/dist/scheduling/constraints/contract.d.ts.map +1 -0
  25. package/dist/scheduling/constraints/contract.js +106 -0
  26. package/dist/scheduling/constraints/cost.d.ts +18 -0
  27. package/dist/scheduling/constraints/cost.d.ts.map +1 -0
  28. package/dist/scheduling/constraints/cost.js +65 -0
  29. package/dist/scheduling/constraints/daily-rest.d.ts +22 -0
  30. package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -0
  31. package/dist/scheduling/constraints/daily-rest.js +118 -0
  32. package/dist/scheduling/constraints/duty-quota.d.ts +20 -0
  33. package/dist/scheduling/constraints/duty-quota.d.ts.map +1 -0
  34. package/dist/scheduling/constraints/duty-quota.js +95 -0
  35. package/dist/scheduling/constraints/engagement-floor.d.ts +28 -0
  36. package/dist/scheduling/constraints/engagement-floor.d.ts.map +1 -0
  37. package/dist/scheduling/constraints/engagement-floor.js +79 -0
  38. package/dist/scheduling/constraints/fairness.d.ts +34 -0
  39. package/dist/scheduling/constraints/fairness.d.ts.map +1 -0
  40. package/dist/scheduling/constraints/fairness.js +149 -0
  41. package/dist/scheduling/constraints/group-composition.d.ts +19 -0
  42. package/dist/scheduling/constraints/group-composition.d.ts.map +1 -0
  43. package/dist/scheduling/constraints/group-composition.js +92 -0
  44. package/dist/scheduling/constraints/hour-budget.d.ts +13 -0
  45. package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -0
  46. package/dist/scheduling/constraints/hour-budget.js +59 -0
  47. package/dist/scheduling/constraints/in-shift-breaks.d.ts +24 -0
  48. package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -0
  49. package/dist/scheduling/constraints/in-shift-breaks.js +97 -0
  50. package/dist/scheduling/constraints/intervals.d.ts +5 -0
  51. package/dist/scheduling/constraints/intervals.d.ts.map +1 -0
  52. package/dist/scheduling/constraints/intervals.js +17 -0
  53. package/dist/scheduling/constraints/max-shift-duration.d.ts +7 -0
  54. package/dist/scheduling/constraints/max-shift-duration.d.ts.map +1 -0
  55. package/dist/scheduling/constraints/max-shift-duration.js +38 -0
  56. package/dist/scheduling/constraints/min-rest.d.ts +22 -0
  57. package/dist/scheduling/constraints/min-rest.d.ts.map +1 -0
  58. package/dist/scheduling/constraints/min-rest.js +60 -0
  59. package/dist/scheduling/constraints/min-staffing.d.ts +14 -0
  60. package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -0
  61. package/dist/scheduling/constraints/min-staffing.js +59 -0
  62. package/dist/scheduling/constraints/night-work.d.ts +24 -0
  63. package/dist/scheduling/constraints/night-work.d.ts.map +1 -0
  64. package/dist/scheduling/constraints/night-work.js +163 -0
  65. package/dist/scheduling/constraints/no-overlap.d.ts +7 -0
  66. package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -0
  67. package/dist/scheduling/constraints/no-overlap.js +36 -0
  68. package/dist/scheduling/constraints/notice.d.ts +44 -0
  69. package/dist/scheduling/constraints/notice.d.ts.map +1 -0
  70. package/dist/scheduling/constraints/notice.js +140 -0
  71. package/dist/scheduling/constraints/one-shift-per-day.d.ts +7 -0
  72. package/dist/scheduling/constraints/one-shift-per-day.d.ts.map +1 -0
  73. package/dist/scheduling/constraints/one-shift-per-day.js +35 -0
  74. package/dist/scheduling/constraints/overtime.d.ts +47 -0
  75. package/dist/scheduling/constraints/overtime.d.ts.map +1 -0
  76. package/dist/scheduling/constraints/overtime.js +149 -0
  77. package/dist/scheduling/constraints/protections.d.ts +21 -0
  78. package/dist/scheduling/constraints/protections.d.ts.map +1 -0
  79. package/dist/scheduling/constraints/protections.js +93 -0
  80. package/dist/scheduling/constraints/qualification.d.ts +18 -0
  81. package/dist/scheduling/constraints/qualification.d.ts.map +1 -0
  82. package/dist/scheduling/constraints/qualification.js +78 -0
  83. package/dist/scheduling/constraints/rest-days.d.ts +30 -0
  84. package/dist/scheduling/constraints/rest-days.d.ts.map +1 -0
  85. package/dist/scheduling/constraints/rest-days.js +133 -0
  86. package/dist/scheduling/constraints/rolling-hours.d.ts +24 -0
  87. package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -0
  88. package/dist/scheduling/constraints/rolling-hours.js +147 -0
  89. package/dist/scheduling/constraints/start-interval.d.ts +20 -0
  90. package/dist/scheduling/constraints/start-interval.d.ts.map +1 -0
  91. package/dist/scheduling/constraints/start-interval.js +53 -0
  92. package/dist/scheduling/constraints/support.d.ts +48 -0
  93. package/dist/scheduling/constraints/support.d.ts.map +1 -0
  94. package/dist/scheduling/constraints/support.js +97 -0
  95. package/dist/scheduling/constraints/time-off.d.ts +7 -0
  96. package/dist/scheduling/constraints/time-off.d.ts.map +1 -0
  97. package/dist/scheduling/constraints/time-off.js +42 -0
  98. package/dist/scheduling/constraints/weekly-rest.d.ts +22 -0
  99. package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -0
  100. package/dist/scheduling/constraints/weekly-rest.js +92 -0
  101. package/dist/scheduling/cost.d.ts +56 -0
  102. package/dist/scheduling/cost.d.ts.map +1 -0
  103. package/dist/scheduling/cost.js +120 -0
  104. package/dist/scheduling/engine/construction.d.ts +22 -0
  105. package/dist/scheduling/engine/construction.d.ts.map +1 -0
  106. package/dist/scheduling/engine/construction.js +97 -0
  107. package/dist/scheduling/engine/explain.d.ts +12 -0
  108. package/dist/scheduling/engine/explain.d.ts.map +1 -0
  109. package/dist/scheduling/engine/explain.js +24 -0
  110. package/dist/scheduling/engine/objective.d.ts +73 -0
  111. package/dist/scheduling/engine/objective.d.ts.map +1 -0
  112. package/dist/scheduling/engine/objective.js +164 -0
  113. package/dist/scheduling/engine/prng.d.ts +5 -0
  114. package/dist/scheduling/engine/prng.d.ts.map +1 -0
  115. package/dist/scheduling/engine/prng.js +24 -0
  116. package/dist/scheduling/engine/propagation.d.ts +19 -0
  117. package/dist/scheduling/engine/propagation.d.ts.map +1 -0
  118. package/dist/scheduling/engine/propagation.js +40 -0
  119. package/dist/scheduling/engine/search.d.ts +50 -0
  120. package/dist/scheduling/engine/search.d.ts.map +1 -0
  121. package/dist/scheduling/engine/search.js +127 -0
  122. package/dist/scheduling/engine/state.d.ts +28 -0
  123. package/dist/scheduling/engine/state.d.ts.map +1 -0
  124. package/dist/scheduling/engine/state.js +96 -0
  125. package/dist/scheduling/engine/timeline.d.ts +179 -0
  126. package/dist/scheduling/engine/timeline.d.ts.map +1 -0
  127. package/dist/scheduling/engine/timeline.js +416 -0
  128. package/dist/scheduling/engine/verdicts.d.ts +18 -0
  129. package/dist/scheduling/engine/verdicts.d.ts.map +1 -0
  130. package/dist/scheduling/engine/verdicts.js +74 -0
  131. package/dist/scheduling/index.d.ts +10 -0
  132. package/dist/scheduling/index.d.ts.map +1 -0
  133. package/dist/scheduling/index.js +29 -0
  134. package/dist/scheduling/model.d.ts +53 -0
  135. package/dist/scheduling/model.d.ts.map +1 -0
  136. package/dist/scheduling/model.js +379 -0
  137. package/dist/scheduling/operations.d.ts +134 -0
  138. package/dist/scheduling/operations.d.ts.map +1 -0
  139. package/dist/scheduling/operations.js +376 -0
  140. package/dist/scheduling/provenance.d.ts +33 -0
  141. package/dist/scheduling/provenance.d.ts.map +1 -0
  142. package/dist/scheduling/provenance.js +70 -0
  143. package/dist/scheduling/rules.d.ts +23 -0
  144. package/dist/scheduling/rules.d.ts.map +1 -0
  145. package/dist/scheduling/rules.js +37 -0
  146. package/dist/scheduling/scheduler.class.d.ts +24 -0
  147. package/dist/scheduling/scheduler.class.d.ts.map +1 -0
  148. package/dist/scheduling/scheduler.class.js +150 -0
  149. package/dist/scheduling/time.d.ts +132 -0
  150. package/dist/scheduling/time.d.ts.map +1 -0
  151. package/dist/scheduling/time.js +256 -0
  152. package/dist/scheduling/types.d.ts +932 -0
  153. package/dist/scheduling/types.d.ts.map +1 -0
  154. package/dist/scheduling/types.js +19 -0
  155. package/dist/scoring/match-score.d.ts.map +1 -1
  156. package/dist/scoring/match-score.js +1 -3
  157. package/dist/types/matcher.d.ts +195 -1
  158. package/dist/types/matcher.d.ts.map +1 -1
  159. package/dist/utils/keys.d.ts +3 -0
  160. package/dist/utils/keys.d.ts.map +1 -1
  161. package/dist/utils/keys.js +15 -0
  162. package/dist/validation/assignment-lint.d.ts +24 -0
  163. package/dist/validation/assignment-lint.d.ts.map +1 -0
  164. package/dist/validation/assignment-lint.js +132 -0
  165. package/package.json +4 -2
@@ -0,0 +1,379 @@
1
+ "use strict";
2
+ /**
3
+ * Model normalization — pure logic.
4
+ *
5
+ * Turns the caller-facing `ScheduleInput` into the fully-indexed `ModelContext`
6
+ * the engine and constraints operate on: shift templates are expanded into
7
+ * dated shift instances (unique `(templateId, date)` ids, so same-named shifts
8
+ * on different days never collide), wall-clock times are resolved through a
9
+ * DST-correct `PeriodClock`, employee time-off becomes blocked minute
10
+ * intervals, per-person rule overrides are merged, and pre-period history is
11
+ * seeded onto person timelines. Everything is side-effect free; the scheduler
12
+ * facade owns sequencing.
13
+ *
14
+ * Two normalizations here carry legal weight and are easy to miss:
15
+ *
16
+ * - **Working minutes ≠ elapsed minutes.** Unpaid breaks come off, and a duty
17
+ * classification can scale the rest. Hour budgets and rolling averages must
18
+ * use working minutes; rest gaps must use the elapsed span.
19
+ * - **Person, not contract.** Rest and window rules aggregate on `personId`
20
+ * (CJEU C-585/19), which defaults to the employee id but must be shared by
21
+ * records belonging to one human.
22
+ *
23
+ * Differences from legacy: the Python solver parsed `"YYYY-MM-DDTHH:MM:SS"`
24
+ * strings, wrapped overnight durations in `abs()`, deduped shift *names* across
25
+ * days, and read only the first key of each time-off entry. All of those are
26
+ * modeled properly here.
27
+ */
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.MINUTES_PER_DAY = exports.availabilityApplies = exports.buildModel = exports.resolveConstraints = exports.mergeRules = exports.expandTemplate = exports.addDays = exports.daysBetween = void 0;
30
+ const types_1 = require("./types");
31
+ const constraint_1 = require("./constraints/constraint");
32
+ const min_rest_1 = require("./constraints/min-rest");
33
+ const overtime_1 = require("./constraints/overtime");
34
+ const time_1 = require("./time");
35
+ Object.defineProperty(exports, "MINUTES_PER_DAY", { enumerable: true, get: function () { return time_1.MINUTES_PER_DAY; } });
36
+ var time_2 = require("./time");
37
+ Object.defineProperty(exports, "daysBetween", { enumerable: true, get: function () { return time_2.daysBetween; } });
38
+ Object.defineProperty(exports, "addDays", { enumerable: true, get: function () { return time_2.addDays; } });
39
+ /** Expand one template into its dated instances inside the period. */
40
+ function expandTemplate(template, clock, periodDays, context) {
41
+ if (!template.id)
42
+ throw new types_1.ScheduleValidationError('Shift template is missing `id`');
43
+ if (template.dates && template.daysOfWeek) {
44
+ throw new types_1.ScheduleValidationError(`Shift template "${template.id}" sets both dates and daysOfWeek`);
45
+ }
46
+ if (template.minEmployees !== undefined && (!Number.isInteger(template.minEmployees) || template.minEmployees < 0)) {
47
+ throw new types_1.ScheduleValidationError(`Shift template "${template.id}" has invalid minEmployees`);
48
+ }
49
+ if (template.maxEmployees !== undefined &&
50
+ (!Number.isInteger(template.maxEmployees) || template.maxEmployees < (template.minEmployees ?? 1))) {
51
+ throw new types_1.ScheduleValidationError(`Shift template "${template.id}" has maxEmployees below minEmployees`);
52
+ }
53
+ const startTod = (0, time_1.parseTimeOfDay)(template.startTime, `shift "${template.id}".startTime`);
54
+ const endTodRaw = (0, time_1.parseTimeOfDay)(template.endTime, `shift "${template.id}".endTime`);
55
+ // Overnight shifts roll the end into the next day explicitly; a same-time
56
+ // start/end is treated as a full 24h shift, never zero length.
57
+ const overnight = endTodRaw <= startTod;
58
+ const dates = [];
59
+ if (template.dates) {
60
+ for (const d of template.dates) {
61
+ (0, time_1.assertIsoDate)(d, `shift "${template.id}".dates`);
62
+ const offset = clock.dayIndexOf(d);
63
+ if (offset >= 0 && offset < periodDays)
64
+ dates.push(d);
65
+ }
66
+ }
67
+ else {
68
+ for (let i = 0; i < periodDays; i++) {
69
+ const d = clock.dateAt(i);
70
+ if (!template.daysOfWeek || template.daysOfWeek.includes((0, time_1.isoWeekday)(d)))
71
+ dates.push(d);
72
+ }
73
+ }
74
+ return dates.map((date) => {
75
+ const startMinute = clock.toPeriodMinutes(date, template.startTime, `shift "${template.id}".startTime`);
76
+ const endDate = overnight ? (0, time_1.addDays)(date, 1) : date;
77
+ const endMinute = clock.toPeriodMinutes(endDate, template.endTime, `shift "${template.id}".endTime`);
78
+ // Resolving both ends through the clock means a DST transition inside
79
+ // the shift shortens or lengthens it, exactly as the payroll would.
80
+ const durationMinutes = endMinute - startMinute;
81
+ if (durationMinutes <= 0) {
82
+ throw new types_1.ScheduleValidationError(`Shift template "${template.id}" resolves to a non-positive duration on ${date}`);
83
+ }
84
+ const unpaidBreak = template.unpaidBreakMinutes ?? 0;
85
+ if (unpaidBreak < 0 || unpaidBreak >= durationMinutes) {
86
+ throw new types_1.ScheduleValidationError(`Shift template "${template.id}" has invalid unpaidBreakMinutes`);
87
+ }
88
+ const paidBreak = template.paidBreakMinutes ?? 0;
89
+ if (paidBreak < 0 || unpaidBreak + paidBreak >= durationMinutes) {
90
+ throw new types_1.ScheduleValidationError(`Shift template "${template.id}" has invalid paidBreakMinutes`);
91
+ }
92
+ // A paid break counts as working time, so only the unpaid one is deducted.
93
+ const workingMinutes = workingMinutesFor(durationMinutes - unpaidBreak, template);
94
+ const range = { start: startMinute, end: endMinute };
95
+ const nightMinutes = context.nightRule ? clock.minutesInClockRange(range, context.nightRule.window) : 0;
96
+ const nightThreshold = context.nightRule?.qualifiesAfterMinutes ?? 180;
97
+ return {
98
+ id: `${template.id}@${date}`,
99
+ templateId: template.id,
100
+ name: template.name,
101
+ date,
102
+ startMinute,
103
+ endMinute,
104
+ durationMinutes,
105
+ workingMinutes,
106
+ paidBreakMinutes: paidBreak,
107
+ minEmployees: template.minEmployees ?? 1,
108
+ maxEmployees: template.maxEmployees,
109
+ tagRequirements: template.tagRequirements ?? {},
110
+ tagMaximums: template.tagMaximums ?? {},
111
+ requiredTags: template.requiredTags ?? [],
112
+ shiftTypeTag: template.shiftTypeTag,
113
+ siteId: template.siteId,
114
+ duty: template.duty,
115
+ nightMinutes,
116
+ isNightShift: nightMinutes >= nightThreshold,
117
+ weekday: (0, time_1.isoWeekday)(date),
118
+ isSunday: (0, time_1.isoWeekday)(date) === 7,
119
+ isPublicHoliday: context.publicHolidays.has(date),
120
+ };
121
+ });
122
+ }
123
+ exports.expandTemplate = expandTemplate;
124
+ /**
125
+ * Working minutes for a duty of `paidSpan` elapsed minutes.
126
+ *
127
+ * A plain shift counts in full. Stand-by may count at a fraction or only for
128
+ * the time actually worked — which of those applies is a legal classification
129
+ * the caller makes and the engine never infers.
130
+ */
131
+ function workingMinutesFor(paidSpan, template) {
132
+ const duty = template.duty;
133
+ if (!duty || duty.countsAsWorkingTime === 'full')
134
+ return paidSpan;
135
+ if (duty.countsAsWorkingTime === 'actualOnly') {
136
+ return Math.min(paidSpan, Math.max(0, duty.expectedActiveMinutes ?? 0));
137
+ }
138
+ const fraction = duty.countsAsWorkingTime;
139
+ if (!Number.isFinite(fraction) || fraction < 0 || fraction > 1) {
140
+ throw new types_1.ScheduleValidationError(`Shift template "${template.id}" has invalid duty.countsAsWorkingTime: ${String(fraction)}`);
141
+ }
142
+ return Math.round(paidSpan * fraction);
143
+ }
144
+ function blockedIntervalsFor(employee, clock, periodDays, instanceById) {
145
+ const out = [];
146
+ for (const entry of employee.timeOff ?? []) {
147
+ (0, time_1.assertIsoDate)(entry.date, `employee "${employee.id}" timeOff`);
148
+ if (entry.shiftInstanceId !== undefined) {
149
+ const inst = instanceById.get(entry.shiftInstanceId);
150
+ if (!inst) {
151
+ throw new types_1.ScheduleValidationError(`Employee "${employee.id}" timeOff references unknown shiftInstanceId "${entry.shiftInstanceId}"`);
152
+ }
153
+ out.push({ start: inst.startMinute, end: inst.endMinute });
154
+ continue;
155
+ }
156
+ const offset = clock.dayIndexOf(entry.date);
157
+ if (offset < 0 || offset >= periodDays)
158
+ continue; // outside the period: irrelevant, not an error
159
+ out.push({ start: clock.dayStartMinutes(offset), end: clock.dayStartMinutes(offset + 1) });
160
+ }
161
+ // External commitments are blackouts the roster may never override
162
+ // (Directive (EU) 2019/1152 Art 9 bars treating parallel employment as
163
+ // schedulable), so they join the same blocked set as time off.
164
+ for (const commitment of employee.externalCommitments ?? []) {
165
+ out.push(spanToMinutes(commitment.from, commitment.to, clock, `employee "${employee.id}" externalCommitments`));
166
+ }
167
+ return out;
168
+ }
169
+ /** Resolve an ISO date or date-time span to period minutes. */
170
+ function spanToMinutes(from, to, clock, field) {
171
+ const parse = (value, endOfDayWhenBare) => {
172
+ const [datePart, timePart] = value.split('T');
173
+ (0, time_1.assertIsoDate)(datePart, field);
174
+ if (timePart)
175
+ return clock.toPeriodMinutes(datePart, timePart.slice(0, 5), field);
176
+ const dayIndex = clock.dayIndexOf(datePart);
177
+ return endOfDayWhenBare ? clock.dayStartMinutes(dayIndex + 1) : clock.dayStartMinutes(dayIndex);
178
+ };
179
+ return { start: parse(from, false), end: parse(to, true) };
180
+ }
181
+ function validateEmployee(employee) {
182
+ if (!employee.id)
183
+ throw new types_1.ScheduleValidationError('Employee is missing `id`');
184
+ for (const [field, value] of [
185
+ ['maxHoursForPeriod', employee.maxHoursForPeriod],
186
+ ['minHoursForPeriod', employee.minHoursForPeriod],
187
+ ['maxShiftDurationMinutes', employee.maxShiftDurationMinutes],
188
+ ]) {
189
+ if (value !== undefined && (!Number.isFinite(value) || value < 0)) {
190
+ throw new types_1.ScheduleValidationError(`Employee "${employee.id}" has invalid ${field}: ${value}`);
191
+ }
192
+ }
193
+ for (const rule of employee.availability ?? []) {
194
+ if (rule.from !== undefined)
195
+ (0, time_1.parseTimeOfDay)(rule.from, `employee "${employee.id}" availability.from`);
196
+ if (rule.to !== undefined)
197
+ (0, time_1.parseTimeOfDay)(rule.to, `employee "${employee.id}" availability.to`);
198
+ if (rule.fromDate !== undefined)
199
+ (0, time_1.assertIsoDate)(rule.fromDate, `employee "${employee.id}" availability.fromDate`);
200
+ if (rule.toDate !== undefined)
201
+ (0, time_1.assertIsoDate)(rule.toDate, `employee "${employee.id}" availability.toDate`);
202
+ }
203
+ for (const q of employee.qualifications ?? []) {
204
+ if (q.validFrom !== undefined)
205
+ (0, time_1.assertIsoDate)(q.validFrom, `employee "${employee.id}" qualifications.validFrom`);
206
+ if (q.validUntil !== undefined)
207
+ (0, time_1.assertIsoDate)(q.validUntil, `employee "${employee.id}" qualifications.validUntil`);
208
+ }
209
+ }
210
+ /**
211
+ * Merge the global rule set with one person's overrides.
212
+ *
213
+ * A shallow per-family merge, not a deep one: a person's `dailyRest` replaces
214
+ * the global `dailyRest` outright. Half-overriding a rule family is how you get
215
+ * a minor who inherits an adult's night window, so the boundary is the family.
216
+ */
217
+ function mergeRules(base, override) {
218
+ if (!base)
219
+ return override ?? {};
220
+ if (!override)
221
+ return base;
222
+ return { ...base, ...override };
223
+ }
224
+ exports.mergeRules = mergeRules;
225
+ /** Resolve built-in constraints with caller hardness/weight overrides, then append customs. */
226
+ function resolveConstraints(options, rules, objectives) {
227
+ const constraints = (0, constraint_1.createDefaultConstraints)({
228
+ minRestMinutes: options?.minRestMinutes ?? rules?.dailyRest?.minMinutes ?? min_rest_1.DEFAULT_MIN_REST_MINUTES,
229
+ oneShiftPerDay: options?.oneShiftPerDay ?? false,
230
+ rules,
231
+ objectives,
232
+ });
233
+ const overrides = options?.overrides ?? {};
234
+ for (const c of constraints) {
235
+ const o = overrides[c.id];
236
+ if (!o)
237
+ continue;
238
+ if (o.hardness !== undefined)
239
+ c.hardness = o.hardness;
240
+ if (o.weight !== undefined)
241
+ c.weight = o.weight;
242
+ }
243
+ return [...constraints, ...(options?.custom ?? [])];
244
+ }
245
+ exports.resolveConstraints = resolveConstraints;
246
+ /** Convert caller history into per-person timeline entries at (usually negative) period minutes. */
247
+ function buildHistory(history, clock, personIdOf) {
248
+ const out = new Map();
249
+ for (const [index, entry] of (history ?? []).entries()) {
250
+ (0, time_1.assertIsoDate)(entry.date, 'history.date');
251
+ const start = clock.toPeriodMinutes(entry.date, entry.startTime, 'history.startTime');
252
+ const endTod = (0, time_1.parseTimeOfDay)(entry.endTime, 'history.endTime');
253
+ const startTod = (0, time_1.parseTimeOfDay)(entry.startTime, 'history.startTime');
254
+ const endDate = endTod <= startTod ? (0, time_1.addDays)(entry.date, 1) : entry.date;
255
+ const end = clock.toPeriodMinutes(endDate, entry.endTime, 'history.endTime');
256
+ const personId = personIdOf.get(entry.employeeId) ?? entry.employeeId;
257
+ const entries = out.get(personId) ?? [];
258
+ entries.push({
259
+ id: entry.id ?? `history:${index}`,
260
+ start,
261
+ end,
262
+ workingMinutes: entry.workingMinutes ?? end - start,
263
+ tag: entry.shiftTypeTag,
264
+ historical: true,
265
+ });
266
+ out.set(personId, entries);
267
+ }
268
+ return out;
269
+ }
270
+ /**
271
+ * Normalize and validate the scheduling problem. Throws
272
+ * `ScheduleValidationError` on malformed input — never a silent wrong schedule.
273
+ */
274
+ function buildModel(input) {
275
+ (0, time_1.assertIsoDate)(input.period.startDate, 'period.startDate');
276
+ (0, time_1.assertIsoDate)(input.period.endDate, 'period.endDate');
277
+ const periodDays = (0, time_1.daysBetween)(input.period.startDate, input.period.endDate) + 1;
278
+ if (periodDays <= 0)
279
+ throw new types_1.ScheduleValidationError('period.endDate must not precede period.startDate');
280
+ const clock = new time_1.PeriodClock(input.period.startDate, periodDays, input.period.timeZone ?? 'UTC');
281
+ const rules = input.rules ?? {};
282
+ const publicHolidays = new Set(input.calendar?.publicHolidays ?? []);
283
+ for (const date of publicHolidays)
284
+ (0, time_1.assertIsoDate)(date, 'calendar.publicHolidays');
285
+ const instances = [];
286
+ const instanceById = new Map();
287
+ for (const template of input.shifts) {
288
+ for (const inst of expandTemplate(template, clock, periodDays, { nightRule: rules.nightWork, publicHolidays })) {
289
+ if (instanceById.has(inst.id))
290
+ throw new types_1.ScheduleValidationError(`Duplicate shift instance id "${inst.id}"`);
291
+ instanceById.set(inst.id, inst);
292
+ instances.push(inst);
293
+ }
294
+ }
295
+ const employeeById = new Map();
296
+ const employeeTags = new Map();
297
+ const employeeBlockedIntervals = new Map();
298
+ const rulesByEmployee = new Map();
299
+ const personIdOf = new Map();
300
+ const employeesOfPerson = new Map();
301
+ for (const employee of input.employees) {
302
+ validateEmployee(employee);
303
+ if (employeeById.has(employee.id))
304
+ throw new types_1.ScheduleValidationError(`Duplicate employee id "${employee.id}"`);
305
+ employeeById.set(employee.id, employee);
306
+ employeeTags.set(employee.id, new Set(employee.tags ?? []));
307
+ employeeBlockedIntervals.set(employee.id, blockedIntervalsFor(employee, clock, periodDays, instanceById));
308
+ // Per-person rule overrides replace whole families, so an override must
309
+ // satisfy the same invariants the global rule was validated against.
310
+ if (employee.rules?.overtime)
311
+ (0, overtime_1.assertValidOvertimeRule)(employee.rules.overtime, `employee "${employee.id}"`);
312
+ rulesByEmployee.set(employee.id, mergeRules(rules, employee.rules));
313
+ const personId = employee.personId ?? employee.id;
314
+ personIdOf.set(employee.id, personId);
315
+ employeesOfPerson.set(personId, [...(employeesOfPerson.get(personId) ?? []), employee.id]);
316
+ }
317
+ const absences = new Map();
318
+ for (const absence of input.absences ?? []) {
319
+ const span = spanToMinutes(absence.from, absence.to, clock, 'absences');
320
+ absences.set(absence.employeeId, [...(absences.get(absence.employeeId) ?? []), { ...span, kind: absence.kind }]);
321
+ // An absence blocks assignment as firmly as time off does.
322
+ const blocked = employeeBlockedIntervals.get(absence.employeeId);
323
+ if (blocked)
324
+ blocked.push(span);
325
+ }
326
+ const publishedPairs = new Set();
327
+ for (const assignment of input.published?.roster ?? []) {
328
+ publishedPairs.add(`${assignment.employeeId}|${assignment.shiftInstanceId}`);
329
+ }
330
+ const pinned = new Set((input.pinned ?? []).map((p) => `${p.employeeId}|${p.shiftInstanceId}`));
331
+ let publishedAtMinute;
332
+ if (input.published?.publishedAt) {
333
+ const [datePart, timePart] = input.published.publishedAt.split('T');
334
+ (0, time_1.assertIsoDate)(datePart, 'published.publishedAt');
335
+ publishedAtMinute = clock.toPeriodMinutes(datePart, (timePart ?? '00:00').slice(0, 5), 'published.publishedAt');
336
+ }
337
+ let asOfMinute;
338
+ if (input.asOf) {
339
+ const [datePart, timePart] = input.asOf.split('T');
340
+ (0, time_1.assertIsoDate)(datePart, 'asOf');
341
+ asOfMinute = clock.toPeriodMinutes(datePart, (timePart ?? '00:00').slice(0, 5), 'asOf');
342
+ }
343
+ return {
344
+ periodStartDate: input.period.startDate,
345
+ periodDays,
346
+ employees: input.employees,
347
+ employeeById,
348
+ employeeTags,
349
+ instances,
350
+ instanceById,
351
+ employeeBlockedIntervals,
352
+ minRestMinutes: input.constraints?.minRestMinutes ?? rules.dailyRest?.minMinutes ?? min_rest_1.DEFAULT_MIN_REST_MINUTES,
353
+ constraints: resolveConstraints(input.constraints, rules, input.objectives),
354
+ clock,
355
+ rules,
356
+ rulesByEmployee,
357
+ personIdOf,
358
+ employeesOfPerson,
359
+ history: buildHistory(input.history, clock, personIdOf),
360
+ publicHolidays,
361
+ absences,
362
+ pinned,
363
+ publishedAtMinute,
364
+ publishedPairs,
365
+ asOfMinute,
366
+ };
367
+ }
368
+ exports.buildModel = buildModel;
369
+ /** Whether an availability rule applies to a shift instance. */
370
+ function availabilityApplies(rule, inst) {
371
+ if (rule.daysOfWeek && !rule.daysOfWeek.includes(inst.weekday))
372
+ return false;
373
+ if (rule.fromDate && inst.date < rule.fromDate)
374
+ return false;
375
+ if (rule.toDate && inst.date > rule.toDate)
376
+ return false;
377
+ return true;
378
+ }
379
+ exports.availabilityApplies = availabilityApplies;
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Operational APIs — the things a roster needs *after* it is built.
3
+ *
4
+ * Rosters are re-solved far more often than they are built, and the questions
5
+ * that arrive at 06:00 are not "give me a month" but "who can cover this, and
6
+ * why not her?". These four entry points answer them against the same
7
+ * constraint set the solver uses, so an answer here can never disagree with the
8
+ * roster the solver would produce.
9
+ *
10
+ * - `checkCompliance` — validate a roster the engine did not build. Human
11
+ * overrides are a legal requirement (GDPR Art 22 gives a right to human
12
+ * intervention), so a hand-edited roster must be re-checkable rather than
13
+ * trusted.
14
+ * - `explainCandidate` — every rule's verdict on one candidate, with numbers.
15
+ * - `repairSchedule` — minimal-perturbation re-plan around a disruption, with
16
+ * a ranked list of who can lawfully be called.
17
+ * - `diagnoseInfeasibility` — why the problem cannot be solved, before it is
18
+ * attempted.
19
+ */
20
+ import type { AssignmentPair, ConstraintViolation, LedgerEntry, RuleVerdict, ScheduleInput, ScheduledAssignment } from './types';
21
+ export interface ComplianceReport {
22
+ compliant: boolean;
23
+ violations: ConstraintViolation[];
24
+ /** Per-assignment verdicts for every rule that had something to say. */
25
+ verdicts: Array<{
26
+ pair: AssignmentPair;
27
+ verdicts: RuleVerdict[];
28
+ }>;
29
+ ledger: LedgerEntry[];
30
+ }
31
+ /**
32
+ * Validate an externally-produced or hand-edited roster.
33
+ *
34
+ * Runs the same constraints as the solver — there is deliberately no second
35
+ * validation path, because two paths drift and the one that drifts is always
36
+ * the one nobody reads.
37
+ */
38
+ export declare function checkCompliance(input: ScheduleInput, roster: ScheduledAssignment[]): ComplianceReport;
39
+ /**
40
+ * Why can — or can't — this person work this shift?
41
+ *
42
+ * A rule-by-rule scan against live state, not a solve. This is the question
43
+ * managers actually ask, and answering it with concrete numbers ("clock-out
44
+ * 22:00, shift starts 06:00, that is 8h against an 11h minimum") is what makes
45
+ * the roster arguable rather than oracular.
46
+ */
47
+ export declare function explainCandidate(input: ScheduleInput, employeeId: string, shiftInstanceId: string, roster?: ScheduledAssignment[]): RuleVerdict[];
48
+ export type Disruption = {
49
+ kind: 'absence';
50
+ employeeId: string;
51
+ from: string;
52
+ to?: string;
53
+ } | {
54
+ kind: 'noShow';
55
+ employeeId: string;
56
+ shiftInstanceId: string;
57
+ } | {
58
+ kind: 'cancelShift';
59
+ shiftInstanceId: string;
60
+ };
61
+ export interface RepairCandidate {
62
+ employeeId: string;
63
+ shiftInstanceId: string;
64
+ eligible: boolean;
65
+ verdicts: RuleVerdict[];
66
+ /** Failing rules only, for a compact "why not" list. */
67
+ blockers: RuleVerdict[];
68
+ marginalCostCents: number;
69
+ /** How far below their fair share of extra work this person is. Higher means more owed. */
70
+ fairnessDebt: number;
71
+ /** Lower is a better call. */
72
+ rank: number;
73
+ rationale: string;
74
+ }
75
+ export interface RepairResult {
76
+ diff: {
77
+ added: AssignmentPair[];
78
+ removed: AssignmentPair[];
79
+ };
80
+ candidates: RepairCandidate[];
81
+ violationsIntroduced: ConstraintViolation[];
82
+ perturbation: {
83
+ changedAssignments: number;
84
+ affectedEmployees: number;
85
+ };
86
+ }
87
+ /**
88
+ * Re-plan around a disruption, changing as little as possible.
89
+ *
90
+ * Everything not touched by the disruption is pinned, so the answer is a *diff*
91
+ * a manager can act on rather than a fresh roster nobody recognises. A full
92
+ * re-solve at 06:00 returns a different schedule for the whole team, which is
93
+ * not an answer anyone will accept.
94
+ *
95
+ * The candidate list is a ranked scan, not a solve — that is what keeps it
96
+ * interactive, and it is also the more useful output: the gap is filled by
97
+ * phoning someone, so the operator needs an ordered list with reasons, not a
98
+ * single name.
99
+ */
100
+ export declare function repairSchedule(input: ScheduleInput, disruption: Disruption, published: ScheduledAssignment[]): RepairResult;
101
+ /**
102
+ * Rank everyone who could take an open shift.
103
+ *
104
+ * The hard gate and the soft ordering are kept separate on purpose: an
105
+ * ineligible person is *never* promoted by being cheap, and the reason they are
106
+ * ineligible is still reported, because "Anna would be ideal but is 2h short on
107
+ * rest" is more useful than Anna's silent absence from the list.
108
+ *
109
+ * Ordering uses cost, fairness debt and stated preference — all facts about
110
+ * declared data and realised assignments. No reliability score, no acceptance
111
+ * history, no no-show prediction: those would make this profiling under AI Act
112
+ * Annex III point 4(b), which is high-risk with no narrow-task exemption.
113
+ */
114
+ export declare function rankCandidates(input: ScheduleInput, shiftInstanceId: string, roster: ScheduledAssignment[], disruption?: Disruption): RepairCandidate[];
115
+ export interface InfeasibilityReport {
116
+ feasible: boolean;
117
+ findings: Array<{
118
+ kind: 'noEligibleEmployee' | 'insufficientCapacity' | 'tagCapacity';
119
+ message: string;
120
+ shiftInstanceId?: string;
121
+ tag?: string;
122
+ shortfall?: number;
123
+ }>;
124
+ }
125
+ /**
126
+ * Why the problem cannot be solved, before spending a search budget on it.
127
+ *
128
+ * Cheap arithmetic catches most real infeasibility: total demand against total
129
+ * available capacity, per tag. "You are 24 registered-nurse-hours short on
130
+ * Tuesday to Thursday nights" starts a conversation; "no solution found" ends
131
+ * one.
132
+ */
133
+ export declare function diagnoseInfeasibility(input: ScheduleInput): InfeasibilityReport;
134
+ //# sourceMappingURL=operations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operations.d.ts","sourceRoot":"","sources":["../../src/scheduling/operations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EACR,cAAc,EACd,mBAAmB,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