@jsb188/mday 1.1.11 → 1.1.12

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 (210) hide show
  1. package/package.json +58 -23
  2. package/src/constants/agentMemory.ts +14 -45
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +156 -47
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +12 -38
  10. package/src/constants/dataTableFieldTypes.generated.ts +3 -7
  11. package/src/constants/docAccess.ts +3 -2
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +114 -12
  14. package/src/constants/fieldDoc.ts +74 -4
  15. package/src/constants/graphqlReactivity.ts +108 -25
  16. package/src/constants/log.ts +9 -0
  17. package/src/constants/logDisplay/README.md +88 -0
  18. package/src/constants/logDisplay/defaults.ts +39 -0
  19. package/src/constants/logDisplay/index.ts +27 -0
  20. package/src/constants/logDisplay/operations/arable.ts +16 -0
  21. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  22. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  23. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  24. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  25. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  26. package/src/constants/logTaxonomy.generated.ts +1834 -730
  27. package/src/constants/organization.ts +13 -14
  28. package/src/constants/qrCode.ts +30 -0
  29. package/src/constants/sheet.ts +65 -101
  30. package/src/constants/sms.ts +18 -0
  31. package/src/constants/storage.ts +33 -9
  32. package/src/constants/usage.ts +3 -0
  33. package/src/constants/workflowSteps.ts +60 -0
  34. package/src/schemas/editLogEntry.ts +106 -283
  35. package/src/schemas/inboundContact.ts +5 -5
  36. package/src/types/agentMemory.d.ts +38 -14
  37. package/src/types/agentNote.d.ts +443 -0
  38. package/src/types/billing.d.ts +537 -0
  39. package/src/types/campaign.d.ts +1043 -193
  40. package/src/types/contact.d.ts +15 -0
  41. package/src/types/csvExport.d.ts +213 -0
  42. package/src/types/dataAnalysis.d.ts +44 -0
  43. package/src/types/dataTable.d.ts +102 -309
  44. package/src/types/definitionElement.d.ts +35 -0
  45. package/src/types/dt.d.ts +257 -0
  46. package/src/types/email.d.ts +144 -55
  47. package/src/types/emailReplyReport.d.ts +76 -0
  48. package/src/types/fieldDoc.d.ts +579 -150
  49. package/src/types/fieldDocContract.d.ts +90 -0
  50. package/src/types/inboundContact.d.ts +8 -0
  51. package/src/types/log.d.ts +94 -3
  52. package/src/types/logDisplay.types.ts +85 -0
  53. package/src/types/organization.d.ts +8 -3
  54. package/src/types/qrCode.d.ts +96 -0
  55. package/src/types/richText.d.ts +81 -0
  56. package/src/types/sheet.d.ts +180 -463
  57. package/src/types/sms.d.ts +38 -0
  58. package/src/types/storage.d.ts +266 -27
  59. package/src/types/workflow.d.ts +196 -66
  60. package/src/utils/agentMemory.ts +15 -0
  61. package/src/utils/agentNote.ts +850 -0
  62. package/src/utils/aiChat.ts +31 -14
  63. package/src/utils/aiChatWork.ts +64 -0
  64. package/src/utils/billing.ts +37 -0
  65. package/src/utils/campaign.ts +642 -209
  66. package/src/utils/campaignAI.ts +72 -0
  67. package/src/utils/campaignAccess.ts +239 -0
  68. package/src/utils/campaignEmail.ts +601 -0
  69. package/src/utils/campaignEmailCompiler.ts +372 -0
  70. package/src/utils/campaignEmailImages.ts +60 -0
  71. package/src/utils/campaignEmailStyles.ts +544 -0
  72. package/src/utils/campaignLifecycle.ts +104 -0
  73. package/src/utils/campaignPreview.ts +285 -0
  74. package/src/utils/contact.ts +50 -0
  75. package/src/utils/csvExport.ts +19 -0
  76. package/src/utils/dataTable.ts +18 -556
  77. package/src/utils/dataTableFieldTypeRegistry.ts +1 -0
  78. package/src/utils/dataTableRelativeDate.ts +447 -0
  79. package/src/utils/definitionElement.ts +84 -0
  80. package/src/utils/email.ts +208 -1
  81. package/src/utils/emailReplyReport.test.ts +187 -0
  82. package/src/utils/emailReplyReport.ts +143 -0
  83. package/src/utils/fieldDoc.ts +81 -37
  84. package/src/utils/fieldDocAnswers.ts +128 -0
  85. package/src/utils/fieldDocDefaults.ts +36 -0
  86. package/src/utils/fieldDocProgram.ts +36 -0
  87. package/src/utils/fieldDocSummary.ts +30 -0
  88. package/src/utils/log.ts +232 -141
  89. package/src/utils/logDisplay.helpers.ts +177 -0
  90. package/src/utils/logDisplay.ts +87 -0
  91. package/src/utils/logStoreRead.ts +9 -13
  92. package/src/utils/logTaxonomy.helpers.ts +17 -0
  93. package/src/utils/logTaxonomyDisplay.ts +80 -124
  94. package/src/utils/noteDoc.ts +66 -284
  95. package/src/utils/organization.ts +117 -283
  96. package/src/utils/qrCode.helpers.ts +189 -0
  97. package/src/utils/qrCode.test.ts +519 -0
  98. package/src/utils/qrCode.ts +273 -0
  99. package/src/utils/richTextHTML.ts +385 -0
  100. package/src/utils/sheet.ts +123 -4834
  101. package/src/utils/sheetAxisMove.ts +77 -291
  102. package/src/utils/sheetBootstrap.ts +771 -1138
  103. package/src/utils/sheetCellLiteral.ts +101 -0
  104. package/src/utils/sheetCommand.ts +23 -88
  105. package/src/utils/sheetDesign.ts +705 -0
  106. package/src/utils/sheetExport.ts +17 -69
  107. package/src/utils/sheetFeatureReference.ts +183 -0
  108. package/src/utils/sheetFormulaArgs.ts +168 -0
  109. package/src/utils/sheetFormulaCompile.ts +475 -0
  110. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  111. package/src/utils/sheetFormulaCriteria.ts +656 -0
  112. package/src/utils/sheetFormulaDate.ts +444 -0
  113. package/src/utils/sheetFormulaEvaluation.ts +388 -403
  114. package/src/utils/sheetFormulaEvaluator.ts +589 -444
  115. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  116. package/src/utils/sheetFormulaLogical.ts +116 -0
  117. package/src/utils/sheetFormulaLookup.ts +488 -0
  118. package/src/utils/sheetFormulaMath.ts +48 -0
  119. package/src/utils/sheetFormulaParser.ts +729 -0
  120. package/src/utils/sheetFormulaRange.ts +330 -0
  121. package/src/utils/sheetFormulaReference.ts +703 -0
  122. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  123. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  124. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  125. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  126. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  127. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  128. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  129. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  130. package/src/utils/sheetFormulaText.ts +430 -0
  131. package/src/utils/sheetJournal.ts +140 -18
  132. package/src/utils/sheetNumberFormat.ts +68 -267
  133. package/src/utils/sheetPreview.ts +68 -0
  134. package/src/utils/sheetSequence.ts +13 -43
  135. package/src/utils/sheetSnapshot.ts +176 -429
  136. package/src/utils/sheetStructureEdit.ts +537 -907
  137. package/src/utils/sheetStructureReferences.ts +389 -0
  138. package/src/utils/storage.ts +49 -3
  139. package/src/utils/time.ts +12 -0
  140. package/src/utils/workflow.ts +199 -73
  141. package/src/utils/workflowLogFingerprint.ts +302 -0
  142. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  143. package/src/utils/workflowProgress.ts +280 -0
  144. package/src/utils/workflowTriggers.ts +61 -0
  145. package/tests/agentNote.test.ts +395 -0
  146. package/tests/campaignAI.test.ts +119 -0
  147. package/tests/campaignAccess.test.ts +239 -0
  148. package/tests/campaignEmail.test.ts +441 -0
  149. package/tests/campaignLifecycle.test.ts +134 -0
  150. package/tests/campaignPublication.test.ts +309 -0
  151. package/tests/dataTableFieldTypeRegistry.test.ts +2 -1
  152. package/tests/dataTableRelativeDate.test.ts +412 -0
  153. package/tests/email.test.ts +39 -0
  154. package/tests/fieldDocProgram.test.ts +114 -0
  155. package/tests/logDisplay.fixtures.ts +67 -0
  156. package/tests/logDisplay.test.ts +227 -0
  157. package/tests/noteDoc.test.ts +37 -192
  158. package/tests/richTextHTML.test.ts +185 -0
  159. package/tests/sheetAxisMove.test.ts +49 -40
  160. package/tests/sheetBootstrap.test.ts +1967 -0
  161. package/tests/sheetFeatureReference.test.ts +22 -0
  162. package/tests/sheetFormulaCriteria.test.ts +269 -0
  163. package/tests/sheetFormulaEvaluator.test.ts +93 -200
  164. package/tests/sheetFormulaFunctions.test.ts +538 -0
  165. package/tests/sheetFormulaLanguage.test.ts +361 -0
  166. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  167. package/tests/sheetFormulaParity.test.ts +188 -0
  168. package/tests/sheetFormulaRange.test.ts +167 -0
  169. package/tests/sheetFormulaReference.test.ts +78 -0
  170. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  171. package/tests/sheetFormulaTextDate.test.ts +512 -0
  172. package/tests/sheetSequence.test.ts +4 -23
  173. package/tests/sheetSnapshot.test.ts +134 -0
  174. package/tests/sheetStructureEdit.test.ts +492 -37
  175. package/tests/sheetStructureReferences.test.ts +589 -0
  176. package/tests/workflowLifecycleStatus.test.ts +60 -0
  177. package/tests/workflowLogFingerprint.test.ts +203 -0
  178. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  179. package/tests/workflowProgress.test.ts +180 -0
  180. package/tests/workflowTriggers.test.ts +29 -0
  181. package/src/constants/agentDoc.ts +0 -12
  182. package/src/constants/logActivityGroupColors.generated.ts +0 -19
  183. package/src/constants/schedule.ts +0 -220
  184. package/src/constants/scheduleRuleTemplateSeed.ts +0 -138
  185. package/src/constants/scheduleRuleTemplates.generated.ts +0 -145
  186. package/src/constants/sheetRegionSources.generated.ts +0 -578
  187. package/src/schemas/fieldDocsQuery.ts +0 -12
  188. package/src/schemas/organization.ts +0 -68
  189. package/src/types/agentDoc.d.ts +0 -64
  190. package/src/types/noteDoc.d.ts +0 -86
  191. package/src/types/schedule.d.ts +0 -391
  192. package/src/utils/agentDoc.ts +0 -109
  193. package/src/utils/campaignFormEditor.ts +0 -871
  194. package/src/utils/dataTableRealtimeAuthority.ts +0 -209
  195. package/src/utils/dataTableRealtimeSelection.ts +0 -134
  196. package/src/utils/dataTableRowDocument.ts +0 -508
  197. package/src/utils/dataTableSource.ts +0 -230
  198. package/src/utils/schedule.ts +0 -799
  199. package/src/utils/scheduleEvaluation.ts +0 -1994
  200. package/src/utils/scheduleICS.ts +0 -246
  201. package/src/utils/scheduleRuleTemplates.ts +0 -188
  202. package/src/utils/sheetRegion.ts +0 -374
  203. package/src/utils/sheetRegionFilter.ts +0 -1259
  204. package/src/utils/sheetRegionSourceRegistry.ts +0 -594
  205. package/tests/schedule.test.ts +0 -693
  206. package/tests/scheduleEvaluation.test.ts +0 -1970
  207. package/tests/scheduleICS.test.ts +0 -208
  208. package/tests/scheduleRuleTemplates.test.ts +0 -176
  209. package/tests/scheduleSweepInvariants.test.ts +0 -428
  210. package/tests/sheetRegionFilter.test.ts +0 -1135
