assignment-user-matcher 1.12.0 → 1.14.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 (61) hide show
  1. package/README.md +78 -3
  2. package/dist/index.d.ts +2 -2
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +8 -1
  5. package/dist/managers/WorkflowManager.d.ts +24 -0
  6. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  7. package/dist/managers/WorkflowManager.js +77 -0
  8. package/dist/matcher.class.d.ts +52 -3
  9. package/dist/matcher.class.d.ts.map +1 -1
  10. package/dist/matcher.class.js +157 -2
  11. package/dist/scheduling/constraints/constraint.d.ts.map +1 -1
  12. package/dist/scheduling/constraints/constraint.js +7 -1
  13. package/dist/scheduling/constraints/contract.d.ts +1 -0
  14. package/dist/scheduling/constraints/contract.d.ts.map +1 -1
  15. package/dist/scheduling/constraints/contract.js +61 -16
  16. package/dist/scheduling/constraints/fairness.js +1 -1
  17. package/dist/scheduling/constraints/overtime.d.ts.map +1 -1
  18. package/dist/scheduling/constraints/overtime.js +4 -2
  19. package/dist/scheduling/constraints/site-eligibility.d.ts +11 -0
  20. package/dist/scheduling/constraints/site-eligibility.d.ts.map +1 -0
  21. package/dist/scheduling/constraints/site-eligibility.js +52 -0
  22. package/dist/scheduling/constraints/site-home.d.ts +14 -0
  23. package/dist/scheduling/constraints/site-home.d.ts.map +1 -0
  24. package/dist/scheduling/constraints/site-home.js +43 -0
  25. package/dist/scheduling/constraints/site-travel-gap.d.ts +19 -0
  26. package/dist/scheduling/constraints/site-travel-gap.d.ts.map +1 -0
  27. package/dist/scheduling/constraints/site-travel-gap.js +88 -0
  28. package/dist/scheduling/contract-hours.d.ts +42 -0
  29. package/dist/scheduling/contract-hours.d.ts.map +1 -0
  30. package/dist/scheduling/contract-hours.js +104 -0
  31. package/dist/scheduling/engine/objective.d.ts.map +1 -1
  32. package/dist/scheduling/engine/objective.js +5 -0
  33. package/dist/scheduling/engine/state.d.ts.map +1 -1
  34. package/dist/scheduling/engine/state.js +1 -0
  35. package/dist/scheduling/engine/timeline.d.ts +2 -0
  36. package/dist/scheduling/engine/timeline.d.ts.map +1 -1
  37. package/dist/scheduling/index.d.ts +4 -1
  38. package/dist/scheduling/index.d.ts.map +1 -1
  39. package/dist/scheduling/index.js +14 -1
  40. package/dist/scheduling/model.d.ts +11 -0
  41. package/dist/scheduling/model.d.ts.map +1 -1
  42. package/dist/scheduling/model.js +81 -1
  43. package/dist/scheduling/operations.d.ts +23 -1
  44. package/dist/scheduling/operations.d.ts.map +1 -1
  45. package/dist/scheduling/operations.js +85 -4
  46. package/dist/scheduling/provenance.d.ts +2 -2
  47. package/dist/scheduling/provenance.d.ts.map +1 -1
  48. package/dist/scheduling/provenance.js +15 -1
  49. package/dist/scheduling/scheduler.class.d.ts.map +1 -1
  50. package/dist/scheduling/scheduler.class.js +4 -1
  51. package/dist/scheduling/sites.d.ts +35 -0
  52. package/dist/scheduling/sites.d.ts.map +1 -0
  53. package/dist/scheduling/sites.js +112 -0
  54. package/dist/scheduling/types.d.ts +120 -1
  55. package/dist/scheduling/types.d.ts.map +1 -1
  56. package/dist/types/matcher.d.ts +49 -1
  57. package/dist/types/matcher.d.ts.map +1 -1
  58. package/dist/utils/keys.d.ts +2 -0
  59. package/dist/utils/keys.d.ts.map +1 -1
  60. package/dist/utils/keys.js +8 -0
  61. package/package.json +13 -1
@@ -39,6 +39,10 @@ function loadLuaScript(filename) {
39
39
  }
40
40
  // Lua script for atomic workflow transitions
41
41
  const WORKFLOW_TRANSITION_LUA = loadLuaScript('workflow-transition.lua');
