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,149 @@
1
+ "use strict";
2
+ /**
3
+ * Overtime — the ordinary-vs-overtime split.
4
+ *
5
+ * `rolling-hours` caps *total* working time; this rule regulates the overtime
6
+ * portion by itself, which several member states do separately: Estonia's TLS
7
+ * §44 makes overtime conditional on the employee's agreement and compensates it
8
+ * primarily in equal time off, Germany builds the 10-hour day out of 8 ordinary
9
+ * plus averaged surplus, Austria caps overtime hours in their own right.
10
+ *
11
+ * Overtime is defined against an *ordinary baseline*, never inferred: the
12
+ * caller supplies `ordinaryPerDayMinutes` / `ordinaryPerWeekMinutes`, and a
13
+ * person's `contract.weeklyMinutes` overrides the weekly figure — a part-timer
14
+ * on 20 agreed hours starts earning overtime at 20, not at full time. Both
15
+ * measures run over rolling windows anchored on the person's own assignment
16
+ * boundaries, like every other window rule in this module.
17
+ *
18
+ * Three checks, all hard:
19
+ * - consent: with `requiresConsent`, any overtime at all needs the employee's
20
+ * recorded `overtimeConsent`;
21
+ * - a cap on overtime in any rolling 24h;
22
+ * - caps on overtime over longer rolling windows, against the weekly baseline
23
+ * pro-rated to the window.
24
+ *
25
+ * Compensation in time off is not a constraint but a debt: `overtimeLedger`
26
+ * turns each employee's period overtime into a `timeOffInLieu` ledger entry.
27
+ */
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.overtimeLedger = exports.overtime = exports.assertValidOvertimeRule = exports.OVERTIME_CITATION = void 0;
30
+ const types_1 = require("../types");
31
+ const support_1 = require("./support");
32
+ exports.OVERTIME_CITATION = 'National overtime law (e.g. EE Töölepingu seadus §44, DE ArbZG §3)';
33
+ /**
34
+ * Assert an overtime rule can actually be evaluated. Applied to the global rule
35
+ * at registration and to each per-person override in `buildModel` — an override
36
+ * replaces the whole family, so it must stand on its own.
37
+ */
38
+ function assertValidOvertimeRule(rule, owner = 'rules') {
39
+ if (rule.ordinaryPerDayMinutes === undefined && rule.ordinaryPerWeekMinutes === undefined) {
40
+ throw new types_1.ScheduleValidationError(`${owner}: overtime rule needs an ordinary baseline: set ordinaryPerDayMinutes and/or ordinaryPerWeekMinutes`);
41
+ }
42
+ if (rule.maxOvertimePerDayMinutes !== undefined && rule.ordinaryPerDayMinutes === undefined) {
43
+ throw new types_1.ScheduleValidationError(`${owner}: overtime.maxOvertimePerDayMinutes requires ordinaryPerDayMinutes`);
44
+ }
45
+ if (rule.maxOvertimeInWindow?.length && rule.ordinaryPerWeekMinutes === undefined) {
46
+ throw new types_1.ScheduleValidationError(`${owner}: overtime.maxOvertimeInWindow requires ordinaryPerWeekMinutes`);
47
+ }
48
+ }
49
+ exports.assertValidOvertimeRule = assertValidOvertimeRule;
50
+ function overtime(rule) {
51
+ assertValidOvertimeRule(rule);
52
+ return (0, support_1.fromVerdict)({
53
+ id: 'overtime',
54
+ hardness: 'hard',
55
+ weight: 1,
56
+ citation: rule.citation ?? exports.OVERTIME_CITATION,
57
+ verdict(state, pair) {
58
+ const inst = (0, support_1.instanceOf)(state, pair);
59
+ if (!inst)
60
+ return (0, support_1.pass)('overtime', 'unknown shift');
61
+ // Per-person overrides replace the whole family, so a minor or an
62
+ // opted-out worker can carry a stricter (or absent) split.
63
+ const applied = (0, support_1.rulesFor)(state.ctx, pair.employeeId).overtime;
64
+ if (!applied)
65
+ return (0, support_1.pass)('overtime', 'no overtime rule applies to this employee');
66
+ const citation = applied.citation ?? exports.OVERTIME_CITATION;
67
+ const employee = state.ctx.employeeById.get(pair.employeeId);
68
+ const weeklyOrdinary = employee?.contract?.weeklyMinutes ?? applied.ordinaryPerWeekMinutes;
69
+ const timeline = (0, support_1.timelineFor)(state, pair.employeeId);
70
+ const range = (0, support_1.rangeOf)(inst);
71
+ const probe = { ...range, id: (0, support_1.entryIdOf)(pair), workingMinutes: inst.workingMinutes, tag: inst.shiftTypeTag };
72
+ return timeline.withEntry(probe, (t) => {
73
+ const dayOvertime = applied.ordinaryPerDayMinutes === undefined
74
+ ? 0
75
+ : Math.max(0, t.maxWorkingMinutesInAnyWindow(support_1.MINUTES_PER_DAY, pad(range, support_1.MINUTES_PER_DAY)) -
76
+ applied.ordinaryPerDayMinutes);
77
+ const weekSpan = 7 * support_1.MINUTES_PER_DAY;
78
+ const weekOvertime = weeklyOrdinary === undefined
79
+ ? 0
80
+ : Math.max(0, t.maxWorkingMinutesInAnyWindow(weekSpan, pad(range, weekSpan)) - weeklyOrdinary);
81
+ if (applied.requiresConsent && employee?.overtimeConsent !== true) {
82
+ const worst = Math.max(dayOvertime, weekOvertime);
83
+ if (worst > 0) {
84
+ return (0, support_1.fail)('overtime', 'hard', `employee "${pair.employeeId}" would work ${(0, support_1.h)(worst)} of overtime but has not agreed to overtime`, { actual: worst, required: 0, unit: 'minutes', citation });
85
+ }
86
+ }
87
+ if (applied.maxOvertimePerDayMinutes !== undefined && dayOvertime > applied.maxOvertimePerDayMinutes) {
88
+ return (0, support_1.fail)('overtime', 'hard', `employee "${pair.employeeId}" would work ${(0, support_1.h)(dayOvertime)} of overtime in a 24h window, over the ${(0, support_1.h)(applied.maxOvertimePerDayMinutes)} cap`, { actual: dayOvertime, required: applied.maxOvertimePerDayMinutes, unit: 'minutes', citation });
89
+ }
90
+ for (const window of applied.maxOvertimeInWindow ?? []) {
91
+ if (weeklyOrdinary === undefined)
92
+ break;
93
+ const span = window.windowDays * support_1.MINUTES_PER_DAY;
94
+ const worked = t.maxWorkingMinutesInAnyWindow(span, pad(range, span));
95
+ const ordinary = Math.round((weeklyOrdinary * window.windowDays) / 7);
96
+ const windowOvertime = Math.max(0, worked - ordinary);
97
+ if (windowOvertime > window.maxMinutes) {
98
+ const label = window.label ?? `${(0, support_1.h)(window.maxMinutes)} overtime / ${window.windowDays}d`;
99
+ return (0, support_1.fail)('overtime', 'hard', `employee "${pair.employeeId}" would work ${(0, support_1.h)(windowOvertime)} of overtime in some ${window.windowDays}-day window, over the ${label} limit`, { actual: windowOvertime, required: window.maxMinutes, unit: 'minutes', citation });
100
+ }
101
+ }
102
+ return (0, support_1.pass)('overtime', 'within every configured overtime limit', { unit: 'minutes', citation });
103
+ });
104
+ },
105
+ });
106
+ }
107
+ exports.overtime = overtime;
108
+ /** Windows overlapping `range` are the only ones the new shift can worsen. */
109
+ function pad(range, span) {
110
+ return { start: range.start - span, end: range.end + span };
111
+ }
112
+ /**
113
+ * Time-off-in-lieu accrued by the roster: each employee's working minutes past
114
+ * their pro-rated ordinary baseline, where the applied rule compensates
115
+ * overtime in time off.
116
+ *
117
+ * Accrual is per employee record, not per person — the debt is owed under a
118
+ * contract even when working-time *limits* aggregate across contracts. It needs
119
+ * a weekly baseline (contract minutes or `ordinaryPerWeekMinutes`); a purely
120
+ * daily split cannot be pro-rated over a period without inventing a workweek.
121
+ */
122
+ function overtimeLedger(state) {
123
+ const out = [];
124
+ for (const employee of state.ctx.employees) {
125
+ const applied = (0, support_1.rulesFor)(state.ctx, employee.id).overtime;
126
+ if (!applied || applied.compensation !== 'timeOff')
127
+ continue;
128
+ const overtimeMinutes = periodOvertimeMinutes(state, employee, applied);
129
+ if (overtimeMinutes <= 0)
130
+ continue;
131
+ out.push({
132
+ kind: 'timeOffInLieu',
133
+ employeeId: employee.id,
134
+ minutes: overtimeMinutes,
135
+ reason: `${(0, support_1.h)(overtimeMinutes)} of overtime to be compensated by equal time off`,
136
+ citation: applied.citation ?? exports.OVERTIME_CITATION,
137
+ });
138
+ }
139
+ return out;
140
+ }
141
+ exports.overtimeLedger = overtimeLedger;
142
+ /** Working minutes past the pro-rated weekly baseline over the whole period. */
143
+ function periodOvertimeMinutes(state, employee, rule) {
144
+ const weeklyOrdinary = employee.contract?.weeklyMinutes ?? rule.ordinaryPerWeekMinutes;
145
+ if (weeklyOrdinary === undefined)
146
+ return 0;
147
+ const baseline = Math.round((weeklyOrdinary * state.ctx.periodDays) / 7);
148
+ return Math.max(0, (state.minutesByEmployee.get(employee.id) ?? 0) - baseline);
149
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Statutory personal protections.
3
+ *
4
+ * `pregnancyNightExclusion` implements Directive 92/85/EEC Art 7: a pregnant
5
+ * worker or new mother who produces a medical certificate must not be obliged
6
+ * to perform night work. The remedy the Directive mandates is a *transfer to
7
+ * daytime work*, or leave where that is not feasible — not simply an absence.
8
+ * So the engine bars night assignment and records what is owed instead, rather
9
+ * than quietly marking the person unavailable and shrinking the roster.
10
+ *
11
+ * `minor` and `hazardousNight` mostly select stricter values, which belong in
12
+ * `Employee.rules` where they compose with every other rule. What lives here is
13
+ * only what a rule override cannot express: the categorical night bar, and the
14
+ * fallback obligation it creates.
15
+ */
16
+ import type { LedgerEntry, SchedulingConstraint, SearchState } from '../types';
17
+ export declare const PREGNANCY_CITATION = "Directive 92/85/EEC Art 7";
18
+ export declare function protections(): SchedulingConstraint;
19
+ /** Obligations owed to protected workers the roster could not accommodate. */
20
+ export declare function protectionLedger(state: SearchState): LedgerEntry[];
21
+ //# sourceMappingURL=protections.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protections.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/protections.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAuB,WAAW,EAAe,oBAAoB,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAGjH,eAAO,MAAM,kBAAkB,8BAA8B,CAAC;AAE9D,wBAAgB,WAAW,IAAI,oBAAoB,CAsDlD;AAED,8EAA8E;AAC9E,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW,EAAE,CAiBlE"}
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ /**
3
+ * Statutory personal protections.
4
+ *
5
+ * `pregnancyNightExclusion` implements Directive 92/85/EEC Art 7: a pregnant
6
+ * worker or new mother who produces a medical certificate must not be obliged
7
+ * to perform night work. The remedy the Directive mandates is a *transfer to
8
+ * daytime work*, or leave where that is not feasible — not simply an absence.
9
+ * So the engine bars night assignment and records what is owed instead, rather
10
+ * than quietly marking the person unavailable and shrinking the roster.
11
+ *
12
+ * `minor` and `hazardousNight` mostly select stricter values, which belong in
13
+ * `Employee.rules` where they compose with every other rule. What lives here is
14
+ * only what a rule override cannot express: the categorical night bar, and the
15
+ * fallback obligation it creates.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.protectionLedger = exports.protections = exports.PREGNANCY_CITATION = void 0;
19
+ const support_1 = require("./support");
20
+ exports.PREGNANCY_CITATION = 'Directive 92/85/EEC Art 7';
21
+ function protections() {
22
+ const constraint = (0, support_1.fromVerdict)({
23
+ id: 'protections',
24
+ hardness: 'hard',
25
+ weight: 1,
26
+ citation: exports.PREGNANCY_CITATION,
27
+ prune(ctx, eligibility) {
28
+ for (const [employeeId, instances] of eligibility) {
29
+ const employee = ctx.employeeById.get(employeeId);
30
+ if (!employee?.protections?.some((p) => p.kind === 'pregnancyNightExclusion'))
31
+ continue;
32
+ for (const instanceId of [...instances]) {
33
+ if (ctx.instanceById.get(instanceId)?.isNightShift)
34
+ instances.delete(instanceId);
35
+ }
36
+ }
37
+ },
38
+ verdict(state, pair) {
39
+ const inst = (0, support_1.instanceOf)(state, pair);
40
+ const employee = state.ctx.employeeById.get(pair.employeeId);
41
+ if (!inst || !employee?.protections?.length)
42
+ return (0, support_1.pass)('protections', 'no protections registered');
43
+ if (inst.isNightShift && employee.protections.some((p) => p.kind === 'pregnancyNightExclusion')) {
44
+ return (0, support_1.fail)('protections', 'hard', `employee "${pair.employeeId}" is excluded from night work on a medical certificate and cannot take "${inst.id}"`, { citation: exports.PREGNANCY_CITATION });
45
+ }
46
+ return (0, support_1.pass)('protections', 'no protection bars this shift', { citation: exports.PREGNANCY_CITATION });
47
+ },
48
+ });
49
+ // Surface the mandated alternative. A protected worker left with no daytime
50
+ // work has not been accommodated — they have been sidelined, which is the
51
+ // outcome Art 7 exists to prevent.
52
+ constraint.evaluate = (state) => {
53
+ const out = [];
54
+ for (const employee of state.ctx.employees) {
55
+ const protection = employee.protections?.find((p) => p.kind === 'pregnancyNightExclusion');
56
+ if (!protection || protection.fallback !== 'dayShift')
57
+ continue;
58
+ if ((state.byEmployee.get(employee.id)?.size ?? 0) > 0)
59
+ continue;
60
+ out.push({
61
+ constraintId: 'protections',
62
+ severity: 'medium',
63
+ employeeId: employee.id,
64
+ message: `employee "${employee.id}" is excluded from night work and was given no daytime alternative; Art 7 requires a transfer to day work or leave`,
65
+ citation: exports.PREGNANCY_CITATION,
66
+ });
67
+ }
68
+ return out;
69
+ };
70
+ return constraint;
71
+ }
72
+ exports.protections = protections;
73
+ /** Obligations owed to protected workers the roster could not accommodate. */
74
+ function protectionLedger(state) {
75
+ const out = [];
76
+ for (const employee of state.ctx.employees) {
77
+ const protection = employee.protections?.find((p) => p.kind === 'pregnancyNightExclusion');
78
+ if (!protection)
79
+ continue;
80
+ if ((state.byEmployee.get(employee.id)?.size ?? 0) > 0)
81
+ continue;
82
+ out.push({
83
+ kind: 'compensatoryRest',
84
+ employeeId: employee.id,
85
+ reason: protection.fallback === 'leave'
86
+ ? 'night-work exclusion with no daytime work available: leave or extended maternity leave is owed'
87
+ : 'night-work exclusion with no daytime work assigned: a transfer to day work is owed',
88
+ citation: exports.PREGNANCY_CITATION,
89
+ });
90
+ }
91
+ return out;
92
+ }
93
+ exports.protectionLedger = protectionLedger;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Qualifications, valid on the day of the shift.
3
+ *
4
+ * The bug this exists to prevent: a static `Set<string>` of skills silently
5
+ * rosters someone onto a shift after their certificate has lapsed. In
6
+ * healthcare, aviation ground handling, food and security that is a live audit
7
+ * failure, and it is invisible in the roster — the person "has" the skill.
8
+ *
9
+ * So possession is a question about a *date*, not a fact about a person:
10
+ * `hasQualification(employee, tag, date)`, never `hasSkill(employee, tag)`.
11
+ * Tags on `Employee.tags` stay valid for the whole period; anything with an
12
+ * expiry belongs in `qualifications`.
13
+ */
14
+ import type { Employee, SchedulingConstraint } from '../types';
15
+ export declare function qualification(): SchedulingConstraint;
16
+ /** Whether the employee holds `tag` on `date`, by plain tag or dated qualification. */
17
+ export declare function holds(employee: Employee, tag: string, date: string, minLevel?: number): boolean;
18
+ //# sourceMappingURL=qualification.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"qualification.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/qualification.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAe,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAG5E,wBAAgB,aAAa,IAAI,oBAAoB,CA+CpD;AAED,uFAAuF;AACvF,wBAAgB,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAS/F"}
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ /**
3
+ * Qualifications, valid on the day of the shift.
4
+ *
5
+ * The bug this exists to prevent: a static `Set<string>` of skills silently
6
+ * rosters someone onto a shift after their certificate has lapsed. In
7
+ * healthcare, aviation ground handling, food and security that is a live audit
8
+ * failure, and it is invisible in the roster — the person "has" the skill.
9
+ *
10
+ * So possession is a question about a *date*, not a fact about a person:
11
+ * `hasQualification(employee, tag, date)`, never `hasSkill(employee, tag)`.
12
+ * Tags on `Employee.tags` stay valid for the whole period; anything with an
13
+ * expiry belongs in `qualifications`.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.holds = exports.qualification = void 0;
17
+ const support_1 = require("./support");
18
+ function qualification() {
19
+ return (0, support_1.fromVerdict)({
20
+ id: 'qualification',
21
+ hardness: 'hard',
22
+ weight: 1,
23
+ prune(ctx, eligibility) {
24
+ for (const [employeeId, instances] of eligibility) {
25
+ const employee = ctx.employeeById.get(employeeId);
26
+ if (!employee)
27
+ continue;
28
+ for (const instanceId of [...instances]) {
29
+ const inst = ctx.instanceById.get(instanceId);
30
+ if (!inst?.requiredTags.length)
31
+ continue;
32
+ const missing = inst.requiredTags.filter((tag) => !holds(employee, tag, inst.date));
33
+ if (missing.length)
34
+ instances.delete(instanceId);
35
+ }
36
+ }
37
+ },
38
+ verdict(state, pair) {
39
+ const inst = (0, support_1.instanceOf)(state, pair);
40
+ const employee = state.ctx.employeeById.get(pair.employeeId);
41
+ if (!inst || !employee || !inst.requiredTags.length) {
42
+ return (0, support_1.pass)('qualification', 'no qualification requirement');
43
+ }
44
+ const missing = inst.requiredTags.filter((tag) => !holds(employee, tag, inst.date));
45
+ if (missing.length === 0) {
46
+ return (0, support_1.pass)('qualification', `holds ${inst.requiredTags.join(', ')} on ${inst.date}`);
47
+ }
48
+ // Distinguish "never had it" from "had it, expired" — they lead to
49
+ // completely different operational fixes.
50
+ const detail = missing
51
+ .map((tag) => {
52
+ const held = (employee.qualifications ?? []).find((q) => q.tag === tag);
53
+ if (held?.validUntil && held.validUntil < inst.date)
54
+ return `${tag} (expired ${held.validUntil})`;
55
+ if (held?.validFrom && held.validFrom > inst.date)
56
+ return `${tag} (valid from ${held.validFrom})`;
57
+ return tag;
58
+ })
59
+ .join(', ');
60
+ return (0, support_1.fail)('qualification', 'hard', `employee "${pair.employeeId}" lacks ${detail} for "${inst.id}"`, {
61
+ actual: inst.requiredTags.length - missing.length,
62
+ required: inst.requiredTags.length,
63
+ unit: 'count',
64
+ });
65
+ },
66
+ });
67
+ }
68
+ exports.qualification = qualification;
69
+ /** Whether the employee holds `tag` on `date`, by plain tag or dated qualification. */
70
+ function holds(employee, tag, date, minLevel) {
71
+ if (minLevel === undefined && (employee.tags ?? []).includes(tag))
72
+ return true;
73
+ return (employee.qualifications ?? []).some((q) => q.tag === tag &&
74
+ (q.validFrom === undefined || q.validFrom <= date) &&
75
+ (q.validUntil === undefined || q.validUntil >= date) &&
76
+ (minLevel === undefined || (q.level ?? 0) >= minLevel));
77
+ }
78
+ exports.holds = holds;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Sunday, public-holiday and free-Sunday rules.
3
+ *
4
+ * Three distinct shapes live here because national law mixes them freely:
5
+ *
6
+ * - **Outright bars.** Germany prohibits Sunday and holiday work altogether
7
+ * (ArbZG §9) subject to a long exception list; Belgium, Austria, Poland and
8
+ * Portugal work the same way. Whether an exception applies is the caller's
9
+ * call, expressed by leaving `sundayAllowed` unset.
10
+ * - **Free-Sunday quotas.** Germany guarantees at least 15 work-free Sundays a
11
+ * year, the Netherlands 13 per 52 weeks, Poland one in every four. These are
12
+ * counting rules over a calendar predicate, and they can only be judged
13
+ * across the whole roster — a single assignment never breaches them.
14
+ * - **Compensatory rest days.** Sunday or holiday work creates a *dated debt*:
15
+ * a substitute rest day within two weeks in Germany, eight for a holiday;
16
+ * six days either side in Poland. The obligation outlives the roster, so it
17
+ * is reported to the caller as a ledger entry rather than solved for.
18
+ */
19
+ import type { LedgerEntry, RestDayRule, SchedulingConstraint, SearchState } from '../types';
20
+ export declare const SUNDAY_CITATION = "National Sunday/holiday rest law";
21
+ export declare function restDays(rule: RestDayRule): SchedulingConstraint;
22
+ /**
23
+ * Substitute rest days owed for Sunday and public-holiday work.
24
+ *
25
+ * Returned to the caller rather than enforced: the obligation is discharged by
26
+ * granting a day off, often in a period this solve does not cover, so the
27
+ * honest output is a dated debt the operator can act on.
28
+ */
29
+ export declare function compensatoryRestLedger(state: SearchState, rule: RestDayRule | undefined): LedgerEntry[];
30
+ //# sourceMappingURL=rest-days.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rest-days.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/rest-days.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAER,WAAW,EACX,WAAW,EAEX,oBAAoB,EACpB,WAAW,EACd,MAAM,UAAU,CAAC;AAIlB,eAAO,MAAM,eAAe,qCAAqC,CAAC;AAElE,wBAAgB,QAAQ,CAAC,IAAI,EAAE,WAAW,GAAG,oBAAoB,CAgEhE;AAwBD;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,GAAG,SAAS,GAAG,WAAW,EAAE,CAuBvG"}
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ /**
3
+ * Sunday, public-holiday and free-Sunday rules.
4
+ *
5
+ * Three distinct shapes live here because national law mixes them freely:
6
+ *
7
+ * - **Outright bars.** Germany prohibits Sunday and holiday work altogether
8
+ * (ArbZG §9) subject to a long exception list; Belgium, Austria, Poland and
9
+ * Portugal work the same way. Whether an exception applies is the caller's
10
+ * call, expressed by leaving `sundayAllowed` unset.
11
+ * - **Free-Sunday quotas.** Germany guarantees at least 15 work-free Sundays a
12
+ * year, the Netherlands 13 per 52 weeks, Poland one in every four. These are
13
+ * counting rules over a calendar predicate, and they can only be judged
14
+ * across the whole roster — a single assignment never breaches them.
15
+ * - **Compensatory rest days.** Sunday or holiday work creates a *dated debt*:
16
+ * a substitute rest day within two weeks in Germany, eight for a holiday;
17
+ * six days either side in Poland. The obligation outlives the roster, so it
18
+ * is reported to the caller as a ledger entry rather than solved for.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.compensatoryRestLedger = exports.restDays = exports.SUNDAY_CITATION = void 0;
22
+ const time_1 = require("../time");
23
+ const support_1 = require("./support");
24
+ exports.SUNDAY_CITATION = 'National Sunday/holiday rest law';
25
+ function restDays(rule) {
26
+ const constraint = (0, support_1.fromVerdict)({
27
+ id: 'rest-days',
28
+ hardness: 'hard',
29
+ weight: 1,
30
+ citation: exports.SUNDAY_CITATION,
31
+ verdict(state, pair) {
32
+ const inst = (0, support_1.instanceOf)(state, pair);
33
+ if (!inst)
34
+ return (0, support_1.pass)('rest-days', 'unknown shift');
35
+ if (rule.sundayAllowed === false && inst.isSunday) {
36
+ return (0, support_1.fail)('rest-days', 'hard', `Sunday work is not permitted, and "${inst.id}" falls on a Sunday`, {
37
+ citation: exports.SUNDAY_CITATION,
38
+ });
39
+ }
40
+ if (rule.holidayAllowed === false && inst.isPublicHoliday) {
41
+ return (0, support_1.fail)('rest-days', 'hard', `public-holiday work is not permitted, and "${inst.id}" falls on ${inst.date}`, { citation: exports.SUNDAY_CITATION });
42
+ }
43
+ return (0, support_1.pass)('rest-days', 'permitted on this calendar day', { citation: exports.SUNDAY_CITATION });
44
+ },
45
+ });
46
+ // Free-Sunday quotas are team-wide counting rules over the finished roster.
47
+ constraint.evaluate = (state) => {
48
+ const out = [];
49
+ if (!rule.minFreeSundaysPerYear && !rule.minFreeSundaysPer)
50
+ return out;
51
+ const sundays = sundaysInPeriod(state);
52
+ if (sundays.length === 0)
53
+ return out;
54
+ for (const employee of state.ctx.employees) {
55
+ const worked = new Set([...(state.byEmployee.get(employee.id) ?? [])]
56
+ .map((id) => state.ctx.instanceById.get(id))
57
+ .filter((inst) => inst?.isSunday)
58
+ .map((inst) => inst.date));
59
+ const free = sundays.filter((date) => !worked.has(date)).length;
60
+ if (rule.minFreeSundaysPer) {
61
+ // Pro-rate the rolling quota to the period actually being solved,
62
+ // so a 4-week roster is judged against its share, not a year's.
63
+ const windows = sundays.length / rule.minFreeSundaysPer.weeks;
64
+ const required = Math.floor(rule.minFreeSundaysPer.count * windows);
65
+ if (required > 0 && free < required) {
66
+ out.push(quotaViolation(employee.id, free, required, 'rolling'));
67
+ }
68
+ }
69
+ if (rule.minFreeSundaysPerYear !== undefined) {
70
+ const required = Math.floor((rule.minFreeSundaysPerYear * sundays.length) / 52);
71
+ if (required > 0 && free < required) {
72
+ out.push(quotaViolation(employee.id, free, required, 'annual'));
73
+ }
74
+ }
75
+ }
76
+ return out;
77
+ };
78
+ return constraint;
79
+ }
80
+ exports.restDays = restDays;
81
+ function quotaViolation(employeeId, free, required, kind) {
82
+ return {
83
+ constraintId: 'rest-days',
84
+ severity: 'medium',
85
+ employeeId,
86
+ message: `employee "${employeeId}" gets ${free} free Sunday(s) in this period, below the ${required} implied by the ${kind} quota`,
87
+ actual: free,
88
+ required,
89
+ unit: 'count',
90
+ citation: exports.SUNDAY_CITATION,
91
+ };
92
+ }
93
+ function sundaysInPeriod(state) {
94
+ const out = [];
95
+ for (let day = 0; day < state.ctx.periodDays; day++) {
96
+ const date = state.ctx.clock.dateAt(day);
97
+ if (state.ctx.clock.weekdayOfMinute(state.ctx.clock.dayStartMinutes(day)) === 7)
98
+ out.push(date);
99
+ }
100
+ return out;
101
+ }
102
+ /**
103
+ * Substitute rest days owed for Sunday and public-holiday work.
104
+ *
105
+ * Returned to the caller rather than enforced: the obligation is discharged by
106
+ * granting a day off, often in a period this solve does not cover, so the
107
+ * honest output is a dated debt the operator can act on.
108
+ */
109
+ function compensatoryRestLedger(state, rule) {
110
+ const within = rule?.compensatoryRestWithinDays;
111
+ if (!within)
112
+ return [];
113
+ const out = [];
114
+ for (const [instanceId, employees] of state.assignments) {
115
+ const inst = state.ctx.instanceById.get(instanceId);
116
+ if (!inst || employees.size === 0)
117
+ continue;
118
+ const deadlineDays = inst.isPublicHoliday ? within.holiday : inst.isSunday ? within.sunday : undefined;
119
+ if (deadlineDays === undefined)
120
+ continue;
121
+ for (const employeeId of employees) {
122
+ out.push({
123
+ kind: 'substituteRestDay',
124
+ employeeId,
125
+ dueBy: (0, time_1.addDays)(inst.date, deadlineDays),
126
+ reason: `worked "${inst.id}" on ${inst.isPublicHoliday ? 'a public holiday' : 'a Sunday'} (${inst.date})`,
127
+ citation: exports.SUNDAY_CITATION,
128
+ });
129
+ }
130
+ }
131
+ return out;
132
+ }
133
+ exports.compensatoryRestLedger = compensatoryRestLedger;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Working-time volume — Directive 2003/88/EC Art 6 and Art 16(b).
3
+ *
4
+ * The headline EU rule is "average working time for each seven-day period,
5
+ * including overtime, not exceeding 48 hours", averaged over a reference period
6
+ * of up to four months — extensible to six by derogation and twelve by
7
+ * collective agreement.
8
+ *
9
+ * The part that defeats a per-week hour budget: **any** seven-day period, and
10
+ * **any** four-month window. A person can sit under 48h in every calendar week
11
+ * and still average over it across week boundaries, and a fixed quarterly
12
+ * reference period hides an overrun that straddles two quarters. So every limit
13
+ * here is evaluated over rolling windows anchored on the person's own
14
+ * assignment boundaries.
15
+ *
16
+ * Art 16(b) also requires paid annual leave and sick leave to be "not included
17
+ * or neutral" in the average. Counting an absent week as zero hours would drag
18
+ * a person's average down and licence a heavier following week, so neutralised
19
+ * absence shortens the window's divisor instead.
20
+ */
21
+ import type { SchedulingConstraint, WorkingTimeLimits } from '../types';
22
+ export declare const WEEKLY_LIMIT_CITATION = "Directive 2003/88/EC Art 6(b), Art 16(b)";
23
+ export declare function rollingHours(limits: WorkingTimeLimits): SchedulingConstraint;
24
+ //# sourceMappingURL=rolling-hours.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rolling-hours.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/rolling-hours.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAe,oBAAoB,EAAe,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAIlG,eAAO,MAAM,qBAAqB,6CAA6C,CAAC;AAEhF,wBAAgB,YAAY,CAAC,MAAM,EAAE,iBAAiB,GAAG,oBAAoB,CAuE5E"}