assignment-user-matcher 1.16.0 → 1.16.1

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 (33) hide show
  1. package/README.md +22 -12
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/scheduling/constraints/consecutive.d.ts +10 -0
  5. package/dist/scheduling/constraints/consecutive.d.ts.map +1 -1
  6. package/dist/scheduling/constraints/consecutive.js +64 -1
  7. package/dist/scheduling/constraints/contract.d.ts.map +1 -1
  8. package/dist/scheduling/constraints/contract.js +12 -3
  9. package/dist/scheduling/constraints/group-composition.js +2 -2
  10. package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -1
  11. package/dist/scheduling/constraints/min-staffing.js +51 -8
  12. package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -1
  13. package/dist/scheduling/constraints/rolling-hours.js +29 -4
  14. package/dist/scheduling/engine/construction.d.ts.map +1 -1
  15. package/dist/scheduling/engine/construction.js +23 -3
  16. package/dist/scheduling/engine/objective.d.ts.map +1 -1
  17. package/dist/scheduling/engine/objective.js +20 -3
  18. package/dist/scheduling/engine/timeline.d.ts +14 -0
  19. package/dist/scheduling/engine/timeline.d.ts.map +1 -1
  20. package/dist/scheduling/engine/timeline.js +33 -0
  21. package/dist/scheduling/index.d.ts +1 -1
  22. package/dist/scheduling/index.d.ts.map +1 -1
  23. package/dist/scheduling/model.d.ts +6 -1
  24. package/dist/scheduling/model.d.ts.map +1 -1
  25. package/dist/scheduling/model.js +209 -11
  26. package/dist/scheduling/operations.d.ts.map +1 -1
  27. package/dist/scheduling/operations.js +45 -6
  28. package/dist/scheduling/sites.d.ts +1 -1
  29. package/dist/scheduling/sites.d.ts.map +1 -1
  30. package/dist/scheduling/sites.js +34 -1
  31. package/dist/scheduling/types.d.ts +140 -6
  32. package/dist/scheduling/types.d.ts.map +1 -1
  33. package/package.json +11 -2
@@ -8,6 +8,6 @@ export { PeriodClock, type MinuteRange, type ClockRange } from './time';
8
8
  export { expandShiftInstances } from './model';
9
9
  export { hours, days, weeklyAverageOver } from './rules';
10
10
  export { DEFAULT_CONTRACT_HOURS_WEIGHT, contractedPeriodMinutes, fullTimeWeeklyMinutes, resolveContractedWeeklyMinutes, } from './contract-hours';
11
- export type { AssignmentPair, AvailabilityRule, BreakRule, ClockRangeConfig, ConsecutiveRule, ConstraintOptions, ConstraintViolation, ContractHoursRule, ContractHoursSummary, 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, ShiftDemandOverride, Site, SiteIndex, TimeOffEntry, WeeklyRestRule, WorkingTimeLimits, WorkingTimeRules, } from './types';
11
+ export type { AssignmentPair, AvailabilityRule, BreakRule, ClockRangeConfig, ConsecutiveRule, ConstraintOptions, ConstraintViolation, ContractHoursRule, ContractHoursSummary, 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, TagRequirement, ShiftDemandOverride, Site, SiteIndex, TimeOffEntry, WeeklyRestRule, WorkingTimeLimits, WorkingTimeRules, } from './types';
12
12
  export type { PersonTimeline, TimelineEntry, TimelineIndex } from './engine/timeline';
13
13
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.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,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,cAAc,EACd,mBAAmB,EACnB,IAAI,EACJ,SAAS,EACT,YAAY,EACZ,cAAc,EACd,iBAAiB,EACjB,gBAAgB,GACnB,MAAM,SAAS,CAAC;AAIjB,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC"}
@@ -38,10 +38,15 @@ export { daysBetween, addDays } from './time';
38
38
  * refers to.
39
39
  */
40
40
  export declare function expandShiftInstances(input: ScheduleInput): ShiftInstance[];
41
- /** Expand one template into its dated instances inside the period. */
42
41
  export declare function expandTemplate(template: ShiftTemplate, clock: PeriodClock, periodDays: number, context: {
43
42
  nightRule?: WorkingTimeRules['nightWork'];
44
43
  publicHolidays: Set<string>;
44
+ /**
45
+ * Per-site holiday calendars, replacing the roster calendar for shifts
46
+ * at that site. Present but empty means the site observes none — the
47
+ * distinction an `undefined` entry cannot carry.
48
+ */
49
+ holidaysBySite?: Map<string, Set<string>>;
45
50
  }): ShiftInstance[];
