@jsb188/schedule 1.1.11 → 1.1.13

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 (62) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +34 -14
  3. package/src/constants/schedule.ts +710 -306
  4. package/src/modules/Gantt.helpers.ts +11 -30
  5. package/src/modules/Gantt.tsx +46 -181
  6. package/src/types/schedule.d.ts +1827 -456
  7. package/src/ui/ProjectFormUI.tsx +8 -31
  8. package/src/ui/ScheduleSettingsUI.tsx +21 -23
  9. package/src/utils/autofill.ts +469 -0
  10. package/src/utils/availability.ts +167 -0
  11. package/src/utils/candidates.ts +447 -0
  12. package/src/utils/coverage.helpers.ts +509 -554
  13. package/src/utils/coverage.ts +1121 -526
  14. package/src/utils/cpm.helpers.ts +27 -29
  15. package/src/utils/cpm.ts +53 -41
  16. package/src/utils/cpmLeveling.helpers.ts +89 -16
  17. package/src/utils/cpmLeveling.ts +28 -26
  18. package/src/utils/cycle.ts +325 -0
  19. package/src/utils/demand.ts +239 -0
  20. package/src/utils/eligibility.ts +553 -400
  21. package/src/utils/ids.ts +47 -0
  22. package/src/utils/laborRules.ts +740 -0
  23. package/src/utils/localTime.ts +312 -0
  24. package/src/utils/offer.ts +300 -0
  25. package/src/utils/planCsv.ts +73 -19
  26. package/src/utils/predicate.ts +111 -0
  27. package/src/utils/request.ts +212 -114
  28. package/src/utils/resource.ts +412 -112
  29. package/src/utils/rule.ts +697 -163
  30. package/src/utils/rulePresets.ts +116 -0
  31. package/src/utils/run.ts +0 -8
  32. package/src/utils/scheduleText.ts +4074 -0
  33. package/src/utils/shiftChange.ts +279 -0
  34. package/src/utils/standing.ts +730 -0
  35. package/src/utils/template.ts +619 -0
  36. package/src/utils/violation.ts +184 -0
  37. package/src/utils/workTime.ts +341 -120
  38. package/src/utils/defaults.ts +0 -8
  39. package/src/utils/recurrence.ts +0 -616
  40. package/src/utils/series.ts +0 -161
  41. package/src/utils/slot.ts +0 -208
  42. package/tests/coverage.fixtures.ts +0 -111
  43. package/tests/coverage.test.ts +0 -503
  44. package/tests/cpm.bench.test.ts +0 -154
  45. package/tests/cpm.test.ts +0 -354
  46. package/tests/cpmCorrectness.test.ts +0 -327
  47. package/tests/cpmLeveling.test.ts +0 -471
  48. package/tests/eligibility.test.ts +0 -320
  49. package/tests/gantt-geometry.test.ts +0 -367
  50. package/tests/gantt-histogram.test.ts +0 -78
  51. package/tests/gantt-keyboard.test.ts +0 -69
  52. package/tests/helpers/cpmFixtures.ts +0 -101
  53. package/tests/projectInputs.test.ts +0 -165
  54. package/tests/recurrence.test.ts +0 -68
  55. package/tests/request.test.ts +0 -99
  56. package/tests/resource.test.ts +0 -95
  57. package/tests/rule.test.ts +0 -98
  58. package/tests/series.test.ts +0 -120
  59. package/tests/workTime.test.ts +0 -1007
  60. package/tests/workTimeContracts.test.ts +0 -111
  61. package/tsconfig.json +0 -13
  62. package/vitest.config.ts +0 -8
package/src/utils/rule.ts CHANGED
@@ -1,216 +1,750 @@
1
1
  import {
2
- SCHEDULE_ACTOR_WINDOW_MAX_DAYS,
3
2
  SCHEDULE_IMPLICIT_RULE_KINDS,
3
+ SCHEDULE_MAX_HOURS_PERIOD_ENUMS,
4
+ SCHEDULE_RATIO_MODE_ENUMS,
4
5
  SCHEDULE_RULE_KIND_ENUMS,
6
+ SCHEDULE_RULE_MAX_DAYS,
7
+ SCHEDULE_RULE_MAX_GROUP_SIZE,
5
8
  SCHEDULE_RULE_MAX_MIN_ADULTS,
9
+ SCHEDULE_RULE_MAX_MIN_COUNT,
10
+ SCHEDULE_RULE_MAX_MINUTES,
6
11
  SCHEDULE_RULE_MAX_RATIO,
12
+ SCHEDULE_RULE_MAX_REST_MINUTES,
13
+ SCHEDULE_RULE_MAX_ROLE_IDS,
14
+ SCHEDULE_RULE_MAX_STAFFING_WINDOWS,
15
+ SCHEDULE_RULE_SEVERITY_ENUMS,
7
16
  SCHEDULE_RULE_SUBJECT_BY_KIND,
17
+ SCHEDULE_SHIFT_MAX_DURATION_MINUTES,
18
+ SCHEDULE_SINGLETON_RULE_KINDS,
8
19
  } from '../constants/schedule.ts';
9
20
  import type {
10
21
  CoverageDiagnosticObj,
11
22
  CoverageResourceInput,
23
+ CoverageRoleInput,
12
24
  CoverageRuleInput,
13
- ScheduleActorWindowConfigObj,
25
+ ScheduleEffectiveRule,
26
+ ScheduleEffectiveRuleIndex,
27
+ ScheduleMaxHoursConfigObj,
28
+ SchedulePersonRuleWindow,
29
+ SchedulePredicateObj,
30
+ ScheduleRuleConfigByKind,
14
31
  ScheduleRuleConfigObj,
15
32
  ScheduleRuleKindEnum,
16
- ScheduleRuleSeverityEnum,
33
+ ScheduleStaffingRequirementConfigObj,
34
+ ScheduleWeeklyWindowObj,
17
35
  } from '../types/schedule.d.ts';
