@jsb188/schedule 1.1.11

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 (60) hide show
  1. package/package.json +61 -0
  2. package/src/constants/schedule.ts +549 -0
  3. package/src/css.d.ts +7 -0
  4. package/src/libs/gantt-geometry.ts +771 -0
  5. package/src/libs/gantt-histogram.ts +124 -0
  6. package/src/libs/gantt-keyboard.ts +113 -0
  7. package/src/libs/gantt-state.ts +57 -0
  8. package/src/libs/gantt-url.ts +63 -0
  9. package/src/modules/Gantt.helpers.ts +138 -0
  10. package/src/modules/Gantt.tsx +719 -0
  11. package/src/types/schedule.d.ts +1149 -0
  12. package/src/ui/ActivityFormUI.tsx +133 -0
  13. package/src/ui/GanttEditorsUI.tsx +102 -0
  14. package/src/ui/GanttHistogramUI.tsx +236 -0
  15. package/src/ui/GanttUI.tsx +792 -0
  16. package/src/ui/ProjectFormUI.tsx +273 -0
  17. package/src/ui/ProjectMobileListUI.tsx +80 -0
  18. package/src/ui/ProjectToolbarUI.tsx +54 -0
  19. package/src/ui/RelationshipListUI.tsx +176 -0
  20. package/src/ui/ScheduleRunUI.tsx +173 -0
  21. package/src/ui/ScheduleSettingsUI.tsx +420 -0
  22. package/src/utils/coverage.helpers.ts +679 -0
  23. package/src/utils/coverage.ts +630 -0
  24. package/src/utils/cpm.helpers.ts +674 -0
  25. package/src/utils/cpm.ts +907 -0
  26. package/src/utils/cpmLeveling.helpers.ts +564 -0
  27. package/src/utils/cpmLeveling.ts +367 -0
  28. package/src/utils/defaults.ts +8 -0
  29. package/src/utils/eligibility.ts +457 -0
  30. package/src/utils/planCsv.ts +344 -0
  31. package/src/utils/predecessorText.ts +96 -0
  32. package/src/utils/recurrence.ts +616 -0
  33. package/src/utils/request.ts +153 -0
  34. package/src/utils/resource.ts +182 -0
  35. package/src/utils/rule.ts +216 -0
  36. package/src/utils/run.ts +43 -0
  37. package/src/utils/series.ts +161 -0
  38. package/src/utils/slot.ts +208 -0
  39. package/src/utils/workTime.ts +1382 -0
  40. package/tests/coverage.fixtures.ts +111 -0
  41. package/tests/coverage.test.ts +503 -0
  42. package/tests/cpm.bench.test.ts +154 -0
  43. package/tests/cpm.test.ts +354 -0
  44. package/tests/cpmCorrectness.test.ts +327 -0
  45. package/tests/cpmLeveling.test.ts +471 -0
  46. package/tests/eligibility.test.ts +320 -0
  47. package/tests/gantt-geometry.test.ts +367 -0
  48. package/tests/gantt-histogram.test.ts +78 -0
  49. package/tests/gantt-keyboard.test.ts +69 -0
  50. package/tests/helpers/cpmFixtures.ts +101 -0
  51. package/tests/projectInputs.test.ts +165 -0
  52. package/tests/recurrence.test.ts +68 -0
  53. package/tests/request.test.ts +99 -0
  54. package/tests/resource.test.ts +95 -0
  55. package/tests/rule.test.ts +98 -0
  56. package/tests/series.test.ts +120 -0
  57. package/tests/workTime.test.ts +1007 -0
  58. package/tests/workTimeContracts.test.ts +111 -0
  59. package/tsconfig.json +13 -0
  60. package/vitest.config.ts +8 -0
