assignment-user-matcher 1.9.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.
- package/README.md +106 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +19 -1
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +11 -0
- package/dist/scheduling/constraints/availability.d.ts +44 -0
- package/dist/scheduling/constraints/availability.d.ts.map +1 -0
- package/dist/scheduling/constraints/availability.js +142 -0
- package/dist/scheduling/constraints/consecutive.d.ts +25 -0
- package/dist/scheduling/constraints/consecutive.d.ts.map +1 -0
- package/dist/scheduling/constraints/consecutive.js +215 -0
- package/dist/scheduling/constraints/constraint.d.ts +35 -0
- package/dist/scheduling/constraints/constraint.d.ts.map +1 -0
- package/dist/scheduling/constraints/constraint.js +97 -0
- package/dist/scheduling/constraints/contract.d.ts +21 -0
- package/dist/scheduling/constraints/contract.d.ts.map +1 -0
- package/dist/scheduling/constraints/contract.js +106 -0
- package/dist/scheduling/constraints/cost.d.ts +18 -0
- package/dist/scheduling/constraints/cost.d.ts.map +1 -0
- package/dist/scheduling/constraints/cost.js +65 -0
- package/dist/scheduling/constraints/daily-rest.d.ts +22 -0
- package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -0
- package/dist/scheduling/constraints/daily-rest.js +118 -0
- package/dist/scheduling/constraints/duty-quota.d.ts +20 -0
- package/dist/scheduling/constraints/duty-quota.d.ts.map +1 -0
- package/dist/scheduling/constraints/duty-quota.js +95 -0
- package/dist/scheduling/constraints/engagement-floor.d.ts +28 -0
- package/dist/scheduling/constraints/engagement-floor.d.ts.map +1 -0
- package/dist/scheduling/constraints/engagement-floor.js +79 -0
- package/dist/scheduling/constraints/fairness.d.ts +34 -0
- package/dist/scheduling/constraints/fairness.d.ts.map +1 -0
- package/dist/scheduling/constraints/fairness.js +149 -0
- package/dist/scheduling/constraints/group-composition.d.ts +19 -0
- package/dist/scheduling/constraints/group-composition.d.ts.map +1 -0
- package/dist/scheduling/constraints/group-composition.js +92 -0
- package/dist/scheduling/constraints/hour-budget.d.ts +13 -0
- package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -0
- package/dist/scheduling/constraints/hour-budget.js +59 -0
- package/dist/scheduling/constraints/in-shift-breaks.d.ts +24 -0
- package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -0
- package/dist/scheduling/constraints/in-shift-breaks.js +97 -0
- package/dist/scheduling/constraints/intervals.d.ts +5 -0
- package/dist/scheduling/constraints/intervals.d.ts.map +1 -0
- package/dist/scheduling/constraints/intervals.js +17 -0
- package/dist/scheduling/constraints/max-shift-duration.d.ts +7 -0
- package/dist/scheduling/constraints/max-shift-duration.d.ts.map +1 -0
- package/dist/scheduling/constraints/max-shift-duration.js +38 -0
- package/dist/scheduling/constraints/min-rest.d.ts +22 -0
- package/dist/scheduling/constraints/min-rest.d.ts.map +1 -0
- package/dist/scheduling/constraints/min-rest.js +60 -0
- package/dist/scheduling/constraints/min-staffing.d.ts +14 -0
- package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -0
- package/dist/scheduling/constraints/min-staffing.js +59 -0
- package/dist/scheduling/constraints/night-work.d.ts +24 -0
- package/dist/scheduling/constraints/night-work.d.ts.map +1 -0
- package/dist/scheduling/constraints/night-work.js +163 -0
- package/dist/scheduling/constraints/no-overlap.d.ts +7 -0
- package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -0
- package/dist/scheduling/constraints/no-overlap.js +36 -0
- package/dist/scheduling/constraints/notice.d.ts +44 -0
- package/dist/scheduling/constraints/notice.d.ts.map +1 -0
- package/dist/scheduling/constraints/notice.js +140 -0
- package/dist/scheduling/constraints/one-shift-per-day.d.ts +7 -0
- package/dist/scheduling/constraints/one-shift-per-day.d.ts.map +1 -0
- package/dist/scheduling/constraints/one-shift-per-day.js +35 -0
- package/dist/scheduling/constraints/overtime.d.ts +47 -0
- package/dist/scheduling/constraints/overtime.d.ts.map +1 -0
- package/dist/scheduling/constraints/overtime.js +149 -0
- package/dist/scheduling/constraints/protections.d.ts +21 -0
- package/dist/scheduling/constraints/protections.d.ts.map +1 -0
- package/dist/scheduling/constraints/protections.js +93 -0
- package/dist/scheduling/constraints/qualification.d.ts +18 -0
- package/dist/scheduling/constraints/qualification.d.ts.map +1 -0
- package/dist/scheduling/constraints/qualification.js +78 -0
- package/dist/scheduling/constraints/rest-days.d.ts +30 -0
- package/dist/scheduling/constraints/rest-days.d.ts.map +1 -0
- package/dist/scheduling/constraints/rest-days.js +133 -0
- package/dist/scheduling/constraints/rolling-hours.d.ts +24 -0
- package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -0
- package/dist/scheduling/constraints/rolling-hours.js +147 -0
- package/dist/scheduling/constraints/start-interval.d.ts +20 -0
- package/dist/scheduling/constraints/start-interval.d.ts.map +1 -0
- package/dist/scheduling/constraints/start-interval.js +53 -0
- package/dist/scheduling/constraints/support.d.ts +48 -0
- package/dist/scheduling/constraints/support.d.ts.map +1 -0
- package/dist/scheduling/constraints/support.js +97 -0
- package/dist/scheduling/constraints/time-off.d.ts +7 -0
- package/dist/scheduling/constraints/time-off.d.ts.map +1 -0
- package/dist/scheduling/constraints/time-off.js +42 -0
- package/dist/scheduling/constraints/weekly-rest.d.ts +22 -0
- package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -0
- package/dist/scheduling/constraints/weekly-rest.js +92 -0
- package/dist/scheduling/cost.d.ts +56 -0
- package/dist/scheduling/cost.d.ts.map +1 -0
- package/dist/scheduling/cost.js +120 -0
- package/dist/scheduling/engine/construction.d.ts +22 -0
- package/dist/scheduling/engine/construction.d.ts.map +1 -0
- package/dist/scheduling/engine/construction.js +97 -0
- package/dist/scheduling/engine/explain.d.ts +12 -0
- package/dist/scheduling/engine/explain.d.ts.map +1 -0
- package/dist/scheduling/engine/explain.js +24 -0
- package/dist/scheduling/engine/objective.d.ts +73 -0
- package/dist/scheduling/engine/objective.d.ts.map +1 -0
- package/dist/scheduling/engine/objective.js +164 -0
- package/dist/scheduling/engine/prng.d.ts +5 -0
- package/dist/scheduling/engine/prng.d.ts.map +1 -0
- package/dist/scheduling/engine/prng.js +24 -0
- package/dist/scheduling/engine/propagation.d.ts +19 -0
- package/dist/scheduling/engine/propagation.d.ts.map +1 -0
- package/dist/scheduling/engine/propagation.js +40 -0
- package/dist/scheduling/engine/search.d.ts +50 -0
- package/dist/scheduling/engine/search.d.ts.map +1 -0
- package/dist/scheduling/engine/search.js +127 -0
- package/dist/scheduling/engine/state.d.ts +28 -0
- package/dist/scheduling/engine/state.d.ts.map +1 -0
- package/dist/scheduling/engine/state.js +96 -0
- package/dist/scheduling/engine/timeline.d.ts +179 -0
- package/dist/scheduling/engine/timeline.d.ts.map +1 -0
- package/dist/scheduling/engine/timeline.js +416 -0
- package/dist/scheduling/engine/verdicts.d.ts +18 -0
- package/dist/scheduling/engine/verdicts.d.ts.map +1 -0
- package/dist/scheduling/engine/verdicts.js +74 -0
- package/dist/scheduling/index.d.ts +10 -0
- package/dist/scheduling/index.d.ts.map +1 -0
- package/dist/scheduling/index.js +29 -0
- package/dist/scheduling/model.d.ts +53 -0
- package/dist/scheduling/model.d.ts.map +1 -0
- package/dist/scheduling/model.js +379 -0
- package/dist/scheduling/operations.d.ts +134 -0
- package/dist/scheduling/operations.d.ts.map +1 -0
- package/dist/scheduling/operations.js +376 -0
- package/dist/scheduling/provenance.d.ts +33 -0
- package/dist/scheduling/provenance.d.ts.map +1 -0
- package/dist/scheduling/provenance.js +70 -0
- package/dist/scheduling/rules.d.ts +23 -0
- package/dist/scheduling/rules.d.ts.map +1 -0
- package/dist/scheduling/rules.js +37 -0
- package/dist/scheduling/scheduler.class.d.ts +24 -0
- package/dist/scheduling/scheduler.class.d.ts.map +1 -0
- package/dist/scheduling/scheduler.class.js +150 -0
- package/dist/scheduling/time.d.ts +132 -0
- package/dist/scheduling/time.d.ts.map +1 -0
- package/dist/scheduling/time.js +256 -0
- package/dist/scheduling/types.d.ts +932 -0
- package/dist/scheduling/types.d.ts.map +1 -0
- package/dist/scheduling/types.js +19 -0
- package/dist/types/matcher.d.ts +15 -0
- package/dist/types/matcher.d.ts.map +1 -1
- package/package.json +4 -2
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Verdict collection — the single place a roster is judged.
|
|
4
|
+
*
|
|
5
|
+
* Both the solver's result assembly and `checkCompliance` run through here.
|
|
6
|
+
* That is deliberate: an earlier version had the solver report only aggregate
|
|
7
|
+
* violations while the compliance check evaluated every pair, so a solve could
|
|
8
|
+
* announce "no hard violations" on a roster the compliance check then rejected.
|
|
9
|
+
* Two judgement paths always drift, and the one that drifts is the one nobody
|
|
10
|
+
* is reading at the time.
|
|
11
|
+
*/
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.collectAggregateViolations = exports.collectPairViolations = exports.verdictsFor = void 0;
|
|
14
|
+
/** Every rule's verdict on one pair, in registry order. */
|
|
15
|
+
function verdictsFor(state, pair) {
|
|
16
|
+
const out = [];
|
|
17
|
+
for (const constraint of state.ctx.constraints) {
|
|
18
|
+
if (constraint.verdict) {
|
|
19
|
+
out.push(constraint.verdict(state, pair));
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
// Rules predating the structured SPI still contribute, through their
|
|
23
|
+
// delta/explain pair, so no rule is silently skipped.
|
|
24
|
+
const breach = constraint.delta(state, pair);
|
|
25
|
+
const message = constraint.explain(state, pair);
|
|
26
|
+
out.push({
|
|
27
|
+
ruleId: constraint.id,
|
|
28
|
+
pass: breach === 0,
|
|
29
|
+
severity: constraint.hardness,
|
|
30
|
+
message: message ?? `satisfies ${constraint.id}`,
|
|
31
|
+
citation: constraint.citation,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
exports.verdictsFor = verdictsFor;
|
|
37
|
+
/** Breaches attributable to individual assignments in the committed roster. */
|
|
38
|
+
function collectPairViolations(state) {
|
|
39
|
+
const out = [];
|
|
40
|
+
for (const [shiftInstanceId, employees] of state.assignments) {
|
|
41
|
+
for (const employeeId of employees) {
|
|
42
|
+
for (const v of verdictsFor(state, { employeeId, shiftInstanceId })) {
|
|
43
|
+
if (v.pass)
|
|
44
|
+
continue;
|
|
45
|
+
out.push({
|
|
46
|
+
constraintId: v.ruleId,
|
|
47
|
+
severity: v.severity,
|
|
48
|
+
employeeId,
|
|
49
|
+
shiftInstanceId,
|
|
50
|
+
message: v.message,
|
|
51
|
+
citation: v.citation,
|
|
52
|
+
actual: v.actual,
|
|
53
|
+
required: v.required,
|
|
54
|
+
unit: v.unit,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
exports.collectPairViolations = collectPairViolations;
|
|
62
|
+
/** Breaches only a whole-roster view can see: coverage, quotas, team fairness. */
|
|
63
|
+
function collectAggregateViolations(state) {
|
|
64
|
+
const out = [];
|
|
65
|
+
for (const constraint of state.ctx.constraints) {
|
|
66
|
+
if (!constraint.evaluate)
|
|
67
|
+
continue;
|
|
68
|
+
for (const violation of constraint.evaluate(state)) {
|
|
69
|
+
out.push({ citation: constraint.citation, ...violation });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
exports.collectAggregateViolations = collectAggregateViolations;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Public surface of the scheduling module. */
|
|
2
|
+
export { ShiftScheduler, solveSchedule, ENGINE_VERSION } from './scheduler.class';
|
|
3
|
+
export { ScheduleValidationError } from './types';
|
|
4
|
+
/** Directive 2003/88/EC Art 3 floor (11h), the default when `minRestMinutes` is omitted. */
|
|
5
|
+
export { DEFAULT_MIN_REST_MINUTES } from './constraints/min-rest';
|
|
6
|
+
export { checkCompliance, explainCandidate, repairSchedule, rankCandidates, diagnoseInfeasibility, type ComplianceReport, type Disruption, type RepairCandidate, type RepairResult, type InfeasibilityReport, } from './operations';
|
|
7
|
+
export { PeriodClock, type MinuteRange, type ClockRange } from './time';
|
|
8
|
+
export { hours, days, weeklyAverageOver } from './rules';
|
|
9
|
+
export type { AssignmentPair, AvailabilityRule, BreakRule, ClockRangeConfig, ConsecutiveRule, ConstraintOptions, ConstraintViolation, DailyRestRule, DutyClassification, DutyQuota, Employee, EmployeeContract, EmployeeCost, EmployeeProtection, EngagementRule, FairnessRule, HistoricalAssignment, LedgerEntry, ModelContext, NightVolumeQuota, NightWorkRule, NoticeRule, ObjectiveWeights, OvertimeRule, Qualification, RestDayRule, RollingAverage, RuleVerdict, ScheduleInput, ScheduleProvenance, ScheduleResult, ScheduledAssignment, SchedulingConstraint, SearchState, Severity, ShiftInstance, ShiftTemplate, TimeOffEntry, WeeklyRestRule, WorkingTimeLimits, WorkingTimeRules, } from './types';
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/scheduling/index.ts"],"names":[],"mappings":"AAAA,+CAA+C;AAC/C,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAClF,OAAO,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAC;AAClD,4FAA4F;AAC5F,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAGlE,OAAO,EACH,eAAe,EACf,gBAAgB,EAChB,cAAc,EACd,cAAc,EACd,qBAAqB,EACrB,KAAK,gBAAgB,EACrB,KAAK,UAAU,EACf,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,mBAAmB,GAC3B,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,WAAW,EAAE,KAAK,WAAW,EAAE,KAAK,UAAU,EAAE,MAAM,QAAQ,CAAC;AAIxE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEzD,YAAY,EACR,cAAc,EACd,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EACjB,mBAAmB,EACnB,aAAa,EACb,kBAAkB,EAClB,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,cAAc,EACd,YAAY,EACZ,oBAAoB,EACpB,WAAW,EACX,YAAY,EACZ,gBAAgB,EAChB,aAAa,EACb,UAAU,EACV,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,WAAW,EACX,cAAc,EACd,WAAW,EACX,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,mBAAmB,EACnB,oBAAoB,EACpB,WAAW,EACX,QAAQ,EACR,aAAa,EACb,aAAa,EACb,YAAY,EACZ,cAAc,EACd,iBAAiB,EACjB,gBAAgB,GACnB,MAAM,SAAS,CAAC"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.weeklyAverageOver = exports.days = exports.hours = exports.PeriodClock = exports.diagnoseInfeasibility = exports.rankCandidates = exports.repairSchedule = exports.explainCandidate = exports.checkCompliance = exports.DEFAULT_MIN_REST_MINUTES = exports.ScheduleValidationError = exports.ENGINE_VERSION = exports.solveSchedule = exports.ShiftScheduler = void 0;
|
|
4
|
+
/** Public surface of the scheduling module. */
|
|
5
|
+
var scheduler_class_1 = require("./scheduler.class");
|
|
6
|
+
Object.defineProperty(exports, "ShiftScheduler", { enumerable: true, get: function () { return scheduler_class_1.ShiftScheduler; } });
|
|
7
|
+
Object.defineProperty(exports, "solveSchedule", { enumerable: true, get: function () { return scheduler_class_1.solveSchedule; } });
|
|
8
|
+
Object.defineProperty(exports, "ENGINE_VERSION", { enumerable: true, get: function () { return scheduler_class_1.ENGINE_VERSION; } });
|
|
9
|
+
var types_1 = require("./types");
|
|
10
|
+
Object.defineProperty(exports, "ScheduleValidationError", { enumerable: true, get: function () { return types_1.ScheduleValidationError; } });
|
|
11
|
+
/** Directive 2003/88/EC Art 3 floor (11h), the default when `minRestMinutes` is omitted. */
|
|
12
|
+
var min_rest_1 = require("./constraints/min-rest");
|
|
13
|
+
Object.defineProperty(exports, "DEFAULT_MIN_REST_MINUTES", { enumerable: true, get: function () { return min_rest_1.DEFAULT_MIN_REST_MINUTES; } });
|
|
14
|
+
// Operational APIs: validate, explain, repair, diagnose.
|
|
15
|
+
var operations_1 = require("./operations");
|
|
16
|
+
Object.defineProperty(exports, "checkCompliance", { enumerable: true, get: function () { return operations_1.checkCompliance; } });
|
|
17
|
+
Object.defineProperty(exports, "explainCandidate", { enumerable: true, get: function () { return operations_1.explainCandidate; } });
|
|
18
|
+
Object.defineProperty(exports, "repairSchedule", { enumerable: true, get: function () { return operations_1.repairSchedule; } });
|
|
19
|
+
Object.defineProperty(exports, "rankCandidates", { enumerable: true, get: function () { return operations_1.rankCandidates; } });
|
|
20
|
+
Object.defineProperty(exports, "diagnoseInfeasibility", { enumerable: true, get: function () { return operations_1.diagnoseInfeasibility; } });
|
|
21
|
+
// Time model, exported so hosts can resolve the same wall-clock the engine does.
|
|
22
|
+
var time_1 = require("./time");
|
|
23
|
+
Object.defineProperty(exports, "PeriodClock", { enumerable: true, get: function () { return time_1.PeriodClock; } });
|
|
24
|
+
// Rule-authoring arithmetic (no jurisdiction values, just the conversions
|
|
25
|
+
// people get wrong — notably weekly-average → rolling-window-total).
|
|
26
|
+
var rules_1 = require("./rules");
|
|
27
|
+
Object.defineProperty(exports, "hours", { enumerable: true, get: function () { return rules_1.hours; } });
|
|
28
|
+
Object.defineProperty(exports, "days", { enumerable: true, get: function () { return rules_1.days; } });
|
|
29
|
+
Object.defineProperty(exports, "weeklyAverageOver", { enumerable: true, get: function () { return rules_1.weeklyAverageOver; } });
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model normalization — pure logic.
|
|
3
|
+
*
|
|
4
|
+
* Turns the caller-facing `ScheduleInput` into the fully-indexed `ModelContext`
|
|
5
|
+
* the engine and constraints operate on: shift templates are expanded into
|
|
6
|
+
* dated shift instances (unique `(templateId, date)` ids, so same-named shifts
|
|
7
|
+
* on different days never collide), wall-clock times are resolved through a
|
|
8
|
+
* DST-correct `PeriodClock`, employee time-off becomes blocked minute
|
|
9
|
+
* intervals, per-person rule overrides are merged, and pre-period history is
|
|
10
|
+
* seeded onto person timelines. Everything is side-effect free; the scheduler
|
|
11
|
+
* facade owns sequencing.
|
|
12
|
+
*
|
|
13
|
+
* Two normalizations here carry legal weight and are easy to miss:
|
|
14
|
+
*
|
|
15
|
+
* - **Working minutes ≠ elapsed minutes.** Unpaid breaks come off, and a duty
|
|
16
|
+
* classification can scale the rest. Hour budgets and rolling averages must
|
|
17
|
+
* use working minutes; rest gaps must use the elapsed span.
|
|
18
|
+
* - **Person, not contract.** Rest and window rules aggregate on `personId`
|
|
19
|
+
* (CJEU C-585/19), which defaults to the employee id but must be shared by
|
|
20
|
+
* records belonging to one human.
|
|
21
|
+
*
|
|
22
|
+
* Differences from legacy: the Python solver parsed `"YYYY-MM-DDTHH:MM:SS"`
|
|
23
|
+
* strings, wrapped overnight durations in `abs()`, deduped shift *names* across
|
|
24
|
+
* days, and read only the first key of each time-off entry. All of those are
|
|
25
|
+
* modeled properly here.
|
|
26
|
+
*/
|
|
27
|
+
import type { AvailabilityRule, ConstraintOptions, ModelContext, ObjectiveWeights, ScheduleInput, SchedulingConstraint, ShiftInstance, ShiftTemplate, WorkingTimeRules } from './types';
|
|
28
|
+
import { PeriodClock, MINUTES_PER_DAY } from './time';
|
|
29
|
+
export { daysBetween, addDays } from './time';
|
|
30
|
+
/** Expand one template into its dated instances inside the period. */
|
|
31
|
+
export declare function expandTemplate(template: ShiftTemplate, clock: PeriodClock, periodDays: number, context: {
|
|
32
|
+
nightRule?: WorkingTimeRules['nightWork'];
|
|
33
|
+
publicHolidays: Set<string>;
|
|
34
|
+
}): ShiftInstance[];
|
|
35
|
+
/**
|
|
36
|
+
* Merge the global rule set with one person's overrides.
|
|
37
|
+
*
|
|
38
|
+
* A shallow per-family merge, not a deep one: a person's `dailyRest` replaces
|
|
39
|
+
* the global `dailyRest` outright. Half-overriding a rule family is how you get
|
|
40
|
+
* a minor who inherits an adult's night window, so the boundary is the family.
|
|
41
|
+
*/
|
|
42
|
+
export declare function mergeRules(base: WorkingTimeRules | undefined, override: WorkingTimeRules | undefined): WorkingTimeRules;
|
|
43
|
+
/** Resolve built-in constraints with caller hardness/weight overrides, then append customs. */
|
|
44
|
+
export declare function resolveConstraints(options: ConstraintOptions | undefined, rules?: WorkingTimeRules, objectives?: ObjectiveWeights): SchedulingConstraint[];
|
|
45
|
+
/**
|
|
46
|
+
* Normalize and validate the scheduling problem. Throws
|
|
47
|
+
* `ScheduleValidationError` on malformed input — never a silent wrong schedule.
|
|
48
|
+
*/
|
|
49
|
+
export declare function buildModel(input: ScheduleInput): ModelContext;
|
|
50
|
+
/** Whether an availability rule applies to a shift instance. */
|
|
51
|
+
export declare function availabilityApplies(rule: AvailabilityRule, inst: ShiftInstance): boolean;
|
|
52
|
+
export { MINUTES_PER_DAY };
|
|
53
|
+
//# sourceMappingURL=model.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/scheduling/model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EACR,gBAAgB,EAChB,iBAAiB,EAGjB,YAAY,EACZ,gBAAgB,EAChB,aAAa,EACb,oBAAoB,EACpB,aAAa,EACb,aAAa,EACb,gBAAgB,EACnB,MAAM,SAAS,CAAC;AAMjB,OAAO,EAAE,WAAW,EAAE,eAAe,EAAmE,MAAM,QAAQ,CAAC;AAEvH,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAE9C,sEAAsE;AACtE,wBAAgB,cAAc,CAC1B,QAAQ,EAAE,aAAa,EACvB,KAAK,EAAE,WAAW,EAClB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE;IAAE,SAAS,CAAC,EAAE,gBAAgB,CAAC,WAAW,CAAC,CAAC;IAAC,cAAc,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;CAAE,GACpF,aAAa,EAAE,CAwFjB;AA4FD;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,gBAAgB,GAAG,SAAS,EAAE,QAAQ,EAAE,gBAAgB,GAAG,SAAS,GAAG,gBAAgB,CAIvH;AAED,+FAA+F;AAC/F,wBAAgB,kBAAkB,CAC9B,OAAO,EAAE,iBAAiB,GAAG,SAAS,EACtC,KAAK,CAAC,EAAE,gBAAgB,EACxB,UAAU,CAAC,EAAE,gBAAgB,GAC9B,oBAAoB,EAAE,CAexB;AAgCD;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,aAAa,GAAG,YAAY,CAiG7D;AAED,gEAAgE;AAChE,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,gBAAgB,EAAE,IAAI,EAAE,aAAa,GAAG,OAAO,CAKxF;AAED,OAAO,EAAE,eAAe,EAAE,CAAC"}
|
|
@@ -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;
|