@@ -1,1970 +0,0 @@
1
- import type {
2
- ScheduleEvalOccurrence,
3
- ScheduleEvalRule,
4
- ScheduleEvaluationSnapshot,
5
- } from '@jsb188/mday/utils/scheduleEvaluation.ts';
6
- import {
7
- evaluateScheduleWindow,
8
- getBlockingScheduleViolations,
9
- getScheduleBreachIdentity,
10
- getScheduleRuleIdentity,
11
- selectEffectiveScheduleRules,
12
- withSimulatedScheduleAssignment,
13
- } from '@jsb188/mday/utils/scheduleEvaluation.ts';
14
- import { describe, expect, it } from 'vitest';
15
-
16
- /*
17
- * The constraint engine decides whether a published schedule is legal, so a
18
- * quiet wrong answer here is worse than a crash: it reports a compliant
19
- * calendar that is not. These cases pin each rule kind, the sweep that feeds
20
- * them, and the scope precedence that decides which rule is even in force.
21
- */
22
-
23
- const LA = 'America/Los_Angeles';
24
-
25
- const at = (iso: string) => new Date(iso);
26
-
27
- /*
28
- * Build a snapshot around one day, filling in the parts a case does not care
29
- * about.
30
- */
31
- function snapshot(
32
- parts: Partial<ScheduleEvaluationSnapshot> = {},
33
- ): ScheduleEvaluationSnapshot {
34
- return {
35
- windowStart: at('2026-08-03T14:00:00Z'),
36
- windowEnd: at('2026-08-04T02:00:00Z'),
37
- timeZone: LA,
38
- occurrences: [],
39
- demand: [],
40
- resources: [],
41
- rules: [],
42
- ...parts,
43
- };
44
- }
45
-
46
- /*
47
- * Build one shift with its slot and assignees. Assignees are given as plain
48
- * ids so a case reads as "two people on this shift".
49
- */
50
- function shift(parts: {
51
- id: string;
52
- resourceId?: string | null;
53
- startAt: string;
54
- endAt: string;
55
- kind?: ScheduleEvalOccurrence['kind'];
56
- slotKey?: string;
57
- requiredCount?: number;
58
- qualifications?: string[] | null;
59
- assignees?: Array<{
60
- id: string;
61
- startAt?: string;
62
- endAt?: string;
63
- qualifications?: string[];
64
- role?: string;
65
- }>;
66
- }): ScheduleEvalOccurrence {
67
- const slotId = `${parts.id}-slot`;
68
-
69
- return {
70
- id: parts.id,
71
- kind: parts.kind || 'SHIFT',
72
- resourceId: parts.resourceId === undefined ? 'room-a' : parts.resourceId,
73
- startAt: at(parts.startAt),
74
- endAt: at(parts.endAt),
75
- slots: [
76
- {
77
- id: slotId,
78
- key: parts.slotKey || 'lead',
79
- requiredCount: parts.requiredCount ?? 1,
80
- predicate: parts.qualifications
81
- ? { qualifications: parts.qualifications }
82
- : null,
83
- },
84
- ],
85
- assignments: (parts.assignees || []).map((assignee) => ({
86
- id: `${parts.id}-${assignee.id}`,
87
- slotId,
88
- actorType: 'ACCOUNT' as const,
89
- actorId: assignee.id,
90
- actorAccountId: assignee.id,
91
- startAt: assignee.startAt ? at(assignee.startAt) : null,
92
- endAt: assignee.endAt ? at(assignee.endAt) : null,
93
- role: assignee.role ?? null,
94
- qualifications: assignee.qualifications ?? [],
95
- tags: [],
96
- })),
97
- };
98
- }
99
-
100
- /*
101
- * Build one rule at a chosen scope level.
102
- */
103
- function rule(
104
- parts: Partial<ScheduleEvalRule> & Pick<ScheduleEvalRule, 'id' | 'kind'>,
105
- ): ScheduleEvalRule {
106
- return {
107
- severity: 'BLOCK',
108
- config: {},
109
- operationTypeId: null,
110
- organizationId: 'org-1',
111
- calendarId: null,
112
- resourceId: null,
113
- effectiveFrom: null,
114
- effectiveTo: null,
115
- ordinal: 0,
116
- ...parts,
117
- };
118
- }
119
-
120
- describe('rule scope resolution — end to end', () => {
121
- /*
122
- * selectEffectiveScheduleRules picking the right winner is only half the
123
- * job. These cases run the whole evaluator, because the resolution used to
124
- * be correct in isolation and wrong in use: the losing rule was resolved
125
- * under a separate pass and its evaluator then reached every resource
126
- * anyway, so an override narrowed the winner without silencing the loser.
127
- */
128
-
129
- it('silences the organization rule on a resource that overrides it', () => {
130
- const { violations } = evaluateScheduleWindow(
131
- snapshot({
132
- occurrences: [
133
- shift({
134
- id: 'b1',
135
- resourceId: 'room-b',
136
- startAt: '2026-08-03T15:00:00Z',
137
- endAt: '2026-08-03T19:00:00Z',
138
- requiredCount: 0,
139
- }),
140
- shift({
141
- id: 'b2',
142
- resourceId: 'room-b',
143
- startAt: '2026-08-03T15:00:00Z',
144
- endAt: '2026-08-03T19:00:00Z',
145
- requiredCount: 0,
146
- }),
147
- ],
148
- resources: [
149
- { id: 'room-a', key: 'room-a', capacity: null, config: null },
150
- { id: 'room-b', key: 'room-b', capacity: null, config: null },
151
- ],
152
- rules: [
153
- rule({
154
- id: 'org',
155
- kind: 'RESOURCE_CAPACITY',
156
- config: { capacity: 1 },
157
- }),
158
- rule({
159
- id: 'room-b-override',
160
- kind: 'RESOURCE_CAPACITY',
161
- resourceId: 'room-b',
162
- config: { capacity: 5 },
163
- }),
164
- ],
165
- }),
166
- );
167
-
168
- // Room B is allowed 5 at once by its own rule; the organization's limit
169
- // of 1 must not still flag it
170
- expect(violations).toEqual([]);
171
- });
172
-
173
- it('still applies the organization rule to resources that do not override it', () => {
174
- const { violations } = evaluateScheduleWindow(
175
- snapshot({
176
- occurrences: [
177
- shift({
178
- id: 'a1',
179
- resourceId: 'room-a',
180
- startAt: '2026-08-03T15:00:00Z',
181
- endAt: '2026-08-03T19:00:00Z',
182
- requiredCount: 0,
183
- }),
184
- shift({
185
- id: 'a2',
186
- resourceId: 'room-a',
187
- startAt: '2026-08-03T15:00:00Z',
188
- endAt: '2026-08-03T19:00:00Z',
189
- requiredCount: 0,
190
- }),
191
- ],
192
- resources: [
193
- { id: 'room-a', key: 'room-a', capacity: null, config: null },
194
- { id: 'room-b', key: 'room-b', capacity: null, config: null },
195
- ],
196
- rules: [
197
- rule({
198
- id: 'org',
199
- kind: 'RESOURCE_CAPACITY',
200
- config: { capacity: 1 },
201
- }),
202
- rule({
203
- id: 'room-b-override',
204
- kind: 'RESOURCE_CAPACITY',
205
- resourceId: 'room-b',
206
- config: { capacity: 5 },
207
- }),
208
- ],
209
- }),
210
- );
211
-
212
- expect(violations).toHaveLength(1);
213
- expect(violations[0].resourceId).toBe('room-a');
214
- });
215
-
216
- it('fires a resource-scoped EXCLUSION_WINDOW rule', () => {
217
- // Cross-segment kinds were resolved once against a null resource, which
218
- // filters resource-scoped rules out entirely — so "turnover between
219
- // classes in Room A", the motivating example in the evaluator's own doc
220
- // comment, silently did nothing
221
- const scoped = evaluateScheduleWindow(
222
- snapshot({
223
- occurrences: [
224
- shift({
225
- id: 'clean',
226
- resourceId: 'room-a',
227
- kind: 'BLOCK',
228
- startAt: '2026-08-03T15:00:00Z',
229
- endAt: '2026-08-03T16:00:00Z',
230
- requiredCount: 0,
231
- }),
232
- shift({
233
- id: 'next',
234
- resourceId: 'room-a',
235
- startAt: '2026-08-03T16:10:00Z',
236
- endAt: '2026-08-03T18:00:00Z',
237
- requiredCount: 0,
238
- }),
239
- ],
240
- rules: [
241
- rule({
242
- id: 'turnover',
243
- kind: 'EXCLUSION_WINDOW',
244
- resourceId: 'room-a',
245
- config: { afterKind: 'BLOCK', blockMinutes: 30 },
246
- }),
247
- ],
248
- }),
249
- );
250
-
251
- expect(scoped.violations).toHaveLength(1);
252
- expect(scoped.violations[0].occurrenceId).toBe('next');
253
- });
254
-
255
- it('fires a resource-scoped ACTOR_WINDOW_AGGREGATE rule', () => {
256
- const scoped = evaluateScheduleWindow(
257
- snapshot({
258
- windowStart: at('2026-08-03T00:00:00Z'),
259
- windowEnd: at('2026-08-04T00:00:00Z'),
260
- occurrences: [
261
- shift({
262
- id: 's1',
263
- resourceId: 'room-a',
264
- startAt: '2026-08-03T02:00:00Z',
265
- endAt: '2026-08-03T06:00:00Z',
266
- requiredCount: 0,
267
- assignees: [{ id: 'acct-1' }],
268
- }),
269
- shift({
270
- id: 's2',
271
- resourceId: 'room-a',
272
- startAt: '2026-08-03T08:00:00Z',
273
- endAt: '2026-08-03T12:00:00Z',
274
- requiredCount: 0,
275
- assignees: [{ id: 'acct-1' }],
276
- }),
277
- ],
278
- rules: [
279
- rule({
280
- id: 'max-shifts',
281
- kind: 'ACTOR_WINDOW_AGGREGATE',
282
- resourceId: 'room-a',
283
- config: { metric: 'SHIFTS', windowHours: 24, max: 1 },
284
- }),
285
- ],
286
- }),
287
- );
288
-
289
- expect(scoped.violations).toHaveLength(1);
290
- expect(scoped.violations[0].actorAccountId).toBe('acct-1');
291
- });
292
- });
293
-
294
- describe('effective dates apply to every rule kind', () => {
295
- /*
296
- * The five segment-local kinds are resolved per segment and honour their
297
- * effective dates. The two cross-segment kinds were resolved once, against
298
- * the window's left edge, so a rule's whole effective window collapsed to a
299
- * single yes/no taken before the breach it was meant to judge. One
300
- * evaluation gave two different answers to "is this rule in force" depending
301
- * only on which kind was asking.
302
- */
303
-
304
- const turnover = (parts: Partial<ScheduleEvalRule>) =>
305
- snapshot({
306
- windowStart: at('2026-08-03T00:00:00Z'),
307
- windowEnd: at('2026-08-10T00:00:00Z'),
308
- occurrences: [
309
- shift({
310
- id: 'clean',
311
- kind: 'BLOCK',
312
- startAt: '2026-08-05T08:00:00Z',
313
- endAt: '2026-08-05T09:00:00Z',
314
- requiredCount: 0,
315
- }),
316
- shift({
317
- id: 'class',
318
- startAt: '2026-08-05T09:10:00Z',
319
- endAt: '2026-08-05T10:00:00Z',
320
- requiredCount: 0,
321
- }),
322
- ],
323
- rules: [
324
- rule({
325
- id: 'turnover',
326
- kind: 'EXCLUSION_WINDOW',
327
- config: { afterKind: 'BLOCK', blockMinutes: 60 },
328
- ...parts,
329
- }),
330
- ],
331
- });
332
-
333
- it('fires a cross-segment rule that came into force before the breach', () => {
334
- // effectiveFrom is a day BEFORE the breach, so the rule is unambiguously
335
- // in force when it happens
336
- const { violations } = evaluateScheduleWindow(
337
- turnover({ effectiveFrom: at('2026-08-04T00:00:00Z') }),
338
- );
339
-
340
- expect(violations).toHaveLength(1);
341
- expect(violations[0].occurrenceId).toBe('class');
342
- });
343
-
344
- it('stays silent for a cross-segment rule that expired before the breach', () => {
345
- // An expired BLOCK-severity rule that still fires does not merely
346
- // mis-report — it refuses to let the window be published at all
347
- const { violations } = evaluateScheduleWindow(
348
- turnover({ effectiveTo: at('2026-08-04T00:00:00Z') }),
349
- );
350
-
351
- expect(violations).toEqual([]);
352
- });
353
-
354
- it('stays silent for a cross-segment rule not yet in force at the breach', () => {
355
- const { violations } = evaluateScheduleWindow(
356
- turnover({ effectiveFrom: at('2026-08-06T00:00:00Z') }),
357
- );
358
-
359
- expect(violations).toEqual([]);
360
- });
361
-
362
- it('applies effective dates to rolling per-actor limits too', () => {
363
- const overtime = (parts: Partial<ScheduleEvalRule>) =>
364
- evaluateScheduleWindow(
365
- snapshot({
366
- windowStart: at('2026-08-03T00:00:00Z'),
367
- windowEnd: at('2026-08-10T00:00:00Z'),
368
- occurrences: [
369
- shift({
370
- id: 'long',
371
- startAt: '2026-08-05T00:00:00Z',
372
- endAt: '2026-08-07T02:00:00Z',
373
- requiredCount: 0,
374
- assignees: [{ id: 'acct-1' }],
375
- }),
376
- ],
377
- rules: [
378
- rule({
379
- id: 'cap',
380
- kind: 'ACTOR_WINDOW_AGGREGATE',
381
- config: { metric: 'HOURS', windowHours: 168, max: 40 },
382
- ...parts,
383
- }),
384
- ],
385
- }),
386
- ).violations;
387
-
388
- expect(
389
- overtime({ effectiveFrom: at('2026-08-04T00:00:00Z') }),
390
- ).toHaveLength(1);
391
- expect(overtime({ effectiveTo: at('2026-08-04T00:00:00Z') })).toEqual([]);
392
- });
393
- });
394
-
395
- describe('rule scope resolution', () => {
396
- it('lets the most specific scope win', () => {
397
- const rules = [
398
- rule({
399
- id: 'op',
400
- kind: 'DERIVED_COUNT',
401
- operationTypeId: 'op-1',
402
- organizationId: null,
403
- config: { category: 'INFANT', divisor: 4 },
404
- }),
405
- rule({
406
- id: 'org',
407
- kind: 'DERIVED_COUNT',
408
- config: { category: 'INFANT', divisor: 3 },
409
- }),
410
- rule({
411
- id: 'cal',
412
- kind: 'DERIVED_COUNT',
413
- calendarId: 'cal-1',
414
- config: { category: 'INFANT', divisor: 2 },
415
- }),
416
- ];
417
-
418
- const effective = selectEffectiveScheduleRules(
419
- rules,
420
- 'room-a',
421
- at('2026-08-03T15:00:00Z'),
422
- );
423
-
424
- expect(effective.map((r) => r.id)).toEqual(['cal']);
425
- });
426
-
427
- it('scopes an override to its own resource', () => {
428
- const rules = [
429
- rule({ id: 'org', kind: 'RESOURCE_CAPACITY', config: { capacity: 1 } }),
430
- rule({
431
- id: 'room-b-only',
432
- kind: 'RESOURCE_CAPACITY',
433
- resourceId: 'room-b',
434
- config: { capacity: 5 },
435
- }),
436
- ];
437
-
438
- expect(
439
- selectEffectiveScheduleRules(
440
- rules,
441
- 'room-b',
442
- at('2026-08-03T15:00:00Z'),
443
- ).map((r) => r.id),
444
- ).toEqual(['room-b-only']);
445
- expect(
446
- selectEffectiveScheduleRules(
447
- rules,
448
- 'room-a',
449
- at('2026-08-03T15:00:00Z'),
450
- ).map((r) => r.id),
451
- ).toEqual(['org']);
452
- });
453
-
454
- it('keeps two rules of the same kind about different things', () => {
455
- // The whole point of rule identity: adding a toddler ratio must not
456
- // silently switch off the infant ratio
457
- const rules = [
458
- rule({
459
- id: 'infant',
460
- kind: 'DERIVED_COUNT',
461
- config: { category: 'INFANT', divisor: 4 },
462
- }),
463
- rule({
464
- id: 'toddler',
465
- kind: 'DERIVED_COUNT',
466
- config: { category: 'TODDLER', divisor: 6 },
467
- }),
468
- ];
469
-
470
- expect(
471
- selectEffectiveScheduleRules(rules, 'room-a', at('2026-08-03T15:00:00Z'))
472
- .map((r) => r.id)
473
- .sort(),
474
- ).toEqual(['infant', 'toddler']);
475
- });
476
-
477
- it('derives identity from what a rule is about', () => {
478
- expect(
479
- getScheduleRuleIdentity(
480
- rule({
481
- id: 'a',
482
- kind: 'DERIVED_COUNT',
483
- config: { category: 'INFANT' },
484
- }),
485
- ),
486
- ).toBe('DERIVED_COUNT:INFANT');
487
- expect(
488
- getScheduleRuleIdentity(rule({ id: 'b', kind: 'RESOURCE_CAPACITY' })),
489
- ).toBe('RESOURCE_CAPACITY');
490
- });
491
-
492
- it('ignores a rule outside its effective window', () => {
493
- const rules = [
494
- rule({
495
- id: 'expired',
496
- kind: 'RESOURCE_CAPACITY',
497
- config: { capacity: 1 },
498
- effectiveTo: at('2026-08-01T00:00:00Z'),
499
- }),
500
- ];
501
-
502
- expect(
503
- selectEffectiveScheduleRules(rules, 'room-a', at('2026-08-03T15:00:00Z')),
504
- ).toEqual([]);
505
- });
506
- });
507
-
508
- describe('REQUIRED_COUNT', () => {
509
- it('flags a slot that is short an assignee', () => {
510
- const { violations } = evaluateScheduleWindow(
511
- snapshot({
512
- occurrences: [
513
- shift({
514
- id: 'shift-1',
515
- startAt: '2026-08-03T14:00:00Z',
516
- endAt: '2026-08-03T18:00:00Z',
517
- requiredCount: 2,
518
- assignees: [{ id: 'acct-1' }],
519
- }),
520
- ],
521
- rules: [rule({ id: 'r1', kind: 'REQUIRED_COUNT' })],
522
- }),
523
- );
524
-
525
- expect(violations).toHaveLength(1);
526
- expect(violations[0].detail).toMatchObject({
527
- required: 2,
528
- actual: 1,
529
- shortfall: 1,
530
- });
531
- expect(violations[0].occurrenceId).toBe('shift-1');
532
- });
533
-
534
- it('says nothing when the slot is filled', () => {
535
- const { violations } = evaluateScheduleWindow(
536
- snapshot({
537
- occurrences: [
538
- shift({
539
- id: 'shift-1',
540
- startAt: '2026-08-03T14:00:00Z',
541
- endAt: '2026-08-03T18:00:00Z',
542
- requiredCount: 2,
543
- assignees: [{ id: 'acct-1' }, { id: 'acct-2' }],
544
- }),
545
- ],
546
- rules: [rule({ id: 'r1', kind: 'REQUIRED_COUNT' })],
547
- }),
548
- );
549
-
550
- expect(violations).toEqual([]);
551
- });
552
-
553
- it('reports only the part of a shift a partial assignment leaves uncovered', () => {
554
- // The reason segments exist: someone covering 14:00-16:00 of a
555
- // 14:00-18:00 shift leaves exactly the back half short
556
- const { violations } = evaluateScheduleWindow(
557
- snapshot({
558
- occurrences: [
559
- shift({
560
- id: 'shift-1',
561
- startAt: '2026-08-03T14:00:00Z',
562
- endAt: '2026-08-03T18:00:00Z',
563
- requiredCount: 1,
564
- assignees: [
565
- {
566
- id: 'acct-1',
567
- startAt: '2026-08-03T14:00:00Z',
568
- endAt: '2026-08-03T16:00:00Z',
569
- },
570
- ],
571
- }),
572
- ],
573
- rules: [rule({ id: 'r1', kind: 'REQUIRED_COUNT' })],
574
- }),
575
- );
576
-
577
- expect(violations).toHaveLength(1);
578
- expect(violations[0].segmentStart.toISOString()).toBe(
579
- '2026-08-03T16:00:00.000Z',
580
- );
581
- expect(violations[0].segmentEnd.toISOString()).toBe(
582
- '2026-08-03T18:00:00.000Z',
583
- );
584
- });
585
-
586
- it('does not count an assignee who fails the slot predicate', () => {
587
- const { violations } = evaluateScheduleWindow(
588
- snapshot({
589
- occurrences: [
590
- shift({
591
- id: 'shift-1',
592
- startAt: '2026-08-03T14:00:00Z',
593
- endAt: '2026-08-03T18:00:00Z',
594
- requiredCount: 1,
595
- qualifications: ['INFANT'],
596
- assignees: [{ id: 'acct-1', qualifications: ['TODDLER'] }],
597
- }),
598
- ],
599
- rules: [rule({ id: 'r1', kind: 'REQUIRED_COUNT' })],
600
- }),
601
- );
602
-
603
- expect(violations).toHaveLength(1);
604
- expect(violations[0].detail).toMatchObject({ actual: 0 });
605
- });
606
- });
607
-
608
- describe('DERIVED_COUNT — the ratio rule', () => {
609
- const ratioSnapshot = (quantity: number, assignees: number) =>
610
- snapshot({
611
- occurrences: [
612
- shift({
613
- id: 'shift-1',
614
- startAt: '2026-08-03T14:00:00Z',
615
- endAt: '2026-08-03T18:00:00Z',
616
- requiredCount: 0,
617
- assignees: Array.from({ length: assignees }, (_, i) => ({
618
- id: `acct-${i + 1}`,
619
- })),
620
- }),
621
- ],
622
- demand: [
623
- {
624
- resourceId: 'room-a',
625
- category: 'INFANT',
626
- startAt: at('2026-08-03T14:00:00Z'),
627
- endAt: at('2026-08-03T18:00:00Z'),
628
- quantity,
629
- },
630
- ],
631
- rules: [
632
- rule({
633
- id: 'ratio',
634
- kind: 'DERIVED_COUNT',
635
- config: { category: 'INFANT', divisor: 4 },
636
- }),
637
- ],
638
- });
639
-
640
- it('rounds the requirement up', () => {
641
- // 9 infants at 1:4 needs 3 adults, not 2.25
642
- const { violations } = evaluateScheduleWindow(ratioSnapshot(9, 2));
643
-
644
- expect(violations).toHaveLength(1);
645
- expect(violations[0].detail).toMatchObject({
646
- quantity: 9,
647
- divisor: 4,
648
- required: 3,
649
- actual: 2,
650
- });
651
- });
652
-
653
- it('is satisfied exactly at the ratio', () => {
654
- expect(evaluateScheduleWindow(ratioSnapshot(8, 2)).violations).toEqual([]);
655
- });
656
-
657
- it('follows the demand down mid-shift', () => {
658
- // 9 infants until 16:00 then 5: the second half needs only 2 adults,
659
- // so a 2-person shift is short only for the first half
660
- const { violations } = evaluateScheduleWindow(
661
- snapshot({
662
- occurrences: [
663
- shift({
664
- id: 'shift-1',
665
- startAt: '2026-08-03T14:00:00Z',
666
- endAt: '2026-08-03T18:00:00Z',
667
- requiredCount: 0,
668
- assignees: [{ id: 'acct-1' }, { id: 'acct-2' }],
669
- }),
670
- ],
671
- demand: [
672
- {
673
- resourceId: 'room-a',
674
- category: 'INFANT',
675
- startAt: at('2026-08-03T14:00:00Z'),
676
- endAt: at('2026-08-03T16:00:00Z'),
677
- quantity: 9,
678
- },
679
- {
680
- resourceId: 'room-a',
681
- category: 'INFANT',
682
- startAt: at('2026-08-03T16:00:00Z'),
683
- endAt: at('2026-08-03T18:00:00Z'),
684
- quantity: 5,
685
- },
686
- ],
687
- rules: [
688
- rule({
689
- id: 'ratio',
690
- kind: 'DERIVED_COUNT',
691
- config: { category: 'INFANT', divisor: 4 },
692
- }),
693
- ],
694
- }),
695
- );
696
-
697
- expect(violations).toHaveLength(1);
698
- expect(violations[0].segmentStart.toISOString()).toBe(
699
- '2026-08-03T14:00:00.000Z',
700
- );
701
- expect(violations[0].segmentEnd.toISOString()).toBe(
702
- '2026-08-03T16:00:00.000Z',
703
- );
704
- });
705
-
706
- it('ignores a demand category no rule asks about', () => {
707
- const { violations } = evaluateScheduleWindow(
708
- snapshot({
709
- occurrences: [
710
- shift({
711
- id: 'shift-1',
712
- startAt: '2026-08-03T14:00:00Z',
713
- endAt: '2026-08-03T18:00:00Z',
714
- requiredCount: 0,
715
- }),
716
- ],
717
- demand: [
718
- {
719
- resourceId: 'room-a',
720
- category: 'PRESCHOOL',
721
- startAt: at('2026-08-03T14:00:00Z'),
722
- endAt: at('2026-08-03T18:00:00Z'),
723
- quantity: 40,
724
- },
725
- ],
726
- rules: [
727
- rule({
728
- id: 'ratio',
729
- kind: 'DERIVED_COUNT',
730
- config: { category: 'INFANT', divisor: 4 },
731
- }),
732
- ],
733
- }),
734
- );
735
-
736
- expect(violations).toEqual([]);
737
- });
738
- });
739
-
740
- describe('RESOURCE_CAPACITY', () => {
741
- it('flags a double-booked room', () => {
742
- const { violations } = evaluateScheduleWindow(
743
- snapshot({
744
- resources: [{ id: 'room-a', key: 'room_a', capacity: 1 }],
745
- occurrences: [
746
- shift({
747
- id: 'shift-1',
748
- startAt: '2026-08-03T14:00:00Z',
749
- endAt: '2026-08-03T18:00:00Z',
750
- requiredCount: 0,
751
- }),
752
- shift({
753
- id: 'shift-2',
754
- startAt: '2026-08-03T16:00:00Z',
755
- endAt: '2026-08-03T20:00:00Z',
756
- requiredCount: 0,
757
- }),
758
- ],
759
- rules: [rule({ id: 'cap', kind: 'RESOURCE_CAPACITY' })],
760
- }),
761
- );
762
-
763
- expect(violations).toHaveLength(1);
764
- expect(violations[0].detail).toMatchObject({ capacity: 1, actual: 2 });
765
- // Only the overlapping stretch is in breach
766
- expect(violations[0].segmentStart.toISOString()).toBe(
767
- '2026-08-03T16:00:00.000Z',
768
- );
769
- expect(violations[0].segmentEnd.toISOString()).toBe(
770
- '2026-08-03T18:00:00.000Z',
771
- );
772
- });
773
-
774
- it('allows back-to-back bookings that only touch', () => {
775
- const { violations } = evaluateScheduleWindow(
776
- snapshot({
777
- resources: [{ id: 'room-a', key: 'room_a', capacity: 1 }],
778
- occurrences: [
779
- shift({
780
- id: 'shift-1',
781
- startAt: '2026-08-03T14:00:00Z',
782
- endAt: '2026-08-03T16:00:00Z',
783
- requiredCount: 0,
784
- }),
785
- shift({
786
- id: 'shift-2',
787
- startAt: '2026-08-03T16:00:00Z',
788
- endAt: '2026-08-03T18:00:00Z',
789
- requiredCount: 0,
790
- }),
791
- ],
792
- rules: [rule({ id: 'cap', kind: 'RESOURCE_CAPACITY' })],
793
- }),
794
- );
795
-
796
- expect(violations).toEqual([]);
797
- });
798
- });
799
-
800
- describe('ELIGIBILITY_AT_TIME', () => {
801
- it('flags the part of a shift after a credential lapses', () => {
802
- // The reason eligibility is judged per segment: the same shift is legal
803
- // until 16:00 and illegal after it
804
- const occurrence = shift({
805
- id: 'shift-1',
806
- startAt: '2026-08-03T14:00:00Z',
807
- endAt: '2026-08-03T18:00:00Z',
808
- requiredCount: 0,
809
- assignees: [{ id: 'acct-1', qualifications: ['CPR'] }],
810
- });
811
- occurrence.assignments[0].qualificationExpiry = {
812
- CPR: at('2026-08-03T16:00:00Z'),
813
- };
814
-
815
- const { violations } = evaluateScheduleWindow(
816
- snapshot({
817
- occurrences: [occurrence],
818
- rules: [
819
- rule({
820
- id: 'cpr',
821
- kind: 'ELIGIBILITY_AT_TIME',
822
- config: { qualification: 'CPR' },
823
- }),
824
- ],
825
- }),
826
- );
827
-
828
- expect(violations).toHaveLength(1);
829
- expect(violations[0].segmentStart.toISOString()).toBe(
830
- '2026-08-03T16:00:00.000Z',
831
- );
832
- expect(violations[0].segmentEnd.toISOString()).toBe(
833
- '2026-08-03T18:00:00.000Z',
834
- );
835
- });
836
-
837
- it('stops counting a lapsed credential toward a slot predicate', () => {
838
- const occurrence = shift({
839
- id: 'shift-1',
840
- startAt: '2026-08-03T14:00:00Z',
841
- endAt: '2026-08-03T18:00:00Z',
842
- requiredCount: 1,
843
- qualifications: ['INFANT'],
844
- assignees: [{ id: 'acct-1', qualifications: ['INFANT'] }],
845
- });
846
- occurrence.assignments[0].qualificationExpiry = {
847
- INFANT: at('2026-08-03T16:00:00Z'),
848
- };
849
-
850
- const { violations } = evaluateScheduleWindow(
851
- snapshot({
852
- occurrences: [occurrence],
853
- rules: [rule({ id: 'r1', kind: 'REQUIRED_COUNT' })],
854
- }),
855
- );
856
-
857
- expect(violations).toHaveLength(1);
858
- expect(violations[0].segmentStart.toISOString()).toBe(
859
- '2026-08-03T16:00:00.000Z',
860
- );
861
- });
862
-
863
- it('flags an assignee missing the required credential', () => {
864
- const { violations } = evaluateScheduleWindow(
865
- snapshot({
866
- occurrences: [
867
- shift({
868
- id: 'shift-1',
869
- startAt: '2026-08-03T14:00:00Z',
870
- endAt: '2026-08-03T18:00:00Z',
871
- requiredCount: 0,
872
- assignees: [
873
- { id: 'acct-1', qualifications: ['CPR'] },
874
- { id: 'acct-2', qualifications: [] },
875
- ],
876
- }),
877
- ],
878
- rules: [
879
- rule({
880
- id: 'cpr',
881
- kind: 'ELIGIBILITY_AT_TIME',
882
- config: { qualification: 'CPR' },
883
- }),
884
- ],
885
- }),
886
- );
887
-
888
- expect(violations).toHaveLength(1);
889
- expect(violations[0].actorAccountId).toBe('acct-2');
890
- });
891
- });
892
-
893
- describe('ACTOR_WINDOW_AGGREGATE', () => {
894
- it('counts hours the person already worked before the window', () => {
895
- // 38 hours of history plus a 4-hour shift breaks a 40-hour cap; without
896
- // the history this shift looks perfectly fine
897
- const { violations } = evaluateScheduleWindow(
898
- snapshot({
899
- occurrences: [
900
- shift({
901
- id: 'shift-1',
902
- startAt: '2026-08-03T14:00:00Z',
903
- endAt: '2026-08-03T18:00:00Z',
904
- requiredCount: 0,
905
- assignees: [{ id: 'acct-1' }],
906
- }),
907
- ],
908
- actorHistory: [
909
- {
910
- occurrenceId: 'past-1',
911
- actorAccountId: 'acct-1',
912
- startAt: at('2026-07-30T00:00:00Z'),
913
- endAt: at('2026-07-31T14:00:00Z'),
914
- },
915
- ],
916
- rules: [
917
- rule({
918
- id: 'overtime',
919
- kind: 'ACTOR_WINDOW_AGGREGATE',
920
- severity: 'WARN',
921
- config: { metric: 'HOURS', windowHours: 168, max: 40 },
922
- }),
923
- ],
924
- }),
925
- );
926
-
927
- expect(violations).toHaveLength(1);
928
- expect(violations[0].actorAccountId).toBe('acct-1');
929
- expect(violations[0].detail).toMatchObject({ metric: 'HOURS', max: 40 });
930
- expect(Number(violations[0].detail.total)).toBeCloseTo(42, 5);
931
- });
932
-
933
- it('stays quiet under the cap', () => {
934
- const { violations } = evaluateScheduleWindow(
935
- snapshot({
936
- occurrences: [
937
- shift({
938
- id: 'shift-1',
939
- startAt: '2026-08-03T14:00:00Z',
940
- endAt: '2026-08-03T18:00:00Z',
941
- requiredCount: 0,
942
- assignees: [{ id: 'acct-1' }],
943
- }),
944
- ],
945
- rules: [
946
- rule({
947
- id: 'overtime',
948
- kind: 'ACTOR_WINDOW_AGGREGATE',
949
- config: { metric: 'HOURS', windowHours: 168, max: 40 },
950
- }),
951
- ],
952
- }),
953
- );
954
-
955
- expect(violations).toEqual([]);
956
- });
957
-
958
- it('keeps counting hours worked in a room that carries its own cap', () => {
959
- // Twelve hours in room A and twelve in room B against a sixteen-hour
960
- // cap. A rolling limit is a fact about a PERSON, so adding a per-room
961
- // rule must not subtract that room's hours from everybody's total —
962
- // which is how twenty-four hours of work came to pass a sixteen-hour cap
963
- // the moment somebody wrote a second rule.
964
- const { violations } = evaluateScheduleWindow(
965
- snapshot({
966
- windowStart: at('2026-08-03T00:00:00Z'),
967
- windowEnd: at('2026-08-04T00:00:00Z'),
968
- occurrences: [
969
- shift({
970
- id: 'in-a',
971
- resourceId: 'room-a',
972
- startAt: '2026-08-03T00:00:00Z',
973
- endAt: '2026-08-03T12:00:00Z',
974
- requiredCount: 0,
975
- assignees: [{ id: 'acct-1' }],
976
- }),
977
- shift({
978
- id: 'in-b',
979
- resourceId: 'room-b',
980
- startAt: '2026-08-03T12:00:00Z',
981
- endAt: '2026-08-04T00:00:00Z',
982
- requiredCount: 0,
983
- assignees: [{ id: 'acct-1' }],
984
- }),
985
- ],
986
- rules: [
987
- rule({
988
- id: 'org-cap',
989
- kind: 'ACTOR_WINDOW_AGGREGATE',
990
- config: { metric: 'HOURS', windowHours: 24, max: 16 },
991
- }),
992
- rule({
993
- id: 'room-b-cap',
994
- kind: 'ACTOR_WINDOW_AGGREGATE',
995
- resourceId: 'room-b',
996
- config: { metric: 'HOURS', windowHours: 24, max: 16 },
997
- }),
998
- ],
999
- }),
1000
- );
1001
-
1002
- expect(violations.length).toBeGreaterThan(0);
1003
- expect(Number(violations[0].detail.total)).toBeCloseTo(24, 5);
1004
- });
1005
-
1006
- it('counts both halves of a split shift on one occurrence', () => {
1007
- // Two partial assignments with a gap between them total eighteen hours
1008
- // against a twelve-hour cap. Deduping the actor timeline by occurrence
1009
- // alone collapsed them to one and reported nine.
1010
- const occurrence = shift({
1011
- id: 'long-day',
1012
- startAt: '2026-08-03T00:00:00Z',
1013
- endAt: '2026-08-03T20:00:00Z',
1014
- requiredCount: 0,
1015
- });
1016
-
1017
- occurrence.assignments = [
1018
- {
1019
- id: 'morning',
1020
- slotId: 'long-day-slot',
1021
- actorType: 'ACCOUNT',
1022
- actorId: 'acct-1',
1023
- actorAccountId: 'acct-1',
1024
- startAt: at('2026-08-03T00:00:00Z'),
1025
- endAt: at('2026-08-03T09:00:00Z'),
1026
- role: null,
1027
- qualifications: [],
1028
- tags: [],
1029
- },
1030
- {
1031
- id: 'evening',
1032
- slotId: 'long-day-slot',
1033
- actorType: 'ACCOUNT',
1034
- actorId: 'acct-1',
1035
- actorAccountId: 'acct-1',
1036
- startAt: at('2026-08-03T11:00:00Z'),
1037
- endAt: at('2026-08-03T20:00:00Z'),
1038
- role: null,
1039
- qualifications: [],
1040
- tags: [],
1041
- },
1042
- ];
1043
-
1044
- const { violations } = evaluateScheduleWindow(
1045
- snapshot({
1046
- windowStart: at('2026-08-03T00:00:00Z'),
1047
- windowEnd: at('2026-08-03T20:00:00Z'),
1048
- occurrences: [occurrence],
1049
- rules: [
1050
- rule({
1051
- id: 'cap',
1052
- kind: 'ACTOR_WINDOW_AGGREGATE',
1053
- config: { metric: 'HOURS', windowHours: 24, max: 12 },
1054
- }),
1055
- ],
1056
- }),
1057
- );
1058
-
1059
- expect(violations.length).toBeGreaterThan(0);
1060
- expect(Number(violations[0].detail.total)).toBeCloseTo(18, 5);
1061
- });
1062
-
1063
- it('counts a shift once when history also contains it', () => {
1064
- // A history window that reaches back from this one necessarily contains
1065
- // it, so the loader hands the same shift over twice. Counting both
1066
- // copies doubled every in-window hour: this 30-hour shift plus its own
1067
- // echo used to total 60 and trip a 40-hour cap that it does not break.
1068
- const { violations } = evaluateScheduleWindow(
1069
- snapshot({
1070
- occurrences: [
1071
- shift({
1072
- id: 'shift-1',
1073
- startAt: '2026-08-03T14:00:00Z',
1074
- endAt: '2026-08-04T20:00:00Z',
1075
- requiredCount: 0,
1076
- assignees: [{ id: 'acct-1' }],
1077
- }),
1078
- ],
1079
- actorHistory: [
1080
- {
1081
- occurrenceId: 'shift-1',
1082
- actorAccountId: 'acct-1',
1083
- startAt: at('2026-08-03T14:00:00Z'),
1084
- endAt: at('2026-08-04T20:00:00Z'),
1085
- },
1086
- ],
1087
- rules: [
1088
- rule({
1089
- id: 'overtime',
1090
- kind: 'ACTOR_WINDOW_AGGREGATE',
1091
- severity: 'WARN',
1092
- config: { metric: 'HOURS', windowHours: 168, max: 40 },
1093
- }),
1094
- ],
1095
- }),
1096
- );
1097
-
1098
- expect(violations).toEqual([]);
1099
- });
1100
-
1101
- it('still counts genuinely separate shifts in the history', () => {
1102
- // The dedupe must key on the occurrence, not collapse the whole history
1103
- const { violations } = evaluateScheduleWindow(
1104
- snapshot({
1105
- occurrences: [
1106
- shift({
1107
- id: 'shift-1',
1108
- startAt: '2026-08-03T14:00:00Z',
1109
- endAt: '2026-08-03T18:00:00Z',
1110
- requiredCount: 0,
1111
- assignees: [{ id: 'acct-1' }],
1112
- }),
1113
- ],
1114
- actorHistory: [
1115
- // The loader's copy of the very shift being judged
1116
- {
1117
- occurrenceId: 'shift-1',
1118
- actorAccountId: 'acct-1',
1119
- startAt: at('2026-08-03T14:00:00Z'),
1120
- endAt: at('2026-08-03T18:00:00Z'),
1121
- },
1122
- {
1123
- occurrenceId: 'past-1',
1124
- actorAccountId: 'acct-1',
1125
- startAt: at('2026-07-30T00:00:00Z'),
1126
- endAt: at('2026-07-31T14:00:00Z'),
1127
- },
1128
- ],
1129
- rules: [
1130
- rule({
1131
- id: 'overtime',
1132
- kind: 'ACTOR_WINDOW_AGGREGATE',
1133
- severity: 'WARN',
1134
- config: { metric: 'HOURS', windowHours: 168, max: 40 },
1135
- }),
1136
- ],
1137
- }),
1138
- );
1139
-
1140
- expect(violations).toHaveLength(1);
1141
- expect(Number(violations[0].detail.total)).toBeCloseTo(42, 5);
1142
- });
1143
-
1144
- it('counts shifts rather than hours when asked to', () => {
1145
- const { violations } = evaluateScheduleWindow(
1146
- snapshot({
1147
- windowStart: at('2026-08-03T00:00:00Z'),
1148
- windowEnd: at('2026-08-04T00:00:00Z'),
1149
- occurrences: [
1150
- shift({
1151
- id: 's1',
1152
- startAt: '2026-08-03T02:00:00Z',
1153
- endAt: '2026-08-03T06:00:00Z',
1154
- requiredCount: 0,
1155
- assignees: [{ id: 'acct-1' }],
1156
- }),
1157
- shift({
1158
- id: 's2',
1159
- startAt: '2026-08-03T08:00:00Z',
1160
- endAt: '2026-08-03T12:00:00Z',
1161
- requiredCount: 0,
1162
- assignees: [{ id: 'acct-1' }],
1163
- }),
1164
- shift({
1165
- id: 's3',
1166
- startAt: '2026-08-03T14:00:00Z',
1167
- endAt: '2026-08-03T18:00:00Z',
1168
- requiredCount: 0,
1169
- assignees: [{ id: 'acct-1' }],
1170
- }),
1171
- ],
1172
- rules: [
1173
- rule({
1174
- id: 'max-shifts',
1175
- kind: 'ACTOR_WINDOW_AGGREGATE',
1176
- config: { metric: 'SHIFTS', windowHours: 24, max: 2 },
1177
- }),
1178
- ],
1179
- }),
1180
- );
1181
-
1182
- expect(violations).toHaveLength(1);
1183
- expect(violations[0].occurrenceId).toBe('s3');
1184
- });
1185
- });
1186
-
1187
- describe('EXCLUSION_WINDOW', () => {
1188
- it('flags a booking inside the blocked gap', () => {
1189
- const { violations } = evaluateScheduleWindow(
1190
- snapshot({
1191
- occurrences: [
1192
- shift({
1193
- id: 'clean',
1194
- kind: 'BLOCK',
1195
- startAt: '2026-08-03T14:00:00Z',
1196
- endAt: '2026-08-03T15:00:00Z',
1197
- requiredCount: 0,
1198
- }),
1199
- shift({
1200
- id: 'next',
1201
- startAt: '2026-08-03T15:10:00Z',
1202
- endAt: '2026-08-03T18:00:00Z',
1203
- requiredCount: 0,
1204
- }),
1205
- ],
1206
- rules: [
1207
- rule({
1208
- id: 'turnover',
1209
- kind: 'EXCLUSION_WINDOW',
1210
- config: { afterKind: 'BLOCK', blockMinutes: 30 },
1211
- }),
1212
- ],
1213
- }),
1214
- );
1215
-
1216
- expect(violations).toHaveLength(1);
1217
- expect(violations[0].occurrenceId).toBe('next');
1218
- expect(violations[0].detail).toMatchObject({
1219
- blockMinutes: 30,
1220
- gapMinutes: 10,
1221
- precededByOccurrenceId: 'clean',
1222
- });
1223
- });
1224
-
1225
- it('allows a booking after the gap has cleared', () => {
1226
- const { violations } = evaluateScheduleWindow(
1227
- snapshot({
1228
- occurrences: [
1229
- shift({
1230
- id: 'clean',
1231
- kind: 'BLOCK',
1232
- startAt: '2026-08-03T14:00:00Z',
1233
- endAt: '2026-08-03T15:00:00Z',
1234
- requiredCount: 0,
1235
- }),
1236
- shift({
1237
- id: 'next',
1238
- startAt: '2026-08-03T15:30:00Z',
1239
- endAt: '2026-08-03T18:00:00Z',
1240
- requiredCount: 0,
1241
- }),
1242
- ],
1243
- rules: [
1244
- rule({
1245
- id: 'turnover',
1246
- kind: 'EXCLUSION_WINDOW',
1247
- config: { afterKind: 'BLOCK', blockMinutes: 30 },
1248
- }),
1249
- ],
1250
- }),
1251
- );
1252
-
1253
- expect(violations).toEqual([]);
1254
- });
1255
- });
1256
-
1257
- describe('CONTINUOUS_COVERAGE', () => {
1258
- it('flags an unstaffed stretch inside opening hours', () => {
1259
- // Open 07:00-11:00 local (14:00-18:00Z in August PDT); staffed only
1260
- // until 09:00 local
1261
- const { violations } = evaluateScheduleWindow(
1262
- snapshot({
1263
- windowStart: at('2026-08-03T14:00:00Z'),
1264
- windowEnd: at('2026-08-03T18:00:00Z'),
1265
- occurrences: [
1266
- shift({
1267
- id: 'shift-1',
1268
- startAt: '2026-08-03T14:00:00Z',
1269
- endAt: '2026-08-03T16:00:00Z',
1270
- requiredCount: 0,
1271
- assignees: [{ id: 'acct-1' }],
1272
- }),
1273
- ],
1274
- rules: [
1275
- rule({
1276
- id: 'open',
1277
- kind: 'CONTINUOUS_COVERAGE',
1278
- config: { opensAt: '07:00', closesAt: '11:00' },
1279
- }),
1280
- ],
1281
- }),
1282
- );
1283
-
1284
- expect(violations).toHaveLength(1);
1285
- expect(violations[0].detail).toMatchObject({ reason: 'NO_COVERAGE' });
1286
- expect(violations[0].segmentStart.toISOString()).toBe(
1287
- '2026-08-03T16:00:00.000Z',
1288
- );
1289
- expect(violations[0].segmentEnd.toISOString()).toBe(
1290
- '2026-08-03T18:00:00.000Z',
1291
- );
1292
- });
1293
-
1294
- it('flags a completely empty day', () => {
1295
- // The case the rule exists for, and the one it used to miss entirely.
1296
- // With nothing scheduled the sweep produces a single segment starting at
1297
- // local midnight, and judging that segment by its start instant put it
1298
- // before opening time — so the rule that fires on absence was switched
1299
- // off by absence, and an unstaffed day reported clean.
1300
- const { violations } = evaluateScheduleWindow(
1301
- snapshot({
1302
- windowStart: at('2026-08-03T07:00:00Z'), // local midnight
1303
- windowEnd: at('2026-08-04T07:00:00Z'),
1304
- rules: [
1305
- rule({
1306
- id: 'open',
1307
- kind: 'CONTINUOUS_COVERAGE',
1308
- config: { opensAt: '07:00', closesAt: '11:00' },
1309
- }),
1310
- ],
1311
- }),
1312
- );
1313
-
1314
- expect(violations).toHaveLength(1);
1315
- expect(violations[0].detail).toMatchObject({ reason: 'NO_COVERAGE' });
1316
- expect(violations[0].segmentStart.toISOString()).toBe(
1317
- '2026-08-03T14:00:00.000Z',
1318
- );
1319
- expect(violations[0].segmentEnd.toISOString()).toBe(
1320
- '2026-08-03T18:00:00.000Z',
1321
- );
1322
- });
1323
-
1324
- it('reports a gap from opening time, not from the start of the day', () => {
1325
- const { violations } = evaluateScheduleWindow(
1326
- snapshot({
1327
- windowStart: at('2026-08-03T07:00:00Z'), // local midnight
1328
- windowEnd: at('2026-08-04T07:00:00Z'),
1329
- occurrences: [
1330
- shift({
1331
- id: 'late',
1332
- startAt: '2026-08-03T16:00:00Z', // 09:00 local
1333
- endAt: '2026-08-03T18:00:00Z', // 11:00 local, closing
1334
- requiredCount: 0,
1335
- assignees: [{ id: 'acct-1' }],
1336
- }),
1337
- ],
1338
- rules: [
1339
- rule({
1340
- id: 'open',
1341
- kind: 'CONTINUOUS_COVERAGE',
1342
- config: { opensAt: '07:00', closesAt: '11:00' },
1343
- }),
1344
- ],
1345
- }),
1346
- );
1347
-
1348
- expect(violations).toHaveLength(1);
1349
- expect(violations[0].segmentStart.toISOString()).toBe(
1350
- '2026-08-03T14:00:00.000Z',
1351
- );
1352
- expect(violations[0].segmentEnd.toISOString()).toBe(
1353
- '2026-08-03T16:00:00.000Z',
1354
- );
1355
- });
1356
-
1357
- it('stops reporting at closing time', () => {
1358
- // A segment straddling closesAt used to be judged entirely by its start
1359
- // instant, so an uncovered stretch was reported running past closing
1360
- const { violations } = evaluateScheduleWindow(
1361
- snapshot({
1362
- windowStart: at('2026-08-03T07:00:00Z'),
1363
- windowEnd: at('2026-08-04T07:00:00Z'),
1364
- occurrences: [
1365
- shift({
1366
- id: 'early',
1367
- startAt: '2026-08-03T14:00:00Z', // 07:00 local, opening
1368
- endAt: '2026-08-03T16:00:00Z', // 09:00 local
1369
- requiredCount: 0,
1370
- assignees: [{ id: 'acct-1' }],
1371
- }),
1372
- ],
1373
- rules: [
1374
- rule({
1375
- id: 'open',
1376
- kind: 'CONTINUOUS_COVERAGE',
1377
- config: { opensAt: '07:00', closesAt: '11:00' },
1378
- }),
1379
- ],
1380
- }),
1381
- );
1382
-
1383
- expect(violations).toHaveLength(1);
1384
- expect(violations[0].segmentStart.toISOString()).toBe(
1385
- '2026-08-03T16:00:00.000Z',
1386
- );
1387
- expect(violations[0].segmentEnd.toISOString()).toBe(
1388
- '2026-08-03T18:00:00.000Z',
1389
- );
1390
- });
1391
-
1392
- it('covers an overnight operating window as one rule', () => {
1393
- // 18:00-06:00 local. Judging by minutes-into-day, this describes no
1394
- // instant at all and the rule silently never fired.
1395
- const { violations } = evaluateScheduleWindow(
1396
- snapshot({
1397
- windowStart: at('2026-08-04T00:00:00Z'), // 17:00 local Aug 3
1398
- windowEnd: at('2026-08-04T14:00:00Z'), // 07:00 local Aug 4
1399
- rules: [
1400
- rule({
1401
- id: 'night',
1402
- kind: 'CONTINUOUS_COVERAGE',
1403
- config: { opensAt: '18:00', closesAt: '06:00' },
1404
- }),
1405
- ],
1406
- }),
1407
- );
1408
-
1409
- expect(violations).toHaveLength(1);
1410
- // 18:00 local Aug 3 through 06:00 local Aug 4, as ONE stretch
1411
- expect(violations[0].segmentStart.toISOString()).toBe(
1412
- '2026-08-04T01:00:00.000Z',
1413
- );
1414
- expect(violations[0].segmentEnd.toISOString()).toBe(
1415
- '2026-08-04T13:00:00.000Z',
1416
- );
1417
- });
1418
-
1419
- it('attributes an overnight window to the weekday it opened on', () => {
1420
- // Monday-only 18:00-06:00 must still be checked at 02:00 Tuesday.
1421
- // 2026-08-03 is a Monday.
1422
- const { violations } = evaluateScheduleWindow(
1423
- snapshot({
1424
- windowStart: at('2026-08-04T08:00:00Z'), // 01:00 local Tuesday
1425
- windowEnd: at('2026-08-04T10:00:00Z'), // 03:00 local Tuesday
1426
- rules: [
1427
- rule({
1428
- id: 'night',
1429
- kind: 'CONTINUOUS_COVERAGE',
1430
- config: { opensAt: '18:00', closesAt: '06:00', weekdays: [1] },
1431
- }),
1432
- ],
1433
- }),
1434
- );
1435
-
1436
- expect(violations).toHaveLength(1);
1437
- });
1438
-
1439
- it('ignores a malformed weekday list rather than falling silent', () => {
1440
- // ["Mon"] becomes [NaN], matches no weekday, and used to switch the rule
1441
- // off entirely — the silent-compliance failure this engine must not have
1442
- const { violations } = evaluateScheduleWindow(
1443
- snapshot({
1444
- windowStart: at('2026-08-03T07:00:00Z'),
1445
- windowEnd: at('2026-08-04T07:00:00Z'),
1446
- rules: [
1447
- rule({
1448
- id: 'open',
1449
- kind: 'CONTINUOUS_COVERAGE',
1450
- config: { opensAt: '07:00', closesAt: '11:00', weekdays: ['Mon'] },
1451
- }),
1452
- ],
1453
- }),
1454
- );
1455
-
1456
- expect(violations).toHaveLength(1);
1457
- });
1458
-
1459
- it('keeps two operating windows on the same calendar independent', () => {
1460
- // A split shift — open, closed for the afternoon, open again. Keyed on
1461
- // the bare kind, the second window replaced the first and half the day
1462
- // went unchecked.
1463
- const { violations } = evaluateScheduleWindow(
1464
- snapshot({
1465
- windowStart: at('2026-08-03T07:00:00Z'), // local midnight
1466
- windowEnd: at('2026-08-04T07:00:00Z'),
1467
- rules: [
1468
- rule({
1469
- id: 'morning',
1470
- kind: 'CONTINUOUS_COVERAGE',
1471
- config: { opensAt: '07:00', closesAt: '11:00' },
1472
- }),
1473
- rule({
1474
- id: 'evening',
1475
- kind: 'CONTINUOUS_COVERAGE',
1476
- config: { opensAt: '16:00', closesAt: '19:00' },
1477
- }),
1478
- ],
1479
- }),
1480
- );
1481
-
1482
- expect(violations.map((violation) => violation.ruleId).sort()).toEqual([
1483
- 'evening',
1484
- 'morning',
1485
- ]);
1486
- });
1487
-
1488
- it('opens at the same wall-clock time on a spring-forward day', () => {
1489
- // 2026-03-08 is the US spring-forward day, 23 hours long. Adding the
1490
- // opening time as a DURATION to local midnight lands an hour late, so
1491
- // the window would open at 08:00 and the 07:00-08:00 gap would go
1492
- // unchecked. It has to be SET as wall clock.
1493
- const { violations } = evaluateScheduleWindow(
1494
- snapshot({
1495
- windowStart: at('2026-03-08T08:00:00Z'), // local midnight PST
1496
- windowEnd: at('2026-03-09T07:00:00Z'), // local midnight PDT
1497
- rules: [
1498
- rule({
1499
- id: 'open',
1500
- kind: 'CONTINUOUS_COVERAGE',
1501
- config: { opensAt: '07:00', closesAt: '11:00' },
1502
- }),
1503
- ],
1504
- }),
1505
- );
1506
-
1507
- expect(violations).toHaveLength(1);
1508
- // 07:00 PDT on the transition day is 14:00Z, not 15:00Z
1509
- expect(violations[0].segmentStart.toISOString()).toBe(
1510
- '2026-03-08T14:00:00.000Z',
1511
- );
1512
- expect(violations[0].segmentEnd.toISOString()).toBe(
1513
- '2026-03-08T18:00:00.000Z',
1514
- );
1515
- });
1516
-
1517
- it('opens at the same wall-clock time on a fall-back day', () => {
1518
- // 2026-11-01 is the US fall-back day, 25 hours long
1519
- const { violations } = evaluateScheduleWindow(
1520
- snapshot({
1521
- windowStart: at('2026-11-01T07:00:00Z'), // local midnight PDT
1522
- windowEnd: at('2026-11-02T08:00:00Z'), // local midnight PST
1523
- rules: [
1524
- rule({
1525
- id: 'open',
1526
- kind: 'CONTINUOUS_COVERAGE',
1527
- config: { opensAt: '07:00', closesAt: '11:00' },
1528
- }),
1529
- ],
1530
- }),
1531
- );
1532
-
1533
- expect(violations).toHaveLength(1);
1534
- // 07:00 PST is 15:00Z
1535
- expect(violations[0].segmentStart.toISOString()).toBe(
1536
- '2026-11-01T15:00:00.000Z',
1537
- );
1538
- expect(violations[0].segmentEnd.toISOString()).toBe(
1539
- '2026-11-01T19:00:00.000Z',
1540
- );
1541
- });
1542
-
1543
- it('keeps projecting to the end of a long window', () => {
1544
- // The day walk used to be bounded by a count derived from the window's
1545
- // DURATION, which undercounts whenever the window opens late in a local
1546
- // day — 24 hours from 23:30 touches three calendar days, not two. The
1547
- // last operating window was dropped, which is the uncovered stretch at
1548
- // the very edge that nobody would think to check.
1549
- const { violations } = evaluateScheduleWindow(
1550
- snapshot({
1551
- windowStart: at('2026-08-03T06:30:00Z'), // 23:30 local Aug 2
1552
- windowEnd: at('2026-08-04T06:30:00Z'), // 23:30 local Aug 3
1553
- rules: [
1554
- rule({
1555
- id: 'always',
1556
- kind: 'CONTINUOUS_COVERAGE',
1557
- config: { opensAt: '00:00', closesAt: '24:00' },
1558
- }),
1559
- ],
1560
- }),
1561
- );
1562
-
1563
- // One unbroken uncovered stretch spanning the whole window, not one that
1564
- // stops a day early
1565
- expect(violations).toHaveLength(1);
1566
- expect(violations[0].segmentStart.toISOString()).toBe(
1567
- '2026-08-03T06:30:00.000Z',
1568
- );
1569
- expect(violations[0].segmentEnd.toISOString()).toBe(
1570
- '2026-08-04T06:30:00.000Z',
1571
- );
1572
- });
1573
-
1574
- it('does not drift in a zone whose DST transition is at midnight', () => {
1575
- // Beirut moves the clock at 00:00, so midnight does not exist on the
1576
- // transition day and startOf('day') yields 01:00. Stepping with
1577
- // plus({days:1}) then carried that 01:00 forward for the rest of the
1578
- // walk, putting every later day an hour late and dropping the final one.
1579
- const { violations } = evaluateScheduleWindow(
1580
- snapshot({
1581
- windowStart: at('2026-03-28T21:30:00Z'),
1582
- windowEnd: at('2026-03-29T21:30:00Z'),
1583
- timeZone: 'Asia/Beirut',
1584
- rules: [
1585
- rule({
1586
- id: 'always',
1587
- kind: 'CONTINUOUS_COVERAGE',
1588
- config: { opensAt: '00:00', closesAt: '24:00' },
1589
- }),
1590
- ],
1591
- }),
1592
- );
1593
-
1594
- expect(violations).toHaveLength(1);
1595
- expect(violations[0].segmentEnd.toISOString()).toBe(
1596
- '2026-03-29T21:30:00.000Z',
1597
- );
1598
- });
1599
-
1600
- it('counts staff in a room that carries its own coverage rule', () => {
1601
- // An organization-wide "somebody must be here" rule asks one question
1602
- // about the whole operation. Narrowing its evidence to exclude a room
1603
- // that has its own override does not narrow the question — it reports an
1604
- // empty building while somebody is standing in that room.
1605
- const { violations } = evaluateScheduleWindow(
1606
- snapshot({
1607
- windowStart: at('2026-08-03T14:00:00Z'),
1608
- windowEnd: at('2026-08-03T18:00:00Z'),
1609
- occurrences: [
1610
- shift({
1611
- id: 'in-room-b',
1612
- resourceId: 'room-b',
1613
- startAt: '2026-08-03T14:00:00Z',
1614
- endAt: '2026-08-03T18:00:00Z',
1615
- requiredCount: 0,
1616
- assignees: [{ id: 'acct-1' }],
1617
- }),
1618
- ],
1619
- rules: [
1620
- rule({
1621
- id: 'org-open',
1622
- kind: 'CONTINUOUS_COVERAGE',
1623
- config: { opensAt: '07:00', closesAt: '11:00' },
1624
- }),
1625
- rule({
1626
- id: 'room-b-open',
1627
- kind: 'CONTINUOUS_COVERAGE',
1628
- resourceId: 'room-b',
1629
- config: { opensAt: '07:00', closesAt: '11:00' },
1630
- }),
1631
- ],
1632
- }),
1633
- );
1634
-
1635
- expect(violations).toEqual([]);
1636
- });
1637
-
1638
- it('says nothing outside opening hours', () => {
1639
- const { violations } = evaluateScheduleWindow(
1640
- snapshot({
1641
- windowStart: at('2026-08-03T18:00:00Z'), // 11:00 local, after close
1642
- windowEnd: at('2026-08-03T20:00:00Z'),
1643
- rules: [
1644
- rule({
1645
- id: 'open',
1646
- kind: 'CONTINUOUS_COVERAGE',
1647
- config: { opensAt: '07:00', closesAt: '11:00' },
1648
- }),
1649
- ],
1650
- }),
1651
- );
1652
-
1653
- expect(violations).toEqual([]);
1654
- });
1655
- });
1656
-
1657
- describe('the sweep itself', () => {
1658
- it('cuts segments only where something actually changes', () => {
1659
- const { segmentCount } = evaluateScheduleWindow(
1660
- snapshot({
1661
- occurrences: [
1662
- shift({
1663
- id: 'shift-1',
1664
- startAt: '2026-08-03T15:00:00Z',
1665
- endAt: '2026-08-03T17:00:00Z',
1666
- requiredCount: 0,
1667
- }),
1668
- ],
1669
- }),
1670
- );
1671
-
1672
- // window start, shift start, shift end, window end -> 3 segments,
1673
- // not the 48 a 15-minute grid would have produced
1674
- expect(segmentCount).toBe(3);
1675
- });
1676
-
1677
- it('produces one segment when nothing happens', () => {
1678
- expect(evaluateScheduleWindow(snapshot()).segmentCount).toBe(1);
1679
- });
1680
-
1681
- it('joins one continuous breach instead of reporting it per segment', () => {
1682
- // Two adjacent shifts, both short: the breach is continuous across the
1683
- // boundary between them for the ratio rule, which is keyed on the room
1684
- const { violations } = evaluateScheduleWindow(
1685
- snapshot({
1686
- occurrences: [
1687
- shift({
1688
- id: 's1',
1689
- startAt: '2026-08-03T14:00:00Z',
1690
- endAt: '2026-08-03T16:00:00Z',
1691
- requiredCount: 0,
1692
- }),
1693
- shift({
1694
- id: 's2',
1695
- startAt: '2026-08-03T16:00:00Z',
1696
- endAt: '2026-08-03T18:00:00Z',
1697
- requiredCount: 0,
1698
- }),
1699
- ],
1700
- demand: [
1701
- {
1702
- resourceId: 'room-a',
1703
- category: 'INFANT',
1704
- startAt: at('2026-08-03T14:00:00Z'),
1705
- endAt: at('2026-08-03T18:00:00Z'),
1706
- quantity: 4,
1707
- },
1708
- ],
1709
- rules: [
1710
- rule({
1711
- id: 'ratio',
1712
- kind: 'DERIVED_COUNT',
1713
- config: { category: 'INFANT', divisor: 4 },
1714
- }),
1715
- ],
1716
- }),
1717
- );
1718
-
1719
- // Different occurrenceId per half, so they stay distinct — but each is
1720
- // a single row rather than one per sweep cut
1721
- expect(violations).toHaveLength(2);
1722
- expect(violations[0].segmentStart.toISOString()).toBe(
1723
- '2026-08-03T14:00:00.000Z',
1724
- );
1725
- expect(violations[0].segmentEnd.toISOString()).toBe(
1726
- '2026-08-03T16:00:00.000Z',
1727
- );
1728
- });
1729
-
1730
- it('clips a breach to the evaluated window', () => {
1731
- const { violations } = evaluateScheduleWindow(
1732
- snapshot({
1733
- windowStart: at('2026-08-03T15:00:00Z'),
1734
- windowEnd: at('2026-08-03T17:00:00Z'),
1735
- occurrences: [
1736
- shift({
1737
- id: 'overnight',
1738
- startAt: '2026-08-03T10:00:00Z',
1739
- endAt: '2026-08-03T22:00:00Z',
1740
- requiredCount: 1,
1741
- }),
1742
- ],
1743
- rules: [rule({ id: 'r1', kind: 'REQUIRED_COUNT' })],
1744
- }),
1745
- );
1746
-
1747
- expect(violations).toHaveLength(1);
1748
- expect(violations[0].segmentStart.toISOString()).toBe(
1749
- '2026-08-03T15:00:00.000Z',
1750
- );
1751
- expect(violations[0].segmentEnd.toISOString()).toBe(
1752
- '2026-08-03T17:00:00.000Z',
1753
- );
1754
- });
1755
- });
1756
-
1757
- describe('publication gating', () => {
1758
- it('separates blocking breaches from warnings', () => {
1759
- const { violations } = evaluateScheduleWindow(
1760
- snapshot({
1761
- occurrences: [
1762
- shift({
1763
- id: 'shift-1',
1764
- startAt: '2026-08-03T14:00:00Z',
1765
- endAt: '2026-08-03T18:00:00Z',
1766
- requiredCount: 2,
1767
- assignees: [{ id: 'acct-1' }],
1768
- }),
1769
- ],
1770
- rules: [
1771
- rule({ id: 'hard', kind: 'REQUIRED_COUNT', severity: 'BLOCK' }),
1772
- rule({
1773
- id: 'soft',
1774
- kind: 'ELIGIBILITY_AT_TIME',
1775
- severity: 'WARN',
1776
- config: { qualification: 'CPR' },
1777
- }),
1778
- ],
1779
- }),
1780
- );
1781
-
1782
- expect(violations).toHaveLength(2);
1783
- expect(
1784
- getBlockingScheduleViolations(violations).map((v) => v.kind),
1785
- ).toEqual(['REQUIRED_COUNT']);
1786
- });
1787
- });
1788
-
1789
- describe('eligibility — does adding this person introduce a breach', () => {
1790
- /*
1791
- * The rule the server applies when deciding who to offer a released shift
1792
- * to: simulate the candidate onto the occurrence, and accept them only if
1793
- * the set of blocking breach IDENTITIES has not grown.
1794
- *
1795
- * These cases pin the two ways the old count comparison got it wrong. They
1796
- * live here rather than beside the server function because the decision is
1797
- * entirely a property of the pure engine; the server half is one query for
1798
- * candidates and one for their history.
1799
- */
1800
-
1801
- const breachIdentities = (
1802
- result: ReturnType<typeof evaluateScheduleWindow>,
1803
- ) =>
1804
- new Set(
1805
- getBlockingScheduleViolations(result.violations).map(
1806
- getScheduleBreachIdentity,
1807
- ),
1808
- );
1809
-
1810
- const simulate = (
1811
- base: ReturnType<typeof snapshot>,
1812
- occurrenceId: string,
1813
- accountId: string,
1814
- qualifications: string[] = [],
1815
- ) =>
1816
- withSimulatedScheduleAssignment(base, occurrenceId, {
1817
- id: `simulated-${accountId}`,
1818
- slotId: `${occurrenceId}-slot`,
1819
- actorType: 'ACCOUNT',
1820
- actorId: accountId,
1821
- actorAccountId: accountId,
1822
- startAt: null,
1823
- endAt: null,
1824
- role: null,
1825
- qualifications,
1826
- tags: [],
1827
- });
1828
-
1829
- /*
1830
- * Return whether a candidate would be offered the shift.
1831
- */
1832
- const isEligible = (
1833
- base: ReturnType<typeof snapshot>,
1834
- occurrenceId: string,
1835
- accountId: string,
1836
- qualifications: string[] = [],
1837
- ) => {
1838
- const baseline = breachIdentities(evaluateScheduleWindow(base));
1839
- const candidate = getBlockingScheduleViolations(
1840
- evaluateScheduleWindow(
1841
- simulate(base, occurrenceId, accountId, qualifications),
1842
- ).violations,
1843
- );
1844
-
1845
- return !candidate.some(
1846
- (violation) => !baseline.has(getScheduleBreachIdentity(violation)),
1847
- );
1848
- };
1849
-
1850
- it('accepts somebody who only partly closes a shortfall', () => {
1851
- // Three needed, one assigned. A second body leaves the shift still short
1852
- // — the same breach, less of it — and must not be refused for it. By
1853
- // violation COUNT this looked unchanged only by luck; by any key that
1854
- // includes the shortfall it looked like a brand-new problem.
1855
- const base = snapshot({
1856
- occurrences: [
1857
- shift({
1858
- id: 'short',
1859
- startAt: '2026-08-03T14:00:00Z',
1860
- endAt: '2026-08-03T18:00:00Z',
1861
- requiredCount: 3,
1862
- assignees: [{ id: 'acct-1' }],
1863
- }),
1864
- ],
1865
- rules: [rule({ id: 'staffing', kind: 'REQUIRED_COUNT' })],
1866
- });
1867
-
1868
- expect(isEligible(base, 'short', 'acct-2')).toBe(true);
1869
- });
1870
-
1871
- it('refuses somebody who lacks a required qualification', () => {
1872
- const base = snapshot({
1873
- occurrences: [
1874
- shift({
1875
- id: 'certified',
1876
- startAt: '2026-08-03T14:00:00Z',
1877
- endAt: '2026-08-03T18:00:00Z',
1878
- requiredCount: 0,
1879
- assignees: [{ id: 'acct-1', qualifications: ['CPR'] }],
1880
- }),
1881
- ],
1882
- rules: [
1883
- rule({
1884
- id: 'cert',
1885
- kind: 'ELIGIBILITY_AT_TIME',
1886
- config: { qualification: 'CPR' },
1887
- }),
1888
- ],
1889
- });
1890
-
1891
- expect(isEligible(base, 'certified', 'acct-2', ['CPR'])).toBe(true);
1892
- expect(isEligible(base, 'certified', 'acct-3', [])).toBe(false);
1893
- });
1894
-
1895
- it('refuses somebody who closes one breach by opening another', () => {
1896
- // THE case that separates counting from comparing. The shift is one
1897
- // short AND requires a certification the candidate does not hold, so
1898
- // filling it trades a REQUIRED_COUNT breach for an ELIGIBILITY one. The
1899
- // total is unchanged, so a count comparison waved them through; the
1900
- // schedule was no less broken, just broken somewhere else.
1901
- const base = snapshot({
1902
- occurrences: [
1903
- shift({
1904
- id: 'certified-short',
1905
- startAt: '2026-08-03T14:00:00Z',
1906
- endAt: '2026-08-03T18:00:00Z',
1907
- requiredCount: 1,
1908
- }),
1909
- ],
1910
- rules: [
1911
- rule({ id: 'staffing', kind: 'REQUIRED_COUNT' }),
1912
- rule({
1913
- id: 'cert',
1914
- kind: 'ELIGIBILITY_AT_TIME',
1915
- config: { qualification: 'CPR' },
1916
- }),
1917
- ],
1918
- });
1919
-
1920
- const baseline = getBlockingScheduleViolations(
1921
- evaluateScheduleWindow(base).violations,
1922
- );
1923
- const withCandidate = getBlockingScheduleViolations(
1924
- evaluateScheduleWindow(simulate(base, 'certified-short', 'acct-2', []))
1925
- .violations,
1926
- );
1927
-
1928
- // Same number of breaches before and after — which is exactly why the
1929
- // old comparison could not tell the difference
1930
- expect(withCandidate).toHaveLength(baseline.length);
1931
- expect(isEligible(base, 'certified-short', 'acct-2', [])).toBe(false);
1932
-
1933
- // Somebody who holds the certification closes the shortfall and opens
1934
- // nothing, so they are eligible
1935
- expect(isEligible(base, 'certified-short', 'acct-3', ['CPR'])).toBe(true);
1936
- });
1937
-
1938
- it('refuses somebody the shift would push over their own rolling limit', () => {
1939
- const base = snapshot({
1940
- windowStart: at('2026-08-03T00:00:00Z'),
1941
- windowEnd: at('2026-08-04T00:00:00Z'),
1942
- occurrences: [
1943
- shift({
1944
- id: 'taken',
1945
- startAt: '2026-08-03T02:00:00Z',
1946
- endAt: '2026-08-03T06:00:00Z',
1947
- requiredCount: 0,
1948
- assignees: [{ id: 'acct-2' }],
1949
- }),
1950
- shift({
1951
- id: 'open',
1952
- startAt: '2026-08-03T14:00:00Z',
1953
- endAt: '2026-08-03T18:00:00Z',
1954
- requiredCount: 0,
1955
- }),
1956
- ],
1957
- rules: [
1958
- rule({
1959
- id: 'max-shifts',
1960
- kind: 'ACTOR_WINDOW_AGGREGATE',
1961
- config: { metric: 'SHIFTS', windowHours: 24, max: 1 },
1962
- }),
1963
- ],
1964
- });
1965
-
1966
- // acct-2 already works once in the rolling day; acct-9 does not
1967
- expect(isEligible(base, 'open', 'acct-2')).toBe(false);
1968
- expect(isEligible(base, 'open', 'acct-9')).toBe(true);
1969
- });
1970
- });