36
+ import { compareScheduleIds, normalizeScheduleIdList } from './ids.ts';
37
+ import { normalizeScheduleClockTime } from './localTime.ts';
38
+ import { validateSchedulePredicate } from './predicate.ts';
18
39
  import { getScheduleKey, isScheduleRecord } from './resource.ts';
19
- import { validateScheduleSlotPredicate } from './slot.ts';
20
40
 
21
- export interface EffectiveRuleIndex {
22
- byKind: Map<
23
- ScheduleRuleKindEnum,
24
- {
25
- fallback: CoverageRuleInput | null;
26
- bySubject: Map<string, CoverageRuleInput>;
27
- }
28
- >;
29
- }
30
- export interface EffectiveRule {
31
- rule: CoverageRuleInput | null;
32
- ruleId: string | null;
33
- severity: ScheduleRuleSeverityEnum;
34
- }
41
+ /**
42
+ * Rule configuration and resolution.
43
+ *
44
+ * - Every kind has a closed config: unknown keys are rejected and the output
45
+ * is normalized (sorted keys and lists, 'HH:mm' times, nulls for absent
46
+ * optional fields), so equal rules store equal JSON.
47
+ * - Scope ladder, per (kind, key): organization (calendarId null) < calendar
48
+ * < resource. A more specific rule with the same key replaces the less
49
+ * specific one; different keys all apply. Singleton kinds
50
+ * (SCHEDULE_SINGLETON_RULE_KINDS) group under one key per kind. A key never
51
+ * replaces a rule of another kind.
52
+ * - ROOM_CAPACITY and ELIGIBILITY apply with no row (the implicit default).
53
+ */
54
+
55
+ type RuleConfigResult = { config?: ScheduleRuleConfigObj; error?: string };
56
+ type RuleGroup = {
57
+ fallback: ScheduleEffectiveRule | null;
58
+ bySubject: Map<string, ScheduleEffectiveRule>;
59
+ };
60
+
61
+ const FILE_CONSTANTS = {
62
+ configKeys: {
63
+ STAFFING_REQUIREMENT: [
64
+ 'roleIdsAny',
65
+ 'windows',
66
+ 'minCount',
67
+ 'locationResourceId',
68
+ ],
69
+ RATIO: ['ratios', 'mode', 'maxGroupSize', 'predicate'],
70
+ ROOM_CAPACITY: [],
71
+ OPERATING_HOURS: ['minAdults', 'predicate'],
72
+ ELIGIBILITY: ['unavailable'],
73
+ MAX_HOURS: ['period', 'days', 'maxMinutes'],
74
+ MIN_REST: ['minMinutes'],
75
+ MAX_CONSECUTIVE_DAYS: ['days'],
76
+ SHIFT_LENGTH: ['minMinutes', 'maxMinutes'],
77
+ NOTICE_PERIOD: ['days'],
78
+ } satisfies Record<ScheduleRuleKindEnum, string[]>,
79
+ dayMinutes: 1440,
80
+ };
35
81
 
