@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,1007 @@
1
+ import { DateTime } from 'luxon';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { SCHEDULE_WORK_TIME_MAX_SPAN_DAYS } from '../src/constants/schedule.ts';
4
+ import type {
5
+ CpmActivityInput,
6
+ CpmRelationshipInput,
7
+ ScheduleWorkCalendarDef,
8
+ } from '../src/types/schedule.d.ts';
9
+ import { runCriticalPathSchedule } from '../src/utils/cpm.ts';
10
+ import {
11
+ addWorkingMinutes,
12
+ buildWorkCalendarTable,
13
+ getDateKeyForDayIndex,
14
+ getDayIndexAt,
15
+ getDayStartMs,
16
+ getStandardWorkCalendarDef,
17
+ getWorkCalendarTable,
18
+ getWorkingDayIndicesBetween,
19
+ getWorkingMinutesOnDay,
20
+ getWorkingMinutesPerDay,
21
+ isWorkingCalendar,
22
+ snapToWorkingFinish,
23
+ snapToWorkingStart,
24
+ validateWeekHours,
25
+ workingMinutesBetween,
26
+ } from '../src/utils/workTime.ts';
27
+
28
+ const ZONE = 'America/Los_Angeles';
29
+ const NY = 'America/New_York';
30
+ const DAY_MS = 86_400_000;
31
+ const calendar = getStandardWorkCalendarDef(ZONE);
32
+
33
+ /*
34
+ * Local LA time to UTC instant (PST = UTC-8 in January, PDT = UTC-7 in March).
35
+ */
36
+ function la(date: string, time: string, offset = '-08:00'): Date {
37
+ return new Date(`${date}T${time}:00${offset}`);
38
+ }
39
+
40
+ /*
41
+ * UTC instant from an ISO string.
42
+ */
43
+ function utc(iso: string): Date {
44
+ return new Date(iso);
45
+ }
46
+
47
+ /*
48
+ * Local New York wall-clock time to a UTC instant via luxon.
49
+ */
50
+ function ny(date: string, time: string): Date {
51
+ return DateTime.fromISO(`${date}T${time}`, { zone: NY }).toJSDate();
52
+ }
53
+
54
+ /*
55
+ * A seven-day calendar so daylight-saving Sundays carry working time.
56
+ */
57
+ function getSevenDayCalendar(
58
+ id: string,
59
+ extra: Partial<ScheduleWorkCalendarDef> = {},
60
+ ): ScheduleWorkCalendarDef {
61
+ const hours: Array<[string, string]> = [
62
+ ['08:00', '12:00'],
63
+ ['13:00', '17:00'],
64
+ ];
65
+ return {
66
+ id,
67
+ timeZone: NY,
68
+ weekHours: {
69
+ '0': hours,
70
+ '1': hours,
71
+ '2': hours,
72
+ '3': hours,
73
+ '4': hours,
74
+ '5': hours,
75
+ '6': hours,
76
+ },
77
+ exceptions: null,
78
+ minutesPerDay: 480,
79
+ ...extra,
80
+ };
81
+ }
82
+
83
+ /*
84
+ * A night-shift calendar: Monday to Friday 22:00-24:00 plus 00:00-06:00 on
85
+ * the following day key (Tuesday to Saturday).
86
+ */
87
+ function getNightShiftCalendar(id: string): ScheduleWorkCalendarDef {
88
+ return {
89
+ id,
90
+ timeZone: NY,
91
+ weekHours: {
92
+ '1': [['22:00', '24:00']],
93
+ '2': [
94
+ ['00:00', '06:00'],
95
+ ['22:00', '24:00'],
96
+ ],
97
+ '3': [
98
+ ['00:00', '06:00'],
99
+ ['22:00', '24:00'],
100
+ ],
101
+ '4': [
102
+ ['00:00', '06:00'],
103
+ ['22:00', '24:00'],
104
+ ],
105
+ '5': [
106
+ ['00:00', '06:00'],
107
+ ['22:00', '24:00'],
108
+ ],
109
+ '6': [['00:00', '06:00']],
110
+ },
111
+ exceptions: null,
112
+ minutesPerDay: 480,
113
+ };
114
+ }
115
+
116
+ /*
117
+ * Deterministic PRNG (mulberry32) so the random suites are reproducible.
118
+ */
119
+ function createRandom(seed: number): () => number {
120
+ let state = seed >>> 0;
121
+ return () => {
122
+ state = (state + 0x6d2b79f5) >>> 0;
123
+ let t = state;
124
+ t = Math.imul(t ^ (t >>> 15), t | 1);
125
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
126
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
127
+ };
128
+ }
129
+
130
+ /**
131
+ * Slow reference walker: the pre-table algorithm, one luxon day at a time,
132
+ * in integer milliseconds. Kept independent of the table code on purpose.
133
+ */
134
+
135
+ interface ReferencePeriod {
136
+ startMs: number;
137
+ endMs: number;
138
+ }
139
+
140
+ const REFERENCE_PERIODS = new Map<string, ReferencePeriod[]>();
141
+
142
+ /*
143
+ * Resolve one local day's periods with luxon "set" for every bound.
144
+ */
145
+ function referencePeriods(
146
+ cal: ScheduleWorkCalendarDef,
147
+ dayStart: DateTime,
148
+ ): ReferencePeriod[] {
149
+ const key = `${cal.id}|${dayStart.toISODate()}`;
150
+ const cached = REFERENCE_PERIODS.get(key);
151
+ if (cached) {
152
+ return cached;
153
+ }
154
+
155
+ const exception = cal.exceptions?.[dayStart.toISODate() as string];
156
+ const weekdayKey = String(dayStart.weekday % 7) as '0';
157
+ const intervals =
158
+ exception !== undefined ? exception || [] : cal.weekHours[weekdayKey] || [];
159
+ const periods: ReferencePeriod[] = [];
160
+
161
+ for (const [from, to] of intervals) {
162
+ const [fromHours, fromMinutes] = from.split(':').map(Number);
163
+ const [toHours, toMinutes] = to.split(':').map(Number);
164
+ const startMs = dayStart
165
+ .set({ hour: fromHours, minute: fromMinutes, second: 0, millisecond: 0 })
166
+ .toMillis();
167
+ const endMs =
168
+ toHours === 24
169
+ ? dayStart.plus({ days: 1 }).toMillis()
170
+ : dayStart
171
+ .set({
172
+ hour: toHours,
173
+ minute: toMinutes,
174
+ second: 0,
175
+ millisecond: 0,
176
+ })
177
+ .toMillis();
178
+ if (endMs > startMs) {
179
+ periods.push({ startMs, endMs });
180
+ }
181
+ }
182
+
183
+ REFERENCE_PERIODS.set(key, periods);
184
+ return periods;
185
+ }
186
+
187
+ /*
188
+ * Local midnight of one instant in the calendar's zone.
189
+ */
190
+ function referenceDayStart(cal: ScheduleWorkCalendarDef, ms: number): DateTime {
191
+ return DateTime.fromMillis(ms, { zone: cal.timeZone }).startOf('day');
192
+ }
193
+
194
+ /*
195
+ * Reference forward snap.
196
+ */
197
+ function referenceSnapStart(
198
+ cal: ScheduleWorkCalendarDef,
199
+ atMs: number,
200
+ ): number {
201
+ let day = referenceDayStart(cal, atMs);
202
+ for (let i = 0; i < SCHEDULE_WORK_TIME_MAX_SPAN_DAYS; i++) {
203
+ for (const period of referencePeriods(cal, day)) {
204
+ if (atMs < period.endMs) {
205
+ return Math.max(atMs, period.startMs);
206
+ }
207
+ }
208
+ day = day.plus({ days: 1 });
209
+ }
210
+ throw new Error('reference: no working time');
211
+ }
212
+
213
+ /*
214
+ * Reference backward snap.
215
+ */
216
+ function referenceSnapFinish(
217
+ cal: ScheduleWorkCalendarDef,
218
+ atMs: number,
219
+ ): number {
220
+ let day = referenceDayStart(cal, atMs);
221
+ for (let i = 0; i < SCHEDULE_WORK_TIME_MAX_SPAN_DAYS; i++) {
222
+ const periods = referencePeriods(cal, day);
223
+ for (let j = periods.length - 1; j >= 0; j--) {
224
+ if (atMs > periods[j].startMs) {
225
+ return Math.min(atMs, periods[j].endMs);
226
+ }
227
+ }
228
+ day = day.minus({ days: 1 });
229
+ }
230
+ throw new Error('reference: no working time');
231
+ }
232
+
233
+ /*
234
+ * Reference signed add.
235
+ */
236
+ function referenceAdd(
237
+ cal: ScheduleWorkCalendarDef,
238
+ fromMs: number,
239
+ minutes: number,
240
+ ): number {
241
+ if (minutes === 0) {
242
+ return fromMs;
243
+ }
244
+
245
+ if (minutes > 0) {
246
+ let cursorMs = referenceSnapStart(cal, fromMs);
247
+ let remainingMs = minutes * 60_000;
248
+ let day = referenceDayStart(cal, cursorMs);
249
+ for (let i = 0; i < SCHEDULE_WORK_TIME_MAX_SPAN_DAYS; i++) {
250
+ for (const period of referencePeriods(cal, day)) {
251
+ if (period.endMs <= cursorMs) {
252
+ continue;
253
+ }
254
+ const startMs = Math.max(period.startMs, cursorMs);
255
+ const availableMs = period.endMs - startMs;
256
+ if (availableMs >= remainingMs) {
257
+ return startMs + remainingMs;
258
+ }
259
+ remainingMs -= availableMs;
260
+ cursorMs = period.endMs;
261
+ }
262
+ day = day.plus({ days: 1 });
263
+ }
264
+ throw new Error('reference: cannot fit');
265
+ }
266
+
267
+ let cursorMs = referenceSnapFinish(cal, fromMs);
268
+ let remainingMs = -minutes * 60_000;
269
+ let day = referenceDayStart(cal, cursorMs);
270
+ for (let i = 0; i < SCHEDULE_WORK_TIME_MAX_SPAN_DAYS; i++) {
271
+ const periods = referencePeriods(cal, day);
272
+ for (let j = periods.length - 1; j >= 0; j--) {
273
+ if (periods[j].startMs >= cursorMs) {
274
+ continue;
275
+ }
276
+ const endMs = Math.min(periods[j].endMs, cursorMs);
277
+ const availableMs = endMs - periods[j].startMs;
278
+ if (availableMs >= remainingMs) {
279
+ return endMs - remainingMs;
280
+ }
281
+ remainingMs -= availableMs;
282
+ cursorMs = periods[j].startMs;
283
+ }
284
+ day = day.minus({ days: 1 });
285
+ }
286
+ throw new Error('reference: cannot fit');
287
+ }
288
+
289
+ /*
290
+ * Reference signed working minutes between two instants.
291
+ */
292
+ function referenceBetween(
293
+ cal: ScheduleWorkCalendarDef,
294
+ fromMs: number,
295
+ toMs: number,
296
+ ): number {
297
+ if (toMs === fromMs) {
298
+ return 0;
299
+ }
300
+ if (toMs < fromMs) {
301
+ return -referenceBetween(cal, toMs, fromMs);
302
+ }
303
+
304
+ let totalMs = 0;
305
+ let day = referenceDayStart(cal, fromMs);
306
+ const lastDay = referenceDayStart(cal, toMs);
307
+ for (let i = 0; i < SCHEDULE_WORK_TIME_MAX_SPAN_DAYS; i++) {
308
+ for (const period of referencePeriods(cal, day)) {
309
+ const overlapStart = Math.max(period.startMs, fromMs);
310
+ const overlapEnd = Math.min(period.endMs, toMs);
311
+ if (overlapEnd > overlapStart) {
312
+ totalMs += overlapEnd - overlapStart;
313
+ }
314
+ }
315
+ if (day >= lastDay) {
316
+ return totalMs / 60_000;
317
+ }
318
+ day = day.plus({ days: 1 });
319
+ }
320
+ throw new Error('reference: span too long');
321
+ }
322
+
323
+ describe('workTime', () => {
324
+ it('snaps a start forward across a weekend', () => {
325
+ // Friday 2026-01-09 17:00 -> Monday 2026-01-12 08:00
326
+ expect(
327
+ snapToWorkingStart(calendar, la('2026-01-09', '17:00')).toISOString(),
328
+ ).toBe(la('2026-01-12', '08:00').toISOString());
329
+ // Saturday noon -> Monday 08:00
330
+ expect(
331
+ snapToWorkingStart(calendar, la('2026-01-10', '12:00')).toISOString(),
332
+ ).toBe(la('2026-01-12', '08:00').toISOString());
333
+ // Inside a period stays put
334
+ expect(
335
+ snapToWorkingStart(calendar, la('2026-01-12', '10:30')).toISOString(),
336
+ ).toBe(la('2026-01-12', '10:30').toISOString());
337
+ // Lunch moves to 13:00
338
+ expect(
339
+ snapToWorkingStart(calendar, la('2026-01-12', '12:15')).toISOString(),
340
+ ).toBe(la('2026-01-12', '13:00').toISOString());
341
+ });
342
+
343
+ it('snaps a finish backward across a weekend', () => {
344
+ expect(
345
+ snapToWorkingFinish(calendar, la('2026-01-10', '12:00')).toISOString(),
346
+ ).toBe(la('2026-01-09', '17:00').toISOString());
347
+ expect(
348
+ snapToWorkingFinish(calendar, la('2026-01-12', '08:00')).toISOString(),
349
+ ).toBe(la('2026-01-09', '17:00').toISOString());
350
+ expect(
351
+ snapToWorkingFinish(calendar, la('2026-01-12', '17:00')).toISOString(),
352
+ ).toBe(la('2026-01-12', '17:00').toISOString());
353
+ });
354
+
355
+ it('adds a working day inside one day and across lunch', () => {
356
+ expect(
357
+ addWorkingMinutes(calendar, la('2026-01-12', '08:00'), 480).toISOString(),
358
+ ).toBe(la('2026-01-12', '17:00').toISOString());
359
+ expect(
360
+ addWorkingMinutes(calendar, la('2026-01-12', '10:00'), 180).toISOString(),
361
+ ).toBe(la('2026-01-12', '14:00').toISOString());
362
+ });
363
+
364
+ it('adds working minutes across a weekend and subtracts them back', () => {
365
+ const start = la('2026-01-09', '13:00');
366
+ const finish = addWorkingMinutes(calendar, start, 480);
367
+ expect(finish.toISOString()).toBe(la('2026-01-12', '12:00').toISOString());
368
+ expect(addWorkingMinutes(calendar, finish, -480).toISOString()).toBe(
369
+ start.toISOString(),
370
+ );
371
+ expect(workingMinutesBetween(calendar, start, finish)).toBe(480);
372
+ expect(workingMinutesBetween(calendar, finish, start)).toBe(-480);
373
+ });
374
+
375
+ it('adds zero minutes without snapping', () => {
376
+ const saturday = la('2026-01-10', '12:00');
377
+ expect(addWorkingMinutes(calendar, saturday, 0)).toBe(saturday);
378
+ });
379
+
380
+ it('keeps working time constant across a daylight-saving transition', () => {
381
+ // Spring forward Sunday 2026-03-08; Friday 6th 08:00 PST + 2 days -> Monday 9th 17:00 PDT
382
+ const finish = addWorkingMinutes(calendar, la('2026-03-06', '08:00'), 960);
383
+ expect(finish.toISOString()).toBe(
384
+ la('2026-03-09', '17:00', '-07:00').toISOString(),
385
+ );
386
+ expect(
387
+ workingMinutesBetween(calendar, la('2026-03-06', '08:00'), finish),
388
+ ).toBe(960);
389
+ });
390
+
391
+ it('honours holidays and half days from exceptions', () => {
392
+ const withHoliday = {
393
+ ...calendar,
394
+ id: 'holiday',
395
+ exceptions: {
396
+ '2026-01-13': [],
397
+ '2026-01-14': [['08:00', '12:00']] as Array<[string, string]>,
398
+ },
399
+ };
400
+
401
+ // Monday 12th 08:00 + 2 days: Monday (8h) + Tuesday holiday + Wednesday half (4h) + Thursday 4h -> Thursday 12:00
402
+ expect(
403
+ addWorkingMinutes(
404
+ withHoliday,
405
+ la('2026-01-12', '08:00'),
406
+ 960,
407
+ ).toISOString(),
408
+ ).toBe(la('2026-01-15', '12:00').toISOString());
409
+ });
410
+
411
+ it('refuses an empty calendar', () => {
412
+ const empty = { id: 'empty', timeZone: ZONE, weekHours: {} };
413
+ expect(isWorkingCalendar(empty)).toBe(false);
414
+ expect(() => snapToWorkingStart(empty, new Date())).toThrow();
415
+ expect(() => buildWorkCalendarTable(empty, new Date(), new Date())).toThrow(
416
+ /no working time/,
417
+ );
418
+ });
419
+
420
+ it('reports minutes per day and validates week hours', () => {
421
+ expect(getWorkingMinutesPerDay(calendar)).toBe(480);
422
+ expect(
423
+ getWorkingMinutesPerDay({
424
+ id: 'x',
425
+ timeZone: ZONE,
426
+ weekHours: { '1': [['09:00', '15:00']] },
427
+ }),
428
+ ).toBe(360);
429
+
430
+ expect(
431
+ validateWeekHours({
432
+ '1': [
433
+ ['09:00', '12:00'],
434
+ ['11:00', '15:00'],
435
+ ],
436
+ }).weekHours,
437
+ ).toEqual({ '1': [['09:00', '15:00']] });
438
+ expect(validateWeekHours({ '7': [] }).error).toBeTruthy();
439
+ expect(validateWeekHours({ '1': [['15:00', '09:00']] }).error).toBeTruthy();
440
+ });
441
+ });
442
+
443
+ describe('workTime day table', () => {
444
+ it('builds a 23-hour spring-forward day with its working minutes intact', () => {
445
+ const table = buildWorkCalendarTable(
446
+ getSevenDayCalendar('dst-spring'),
447
+ utc('2026-03-07T12:00:00Z'),
448
+ utc('2026-03-09T12:00:00Z'),
449
+ );
450
+ const day = table.days.find((row) => row.dateKey === '2026-03-08')!;
451
+ const next = table.days[day.dayIndex + 1];
452
+
453
+ // Midnight EST is 05:00Z; the next midnight is EDT, 04:00Z
454
+ expect(day.dayStartMs).toBe(utc('2026-03-08T05:00:00Z').getTime());
455
+ expect(next.dayStartMs - day.dayStartMs).toBe(23 * 3_600_000);
456
+ expect(day.periods).toEqual([
457
+ {
458
+ startMs: utc('2026-03-08T12:00:00Z').getTime(),
459
+ endMs: utc('2026-03-08T16:00:00Z').getTime(),
460
+ },
461
+ {
462
+ startMs: utc('2026-03-08T17:00:00Z').getTime(),
463
+ endMs: utc('2026-03-08T21:00:00Z').getTime(),
464
+ },
465
+ ]);
466
+ expect(day.workingMinutes).toBe(480);
467
+ expect(next.cumulativeMinutesAtDayStart).toBe(
468
+ day.cumulativeMinutesAtDayStart + 480,
469
+ );
470
+ });
471
+
472
+ it('builds a 25-hour fall-back day with its working minutes intact', () => {
473
+ const table = buildWorkCalendarTable(
474
+ getSevenDayCalendar('dst-fall'),
475
+ utc('2026-10-31T12:00:00Z'),
476
+ utc('2026-11-02T12:00:00Z'),
477
+ );
478
+ const day = table.days.find((row) => row.dateKey === '2026-11-01')!;
479
+ const next = table.days[day.dayIndex + 1];
480
+
481
+ expect(day.dayStartMs).toBe(utc('2026-11-01T04:00:00Z').getTime());
482
+ expect(next.dayStartMs - day.dayStartMs).toBe(25 * 3_600_000);
483
+ expect(day.periods).toEqual([
484
+ {
485
+ startMs: utc('2026-11-01T13:00:00Z').getTime(),
486
+ endMs: utc('2026-11-01T17:00:00Z').getTime(),
487
+ },
488
+ {
489
+ startMs: utc('2026-11-01T18:00:00Z').getTime(),
490
+ endMs: utc('2026-11-01T22:00:00Z').getTime(),
491
+ },
492
+ ]);
493
+ expect(day.workingMinutes).toBe(480);
494
+ });
495
+
496
+ it('measures a period that straddles the fall-back hour in elapsed time', () => {
497
+ const table = buildWorkCalendarTable(
498
+ getSevenDayCalendar('dst-night', {
499
+ exceptions: { '2026-11-01': [['00:00', '06:00']] },
500
+ }),
501
+ utc('2026-11-01T12:00:00Z'),
502
+ utc('2026-11-01T12:00:00Z'),
503
+ );
504
+
505
+ // 00:00 EDT to 06:00 EST spans seven real hours (documented behaviour)
506
+ expect(table.days[0].workingMinutes).toBe(420);
507
+ });
508
+
509
+ it('ends a "24:00" period exactly at the next local midnight', () => {
510
+ const cal = getSevenDayCalendar('midnight', {
511
+ weekHours: {
512
+ '0': [['20:00', '24:00']],
513
+ '1': [['20:00', '24:00']],
514
+ },
515
+ });
516
+ const table = buildWorkCalendarTable(
517
+ cal,
518
+ utc('2026-11-01T12:00:00Z'),
519
+ utc('2026-11-03T12:00:00Z'),
520
+ );
521
+ const sunday = table.days[0];
522
+ const monday = table.days[1];
523
+
524
+ expect(sunday.dateKey).toBe('2026-11-01');
525
+ expect(sunday.periods[0].endMs).toBe(monday.dayStartMs);
526
+ expect(sunday.periods[0].startMs).toBe(ny('2026-11-01', '20:00').getTime());
527
+ expect(sunday.workingMinutes).toBe(240);
528
+ expect(monday.periods[0].endMs).toBe(table.days[2].dayStartMs);
529
+ expect(monday.workingMinutes).toBe(240);
530
+ expect(
531
+ addWorkingMinutes(cal, ny('2026-11-01', '20:00'), 240).getTime(),
532
+ ).toBe(monday.dayStartMs);
533
+ });
534
+
535
+ it('applies exceptions as holidays and half days', () => {
536
+ const table = buildWorkCalendarTable(
537
+ getSevenDayCalendar('exceptions', {
538
+ exceptions: {
539
+ '2026-01-13': [],
540
+ '2026-01-14': [['08:00', '12:00']],
541
+ },
542
+ }),
543
+ ny('2026-01-12', '00:00'),
544
+ ny('2026-01-15', '00:00'),
545
+ );
546
+
547
+ expect(table.days.map((day) => day.workingMinutes)).toEqual([
548
+ 480, 0, 240, 480,
549
+ ]);
550
+ expect(table.days[1].periods).toEqual([]);
551
+ expect(table.days.map((day) => day.cumulativeMinutesAtDayStart)).toEqual([
552
+ 0, 480, 480, 720,
553
+ ]);
554
+ expect(getWorkingMinutesOnDay(table, 2)).toBe(240);
555
+ expect(getDateKeyForDayIndex(table, 1)).toBe('2026-01-13');
556
+ expect(getDayStartMs(table, 3)).toBe(ny('2026-01-15', '00:00').getTime());
557
+ expect(() => getWorkingMinutesOnDay(table, 4)).toThrow(RangeError);
558
+ });
559
+
560
+ it('extends the memoized table backward and forward in place', () => {
561
+ const cal = getSevenDayCalendar('lazy');
562
+ const at = ny('2026-06-15', '09:00');
563
+ const table = getWorkCalendarTable(cal, at);
564
+ const initialFirst = table.firstDayStartMs;
565
+ const initialEnd = table.lastDayEndMs;
566
+ const initialCount = table.days.length;
567
+
568
+ expect(getDayIndexAt(table, at)).toBeGreaterThanOrEqual(0);
569
+ expect(table.days[0].dayIndex).toBe(0);
570
+
571
+ // Backward: same object, rows prepended, indices and totals rebuilt
572
+ const earlier = new Date(at.getTime() - 200 * DAY_MS);
573
+ expect(getWorkCalendarTable(cal, earlier)).toBe(table);
574
+ expect(table.firstDayStartMs).toBeLessThan(initialFirst);
575
+ expect(table.firstDayStartMs).toBeLessThanOrEqual(earlier.getTime());
576
+ expect(table.lastDayEndMs).toBe(initialEnd);
577
+ expect(table.days.length).toBeGreaterThan(initialCount);
578
+ expect(table.days.findIndex((day) => day.dayStartMs === initialFirst)).toBe(
579
+ table.days.length - initialCount,
580
+ );
581
+
582
+ // Forward: same object, rows appended
583
+ const later = new Date(at.getTime() + 400 * DAY_MS);
584
+ expect(getWorkCalendarTable(cal, later)).toBe(table);
585
+ expect(table.lastDayEndMs).toBeGreaterThan(later.getTime());
586
+
587
+ for (let i = 0; i < table.days.length; i++) {
588
+ expect(table.days[i].dayIndex).toBe(i);
589
+ if (i > 0) {
590
+ expect(table.days[i].cumulativeMinutesAtDayStart).toBe(
591
+ table.days[i - 1].cumulativeMinutesAtDayStart +
592
+ table.days[i - 1].workingMinutes,
593
+ );
594
+ expect(table.days[i].dayStartMs).toBeGreaterThan(
595
+ table.days[i - 1].dayStartMs,
596
+ );
597
+ }
598
+ }
599
+
600
+ // A request that cannot share the table starts a fresh one
601
+ const farAway = new Date(
602
+ at.getTime() + (SCHEDULE_WORK_TIME_MAX_SPAN_DAYS - 100) * DAY_MS,
603
+ );
604
+ const fresh = getWorkCalendarTable(cal, farAway);
605
+ expect(fresh).not.toBe(table);
606
+ expect(getDayIndexAt(fresh, farAway)).toBeGreaterThanOrEqual(0);
607
+ expect(getWorkCalendarTable(cal, farAway)).toBe(fresh);
608
+ });
609
+
610
+ it('refuses spans beyond the scan limit instead of truncating', () => {
611
+ const cal = getSevenDayCalendar('span');
612
+ const at = ny('2026-01-05', '08:00');
613
+ const limit = SCHEDULE_WORK_TIME_MAX_SPAN_DAYS;
614
+
615
+ expect(() =>
616
+ getWorkCalendarTable(
617
+ cal,
618
+ at,
619
+ new Date(at.getTime() + (limit + 1) * DAY_MS),
620
+ ),
621
+ ).toThrow(/exceeds/);
622
+ expect(() =>
623
+ buildWorkCalendarTable(
624
+ cal,
625
+ at,
626
+ new Date(at.getTime() + (limit + 1) * DAY_MS),
627
+ ),
628
+ ).toThrow(/exceeds/);
629
+ expect(() =>
630
+ workingMinutesBetween(
631
+ cal,
632
+ at,
633
+ new Date(
634
+ at.getTime() + (SCHEDULE_WORK_TIME_MAX_SPAN_DAYS + 1) * DAY_MS,
635
+ ),
636
+ ),
637
+ ).toThrow(/exceeds/);
638
+ expect(() =>
639
+ workingMinutesBetween(
640
+ cal,
641
+ new Date(
642
+ at.getTime() + (SCHEDULE_WORK_TIME_MAX_SPAN_DAYS + 1) * DAY_MS,
643
+ ),
644
+ at,
645
+ ),
646
+ ).toThrow(/exceeds/);
647
+
648
+ // Ten years still resolves
649
+ const tenYears = new Date(at.getTime() + 3_650 * DAY_MS);
650
+ expect(workingMinutesBetween(cal, at, tenYears)).toBe(3_650 * 480);
651
+ });
652
+
653
+ it('throws at once on an invalid time zone', () => {
654
+ const bad = {
655
+ ...getSevenDayCalendar('bad-zone'),
656
+ timeZone: 'Mars/Olympus',
657
+ };
658
+ const startedAt = performance.now();
659
+
660
+ expect(() => buildWorkCalendarTable(bad, new Date(), new Date())).toThrow(
661
+ /invalid time zone/,
662
+ );
663
+ expect(() => snapToWorkingStart(bad, new Date())).toThrow(
664
+ /invalid time zone/,
665
+ );
666
+ expect(() => addWorkingMinutes(bad, new Date(), 60)).toThrow(
667
+ /invalid time zone/,
668
+ );
669
+ expect(performance.now() - startedAt).toBeLessThan(250);
670
+ });
671
+
672
+ it('locates days by binary search at every edge', () => {
673
+ const cal = getSevenDayCalendar('edges');
674
+ const table = buildWorkCalendarTable(
675
+ cal,
676
+ ny('2026-01-05', '00:00'),
677
+ ny('2026-01-09', '00:00'),
678
+ );
679
+
680
+ expect(table.days).toHaveLength(5);
681
+ expect(getDayIndexAt(table, new Date(table.days[3].dayStartMs))).toBe(3);
682
+ expect(getDayIndexAt(table, new Date(table.days[3].dayStartMs - 1))).toBe(
683
+ 2,
684
+ );
685
+ expect(getDayIndexAt(table, new Date(table.firstDayStartMs))).toBe(0);
686
+ expect(getDayIndexAt(table, new Date(table.firstDayStartMs - 1))).toBe(-1);
687
+ expect(getDayIndexAt(table, new Date(table.lastDayEndMs - 1))).toBe(4);
688
+ expect(getDayIndexAt(table, new Date(table.lastDayEndMs))).toBe(5);
689
+ });
690
+
691
+ it('snaps instants exactly on period boundaries by the engine rules', () => {
692
+ const monday0800 = la('2026-01-12', '08:00');
693
+ const monday1200 = la('2026-01-12', '12:00');
694
+ const monday1300 = la('2026-01-12', '13:00');
695
+ const monday1700 = la('2026-01-12', '17:00');
696
+ const friday1700 = la('2026-01-09', '17:00');
697
+
698
+ // A start at a period start stays; at a period end moves to the next start
699
+ expect(snapToWorkingStart(calendar, monday0800).getTime()).toBe(
700
+ monday0800.getTime(),
701
+ );
702
+ expect(snapToWorkingStart(calendar, monday1200).getTime()).toBe(
703
+ monday1300.getTime(),
704
+ );
705
+ expect(snapToWorkingStart(calendar, monday1700).getTime()).toBe(
706
+ la('2026-01-13', '08:00').getTime(),
707
+ );
708
+ // A finish at a period end stays; at a period start moves to the previous end
709
+ expect(snapToWorkingFinish(calendar, monday1200).getTime()).toBe(
710
+ monday1200.getTime(),
711
+ );
712
+ expect(snapToWorkingFinish(calendar, monday1300).getTime()).toBe(
713
+ monday1200.getTime(),
714
+ );
715
+ expect(snapToWorkingFinish(calendar, monday0800).getTime()).toBe(
716
+ friday1700.getTime(),
717
+ );
718
+ // Adding lands on period ends going forward and period starts going back
719
+ expect(addWorkingMinutes(calendar, monday0800, 240).getTime()).toBe(
720
+ monday1200.getTime(),
721
+ );
722
+ expect(addWorkingMinutes(calendar, monday1700, -240).getTime()).toBe(
723
+ monday1300.getTime(),
724
+ );
725
+ expect(addWorkingMinutes(calendar, monday0800, -1).getTime()).toBe(
726
+ la('2026-01-09', '16:59').getTime(),
727
+ );
728
+ });
729
+
730
+ it('works on a night-shift calendar spanning midnight', () => {
731
+ const cal = getNightShiftCalendar('night');
732
+ const monday2200 = ny('2026-01-12', '22:00');
733
+ const tuesday0600 = ny('2026-01-13', '06:00');
734
+
735
+ expect(addWorkingMinutes(cal, monday2200, 480).getTime()).toBe(
736
+ tuesday0600.getTime(),
737
+ );
738
+ expect(addWorkingMinutes(cal, tuesday0600, -480).getTime()).toBe(
739
+ monday2200.getTime(),
740
+ );
741
+ expect(workingMinutesBetween(cal, monday2200, tuesday0600)).toBe(480);
742
+ expect(snapToWorkingStart(cal, tuesday0600).getTime()).toBe(
743
+ ny('2026-01-13', '22:00').getTime(),
744
+ );
745
+ expect(snapToWorkingFinish(cal, ny('2026-01-13', '06:30')).getTime()).toBe(
746
+ tuesday0600.getTime(),
747
+ );
748
+ expect(snapToWorkingStart(cal, ny('2026-01-13', '00:00')).getTime()).toBe(
749
+ ny('2026-01-13', '00:00').getTime(),
750
+ );
751
+ // Saturday 06:00 closes the week; Monday 22:00 opens the next
752
+ expect(snapToWorkingStart(cal, ny('2026-01-17', '06:00')).getTime()).toBe(
753
+ ny('2026-01-19', '22:00').getTime(),
754
+ );
755
+ expect(
756
+ addWorkingMinutes(cal, ny('2026-01-16', '22:00'), 481).getTime(),
757
+ ).toBe(ny('2026-01-19', '22:01').getTime());
758
+ });
759
+
760
+ it('lists the working days a span overlaps', () => {
761
+ const table = buildWorkCalendarTable(
762
+ calendar,
763
+ la('2026-01-05', '00:00'),
764
+ la('2026-01-18', '00:00'),
765
+ );
766
+
767
+ // Friday 15:00 to Tuesday 10:00 touches Friday, Monday and Tuesday
768
+ expect(
769
+ getWorkingDayIndicesBetween(
770
+ table,
771
+ la('2026-01-09', '15:00'),
772
+ la('2026-01-13', '10:00'),
773
+ ).map((index) => getDateKeyForDayIndex(table, index)),
774
+ ).toEqual(['2026-01-09', '2026-01-12', '2026-01-13']);
775
+ // Lunch and weekends overlap nothing
776
+ expect(
777
+ getWorkingDayIndicesBetween(
778
+ table,
779
+ la('2026-01-12', '12:00'),
780
+ la('2026-01-12', '13:00'),
781
+ ),
782
+ ).toEqual([]);
783
+ expect(
784
+ getWorkingDayIndicesBetween(
785
+ table,
786
+ la('2026-01-10', '00:00'),
787
+ la('2026-01-11', '23:00'),
788
+ ),
789
+ ).toEqual([]);
790
+ // Instants outside the table are clipped to it
791
+ expect(
792
+ getWorkingDayIndicesBetween(
793
+ table,
794
+ la('2025-12-01', '00:00'),
795
+ la('2026-01-06', '09:00'),
796
+ ),
797
+ ).toEqual([0, 1]);
798
+ expect(
799
+ getWorkingDayIndicesBetween(
800
+ table,
801
+ la('2026-01-06', '09:00'),
802
+ la('2026-01-06', '09:00'),
803
+ ),
804
+ ).toEqual([]);
805
+ });
806
+ });
807
+
808
+ describe('workTime equivalence with the reference walker', () => {
809
+ const calendars: ScheduleWorkCalendarDef[] = [
810
+ { ...getStandardWorkCalendarDef(ZONE), id: 'ref-standard' },
811
+ getSevenDayCalendar('ref-seven', {
812
+ exceptions: {
813
+ '2026-01-01': [],
814
+ '2026-05-25': [],
815
+ '2026-07-03': [['08:00', '12:00']],
816
+ '2026-11-26': [],
817
+ '2026-12-24': [['08:00', '12:00']],
818
+ '2026-12-25': [],
819
+ '2027-01-01': [],
820
+ '2027-03-14': [['06:00', '10:00']],
821
+ '2027-11-07': [['00:00', '06:00']],
822
+ },
823
+ }),
824
+ getNightShiftCalendar('ref-night'),
825
+ ];
826
+ const windowStartMs = utc('2026-01-01T00:00:00Z').getTime();
827
+ const windowMs = utc('2027-12-31T00:00:00Z').getTime() - windowStartMs;
828
+ const random = createRandom(0x5eed);
829
+
830
+ /*
831
+ * A random instant in the window; every third one lands on a whole minute
832
+ * so boundary cases are exercised, the rest carry milliseconds.
833
+ */
834
+ const randomInstantMs = (): number => {
835
+ const raw = windowStartMs + Math.floor(random() * windowMs);
836
+ return Math.floor(random() * 3) === 0 ? raw - (raw % 60_000) : raw;
837
+ };
838
+
839
+ for (const cal of calendars) {
840
+ it(`matches snap, add and between on ${cal.id}`, () => {
841
+ for (let i = 0; i < 1000; i++) {
842
+ const atMs = randomInstantMs();
843
+ const at = new Date(atMs);
844
+ const minutes =
845
+ Math.floor(random() * 2 * 30 * 480) -
846
+ 30 * 480 +
847
+ (i % 7 === 0 ? 0 : 1);
848
+ const otherMs = randomInstantMs();
849
+
850
+ expect(
851
+ snapToWorkingStart(cal, at).getTime(),
852
+ `snapToWorkingStart ${cal.id} ${at.toISOString()}`,
853
+ ).toBe(referenceSnapStart(cal, atMs));
854
+ expect(
855
+ snapToWorkingFinish(cal, at).getTime(),
856
+ `snapToWorkingFinish ${cal.id} ${at.toISOString()}`,
857
+ ).toBe(referenceSnapFinish(cal, atMs));
858
+ expect(
859
+ addWorkingMinutes(cal, at, minutes).getTime(),
860
+ `addWorkingMinutes ${cal.id} ${at.toISOString()} ${minutes}`,
861
+ ).toBe(referenceAdd(cal, atMs, minutes));
862
+ expect(
863
+ workingMinutesBetween(cal, at, new Date(otherMs)),
864
+ `workingMinutesBetween ${cal.id} ${at.toISOString()} ${otherMs}`,
865
+ ).toBe(referenceBetween(cal, atMs, otherMs));
866
+ }
867
+ });
868
+ }
869
+
870
+ it('round-trips add and between at period boundaries', () => {
871
+ const cal = calendars[1];
872
+ const table = buildWorkCalendarTable(
873
+ cal,
874
+ utc('2026-03-01T00:00:00Z'),
875
+ utc('2026-12-01T00:00:00Z'),
876
+ );
877
+
878
+ for (const day of table.days) {
879
+ for (const period of day.periods) {
880
+ for (const ms of [period.startMs, period.endMs]) {
881
+ const at = new Date(ms);
882
+ for (const minutes of [1, 239, 240, 480, 481, 2_400]) {
883
+ const forward = addWorkingMinutes(cal, at, minutes);
884
+ expect(workingMinutesBetween(cal, at, forward)).toBe(minutes);
885
+ expect(forward.getTime()).toBe(referenceAdd(cal, ms, minutes));
886
+ const backward = addWorkingMinutes(cal, at, -minutes);
887
+ expect(workingMinutesBetween(cal, backward, at)).toBe(minutes);
888
+ expect(backward.getTime()).toBe(referenceAdd(cal, ms, -minutes));
889
+ }
890
+ }
891
+ }
892
+ }
893
+ });
894
+ });
895
+
896
+ describe.runIf(process.env.BENCH === '1')('workTime benchmark', () => {
897
+ const DAY = 480;
898
+ const benchCalendars = { STANDARD: getStandardWorkCalendarDef(ZONE) };
899
+
900
+ /*
901
+ * A finish-to-start chain of 1-30 minute tasks. Durations are short so a
902
+ * fully serial 20,000-activity chain stays inside the ten-year table
903
+ * limit; engine cost does not depend on duration magnitude.
904
+ */
905
+ const buildChain = (count: number) => {
906
+ const random = createRandom(count);
907
+ const activities: CpmActivityInput[] = [];
908
+ const relationships: CpmRelationshipInput[] = [];
909
+ for (let i = 0; i < count; i++) {
910
+ activities.push({
911
+ id: `C${i}`,
912
+ type: 'TASK',
913
+ plannedDurationMinutes: 1 + Math.floor(random() * 30),
914
+ });
915
+ if (i > 0) {
916
+ relationships.push({
917
+ predecessorId: `C${i - 1}`,
918
+ successorId: `C${i}`,
919
+ type: 'FS',
920
+ lagMinutes: 0,
921
+ });
922
+ }
923
+ }
924
+ return { activities, relationships };
925
+ };
926
+
927
+ /*
928
+ * A construction-shaped DAG: 1-30 minute tasks, each fanning out to up to
929
+ * three successors within the next twenty ids, mixed relationship types
930
+ * and lags of -15..+15 minutes (short for the same reason as the chain).
931
+ */
932
+ const buildFanOut = (count: number) => {
933
+ const random = createRandom(count * 7 + 1);
934
+ const types: CpmRelationshipInput['type'][] = [
935
+ 'FS',
936
+ 'FS',
937
+ 'SS',
938
+ 'FF',
939
+ 'SF',
940
+ ];
941
+ const activities: CpmActivityInput[] = [];
942
+ const relationships: CpmRelationshipInput[] = [];
943
+ const seen = new Set<string>();
944
+ for (let i = 0; i < count; i++) {
945
+ activities.push({
946
+ id: `D${i}`,
947
+ type: 'TASK',
948
+ plannedDurationMinutes: 1 + Math.floor(random() * 30),
949
+ });
950
+ const fanOut = 1 + Math.floor(random() * 3);
951
+ for (let k = 0; k < fanOut; k++) {
952
+ const successor = i + 1 + Math.floor(random() * 20);
953
+ const key = `${i}-${successor}`;
954
+ if (successor >= count || seen.has(key)) {
955
+ continue;
956
+ }
957
+ seen.add(key);
958
+ relationships.push({
959
+ predecessorId: `D${i}`,
960
+ successorId: `D${successor}`,
961
+ type: types[Math.floor(random() * types.length)],
962
+ lagMinutes: (Math.floor(random() * 3) - 1) * 15,
963
+ });
964
+ }
965
+ }
966
+ return { activities, relationships };
967
+ };
968
+
969
+ /*
970
+ * Run the engine once and return the wall-clock milliseconds.
971
+ */
972
+ const timeRun = (network: ReturnType<typeof buildChain>): number => {
973
+ const startedAt = performance.now();
974
+ const result = runCriticalPathSchedule({
975
+ ...network,
976
+ calendars: benchCalendars,
977
+ defaultCalendarId: 'STANDARD',
978
+ projectStartAt: la('2026-01-05', '08:00'),
979
+ dataDateAt: la('2026-01-05', '08:00'),
980
+ });
981
+ const elapsed = performance.now() - startedAt;
982
+ expect(result.ok).toBe(true);
983
+ expect(result.activities).toHaveLength(network.activities.length);
984
+ return elapsed;
985
+ };
986
+
987
+ it('schedules 5,000-activity networks in under a second', () => {
988
+ const lines: string[] = [];
989
+
990
+ for (const count of [500, 2_000, 5_000, 20_000]) {
991
+ const chain = buildChain(count);
992
+ const fanOut = buildFanOut(count);
993
+ const chainMs = timeRun(chain);
994
+ const fanOutMs = timeRun(fanOut);
995
+ lines.push(
996
+ `${String(count).padStart(6)} activities: chain ${chainMs.toFixed(0).padStart(5)} ms (${chain.relationships.length} rels), fan-out DAG ${fanOutMs.toFixed(0).padStart(5)} ms (${fanOut.relationships.length} rels)`,
997
+ );
998
+
999
+ if (count === 5_000) {
1000
+ expect(chainMs).toBeLessThan(1_000);
1001
+ expect(fanOutMs).toBeLessThan(1_000);
1002
+ }
1003
+ }
1004
+
1005
+ console.log(`\nworkTime benchmark (BENCH=1)\n${lines.join('\n')}\n`);
1006
+ }, 600_000);
1007
+ });