42
+ // Retention purges are capped per maintenance pass so enabling retention on a
43
+ // deployment with a large historical completed store drains it across ticks
44
+ // instead of one deletion storm.
45
+ const RETENTION_PURGE_BATCH = 5000;
42
46
  class AssignmentMatcher {
43
47
  constructor(redisClient, options) {
44
48
  this.redisClient = redisClient;
@@ -63,6 +67,11 @@ class AssignmentMatcher {
63
67
  this.maxUserBacklogSize = options?.maxUserBacklogSize ?? 9;
64
68
  this.matchExpirationMs = options?.matchExpirationMs ?? 60000;
65
69
  this.idleUserTimeoutMs = options?.idleUserTimeoutMs ?? null;
70
+ const completedRetentionMs = options?.completedAssignmentsRetentionMs;
71
+ this.completedAssignmentsRetentionMs =
72
+ completedRetentionMs !== undefined && Number.isFinite(completedRetentionMs) && completedRetentionMs > 0
73
+ ? completedRetentionMs
74
+ : null;
66
75
  this.pendingAssignmentsKey = this.keys.pendingAssignmentsData();
67
76
  this.pendingAssignmentsExpiryKey = this.keys.pendingAssignmentsExpiry();
68
77
  this.assignmentOwnerKey = this.keys.assignmentOwner();
@@ -76,6 +85,7 @@ class AssignmentMatcher {
76
85
  this.recurringAssignmentsKey = this.keys.recurringAssignments();
77
86
  this.recurringDueAtKey = this.keys.recurringDueAt();
78
87
  this.completedAssignmentsKey = this.keys.completedAssignments();
88
+ this.completedAssignmentsAtKey = this.keys.completedAssignmentsAt();
79
89
  this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
80
90
  this.usingDefaultMatchScore = !options?.matchingFunction;
81
91
  this.matchScore = options?.matchingFunction ?? this.defaultMatchScore.bind(this);
@@ -145,6 +155,7 @@ class AssignmentMatcher {
145
155
  reclaimIntervalMs: options?.workflowReclaimPollIntervalMs ?? 5000,
146
156
  reclaimMinIdleMs: options?.workflowOrphanReclaimMs ?? 60000,
147
157
  retentionMs: options?.workflowInstanceRetentionMs,
158
+ autoTrimEventStream: options?.workflowEventStreamAutoTrim,
148
159
  retryBackoffMs: options?.workflowRetryBackoffMs,
149
160
  eventBatchSize: options?.workflowEventBatchSize,
150
161
  pollBlockMs: options?.workflowPollBlockMs,
@@ -1760,7 +1771,11 @@ class AssignmentMatcher {
1760
1771
  continue;
1761
1772
  const score = expiryScores[i];
1762
1773
  const expiresAt = score === null || score === undefined ? null : Number(score);
1763
- const pendingSince = expiresAt === null ? null : expiresAt - this.matchExpirationMs;
1774
+ // The expiry score was written as claimAt + the assignment's own
1775
+ // response deadline (escalation.respondWithinMs, falling back to
1776
+ // matchExpirationMs) — deriving pendingSince from anything else
1777
+ // mis-ages every escalating assignment.
1778
+ const pendingSince = expiresAt === null ? null : expiresAt - (0, policy_1.responseDeadlineFromJson)(json, this.matchExpirationMs);
1764
1779
  const pendingForMs = pendingSince === null ? null : Math.max(0, now - pendingSince);
1765
1780
  metas.push({ json, ownerId: owners[i] ?? null, pendingForMs, pendingSince, expiresAt });
1766
1781
  }
@@ -1804,6 +1819,57 @@ class AssignmentMatcher {
1804
1819
  results.sort((a, b) => (b.pendingForMs ?? -1) - (a.pendingForMs ?? -1));
1805
1820
  return results;
1806
1821
  }
1822
+ /**
1823
+ * List terminal assignments from the completed store (both completions and
1824
+ * failures — they share the store, distinguished by the `_status` stamp:
1825
+ * `_completedBy`/`_completedAt` vs `_failedBy`/`_failedAt`). Cursor-paged
1826
+ * over HSCAN. The store is pruned only when
1827
+ * `completedAssignmentsRetentionMs` is set; pagination is best-effort
1828
+ * under a concurrent purge — the cursor is a positional offset over scan
1829
+ * order, so entries deleted between pages can shift what a later page
1830
+ * returns. Loop until `hasMore` is false and re-page if completeness
1831
+ * matters.
1832
+ */
1833
+ async getCompletedAssignments(options) {
1834
+ await this.readyPromise;
1835
+ const limit = Math.max(1, Math.min(Math.floor(options?.limit ?? 100) || 100, 1000));
1836
+ const offset = Math.max(0, parseInt(options?.cursor ?? '0', 10) || 0);
1837
+ const assignments = [];
1838
+ const seen = new Set();
1839
+ let scanned = 0;
1840
+ let hasMore = false;
1841
+ let cursor = '0';
1842
+ do {
1843
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.completedAssignmentsKey, cursor, {
1844
+ COUNT: Math.max(limit, 100),
1845
+ });
1846
+ cursor = nextCursor;
1847
+ for (const entry of entries) {
1848
+ // HSCAN may repeat a field across pages under a concurrent rehash.
1849
+ if (seen.has(entry.field))
1850
+ continue;
1851
+ seen.add(entry.field);
1852
+ if (scanned < offset) {
1853
+ scanned++;
1854
+ continue;
1855
+ }
1856
+ if (assignments.length >= limit) {
1857
+ hasMore = true;
1858
+ break;
1859
+ }
1860
+ scanned++;
1861
+ try {
1862
+ const assignment = JSON.parse(entry.value);
1863
+ assignment._status = assignment._failedAt !== undefined ? 'failed' : 'completed';
1864
+ assignments.push(assignment);
1865
+ }
1866
+ catch {
1867
+ // Skip corrupt entries (same precedent as the pending listing).
1868
+ }
1869
+ }
1870
+ } while (cursor !== '0' && !hasMore);
1871
+ return { assignments, nextCursor: hasMore ? String(scanned) : null, hasMore };
1872
+ }
1807
1873
  /** Default match score implementation using extracted scoring module */
1808
1874
  defaultMatchScore(user, assignmentTags, assignmentPriority, _assignmentId, skillThresholds) {
1809
1875
  return Promise.resolve((0, match_score_1.calculateMatchScore)(user, assignmentTags, assignmentPriority, this.enableDefaultMatching, skillThresholds));
@@ -2964,6 +3030,7 @@ class AssignmentMatcher {
2964
3030
  _failedAt: now,
2965
3031
  _failureReason: `rejection-budget-exhausted:${cause}`,
2966
3032
  }));
3033
+ multi.zAdd(this.completedAssignmentsAtKey, { score: now, value: assignment.id });
2967
3034
  }
2968
3035
  await multi.exec();
2969
3036
  this.emitAssignmentLifecycle({
@@ -3011,6 +3078,8 @@ class AssignmentMatcher {
3011
3078
  _result: result,
3012
3079
  };
3013
3080
  multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(completedData));
3081
+ // Retention index: the sweep reads only entries past the window.
3082
+ multi.zAdd(this.completedAssignmentsAtKey, { score: now, value: assignmentId });
3014
3083
  await multi.exec();
3015
3084
  if (json.indexOf('"sla"') !== -1) {
3016
3085
  await this.recordSlaComplete(json, now);
@@ -3066,6 +3135,7 @@ class AssignmentMatcher {
3066
3135
  _failureReason: reason,
3067
3136
  };
3068
3137
  multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(failedData));
3138
+ multi.zAdd(this.completedAssignmentsAtKey, { score: now, value: assignmentId });
3069
3139
  await multi.exec();
3070
3140
  if (this.enableLearning) {
3071
3141
  await this.learning.applyOutcome(assignmentId, 'fail');
@@ -3220,6 +3290,17 @@ class AssignmentMatcher {
3220
3290
  await this.readyPromise;
3221
3291
  return this.workflow.publishWorkflowEvent(event);
3222
3292
  }
3293
+ /**
3294
+ * Trim the workflow event stream up to the consumption frontier — every
3295
+ * entry delivered *and* acknowledged by every consumer group. Never trims
3296
+ * ahead of consumers, so no event can be lost to trimming. Runs
3297
+ * automatically after event processing and on the reclaim interval when
3298
+ * `workflowEventStreamAutoTrim` is set; callable directly otherwise.
3299
+ */
3300
+ async trimWorkflowEventStream() {
3301
+ await this.readyPromise;
3302
+ return this.workflow.trimWorkflowEventStream();
3303
+ }
3223
3304
  /**
3224
3305
  * Start the workflow orchestrator.
3225
3306
  * This listens to the event stream and processes workflow transitions.
@@ -3478,6 +3559,7 @@ class AssignmentMatcher {
3478
3559
  _failedAt: now,
3479
3560
  _failureReason: 'completion-sla-breach',
3480
3561
  }))
3562
+ .zAdd(this.completedAssignmentsAtKey, { score: now, value: id })
3481
3563
  // Terminal: the freshness TTL no longer applies.
3482
3564
  .zRem(this.assignmentsSlaExpiryKey, id);
3483
3565
  if (workerId)
@@ -3930,6 +4012,73 @@ class AssignmentMatcher {
3930
4012
  const assignment = await this.getAssignment(id);
3931
4013
  return assignment ? (0, policy_1.escalationLevelOf)(assignment) : 0;
3932
4014
  }
4015
+ /**
4016
+ * Purge terminal assignments older than `completedAssignmentsRetentionMs`.
4017
+ *
4018
+ * The completed store has no expiry of its own — an accepted assignment's
4019
+ * deadlines all die at accept — so without this sweep it grows forever on
4020
+ * busy deployments. The terminal-timestamp index (`completedAssignmentsAt`,
4021
+ * written atomically with each completed hSet) keeps the steady-state pass
4022
+ * O(eligible) — the same shape as every other deadline sweep — and purges
4023
+ * are capped per pass, so enabling retention on a deployment with a large
4024
+ * historical store drains it across ticks instead of in one deletion
4025
+ * storm. The window applies retroactively: pre-existing records older
4026
+ * than it are purged too. Entries without a terminal timestamp
4027
+ * (externally injected or corrupt) are never indexed and never deleted.
4028
+ * No-op, reporting zero, when no retention window is configured.
4029
+ */
4030
+ async processCompletedAssignmentsRetention() {
4031
+ await this.readyPromise;
4032
+ const retentionMs = this.completedAssignmentsRetentionMs;
4033
+ if (retentionMs === null)
4034
+ return { purged: 0 };
4035
+ await this.backfillCompletedRetentionIndex();
4036
+ const cutoff = Date.now() - retentionMs;
4037
+ const stale = await this.redisClient.zRangeByScore(this.completedAssignmentsAtKey, '-inf', cutoff, {
4038
+ LIMIT: { offset: 0, count: RETENTION_PURGE_BATCH },
4039
+ });
4040
+ if (stale.length === 0)
4041
+ return { purged: 0 };
4042
+ await this.redisClient
4043
+ .multi()
4044
+ .hDel(this.completedAssignmentsKey, stale)
4045
+ .zRem(this.completedAssignmentsAtKey, stale)
4046
+ .exec();
4047
+ return { purged: stale.length };
4048
+ }
4049
+ /**
4050
+ * One-shot migration for entries written before the terminal-timestamp
4051
+ * index existed (same pattern as `backfillWorkflowIndexes()`): a single
4052
+ * full HSCAN pass indexes them, then the marker key makes the pass never
4053
+ * run again. Entries without a terminal timestamp stay unindexed — and
4054
+ * therefore never purgeable — by design.
4055
+ */
4056
+ async backfillCompletedRetentionIndex() {
4057
+ if (Number(await this.redisClient.exists(this.keys.completedRetentionIndexed())))
4058
+ return;
4059
+ const multi = this.redisClient.multi();
4060
+ let cursor = '0';
4061
+ do {
4062
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.completedAssignmentsKey, cursor, {
4063
+ COUNT: 500,
4064
+ });
4065
+ cursor = nextCursor;
4066
+ for (const entry of entries) {
4067
+ try {
4068
+ const parsed = JSON.parse(entry.value);
4069
+ const terminalAt = Number(parsed._completedAt ?? parsed._failedAt);
4070
+ if (Number.isFinite(terminalAt) && terminalAt > 0) {
4071
+ multi.zAdd(this.completedAssignmentsAtKey, { score: terminalAt, value: entry.field });
4072
+ }
4073
+ }
4074
+ catch {
4075
+ // Corrupt entries are not the sweep's to index or delete.
4076
+ }
4077
+ }
4078
+ } while (cursor !== '0');
4079
+ multi.set(this.keys.completedRetentionIndexed(), '1');
4080
+ await multi.exec();
4081
+ }
3933
4082
  /**
3934
4083
  * Run every enabled maintenance sweep once: response deadlines and
3935
4084
  * escalations, workflow step timeouts, and idle-user release.
@@ -3954,6 +4103,7 @@ class AssignmentMatcher {
3954
4103
  let scheduleMisses = 0;
3955
4104
  let recurrenceMaterializations = 0;
3956
4105
  let recurrenceRetirements = 0;
4106
+ let retentionPurged = 0;
3957
4107
  // Recurrence before schedule: an occurrence materialized due-now is
3958
4108
  // then activated by the schedule sweep in this same tick.
3959
4109
  if (opts.recurrence) {
@@ -3986,6 +4136,9 @@ class AssignmentMatcher {
3986
4136
  if (opts.idleUsers && this.idleUserTimeoutMs !== null) {
3987
4137
  releasedIdleUsers = (await this.processIdleUsers()).length;
3988
4138
  }
4139
+ if (opts.completedRetention && this.completedAssignmentsRetentionMs !== null) {
4140
+ retentionPurged = (await this.processCompletedAssignmentsRetention()).purged;
4141
+ }
3989
4142
  return {
3990
4143
  expiredMatches,
3991
4144
  escalations,
@@ -3998,6 +4151,7 @@ class AssignmentMatcher {
3998
4151
  scheduleMisses,
3999
4152
  recurrenceMaterializations,
4000
4153
  recurrenceRetirements,
4154
+ retentionPurged,
4001
4155
  tookMs: Date.now() - startedAt,
4002
4156
  };
4003
4157
  }
@@ -4005,7 +4159,7 @@ class AssignmentMatcher {
4005
4159
  * Start the periodic maintenance tick. Idempotent; a second call with
4006
4160
  * different options replaces the first.
4007
4161
  *
4008
- * @param options.intervalMs how often to sweep (default 5000)
4162
+ * @param options which sweeps to run, plus `intervalMs` (default 5000) for the tick itself
4009
4163
  */
4010
4164
  startMaintenance(options) {
4011
4165
  this.stopMaintenance();
@@ -4046,6 +4200,7 @@ class AssignmentMatcher {
4046
4200
  recurrence: options?.recurrence ?? true,
4047
4201
  workflowStepTimeouts: options?.workflowStepTimeouts ?? this.enableWorkflows,
4048
4202
  idleUsers: options?.idleUsers ?? this.idleUserTimeoutMs !== null,
4203
+ completedRetention: options?.completedRetention ?? this.completedAssignmentsRetentionMs !== null,
4049
4204
  };
4050
4205
  }
4051
4206
  /** @deprecated Use `startMaintenance()`, which also sweeps workflow step timeouts. */
@@ -1 +1 @@
1
- {"version":3,"file":"constraint.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/constraint.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AA4BzF,MAAM,WAAW,wBAAwB;IACrC,gEAAgE;IAChE,cAAc,EAAE,MAAM,CAAC;IACvB,gFAAgF;IAChF,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,+EAA+E;IAC/E,KAAK,CAAC,EAAE,gBAAgB,CAAC;IACzB,qFAAqF;IACrF,UAAU,CAAC,EAAE,gBAAgB,CAAC;CACjC;AAED;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,wBAAwB,GAAG,oBAAoB,EAAE,CAkClG"}
1
+ {"version":3,"file":"constraint.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/constraint.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AA+BzF,MAAM,WAAW,wBAAwB;IACrC,gEAAgE;IAChE,cAAc,EAAE,MAAM,CAAC;IACvB,gFAAgF;IAChF,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,+EAA+E;IAC/E,KAAK,CAAC,EAAE,gBAAgB,CAAC;IACzB,qFAAqF;IACrF,UAAU,CAAC,EAAE,gBAAgB,CAAC;CACjC;AAED;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,wBAAwB,GAAG,oBAAoB,EAAE,CA6ClG"}
@@ -40,6 +40,9 @@ const contract_1 = require("./contract");
40
40
  const overtime_1 = require("./overtime");
41
41
  const duty_quota_1 = require("./duty-quota");
42
42
  const cost_1 = require("./cost");
43
+ const site_eligibility_1 = require("./site-eligibility");
44
+ const site_travel_gap_1 = require("./site-travel-gap");
45
+ const site_home_1 = require("./site-home");
43
46
  /**
44
47
  * The built-in constraints in evaluation order.
45
48
  *
@@ -86,12 +89,15 @@ function createDefaultConstraints(options) {
86
89
  constraints.push((0, fairness_1.fairness)(rules.fairness));
87
90
  // Always-on person-scoped rules: they no-op unless the employee carries the
88
91
  // relevant data, so they cost nothing for simple rosters.
89
- constraints.push((0, availability_1.availability)(), (0, qualification_1.qualification)(), (0, group_composition_1.groupComposition)(), (0, protections_1.protections)(), (0, contract_1.contractLimits)());
92
+ constraints.push((0, availability_1.availability)(), (0, qualification_1.qualification)(), (0, group_composition_1.groupComposition)(), (0, protections_1.protections)(), (0, contract_1.contractLimits)(), (0, site_eligibility_1.siteEligibility)(), (0, site_travel_gap_1.siteTravelGap)());
90
93
  // The cost term is score-only: its verdict always passes, so it steers the
91
94
  // search without ever appearing as a violation.
92
95
  const costWeight = options.objectives?.costWeightPerEuro;
93
96
  if (costWeight !== undefined && costWeight > 0)
94
97
  constraints.push((0, cost_1.costObjective)(costWeight));
98
+ const homeSiteWeight = options.objectives?.homeSiteWeight;
99
+ if (homeSiteWeight !== undefined && homeSiteWeight > 0)
100
+ constraints.push((0, site_home_1.siteHomePreference)(homeSiteWeight));
95
101
  return constraints;
96
102
  }
97
103
  exports.createDefaultConstraints = createDefaultConstraints;
@@ -17,5 +17,6 @@
17
17
  * outruns the contract.
18
18
  */
19
19
  import type { SchedulingConstraint } from '../types';
20
+ export declare const CONTRACT_HOURS_CITATION = "Contract of employment; Directive 97/81/EC cl. 4 (pro rata temporis)";
20
21
  export declare function contractLimits(): SchedulingConstraint;
21
22
  //# sourceMappingURL=contract.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAoC,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAGvF,wBAAgB,cAAc,IAAI,oBAAoB,CAkHrD"}
1
+ {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAoC,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAGvF,eAAO,MAAM,uBAAuB,yEAAyE,CAAC;AAE9G,wBAAgB,cAAc,IAAI,oBAAoB,CAmKrD"}
@@ -18,8 +18,9 @@
18
18
  * outruns the contract.
19
19
  */
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.contractLimits = void 0;
21
+ exports.contractLimits = exports.CONTRACT_HOURS_CITATION = void 0;
22
22
  const support_1 = require("./support");
23
+ exports.CONTRACT_HOURS_CITATION = 'Contract of employment; Directive 97/81/EC cl. 4 (pro rata temporis)';
23
24
  function contractLimits() {
24
25
  const constraint = (0, support_1.fromVerdict)({
25
26
  id: 'contract',
@@ -77,17 +78,39 @@ function contractLimits() {
77
78
  unit: 'days',
78
79
  });
79
80
  }
80
- if (contract.maxPeriodMinutes !== undefined) {
81
- const worked = attributable.reduce((sum, e) => {
82
- const overlap = Math.min(e.end, periodWindow.end) - Math.max(e.start, periodWindow.start);
83
- const span = e.end - e.start;
84
- return sum + (span > 0 ? Math.round((e.workingMinutes * Math.max(0, overlap)) / span) : 0);
85
- }, 0);
86
- if (worked > contract.maxPeriodMinutes) {
87
- return (0, support_1.fail)('contract', 'hard', `employee "${pair.employeeId}" would work ${(0, support_1.h)(worked)}, over their ${(0, support_1.h)(contract.maxPeriodMinutes)} contract maximum`, { actual: worked, required: contract.maxPeriodMinutes, unit: 'minutes' });
88
- }
81
+ const contracted = state.ctx.contractedPeriodMinutes.get(pair.employeeId);
82
+ const maxOver = (0, support_1.rulesFor)(state.ctx, pair.employeeId).contract?.maxOverMinutes;
83
+ if (contract.maxPeriodMinutes === undefined && contracted === undefined) {
84
+ return (0, support_1.pass)('contract', 'within contract limits');
85
+ }
86
+ const worked = attributable.reduce((sum, e) => {
87
+ const overlap = Math.min(e.end, periodWindow.end) - Math.max(e.start, periodWindow.start);
88
+ const span = e.end - e.start;
89
+ return sum + (span > 0 ? Math.round((e.workingMinutes * Math.max(0, overlap)) / span) : 0);
90
+ }, 0);
91
+ if (contract.maxPeriodMinutes !== undefined && worked > contract.maxPeriodMinutes) {
92
+ return (0, support_1.fail)('contract', 'hard', `employee "${pair.employeeId}" would work ${(0, support_1.h)(worked)}, over their ${(0, support_1.h)(contract.maxPeriodMinutes)} contract maximum`, { actual: worked, required: contract.maxPeriodMinutes, unit: 'minutes' });
93
+ }
94
+ // The contracted week pro-rated to the period, plus whatever
95
+ // surplus the rules allow. Whether the surplus is a breach or
96
+ // merely overtime is the caller's regime, which is why the cap
97
+ // is opt-in.
98
+ if (contracted !== undefined && maxOver !== undefined && worked > contracted + maxOver) {
99
+ return (0, support_1.fail)('contract', 'hard', `employee "${pair.employeeId}" would work ${(0, support_1.h)(worked)}, over their ${(0, support_1.h)(contracted)} contracted for the period` +
100
+ (maxOver > 0 ? ` (${(0, support_1.h)(maxOver)} over allowed)` : ''), {
101
+ actual: worked,
102
+ required: contracted + maxOver,
103
+ unit: 'minutes',
104
+ citation: (0, support_1.rulesFor)(state.ctx, pair.employeeId).contract?.citation ?? exports.CONTRACT_HOURS_CITATION,
105
+ });
89
106
  }
90
- return (0, support_1.pass)('contract', 'within contract limits');
107
+ return contracted === undefined
108
+ ? (0, support_1.pass)('contract', 'within contract limits')
109
+ : (0, support_1.pass)('contract', `${(0, support_1.h)(worked)} of ${(0, support_1.h)(contracted)} contracted for the period`, {
110
+ actual: worked,
111
+ required: contracted,
112
+ unit: 'minutes',
113
+ });
91
114
  });
92
115
  },
93
116
  });
@@ -98,19 +121,41 @@ function contractLimits() {
98
121
  const out = [];
99
122
  for (const employee of state.ctx.employees) {
100
123
  const contract = employee.contract;
101
- if (!contract || contract.kind === 'days' || contract.minPeriodMinutes === undefined)
124
+ if (!contract)
102
125
  continue;
103
126
  const worked = state.minutesByEmployee.get(employee.id) ?? 0;
104
- if (worked >= contract.minPeriodMinutes)
127
+ if (contract.kind !== 'days' && contract.minPeriodMinutes !== undefined && worked < contract.minPeriodMinutes) {
128
+ out.push({
129
+ constraintId: 'contract',
130
+ severity: 'hard',
131
+ employeeId: employee.id,
132
+ message: `employee "${employee.id}" is rostered ${(0, support_1.h)(worked)}, below their ${(0, support_1.h)(contract.minPeriodMinutes)} contract minimum`,
133
+ actual: worked,
134
+ required: contract.minPeriodMinutes,
135
+ unit: 'minutes',
136
+ });
137
+ }
138
+ // A shortfall against the contracted week is a report, not a
139
+ // breach: the roster is short of what the person is owed, which
140
+ // the manager needs to see, but blocking on it would stall the
141
+ // very assignments that close it.
142
+ const rule = (0, support_1.rulesFor)(state.ctx, employee.id).contract;
143
+ const contracted = state.ctx.contractedPeriodMinutes.get(employee.id);
144
+ if (rule?.maxUnderMinutes === undefined || contracted === undefined)
145
+ continue;
146
+ const shortfall = contracted - worked;
147
+ if (shortfall <= rule.maxUnderMinutes)
105
148
  continue;
149
+ const fte = contract.fte !== undefined ? ` (${contract.fte} FTE)` : '';
106
150
  out.push({
107
151
  constraintId: 'contract',
108
- severity: 'hard',
152
+ severity: 'soft',
109
153
  employeeId: employee.id,
110
- message: `employee "${employee.id}" is rostered ${(0, support_1.h)(worked)}, below their ${(0, support_1.h)(contract.minPeriodMinutes)} contract minimum`,
154
+ message: `employee "${employee.id}" is planned ${(0, support_1.h)(worked)} against ${(0, support_1.h)(contracted)} contracted for the period${fte}, ${(0, support_1.h)(shortfall)} short`,
111
155
  actual: worked,
112
- required: contract.minPeriodMinutes,
156
+ required: contracted - rule.maxUnderMinutes,
113
157
  unit: 'minutes',
158
+ citation: rule.citation ?? exports.CONTRACT_HOURS_CITATION,
114
159
  });
115
160
  }
116
161
  return out;
@@ -136,7 +136,7 @@ function shareWeights(state, rule, employeeIds) {
136
136
  weights.set(id, 1);
137
137
  continue;
138
138
  }
139
- const weekly = state.ctx.employeeById.get(id)?.contract?.weeklyMinutes;
139
+ const weekly = state.ctx.contractedWeeklyMinutes.get(id);
140
140
  weights.set(id, weekly && weekly > 0 ? weekly : 1);
141
141
  }
142
142
  return weights;
@@ -1 +1 @@
1
- {"version":3,"file":"overtime.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/overtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAY,WAAW,EAAE,YAAY,EAAe,oBAAoB,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAgBpH,eAAO,MAAM,iBAAiB,2FAAuE,CAAC;AAEtG;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,SAAU,GAAG,IAAI,CAYjF;AAED,wBAAgB,QAAQ,CAAC,IAAI,EAAE,YAAY,GAAG,oBAAoB,CAkFjE;AAOD;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW,EAAE,CAiBhE"}
1
+ {"version":3,"file":"overtime.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/overtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAY,WAAW,EAAE,YAAY,EAAe,oBAAoB,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAgBpH,eAAO,MAAM,iBAAiB,2FAAuE,CAAC;AAEtG;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,SAAU,GAAG,IAAI,CAYjF;AAED,wBAAgB,QAAQ,CAAC,IAAI,EAAE,YAAY,GAAG,oBAAoB,CAoFjE;AAOD;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW,EAAE,CAiBhE"}
@@ -65,7 +65,9 @@ function overtime(rule) {
65
65
  return (0, support_1.pass)('overtime', 'no overtime rule applies to this employee');
66
66
  const citation = applied.citation ?? exports.OVERTIME_CITATION;
67
67
  const employee = state.ctx.employeeById.get(pair.employeeId);
68
- const weeklyOrdinary = employee?.contract?.weeklyMinutes ?? applied.ordinaryPerWeekMinutes;
68
+ // The contracted week is resolved once in the model (explicit
69
+ // minutes or `fte` × full-time week), never re-derived here.
70
+ const weeklyOrdinary = state.ctx.contractedWeeklyMinutes.get(pair.employeeId) ?? applied.ordinaryPerWeekMinutes;
69
71
  const timeline = (0, support_1.timelineFor)(state, pair.employeeId);
70
72
  const range = (0, support_1.rangeOf)(inst);
71
73
  const probe = { ...range, id: (0, support_1.entryIdOf)(pair), workingMinutes: inst.workingMinutes, tag: inst.shiftTypeTag };
@@ -141,7 +143,7 @@ function overtimeLedger(state) {
141
143
  exports.overtimeLedger = overtimeLedger;
142
144
  /** Working minutes past the pro-rated weekly baseline over the whole period. */
143
145
  function periodOvertimeMinutes(state, employee, rule) {
144
- const weeklyOrdinary = employee.contract?.weeklyMinutes ?? rule.ordinaryPerWeekMinutes;
146
+ const weeklyOrdinary = state.ctx.contractedWeeklyMinutes.get(employee.id) ?? rule.ordinaryPerWeekMinutes;
145
147
  if (weeklyOrdinary === undefined)
146
148
  return 0;
147
149
  const baseline = Math.round((weeklyOrdinary * state.ctx.periodDays) / 7);
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Site eligibility — a hard allow-list per employee.
3
+ *
4
+ * When an employee carries `siteIds`, they may only be assigned to shifts whose
5
+ * `siteId` is in that list. Shifts without a site remain open to everyone, and
6
+ * employees without the list remain eligible everywhere, so existing inputs are
7
+ * unaffected.
8
+ */
9
+ import type { SchedulingConstraint } from '../types';
10
+ export declare function siteEligibility(): SchedulingConstraint;
11
+ //# sourceMappingURL=site-eligibility.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-eligibility.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/site-eligibility.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAkB,oBAAoB,EAAe,MAAM,UAAU,CAAC;AAGlF,wBAAgB,eAAe,IAAI,oBAAoB,CAsCtD"}
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ /**
3
+ * Site eligibility — a hard allow-list per employee.
4
+ *
5
+ * When an employee carries `siteIds`, they may only be assigned to shifts whose
6
+ * `siteId` is in that list. Shifts without a site remain open to everyone, and
7
+ * employees without the list remain eligible everywhere, so existing inputs are
8
+ * unaffected.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.siteEligibility = void 0;
12
+ const support_1 = require("./support");
13
+ function siteEligibility() {
14
+ return (0, support_1.fromVerdict)({
15
+ id: 'site-eligibility',
16
+ hardness: 'hard',
17
+ prune(ctx, eligibility) {
18
+ for (const [employeeId, instances] of eligibility) {
19
+ const allowed = ctx.employeeById.get(employeeId)?.siteIds;
20
+ if (!allowed || allowed.length === 0)
21
+ continue;
22
+ for (const instanceId of [...instances]) {
23
+ const inst = ctx.instanceById.get(instanceId);
24
+ if (inst?.siteId && !allowed.includes(inst.siteId)) {
25
+ instances.delete(instanceId);
26
+ }
27
+ }
28
+ }
29
+ },
30
+ verdict(state, pair) {
31
+ const inst = (0, support_1.instanceOf)(state, pair);
32
+ const employee = state.ctx.employeeById.get(pair.employeeId);
33
+ const siteId = inst?.siteId;
34
+ const allowed = employee?.siteIds;
35
+ if (!siteId || !allowed || allowed.length === 0) {
36
+ return (0, support_1.pass)('site-eligibility', 'no site restriction');
37
+ }
38
+ if (allowed.includes(siteId)) {
39
+ return (0, support_1.pass)('site-eligibility', `eligible for site "${siteId}"`);
40
+ }
41
+ return {
42
+ ruleId: 'site-eligibility',
43
+ pass: false,
44
+ severity: 'hard',
45
+ message: `employee "${pair.employeeId}" is not eligible for site "${siteId}"`,
46
+ actual: 0,
47
+ required: 1,
48
+ };
49
+ },
50
+ });
51
+ }
52
+ exports.siteEligibility = siteEligibility;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Home-site preference — a soft objective term.
3
+ *
4
+ * Opt-in via `ScheduleInput.objectives.homeSiteWeight`. The term contributes
5
+ * `weight` points for every assignment where the employee has a `homeSiteId`
6
+ * that differs from the shift's site. It never blocks an assignment; it merely
7
+ * steers the solver toward rosters that keep people at their home site.
8
+ *
9
+ * Like the cost term, this is declared data, not a behavioural or predictive
10
+ * signal, so it does not affect the `profilingFree` provenance claim.
11
+ */
12
+ import type { SchedulingConstraint } from '../types';
13
+ export declare function siteHomePreference(weight: number): SchedulingConstraint;
14
+ //# sourceMappingURL=site-home.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-home.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/site-home.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAkB,oBAAoB,EAAe,MAAM,UAAU,CAAC;AAGlF,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,oBAAoB,CA2BvE"}
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ /**
3
+ * Home-site preference — a soft objective term.
4
+ *
5
+ * Opt-in via `ScheduleInput.objectives.homeSiteWeight`. The term contributes
6
+ * `weight` points for every assignment where the employee has a `homeSiteId`
7
+ * that differs from the shift's site. It never blocks an assignment; it merely
8
+ * steers the solver toward rosters that keep people at their home site.
9
+ *
10
+ * Like the cost term, this is declared data, not a behavioural or predictive
11
+ * signal, so it does not affect the `profilingFree` provenance claim.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.siteHomePreference = void 0;
15
+ const support_1 = require("./support");
16
+ function siteHomePreference(weight) {
17
+ return (0, support_1.fromVerdict)({
18
+ id: 'site-home',
19
+ hardness: 'soft',
20
+ weight,
21
+ verdict(state, pair) {
22
+ const inst = (0, support_1.instanceOf)(state, pair);
23
+ const employee = state.ctx.employeeById.get(pair.employeeId);
24
+ const shiftSite = inst?.siteId;
25
+ const homeSite = employee?.homeSiteId;
26
+ if (!shiftSite || !homeSite) {
27
+ return (0, support_1.pass)('site-home', 'no home-site preference configured');
28
+ }
29
+ if (shiftSite === homeSite) {
30
+ return (0, support_1.pass)('site-home', `home site (${shiftSite})`);
31
+ }
32
+ return {
33
+ ruleId: 'site-home',
34
+ pass: false,
35
+ severity: 'soft',
36
+ message: `based at site "${homeSite}", shift at site "${shiftSite}"`,
37
+ actual: 1,
38
+ required: 0,
39
+ };
40
+ },
41
+ });
42
+ }
43
+ exports.siteHomePreference = siteHomePreference;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Cross-site travel gap.
3
+ *
4
+ * When a person works two consecutive assignments at different sites, the gap
5
+ * between them must be at least the travel time between those sites. Only the
6
+ * immediate predecessor and successor on the person timeline are judged; a
7
+ * non-adjacent assignment does not create a direct travel obligation.
8
+ *
9
+ * The rule only enforces the gap; it does **not** count travel time as working
10
+ * time (CJEU C-266/14 would require that, but it is out of scope here — the
11
+ * caller models working time through `duty` and break rules).
12
+ *
13
+ * Because the default `min-rest` rule requires 11h between any two assignments,
14
+ * this rule mainly matters in split-shift setups where the caller has relaxed
15
+ * `minRestMinutes` or configured a `dailyRest` rule with a shorter window.
16
+ */
17
+ import type { SchedulingConstraint } from '../types';
18
+ export declare function siteTravelGap(): SchedulingConstraint;
19
+ //# sourceMappingURL=site-travel-gap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-travel-gap.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/site-travel-gap.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAA+B,oBAAoB,EAAe,MAAM,UAAU,CAAC;AAK/F,wBAAgB,aAAa,IAAI,oBAAoB,CA2EpD"}