46
51
  /**
47
52
  * Merge the global rule set with one person's overrides.
@@ -1 +1 @@
1
- {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/scheduling/model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAER,gBAAgB,EAChB,iBAAiB,EAGjB,YAAY,EACZ,gBAAgB,EAChB,aAAa,EACb,oBAAoB,EACpB,aAAa,EACb,aAAa,EACb,gBAAgB,EACnB,MAAM,SAAS,CAAC;AASjB,OAAO,EAAE,WAAW,EAA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AO,EAAE,eAAe,EAAE,CAAC"}
@@ -32,6 +32,7 @@ const constraint_1 = require("./constraints/constraint");
32
32
  const employee_scope_1 = require("./constraints/employee-scope");
33
33
  const min_rest_1 = require("./constraints/min-rest");
34
34
  const overtime_1 = require("./constraints/overtime");
35
+ const qualification_1 = require("./constraints/qualification");
35
36
  const contract_hours_1 = require("./contract-hours");
36
37
  const sites_1 = require("./sites");
37
38
  const time_1 = require("./time");
@@ -59,7 +60,14 @@ function expandShiftInstances(input) {
59
60
  const publicHolidays = new Set(input.calendar?.publicHolidays ?? []);
60
61
  for (const date of publicHolidays)
61
62
  (0, time_1.assertIsoDate)(date, 'calendar.publicHolidays');
62
- const context = { nightRule: input.rules?.nightWork, publicHolidays };
63
+ // The same site reading the solve does. Without it this path answered a
64
+ // different `isPublicHoliday` from `buildModel` for the very same input —
65
+ // the second reading path the module's own rules forbid — and skipped the
66
+ // site validation that refuses a mixed-zone roster.
67
+ const siteIndex = (0, sites_1.buildSiteIndex)(input.sites, input.travelSpeedKmh, input.period.timeZone);
68
+ void siteIndex;
69
+ const holidaysBySite = siteHolidayCalendars(input.sites);
70
+ const context = { nightRule: input.rules?.nightWork, publicHolidays, holidaysBySite };
63
71
  const instances = [];
64
72
  const seen = new Set();
65
73
  for (const template of input.shifts) {
@@ -74,6 +82,33 @@ function expandShiftInstances(input) {
74
82
  }
75
83
  exports.expandShiftInstances = expandShiftInstances;
76
84
  /** Expand one template into its dated instances inside the period. */
