@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.
- package/package.json +58 -23
- package/src/constants/agentMemory.ts +14 -45
- package/src/constants/agentNote.ts +212 -0
- package/src/constants/aiChat.ts +5 -0
- package/src/constants/billing.ts +126 -0
- package/src/constants/campaign.ts +156 -47
- package/src/constants/contact.ts +72 -0
- package/src/constants/csvExport.ts +133 -0
- package/src/constants/dataTable.ts +12 -38
- package/src/constants/dataTableFieldTypes.generated.ts +3 -7
- package/src/constants/docAccess.ts +3 -2
- package/src/constants/dt.ts +234 -0
- package/src/constants/email.ts +114 -12
- package/src/constants/fieldDoc.ts +74 -4
- package/src/constants/graphqlReactivity.ts +108 -25
- package/src/constants/log.ts +9 -0
- package/src/constants/logDisplay/README.md +88 -0
- package/src/constants/logDisplay/defaults.ts +39 -0
- package/src/constants/logDisplay/index.ts +27 -0
- package/src/constants/logDisplay/operations/arable.ts +16 -0
- package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
- package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
- package/src/constants/logDisplay/shared/accounting.ts +13 -0
- package/src/constants/logDisplay/shared/interactions.ts +13 -0
- package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
- package/src/constants/logTaxonomy.generated.ts +1834 -730
- package/src/constants/organization.ts +13 -14
- package/src/constants/qrCode.ts +30 -0
- package/src/constants/sheet.ts +65 -101
- package/src/constants/sms.ts +18 -0
- package/src/constants/storage.ts +33 -9
- package/src/constants/usage.ts +3 -0
- package/src/constants/workflowSteps.ts +60 -0
- package/src/schemas/editLogEntry.ts +106 -283
- package/src/schemas/inboundContact.ts +5 -5
- package/src/types/agentMemory.d.ts +38 -14
- package/src/types/agentNote.d.ts +443 -0
- package/src/types/billing.d.ts +537 -0
- package/src/types/campaign.d.ts +1043 -193
- package/src/types/contact.d.ts +15 -0
- package/src/types/csvExport.d.ts +213 -0
- package/src/types/dataAnalysis.d.ts +44 -0
- package/src/types/dataTable.d.ts +102 -309
- package/src/types/definitionElement.d.ts +35 -0
- package/src/types/dt.d.ts +257 -0
- package/src/types/email.d.ts +144 -55
- package/src/types/emailReplyReport.d.ts +76 -0
- package/src/types/fieldDoc.d.ts +579 -150
- package/src/types/fieldDocContract.d.ts +90 -0
- package/src/types/inboundContact.d.ts +8 -0
- package/src/types/log.d.ts +94 -3
- package/src/types/logDisplay.types.ts +85 -0
- package/src/types/organization.d.ts +8 -3
- package/src/types/qrCode.d.ts +96 -0
- package/src/types/richText.d.ts +81 -0
- package/src/types/sheet.d.ts +180 -463
- package/src/types/sms.d.ts +38 -0
- package/src/types/storage.d.ts +266 -27
- package/src/types/workflow.d.ts +196 -66
- package/src/utils/agentMemory.ts +15 -0
- package/src/utils/agentNote.ts +850 -0
- package/src/utils/aiChat.ts +31 -14
- package/src/utils/aiChatWork.ts +64 -0
- package/src/utils/billing.ts +37 -0
- package/src/utils/campaign.ts +642 -209
- package/src/utils/campaignAI.ts +72 -0
- package/src/utils/campaignAccess.ts +239 -0
- package/src/utils/campaignEmail.ts +601 -0
- package/src/utils/campaignEmailCompiler.ts +372 -0
- package/src/utils/campaignEmailImages.ts +60 -0
- package/src/utils/campaignEmailStyles.ts +544 -0
- package/src/utils/campaignLifecycle.ts +104 -0
- package/src/utils/campaignPreview.ts +285 -0
- package/src/utils/contact.ts +50 -0
- package/src/utils/csvExport.ts +19 -0
- package/src/utils/dataTable.ts +18 -556
- package/src/utils/dataTableFieldTypeRegistry.ts +1 -0
- package/src/utils/dataTableRelativeDate.ts +447 -0
- package/src/utils/definitionElement.ts +84 -0
- package/src/utils/email.ts +208 -1
- package/src/utils/emailReplyReport.test.ts +187 -0
- package/src/utils/emailReplyReport.ts +143 -0
- package/src/utils/fieldDoc.ts +81 -37
- package/src/utils/fieldDocAnswers.ts +128 -0
- package/src/utils/fieldDocDefaults.ts +36 -0
- package/src/utils/fieldDocProgram.ts +36 -0
- package/src/utils/fieldDocSummary.ts +30 -0
- package/src/utils/log.ts +232 -141
- package/src/utils/logDisplay.helpers.ts +177 -0
- package/src/utils/logDisplay.ts +87 -0
- package/src/utils/logStoreRead.ts +9 -13
- package/src/utils/logTaxonomy.helpers.ts +17 -0
- package/src/utils/logTaxonomyDisplay.ts +80 -124
- package/src/utils/noteDoc.ts +66 -284
- package/src/utils/organization.ts +117 -283
- package/src/utils/qrCode.helpers.ts +189 -0
- package/src/utils/qrCode.test.ts +519 -0
- package/src/utils/qrCode.ts +273 -0
- package/src/utils/richTextHTML.ts +385 -0
- package/src/utils/sheet.ts +123 -4834
- package/src/utils/sheetAxisMove.ts +77 -291
- package/src/utils/sheetBootstrap.ts +771 -1138
- package/src/utils/sheetCellLiteral.ts +101 -0
- package/src/utils/sheetCommand.ts +23 -88
- package/src/utils/sheetDesign.ts +705 -0
- package/src/utils/sheetExport.ts +17 -69
- package/src/utils/sheetFeatureReference.ts +183 -0
- package/src/utils/sheetFormulaArgs.ts +168 -0
- package/src/utils/sheetFormulaCompile.ts +475 -0
- package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
- package/src/utils/sheetFormulaCriteria.ts +656 -0
- package/src/utils/sheetFormulaDate.ts +444 -0
- package/src/utils/sheetFormulaEvaluation.ts +388 -403
- package/src/utils/sheetFormulaEvaluator.ts +589 -444
- package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
- package/src/utils/sheetFormulaLogical.ts +116 -0
- package/src/utils/sheetFormulaLookup.ts +488 -0
- package/src/utils/sheetFormulaMath.ts +48 -0
- package/src/utils/sheetFormulaParser.ts +729 -0
- package/src/utils/sheetFormulaRange.ts +330 -0
- package/src/utils/sheetFormulaReference.ts +703 -0
- package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
- package/src/utils/sheetFormulaReferenceDates.ts +237 -0
- package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
- package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
- package/src/utils/sheetFormulaReferenceMath.ts +95 -0
- package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
- package/src/utils/sheetFormulaReferenceText.ts +462 -0
- package/src/utils/sheetFormulaSyntax.ts +1027 -0
- package/src/utils/sheetFormulaText.ts +430 -0
- package/src/utils/sheetJournal.ts +140 -18
- package/src/utils/sheetNumberFormat.ts +68 -267
- package/src/utils/sheetPreview.ts +68 -0
- package/src/utils/sheetSequence.ts +13 -43
- package/src/utils/sheetSnapshot.ts +176 -429
- package/src/utils/sheetStructureEdit.ts +537 -907
- package/src/utils/sheetStructureReferences.ts +389 -0
- package/src/utils/storage.ts +49 -3
- package/src/utils/time.ts +12 -0
- package/src/utils/workflow.ts +199 -73
- package/src/utils/workflowLogFingerprint.ts +302 -0
- package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
- package/src/utils/workflowProgress.ts +280 -0
- package/src/utils/workflowTriggers.ts +61 -0
- package/tests/agentNote.test.ts +395 -0
- package/tests/campaignAI.test.ts +119 -0
- package/tests/campaignAccess.test.ts +239 -0
- package/tests/campaignEmail.test.ts +441 -0
- package/tests/campaignLifecycle.test.ts +134 -0
- package/tests/campaignPublication.test.ts +309 -0
- package/tests/dataTableFieldTypeRegistry.test.ts +2 -1
- package/tests/dataTableRelativeDate.test.ts +412 -0
- package/tests/email.test.ts +39 -0
- package/tests/fieldDocProgram.test.ts +114 -0
- package/tests/logDisplay.fixtures.ts +67 -0
- package/tests/logDisplay.test.ts +227 -0
- package/tests/noteDoc.test.ts +37 -192
- package/tests/richTextHTML.test.ts +185 -0
- package/tests/sheetAxisMove.test.ts +49 -40
- package/tests/sheetBootstrap.test.ts +1967 -0
- package/tests/sheetFeatureReference.test.ts +22 -0
- package/tests/sheetFormulaCriteria.test.ts +269 -0
- package/tests/sheetFormulaEvaluator.test.ts +93 -200
- package/tests/sheetFormulaFunctions.test.ts +538 -0
- package/tests/sheetFormulaLanguage.test.ts +361 -0
- package/tests/sheetFormulaParity.fixtures.ts +872 -0
- package/tests/sheetFormulaParity.test.ts +188 -0
- package/tests/sheetFormulaRange.test.ts +167 -0
- package/tests/sheetFormulaReference.test.ts +78 -0
- package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
- package/tests/sheetFormulaTextDate.test.ts +512 -0
- package/tests/sheetSequence.test.ts +4 -23
- package/tests/sheetSnapshot.test.ts +134 -0
- package/tests/sheetStructureEdit.test.ts +492 -37
- package/tests/sheetStructureReferences.test.ts +589 -0
- package/tests/workflowLifecycleStatus.test.ts +60 -0
- package/tests/workflowLogFingerprint.test.ts +203 -0
- package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
- package/tests/workflowProgress.test.ts +180 -0
- package/tests/workflowTriggers.test.ts +29 -0
- package/src/constants/agentDoc.ts +0 -12
- package/src/constants/logActivityGroupColors.generated.ts +0 -19
- package/src/constants/schedule.ts +0 -220
- package/src/constants/scheduleRuleTemplateSeed.ts +0 -138
- package/src/constants/scheduleRuleTemplates.generated.ts +0 -145
- package/src/constants/sheetRegionSources.generated.ts +0 -578
- package/src/schemas/fieldDocsQuery.ts +0 -12
- package/src/schemas/organization.ts +0 -68
- package/src/types/agentDoc.d.ts +0 -64
- package/src/types/noteDoc.d.ts +0 -86
- package/src/types/schedule.d.ts +0 -391
- package/src/utils/agentDoc.ts +0 -109
- package/src/utils/campaignFormEditor.ts +0 -871
- package/src/utils/dataTableRealtimeAuthority.ts +0 -209
- package/src/utils/dataTableRealtimeSelection.ts +0 -134
- package/src/utils/dataTableRowDocument.ts +0 -508
- package/src/utils/dataTableSource.ts +0 -230
- package/src/utils/schedule.ts +0 -799
- package/src/utils/scheduleEvaluation.ts +0 -1994
- package/src/utils/scheduleICS.ts +0 -246
- package/src/utils/scheduleRuleTemplates.ts +0 -188
- package/src/utils/sheetRegion.ts +0 -374
- package/src/utils/sheetRegionFilter.ts +0 -1259
- package/src/utils/sheetRegionSourceRegistry.ts +0 -594
- package/tests/schedule.test.ts +0 -693
- package/tests/scheduleEvaluation.test.ts +0 -1970
- package/tests/scheduleICS.test.ts +0 -208
- package/tests/scheduleRuleTemplates.test.ts +0 -176
- package/tests/scheduleSweepInvariants.test.ts +0 -428
- package/tests/sheetRegionFilter.test.ts +0 -1135
|
@@ -1,1994 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
DEFAULT_TIMEZONE,
|
|
3
|
-
isValidTimeZone,
|
|
4
|
-
} from '@jsb188/app/utils/timeZone.ts';
|
|
5
|
-
import { DateTime } from 'luxon';
|
|
6
|
-
import type {
|
|
7
|
-
ScheduleRuleKindEnum,
|
|
8
|
-
ScheduleRuleSeverityEnum,
|
|
9
|
-
} from '../types/schedule.d.ts';
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* The scheduling constraint engine.
|
|
13
|
-
*
|
|
14
|
-
* Everything here is pure: it takes one in-memory snapshot of a calendar
|
|
15
|
-
* window and returns the rule breaches inside it. No database, no clock, no
|
|
16
|
-
* I/O — so the whole engine is testable from a literal, and the server layer
|
|
17
|
-
* is reduced to loading the snapshot and writing the answer down.
|
|
18
|
-
*
|
|
19
|
-
* The method is a sweep line, not a fixed grid. Every interval boundary in
|
|
20
|
-
* the window — occurrence starts and ends, partial-shift assignments, demand
|
|
21
|
-
* changes, rule effective dates — becomes a cut point; the segments between
|
|
22
|
-
* consecutive cuts are the intervals over which nothing changes, so each one
|
|
23
|
-
* can be judged with a single comparison. That is what makes minute-exact
|
|
24
|
-
* ratio checking and day-long farm scheduling the same code: a daycare day
|
|
25
|
-
* produces a few dozen segments, a week of all-day entries produces a handful,
|
|
26
|
-
* and neither has to agree on a granularity in advance.
|
|
27
|
-
*
|
|
28
|
-
* Fifteen-minute buckets would have been simpler and wrong twice over: wrong
|
|
29
|
-
* at the edges, where a breach that starts at 9:05 gets reported at 9:00 or
|
|
30
|
-
* missed, and wasteful everywhere else, where 96 buckets a day get evaluated
|
|
31
|
-
* to answer a question that changes four times.
|
|
32
|
-
*/
|
|
33
|
-
|
|
34
|
-
export interface ScheduleEvalSlot {
|
|
35
|
-
id: string;
|
|
36
|
-
key: string;
|
|
37
|
-
requiredCount: number;
|
|
38
|
-
predicate?: {
|
|
39
|
-
roles?: string[] | null;
|
|
40
|
-
qualifications?: string[] | null;
|
|
41
|
-
tags?: string[] | null;
|
|
42
|
-
} | null;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export interface ScheduleEvalAssignment {
|
|
46
|
-
id: string;
|
|
47
|
-
slotId: string | null;
|
|
48
|
-
actorType: 'ACCOUNT' | 'ORGANIZATION' | 'CONTACT';
|
|
49
|
-
// The concrete actor id, whichever column it came from
|
|
50
|
-
actorId: string;
|
|
51
|
-
actorAccountId: string | null;
|
|
52
|
-
// Null unless this assignment covers only part of its occurrence
|
|
53
|
-
startAt: Date | null;
|
|
54
|
-
endAt: Date | null;
|
|
55
|
-
// Resolved by the loader; the engine never looks anything up
|
|
56
|
-
role?: string | null;
|
|
57
|
-
qualifications?: string[] | null;
|
|
58
|
-
// Expiry instant per qualification, when it has one. A credential that
|
|
59
|
-
// lapses mid-shift makes the same shift legal before it and illegal after,
|
|
60
|
-
// which is why eligibility is judged per segment rather than per shift.
|
|
61
|
-
qualificationExpiry?: Record<string, Date | null> | null;
|
|
62
|
-
tags?: string[] | null;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export interface ScheduleEvalOccurrence {
|
|
66
|
-
id: string;
|
|
67
|
-
kind: 'SHIFT' | 'EVENT' | 'BLOCK';
|
|
68
|
-
resourceId: string | null;
|
|
69
|
-
startAt: Date;
|
|
70
|
-
endAt: Date;
|
|
71
|
-
slots: ScheduleEvalSlot[];
|
|
72
|
-
assignments: ScheduleEvalAssignment[];
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export interface ScheduleEvalDemand {
|
|
76
|
-
resourceId: string | null;
|
|
77
|
-
category: string;
|
|
78
|
-
startAt: Date;
|
|
79
|
-
endAt: Date;
|
|
80
|
-
quantity: number;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export interface ScheduleEvalResource {
|
|
84
|
-
id: string;
|
|
85
|
-
key: string;
|
|
86
|
-
capacity: number | null;
|
|
87
|
-
config?: Record<string, unknown> | null;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
export interface ScheduleEvalRule {
|
|
91
|
-
id: string;
|
|
92
|
-
kind: ScheduleRuleKindEnum;
|
|
93
|
-
severity: ScheduleRuleSeverityEnum;
|
|
94
|
-
// Which template supplies this rule's wording; carried onto every
|
|
95
|
-
// violation so the renderer never has to look the rule up again. Optional
|
|
96
|
-
// because a hand-written rule has none and still evaluates identically.
|
|
97
|
-
templateKey?: string | null;
|
|
98
|
-
config: Record<string, any>;
|
|
99
|
-
// Which scope level this rule came from; the most specific one wins
|
|
100
|
-
operationTypeId: string | null;
|
|
101
|
-
organizationId: string | null;
|
|
102
|
-
calendarId: string | null;
|
|
103
|
-
resourceId: string | null;
|
|
104
|
-
effectiveFrom: Date | null;
|
|
105
|
-
effectiveTo: Date | null;
|
|
106
|
-
ordinal: number;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* One assignment outside the evaluated window, needed only by the rolling
|
|
111
|
-
* per-actor limits (a Monday shift can push a Sunday-to-Saturday total over).
|
|
112
|
-
*/
|
|
113
|
-
|
|
114
|
-
export interface ScheduleEvalActorHistoryEntry {
|
|
115
|
-
occurrenceId: string;
|
|
116
|
-
actorAccountId: string;
|
|
117
|
-
// The resource the shift was worked on, so a resource-scoped rolling limit
|
|
118
|
-
// can filter history the same way it filters the occurrences in the window.
|
|
119
|
-
// Without it, the same schedule gets a different verdict depending on where
|
|
120
|
-
// the evaluated window happens to be drawn: a shift counted as history is
|
|
121
|
-
// unfiltered, and the identical shift counted as an in-window occurrence is
|
|
122
|
-
// filtered out.
|
|
123
|
-
resourceId?: string | null;
|
|
124
|
-
startAt: Date;
|
|
125
|
-
endAt: Date;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
export interface ScheduleEvaluationSnapshot {
|
|
129
|
-
windowStart: Date;
|
|
130
|
-
windowEnd: Date;
|
|
131
|
-
// Used only by CONTINUOUS_COVERAGE, which reasons in local operating hours
|
|
132
|
-
timeZone: string;
|
|
133
|
-
occurrences: ScheduleEvalOccurrence[];
|
|
134
|
-
demand: ScheduleEvalDemand[];
|
|
135
|
-
resources: ScheduleEvalResource[];
|
|
136
|
-
rules: ScheduleEvalRule[];
|
|
137
|
-
actorHistory?: ScheduleEvalActorHistoryEntry[];
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
export interface ScheduleEvalViolation {
|
|
141
|
-
ruleId: string | null;
|
|
142
|
-
templateKey: string | null;
|
|
143
|
-
kind: ScheduleRuleKindEnum;
|
|
144
|
-
severity: ScheduleRuleSeverityEnum;
|
|
145
|
-
resourceId: string | null;
|
|
146
|
-
occurrenceId: string | null;
|
|
147
|
-
actorAccountId: string | null;
|
|
148
|
-
segmentStart: Date;
|
|
149
|
-
segmentEnd: Date;
|
|
150
|
-
detail: Record<string, unknown>;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
export interface ScheduleEvaluationResult {
|
|
154
|
-
segmentCount: number;
|
|
155
|
-
violations: ScheduleEvalViolation[];
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* One segment of the sweep: an interval over which the whole snapshot is
|
|
160
|
-
* constant, together with what is active during it.
|
|
161
|
-
*/
|
|
162
|
-
|
|
163
|
-
interface ScheduleEvalSegment {
|
|
164
|
-
start: Date;
|
|
165
|
-
end: Date;
|
|
166
|
-
occurrences: ScheduleEvalOccurrence[];
|
|
167
|
-
// Assignments active in this segment, keyed by occurrence id
|
|
168
|
-
assignmentsByOccurrenceId: Map<string, ScheduleEvalAssignment[]>;
|
|
169
|
-
demand: ScheduleEvalDemand[];
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/*
|
|
173
|
-
* Return the later of two instants.
|
|
174
|
-
*/
|
|
175
|
-
|
|
176
|
-
function maxDate(a: Date, b: Date): Date {
|
|
177
|
-
return a.getTime() >= b.getTime() ? a : b;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/*
|
|
181
|
-
* Return the earlier of two instants.
|
|
182
|
-
*/
|
|
183
|
-
|
|
184
|
-
function minDate(a: Date, b: Date): Date {
|
|
185
|
-
return a.getTime() <= b.getTime() ? a : b;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/*
|
|
189
|
-
* Return the interval one assignment actually covers: its own window when it
|
|
190
|
-
* is a partial shift, otherwise its occurrence's.
|
|
191
|
-
*/
|
|
192
|
-
|
|
193
|
-
function getAssignmentInterval(
|
|
194
|
-
assignment: ScheduleEvalAssignment,
|
|
195
|
-
occurrence: ScheduleEvalOccurrence,
|
|
196
|
-
): { startAt: Date; endAt: Date } {
|
|
197
|
-
return {
|
|
198
|
-
startAt: assignment.startAt || occurrence.startAt,
|
|
199
|
-
endAt: assignment.endAt || occurrence.endAt,
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
/*
|
|
204
|
-
* Resolve the zone a snapshot reasons in, falling back rather than throwing.
|
|
205
|
-
*/
|
|
206
|
-
|
|
207
|
-
function getSnapshotTimeZone(snapshot: ScheduleEvaluationSnapshot): string {
|
|
208
|
-
return snapshot.timeZone && isValidTimeZone(snapshot.timeZone)
|
|
209
|
-
? snapshot.timeZone
|
|
210
|
-
: DEFAULT_TIMEZONE;
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
/*
|
|
214
|
-
* Parse an "HH:MM" operating-hours bound into minutes past local midnight.
|
|
215
|
-
*/
|
|
216
|
-
|
|
217
|
-
function parseClockMinutes(value: unknown): number | null {
|
|
218
|
-
const match = /^(\d{1,2}):(\d{2})$/.exec(String(value ?? ''));
|
|
219
|
-
|
|
220
|
-
if (!match) {
|
|
221
|
-
return null;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
const hours = Number(match[1]);
|
|
225
|
-
const minutes = Number(match[2]);
|
|
226
|
-
|
|
227
|
-
if (hours > 24 || minutes > 59) {
|
|
228
|
-
return null;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
return hours * 60 + minutes;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/*
|
|
235
|
-
* Return the instant a number of minutes past one local midnight falls at.
|
|
236
|
-
*
|
|
237
|
-
* Set as wall-clock rather than added as a duration. Luxon's plus({minutes})
|
|
238
|
-
* adds ABSOLUTE time, so on a spring-forward day it lands an hour late: local
|
|
239
|
-
* midnight plus 420 real minutes is 08:00, not the 07:00 the rule says. An
|
|
240
|
-
* operating window opens at seven o'clock on every day of the year, including
|
|
241
|
-
* the two that are not 24 hours long.
|
|
242
|
-
*
|
|
243
|
-
* Values past a day are carried onto the next calendar day, which is what makes
|
|
244
|
-
* "24:00" and the post-midnight half of an overnight window expressible.
|
|
245
|
-
*/
|
|
246
|
-
|
|
247
|
-
function getLocalInstantAtMinutes(
|
|
248
|
-
localDay: DateTime,
|
|
249
|
-
minutesPastMidnight: number,
|
|
250
|
-
): DateTime {
|
|
251
|
-
const dayOffset = Math.floor(minutesPastMidnight / 1440);
|
|
252
|
-
const withinDay = minutesPastMidnight - dayOffset * 1440;
|
|
253
|
-
const base = dayOffset ? localDay.plus({ days: dayOffset }) : localDay;
|
|
254
|
-
|
|
255
|
-
return base.set({
|
|
256
|
-
hour: Math.floor(withinDay / 60),
|
|
257
|
-
minute: withinDay % 60,
|
|
258
|
-
second: 0,
|
|
259
|
-
millisecond: 0,
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
/*
|
|
264
|
-
* Return the weekdays one operating-hours rule is restricted to, or null for
|
|
265
|
-
* "every day".
|
|
266
|
-
*
|
|
267
|
-
* A malformed list resolves to null — no restriction — rather than to a list
|
|
268
|
-
* that matches nothing. {"weekdays":["Mon"]} maps to [NaN], and treating that
|
|
269
|
-
* as a real restriction switched the rule off silently, which is the one
|
|
270
|
-
* outcome a constraint engine must never produce: a schedule reported compliant
|
|
271
|
-
* because the rule judging it quietly did nothing. Firing too often is a false
|
|
272
|
-
* alarm somebody can see and correct; never firing is invisible.
|
|
273
|
-
*/
|
|
274
|
-
|
|
275
|
-
function getOperatingWeekdays(value: unknown): number[] | null {
|
|
276
|
-
if (!Array.isArray(value) || !value.length) {
|
|
277
|
-
return null;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
const weekdays = value
|
|
281
|
-
.map(Number)
|
|
282
|
-
.filter(
|
|
283
|
-
(weekday) => Number.isInteger(weekday) && weekday >= 0 && weekday <= 6,
|
|
284
|
-
);
|
|
285
|
-
|
|
286
|
-
return weekdays.length ? weekdays : null;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
/**
|
|
290
|
-
* Project one CONTINUOUS_COVERAGE rule's operating hours onto absolute
|
|
291
|
-
* intervals covering an evaluated window.
|
|
292
|
-
*
|
|
293
|
-
* The rule is written in local wall-clock ("we are open 07:00 to 18:00") while
|
|
294
|
-
* the sweep works in absolute instants, so the two have to be reconciled
|
|
295
|
-
* somewhere. Doing it here — once, as real intervals — rather than by testing
|
|
296
|
-
* each segment's start instant is what makes the rule correct at the edges: a
|
|
297
|
-
* segment that straddles opening or closing time gets cut at the boundary
|
|
298
|
-
* instead of being judged wholly by whichever side its start landed on.
|
|
299
|
-
*
|
|
300
|
-
* "closesAt" at or before "opensAt" means the window wraps past midnight, which
|
|
301
|
-
* is how a night shift is expressed. Such a window is attributed to the weekday
|
|
302
|
-
* it OPENED on, so a Monday-only 18:00-06:00 rule still applies at 02:00 on
|
|
303
|
-
* Tuesday.
|
|
304
|
-
*
|
|
305
|
-
* Days are stepped with calendar arithmetic, never by adding 86_400_000: a
|
|
306
|
-
* daylight-saving day is 23 or 25 hours long, and an operating window has to
|
|
307
|
-
* open at 07:00 local on those days like any other.
|
|
308
|
-
*/
|
|
309
|
-
|
|
310
|
-
function getOperatingWindowIntervals(
|
|
311
|
-
rule: ScheduleEvalRule,
|
|
312
|
-
timeZone: string,
|
|
313
|
-
windowStart: Date,
|
|
314
|
-
windowEnd: Date,
|
|
315
|
-
): Array<{ start: Date; end: Date }> {
|
|
316
|
-
const opensAt = parseClockMinutes(rule.config?.opensAt);
|
|
317
|
-
const closesAt = parseClockMinutes(rule.config?.closesAt);
|
|
318
|
-
|
|
319
|
-
if (opensAt === null || closesAt === null) {
|
|
320
|
-
return [];
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
const weekdays = getOperatingWeekdays(rule.config?.weekdays);
|
|
324
|
-
const wrapsPastMidnight = closesAt <= opensAt;
|
|
325
|
-
const intervals: Array<{ start: Date; end: Date }> = [];
|
|
326
|
-
|
|
327
|
-
// Start a day early so a window opened the previous evening and still open
|
|
328
|
-
// inside this one is represented
|
|
329
|
-
let localDay = DateTime.fromJSDate(windowStart)
|
|
330
|
-
.setZone(timeZone)
|
|
331
|
-
.startOf('day')
|
|
332
|
-
.minus({ days: 1 });
|
|
333
|
-
|
|
334
|
-
if (!localDay.isValid) {
|
|
335
|
-
return [];
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
const windowEndTime = windowEnd.getTime();
|
|
339
|
-
|
|
340
|
-
// Walk until the local day itself starts after the window ends, rather than
|
|
341
|
-
// for a computed number of days. Counting days from the window's DURATION
|
|
342
|
-
// undercounts whenever the window opens late in a local day: 24 hours
|
|
343
|
-
// starting at 23:30 touches three calendar days, not two, and the arithmetic
|
|
344
|
-
// version dropped the last one — silently losing the final operating window,
|
|
345
|
-
// which is the uncovered stretch at the very edge nobody would think to look
|
|
346
|
-
// for. The cap is a guard against a pathological zone, not the bound.
|
|
347
|
-
// The walk ends when the local day itself starts after the window does. The
|
|
348
|
-
// step count is only a backstop against a zone the cursor cannot advance
|
|
349
|
-
// past, so it is derived from the window rather than fixed: a constant
|
|
350
|
-
// ceiling would silently stop projecting partway through a long window,
|
|
351
|
-
// which is the same class of quiet wrong answer this projection exists to
|
|
352
|
-
// remove. A span of D milliseconds touches at most ceil(D / one day) + 1
|
|
353
|
-
// calendar days, plus the day this starts early on.
|
|
354
|
-
const maxLocalDays =
|
|
355
|
-
Math.ceil((windowEndTime - windowStart.getTime()) / 86_400_000) + 3;
|
|
356
|
-
|
|
357
|
-
// Each step re-anchors with startOf('day') rather than trusting plus({days:1})
|
|
358
|
-
// to land on midnight. In a zone whose DST transition happens AT midnight —
|
|
359
|
-
// Beirut, Santiago — midnight does not exist on the transition day, so
|
|
360
|
-
// startOf('day') yields 01:00, and adding a day to that carries the 01:00
|
|
361
|
-
// forward for the rest of the walk. Every later day is then an hour late, and
|
|
362
|
-
// the day whose window opens just before the window ends is dropped entirely.
|
|
363
|
-
for (
|
|
364
|
-
let step = 0;
|
|
365
|
-
step < maxLocalDays && localDay.toMillis() <= windowEndTime;
|
|
366
|
-
step++, localDay = localDay.plus({ days: 1 }).startOf('day')
|
|
367
|
-
) {
|
|
368
|
-
// A zone whose transition falls at midnight can leave startOf('day')
|
|
369
|
-
// with no valid local representation; skip that day rather than throw
|
|
370
|
-
if (!localDay.isValid) {
|
|
371
|
-
continue;
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
if (weekdays && !weekdays.includes(localDay.weekday % 7)) {
|
|
375
|
-
continue;
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
const opens = getLocalInstantAtMinutes(localDay, opensAt);
|
|
379
|
-
const closes = getLocalInstantAtMinutes(
|
|
380
|
-
localDay,
|
|
381
|
-
wrapsPastMidnight ? closesAt + 1440 : closesAt,
|
|
382
|
-
);
|
|
383
|
-
|
|
384
|
-
if (!opens.isValid || !closes.isValid) {
|
|
385
|
-
continue;
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
const start = maxDate(opens.toJSDate(), windowStart);
|
|
389
|
-
const end = minDate(closes.toJSDate(), windowEnd);
|
|
390
|
-
|
|
391
|
-
if (start.getTime() < end.getTime()) {
|
|
392
|
-
intervals.push({ start, end });
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
return intervals;
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
/*
|
|
400
|
-
* Return every operating-window edge inside the evaluated window, so the sweep
|
|
401
|
-
* cuts a segment at opening and closing time.
|
|
402
|
-
*/
|
|
403
|
-
|
|
404
|
-
function getOperatingWindowBoundaries(
|
|
405
|
-
snapshot: ScheduleEvaluationSnapshot,
|
|
406
|
-
): Date[] {
|
|
407
|
-
const timeZone = getSnapshotTimeZone(snapshot);
|
|
408
|
-
const boundaries: Date[] = [];
|
|
409
|
-
|
|
410
|
-
for (const rule of snapshot.rules) {
|
|
411
|
-
if (rule.kind !== 'CONTINUOUS_COVERAGE') {
|
|
412
|
-
continue;
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
for (const interval of getOperatingWindowIntervals(
|
|
416
|
-
rule,
|
|
417
|
-
timeZone,
|
|
418
|
-
snapshot.windowStart,
|
|
419
|
-
snapshot.windowEnd,
|
|
420
|
-
)) {
|
|
421
|
-
boundaries.push(interval.start, interval.end);
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
return boundaries;
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
/*
|
|
429
|
-
* Collect every instant at which the snapshot can change, clipped to the
|
|
430
|
-
* evaluated window. These cuts are what make each resulting segment uniform.
|
|
431
|
-
*/
|
|
432
|
-
|
|
433
|
-
function getSegmentBoundaries(snapshot: ScheduleEvaluationSnapshot): Date[] {
|
|
434
|
-
const { windowStart, windowEnd } = snapshot;
|
|
435
|
-
const boundaries = new Set<number>([
|
|
436
|
-
windowStart.getTime(),
|
|
437
|
-
windowEnd.getTime(),
|
|
438
|
-
]);
|
|
439
|
-
|
|
440
|
-
const addBoundary = (instant: Date | null | undefined) => {
|
|
441
|
-
if (!instant) {
|
|
442
|
-
return;
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
const time = instant.getTime();
|
|
446
|
-
if (time > windowStart.getTime() && time < windowEnd.getTime()) {
|
|
447
|
-
boundaries.add(time);
|
|
448
|
-
}
|
|
449
|
-
};
|
|
450
|
-
|
|
451
|
-
for (const occurrence of snapshot.occurrences) {
|
|
452
|
-
addBoundary(occurrence.startAt);
|
|
453
|
-
addBoundary(occurrence.endAt);
|
|
454
|
-
|
|
455
|
-
for (const assignment of occurrence.assignments) {
|
|
456
|
-
addBoundary(assignment.startAt);
|
|
457
|
-
addBoundary(assignment.endAt);
|
|
458
|
-
|
|
459
|
-
for (const expiresAt of Object.values(
|
|
460
|
-
assignment.qualificationExpiry || {},
|
|
461
|
-
)) {
|
|
462
|
-
addBoundary(expiresAt);
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
for (const demand of snapshot.demand) {
|
|
468
|
-
addBoundary(demand.startAt);
|
|
469
|
-
addBoundary(demand.endAt);
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
for (const rule of snapshot.rules) {
|
|
473
|
-
addBoundary(rule.effectiveFrom);
|
|
474
|
-
addBoundary(rule.effectiveTo);
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
// Opening and closing time are boundaries like any other. Without them a
|
|
478
|
-
// segment can straddle either edge, and an absence rule judging that segment
|
|
479
|
-
// by its start instant answers for the wrong side of the edge.
|
|
480
|
-
for (const boundary of getOperatingWindowBoundaries(snapshot)) {
|
|
481
|
-
addBoundary(boundary);
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
return Array.from(boundaries)
|
|
485
|
-
.sort((a, b) => a - b)
|
|
486
|
-
.map((time) => new Date(time));
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
/*
|
|
490
|
-
* One interval to be swept, paired with whatever it carries.
|
|
491
|
-
*/
|
|
492
|
-
|
|
493
|
-
interface SweepInterval<T> {
|
|
494
|
-
startTime: number;
|
|
495
|
-
endTime: number;
|
|
496
|
-
value: T;
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
/*
|
|
500
|
-
* Return one list of intervals sorted by start instant, so a sweep can admit
|
|
501
|
-
* them with a moving cursor instead of rescanning the list per segment.
|
|
502
|
-
*/
|
|
503
|
-
|
|
504
|
-
function getSortedSweepIntervals<T>(
|
|
505
|
-
items: T[],
|
|
506
|
-
getInterval: (item: T) => { startAt: Date; endAt: Date },
|
|
507
|
-
): Array<SweepInterval<T>> {
|
|
508
|
-
return items
|
|
509
|
-
.map((item) => {
|
|
510
|
-
const interval = getInterval(item);
|
|
511
|
-
|
|
512
|
-
return {
|
|
513
|
-
startTime: interval.startAt.getTime(),
|
|
514
|
-
endTime: interval.endAt.getTime(),
|
|
515
|
-
value: item,
|
|
516
|
-
};
|
|
517
|
-
})
|
|
518
|
-
.sort((left, right) => left.startTime - right.startTime);
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
/*
|
|
522
|
-
* Advance one sorted interval list into an active set for a segment.
|
|
523
|
-
*
|
|
524
|
-
* Segments are visited in ascending order and every interval boundary is itself
|
|
525
|
-
* a segment boundary, so an interval is admitted exactly once — when the sweep
|
|
526
|
-
* reaches its start — and dropped when the segment start passes its end. That
|
|
527
|
-
* replaces the per-segment filter that made building the sweep quadratic: a
|
|
528
|
-
* week holding 500 shifts cut into 1,000 segments was half a million interval
|
|
529
|
-
* tests before anything was evaluated.
|
|
530
|
-
*
|
|
531
|
-
* Returns the new cursor position.
|
|
532
|
-
*/
|
|
533
|
-
|
|
534
|
-
function admitSweepIntervals<T>(
|
|
535
|
-
intervals: Array<SweepInterval<T>>,
|
|
536
|
-
cursor: number,
|
|
537
|
-
segmentStartTime: number,
|
|
538
|
-
active: Set<SweepInterval<T>>,
|
|
539
|
-
): number {
|
|
540
|
-
let next = cursor;
|
|
541
|
-
|
|
542
|
-
while (
|
|
543
|
-
next < intervals.length &&
|
|
544
|
-
intervals[next].startTime <= segmentStartTime
|
|
545
|
-
) {
|
|
546
|
-
const interval = intervals[next];
|
|
547
|
-
|
|
548
|
-
// A zero-length interval covers no segment at all
|
|
549
|
-
if (interval.endTime > segmentStartTime) {
|
|
550
|
-
active.add(interval);
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
next++;
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
for (const interval of active) {
|
|
557
|
-
if (interval.endTime <= segmentStartTime) {
|
|
558
|
-
active.delete(interval);
|
|
559
|
-
}
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
return next;
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
/*
|
|
566
|
-
* Build the segments of the sweep, each carrying what is active during it.
|
|
567
|
-
*/
|
|
568
|
-
|
|
569
|
-
function buildSegments(
|
|
570
|
-
snapshot: ScheduleEvaluationSnapshot,
|
|
571
|
-
): ScheduleEvalSegment[] {
|
|
572
|
-
const boundaries = getSegmentBoundaries(snapshot);
|
|
573
|
-
const segments: ScheduleEvalSegment[] = [];
|
|
574
|
-
|
|
575
|
-
const occurrenceIntervals = getSortedSweepIntervals(
|
|
576
|
-
snapshot.occurrences,
|
|
577
|
-
(occurrence) => occurrence,
|
|
578
|
-
);
|
|
579
|
-
const demandIntervals = getSortedSweepIntervals(
|
|
580
|
-
snapshot.demand,
|
|
581
|
-
(demand) => demand,
|
|
582
|
-
);
|
|
583
|
-
|
|
584
|
-
// Per-occurrence assignment sweeps, so a partial shift is admitted and
|
|
585
|
-
// dropped on its own boundaries rather than its occurrence's
|
|
586
|
-
const assignmentIntervalsByOccurrenceId = new Map<
|
|
587
|
-
string,
|
|
588
|
-
Array<SweepInterval<ScheduleEvalAssignment>>
|
|
589
|
-
>();
|
|
590
|
-
const assignmentCursorByOccurrenceId = new Map<string, number>();
|
|
591
|
-
const activeAssignmentsByOccurrenceId = new Map<
|
|
592
|
-
string,
|
|
593
|
-
Set<SweepInterval<ScheduleEvalAssignment>>
|
|
594
|
-
>();
|
|
595
|
-
|
|
596
|
-
for (const occurrence of snapshot.occurrences) {
|
|
597
|
-
assignmentIntervalsByOccurrenceId.set(
|
|
598
|
-
occurrence.id,
|
|
599
|
-
getSortedSweepIntervals(occurrence.assignments, (assignment) =>
|
|
600
|
-
getAssignmentInterval(assignment, occurrence),
|
|
601
|
-
),
|
|
602
|
-
);
|
|
603
|
-
assignmentCursorByOccurrenceId.set(occurrence.id, 0);
|
|
604
|
-
activeAssignmentsByOccurrenceId.set(occurrence.id, new Set());
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
const activeOccurrences = new Set<SweepInterval<ScheduleEvalOccurrence>>();
|
|
608
|
-
const activeDemand = new Set<SweepInterval<ScheduleEvalDemand>>();
|
|
609
|
-
let occurrenceCursor = 0;
|
|
610
|
-
let demandCursor = 0;
|
|
611
|
-
|
|
612
|
-
for (let i = 0; i < boundaries.length - 1; i++) {
|
|
613
|
-
const start = boundaries[i];
|
|
614
|
-
const end = boundaries[i + 1];
|
|
615
|
-
const startTime = start.getTime();
|
|
616
|
-
|
|
617
|
-
occurrenceCursor = admitSweepIntervals(
|
|
618
|
-
occurrenceIntervals,
|
|
619
|
-
occurrenceCursor,
|
|
620
|
-
startTime,
|
|
621
|
-
activeOccurrences,
|
|
622
|
-
);
|
|
623
|
-
demandCursor = admitSweepIntervals(
|
|
624
|
-
demandIntervals,
|
|
625
|
-
demandCursor,
|
|
626
|
-
startTime,
|
|
627
|
-
activeDemand,
|
|
628
|
-
);
|
|
629
|
-
|
|
630
|
-
const occurrences: ScheduleEvalOccurrence[] = [];
|
|
631
|
-
const assignmentsByOccurrenceId = new Map<
|
|
632
|
-
string,
|
|
633
|
-
ScheduleEvalAssignment[]
|
|
634
|
-
>();
|
|
635
|
-
|
|
636
|
-
for (const interval of activeOccurrences) {
|
|
637
|
-
const occurrence = interval.value;
|
|
638
|
-
occurrences.push(occurrence);
|
|
639
|
-
|
|
640
|
-
const active = activeAssignmentsByOccurrenceId.get(occurrence.id) as Set<
|
|
641
|
-
SweepInterval<ScheduleEvalAssignment>
|
|
642
|
-
>;
|
|
643
|
-
|
|
644
|
-
assignmentCursorByOccurrenceId.set(
|
|
645
|
-
occurrence.id,
|
|
646
|
-
admitSweepIntervals(
|
|
647
|
-
assignmentIntervalsByOccurrenceId.get(occurrence.id) || [],
|
|
648
|
-
assignmentCursorByOccurrenceId.get(occurrence.id) || 0,
|
|
649
|
-
startTime,
|
|
650
|
-
active,
|
|
651
|
-
),
|
|
652
|
-
);
|
|
653
|
-
|
|
654
|
-
assignmentsByOccurrenceId.set(
|
|
655
|
-
occurrence.id,
|
|
656
|
-
Array.from(active, (entry) => entry.value),
|
|
657
|
-
);
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
segments.push({
|
|
661
|
-
start,
|
|
662
|
-
end,
|
|
663
|
-
occurrences,
|
|
664
|
-
assignmentsByOccurrenceId,
|
|
665
|
-
demand: Array.from(activeDemand, (interval) => interval.value),
|
|
666
|
-
});
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
return segments;
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
/**
|
|
673
|
-
* Return the identity a rule competes on when the most specific scope wins.
|
|
674
|
-
*
|
|
675
|
-
* Two rules of the same kind only override each other when they are about the
|
|
676
|
-
* same thing: an organization's infant-ratio rule overrides the operation
|
|
677
|
-
* default for infants, and leaves the toddler rule alone. Without this, adding
|
|
678
|
-
* a second ratio would silently disable the first.
|
|
679
|
-
*/
|
|
680
|
-
|
|
681
|
-
export function getScheduleRuleIdentity(rule: ScheduleEvalRule): string {
|
|
682
|
-
switch (rule.kind) {
|
|
683
|
-
case 'REQUIRED_COUNT':
|
|
684
|
-
return `${rule.kind}:${rule.config?.slotKey ?? '*'}`;
|
|
685
|
-
case 'DERIVED_COUNT':
|
|
686
|
-
return `${rule.kind}:${rule.config?.category ?? '*'}`;
|
|
687
|
-
case 'ACTOR_WINDOW_AGGREGATE':
|
|
688
|
-
return `${rule.kind}:${rule.config?.metric ?? 'HOURS'}`;
|
|
689
|
-
case 'ELIGIBILITY_AT_TIME':
|
|
690
|
-
return `${rule.kind}:${rule.config?.qualification ?? '*'}`;
|
|
691
|
-
case 'EXCLUSION_WINDOW':
|
|
692
|
-
return `${rule.kind}:${rule.config?.afterKind ?? '*'}`;
|
|
693
|
-
case 'CONTINUOUS_COVERAGE': {
|
|
694
|
-
// Keyed by the instants the rule governs — its opening time AND the
|
|
695
|
-
// days it applies to — so two windows only compete when they are
|
|
696
|
-
// genuinely about the same thing.
|
|
697
|
-
//
|
|
698
|
-
// A bare kind made any second coverage rule silently replace the
|
|
699
|
-
// first. Keying on the opening time alone fixed the split-shift case
|
|
700
|
-
// and left a subtler one: weekday-restricted windows that open at the
|
|
701
|
-
// same hour, like Mon-Fri 08:00-18:00 alongside Saturday 08:00-12:00,
|
|
702
|
-
// still collided — and since the shipped template defaults every rule
|
|
703
|
-
// to 08:00, that collision was the likely shape rather than an exotic
|
|
704
|
-
// one. Days are normalized so [1,2] and [2,1] are one key.
|
|
705
|
-
const weekdays = getOperatingWeekdays(rule.config?.weekdays);
|
|
706
|
-
const days = weekdays
|
|
707
|
-
? [...weekdays].sort((a, b) => a - b).join(',')
|
|
708
|
-
: '*';
|
|
709
|
-
|
|
710
|
-
return `${rule.kind}:${rule.config?.opensAt ?? '*'}:${days}`;
|
|
711
|
-
}
|
|
712
|
-
default:
|
|
713
|
-
return rule.kind;
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
/*
|
|
718
|
-
* How specific one rule's scope is. Higher wins.
|
|
719
|
-
*/
|
|
720
|
-
|
|
721
|
-
function getRuleSpecificity(rule: ScheduleEvalRule): number {
|
|
722
|
-
if (rule.resourceId) {
|
|
723
|
-
return 3;
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
if (rule.calendarId) {
|
|
727
|
-
return 2;
|
|
728
|
-
}
|
|
729
|
-
|
|
730
|
-
if (rule.organizationId) {
|
|
731
|
-
return 1;
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
return 0;
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
/*
|
|
738
|
-
* Check whether one rule applies to a resource at all. A resource-scoped rule
|
|
739
|
-
* is invisible to every other resource; everything else applies everywhere.
|
|
740
|
-
*/
|
|
741
|
-
|
|
742
|
-
function doesRuleApplyToResource(
|
|
743
|
-
rule: ScheduleEvalRule,
|
|
744
|
-
resourceId: string | null,
|
|
745
|
-
): boolean {
|
|
746
|
-
return !rule.resourceId || rule.resourceId === resourceId;
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
/*
|
|
750
|
-
* Check whether one rule is in force at an instant.
|
|
751
|
-
*/
|
|
752
|
-
|
|
753
|
-
function isRuleEffectiveAt(rule: ScheduleEvalRule, at: Date): boolean {
|
|
754
|
-
if (rule.effectiveFrom && at.getTime() < rule.effectiveFrom.getTime()) {
|
|
755
|
-
return false;
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
if (rule.effectiveTo && at.getTime() >= rule.effectiveTo.getTime()) {
|
|
759
|
-
return false;
|
|
760
|
-
}
|
|
761
|
-
|
|
762
|
-
return true;
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
/**
|
|
766
|
-
* Reduce every candidate rule to the effective set for one resource at one
|
|
767
|
-
* instant: for each rule identity, the most specific scope in force wins, with
|
|
768
|
-
* "ordinal" then the id breaking a tie so the result is deterministic.
|
|
769
|
-
*/
|
|
770
|
-
|
|
771
|
-
export function selectEffectiveScheduleRules(
|
|
772
|
-
rules: ScheduleEvalRule[],
|
|
773
|
-
resourceId: string | null,
|
|
774
|
-
at: Date,
|
|
775
|
-
): ScheduleEvalRule[] {
|
|
776
|
-
const winners = new Map<string, ScheduleEvalRule>();
|
|
777
|
-
|
|
778
|
-
for (const rule of rules) {
|
|
779
|
-
if (
|
|
780
|
-
!doesRuleApplyToResource(rule, resourceId) ||
|
|
781
|
-
!isRuleEffectiveAt(rule, at)
|
|
782
|
-
) {
|
|
783
|
-
continue;
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
const identity = getScheduleRuleIdentity(rule);
|
|
787
|
-
const current = winners.get(identity);
|
|
788
|
-
|
|
789
|
-
if (!current) {
|
|
790
|
-
winners.set(identity, rule);
|
|
791
|
-
continue;
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
const currentSpecificity = getRuleSpecificity(current);
|
|
795
|
-
const candidateSpecificity = getRuleSpecificity(rule);
|
|
796
|
-
|
|
797
|
-
if (candidateSpecificity > currentSpecificity) {
|
|
798
|
-
winners.set(identity, rule);
|
|
799
|
-
continue;
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
if (candidateSpecificity === currentSpecificity) {
|
|
803
|
-
if (
|
|
804
|
-
rule.ordinal < current.ordinal ||
|
|
805
|
-
(rule.ordinal === current.ordinal && rule.id < current.id)
|
|
806
|
-
) {
|
|
807
|
-
winners.set(identity, rule);
|
|
808
|
-
}
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
return Array.from(winners.values());
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
/*
|
|
816
|
-
* Check whether one assignment's holder still had a qualification at an
|
|
817
|
-
* instant. A credential with no expiry is held forever.
|
|
818
|
-
*/
|
|
819
|
-
|
|
820
|
-
function holdsQualificationAt(
|
|
821
|
-
assignment: ScheduleEvalAssignment,
|
|
822
|
-
qualification: string,
|
|
823
|
-
at: Date,
|
|
824
|
-
): boolean {
|
|
825
|
-
if (!(assignment.qualifications || []).includes(qualification)) {
|
|
826
|
-
return false;
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
const expiresAt = assignment.qualificationExpiry?.[qualification];
|
|
830
|
-
|
|
831
|
-
return !expiresAt || expiresAt.getTime() > at.getTime();
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
/*
|
|
835
|
-
* Check whether one assignment satisfies a slot's predicate at an instant. An
|
|
836
|
-
* empty predicate means anyone may fill the slot.
|
|
837
|
-
*/
|
|
838
|
-
|
|
839
|
-
function doesAssignmentMatchPredicate(
|
|
840
|
-
assignment: ScheduleEvalAssignment,
|
|
841
|
-
predicate: ScheduleEvalSlot['predicate'],
|
|
842
|
-
at: Date,
|
|
843
|
-
): boolean {
|
|
844
|
-
if (!predicate) {
|
|
845
|
-
return true;
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
if (
|
|
849
|
-
predicate.roles?.length &&
|
|
850
|
-
!predicate.roles.includes(assignment.role || '')
|
|
851
|
-
) {
|
|
852
|
-
return false;
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
if (predicate.qualifications?.length) {
|
|
856
|
-
if (
|
|
857
|
-
!predicate.qualifications.every((qualification) =>
|
|
858
|
-
holdsQualificationAt(assignment, qualification, at),
|
|
859
|
-
)
|
|
860
|
-
) {
|
|
861
|
-
return false;
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
if (predicate.tags?.length) {
|
|
866
|
-
const held = new Set(assignment.tags || []);
|
|
867
|
-
if (!predicate.tags.every((tag) => held.has(tag))) {
|
|
868
|
-
return false;
|
|
869
|
-
}
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
return true;
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
/*
|
|
876
|
-
* Count the assignments filling one slot during a segment.
|
|
877
|
-
*/
|
|
878
|
-
|
|
879
|
-
function countSlotAssignments(
|
|
880
|
-
slot: ScheduleEvalSlot,
|
|
881
|
-
assignments: ScheduleEvalAssignment[],
|
|
882
|
-
at: Date,
|
|
883
|
-
): number {
|
|
884
|
-
return assignments.filter(
|
|
885
|
-
(assignment) =>
|
|
886
|
-
assignment.slotId === slot.id &&
|
|
887
|
-
doesAssignmentMatchPredicate(assignment, slot.predicate, at),
|
|
888
|
-
).length;
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
/*
|
|
892
|
-
* REQUIRED_COUNT — each slot needs its required number of matching assignees.
|
|
893
|
-
* The rule turns slot enforcement on for a calendar; its config may narrow to
|
|
894
|
-
* one slot key and may override that slot's own count.
|
|
895
|
-
*/
|
|
896
|
-
|
|
897
|
-
function evaluateRequiredCount(
|
|
898
|
-
rule: ScheduleEvalRule,
|
|
899
|
-
scopes: Set<string | null>,
|
|
900
|
-
segment: ScheduleEvalSegment,
|
|
901
|
-
violations: ScheduleEvalViolation[],
|
|
902
|
-
) {
|
|
903
|
-
const slotKey = rule.config?.slotKey ? String(rule.config.slotKey) : null;
|
|
904
|
-
|
|
905
|
-
for (const occurrence of segment.occurrences) {
|
|
906
|
-
if (!scopes.has(occurrence.resourceId)) {
|
|
907
|
-
continue;
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
const assignments =
|
|
911
|
-
segment.assignmentsByOccurrenceId.get(occurrence.id) || [];
|
|
912
|
-
|
|
913
|
-
for (const slot of occurrence.slots) {
|
|
914
|
-
if (slotKey && slot.key !== slotKey) {
|
|
915
|
-
continue;
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
const required =
|
|
919
|
-
slotKey &&
|
|
920
|
-
rule.config?.count !== undefined &&
|
|
921
|
-
rule.config?.count !== null
|
|
922
|
-
? Number(rule.config.count)
|
|
923
|
-
: slot.requiredCount;
|
|
924
|
-
const actual = countSlotAssignments(slot, assignments, segment.start);
|
|
925
|
-
|
|
926
|
-
if (actual < required) {
|
|
927
|
-
violations.push({
|
|
928
|
-
ruleId: rule.id,
|
|
929
|
-
templateKey: rule.templateKey ?? null,
|
|
930
|
-
kind: rule.kind,
|
|
931
|
-
severity: rule.severity,
|
|
932
|
-
resourceId: occurrence.resourceId,
|
|
933
|
-
occurrenceId: occurrence.id,
|
|
934
|
-
actorAccountId: null,
|
|
935
|
-
segmentStart: segment.start,
|
|
936
|
-
segmentEnd: segment.end,
|
|
937
|
-
detail: {
|
|
938
|
-
slotKey: slot.key,
|
|
939
|
-
required,
|
|
940
|
-
actual,
|
|
941
|
-
shortfall: required - actual,
|
|
942
|
-
},
|
|
943
|
-
});
|
|
944
|
-
}
|
|
945
|
-
}
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
/*
|
|
950
|
-
* DERIVED_COUNT — the required headcount is computed from a measured quantity
|
|
951
|
-
* over the same interval. This is the ratio rule: children present divided by
|
|
952
|
-
* the legal ratio, rounded up.
|
|
953
|
-
*/
|
|
954
|
-
|
|
955
|
-
function evaluateDerivedCount(
|
|
956
|
-
rule: ScheduleEvalRule,
|
|
957
|
-
scopes: Set<string | null>,
|
|
958
|
-
segment: ScheduleEvalSegment,
|
|
959
|
-
violations: ScheduleEvalViolation[],
|
|
960
|
-
) {
|
|
961
|
-
const category = rule.config?.category ? String(rule.config.category) : null;
|
|
962
|
-
const divisor = Number(rule.config?.divisor);
|
|
963
|
-
const slotKey = rule.config?.slotKey ? String(rule.config.slotKey) : null;
|
|
964
|
-
|
|
965
|
-
if (!category || !Number.isFinite(divisor) || divisor <= 0) {
|
|
966
|
-
return;
|
|
967
|
-
}
|
|
968
|
-
|
|
969
|
-
// Demand is measured per resource, so the requirement is too
|
|
970
|
-
const quantityByResourceId = new Map<string, number>();
|
|
971
|
-
|
|
972
|
-
for (const demand of segment.demand) {
|
|
973
|
-
if (demand.category !== category || !demand.resourceId) {
|
|
974
|
-
continue;
|
|
975
|
-
}
|
|
976
|
-
|
|
977
|
-
quantityByResourceId.set(
|
|
978
|
-
demand.resourceId,
|
|
979
|
-
(quantityByResourceId.get(demand.resourceId) || 0) + demand.quantity,
|
|
980
|
-
);
|
|
981
|
-
}
|
|
982
|
-
|
|
983
|
-
for (const [resourceId, quantity] of quantityByResourceId) {
|
|
984
|
-
if (!scopes.has(resourceId)) {
|
|
985
|
-
continue;
|
|
986
|
-
}
|
|
987
|
-
|
|
988
|
-
const required = Math.ceil(quantity / divisor);
|
|
989
|
-
const occurrences = segment.occurrences.filter(
|
|
990
|
-
(occurrence) => occurrence.resourceId === resourceId,
|
|
991
|
-
);
|
|
992
|
-
const actual = occurrences.reduce((total, occurrence) => {
|
|
993
|
-
const assignments =
|
|
994
|
-
segment.assignmentsByOccurrenceId.get(occurrence.id) || [];
|
|
995
|
-
const counted = slotKey
|
|
996
|
-
? assignments.filter((assignment) =>
|
|
997
|
-
occurrence.slots.some(
|
|
998
|
-
(slot) => slot.key === slotKey && slot.id === assignment.slotId,
|
|
999
|
-
),
|
|
1000
|
-
)
|
|
1001
|
-
: assignments;
|
|
1002
|
-
|
|
1003
|
-
return total + counted.length;
|
|
1004
|
-
}, 0);
|
|
1005
|
-
|
|
1006
|
-
if (actual < required) {
|
|
1007
|
-
violations.push({
|
|
1008
|
-
ruleId: rule.id,
|
|
1009
|
-
templateKey: rule.templateKey ?? null,
|
|
1010
|
-
kind: rule.kind,
|
|
1011
|
-
severity: rule.severity,
|
|
1012
|
-
resourceId,
|
|
1013
|
-
occurrenceId: occurrences[0]?.id ?? null,
|
|
1014
|
-
actorAccountId: null,
|
|
1015
|
-
segmentStart: segment.start,
|
|
1016
|
-
segmentEnd: segment.end,
|
|
1017
|
-
detail: {
|
|
1018
|
-
category,
|
|
1019
|
-
quantity,
|
|
1020
|
-
divisor,
|
|
1021
|
-
required,
|
|
1022
|
-
actual,
|
|
1023
|
-
shortfall: required - actual,
|
|
1024
|
-
},
|
|
1025
|
-
});
|
|
1026
|
-
}
|
|
1027
|
-
}
|
|
1028
|
-
}
|
|
1029
|
-
|
|
1030
|
-
/*
|
|
1031
|
-
* RESOURCE_CAPACITY — a resource holds at most C concurrent occurrences. This
|
|
1032
|
-
* is what stops one room being booked twice or one vehicle being sent to two
|
|
1033
|
-
* places at once.
|
|
1034
|
-
*/
|
|
1035
|
-
|
|
1036
|
-
function evaluateResourceCapacity(
|
|
1037
|
-
rule: ScheduleEvalRule,
|
|
1038
|
-
scopes: Set<string | null>,
|
|
1039
|
-
segment: ScheduleEvalSegment,
|
|
1040
|
-
resourcesById: Map<string, ScheduleEvalResource>,
|
|
1041
|
-
violations: ScheduleEvalViolation[],
|
|
1042
|
-
) {
|
|
1043
|
-
const countByResourceId = new Map<string, string[]>();
|
|
1044
|
-
|
|
1045
|
-
for (const occurrence of segment.occurrences) {
|
|
1046
|
-
if (!occurrence.resourceId || !scopes.has(occurrence.resourceId)) {
|
|
1047
|
-
continue;
|
|
1048
|
-
}
|
|
1049
|
-
|
|
1050
|
-
const existing = countByResourceId.get(occurrence.resourceId);
|
|
1051
|
-
|
|
1052
|
-
if (existing) {
|
|
1053
|
-
existing.push(occurrence.id);
|
|
1054
|
-
} else {
|
|
1055
|
-
countByResourceId.set(occurrence.resourceId, [occurrence.id]);
|
|
1056
|
-
}
|
|
1057
|
-
}
|
|
1058
|
-
|
|
1059
|
-
for (const [resourceId, occurrenceIds] of countByResourceId) {
|
|
1060
|
-
const configured = rule.config?.capacity;
|
|
1061
|
-
const capacity =
|
|
1062
|
-
configured === undefined || configured === null
|
|
1063
|
-
? resourcesById.get(resourceId)?.capacity
|
|
1064
|
-
: Number(configured);
|
|
1065
|
-
|
|
1066
|
-
if (
|
|
1067
|
-
capacity === null ||
|
|
1068
|
-
capacity === undefined ||
|
|
1069
|
-
!Number.isFinite(capacity)
|
|
1070
|
-
) {
|
|
1071
|
-
continue;
|
|
1072
|
-
}
|
|
1073
|
-
|
|
1074
|
-
if (occurrenceIds.length > capacity) {
|
|
1075
|
-
violations.push({
|
|
1076
|
-
ruleId: rule.id,
|
|
1077
|
-
templateKey: rule.templateKey ?? null,
|
|
1078
|
-
kind: rule.kind,
|
|
1079
|
-
severity: rule.severity,
|
|
1080
|
-
resourceId,
|
|
1081
|
-
occurrenceId: occurrenceIds[0],
|
|
1082
|
-
actorAccountId: null,
|
|
1083
|
-
segmentStart: segment.start,
|
|
1084
|
-
segmentEnd: segment.end,
|
|
1085
|
-
detail: {
|
|
1086
|
-
capacity,
|
|
1087
|
-
actual: occurrenceIds.length,
|
|
1088
|
-
occurrenceIds,
|
|
1089
|
-
},
|
|
1090
|
-
});
|
|
1091
|
-
}
|
|
1092
|
-
}
|
|
1093
|
-
}
|
|
1094
|
-
|
|
1095
|
-
/*
|
|
1096
|
-
* ELIGIBILITY_AT_TIME — everyone working must hold a required attribute at
|
|
1097
|
-
* that instant. Expiry is why this is checked per segment rather than once:
|
|
1098
|
-
* a credential can lapse in the middle of a shift.
|
|
1099
|
-
*/
|
|
1100
|
-
|
|
1101
|
-
function evaluateEligibilityAtTime(
|
|
1102
|
-
rule: ScheduleEvalRule,
|
|
1103
|
-
scopes: Set<string | null>,
|
|
1104
|
-
segment: ScheduleEvalSegment,
|
|
1105
|
-
violations: ScheduleEvalViolation[],
|
|
1106
|
-
) {
|
|
1107
|
-
const qualification = rule.config?.qualification
|
|
1108
|
-
? String(rule.config.qualification)
|
|
1109
|
-
: null;
|
|
1110
|
-
|
|
1111
|
-
if (!qualification) {
|
|
1112
|
-
return;
|
|
1113
|
-
}
|
|
1114
|
-
|
|
1115
|
-
for (const occurrence of segment.occurrences) {
|
|
1116
|
-
if (!scopes.has(occurrence.resourceId)) {
|
|
1117
|
-
continue;
|
|
1118
|
-
}
|
|
1119
|
-
|
|
1120
|
-
const assignments =
|
|
1121
|
-
segment.assignmentsByOccurrenceId.get(occurrence.id) || [];
|
|
1122
|
-
|
|
1123
|
-
for (const assignment of assignments) {
|
|
1124
|
-
if (holdsQualificationAt(assignment, qualification, segment.start)) {
|
|
1125
|
-
continue;
|
|
1126
|
-
}
|
|
1127
|
-
|
|
1128
|
-
violations.push({
|
|
1129
|
-
ruleId: rule.id,
|
|
1130
|
-
templateKey: rule.templateKey ?? null,
|
|
1131
|
-
kind: rule.kind,
|
|
1132
|
-
severity: rule.severity,
|
|
1133
|
-
resourceId: occurrence.resourceId,
|
|
1134
|
-
occurrenceId: occurrence.id,
|
|
1135
|
-
actorAccountId: assignment.actorAccountId,
|
|
1136
|
-
segmentStart: segment.start,
|
|
1137
|
-
segmentEnd: segment.end,
|
|
1138
|
-
detail: {
|
|
1139
|
-
qualification,
|
|
1140
|
-
actorType: assignment.actorType,
|
|
1141
|
-
actorId: assignment.actorId,
|
|
1142
|
-
assignmentId: assignment.id,
|
|
1143
|
-
},
|
|
1144
|
-
});
|
|
1145
|
-
}
|
|
1146
|
-
}
|
|
1147
|
-
}
|
|
1148
|
-
|
|
1149
|
-
/*
|
|
1150
|
-
* CONTINUOUS_COVERAGE — no instant inside the operating window may be
|
|
1151
|
-
* unstaffed. This is the "we open at 6am and someone must always be here"
|
|
1152
|
-
* rule; unlike the others it fires on ABSENCE, so it is the only one that can
|
|
1153
|
-
* flag a stretch of time with nothing scheduled in it at all.
|
|
1154
|
-
*/
|
|
1155
|
-
|
|
1156
|
-
function evaluateContinuousCoverage(
|
|
1157
|
-
rule: ScheduleEvalRule,
|
|
1158
|
-
evidenceScopes: Set<string | null>,
|
|
1159
|
-
segment: ScheduleEvalSegment,
|
|
1160
|
-
operatingIntervals: Array<{ start: Date; end: Date }>,
|
|
1161
|
-
violations: ScheduleEvalViolation[],
|
|
1162
|
-
) {
|
|
1163
|
-
// Opening and closing time are segment boundaries, so no segment can begin
|
|
1164
|
-
// inside one operating window and end outside it: testing the start instant
|
|
1165
|
-
// answers for the whole segment
|
|
1166
|
-
const segmentStartTime = segment.start.getTime();
|
|
1167
|
-
const isOpen = operatingIntervals.some(
|
|
1168
|
-
(interval) =>
|
|
1169
|
-
interval.start.getTime() <= segmentStartTime &&
|
|
1170
|
-
interval.end.getTime() > segmentStartTime,
|
|
1171
|
-
);
|
|
1172
|
-
|
|
1173
|
-
if (!isOpen) {
|
|
1174
|
-
return;
|
|
1175
|
-
}
|
|
1176
|
-
|
|
1177
|
-
const staffed = segment.occurrences.some((occurrence) => {
|
|
1178
|
-
if (!evidenceScopes.has(occurrence.resourceId)) {
|
|
1179
|
-
return false;
|
|
1180
|
-
}
|
|
1181
|
-
|
|
1182
|
-
return (
|
|
1183
|
-
(segment.assignmentsByOccurrenceId.get(occurrence.id) || []).length > 0
|
|
1184
|
-
);
|
|
1185
|
-
});
|
|
1186
|
-
|
|
1187
|
-
if (!staffed) {
|
|
1188
|
-
violations.push({
|
|
1189
|
-
ruleId: rule.id,
|
|
1190
|
-
templateKey: rule.templateKey ?? null,
|
|
1191
|
-
kind: rule.kind,
|
|
1192
|
-
severity: rule.severity,
|
|
1193
|
-
resourceId: rule.resourceId,
|
|
1194
|
-
occurrenceId: null,
|
|
1195
|
-
actorAccountId: null,
|
|
1196
|
-
segmentStart: segment.start,
|
|
1197
|
-
segmentEnd: segment.end,
|
|
1198
|
-
detail: {
|
|
1199
|
-
opensAt: rule.config?.opensAt,
|
|
1200
|
-
closesAt: rule.config?.closesAt,
|
|
1201
|
-
reason: 'NO_COVERAGE',
|
|
1202
|
-
},
|
|
1203
|
-
});
|
|
1204
|
-
}
|
|
1205
|
-
}
|
|
1206
|
-
|
|
1207
|
-
/*
|
|
1208
|
-
* ACTOR_WINDOW_AGGREGATE — per-person rolling limits: hours per week, shifts
|
|
1209
|
-
* per day, minimum rest between shifts.
|
|
1210
|
-
*
|
|
1211
|
-
* This one cannot ride the sweep. A segment knows what is happening during it,
|
|
1212
|
-
* while these limits are about a person's total across a window that reaches
|
|
1213
|
-
* outside the evaluated range entirely — a Monday shift can put someone over
|
|
1214
|
-
* a Sunday-to-Saturday cap. It is evaluated per assignment instead, against
|
|
1215
|
-
* the actor's own timeline.
|
|
1216
|
-
*/
|
|
1217
|
-
|
|
1218
|
-
function evaluateActorWindowAggregate(
|
|
1219
|
-
rule: ScheduleEvalRule,
|
|
1220
|
-
evidenceScopes: Set<string | null>,
|
|
1221
|
-
snapshot: ScheduleEvaluationSnapshot,
|
|
1222
|
-
violations: ScheduleEvalViolation[],
|
|
1223
|
-
) {
|
|
1224
|
-
const metric = String(rule.config?.metric ?? 'HOURS');
|
|
1225
|
-
const windowHours = Number(rule.config?.windowHours);
|
|
1226
|
-
const max = Number(rule.config?.max);
|
|
1227
|
-
|
|
1228
|
-
if (
|
|
1229
|
-
!Number.isFinite(windowHours) ||
|
|
1230
|
-
windowHours <= 0 ||
|
|
1231
|
-
!Number.isFinite(max) ||
|
|
1232
|
-
max < 0
|
|
1233
|
-
) {
|
|
1234
|
-
return;
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
const windowMs = windowHours * 3_600_000;
|
|
1238
|
-
|
|
1239
|
-
// Keyed by occurrence AND interval so one stretch of work is counted exactly
|
|
1240
|
-
// once.
|
|
1241
|
-
//
|
|
1242
|
-
// The history a loader supplies is a window over the actor's assignments,
|
|
1243
|
-
// and any sane window that reaches BACK from this one also contains it — so
|
|
1244
|
-
// the shifts being judged arrive from both directions. Counting both copies
|
|
1245
|
-
// doubled every in-window hour, and a forty-hour weekly cap fired at twenty
|
|
1246
|
-
// actual hours. The duplicate is identical in occurrence and in interval, so
|
|
1247
|
-
// it collapses; two genuinely different partial assignments on one
|
|
1248
|
-
// occurrence — a split shift with a gap in the middle — differ in interval
|
|
1249
|
-
// and both survive. Keying on the occurrence alone silently discarded the
|
|
1250
|
-
// second half of every split shift. Deduping here rather than in each loader
|
|
1251
|
-
// means no future caller can reintroduce either failure.
|
|
1252
|
-
const timeline = new Map<
|
|
1253
|
-
string,
|
|
1254
|
-
Map<string, ScheduleEvalActorHistoryEntry>
|
|
1255
|
-
>();
|
|
1256
|
-
|
|
1257
|
-
const addEntry = (entry: ScheduleEvalActorHistoryEntry) => {
|
|
1258
|
-
const key = `${entry.occurrenceId}|${entry.startAt.getTime()}|${entry.endAt.getTime()}`;
|
|
1259
|
-
const existing = timeline.get(entry.actorAccountId);
|
|
1260
|
-
|
|
1261
|
-
if (existing) {
|
|
1262
|
-
existing.set(key, entry);
|
|
1263
|
-
} else {
|
|
1264
|
-
timeline.set(entry.actorAccountId, new Map([[key, entry]]));
|
|
1265
|
-
}
|
|
1266
|
-
};
|
|
1267
|
-
|
|
1268
|
-
// History is filtered by the same evidence scope the in-window occurrences
|
|
1269
|
-
// are, so the answer does not depend on which side of the window boundary a
|
|
1270
|
-
// shift happens to fall on. An entry that does not say which resource it was
|
|
1271
|
-
// worked on is admitted: a loader that cannot supply it should over-count
|
|
1272
|
-
// against a cap rather than under-count.
|
|
1273
|
-
for (const entry of snapshot.actorHistory || []) {
|
|
1274
|
-
if (
|
|
1275
|
-
entry.resourceId !== undefined &&
|
|
1276
|
-
!evidenceScopes.has(entry.resourceId ?? null)
|
|
1277
|
-
) {
|
|
1278
|
-
continue;
|
|
1279
|
-
}
|
|
1280
|
-
|
|
1281
|
-
addEntry(entry);
|
|
1282
|
-
}
|
|
1283
|
-
|
|
1284
|
-
// Assignments inside the window are the ones that can be flagged; history
|
|
1285
|
-
// only contributes to the totals.
|
|
1286
|
-
//
|
|
1287
|
-
// This rule kind is scoped by the rule's OWN resource and by nothing else.
|
|
1288
|
-
// The usual narrowing — dropping the resources whose own override beat this
|
|
1289
|
-
// rule — is right for a rule that attributes its violation to a resource,
|
|
1290
|
-
// and wrong here, because a rolling limit is a fact about a PERSON. Under
|
|
1291
|
-
// the usual narrowing an organization-wide cap could neither count nor flag
|
|
1292
|
-
// the hours worked in a room that carried its own cap, so twelve hours in
|
|
1293
|
-
// one room and twelve in another passed a sixteen-hour cap the moment
|
|
1294
|
-
// somebody wrote the second rule. The two rules are not alternatives; they
|
|
1295
|
-
// ask different questions and both apply.
|
|
1296
|
-
const inWindow: ScheduleEvalActorHistoryEntry[] = [];
|
|
1297
|
-
|
|
1298
|
-
for (const occurrence of snapshot.occurrences) {
|
|
1299
|
-
if (!evidenceScopes.has(occurrence.resourceId)) {
|
|
1300
|
-
continue;
|
|
1301
|
-
}
|
|
1302
|
-
|
|
1303
|
-
for (const assignment of occurrence.assignments) {
|
|
1304
|
-
if (!assignment.actorAccountId) {
|
|
1305
|
-
continue;
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
const interval = getAssignmentInterval(assignment, occurrence);
|
|
1309
|
-
const entry = {
|
|
1310
|
-
occurrenceId: occurrence.id,
|
|
1311
|
-
actorAccountId: assignment.actorAccountId,
|
|
1312
|
-
startAt: interval.startAt,
|
|
1313
|
-
endAt: interval.endAt,
|
|
1314
|
-
};
|
|
1315
|
-
|
|
1316
|
-
addEntry(entry);
|
|
1317
|
-
inWindow.push(entry);
|
|
1318
|
-
}
|
|
1319
|
-
}
|
|
1320
|
-
|
|
1321
|
-
for (const entry of inWindow) {
|
|
1322
|
-
const entries = Array.from(
|
|
1323
|
-
timeline.get(entry.actorAccountId)?.values() || [],
|
|
1324
|
-
);
|
|
1325
|
-
// The rolling window ends when this assignment ends, so the assignment
|
|
1326
|
-
// being judged is always inside it
|
|
1327
|
-
const windowStart = new Date(entry.endAt.getTime() - windowMs);
|
|
1328
|
-
const contributing = entries.filter(
|
|
1329
|
-
(candidate) =>
|
|
1330
|
-
candidate.endAt.getTime() > windowStart.getTime() &&
|
|
1331
|
-
candidate.startAt.getTime() < entry.endAt.getTime(),
|
|
1332
|
-
);
|
|
1333
|
-
|
|
1334
|
-
const total =
|
|
1335
|
-
metric === 'SHIFTS'
|
|
1336
|
-
? contributing.length
|
|
1337
|
-
: contributing.reduce((hours, candidate) => {
|
|
1338
|
-
const overlapStart = maxDate(candidate.startAt, windowStart);
|
|
1339
|
-
const overlapEnd = minDate(candidate.endAt, entry.endAt);
|
|
1340
|
-
return (
|
|
1341
|
-
hours +
|
|
1342
|
-
Math.max(0, overlapEnd.getTime() - overlapStart.getTime()) /
|
|
1343
|
-
3_600_000
|
|
1344
|
-
);
|
|
1345
|
-
}, 0);
|
|
1346
|
-
|
|
1347
|
-
if (total > max) {
|
|
1348
|
-
violations.push({
|
|
1349
|
-
ruleId: rule.id,
|
|
1350
|
-
templateKey: rule.templateKey ?? null,
|
|
1351
|
-
kind: rule.kind,
|
|
1352
|
-
severity: rule.severity,
|
|
1353
|
-
resourceId: null,
|
|
1354
|
-
occurrenceId: entry.occurrenceId,
|
|
1355
|
-
actorAccountId: entry.actorAccountId,
|
|
1356
|
-
segmentStart: entry.startAt,
|
|
1357
|
-
segmentEnd: entry.endAt,
|
|
1358
|
-
detail: {
|
|
1359
|
-
metric,
|
|
1360
|
-
windowHours,
|
|
1361
|
-
max,
|
|
1362
|
-
total: Math.round(total * 100) / 100,
|
|
1363
|
-
over: Math.round((total - max) * 100) / 100,
|
|
1364
|
-
},
|
|
1365
|
-
});
|
|
1366
|
-
}
|
|
1367
|
-
}
|
|
1368
|
-
}
|
|
1369
|
-
|
|
1370
|
-
/*
|
|
1371
|
-
* EXCLUSION_WINDOW — after an occurrence of one kind ends on a resource,
|
|
1372
|
-
* nothing may start there for a set duration: cleaning turnover between
|
|
1373
|
-
* classes, a spray re-entry interval, equipment cool-down.
|
|
1374
|
-
*
|
|
1375
|
-
* Also outside the sweep: it is a relationship between two occurrences, not a
|
|
1376
|
-
* property of any single instant.
|
|
1377
|
-
*/
|
|
1378
|
-
|
|
1379
|
-
function evaluateExclusionWindow(
|
|
1380
|
-
rule: ScheduleEvalRule,
|
|
1381
|
-
scopes: Set<string | null>,
|
|
1382
|
-
snapshot: ScheduleEvaluationSnapshot,
|
|
1383
|
-
violations: ScheduleEvalViolation[],
|
|
1384
|
-
) {
|
|
1385
|
-
const afterKind = rule.config?.afterKind
|
|
1386
|
-
? String(rule.config.afterKind)
|
|
1387
|
-
: null;
|
|
1388
|
-
const blockKind = rule.config?.blockKind
|
|
1389
|
-
? String(rule.config.blockKind)
|
|
1390
|
-
: null;
|
|
1391
|
-
const blockMinutes = Number(rule.config?.blockMinutes);
|
|
1392
|
-
|
|
1393
|
-
if (!afterKind || !Number.isFinite(blockMinutes) || blockMinutes <= 0) {
|
|
1394
|
-
return;
|
|
1395
|
-
}
|
|
1396
|
-
|
|
1397
|
-
const blockMs = blockMinutes * 60_000;
|
|
1398
|
-
const byResourceId = new Map<string, ScheduleEvalOccurrence[]>();
|
|
1399
|
-
|
|
1400
|
-
for (const occurrence of snapshot.occurrences) {
|
|
1401
|
-
if (!occurrence.resourceId || !scopes.has(occurrence.resourceId)) {
|
|
1402
|
-
continue;
|
|
1403
|
-
}
|
|
1404
|
-
|
|
1405
|
-
const existing = byResourceId.get(occurrence.resourceId);
|
|
1406
|
-
|
|
1407
|
-
if (existing) {
|
|
1408
|
-
existing.push(occurrence);
|
|
1409
|
-
} else {
|
|
1410
|
-
byResourceId.set(occurrence.resourceId, [occurrence]);
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
|
|
1414
|
-
for (const [resourceId, occurrences] of byResourceId) {
|
|
1415
|
-
const ordered = [...occurrences].sort(
|
|
1416
|
-
(a, b) => a.startAt.getTime() - b.startAt.getTime(),
|
|
1417
|
-
);
|
|
1418
|
-
|
|
1419
|
-
for (const earlier of ordered) {
|
|
1420
|
-
if (earlier.kind !== afterKind) {
|
|
1421
|
-
continue;
|
|
1422
|
-
}
|
|
1423
|
-
|
|
1424
|
-
const clearAt = new Date(earlier.endAt.getTime() + blockMs);
|
|
1425
|
-
|
|
1426
|
-
for (const later of ordered) {
|
|
1427
|
-
// Sorted by start, so once one candidate starts at or after the
|
|
1428
|
-
// blocked window closes, every later one does too
|
|
1429
|
-
if (later.startAt.getTime() >= clearAt.getTime()) {
|
|
1430
|
-
break;
|
|
1431
|
-
}
|
|
1432
|
-
|
|
1433
|
-
if (
|
|
1434
|
-
later.id === earlier.id ||
|
|
1435
|
-
later.startAt.getTime() < earlier.endAt.getTime()
|
|
1436
|
-
) {
|
|
1437
|
-
continue;
|
|
1438
|
-
}
|
|
1439
|
-
|
|
1440
|
-
if (blockKind && later.kind !== blockKind) {
|
|
1441
|
-
continue;
|
|
1442
|
-
}
|
|
1443
|
-
|
|
1444
|
-
violations.push({
|
|
1445
|
-
ruleId: rule.id,
|
|
1446
|
-
templateKey: rule.templateKey ?? null,
|
|
1447
|
-
kind: rule.kind,
|
|
1448
|
-
severity: rule.severity,
|
|
1449
|
-
resourceId,
|
|
1450
|
-
occurrenceId: later.id,
|
|
1451
|
-
actorAccountId: null,
|
|
1452
|
-
segmentStart: earlier.endAt,
|
|
1453
|
-
segmentEnd: later.startAt,
|
|
1454
|
-
detail: {
|
|
1455
|
-
afterKind,
|
|
1456
|
-
blockMinutes,
|
|
1457
|
-
precededByOccurrenceId: earlier.id,
|
|
1458
|
-
gapMinutes: Math.round(
|
|
1459
|
-
(later.startAt.getTime() - earlier.endAt.getTime()) / 60_000,
|
|
1460
|
-
),
|
|
1461
|
-
},
|
|
1462
|
-
});
|
|
1463
|
-
}
|
|
1464
|
-
}
|
|
1465
|
-
}
|
|
1466
|
-
}
|
|
1467
|
-
|
|
1468
|
-
/**
|
|
1469
|
-
* Return WHICH breach a violation is, ignoring how bad it is and when.
|
|
1470
|
-
*
|
|
1471
|
-
* This is the identity that answers "is this the same problem as that one" —
|
|
1472
|
-
* the rule, the resource, the occurrence, the person. It deliberately excludes
|
|
1473
|
-
* "detail", so a shortfall of two and a shortfall of one on the same slot are
|
|
1474
|
-
* one breach getting better rather than two different breaches.
|
|
1475
|
-
*
|
|
1476
|
-
* That distinction is what makes it the right basis for deciding eligibility.
|
|
1477
|
-
* Comparing violation COUNTS lets somebody who closes one breach and opens
|
|
1478
|
-
* another look like they changed nothing, and comparing full merge keys rejects
|
|
1479
|
-
* somebody who merely improves a shortfall, because improving it rewrites the
|
|
1480
|
-
* detail. Comparing identities asks the question actually being asked: does
|
|
1481
|
-
* putting this person on this shift introduce a problem that was not there
|
|
1482
|
-
* before?
|
|
1483
|
-
*/
|
|
1484
|
-
|
|
1485
|
-
export function getScheduleBreachIdentity(
|
|
1486
|
-
violation: ScheduleEvalViolation,
|
|
1487
|
-
): string {
|
|
1488
|
-
return [
|
|
1489
|
-
violation.ruleId,
|
|
1490
|
-
violation.kind,
|
|
1491
|
-
violation.resourceId,
|
|
1492
|
-
violation.occurrenceId,
|
|
1493
|
-
violation.actorAccountId,
|
|
1494
|
-
].join('|');
|
|
1495
|
-
}
|
|
1496
|
-
|
|
1497
|
-
/*
|
|
1498
|
-
* Return the key that decides whether two violations are "the same breach"
|
|
1499
|
-
* and can therefore be joined when they sit on adjacent segments.
|
|
1500
|
-
*
|
|
1501
|
-
* Adjacent segments only merge when the breach is identical in degree as well
|
|
1502
|
-
* as identity, so the detail is part of the key: a shortfall that changes from
|
|
1503
|
-
* two to one at 09:00 is two facts about the morning, not one.
|
|
1504
|
-
*/
|
|
1505
|
-
|
|
1506
|
-
function getViolationMergeKey(violation: ScheduleEvalViolation): string {
|
|
1507
|
-
return `${getScheduleBreachIdentity(violation)}|${JSON.stringify(violation.detail)}`;
|
|
1508
|
-
}
|
|
1509
|
-
|
|
1510
|
-
/**
|
|
1511
|
-
* Join violations that describe one continuous breach across adjacent
|
|
1512
|
-
* segments.
|
|
1513
|
-
*
|
|
1514
|
-
* Without this a four-hour ratio shortfall on a busy morning is reported as
|
|
1515
|
-
* thirty separate violations — one per segment the sweep happened to cut — and
|
|
1516
|
-
* a director looking at the coverage board cannot tell one long problem from
|
|
1517
|
-
* thirty small ones.
|
|
1518
|
-
*/
|
|
1519
|
-
|
|
1520
|
-
export function mergeAdjacentScheduleViolations(
|
|
1521
|
-
violations: ScheduleEvalViolation[],
|
|
1522
|
-
): ScheduleEvalViolation[] {
|
|
1523
|
-
// Keyed once per violation rather than inside the comparator. The key
|
|
1524
|
-
// serializes the detail object, so computing it per comparison made sorting
|
|
1525
|
-
// a long shortfall — which produces one violation per segment it spans —
|
|
1526
|
-
// cost O(n log n) JSON serializations of the same handful of objects.
|
|
1527
|
-
const keyed = violations.map((violation) => ({
|
|
1528
|
-
violation,
|
|
1529
|
-
key: getViolationMergeKey(violation),
|
|
1530
|
-
}));
|
|
1531
|
-
|
|
1532
|
-
keyed.sort(
|
|
1533
|
-
(a, b) =>
|
|
1534
|
-
a.violation.segmentStart.getTime() - b.violation.segmentStart.getTime() ||
|
|
1535
|
-
a.key.localeCompare(b.key),
|
|
1536
|
-
);
|
|
1537
|
-
|
|
1538
|
-
const merged: ScheduleEvalViolation[] = [];
|
|
1539
|
-
const openByKey = new Map<string, ScheduleEvalViolation>();
|
|
1540
|
-
|
|
1541
|
-
for (const { violation, key } of keyed) {
|
|
1542
|
-
const open = openByKey.get(key);
|
|
1543
|
-
|
|
1544
|
-
if (
|
|
1545
|
-
open &&
|
|
1546
|
-
open.segmentEnd.getTime() === violation.segmentStart.getTime()
|
|
1547
|
-
) {
|
|
1548
|
-
open.segmentEnd = violation.segmentEnd;
|
|
1549
|
-
continue;
|
|
1550
|
-
}
|
|
1551
|
-
|
|
1552
|
-
const next = { ...violation };
|
|
1553
|
-
openByKey.set(key, next);
|
|
1554
|
-
merged.push(next);
|
|
1555
|
-
}
|
|
1556
|
-
|
|
1557
|
-
return merged.sort(
|
|
1558
|
-
(a, b) =>
|
|
1559
|
-
a.segmentStart.getTime() - b.segmentStart.getTime() ||
|
|
1560
|
-
String(a.occurrenceId).localeCompare(String(b.occurrenceId)),
|
|
1561
|
-
);
|
|
1562
|
-
}
|
|
1563
|
-
|
|
1564
|
-
/**
|
|
1565
|
-
* Evaluate one calendar window against its rules.
|
|
1566
|
-
*
|
|
1567
|
-
* Five of the seven rule kinds are segment-local and run inside the sweep;
|
|
1568
|
-
* ACTOR_WINDOW_AGGREGATE and EXCLUSION_WINDOW reason across segments and run
|
|
1569
|
-
* once over the whole snapshot.
|
|
1570
|
-
*/
|
|
1571
|
-
|
|
1572
|
-
/*
|
|
1573
|
-
* Return the instants at which the effective rule SET can change.
|
|
1574
|
-
*
|
|
1575
|
-
* Rule selection depends on the instant only through the effective-date
|
|
1576
|
-
* predicates, so between two consecutive such instants the answer is identical
|
|
1577
|
-
* for a given resource. That is what makes the selection cacheable across
|
|
1578
|
-
* segments: a day cut into two hundred segments by shift boundaries still has
|
|
1579
|
-
* one rule epoch, and resolving the rules once instead of two hundred times per
|
|
1580
|
-
* resource is the difference between a linear pass and a quadratic one.
|
|
1581
|
-
*/
|
|
1582
|
-
|
|
1583
|
-
function getRuleEpochBoundaries(rules: ScheduleEvalRule[]): number[] {
|
|
1584
|
-
const instants = new Set<number>();
|
|
1585
|
-
|
|
1586
|
-
for (const rule of rules) {
|
|
1587
|
-
if (rule.effectiveFrom) {
|
|
1588
|
-
instants.add(rule.effectiveFrom.getTime());
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
if (rule.effectiveTo) {
|
|
1592
|
-
instants.add(rule.effectiveTo.getTime());
|
|
1593
|
-
}
|
|
1594
|
-
}
|
|
1595
|
-
|
|
1596
|
-
return Array.from(instants).sort((a, b) => a - b);
|
|
1597
|
-
}
|
|
1598
|
-
|
|
1599
|
-
/*
|
|
1600
|
-
* Return the stretches of the window over which the set of rules in force
|
|
1601
|
-
* cannot change, clipped to the window.
|
|
1602
|
-
*
|
|
1603
|
-
* The cross-segment rule kinds cannot ride the sweep, but they still have to
|
|
1604
|
-
* honour effective dates. Running them once per epoch, with each violation kept
|
|
1605
|
-
* only if its own anchor falls inside that epoch, gives them the same
|
|
1606
|
-
* per-instant answer the segment-local kinds get for free — and because the
|
|
1607
|
-
* epochs partition the window, no violation can be emitted twice.
|
|
1608
|
-
*/
|
|
1609
|
-
|
|
1610
|
-
function getRuleEpochIntervals(
|
|
1611
|
-
epochBoundaries: number[],
|
|
1612
|
-
windowStart: Date,
|
|
1613
|
-
windowEnd: Date,
|
|
1614
|
-
): Array<{ start: Date; end: Date }> {
|
|
1615
|
-
const cuts = new Set<number>([windowStart.getTime(), windowEnd.getTime()]);
|
|
1616
|
-
|
|
1617
|
-
for (const boundary of epochBoundaries) {
|
|
1618
|
-
if (boundary > windowStart.getTime() && boundary < windowEnd.getTime()) {
|
|
1619
|
-
cuts.add(boundary);
|
|
1620
|
-
}
|
|
1621
|
-
}
|
|
1622
|
-
|
|
1623
|
-
const ordered = Array.from(cuts).sort((a, b) => a - b);
|
|
1624
|
-
const intervals: Array<{ start: Date; end: Date }> = [];
|
|
1625
|
-
|
|
1626
|
-
for (let index = 0; index < ordered.length - 1; index++) {
|
|
1627
|
-
intervals.push({
|
|
1628
|
-
start: new Date(ordered[index]),
|
|
1629
|
-
end: new Date(ordered[index + 1]),
|
|
1630
|
-
});
|
|
1631
|
-
}
|
|
1632
|
-
|
|
1633
|
-
return intervals;
|
|
1634
|
-
}
|
|
1635
|
-
|
|
1636
|
-
/*
|
|
1637
|
-
* Return which rule epoch one instant falls in.
|
|
1638
|
-
*/
|
|
1639
|
-
|
|
1640
|
-
function getRuleEpochIndex(epochBoundaries: number[], at: Date): number {
|
|
1641
|
-
const time = at.getTime();
|
|
1642
|
-
let index = 0;
|
|
1643
|
-
|
|
1644
|
-
while (index < epochBoundaries.length && epochBoundaries[index] <= time) {
|
|
1645
|
-
index++;
|
|
1646
|
-
}
|
|
1647
|
-
|
|
1648
|
-
return index;
|
|
1649
|
-
}
|
|
1650
|
-
|
|
1651
|
-
/*
|
|
1652
|
-
* Return every resource scope the rules have to be resolved against.
|
|
1653
|
-
*
|
|
1654
|
-
* "null" is the scope of everything not attached to a resource. Resources named
|
|
1655
|
-
* only by a RULE are included even when nothing is scheduled on them, because
|
|
1656
|
-
* CONTINUOUS_COVERAGE fires on absence: gating the scope list on presence would
|
|
1657
|
-
* mean a room with nothing in it could never be reported as uncovered, which is
|
|
1658
|
-
* precisely the case that rule exists to catch.
|
|
1659
|
-
*/
|
|
1660
|
-
|
|
1661
|
-
function getRuleScopeUniverse(
|
|
1662
|
-
snapshot: ScheduleEvaluationSnapshot,
|
|
1663
|
-
): Array<string | null> {
|
|
1664
|
-
const scopes = new Set<string | null>([null]);
|
|
1665
|
-
|
|
1666
|
-
for (const occurrence of snapshot.occurrences) {
|
|
1667
|
-
scopes.add(occurrence.resourceId);
|
|
1668
|
-
}
|
|
1669
|
-
|
|
1670
|
-
for (const demand of snapshot.demand) {
|
|
1671
|
-
scopes.add(demand.resourceId);
|
|
1672
|
-
}
|
|
1673
|
-
|
|
1674
|
-
for (const rule of snapshot.rules) {
|
|
1675
|
-
if (rule.resourceId) {
|
|
1676
|
-
scopes.add(rule.resourceId);
|
|
1677
|
-
}
|
|
1678
|
-
}
|
|
1679
|
-
|
|
1680
|
-
return Array.from(scopes);
|
|
1681
|
-
}
|
|
1682
|
-
|
|
1683
|
-
/**
|
|
1684
|
-
* Return the resources whose data counts as EVIDENCE for one rule, as opposed
|
|
1685
|
-
* to the resources the rule is responsible for reporting on.
|
|
1686
|
-
*
|
|
1687
|
-
* The two are the same for a rule that attributes its violation to a particular
|
|
1688
|
-
* resource — a capacity breach, a slot shortfall, a ratio — where being
|
|
1689
|
-
* overridden on one resource means simply not judging that resource.
|
|
1690
|
-
*
|
|
1691
|
-
* They are not the same for a rule that asks one question about the operation
|
|
1692
|
-
* as a whole: "is anybody working right now", "how many hours has this person
|
|
1693
|
-
* worked". There, narrowing the evidence to exclude a resource that carries its
|
|
1694
|
-
* own override does not narrow the question, it corrupts the answer — an
|
|
1695
|
-
* organization-wide coverage rule would report an empty building while somebody
|
|
1696
|
-
* stands in the overridden room, and an organization-wide hours cap would stop
|
|
1697
|
-
* counting the hours worked there. So an unscoped rule sees everything, and a
|
|
1698
|
-
* resource-scoped one sees exactly its own resource.
|
|
1699
|
-
*/
|
|
1700
|
-
|
|
1701
|
-
function getRuleEvidenceScopes(
|
|
1702
|
-
rule: ScheduleEvalRule,
|
|
1703
|
-
scopeUniverse: Array<string | null>,
|
|
1704
|
-
): Set<string | null> {
|
|
1705
|
-
return rule.resourceId
|
|
1706
|
-
? new Set<string | null>([rule.resourceId])
|
|
1707
|
-
: new Set(scopeUniverse);
|
|
1708
|
-
}
|
|
1709
|
-
|
|
1710
|
-
/**
|
|
1711
|
-
* Resolve the rules in force at one instant, each paired with the exact set of
|
|
1712
|
-
* resource scopes it is the winner for.
|
|
1713
|
-
*
|
|
1714
|
-
* This pairing is the whole point. Resolution already picked a per-resource
|
|
1715
|
-
* winner correctly, but evaluation then ran each winning rule against EVERY
|
|
1716
|
-
* resource — so an organization-wide rule kept judging a resource whose own
|
|
1717
|
-
* override had beaten it, and the override's narrower limit was reported
|
|
1718
|
-
* alongside the default it was supposed to replace. Handing each rule the
|
|
1719
|
-
* scopes it actually won makes "most specific wins" true at the point it is
|
|
1720
|
-
* used, not just at the point it is computed.
|
|
1721
|
-
*/
|
|
1722
|
-
|
|
1723
|
-
function getScopedEffectiveRules(
|
|
1724
|
-
scopeUniverse: Array<string | null>,
|
|
1725
|
-
at: Date,
|
|
1726
|
-
resolve: (resourceId: string | null, at: Date) => ScheduleEvalRule[],
|
|
1727
|
-
): Array<{ rule: ScheduleEvalRule; scopes: Set<string | null> }> {
|
|
1728
|
-
const byRuleId = new Map<
|
|
1729
|
-
string,
|
|
1730
|
-
{ rule: ScheduleEvalRule; scopes: Set<string | null> }
|
|
1731
|
-
>();
|
|
1732
|
-
|
|
1733
|
-
for (const resourceId of scopeUniverse) {
|
|
1734
|
-
for (const rule of resolve(resourceId, at)) {
|
|
1735
|
-
const existing = byRuleId.get(rule.id);
|
|
1736
|
-
|
|
1737
|
-
if (existing) {
|
|
1738
|
-
existing.scopes.add(resourceId);
|
|
1739
|
-
} else {
|
|
1740
|
-
byRuleId.set(rule.id, { rule, scopes: new Set([resourceId]) });
|
|
1741
|
-
}
|
|
1742
|
-
}
|
|
1743
|
-
}
|
|
1744
|
-
|
|
1745
|
-
return Array.from(byRuleId.values());
|
|
1746
|
-
}
|
|
1747
|
-
|
|
1748
|
-
export function evaluateScheduleWindow(
|
|
1749
|
-
snapshot: ScheduleEvaluationSnapshot,
|
|
1750
|
-
): ScheduleEvaluationResult {
|
|
1751
|
-
const timeZone =
|
|
1752
|
-
snapshot.timeZone && isValidTimeZone(snapshot.timeZone)
|
|
1753
|
-
? snapshot.timeZone
|
|
1754
|
-
: DEFAULT_TIMEZONE;
|
|
1755
|
-
const resourcesById = new Map(
|
|
1756
|
-
snapshot.resources.map((resource) => [resource.id, resource]),
|
|
1757
|
-
);
|
|
1758
|
-
const segments = buildSegments(snapshot);
|
|
1759
|
-
const violations: ScheduleEvalViolation[] = [];
|
|
1760
|
-
|
|
1761
|
-
const epochBoundaries = getRuleEpochBoundaries(snapshot.rules);
|
|
1762
|
-
const rulesByResourceEpoch = new Map<string, ScheduleEvalRule[]>();
|
|
1763
|
-
|
|
1764
|
-
/*
|
|
1765
|
-
* Resolve the effective rules for one resource at one instant, reusing the
|
|
1766
|
-
* answer for every other segment in the same rule epoch.
|
|
1767
|
-
*/
|
|
1768
|
-
|
|
1769
|
-
const getEffectiveRules = (
|
|
1770
|
-
resourceId: string | null,
|
|
1771
|
-
at: Date,
|
|
1772
|
-
): ScheduleEvalRule[] => {
|
|
1773
|
-
const cacheKey = `${resourceId ?? ''}|${getRuleEpochIndex(epochBoundaries, at)}`;
|
|
1774
|
-
const cached = rulesByResourceEpoch.get(cacheKey);
|
|
1775
|
-
|
|
1776
|
-
if (cached) {
|
|
1777
|
-
return cached;
|
|
1778
|
-
}
|
|
1779
|
-
|
|
1780
|
-
const resolved = selectEffectiveScheduleRules(
|
|
1781
|
-
snapshot.rules,
|
|
1782
|
-
resourceId,
|
|
1783
|
-
at,
|
|
1784
|
-
);
|
|
1785
|
-
rulesByResourceEpoch.set(cacheKey, resolved);
|
|
1786
|
-
|
|
1787
|
-
return resolved;
|
|
1788
|
-
};
|
|
1789
|
-
|
|
1790
|
-
const ruleScopeUniverse = getRuleScopeUniverse(snapshot);
|
|
1791
|
-
const scopedRulesByEpoch = new Map<
|
|
1792
|
-
number,
|
|
1793
|
-
Array<{ rule: ScheduleEvalRule; scopes: Set<string | null> }>
|
|
1794
|
-
>();
|
|
1795
|
-
|
|
1796
|
-
/*
|
|
1797
|
-
* Resolve the scoped rule set for one instant, reusing it across every
|
|
1798
|
-
* segment in the same rule epoch. Scope resolution depends on the instant
|
|
1799
|
-
* only through the effective-date predicates, so a day cut into two hundred
|
|
1800
|
-
* segments by shift boundaries resolves once rather than two hundred times.
|
|
1801
|
-
*/
|
|
1802
|
-
|
|
1803
|
-
const getScopedRules = (at: Date) => {
|
|
1804
|
-
const epoch = getRuleEpochIndex(epochBoundaries, at);
|
|
1805
|
-
const cached = scopedRulesByEpoch.get(epoch);
|
|
1806
|
-
|
|
1807
|
-
if (cached) {
|
|
1808
|
-
return cached;
|
|
1809
|
-
}
|
|
1810
|
-
|
|
1811
|
-
const resolved = getScopedEffectiveRules(
|
|
1812
|
-
ruleScopeUniverse,
|
|
1813
|
-
at,
|
|
1814
|
-
getEffectiveRules,
|
|
1815
|
-
);
|
|
1816
|
-
scopedRulesByEpoch.set(epoch, resolved);
|
|
1817
|
-
|
|
1818
|
-
return resolved;
|
|
1819
|
-
};
|
|
1820
|
-
|
|
1821
|
-
// Projected once per rule rather than per segment: the projection is a
|
|
1822
|
-
// property of the rule and the window, and a day of shifts can cut the
|
|
1823
|
-
// window into hundreds of segments
|
|
1824
|
-
const operatingIntervalsByRuleId = new Map<
|
|
1825
|
-
string,
|
|
1826
|
-
Array<{ start: Date; end: Date }>
|
|
1827
|
-
>();
|
|
1828
|
-
|
|
1829
|
-
const getOperatingIntervals = (
|
|
1830
|
-
rule: ScheduleEvalRule,
|
|
1831
|
-
): Array<{ start: Date; end: Date }> => {
|
|
1832
|
-
const cached = operatingIntervalsByRuleId.get(rule.id);
|
|
1833
|
-
|
|
1834
|
-
if (cached) {
|
|
1835
|
-
return cached;
|
|
1836
|
-
}
|
|
1837
|
-
|
|
1838
|
-
const intervals = getOperatingWindowIntervals(
|
|
1839
|
-
rule,
|
|
1840
|
-
timeZone,
|
|
1841
|
-
snapshot.windowStart,
|
|
1842
|
-
snapshot.windowEnd,
|
|
1843
|
-
);
|
|
1844
|
-
operatingIntervalsByRuleId.set(rule.id, intervals);
|
|
1845
|
-
|
|
1846
|
-
return intervals;
|
|
1847
|
-
};
|
|
1848
|
-
|
|
1849
|
-
for (const segment of segments) {
|
|
1850
|
-
for (const { rule, scopes } of getScopedRules(segment.start)) {
|
|
1851
|
-
switch (rule.kind) {
|
|
1852
|
-
case 'REQUIRED_COUNT':
|
|
1853
|
-
evaluateRequiredCount(rule, scopes, segment, violations);
|
|
1854
|
-
break;
|
|
1855
|
-
case 'DERIVED_COUNT':
|
|
1856
|
-
evaluateDerivedCount(rule, scopes, segment, violations);
|
|
1857
|
-
break;
|
|
1858
|
-
case 'RESOURCE_CAPACITY':
|
|
1859
|
-
evaluateResourceCapacity(
|
|
1860
|
-
rule,
|
|
1861
|
-
scopes,
|
|
1862
|
-
segment,
|
|
1863
|
-
resourcesById,
|
|
1864
|
-
violations,
|
|
1865
|
-
);
|
|
1866
|
-
break;
|
|
1867
|
-
case 'ELIGIBILITY_AT_TIME':
|
|
1868
|
-
evaluateEligibilityAtTime(rule, scopes, segment, violations);
|
|
1869
|
-
break;
|
|
1870
|
-
case 'CONTINUOUS_COVERAGE':
|
|
1871
|
-
evaluateContinuousCoverage(
|
|
1872
|
-
rule,
|
|
1873
|
-
getRuleEvidenceScopes(rule, ruleScopeUniverse),
|
|
1874
|
-
segment,
|
|
1875
|
-
getOperatingIntervals(rule),
|
|
1876
|
-
violations,
|
|
1877
|
-
);
|
|
1878
|
-
break;
|
|
1879
|
-
default:
|
|
1880
|
-
// Cross-segment kinds run once, below
|
|
1881
|
-
break;
|
|
1882
|
-
}
|
|
1883
|
-
}
|
|
1884
|
-
}
|
|
1885
|
-
|
|
1886
|
-
// The cross-segment kinds reason across the whole snapshot rather than
|
|
1887
|
-
// within one segment, so they are run once per RULE EPOCH — a stretch over
|
|
1888
|
-
// which the set of rules in force cannot change — and each emitted violation
|
|
1889
|
-
// is kept only if its own anchor instant falls inside the epoch that
|
|
1890
|
-
// produced it.
|
|
1891
|
-
//
|
|
1892
|
-
// Resolving them once against the window's left edge, as this did, collapsed
|
|
1893
|
-
// each rule's whole effective window to a single yes/no taken before the
|
|
1894
|
-
// breach it was meant to judge: a rule that came into force on Tuesday never
|
|
1895
|
-
// fired on Wednesday's breach, and a rule that expired on Tuesday still
|
|
1896
|
-
// blocked publication for it. The five segment-local kinds always got this
|
|
1897
|
-
// right because they resolve per segment; these two now agree with them.
|
|
1898
|
-
for (const epoch of getRuleEpochIntervals(
|
|
1899
|
-
epochBoundaries,
|
|
1900
|
-
snapshot.windowStart,
|
|
1901
|
-
snapshot.windowEnd,
|
|
1902
|
-
)) {
|
|
1903
|
-
const anchoredViolations: ScheduleEvalViolation[] = [];
|
|
1904
|
-
|
|
1905
|
-
for (const { rule, scopes } of getScopedRules(epoch.start)) {
|
|
1906
|
-
if (rule.kind === 'ACTOR_WINDOW_AGGREGATE') {
|
|
1907
|
-
evaluateActorWindowAggregate(
|
|
1908
|
-
rule,
|
|
1909
|
-
getRuleEvidenceScopes(rule, ruleScopeUniverse),
|
|
1910
|
-
snapshot,
|
|
1911
|
-
anchoredViolations,
|
|
1912
|
-
);
|
|
1913
|
-
} else if (rule.kind === 'EXCLUSION_WINDOW') {
|
|
1914
|
-
evaluateExclusionWindow(rule, scopes, snapshot, anchoredViolations);
|
|
1915
|
-
}
|
|
1916
|
-
}
|
|
1917
|
-
|
|
1918
|
-
// The epochs partition the window, so anchoring on the instant the breach
|
|
1919
|
-
// is reported at emits each violation exactly once
|
|
1920
|
-
for (const violation of anchoredViolations) {
|
|
1921
|
-
const anchor = violation.segmentEnd.getTime();
|
|
1922
|
-
|
|
1923
|
-
if (anchor > epoch.start.getTime() && anchor <= epoch.end.getTime()) {
|
|
1924
|
-
violations.push(violation);
|
|
1925
|
-
}
|
|
1926
|
-
}
|
|
1927
|
-
}
|
|
1928
|
-
|
|
1929
|
-
return {
|
|
1930
|
-
segmentCount: segments.length,
|
|
1931
|
-
violations: mergeAdjacentScheduleViolations(violations),
|
|
1932
|
-
};
|
|
1933
|
-
}
|
|
1934
|
-
|
|
1935
|
-
/**
|
|
1936
|
-
* Return a copy of one snapshot with an extra assignment on an occurrence.
|
|
1937
|
-
*
|
|
1938
|
-
* This is what makes "may this person take this shift" answerable without
|
|
1939
|
-
* writing anything: load the window once, then re-evaluate it in memory per
|
|
1940
|
-
* candidate and keep the ones who introduce no new blocking breach. Offering a
|
|
1941
|
-
* shift to somebody who would break the schedule by accepting it is the
|
|
1942
|
-
* failure this avoids — and it has to be answered before the shift is shown,
|
|
1943
|
-
* not after they tap it.
|
|
1944
|
-
*/
|
|
1945
|
-
|
|
1946
|
-
export function withSimulatedScheduleAssignment(
|
|
1947
|
-
snapshot: ScheduleEvaluationSnapshot,
|
|
1948
|
-
occurrenceId: string,
|
|
1949
|
-
assignment: ScheduleEvalAssignment,
|
|
1950
|
-
): ScheduleEvaluationSnapshot {
|
|
1951
|
-
const occurrences = snapshot.occurrences.map((occurrence) =>
|
|
1952
|
-
occurrence.id === occurrenceId
|
|
1953
|
-
? { ...occurrence, assignments: [...occurrence.assignments, assignment] }
|
|
1954
|
-
: occurrence,
|
|
1955
|
-
);
|
|
1956
|
-
|
|
1957
|
-
// "actorHistory" is deliberately untouched. The rolling per-actor evaluator
|
|
1958
|
-
// already walks snapshot.occurrences and folds every assignment it finds
|
|
1959
|
-
// into the actor's timeline, so mirroring the simulated one into the
|
|
1960
|
-
// history would count the same shift twice — and a "max 1 shift per week"
|
|
1961
|
-
// rule would then reject the very first shift offered to anybody.
|
|
1962
|
-
return { ...snapshot, occurrences };
|
|
1963
|
-
}
|
|
1964
|
-
|
|
1965
|
-
/**
|
|
1966
|
-
* Return a copy of one snapshot with an assignment removed, for asking what a
|
|
1967
|
-
* schedule would look like if somebody dropped a shift.
|
|
1968
|
-
*/
|
|
1969
|
-
|
|
1970
|
-
export function withoutScheduleAssignment(
|
|
1971
|
-
snapshot: ScheduleEvaluationSnapshot,
|
|
1972
|
-
assignmentId: string,
|
|
1973
|
-
): ScheduleEvaluationSnapshot {
|
|
1974
|
-
return {
|
|
1975
|
-
...snapshot,
|
|
1976
|
-
occurrences: snapshot.occurrences.map((occurrence) => ({
|
|
1977
|
-
...occurrence,
|
|
1978
|
-
assignments: occurrence.assignments.filter(
|
|
1979
|
-
(assignment) => assignment.id !== assignmentId,
|
|
1980
|
-
),
|
|
1981
|
-
})),
|
|
1982
|
-
};
|
|
1983
|
-
}
|
|
1984
|
-
|
|
1985
|
-
/**
|
|
1986
|
-
* Check whether a set of violations blocks publication. Only BLOCK-severity
|
|
1987
|
-
* breaches do; WARN breaches are recorded and acknowledged.
|
|
1988
|
-
*/
|
|
1989
|
-
|
|
1990
|
-
export function getBlockingScheduleViolations(
|
|
1991
|
-
violations: ScheduleEvalViolation[],
|
|
1992
|
-
): ScheduleEvalViolation[] {
|
|
1993
|
-
return violations.filter((violation) => violation.severity === 'BLOCK');
|
|
1994
|
-
}
|