@@ -0,0 +1,457 @@
1
+ import { SCHEDULE_ELIGIBILITY_REASON_ENUMS } from '../constants/schedule.ts';
2
+ import type {
3
+ CoverageAssignmentInput,
4
+ CoverageDemandInput,
5
+ CoverageEvaluationInput,
6
+ CoverageExternalAssignmentInput,
7
+ CoverageOccurrenceInput,
8
+ CoverageResourceInput,
9
+ CoverageRuleInput,
10
+ CoverageTimeOffInput,
11
+ CoverageViolationObj,
12
+ ScheduleEligibilityReasonEnum,
13
+ ScheduleRuleSeverityEnum,
14
+ ScheduleWorkCalendarDef,
15
+ } from '../types/schedule.d.ts';
16
+ import { evaluateScheduleCoverage } from './coverage.ts';
17
+ import {
18
+ coverageTime,
19
+ fillOccurrenceSlots,
20
+ normalizeCoverageInput,
21
+ stableStringify,
22
+ } from './coverage.helpers.ts';
23
+ import { getMaxActorWindowDays } from './rule.ts';
24
+ import { getSlotPredicateMissing } from './slot.ts';
25
+
26
+ export interface EligibilityReason {
27
+ code: ScheduleEligibilityReasonEnum;
28
+ severity: ScheduleRuleSeverityEnum;
29
+ ruleId: string | null;
30
+ detail: Record<string, unknown>;
31
+ startAt: Date | null;
32
+ endAt: Date | null;
33
+ }
34
+ export interface ShiftEligibilityContext {
35
+ calendarId: string;
36
+ now: Date;
37
+ resources: CoverageResourceInput[];
38
+ assignmentsOfResource: CoverageExternalAssignmentInput[];
39
+ timeOff: CoverageTimeOffInput[];
40
+ rules: CoverageRuleInput[];
41
+ requireOpenSlot?: boolean;
42
+ // A swap exchanges the exact outgoing seat, including an explicit surplus seat.
43
+ preserveUnslotted?: boolean;
44
+ }
45
+ export interface ShiftEligibilityResult {
46
+ eligible: boolean;
47
+ slotKey: string | null;
48
+ reasons: EligibilityReason[];
49
+ }
50
+ export interface AssignmentChange {
51
+ add: Array<{
52
+ occurrenceId: string;
53
+ resourceId: string;
54
+ slotKey: string | null;
55
+ }>;
56
+ remove: Array<{ occurrenceId: string; resourceId: string }>;
57
+ }
58
+
59
+ /* Add one hypothetical assignment using copy-on-write for only the touched occurrence. */
60
+ export function withSimulatedAssignment(
61
+ snapshot: CoverageEvaluationInput,
62
+ occurrenceId: string,
63
+ assignment: CoverageAssignmentInput,
64
+ ): CoverageEvaluationInput {
65
+ return {
66
+ ...snapshot,
67
+ occurrences: snapshot.occurrences.map((occurrence) =>
68
+ occurrence.id === occurrenceId
69
+ ? {
70
+ ...occurrence,
71
+ assignments: [...occurrence.assignments, assignment],
72
+ }
73
+ : occurrence,
74
+ ),
75
+ };
76
+ }
77
+
78
+ /* Remove one person's assignment without mutating the source snapshot. */
79
+ export function withoutAssignment(
80
+ snapshot: CoverageEvaluationInput,
81
+ occurrenceId: string,
82
+ resourceId: string,
83
+ ): CoverageEvaluationInput {
84
+ return {
85
+ ...snapshot,
86
+ occurrences: snapshot.occurrences.map((occurrence) =>
87
+ occurrence.id === occurrenceId
88
+ ? {
89
+ ...occurrence,
90
+ assignments: occurrence.assignments.filter(
91
+ (assignment) => assignment.resourceId !== resourceId,
92
+ ),
93
+ }
94
+ : occurrence,
95
+ ),
96
+ };
97
+ }
98
+
99
+ /* Apply all removals before additions so swaps cannot temporarily double-book a seat. */
100
+ export function simulateAssignmentChange(
101
+ snapshot: CoverageEvaluationInput,
102
+ change: AssignmentChange,
103
+ ): CoverageEvaluationInput {
104
+ let result = snapshot;
105
+ for (const removal of change.remove)
106
+ result = withoutAssignment(
107
+ result,
108
+ removal.occurrenceId,
109
+ removal.resourceId,
110
+ );
111
+ for (const addition of change.add)
112
+ result = withSimulatedAssignment(result, addition.occurrenceId, {
113
+ id: null,
114
+ resourceId: addition.resourceId,
115
+ slotKey: addition.slotKey,
116
+ });
117
+ return result;
118
+ }
119
+
120
+ /* Compare problem identities and maximum degree, allowing improving stretches to move. */
121
+ export function diffCoverageViolations(
122
+ before: CoverageViolationObj[],
123
+ after: CoverageViolationObj[],
124
+ ): {
125
+ introduced: CoverageViolationObj[];
126
+ worsened: CoverageViolationObj[];
127
+ resolved: CoverageViolationObj[];
128
+ } {
129
+ const prior = new Map<string, number>();
130
+ const next = new Map<string, number>();
131
+ for (const violation of before)
132
+ prior.set(
133
+ violation.identity,
134
+ Math.max(prior.get(violation.identity) ?? -Infinity, violation.degree),
135
+ );
136
+ for (const violation of after)
137
+ next.set(
138
+ violation.identity,
139
+ Math.max(next.get(violation.identity) ?? -Infinity, violation.degree),
140
+ );
141
+ return {
142
+ introduced: after.filter((violation) => !prior.has(violation.identity)),
143
+ worsened: after.filter(
144
+ (violation) =>
145
+ prior.has(violation.identity) &&
146
+ next.get(violation.identity)! > prior.get(violation.identity)!,
147
+ ),
148
+ resolved: before.filter((violation) => !next.has(violation.identity)),
149
+ };
150
+ }
151
+
152
+ /* Present stable, deduplicated reasons with blocking facts before warnings. */
153
+ function finishEligibility(
154
+ slotKey: string | null,
155
+ reasons: EligibilityReason[],
156
+ ): ShiftEligibilityResult {
157
+ const unique = new Map<string, EligibilityReason>();
158
+ for (const reason of reasons) unique.set(stableStringify(reason), reason);
159
+ const sorted = [...unique.values()].sort(
160
+ (a, b) =>
161
+ Number(b.severity === 'BLOCK') - Number(a.severity === 'BLOCK') ||
162
+ SCHEDULE_ELIGIBILITY_REASON_ENUMS.indexOf(a.code) -
163
+ SCHEDULE_ELIGIBILITY_REASON_ENUMS.indexOf(b.code) ||
164
+ (a.startAt?.getTime() ?? 0) - (b.startAt?.getTime() ?? 0),
165
+ );
166
+ return {
167
+ eligible: !sorted.some((reason) => reason.severity === 'BLOCK'),
168
+ slotKey,
169
+ reasons: sorted,
170
+ };
171
+ }
172
+
173
+ /* Map the coverage engine's assignment and aggregate violations to picker reasons. */
174
+ function violationToReason(
175
+ violation: CoverageViolationObj,
176
+ occurrence: CoverageOccurrenceInput,
177
+ ): EligibilityReason | null {
178
+ let code: ScheduleEligibilityReasonEnum;
179
+ if (violation.kind === 'ELIGIBILITY' && violation.code)
180
+ code =
181
+ violation.code === 'QUALIFICATION_EXPIRED' &&
182
+ violation.startAt.getTime() > coverageTime(occurrence.startAt)
183
+ ? 'QUALIFICATION_EXPIRES_DURING_SHIFT'
184
+ : (violation.code as ScheduleEligibilityReasonEnum);
185
+ else if (violation.kind === 'ACTOR_WINDOW_AGGREGATE')
186
+ code = violation.code === 'HOURS' ? 'WINDOW_HOURS_EXCEEDED' : 'MIN_REST';
187
+ else return null;
188
+ return {
189
+ code,
190
+ severity: violation.severity,
191
+ ruleId: violation.ruleId,
192
+ detail:
193
+ violation.kind === 'ACTOR_WINDOW_AGGREGATE'
194
+ ? { ...violation.detail, occurrenceId: violation.occurrenceId }
195
+ : violation.detail,
196
+ startAt: violation.startAt,
197
+ endAt: violation.endAt,
198
+ };
199
+ }
200
+
201
+ /* Resolve a candidate seat, then use coverage simulation as the source of policy eligibility. */
202
+ export function evaluateShiftEligibility(args: {
203
+ occurrence: CoverageOccurrenceInput;
204
+ slotKey: string | null;
205
+ resource: CoverageResourceInput;
206
+ context: ShiftEligibilityContext;
207
+ }): ShiftEligibilityResult {
208
+ const { occurrence, resource, context } = args;
209
+ const resources = new Map(
210
+ context.resources.map((person) => [person.id, person]),
211
+ );
212
+ if (
213
+ occurrence.assignments.some(
214
+ (assignment) => !resources.has(assignment.resourceId),
215
+ )
216
+ )
217
+ throw new Error('SCHEDULE_ELIGIBILITY_CONTEXT_INCOMPLETE');
218
+ resources.set(resource.id, resource);
219
+ const reasons: EligibilityReason[] = [];
220
+ /* Add structural reasons that cannot be represented by a persisted coverage violation. */
221
+ const reason = (
222
+ code: ScheduleEligibilityReasonEnum,
223
+ severity: ScheduleRuleSeverityEnum = 'BLOCK',
224
+ detail: Record<string, unknown> = {},
225
+ ): void => {
226
+ reasons.push({
227
+ code,
228
+ severity,
229
+ ruleId: null,
230
+ detail,
231
+ startAt: null,
232
+ endAt: null,
233
+ });
234
+ };
235
+ if (resource.kind !== 'LABOR') reason('NOT_LABOR');
236
+ if (
237
+ resource.retiredAt != null &&
238
+ coverageTime(resource.retiredAt) <= coverageTime(occurrence.endAt)
239
+ )
240
+ reason('RESOURCE_RETIRED');
241
+ if (occurrence.kind !== 'SHIFT') reason('OCCURRENCE_NOT_SHIFT');
242
+ if (coverageTime(occurrence.endAt) <= context.now.getTime())
243
+ reason('OCCURRENCE_ENDED');
244
+ if (
245
+ occurrence.assignments.some(
246
+ (assignment) => assignment.resourceId === resource.id,
247
+ )
248
+ )
249
+ reason('ALREADY_ASSIGNED');
250
+ const windowDays = Math.max(1, getMaxActorWindowDays(context.rules));
251
+ // Earlier assignments remain timeline evidence; only the target and later anchors can worsen.
252
+ const snapshot: CoverageEvaluationInput = {
253
+ calendarId: context.calendarId,
254
+ window: {
255
+ from: occurrence.startAt,
256
+ to: new Date(coverageTime(occurrence.endAt) + windowDays * 86_400_000),
257
+ },
258
+ timeZone: 'UTC',
259
+ operatingHours: null,
260
+ occurrences: [occurrence],
261
+ external: context.assignmentsOfResource.filter(
262
+ (row) => row.occurrenceId !== occurrence.id,
263
+ ),
264
+ resources: [...resources.values()],
265
+ demand: [],
266
+ timeOff: context.timeOff,
267
+ rules: context.rules.filter(
268
+ (rule) =>
269
+ rule.kind === 'ELIGIBILITY' || rule.kind === 'ACTOR_WINDOW_AGGREGATE',
270
+ ),
271
+ options: { anchorExternal: true },
272
+ };
273
+ const normalized = normalizeCoverageInput(snapshot);
274
+ const normalizedOccurrence = normalized.occurrences[0];
275
+ if (!normalizedOccurrence)
276
+ return finishEligibility(args.slotKey, [
277
+ ...reasons,
278
+ {
279
+ code: 'OCCURRENCE_ENDED',
280
+ severity: 'BLOCK',
281
+ ruleId: null,
282
+ detail: { invalidInterval: true },
283
+ startAt: null,
284
+ endAt: null,
285
+ },
286
+ ]);
287
+ const fill = fillOccurrenceSlots(normalizedOccurrence, normalized);
288
+ const slots = normalizedOccurrence.slots;
289
+ /* Qualification keys select a seat while expiry is evaluated over the entire shift by the sweep. */
290
+ const matches = (slot: (typeof slots)[number]): boolean =>
291
+ !Object.values(
292
+ getSlotPredicateMissing(resource.config, slot.predicate),
293
+ ).some((keys) => keys.length);
294
+ let slot =
295
+ context.preserveUnslotted && args.slotKey === null
296
+ ? undefined
297
+ : args.slotKey !== null
298
+ ? slots.find((slot) => slot.key === args.slotKey)
299
+ : (slots.find(
300
+ (slot) =>
301
+ (fill.filled.get(slot.key) ?? 0) < slot.requiredCount &&
302
+ matches(slot),
303
+ ) ?? slots.find(matches));
304
+ if (args.slotKey !== null && !slot)
305
+ reason('SLOT_UNKNOWN', 'BLOCK', { slotKey: args.slotKey });
306
+ else if (!slot && !context.preserveUnslotted)
307
+ reason('NO_MATCHING_SLOT', context.requireOpenSlot ? 'BLOCK' : 'WARN');
308
+ if (slot && (fill.filled.get(slot.key) ?? 0) >= slot.requiredCount)
309
+ reason('SLOT_FULL', context.requireOpenSlot ? 'BLOCK' : 'WARN', {
310
+ slotKey: slot.key,
311
+ });
312
+ if (reasons.some((item) => item.severity === 'BLOCK'))
313
+ return finishEligibility(slot?.key ?? null, reasons);
314
+ // Freeze current greedy placements so adding a candidate cannot reshuffle existing people's seats.
315
+ const placements = new Map(
316
+ fill.standings.map((standing) => [
317
+ standing.personId,
318
+ standing.placedSlotKey,
319
+ ]),
320
+ );
321
+ const stableOccurrence = {
322
+ ...occurrence,
323
+ assignments: occurrence.assignments.map((assignment) =>
324
+ assignment.slotKey === null && placements.get(assignment.resourceId)
325
+ ? { ...assignment, slotKey: placements.get(assignment.resourceId)! }
326
+ : assignment,
327
+ ),
328
+ };
329
+ const beforeSnapshot = { ...snapshot, occurrences: [stableOccurrence] };
330
+ const before = evaluateScheduleCoverage(beforeSnapshot).violations;
331
+ const after = evaluateScheduleCoverage(
332
+ withSimulatedAssignment(beforeSnapshot, occurrence.id, {
333
+ id: null,
334
+ resourceId: resource.id,
335
+ slotKey: slot?.key ?? null,
336
+ }),
337
+ ).violations;
338
+ const diff = diffCoverageViolations(before, after);
339
+ for (const violation of [...diff.introduced, ...diff.worsened]) {
340
+ if (violation.resourceId !== resource.id) continue;
341
+ const mapped = violationToReason(violation, occurrence);
342
+ if (mapped) reasons.push(mapped);
343
+ }
344
+ return finishEligibility(slot?.key ?? null, reasons);
345
+ }
346
+
347
+ /* Check both swap directions after each outgoing person has vacated the exchanged seat. */
348
+ export function evaluateSwapEligibility(args: {
349
+ a: {
350
+ occurrence: CoverageOccurrenceInput;
351
+ resource: CoverageResourceInput;
352
+ context: ShiftEligibilityContext;
353
+ };
354
+ b: {
355
+ occurrence: CoverageOccurrenceInput;
356
+ resource: CoverageResourceInput;
357
+ context: ShiftEligibilityContext;
358
+ };
359
+ }): {
360
+ eligible: boolean;
361
+ slotKeys: { a: string | null; b: string | null };
362
+ reasons: { a: EligibilityReason[]; b: EligibilityReason[] };
363
+ } {
364
+ const { a, b } = args;
365
+ const aSeat = a.occurrence.assignments.find(
366
+ (assignment) => assignment.resourceId === a.resource.id,
367
+ );
368
+ const bSeat = b.occurrence.assignments.find(
369
+ (assignment) => assignment.resourceId === b.resource.id,
370
+ );
371
+ if (!aSeat || !bSeat) throw new Error('SCHEDULE_SWAP_ASSIGNMENT_MISSING');
372
+ for (const context of [a.context, b.context]) {
373
+ const ids = new Set(context.resources.map((resource) => resource.id));
374
+ if (
375
+ [...a.occurrence.assignments, ...b.occurrence.assignments].some(
376
+ (assignment) => !ids.has(assignment.resourceId),
377
+ )
378
+ )
379
+ throw new Error('SCHEDULE_ELIGIBILITY_CONTEXT_INCOMPLETE');
380
+ }
381
+ const occurrences = new Set([a.occurrence.id, b.occurrence.id]);
382
+ const aResult = evaluateShiftEligibility({
383
+ occurrence: {
384
+ ...b.occurrence,
385
+ assignments: b.occurrence.assignments.filter(
386
+ (assignment) => assignment.resourceId !== b.resource.id,
387
+ ),
388
+ },
389
+ slotKey: bSeat.slotKey,
390
+ resource: a.resource,
391
+ context: {
392
+ ...a.context,
393
+ preserveUnslotted: bSeat.slotKey === null,
394
+ calendarId: b.context.calendarId,
395
+ rules: b.context.rules,
396
+ assignmentsOfResource: a.context.assignmentsOfResource.filter(
397
+ (row) => !occurrences.has(row.occurrenceId),
398
+ ),
399
+ },
400
+ });
401
+ const bResult = evaluateShiftEligibility({
402
+ occurrence: {
403
+ ...a.occurrence,
404
+ assignments: a.occurrence.assignments.filter(
405
+ (assignment) => assignment.resourceId !== a.resource.id,
406
+ ),
407
+ },
408
+ slotKey: aSeat.slotKey,
409
+ resource: b.resource,
410
+ context: {
411
+ ...b.context,
412
+ preserveUnslotted: aSeat.slotKey === null,
413
+ calendarId: a.context.calendarId,
414
+ rules: a.context.rules,
415
+ assignmentsOfResource: b.context.assignmentsOfResource.filter(
416
+ (row) => !occurrences.has(row.occurrenceId),
417
+ ),
418
+ },
419
+ });
420
+ return {
421
+ eligible: aResult.eligible && bResult.eligible,
422
+ slotKeys: { a: aResult.slotKey, b: bResult.slotKey },
423
+ reasons: { a: aResult.reasons, b: bResult.reasons },
424
+ };
425
+ }
426
+
427
+ /* Show newly introduced and worsened room coverage when a manager considers a drop. */
428
+ export function evaluateDropImpact(args: {
429
+ occurrence: CoverageOccurrenceInput;
430
+ resourceId: string;
431
+ context: {
432
+ calendarId: string;
433
+ roomOccurrences: CoverageOccurrenceInput[];
434
+ demand: CoverageDemandInput[];
435
+ timeOff: CoverageTimeOffInput[];
436
+ rules: CoverageRuleInput[];
437
+ resources: CoverageResourceInput[];
438
+ operatingHours: ScheduleWorkCalendarDef | null;
439
+ timeZone: string;
440
+ };
441
+ }): { introduced: CoverageViolationObj[]; worsened: CoverageViolationObj[] } {
442
+ const { occurrence, resourceId, context } = args;
443
+ const snapshot: CoverageEvaluationInput = {
444
+ ...context,
445
+ window: { from: occurrence.startAt, to: occurrence.endAt },
446
+ occurrences: context.roomOccurrences.some((row) => row.id === occurrence.id)
447
+ ? context.roomOccurrences
448
+ : [...context.roomOccurrences, occurrence],
449
+ external: [],
450
+ };
451
+ const before = evaluateScheduleCoverage(snapshot).violations;
452
+ const after = evaluateScheduleCoverage(
453
+ withoutAssignment(snapshot, occurrence.id, resourceId),
454
+ ).violations;
455
+ const { introduced, worsened } = diffCoverageViolations(before, after);
456
+ return { introduced, worsened };
457
+ }