85
+ /**
86
+ * Per-site holiday calendars, keyed by site.
87
+ *
88
+ * A site that declares its own list replaces the roster's for its shifts; one
89
+ * that declares none inherits it, and a present-but-empty list means the site
90
+ * observes none. One builder because `expandShiftInstances` and `buildModel`
91
+ * both need it and answering differently is the failure the module's own rules
92
+ * name.
93
+ */
94
+ function siteHolidayCalendars(sites) {
95
+ const out = new Map();
96
+ for (const site of sites ?? []) {
97
+ if (site.publicHolidays !== undefined)
98
+ out.set(site.id, new Set(site.publicHolidays));
99
+ }
100
+ return out;
101
+ }
102
+ /**
103
+ * Which holiday calendar applies to a shift: the hosting site's own list where
104
+ * it declares one, otherwise the roster's. Holidays follow the place the work
105
+ * happens, so a shift with no site can only mean the roster calendar.
106
+ */
107
+ function holidaysFor(siteId, context) {
108
+ if (siteId === undefined)
109
+ return context.publicHolidays;
110
+ return context.holidaysBySite?.get(siteId) ?? context.publicHolidays;
111
+ }
77
112
  function expandTemplate(template, clock, periodDays, context) {
78
113
  if (!template.id)
79
114
  throw new types_1.ScheduleValidationError('Shift template is missing `id`');
@@ -88,6 +123,23 @@ function expandTemplate(template, clock, periodDays, context) {
88
123
  throw new types_1.ScheduleValidationError(`Shift template "${template.id}" has maxEmployees below minEmployees`);
89
124
  }
90
125
  const overrides = validateDemandOverrides(template);
126
+ /*
127
+ * Shape checks run once per template, here, rather than per date inside
128
+ * `resolveDemand`.
129
+ *
130
+ * A template whose dates all fall outside the period produces no
131
+ * occurrences at all, so validation that happened per date never ran for it
132
+ * — bad configuration survived one solve and threw on the next, when the
133
+ * period moved over it.
134
+ */
135
+ normalizeTagRequirements(template.tagRequirements, template.id);
136
+ normalizeTagRatios(template.tagRatios, template.id);
137
+ normalizeTagMaximums(template.tagMaximums, template.id);
138
+ for (const override of overrides) {
139
+ normalizeTagRequirements(override.tagRequirements, template.id);
140
+ normalizeTagRatios(override.tagRatios, template.id);
141
+ normalizeTagMaximums(override.tagMaximums, template.id);
142
+ }
91
143
  const startTod = (0, time_1.parseTimeOfDay)(template.startTime, `shift "${template.id}".startTime`);
92
144
  const endTodRaw = (0, time_1.parseTimeOfDay)(template.endTime, `shift "${template.id}".endTime`);
93
145
  // Overnight shifts roll the end into the next day explicitly; a same-time
@@ -168,6 +220,7 @@ function expandTemplate(template, clock, periodDays, context) {
168
220
  minEmployees: demand.minEmployees,
169
221
  maxEmployees: demand.maxEmployees,
170
222
  tagRequirements: demand.tagRequirements,
223
+ tagRatios: demand.tagRatios,
171
224
  tagMaximums: demand.tagMaximums,
172
225
  requiredTags: demand.requiredTags,
173
226
  shiftTypeTag: template.shiftTypeTag,
@@ -177,7 +230,7 @@ function expandTemplate(template, clock, periodDays, context) {
177
230
  isNightShift: nightMinutes >= nightThreshold,
178
231
  weekday: (0, time_1.isoWeekday)(date),
179
232
  isSunday: (0, time_1.isoWeekday)(date) === 7,
180
- isPublicHoliday: context.publicHolidays.has(date),
233
+ isPublicHoliday: holidaysFor(template.siteId, context).has(date),
181
234
  };
182
235
  if (demand.label !== undefined)
183
236
  instance.demandLabel = demand.label;
@@ -226,6 +279,105 @@ function validateDemandOverrides(template) {
226
279
  * peak" plainly means three. Only a maximum the override itself states is held
227
280
  * against the resolved minimum — that combination is a shape nobody can staff.
228
281
  */
282
+ /**
283
+ * Days of the period this contract is in force.
284
+ *
285
+ * Both bounds inclusive, clipped to the period, and zero when they do not
286
+ * overlap it at all — somebody whose contract ended in February is owed nothing
287
+ * in March rather than a full month they were not employed for.
288
+ *
289
+ * Arithmetic only: `validateContractDates` runs for every employee, including
290
+ * the ones this is never called for.
291
+ */
292
+ /**
293
+ * The contract fields that change a roster whether or not a contracted week
294
+ * resolves.
295
+ *
296
+ * Separate from `daysInForce` because that runs only for employees whose
297
+ * weekly minutes resolve — and `contractLimits` string-compares these dates for
298
+ * *everybody*. An unpadded `2026-3-2` sorts after `2026-03-02`, so it pruned
299
+ * every instance and produced an empty roster with no error; a negative
300
+ * opening balance silently lifted a rolling cap. Both were validated for a
301
+ * full-timer and waved through for anybody else.
302
+ */
303
+ function validateContractDates(employee) {
304
+ const contract = employee.contract;
305
+ if (!contract)
306
+ return;
307
+ if (contract.startDate)
308
+ (0, time_1.assertIsoDate)(contract.startDate, `employee "${employee.id}".contract.startDate`);
309
+ if (contract.endDate)
310
+ (0, time_1.assertIsoDate)(contract.endDate, `employee "${employee.id}".contract.endDate`);
311
+ if (contract.startDate && contract.endDate && contract.startDate > contract.endDate) {
312
+ throw new types_1.ScheduleValidationError(`Employee "${employee.id}" has a contract starting ${contract.startDate}, after it ends ${contract.endDate}`);
313
+ }
314
+ if (contract.openingBalanceMinutes !== undefined) {
315
+ if (!Number.isFinite(contract.openingBalanceMinutes) || contract.openingBalanceMinutes < 0) {
316
+ throw new types_1.ScheduleValidationError(`Employee "${employee.id}".contract.openingBalanceMinutes must be a non-negative number of minutes`);
317
+ }
318
+ }
319
+ }
320
+ function daysInForce(employee, periodStart, periodDays) {
321
+ const contract = employee.contract;
322
+ const periodEnd = (0, time_1.addDays)(periodStart, periodDays - 1);
323
+ const from = contract?.startDate && contract.startDate > periodStart ? contract.startDate : periodStart;
324
+ const to = contract?.endDate && contract.endDate < periodEnd ? contract.endDate : periodEnd;
325
+ if (from > to)
326
+ return 0;
327
+ return (0, time_1.daysBetween)(from, to) + 1;
328
+ }
329
+ /**
330
+ * Both shapes of `tagRequirements`, resolved to one.
331
+ *
332
+ * A plain number is a count with no grade floor; the object form carries one.
333
+ * Normalising here means no rule downstream sees a union — the alternative,
334
+ * every counting site widening a `typeof` check, is how one of them ends up
335
+ * reading `{ min: 2 }` as `NaN` and quietly requiring nobody.
336
+ */
337
+ function normalizeTagRequirements(stated, templateId) {
338
+ const out = {};
339
+ for (const [tag, value] of Object.entries(stated ?? {})) {
340
+ const requirement = typeof value === 'number' ? { min: value } : value;
341
+ if (!Number.isInteger(requirement?.min) || requirement.min < 0) {
342
+ throw new types_1.ScheduleValidationError(`Shift template "${templateId}".tagRequirements["${tag}"] needs a non-negative whole minimum`);
343
+ }
344
+ if (requirement.level !== undefined) {
345
+ if (!Number.isFinite(requirement.level) || requirement.level <= 0) {
346
+ // Zero is refused rather than accepted, because it reads as "no
347
+ // floor" and means the opposite: `holds` skips the plain-tag
348
+ // branch the moment a level is present, so `{ min: 1, level: 0 }`
349
+ // silently excludes everybody whose tag carries no grade. Omit
350
+ // the level to count anybody holding the tag.
351
+ throw new types_1.ScheduleValidationError(`Shift template "${templateId}".tagRequirements["${tag}"].level must be a positive number; ` +
352
+ `omit it to count anybody holding the tag`);
353
+ }
354
+ }
355
+ out[tag] = requirement.level === undefined ? { min: requirement.min } : { min: requirement.min, level: requirement.level };
356
+ }
357
+ return out;
358
+ }
359
+ /** Ceilings, checked like the minimums beside them. A negative maximum can never be met. */
360
+ function normalizeTagMaximums(stated, templateId) {
361
+ const out = {};
362
+ for (const [tag, max] of Object.entries(stated ?? {})) {
363
+ if (!Number.isInteger(max) || max < 0) {
364
+ throw new types_1.ScheduleValidationError(`Shift template "${templateId}".tagMaximums["${tag}"] needs a non-negative whole maximum`);
365
+ }
366
+ out[tag] = max;
367
+ }
368
+ return out;
369
+ }
370
+ /** Proportions, checked as fractions. A ratio outside 0..1 is not a proportion of anything. */
371
+ function normalizeTagRatios(stated, templateId) {
372
+ const out = {};
373
+ for (const [tag, ratio] of Object.entries(stated ?? {})) {
374
+ if (typeof ratio !== 'number' || !Number.isFinite(ratio) || ratio < 0 || ratio > 1) {
375
+ throw new types_1.ScheduleValidationError(`Shift template "${templateId}".tagRatios["${tag}"] must be a fraction between 0 and 1`);
376
+ }
377
+ out[tag] = ratio;
378
+ }
379
+ return out;
380
+ }
229
381
  function resolveDemand(template, overrides, date, onPattern) {
230
382
  let min = template.minEmployees ?? 1;
231
383
  let max = template.maxEmployees;
@@ -235,8 +387,9 @@ function resolveDemand(template, overrides, date, onPattern) {
235
387
  const demand = {
236
388
  minEmployees: min,
237
389
  maxEmployees: max,
238
- tagRequirements: template.tagRequirements ?? {},
239
- tagMaximums: template.tagMaximums ?? {},
390
+ tagRequirements: normalizeTagRequirements(template.tagRequirements, template.id),
391
+ tagRatios: normalizeTagRatios(template.tagRatios, template.id),
392
+ tagMaximums: normalizeTagMaximums(template.tagMaximums, template.id),
240
393
  requiredTags: template.requiredTags ?? [],
241
394
  };
242
395
  const weekday = (0, time_1.isoWeekday)(date);
@@ -260,10 +413,14 @@ function resolveDemand(template, overrides, date, onPattern) {
260
413
  }
261
414
  if (override.extraEmployees !== undefined)
262
415
  extra += override.extraEmployees;
263
- if (override.tagRequirements !== undefined)
264
- demand.tagRequirements = override.tagRequirements;
265
- if (override.tagMaximums !== undefined)
266
- demand.tagMaximums = override.tagMaximums;
416
+ if (override.tagRequirements !== undefined) {
417
+ demand.tagRequirements = normalizeTagRequirements(override.tagRequirements, template.id);
418
+ }
419
+ if (override.tagRatios !== undefined)
420
+ demand.tagRatios = normalizeTagRatios(override.tagRatios, template.id);
421
+ if (override.tagMaximums !== undefined) {
422
+ demand.tagMaximums = normalizeTagMaximums(override.tagMaximums, template.id);
423
+ }
267
424
  if (override.requiredTags !== undefined)
268
425
  demand.requiredTags = override.requiredTags;
269
426
  if (override.runs !== undefined)
@@ -346,6 +503,7 @@ function spanToMinutes(from, to, clock, field) {
346
503
  function validateEmployee(employee) {
347
504
  if (!employee.id)
348
505
  throw new types_1.ScheduleValidationError('Employee is missing `id`');
506
+ validateContractDates(employee);
349
507
  for (const [field, value] of [
350
508
  ['maxHoursForPeriod', employee.maxHoursForPeriod],
351
509
  ['minHoursForPeriod', employee.minHoursForPeriod],
@@ -480,14 +638,19 @@ function buildModel(input) {
480
638
  throw new types_1.ScheduleValidationError('period.endDate must not precede period.startDate');
481
639
  const clock = new time_1.PeriodClock(input.period.startDate, periodDays, input.period.timeZone ?? 'UTC');
482
640
  const rules = input.rules ?? {};
483
- const siteIndex = (0, sites_1.buildSiteIndex)(input.sites, input.travelSpeedKmh);
641
+ const siteIndex = (0, sites_1.buildSiteIndex)(input.sites, input.travelSpeedKmh, input.period.timeZone);
484
642
  const publicHolidays = new Set(input.calendar?.publicHolidays ?? []);
485
643
  for (const date of publicHolidays)
486
644
  (0, time_1.assertIsoDate)(date, 'calendar.publicHolidays');
645
+ const holidaysBySite = siteHolidayCalendars(input.sites);
487
646
  const instances = [];
488
647
  const instanceById = new Map();
489
648
  for (const template of input.shifts) {
490
- for (const inst of expandTemplate(template, clock, periodDays, { nightRule: rules.nightWork, publicHolidays })) {
649
+ for (const inst of expandTemplate(template, clock, periodDays, {
650
+ nightRule: rules.nightWork,
651
+ publicHolidays,
652
+ holidaysBySite,
653
+ })) {
491
654
  if (instanceById.has(inst.id))
492
655
  throw new types_1.ScheduleValidationError(`Duplicate shift instance id "${inst.id}"`);
493
656
  instanceById.set(inst.id, inst);
@@ -516,6 +679,35 @@ function buildModel(input) {
516
679
  personIdOf.set(employee.id, personId);
517
680
  employeesOfPerson.set(personId, [...(employeesOfPerson.get(personId) ?? []), employee.id]);
518
681
  }
682
+ // Tag possession is a question about the shift's date, so per-tag minimums
683
+ // and maximums must resolve it the same way `requiredTags` does. Plain tags
684
+ // short-circuit; only a dated qualification needs the scan. The cache keeps
685
+ // the search loop's repeated lookups off that scan — the model is immutable
686
+ // once built, so a memo can never go stale.
687
+ const tagOnCache = new Map();
688
+ /**
689
+ * The graded question. Deliberately not cached: a level floor makes the key
690
+ * space four-dimensional, and graded requirements are rare enough that the
691
+ * scan costs less than the memo would.
692
+ */
693
+ const holdsTagAt = (employeeId, tag, date, minLevel) => {
694
+ const employee = employeeById.get(employeeId);
695
+ return employee ? (0, qualification_1.holds)(employee, tag, date, minLevel) : false;
696
+ };
697
+ const holdsTagOn = (employeeId, tag, date) => {
698
+ if (employeeTags.get(employeeId)?.has(tag))
699
+ return true;
700
+ const employee = employeeById.get(employeeId);
701
+ if (!employee?.qualifications?.length)
702
+ return false;
703
+ const key = `${employeeId}\0${tag}\0${date}`;
704
+ const cached = tagOnCache.get(key);
705
+ if (cached !== undefined)
706
+ return cached;
707
+ const result = (0, qualification_1.holds)(employee, tag, date);
708
+ tagOnCache.set(key, result);
709
+ return result;
710
+ };
519
711
  // The contracted week resolves exactly once, against the rules that apply
520
712
  // to the person (a per-person override may carry its own full-time week),
521
713
  // and every rule reads the resolved figure from the context.
@@ -526,7 +718,11 @@ function buildModel(input) {
526
718
  if (weekly === undefined)
527
719
  continue;
528
720
  contractedWeeklyMinutes.set(employee.id, weekly);
529
- contractedPeriod.set(employee.id, (0, contract_hours_1.contractedPeriodMinutes)(weekly, periodDays));
721
+ // Days the contract is actually in force inside the period, not the
722
+ // period's own length: somebody who joins on day fifteen is owed a
723
+ // fortnight, and planning them a full month is what made the
724
+ // contract-hours objective load a new starter past everybody else.
725
+ contractedPeriod.set(employee.id, (0, contract_hours_1.contractedPeriodMinutes)(weekly, daysInForce(employee, input.period.startDate, periodDays)));
530
726
  }
531
727
  const contractHoursWeight = input.objectives?.contractHoursWeight ?? contract_hours_1.DEFAULT_CONTRACT_HOURS_WEIGHT;
532
728
  if (!Number.isFinite(contractHoursWeight) || contractHoursWeight < 0) {
@@ -568,6 +764,8 @@ function buildModel(input) {
568
764
  employees: input.employees,
569
765
  employeeById,
570
766
  employeeTags,
767
+ holdsTagOn,
768
+ holdsTagAt,
571
769
  instances,
572
770
  instanceById,
573
771
  siteIndex,
@@ -1 +1 @@
1
- {"version":3,"file":"operations.d.ts","sourceRoot":"","sources":["../../src/scheduling/operations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,KAAK,EACR,cAAc,EACd,mBAAmB,EACnB,WAAW,EACX,WAAW,EACX,aAAa,EACb,mBAAmB,EAEnB,oBAAoB,EACvB,MAAM,SAAS,CAAC;AA6BjB,MAAM,WAAW,gBAAgB;IAC7B,SAAS,EAAE,OAAO,CAAC;IACnB,qEAAqE;IACrE,gBAAgB,EAAE,OAAO,CAAC;IAC1B,oDAAoD;IACpD,WAAW,EAAE,OAAO,CAAC;IACrB,UAAU,EAAE,mBAAmB,EAAE,CAAC;IAClC,wEAAwE;IACxE,QAAQ,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,cAAc,CAAC;QAAC,QAAQ,EAAE,WAAW,EAAE,CAAA;KAAE,CAAC,CAAC;IACnE;;;;;OAKG;IACH,MAAM,EAAE,WAAW,EAAE,CAAC;IACtB,uGAAuG;IACvG,aAAa,EAAE,oBAAoB,EAAE,CAAC;CACzC;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,gBAAg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AC,EAAE,MAAM,CAAC;QACzB,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,SAAS,CAAC,EAAE,MAAM,CAAC;KACtB,CAAC,CAAC;CACN;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,aAAa,GAAG,mBAAmB,CAuD/E"}
@@ -262,7 +262,30 @@ function rankCandidates(input, shiftInstanceId, roster, disruption) {
262
262
  rationale: rationaleFor(eligible, blockers, costCents, fairnessDebt, preference, travelMinutes, distanceKm, originSiteId, isHomeSite, contractDeltaMinutes),
263
263
  });
264
264
  }
265
- return candidates.sort((a, b) => a.rank - b.rank || (a.employeeId < b.employeeId ? -1 : 1));
265
+ /*
266
+ * Rank, then seniority, then id.
267
+ *
268
+ * `Employee.seniority` was declared from the start and read nowhere, so the
269
+ * field asserted a capability the engine did not have. Collective
270
+ * agreements very commonly order offers by it, and the honest place for
271
+ * that is a **tiebreak**: it decides between candidates who are otherwise
272
+ * indistinguishable, and never outranks cost, travel or contract debt. An
273
+ * agreement that says "offer by seniority" means exactly that — not that a
274
+ * senior person should be called out across the city ahead of somebody on
275
+ * site.
276
+ *
277
+ * It stays inside the profiling-free boundary. Seniority is a declared
278
+ * contractual fact of the same class as a qualification or a contracted
279
+ * week — not reliability, not acceptance history, not anything learned —
280
+ * which is what `provenance.profilingFree` asserts and what keeps this
281
+ * module outside AI Act Annex III point 4(b).
282
+ *
283
+ * The id remains the final tiebreak so the order is total and reproducible
284
+ * for the many teams that record no seniority at all.
285
+ */
286
+ return candidates.sort((a, b) => a.rank - b.rank ||
287
+ (ctx.employeeById.get(b.employeeId)?.seniority ?? 0) - (ctx.employeeById.get(a.employeeId)?.seniority ?? 0) ||
288
+ (a.employeeId < b.employeeId ? -1 : 1));
266
289
  }
267
290
  exports.rankCandidates = rankCandidates;
268
291
  function rationaleFor(eligible, blockers, costCents, fairnessDebt, preference, travelMinutes, distanceKm, originSiteId, isHomeSite, contractDeltaMinutes) {
@@ -450,8 +473,12 @@ function diagnoseInfeasibility(input) {
450
473
  message: `the roster needs ${(demandMinutes / 60).toFixed(1)}h of work but the team's hour budgets total ${(capacityMinutes / 60).toFixed(1)}h`,
451
474
  });
452
475
  }
453
- for (const [tag, needed] of tagDemand(ctx).entries()) {
454
- const supply = ctx.employees.filter((e) => ctx.employeeTags.get(e.id)?.has(tag)).length;
476
+ for (const [tag, { needed, dates }] of tagDemand(ctx).entries()) {
477
+ // Holding the tag on *some* day the tag is wanted is what makes a person
478
+ // supply for it. Counting plain tags alone would call a lapsed
479
+ // certificate supply; counting only the first date would call a nurse
480
+ // who joins mid-period nobody.
481
+ const supply = ctx.employees.filter((e) => dates.some((date) => ctx.holdsTagOn(e.id, tag, date))).length;
455
482
  if (supply === 0 && needed > 0) {
456
483
  findings.push({
457
484
  kind: 'tagCapacity',
@@ -464,14 +491,26 @@ function diagnoseInfeasibility(input) {
464
491
  return { feasible: findings.length === 0, findings };
465
492
  }
466
493
  exports.diagnoseInfeasibility = diagnoseInfeasibility;
494
+ /** Per tag: how many assignments want it, and on which dates they want it. */
467
495
  function tagDemand(ctx) {
468
496
  const demand = new Map();
497
+ const add = (tag, count, date) => {
498
+ const entry = demand.get(tag) ?? { needed: 0, dates: [] };
499
+ entry.needed += count;
500
+ if (!entry.dates.includes(date))
501
+ entry.dates.push(date);
502
+ demand.set(tag, entry);
503
+ };
469
504
  for (const inst of ctx.instances) {
470
- for (const [tag, count] of Object.entries(inst.tagRequirements)) {
471
- demand.set(tag, (demand.get(tag) ?? 0) + count);
505
+ for (const [tag, requirement] of Object.entries(inst.tagRequirements))
506
+ add(tag, requirement.min, inst.date);
507
+ // A proportion of the minimum team, rounded up — the fewest people this
508
+ // occurrence could possibly need holding the tag.
509
+ for (const [tag, ratio] of Object.entries(inst.tagRatios)) {
510
+ add(tag, Math.ceil(ratio * inst.minEmployees), inst.date);
472
511
  }
473
512
  for (const tag of inst.requiredTags)
474
- demand.set(tag, (demand.get(tag) ?? 0) + inst.minEmployees);
513
+ add(tag, inst.minEmployees, inst.date);
475
514
  }
476
515
  return demand;
477
516
  }
@@ -16,7 +16,7 @@ import type { Site, SiteIndex } from './types';
16
16
  * referenced by templates or employees but not declared here are tolerated;
17
17
  * they simply have no coordinates or matrix entries.
18
18
  */
19
- export declare function buildSiteIndex(sites: Site[] | undefined, travelSpeedKmh?: number): SiteIndex;
19
+ export declare function buildSiteIndex(sites: Site[] | undefined, travelSpeedKmh?: number, periodTimeZone?: string): SiteIndex;
20
20
  /**
21
21
  * Travel time between two sites, in minutes.
22
22
  *
@@ -1 +1 @@
1
- {"version":3,"file":"sites.d.ts","sourceRoot":"","sources":["../../src/scheduling/sites.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAI/C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,SAAS,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,SAAS,CA2C5F;AAsBD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAIrG;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAalG"}
1
+ {"version":3,"file":"sites.d.ts","sourceRoot":"","sources":["../../src/scheduling/sites.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAmC/C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,SAAS,EAAE,cAAc,CAAC,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,SAAS,CAiDrH;AAsBD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAIrG;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAalG"}
@@ -11,7 +11,35 @@
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.distanceKmBetween = exports.travelMinutesBetween = exports.buildSiteIndex = void 0;
13
13
  const types_1 = require("./types");
14
+ const time_1 = require("./time");
14
15
  const geo_1 = require("../utils/geo");
16
+ /**
17
+ * A site's zone must match the roster's, because there is only one clock.
18
+ *
19
+ * Instances are placed in absolute period minutes, so rest gaps and overlaps
20
+ * survive a zone difference — but the night band, break windows, weekday and
21
+ * holiday attribution are all resolved once, at expansion, against the period's
22
+ * `PeriodClock`. A Stockholm site inside a Tallinn roster would have its 22:00
23
+ * night boundary computed an hour out, and nothing downstream could tell.
24
+ *
25
+ * Refusing is the honest answer: an hour of silent drift in a compliance
26
+ * verdict is worse than an error that says to split the roster.
27
+ */
28
+ function assertSiteZone(siteId, siteZone, periodTimeZone) {
29
+ try {
30
+ new Intl.DateTimeFormat('en-US', { timeZone: siteZone });
31
+ }
32
+ catch {
33
+ throw new types_1.ScheduleValidationError(`Site "${siteId}" has an unknown time zone: "${siteZone}"`);
34
+ }
35
+ const rosterZone = periodTimeZone ?? 'UTC';
36
+ if (siteZone !== rosterZone) {
37
+ throw new types_1.ScheduleValidationError(`Site "${siteId}" is in "${siteZone}" but the roster's period is in "${rosterZone}". ` +
38
+ `One roster resolves wall-clock times against one zone, so a roster spanning zones would ` +
39
+ `place this site's night band, breaks and day boundaries an hour out without reporting it. ` +
40
+ `Solve one roster per zone.`);
41
+ }
42
+ }
15
43
  /**
16
44
  * Build a validated site index from caller input.
17
45
  *
@@ -20,7 +48,7 @@ const geo_1 = require("../utils/geo");
20
48
  * referenced by templates or employees but not declared here are tolerated;
21
49
  * they simply have no coordinates or matrix entries.
22
50
  */
23
- function buildSiteIndex(sites, travelSpeedKmh) {
51
+ function buildSiteIndex(sites, travelSpeedKmh, periodTimeZone) {
24
52
  if (travelSpeedKmh !== undefined && (!Number.isFinite(travelSpeedKmh) || travelSpeedKmh <= 0)) {
25
53
  throw new types_1.ScheduleValidationError(`travelSpeedKmh must be a positive finite number: ${travelSpeedKmh}`);
26
54
  }
@@ -30,6 +58,11 @@ function buildSiteIndex(sites, travelSpeedKmh) {
30
58
  throw new types_1.ScheduleValidationError('Site is missing `id`');
31
59
  if (byId.has(site.id))
32
60
  throw new types_1.ScheduleValidationError(`Duplicate site id "${site.id}"`);
61
+ for (const date of site.publicHolidays ?? []) {
62
+ (0, time_1.assertIsoDate)(date, `Site "${site.id}".publicHolidays`);
63
+ }
64
+ if (site.timeZone !== undefined)
65
+ assertSiteZone(site.id, site.timeZone, periodTimeZone);
33
66
  if (site.lat !== undefined || site.lng !== undefined) {
34
67
  if (!(0, geo_1.hasValidCoordinates)(site.lat, site.lng)) {
35
68
  throw new types_1.ScheduleValidationError(`Site "${site.id}" has invalid coordinates: lat=${site.lat}, lng=${site.lng}`);