36
- /* Check a bounded integer without coercing configuration strings or booleans. */
37
- function isIntegerWithin(value: unknown, maximum: number): value is number {
82
+ /*
83
+ * Check that a value is an integer within [minimum, maximum], without
84
+ * coercing strings or booleans.
85
+ */
86
+ function isIntegerInRange(
87
+ value: unknown,
88
+ minimum: number,
89
+ maximum: number,
90
+ ): value is number {
38
91
  return (
39
92
  typeof value === 'number' &&
40
93
  Number.isInteger(value) &&
41
- value > 0 &&
94
+ value >= minimum &&
42
95
  value <= maximum
43
96
  );
44
97
  }
45
98
 
46
- /* Reject unknown fields and normalize the configuration appropriate to one rule kind. */
47
- export function validateScheduleRuleConfig(
48
- kind: ScheduleRuleKindEnum,
49
- input: unknown,
50
- ): { config?: ScheduleRuleConfigObj; error?: string } {
51
- const raw = input ?? {};
52
- if (!isScheduleRecord(raw))
53
- return { error: 'Rule configuration must be an object.' };
54
- if (!SCHEDULE_RULE_KIND_ENUMS.includes(kind))
55
- return { error: `Unknown rule kind: ${kind}.` };
56
- const allowed =
57
- kind === 'DERIVED_COUNT'
58
- ? ['ratios', 'predicate']
59
- : kind === 'OPERATING_HOURS'
60
- ? ['minAdults', 'predicate']
61
- : kind === 'ACTOR_WINDOW_AGGREGATE'
62
- ? ['windowDays', 'maxMinutes', 'minRestMinutes']
63
- : [];
64
- const unknown = Object.keys(raw).find((key) => !allowed.includes(key));
65
- if (unknown)
66
- return { error: `Unknown ${kind} configuration key: ${unknown}.` };
67
- if (kind === 'DERIVED_COUNT' || kind === 'OPERATING_HOURS') {
68
- const { predicate, error } = validateScheduleSlotPredicate(raw.predicate);
69
- if (error) return { error };
70
- if (kind === 'OPERATING_HOURS')
71
- return isIntegerWithin(raw.minAdults, SCHEDULE_RULE_MAX_MIN_ADULTS)
72
- ? { config: { minAdults: raw.minAdults, predicate: predicate ?? null } }
73
- : { error: 'Operating hours require minAdults between 1 and 99.' };
74
- if (!isScheduleRecord(raw.ratios) || !Object.keys(raw.ratios).length)
75
- return { error: 'Derived count requires at least one ratio.' };
76
- const entries: Array<[string, number]> = [];
77
- const seen = new Set<string>();
78
- for (const [rawKey, value] of Object.entries(raw.ratios)) {
79
- const key = getScheduleKey(rawKey);
80
- if (
81
- !key ||
82
- seen.has(key) ||
83
- !isIntegerWithin(value, SCHEDULE_RULE_MAX_RATIO)
84
- )
85
- return { error: `Invalid or duplicate ratio: ${rawKey}.` };
86
- seen.add(key);
87
- entries.push([key, value]);
88
- }
99
+ /*
100
+ * Normalize one optional id (a staffing rule's location): null when absent,
101
+ * undefined when present but invalid.
102
+ */
103
+ function normalizeOptionalScheduleId(
104
+ value: unknown,
105
+ ): string | null | undefined {
106
+ if (value === undefined || value === null) return null;
107
+ return normalizeScheduleIdList([value], 1)?.[0];
108
+ }
109
+
110
+ /*
111
+ * Validate a record of age-group key -> integer in [1, maximum]: keys are
112
+ * trimmed and must stay unique. Returns the entries sorted by key, or an
113
+ * error naming the field.
114
+ */
115
+ function validateScheduleKeyedIntegers(
116
+ value: unknown,
117
+ maximum: number,
118
+ field: string,
119
+ ): { entries?: Record<string, number>; error?: string } {
120
+ if (!isScheduleRecord(value))
121
+ return { error: `"${field}" must map age-group keys to whole numbers.` };
122
+ const entries: Array<[string, number]> = [];
123
+ const seen = new Set<string>();
124
+ for (const [rawKey, count] of Object.entries(value)) {
125
+ const key = getScheduleKey(rawKey);
126
+ if (!key || seen.has(key) || !isIntegerInRange(count, 1, maximum))
127
+ return {
128
+ error: `"${field}" has an invalid or duplicate entry "${rawKey}" (whole numbers 1 to ${maximum}).`,
129
+ };
130
+ seen.add(key);
131
+ entries.push([key, count]);
132
+ }
133
+ return {
134
+ entries: Object.fromEntries(
135
+ entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
136
+ ),
137
+ };
138
+ }
139
+
140
+ /*
141
+ * Validate one weekly staffing window {weekday, start, end}; times come back
142
+ * as 'HH:mm'. An end at or before the start ends the next day.
143
+ */
144
+ function validateStaffingWindow(input: unknown): {
145
+ window?: ScheduleWeeklyWindowObj;
146
+ error?: string;
147
+ } {
148
+ if (
149
+ !isScheduleRecord(input) ||
150
+ Object.keys(input).some((key) => !['weekday', 'start', 'end'].includes(key))
151
+ )
152
+ return { error: 'A staffing window must be {weekday, start, end}.' };
153
+ const start =
154
+ typeof input.start === 'string'
155
+ ? normalizeScheduleClockTime(input.start)
156
+ : null;
157
+ const end =
158
+ typeof input.end === 'string'
159
+ ? normalizeScheduleClockTime(input.end)
160
+ : null;
161
+ if (!isIntegerInRange(input.weekday, 0, 6) || !start || !end)
89
162
  return {
90
- config: {
91
- ratios: Object.fromEntries(
92
- entries.sort(([a], [b]) => a.localeCompare(b)),
93
- ),
94
- predicate: predicate ?? null,
95
- },
163
+ error:
164
+ 'A staffing window needs a weekday 0 to 6 and start and end times as HH:mm.',
165
+ };
166
+ return { window: { weekday: input.weekday, start, end } };
167
+ }
168
+
169
+ /*
170
+ * Compare two staffing windows by weekday, then start, then end.
171
+ */
172
+ function compareStaffingWindows(
173
+ a: ScheduleWeeklyWindowObj,
174
+ b: ScheduleWeeklyWindowObj,
175
+ ): number {
176
+ return (
177
+ a.weekday - b.weekday ||
178
+ (a.start < b.start ? -1 : a.start > b.start ? 1 : 0) ||
179
+ (a.end < b.end ? -1 : a.end > b.end ? 1 : 0)
180
+ );
181
+ }
182
+
183
+ /*
184
+ * Validate a STAFFING_REQUIREMENT config: roles (at least one), weekly
185
+ * windows (sorted, deduped), the minimum count and an optional location.
186
+ */
187
+ function validateStaffingRequirementConfig(
188
+ raw: Record<string, unknown>,
189
+ ): RuleConfigResult {
190
+ const roleIdsAny = normalizeScheduleIdList(
191
+ raw.roleIdsAny,
192
+ SCHEDULE_RULE_MAX_ROLE_IDS,
193
+ );
194
+ if (!roleIdsAny?.length)
195
+ return {
196
+ error: `Staffing requires "roleIdsAny": 1 to ${SCHEDULE_RULE_MAX_ROLE_IDS} role ids.`,
197
+ };
198
+ if (
199
+ !Array.isArray(raw.windows) ||
200
+ !raw.windows.length ||
201
+ raw.windows.length > SCHEDULE_RULE_MAX_STAFFING_WINDOWS
202
+ )
203
+ return {
204
+ error: `Staffing requires "windows": 1 to ${SCHEDULE_RULE_MAX_STAFFING_WINDOWS} weekly windows.`,
205
+ };
206
+ const windows = new Map<string, ScheduleWeeklyWindowObj>();
207
+ for (const item of raw.windows) {
208
+ const { window, error } = validateStaffingWindow(item);
209
+ if (!window) return { error };
210
+ windows.set(`${window.weekday}|${window.start}|${window.end}`, window);
211
+ }
212
+ if (!isIntegerInRange(raw.minCount, 1, SCHEDULE_RULE_MAX_MIN_COUNT))
213
+ return {
214
+ error: `Staffing requires "minCount" between 1 and ${SCHEDULE_RULE_MAX_MIN_COUNT}.`,
215
+ };
216
+ const locationResourceId = normalizeOptionalScheduleId(
217
+ raw.locationResourceId,
218
+ );
219
+ if (locationResourceId === undefined)
220
+ return { error: 'Staffing "locationResourceId" must be an id or null.' };
221
+ return {
222
+ config: {
223
+ roleIdsAny,
224
+ windows: [...windows.values()].sort(compareStaffingWindows),
225
+ minCount: raw.minCount,
226
+ locationResourceId,
227
+ },
228
+ };
229
+ }
230
+
231
+ /*
232
+ * Validate a RATIO config: ratios per age group, the mode (default BLENDED),
233
+ * optional maximum group sizes and the adult predicate.
234
+ */
235
+ function validateRatioConfig(raw: Record<string, unknown>): RuleConfigResult {
236
+ const ratios = validateScheduleKeyedIntegers(
237
+ raw.ratios,
238
+ SCHEDULE_RULE_MAX_RATIO,
239
+ 'ratios',
240
+ );
241
+ if (!ratios.entries) return { error: ratios.error };
242
+ if (!Object.keys(ratios.entries).length)
243
+ return { error: 'A ratio rule requires at least one ratio.' };
244
+ const mode = raw.mode ?? 'BLENDED';
245
+ if (!SCHEDULE_RATIO_MODE_ENUMS.includes(mode as never))
246
+ return {
247
+ error: `Ratio "mode" must be one of ${SCHEDULE_RATIO_MODE_ENUMS.join(', ')}.`,
96
248
  };
249
+ let maxGroupSize: Record<string, number> | null = null;
250
+ if (raw.maxGroupSize != null) {
251
+ const sizes = validateScheduleKeyedIntegers(
252
+ raw.maxGroupSize,
253
+ SCHEDULE_RULE_MAX_GROUP_SIZE,
254
+ 'maxGroupSize',
255
+ );
256
+ if (!sizes.entries) return { error: sizes.error };
257
+ maxGroupSize = Object.keys(sizes.entries).length ? sizes.entries : null;
97
258
  }
98
- if (kind === 'ACTOR_WINDOW_AGGREGATE') {
99
- const hasHours = raw.windowDays != null || raw.maxMinutes != null;
100
- const hasRest = raw.minRestMinutes != null;
259
+ const { predicate, error } = validateSchedulePredicate(raw.predicate);
260
+ if (error) return { error };
261
+ return {
262
+ config: {
263
+ ratios: ratios.entries,
264
+ mode: mode as ScheduleRuleConfigByKind['RATIO']['mode'],
265
+ maxGroupSize,
266
+ predicate: predicate ?? null,
267
+ },
268
+ };
269
+ }
270
+
271
+ /*
272
+ * Validate an OPERATING_HOURS config: the minimum adults and who counts.
273
+ */
274
+ function validateOperatingHoursConfig(
275
+ raw: Record<string, unknown>,
276
+ ): RuleConfigResult {
277
+ if (!isIntegerInRange(raw.minAdults, 1, SCHEDULE_RULE_MAX_MIN_ADULTS))
278
+ return {
279
+ error: `Operating hours require "minAdults" between 1 and ${SCHEDULE_RULE_MAX_MIN_ADULTS}.`,
280
+ };
281
+ const { predicate, error } = validateSchedulePredicate(raw.predicate);
282
+ if (error) return { error };
283
+ return { config: { minAdults: raw.minAdults, predicate: predicate ?? null } };
284
+ }
285
+
286
+ /*
287
+ * Validate an ELIGIBILITY config: only the UNAVAILABLE severity is
288
+ * configurable (default WARN); hard checks are always BLOCK.
289
+ */
290
+ function validateEligibilityConfig(
291
+ raw: Record<string, unknown>,
292
+ ): RuleConfigResult {
293
+ const unavailable = raw.unavailable ?? 'WARN';
294
+ if (!SCHEDULE_RULE_SEVERITY_ENUMS.includes(unavailable as never))
295
+ return { error: 'Eligibility "unavailable" must be WARN or BLOCK.' };
296
+ return {
297
+ config: {
298
+ unavailable:
299
+ unavailable as ScheduleRuleConfigByKind['ELIGIBILITY']['unavailable'],
300
+ },
301
+ };
302
+ }
303
+
304
+ /*
305
+ * Validate a MAX_HOURS config: the period, its days (ROLLING_DAYS only) and
306
+ * the most worked minutes per period.
307
+ */
308
+ function validateMaxHoursConfig(
309
+ raw: Record<string, unknown>,
310
+ ): RuleConfigResult {
311
+ if (!SCHEDULE_MAX_HOURS_PERIOD_ENUMS.includes(raw.period as never))
312
+ return {
313
+ error: `Max hours "period" must be one of ${SCHEDULE_MAX_HOURS_PERIOD_ENUMS.join(', ')}.`,
314
+ };
315
+ const period = raw.period as ScheduleMaxHoursConfigObj['period'];
316
+ if (
317
+ period === 'ROLLING_DAYS'
318
+ ? !isIntegerInRange(raw.days, 1, SCHEDULE_RULE_MAX_DAYS)
319
+ : raw.days != null
320
+ )
321
+ return {
322
+ error: `Max hours "days" is required for ROLLING_DAYS (1 to ${SCHEDULE_RULE_MAX_DAYS}) and not allowed otherwise.`,
323
+ };
324
+ if (!isIntegerInRange(raw.maxMinutes, 1, SCHEDULE_RULE_MAX_MINUTES))
325
+ return {
326
+ error: `Max hours "maxMinutes" must be between 1 and ${SCHEDULE_RULE_MAX_MINUTES}.`,
327
+ };
328
+ return {
329
+ config: {
330
+ period,
331
+ days: period === 'ROLLING_DAYS' ? (raw.days as number) : null,
332
+ maxMinutes: raw.maxMinutes,
333
+ },
334
+ };
335
+ }
336
+
337
+ /*
338
+ * Validate a MIN_REST config: the least minutes between consecutive seats.
339
+ */
340
+ function validateMinRestConfig(raw: Record<string, unknown>): RuleConfigResult {
341
+ return isIntegerInRange(raw.minMinutes, 1, SCHEDULE_RULE_MAX_REST_MINUTES)
342
+ ? { config: { minMinutes: raw.minMinutes } }
343
+ : {
344
+ error: `Minimum rest "minMinutes" must be between 1 and ${SCHEDULE_RULE_MAX_REST_MINUTES}.`,
345
+ };
346
+ }
347
+
348
+ /*
349
+ * Validate a config whose only field is a day count 1..SCHEDULE_RULE_MAX_DAYS
350
+ * (MAX_CONSECUTIVE_DAYS, NOTICE_PERIOD).
351
+ */
352
+ function validateDaysConfig(
353
+ raw: Record<string, unknown>,
354
+ label: string,
355
+ ): RuleConfigResult {
356
+ return isIntegerInRange(raw.days, 1, SCHEDULE_RULE_MAX_DAYS)
357
+ ? { config: { days: raw.days } }
358
+ : {
359
+ error: `${label} "days" must be between 1 and ${SCHEDULE_RULE_MAX_DAYS}.`,
360
+ };
361
+ }
362
+
363
+ /*
364
+ * Validate a SHIFT_LENGTH config: at least one of minMinutes / maxMinutes
365
+ * (1..SCHEDULE_SHIFT_MAX_DURATION_MINUTES), min at most max.
366
+ */
367
+ function validateShiftLengthConfig(
368
+ raw: Record<string, unknown>,
369
+ ): RuleConfigResult {
370
+ const bounds: Array<'minMinutes' | 'maxMinutes'> = [
371
+ 'minMinutes',
372
+ 'maxMinutes',
373
+ ];
374
+ for (const field of bounds)
101
375
  if (
102
- (!hasHours && !hasRest) ||
103
- (hasHours &&
104
- (!isIntegerWithin(raw.windowDays, SCHEDULE_ACTOR_WINDOW_MAX_DAYS) ||
105
- !isIntegerWithin(raw.maxMinutes, 44_640))) ||
106
- (hasRest && !isIntegerWithin(raw.minRestMinutes, 1440))
376
+ raw[field] != null &&
377
+ !isIntegerInRange(raw[field], 1, SCHEDULE_SHIFT_MAX_DURATION_MINUTES)
107
378
  )
108
379
  return {
109
- error:
110
- 'Actor limits require windowDays with maxMinutes and/or minRestMinutes in their permitted ranges.',
380
+ error: `Shift length "${field}" must be between 1 and ${SCHEDULE_SHIFT_MAX_DURATION_MINUTES}.`,
111
381
  };
382
+ const minMinutes = (raw.minMinutes as number | undefined) ?? null;
383
+ const maxMinutes = (raw.maxMinutes as number | undefined) ?? null;
384
+ if (minMinutes === null && maxMinutes === null)
385
+ return { error: 'Shift length needs "minMinutes" or "maxMinutes".' };
386
+ if (minMinutes !== null && maxMinutes !== null && minMinutes > maxMinutes)
112
387
  return {
113
- config: {
114
- windowDays: (raw.windowDays as number) ?? null,
115
- maxMinutes: (raw.maxMinutes as number) ?? null,
116
- minRestMinutes: (raw.minRestMinutes as number) ?? null,
117
- },
388
+ error: 'Shift length "minMinutes" cannot exceed "maxMinutes".',
118
389
  };
390
+ return { config: { minMinutes, maxMinutes } };
391
+ }
392
+
393
+ /*
394
+ * Run the validator of one kind on a config record whose keys are known.
395
+ */
396
+ function validateRuleConfigByKind(
397
+ kind: ScheduleRuleKindEnum,
398
+ raw: Record<string, unknown>,
399
+ ): RuleConfigResult {
400
+ switch (kind) {
401
+ case 'STAFFING_REQUIREMENT':
402
+ return validateStaffingRequirementConfig(raw);
403
+ case 'RATIO':
404
+ return validateRatioConfig(raw);
405
+ case 'ROOM_CAPACITY':
406
+ return { config: {} };
407
+ case 'OPERATING_HOURS':
408
+ return validateOperatingHoursConfig(raw);
409
+ case 'ELIGIBILITY':
410
+ return validateEligibilityConfig(raw);
411
+ case 'MAX_HOURS':
412
+ return validateMaxHoursConfig(raw);
413
+ case 'MIN_REST':
414
+ return validateMinRestConfig(raw);
415
+ case 'MAX_CONSECUTIVE_DAYS':
416
+ return validateDaysConfig(raw, 'Max consecutive days');
417
+ case 'SHIFT_LENGTH':
418
+ return validateShiftLengthConfig(raw);
419
+ case 'NOTICE_PERIOD':
420
+ return validateDaysConfig(raw, 'Notice period');
119
421
  }
120
- return { config: {} };
121
422
  }
122
423
 
123
- /* Compare identifiers numerically when both are integer ids, then lexically. */
124
- export function compareScheduleIds(a: string, b: string): number {
125
- if (/^\d+$/.test(a) && /^\d+$/.test(b))
126
- return BigInt(a) < BigInt(b) ? -1 : BigInt(a) > BigInt(b) ? 1 : 0;
127
- return a < b ? -1 : a > b ? 1 : 0;
424
+ /*
425
+ * Validate and normalize one rule's config for its kind. Unknown kinds and
426
+ * unknown config keys are rejected; a null or absent config reads as {}.
427
+ * Never throws: the error is an English sentence.
428
+ */
429
+ export function validateScheduleRuleConfig<K extends ScheduleRuleKindEnum>(
430
+ kind: K,
431
+ input: unknown,
432
+ ): { config?: ScheduleRuleConfigByKind[K]; error?: string } {
433
+ if (!SCHEDULE_RULE_KIND_ENUMS.includes(kind))
434
+ return { error: `Unknown rule kind: ${String(kind)}.` };
435
+ const raw = input ?? {};
436
+ if (!isScheduleRecord(raw))
437
+ return { error: 'Rule configuration must be an object.' };
438
+ const allowed: readonly string[] = FILE_CONSTANTS.configKeys[kind];
439
+ const unknown = Object.keys(raw).find((key) => !allowed.includes(key));
440
+ if (unknown)
441
+ return { error: `Unknown ${kind} configuration key: ${unknown}.` };
442
+ return validateRuleConfigByKind(kind, raw) as {
443
+ config?: ScheduleRuleConfigByKind[K];
444
+ error?: string;
445
+ };
446
+ }
447
+
448
+ /*
449
+ * Build one diagnostic for a rule that cannot be indexed.
450
+ */
451
+ function getRuleDiagnostic(
452
+ rule: CoverageRuleInput,
453
+ code: CoverageDiagnosticObj['code'],
454
+ detail: Record<string, unknown> = {},
455
+ resourceId: string | null = rule.resourceId,
456
+ ): CoverageDiagnosticObj {
457
+ return { code, ruleId: rule.id, resourceId, shiftId: null, detail };
458
+ }
459
+
460
+ /*
461
+ * List the role ids a validated config names: a staffing rule's roleIdsAny
462
+ * and a predicate's roleIdsAny.
463
+ */
464
+ function getRuleConfigRoleIds(config: ScheduleRuleConfigObj): string[] {
465
+ const staffing = (config as Partial<ScheduleStaffingRequirementConfigObj>)
466
+ .roleIdsAny;
467
+ const predicate = (config as { predicate?: SchedulePredicateObj | null })
468
+ .predicate;
469
+ return [...new Set([...(staffing ?? []), ...(predicate?.roleIdsAny ?? [])])];
128
470
  }
129
471
 
130
- /* Resolve one winner per subject using org, calendar and resource scope precedence. */
472
+ /*
473
+ * Check a rule's subject (rule.resourceId, and a staffing rule's location)
474
+ * against the resources and the kind's subject; return the diagnostics that
475
+ * keep it out of the index ([] when it is fine).
476
+ */
477
+ function getRuleSubjectDiagnostics(
478
+ rule: CoverageRuleInput,
479
+ config: ScheduleRuleConfigObj,
480
+ resourcesById: ReadonlyMap<
481
+ string,
482
+ Pick<CoverageResourceInput, 'id' | 'kind'>
483
+ >,
484
+ ): CoverageDiagnosticObj[] {
485
+ const subject = SCHEDULE_RULE_SUBJECT_BY_KIND[rule.kind];
486
+ if (rule.resourceId !== null) {
487
+ if (subject === 'NONE')
488
+ return [getRuleDiagnostic(rule, 'RULE_SUBJECT_KIND_MISMATCH')];
489
+ const resource = resourcesById.get(rule.resourceId);
490
+ if (!resource) return [getRuleDiagnostic(rule, 'UNKNOWN_RESOURCE')];
491
+ if (resource.kind !== (subject === 'ROOM' ? 'SPACE' : 'PERSON'))
492
+ return [getRuleDiagnostic(rule, 'RULE_SUBJECT_KIND_MISMATCH')];
493
+ }
494
+ const locationId = (config as Partial<ScheduleStaffingRequirementConfigObj>)
495
+ .locationResourceId;
496
+ if (rule.kind !== 'STAFFING_REQUIREMENT' || !locationId) return [];
497
+ const location = resourcesById.get(locationId);
498
+ const detail = { field: 'locationResourceId' };
499
+ if (!location)
500
+ return [getRuleDiagnostic(rule, 'UNKNOWN_RESOURCE', detail, locationId)];
501
+ return location.kind === 'SPACE'
502
+ ? []
503
+ : [
504
+ getRuleDiagnostic(
505
+ rule,
506
+ 'RULE_SUBJECT_KIND_MISMATCH',
507
+ detail,
508
+ locationId,
509
+ ),
510
+ ];
511
+ }
512
+
513
+ /*
514
+ * Return the diagnostics that keep a rule out of the index: invalid config,
515
+ * a wrong or missing subject, or (when a role catalog is given) a role id
516
+ * missing from it. [] = the rule is indexable.
517
+ */
518
+ function getRuleDiagnostics(
519
+ rule: CoverageRuleInput,
520
+ config: ScheduleRuleConfigObj | undefined,
521
+ error: string | undefined,
522
+ resourcesById: ReadonlyMap<
523
+ string,
524
+ Pick<CoverageResourceInput, 'id' | 'kind'>
525
+ >,
526
+ rolesById: ReadonlyMap<string, CoverageRoleInput> | null,
527
+ ): CoverageDiagnosticObj[] {
528
+ if (!config)
529
+ return [
530
+ getRuleDiagnostic(rule, 'RULE_CONFIG_INVALID', {
531
+ error: error ?? 'Invalid rule configuration.',
532
+ }),
533
+ ];
534
+ const subject = getRuleSubjectDiagnostics(rule, config, resourcesById);
535
+ if (subject.length || !rolesById) return subject;
536
+ return getRuleConfigRoleIds(config)
537
+ .filter((roleId) => !rolesById.has(roleId))
538
+ .sort(compareScheduleIds)
539
+ .map((roleId) => getRuleDiagnostic(rule, 'UNKNOWN_ROLE', { roleId }));
540
+ }
541
+
542
+ /*
543
+ * The group key of a rule: its key, or '' for singleton kinds.
544
+ */
545
+ function getRuleGroupKey(rule: CoverageRuleInput): string {
546
+ return (SCHEDULE_SINGLETON_RULE_KINDS as readonly string[]).includes(
547
+ rule.kind,
548
+ )
549
+ ? ''
550
+ : rule.key;
551
+ }
552
+
553
+ /*
554
+ * Put one valid rule into its (kind, key) group: a resource-scoped rule goes
555
+ * to bySubject, any other to fallback. Rules arrive in ascending id order, so
556
+ * a rule replaces the current holder only when it is calendar-scoped and the
557
+ * holder is organization-scoped (an exact tie keeps the lower id).
558
+ */
559
+ function indexEffectiveRule(
560
+ index: ScheduleEffectiveRuleIndex,
561
+ rule: CoverageRuleInput,
562
+ config: ScheduleRuleConfigObj,
563
+ ): void {
564
+ let groups = index.byKind.get(rule.kind);
565
+ if (!groups) {
566
+ groups = new Map();
567
+ index.byKind.set(rule.kind, groups);
568
+ }
569
+ const groupKey = getRuleGroupKey(rule);
570
+ let group: RuleGroup | undefined = groups.get(groupKey);
571
+ if (!group) {
572
+ group = { fallback: null, bySubject: new Map() };
573
+ groups.set(groupKey, group);
574
+ }
575
+ const current =
576
+ rule.resourceId === null
577
+ ? group.fallback
578
+ : group.bySubject.get(rule.resourceId);
579
+ if (
580
+ current?.rule &&
581
+ (current.rule.calendarId !== null || rule.calendarId === null)
582
+ )
583
+ return;
584
+ const effective: ScheduleEffectiveRule = {
585
+ rule,
586
+ ruleId: rule.id,
587
+ kind: rule.kind,
588
+ key: rule.key,
589
+ severity: rule.severity,
590
+ config,
591
+ };
592
+ if (rule.resourceId === null) group.fallback = effective;
593
+ else group.bySubject.set(rule.resourceId, effective);
594
+ }
595
+
596
+ /*
597
+ * Resolve the rules that apply to one calendar: rules of other calendars are
598
+ * skipped; a rule with an invalid config, a missing or wrong subject, or a
599
+ * role missing from rolesById (when given) becomes a diagnostic instead of an
600
+ * index entry. Groups are (kind, key), and (kind, '') for singleton kinds.
601
+ */
131
602
  export function resolveEffectiveScheduleRules(
132
603
  rules: CoverageRuleInput[],
133
604
  calendarId: string,
134
- resourcesById: Map<string, CoverageResourceInput>,
135
- ): { index: EffectiveRuleIndex; diagnostics: CoverageDiagnosticObj[] } {
136
- const index: EffectiveRuleIndex = {
137
- byKind: new Map(
138
- SCHEDULE_RULE_KIND_ENUMS.map((kind) => [
139
- kind,
140
- { fallback: null, bySubject: new Map() },
141
- ]),
142
- ),
143
- };
605
+ resourcesById: ReadonlyMap<
606
+ string,
607
+ Pick<CoverageResourceInput, 'id' | 'kind'>
608
+ >,
609
+ rolesById: ReadonlyMap<string, CoverageRoleInput> | null,
610
+ ): {
611
+ index: ScheduleEffectiveRuleIndex;
612
+ diagnostics: CoverageDiagnosticObj[];
613
+ } {
614
+ const index: ScheduleEffectiveRuleIndex = { byKind: new Map() };
144
615
  const diagnostics: CoverageDiagnosticObj[] = [];
145
- for (const rule of [...rules].sort((a, b) =>
146
- compareScheduleIds(a.id, b.id),
147
- )) {
616
+ const sorted = [...rules].sort((a, b) => compareScheduleIds(a.id, b.id));
617
+ for (const rule of sorted) {
148
618
  if (rule.calendarId !== null && rule.calendarId !== calendarId) continue;
149
- const validated = validateScheduleRuleConfig(rule.kind, rule.config);
150
- const resource = rule.resourceId
151
- ? resourcesById.get(rule.resourceId)
152
- : null;
153
- const code = validated.error
154
- ? 'RULE_CONFIG_INVALID'
155
- : rule.resourceId && !resource
156
- ? 'UNKNOWN_RESOURCE'
157
- : resource &&
158
- resource.kind !==
159
- (SCHEDULE_RULE_SUBJECT_BY_KIND[rule.kind] === 'ROOM'
160
- ? 'SPACE'
161
- : 'LABOR')
162
- ? 'RULE_SUBJECT_KIND_MISMATCH'
163
- : null;
164
- if (code) {
165
- diagnostics.push({
166
- code,
167
- ruleId: rule.id,
168
- resourceId: rule.resourceId,
169
- occurrenceId: null,
170
- demandId: null,
171
- detail: validated.error ? { error: validated.error } : {},
172
- });
173
- continue;
174
- }
175
- const group = index.byKind.get(rule.kind)!;
176
- const current = rule.resourceId
177
- ? group.bySubject.get(rule.resourceId)
178
- : group.fallback;
179
- if (current && (current.calendarId !== null || rule.calendarId === null))
180
- continue;
181
- const normalized = { ...rule, config: validated.config! };
182
- if (rule.resourceId) group.bySubject.set(rule.resourceId, normalized);
183
- else group.fallback = normalized;
619
+ const { config, error } = validateScheduleRuleConfig(
620
+ rule.kind,
621
+ rule.config,
622
+ );
623
+ const problems = getRuleDiagnostics(
624
+ rule,
625
+ config,
626
+ error,
627
+ resourcesById,
628
+ rolesById,
629
+ );
630
+ if (problems.length) diagnostics.push(...problems);
631
+ else indexEffectiveRule(index, rule, config!);
184
632
  }
185
633
  return { index, diagnostics };
186
634
  }
187
635
 
188
- /* Get the effective row or the implicit BLOCK default for a subject. */
189
- export function getEffectiveRule(
190
- index: EffectiveRuleIndex,
636
+ /*
637
+ * Build the implicit default of an SCHEDULE_IMPLICIT_RULE_KINDS kind: BLOCK,
638
+ * config {} for ROOM_CAPACITY and {unavailable: WARN} for ELIGIBILITY.
639
+ */
640
+ function getImplicitScheduleRule(
641
+ kind: ScheduleRuleKindEnum,
642
+ ): ScheduleEffectiveRule {
643
+ return {
644
+ rule: null,
645
+ ruleId: null,
646
+ kind,
647
+ key: null,
648
+ severity: 'BLOCK',
649
+ config: kind === 'ELIGIBILITY' ? { unavailable: 'WARN' } : {},
650
+ };
651
+ }
652
+
653
+ /*
654
+ * Compare two effective rules by key, then rule id (implicit rules first).
655
+ */
656
+ function compareEffectiveRules(
657
+ a: ScheduleEffectiveRule,
658
+ b: ScheduleEffectiveRule,
659
+ ): number {
660
+ const keyA = a.key ?? '';
661
+ const keyB = b.key ?? '';
662
+ if (keyA !== keyB) return keyA < keyB ? -1 : 1;
663
+ if (a.ruleId === null || b.ruleId === null)
664
+ return Number(b.ruleId === null) - Number(a.ruleId === null);
665
+ return compareScheduleIds(a.ruleId, b.ruleId);
666
+ }
667
+
668
+ /*
669
+ * Return every rule of a kind that applies to one subject (a room, a person,
670
+ * or null for the location as a whole): per key, the subject's own rule, else
671
+ * the calendar-or-organization rule. OPERATING_HOURS never inherits: a room
672
+ * reads room rules only and null reads the location rule. An implicit kind
673
+ * with nothing applicable returns its implicit default. Sorted by key, then
674
+ * rule id.
675
+ */
676
+ export function getEffectiveScheduleRules(
677
+ index: ScheduleEffectiveRuleIndex,
191
678
  kind: ScheduleRuleKindEnum,
192
679
  subjectId: string | null,
193
- ): EffectiveRule | null {
194
- const group = index.byKind.get(kind);
195
- const rule = subjectId
196
- ? (group?.bySubject.get(subjectId) ??
197
- (kind === 'OPERATING_HOURS' ? null : group?.fallback))
198
- : group?.fallback;
199
- if (rule) return { rule, ruleId: rule.id, severity: rule.severity };
200
- return (SCHEDULE_IMPLICIT_RULE_KINDS as readonly string[]).includes(kind)
201
- ? { rule: null, ruleId: null, severity: 'BLOCK' }
202
- : null;
203
- }
204
-
205
- /* Bound the external assignment history needed by active actor window rules. */
206
- export function getMaxActorWindowDays(rules: CoverageRuleInput[]): number {
680
+ ): ScheduleEffectiveRule[] {
681
+ const result: ScheduleEffectiveRule[] = [];
682
+ for (const group of index.byKind.get(kind)?.values() ?? []) {
683
+ const own = subjectId === null ? null : group.bySubject.get(subjectId);
684
+ const rule =
685
+ kind === 'OPERATING_HOURS' && subjectId !== null
686
+ ? own
687
+ : (own ?? group.fallback);
688
+ if (rule) result.push(rule);
689
+ }
690
+ if (
691
+ !result.length &&
692
+ (SCHEDULE_IMPLICIT_RULE_KINDS as readonly string[]).includes(kind)
693
+ )
694
+ return [getImplicitScheduleRule(kind)];
695
+ return result.sort(compareEffectiveRules);
696
+ }
697
+
698
+ /*
699
+ * How many days before a seat's date MAX_CONSECUTIVE_DAYS reads to measure
700
+ * the run ending on it: twice the limit. A run up to that long is measured
701
+ * exactly; a longer one is reported at that length as truncated, so a
702
+ * finding never depends on how far back the caller loaded the timeline.
703
+ */
704
+ export function getScheduleConsecutiveDaysLookback(days: number): number {
705
+ return days * 2;
706
+ }
707
+
708
+ /*
709
+ * How many whole days one valid person rule needs on each side of an
710
+ * evaluated range (0 for kinds that read one seat).
711
+ */
712
+ function getPersonRuleWindowDays(
713
+ kind: ScheduleRuleKindEnum,
714
+ config: ScheduleRuleConfigObj,
715
+ ): number {
716
+ if (kind === 'MAX_HOURS') {
717
+ const { period, days } = config as ScheduleMaxHoursConfigObj;
718
+ return period === 'DAY' ? 1 : period === 'PAY_WEEK' ? 7 : (days ?? 0);
719
+ }
720
+ if (kind === 'MIN_REST')
721
+ return Math.ceil(
722
+ (config as ScheduleRuleConfigByKind['MIN_REST']).minMinutes /
723
+ FILE_CONSTANTS.dayMinutes,
724
+ );
725
+ if (kind === 'MAX_CONSECUTIVE_DAYS')
726
+ return getScheduleConsecutiveDaysLookback(
727
+ (config as ScheduleRuleConfigByKind['MAX_CONSECUTIVE_DAYS']).days,
728
+ );
729
+ return 0;
730
+ }
731
+
732
+ /*
733
+ * How far around an evaluated range a person's other seats must be loaded
734
+ * (IMPLEMENTATION §1.5: lookback and lookahead): the largest need of the
735
+ * valid person rules given. MAX_HOURS DAY 1, PAY_WEEK 7, ROLLING_DAYS days;
736
+ * MIN_REST ceil(minMinutes / 1440); MAX_CONSECUTIVE_DAYS
737
+ * getScheduleConsecutiveDaysLookback(days) (twice the limit); everything
738
+ * else 0. Invalid configs are ignored.
739
+ */
740
+ export function getSchedulePersonRuleWindow(
741
+ rules: CoverageRuleInput[],
742
+ ): SchedulePersonRuleWindow {
207
743
  let days = 0;
208
744
  for (const rule of rules) {
209
- if (rule.kind !== 'ACTOR_WINDOW_AGGREGATE') continue;
210
- const validated = validateScheduleRuleConfig(rule.kind, rule.config);
211
- if (!validated.config) continue;
212
- const config = validated.config as ScheduleActorWindowConfigObj;
213
- days = Math.max(days, config.windowDays ?? (config.minRestMinutes ? 1 : 0));
745
+ const { config } = validateScheduleRuleConfig(rule.kind, rule.config);
746
+ if (config)
747
+ days = Math.max(days, getPersonRuleWindowDays(rule.kind, config));
214
748
  }
215
- return days;
749
+ return { lookbackDays: days, lookaheadDays: days };
216
750
  }