@jsb188/schedule 1.1.12 → 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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +33 -14
  3. package/src/constants/schedule.ts +710 -306
  4. package/src/types/schedule.d.ts +1827 -456
  5. package/src/ui/ScheduleSettingsUI.tsx +21 -23
  6. package/src/utils/autofill.ts +469 -0
  7. package/src/utils/availability.ts +167 -0
  8. package/src/utils/candidates.ts +447 -0
  9. package/src/utils/coverage.helpers.ts +509 -554
  10. package/src/utils/coverage.ts +1121 -526
  11. package/src/utils/cpm.helpers.ts +27 -29
  12. package/src/utils/cpm.ts +53 -41
  13. package/src/utils/cpmLeveling.helpers.ts +89 -16
  14. package/src/utils/cpmLeveling.ts +28 -26
  15. package/src/utils/cycle.ts +325 -0
  16. package/src/utils/demand.ts +239 -0
  17. package/src/utils/eligibility.ts +553 -400
  18. package/src/utils/ids.ts +47 -0
  19. package/src/utils/laborRules.ts +740 -0
  20. package/src/utils/localTime.ts +312 -0
  21. package/src/utils/offer.ts +300 -0
  22. package/src/utils/planCsv.ts +73 -19
  23. package/src/utils/predicate.ts +111 -0
  24. package/src/utils/request.ts +212 -114
  25. package/src/utils/resource.ts +412 -112
  26. package/src/utils/rule.ts +697 -163
  27. package/src/utils/rulePresets.ts +116 -0
  28. package/src/utils/run.ts +0 -8
  29. package/src/utils/scheduleText.ts +4074 -0
  30. package/src/utils/shiftChange.ts +279 -0
  31. package/src/utils/standing.ts +730 -0
  32. package/src/utils/template.ts +619 -0
  33. package/src/utils/violation.ts +184 -0
  34. package/src/utils/workTime.ts +341 -120
  35. package/src/utils/defaults.ts +0 -8
  36. package/src/utils/recurrence.ts +0 -616
  37. package/src/utils/series.ts +0 -161
  38. package/src/utils/slot.ts +0 -208
  39. package/tests/coverage.fixtures.ts +0 -111
  40. package/tests/coverage.test.ts +0 -503
  41. package/tests/cpm.bench.test.ts +0 -154
  42. package/tests/cpm.test.ts +0 -354
  43. package/tests/cpmCorrectness.test.ts +0 -327
  44. package/tests/cpmLeveling.test.ts +0 -471
  45. package/tests/eligibility.test.ts +0 -320
  46. package/tests/gantt-geometry.test.ts +0 -367
  47. package/tests/gantt-histogram.test.ts +0 -78
  48. package/tests/gantt-keyboard.test.ts +0 -69
  49. package/tests/helpers/cpmFixtures.ts +0 -101
  50. package/tests/projectInputs.test.ts +0 -165
  51. package/tests/recurrence.test.ts +0 -68
  52. package/tests/request.test.ts +0 -99
  53. package/tests/resource.test.ts +0 -95
  54. package/tests/rule.test.ts +0 -98
  55. package/tests/series.test.ts +0 -120
  56. package/tests/workTime.test.ts +0 -1007
  57. package/tests/workTimeContracts.test.ts +0 -111
  58. package/tsconfig.json +0 -13
  59. package/vitest.config.ts +0 -8
@@ -8,6 +8,11 @@ import type {
8
8
  ScheduleWorkCalendarDef,
9
9
  ScheduleWorkInterval,
10
10
  } from '../types/schedule.d.ts';
11
+ import {
12
+ addScheduleDays,
13
+ formatScheduleClockTime,
14
+ toScheduleTimeMs,
15
+ } from './localTime.ts';
11
16
 
12
17
  /**
13
18
  * Working-time arithmetic.
@@ -18,6 +23,19 @@ import type {
18
23
  * "five days" starting Wednesday finishes the following Tuesday, and a lag
19
24
  * of one day across New Year skips the holiday.
20
25
  *
26
+ * An interval whose end is at or before its start crosses midnight: a bar's
27
+ * Friday "20:00"-"02:00" works until 02:00 on Saturday, and an equal pair is
28
+ * 24 hours ("00:00"-"00:00" is the whole day, as "00:00"-"24:00"). The part
29
+ * after midnight (the spill) belongs to the start's day, the business day:
30
+ *
31
+ * - a dated exception on Saturday (a holiday) replaces Saturday's own hours
32
+ * but keeps Friday's spill
33
+ * - an exception on Friday replaces Friday's hours, spill included; its own
34
+ * wrapped intervals spill into Saturday
35
+ *
36
+ * A day's own hours and the previous day's spill are merged, so overlapping
37
+ * hours count once.
38
+ *
21
39
  * Two conventions keep start and finish dates readable to planners, and the
22
40
  * engine relies on both:
23
41
  *
@@ -32,15 +50,18 @@ import type {
32
50
  *
33
51
  * Instants are JS Dates (UTC); the calendar's IANA zone decides which local
34
52
  * day each instant belongs to. Clock times are placed on each local day's own
35
- * start, so a day-shift calendar keeps its working minutes across a
36
- * daylight-saving transition; a period that straddles the transition itself
37
- * (a night shift on the fall-back day) is measured in elapsed time.
53
+ * start (a spill on the day it runs into), so a day-shift calendar keeps its
54
+ * working minutes across a daylight-saving transition; a period that
55
+ * straddles the transition itself (a night shift on the fall-back day) is
56
+ * measured in elapsed time, and a bound inside a spring-forward gap moves
57
+ * forward by the gap.
38
58
  *
39
59
  * All arithmetic runs on a DAY TABLE: one row per local day holding the
40
- * day's working periods as UTC milliseconds and the cumulative working
41
- * minutes at the day's start. Luxon is used only to build rows; every
42
- * operation is then a binary search over the table plus a walk of one day's
43
- * periods, so cost no longer grows with the number of days spanned.
60
+ * day's working periods as UTC milliseconds (sorted, disjoint, inside the
61
+ * day) and the cumulative working minutes at the day's start. Luxon is used
62
+ * only to build rows; every operation is then a binary search over the table
63
+ * plus a walk of one day's periods, so cost no longer grows with the number
64
+ * of days spanned.
44
65
  */
45
66
 
46
67
  /* An arithmetic request exceeds the supported forty-year calendar span. */
@@ -99,9 +120,26 @@ export interface WorkCalendarTable {
99
120
  lastDayEndMs: number;
100
121
  }
101
122
 
123
+ // One day list (weekday or exception) read into minutes
124
+ interface WorkDayRule {
125
+ // The day's own periods as [from, to] minutes on the day, merged, to <= 1440
126
+ own: Array<[number, number]>;
127
+ // Minutes past the next midnight its wrapped intervals reach (0 = none)
128
+ spillMinutes: number;
129
+ }
130
+
131
+ // The parsed day lists of one calendar
132
+ interface WorkDayRules {
133
+ weekdays: WorkDayRule[]; // index 0 = Sunday
134
+ exceptions: Map<string, WorkDayRule>;
135
+ }
136
+
102
137
  // Per-calendar memo of the lazily extended day table
103
138
  const TABLE_CACHE = new WeakMap<ScheduleWorkCalendarDef, WorkCalendarTable>();
104
139
 
140
+ // Per-calendar memo of the parsed day lists (defs are never mutated after use)
141
+ const DAY_RULE_CACHE = new WeakMap<ScheduleWorkCalendarDef, WorkDayRules>();
142
+
105
143
  const FILE_CONSTANTS = {
106
144
  standardWeekHours: {
107
145
  '1': [
@@ -127,6 +165,7 @@ const FILE_CONSTANTS = {
127
165
  } as ScheduleWeekHoursObj,
128
166
  standardMinutesPerDay: 480,
129
167
  fallbackMinutesPerDay: 480,
168
+ dayMinutes: 1440,
130
169
  dayMs: 86_400_000,
131
170
  minuteMs: 60_000,
132
171
  // Days added around a requested range so nearby instants need no extension
@@ -158,13 +197,13 @@ export function getStandardWorkCalendarDef(
158
197
  */
159
198
 
160
199
  export function toWorkTimeDate(value: Date | string | number): Date {
161
- const date = value instanceof Date ? value : new Date(value);
200
+ const ms = toScheduleTimeMs(value);
162
201
 
163
- if (Number.isNaN(date.getTime())) {
202
+ if (Number.isNaN(ms)) {
164
203
  throw new Error(`Invalid instant: ${String(value)}`);
165
204
  }
166
205
 
167
- return date;
206
+ return value instanceof Date ? value : new Date(ms);
168
207
  }
169
208
 
170
209
  /*
@@ -189,10 +228,81 @@ function parseClockMinutes(value: string): number | null {
189
228
  return hours * 60 + minutes;
190
229
  }
191
230
 
231
+ /*
232
+ * Read one [from, to] pair as minutes on its start day's axis: an end at or
233
+ * before the start ends on the next day, so it becomes [from, to + 1440].
234
+ * Null when a bound is malformed or the start is "24:00". Every range starts
235
+ * before 1440 and ends before 2880, so a spill never reaches a second day.
236
+ */
237
+
238
+ function readIntervalMinutes(
239
+ interval: ScheduleWorkInterval,
240
+ ): [number, number] | null {
241
+ const from = parseClockMinutes(interval[0]);
242
+ const to = parseClockMinutes(interval[1]);
243
+
244
+ if (from === null || to === null || from >= FILE_CONSTANTS.dayMinutes) {
245
+ return null;
246
+ }
247
+
248
+ return [from, to > from ? to : to + FILE_CONSTANTS.dayMinutes];
249
+ }
250
+
251
+ /*
252
+ * Sort minute ranges by start and merge the ones that overlap or touch. With
253
+ * a maximum length, two ranges whose union would be longer stay apart.
254
+ */
255
+
256
+ function mergeMinuteRanges(
257
+ ranges: Array<[number, number]>,
258
+ maxLength = Number.POSITIVE_INFINITY,
259
+ ): Array<[number, number]> {
260
+ const sorted = [...ranges].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
261
+ const merged: Array<[number, number]> = [];
262
+
263
+ for (const [from, to] of sorted) {
264
+ const last = merged[merged.length - 1];
265
+
266
+ if (
267
+ last &&
268
+ from <= last[1] &&
269
+ Math.max(last[1], to) - last[0] <= maxLength
270
+ ) {
271
+ last[1] = Math.max(last[1], to);
272
+ } else {
273
+ merged.push([from, to]);
274
+ }
275
+ }
276
+
277
+ return merged;
278
+ }
279
+
280
+ /*
281
+ * Format a range of at most 24 hours back into a stored pair: an end past
282
+ * midnight is written on the next day's clock (so it reads at or before the
283
+ * start), and an end exactly at midnight is "24:00".
284
+ */
285
+
286
+ function formatIntervalMinutes([from, to]: [
287
+ number,
288
+ number,
289
+ ]): ScheduleWorkInterval {
290
+ return [
291
+ formatScheduleClockTime(from),
292
+ to === FILE_CONSTANTS.dayMinutes
293
+ ? '24:00'
294
+ : formatScheduleClockTime(to % FILE_CONSTANTS.dayMinutes),
295
+ ];
296
+ }
297
+
192
298
  /**
193
- * Validate one list of "HH:mm" intervals; returns the normalized, merged,
194
- * ascending list or an error message. Used on every calendar write so the
195
- * engine never meets an interval it cannot walk.
299
+ * Validate one list of "HH:mm" intervals; returns the normalized ascending
300
+ * list or an error message. Used on every calendar write so the engine never
301
+ * meets an interval it cannot walk. An end at or before the start ends on
302
+ * the next day; a start of "24:00" is refused. Overlapping or touching
303
+ * intervals are merged unless their union would run longer than 24 hours,
304
+ * which one pair cannot express: those stay apart, and the day table merges
305
+ * them. Validating the output again returns it unchanged.
196
306
  */
197
307
 
198
308
  export function validateWorkIntervals(input: unknown): {
@@ -203,50 +313,30 @@ export function validateWorkIntervals(input: unknown): {
203
313
  return { error: 'Working hours must be a list of [from, to] pairs.' };
204
314
  }
205
315
 
206
- const parsed: Array<[number, number]> = [];
316
+ const ranges: Array<[number, number]> = [];
207
317
 
208
318
  for (const item of input) {
209
319
  if (!Array.isArray(item) || item.length !== 2) {
210
320
  return { error: 'Each working interval must be a [from, to] pair.' };
211
321
  }
212
322
 
213
- const from = parseClockMinutes(item[0]);
214
- const to = parseClockMinutes(item[1]);
323
+ const range = readIntervalMinutes(item as ScheduleWorkInterval);
215
324
 
216
- if (from === null || to === null) {
325
+ if (!range) {
217
326
  return {
218
- error: `Working interval times must be "HH:mm": ${JSON.stringify(item)}.`,
327
+ error:
328
+ parseClockMinutes(item[0]) === FILE_CONSTANTS.dayMinutes
329
+ ? `A working interval cannot start at 24:00: ${JSON.stringify(item)}.`
330
+ : `Working interval times must be "HH:mm": ${JSON.stringify(item)}.`,
219
331
  };
220
332
  }
221
333
 
222
- if (to <= from) {
223
- return {
224
- error: `A working interval must end after it starts: ${JSON.stringify(item)}.`,
225
- };
226
- }
227
-
228
- parsed.push([from, to]);
229
- }
230
-
231
- parsed.sort((a, b) => a[0] - b[0]);
232
-
233
- // Merge touching or overlapping intervals so the walker sees each minute once
234
- const merged: Array<[number, number]> = [];
235
- for (const interval of parsed) {
236
- const last = merged[merged.length - 1];
237
- if (last && interval[0] <= last[1]) {
238
- last[1] = Math.max(last[1], interval[1]);
239
- } else {
240
- merged.push([interval[0], interval[1]]);
241
- }
334
+ ranges.push(range);
242
335
  }
243
336
 
244
- const format = (minutes: number) =>
245
- `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
246
-
247
337
  return {
248
- intervals: merged.map(
249
- ([from, to]) => [format(from), format(to)] as ScheduleWorkInterval,
338
+ intervals: mergeMinuteRanges(ranges, FILE_CONSTANTS.dayMinutes).map(
339
+ formatIntervalMinutes,
250
340
  ),
251
341
  };
252
342
  }
@@ -307,9 +397,82 @@ export function isWorkingCalendar(calendar: ScheduleWorkCalendarDef): boolean {
307
397
  );
308
398
  }
309
399
 
400
+ /*
401
+ * Read one day list (weekday or exception) into its own periods and the
402
+ * spill its wrapped intervals carry into the next day. Malformed pairs are
403
+ * skipped: the write path validates, and the engine must still walk.
404
+ */
405
+
406
+ function toWorkDayRule(
407
+ intervals: ScheduleWorkInterval[] | null | undefined,
408
+ ): WorkDayRule {
409
+ const ranges: Array<[number, number]> = [];
410
+
411
+ for (const interval of intervals || []) {
412
+ const range = readIntervalMinutes(interval);
413
+ if (range) {
414
+ ranges.push(range);
415
+ }
416
+ }
417
+
418
+ const rule: WorkDayRule = { own: [], spillMinutes: 0 };
419
+
420
+ // Fully merged ranges are disjoint, so clipping at midnight keeps them so
421
+ for (const [from, to] of mergeMinuteRanges(ranges)) {
422
+ rule.own.push([from, Math.min(to, FILE_CONSTANTS.dayMinutes)]);
423
+ rule.spillMinutes = Math.max(
424
+ rule.spillMinutes,
425
+ to - FILE_CONSTANTS.dayMinutes,
426
+ );
427
+ }
428
+
429
+ return rule;
430
+ }
431
+
432
+ /*
433
+ * Return the parsed day lists of one calendar, built once per def.
434
+ */
435
+
436
+ function getWorkDayRules(calendar: ScheduleWorkCalendarDef): WorkDayRules {
437
+ let rules = DAY_RULE_CACHE.get(calendar);
438
+
439
+ if (!rules) {
440
+ rules = {
441
+ weekdays: Array.from({ length: 7 }, (_, weekday) =>
442
+ toWorkDayRule(
443
+ calendar.weekHours?.[String(weekday) as keyof ScheduleWeekHoursObj],
444
+ ),
445
+ ),
446
+ exceptions: new Map(
447
+ Object.entries(calendar.exceptions || {}).map(([dateKey, hours]) => [
448
+ dateKey,
449
+ toWorkDayRule(hours),
450
+ ]),
451
+ ),
452
+ };
453
+ DAY_RULE_CACHE.set(calendar, rules);
454
+ }
455
+
456
+ return rules;
457
+ }
458
+
459
+ /*
460
+ * Resolve the day list that applies to one local date: a dated exception
461
+ * wins outright over the weekly pattern (weekday 0 = Sunday).
462
+ */
463
+
464
+ function getWorkDayRule(
465
+ rules: WorkDayRules,
466
+ dateKey: string,
467
+ weekday: number,
468
+ ): WorkDayRule {
469
+ return rules.exceptions.get(dateKey) ?? rules.weekdays[weekday];
470
+ }
471
+
310
472
  /**
311
473
  * Return how many working minutes one "day" of duration represents on a
312
- * calendar: the explicit setting, else the longest working weekday.
474
+ * calendar: the explicit setting, else the longest working weekday. A
475
+ * wrapped interval counts in full for the weekday it starts on.
313
476
  */
314
477
 
315
478
  export function getWorkingMinutesPerDay(
@@ -321,18 +484,10 @@ export function getWorkingMinutesPerDay(
321
484
 
322
485
  let longest = 0;
323
486
 
324
- for (const intervals of Object.values(calendar.weekHours || {})) {
325
- let total = 0;
326
- for (const [from, to] of intervals || []) {
327
- const fromMinutes = parseClockMinutes(from);
328
- const toMinutes = parseClockMinutes(to);
329
- if (
330
- fromMinutes !== null &&
331
- toMinutes !== null &&
332
- toMinutes > fromMinutes
333
- ) {
334
- total += toMinutes - fromMinutes;
335
- }
487
+ for (const rule of getWorkDayRules(calendar).weekdays) {
488
+ let total = rule.spillMinutes;
489
+ for (const [from, to] of rule.own) {
490
+ total += to - from;
336
491
  }
337
492
  longest = Math.max(longest, total);
338
493
  }
@@ -340,6 +495,83 @@ export function getWorkingMinutesPerDay(
340
495
  return longest || FILE_CONSTANTS.fallbackMinutesPerDay;
341
496
  }
342
497
 
498
+ /*
499
+ * Place minutes of one local day on its own start (a bound in a
500
+ * spring-forward gap moves forward); 1440 is the next local midnight.
501
+ */
502
+
503
+ function getLocalDayMinuteMs(
504
+ dayStart: DateTime,
505
+ nextDayStart: DateTime,
506
+ minutes: number,
507
+ ): number {
508
+ if (minutes >= FILE_CONSTANTS.dayMinutes) {
509
+ return nextDayStart.toMillis();
510
+ }
511
+
512
+ return dayStart
513
+ .set({
514
+ hour: Math.floor(minutes / 60),
515
+ minute: minutes % 60,
516
+ second: 0,
517
+ millisecond: 0,
518
+ })
519
+ .toMillis();
520
+ }
521
+
522
+ /**
523
+ * Return when the work of one local date ("YYYY-MM-DD") starts and ends on a
524
+ * calendar: the start of its first own interval and the end of its last (a
525
+ * wrapped interval ends past midnight). Hours spilled into it from the day
526
+ * before belong to that day. A date without its own working time spans its
527
+ * whole local day (midnight to the next midnight). Throws on an invalid date
528
+ * or zone.
529
+ */
530
+
531
+ export function getWorkingDayBounds(
532
+ calendar: ScheduleWorkCalendarDef,
533
+ dateKey: string,
534
+ ): { startAt: Date; endAt: Date } {
535
+ const dayStart = DateTime.fromISO(dateKey, {
536
+ zone: calendar.timeZone,
537
+ }).startOf('day');
538
+
539
+ if (!dayStart.isValid || dayStart.toISODate() !== dateKey) {
540
+ throw new RangeError(
541
+ `Work calendar ${calendar.id}: ${dateKey} is not a local date in ${calendar.timeZone}`,
542
+ );
543
+ }
544
+
545
+ const nextDayStart = dayStart.plus({ days: 1 });
546
+ const rule = getWorkDayRule(
547
+ getWorkDayRules(calendar),
548
+ dateKey,
549
+ dayStart.weekday % 7,
550
+ );
551
+ const first = rule.own[0];
552
+ const last = rule.own[rule.own.length - 1];
553
+
554
+ if (!first) {
555
+ return {
556
+ startAt: new Date(dayStart.toMillis()),
557
+ endAt: new Date(nextDayStart.toMillis()),
558
+ };
559
+ }
560
+
561
+ const endMs = rule.spillMinutes
562
+ ? getLocalDayMinuteMs(
563
+ nextDayStart,
564
+ nextDayStart.plus({ days: 1 }),
565
+ rule.spillMinutes,
566
+ )
567
+ : getLocalDayMinuteMs(dayStart, nextDayStart, last[1]);
568
+
569
+ return {
570
+ startAt: new Date(getLocalDayMinuteMs(dayStart, nextDayStart, first[0])),
571
+ endAt: new Date(endMs),
572
+ };
573
+ }
574
+
343
575
  /*
344
576
  * Refuse to walk a calendar with no working time; the table span bound below
345
577
  * is the second line of defence for a calendar whose only hours are
@@ -370,33 +602,38 @@ function getSpanError(
370
602
  }
371
603
 
372
604
  /*
373
- * Resolve the raw "HH:mm" intervals that apply to one local date: a dated
374
- * exception wins outright over the weekly pattern.
605
+ * Sort one day's periods and merge the ones that overlap or touch (the
606
+ * previous day's spill against the day's own hours), in place.
375
607
  */
376
608
 
377
- function getRawIntervalsForDay(
378
- calendar: ScheduleWorkCalendarDef,
379
- dateKey: string,
380
- weekday: number,
381
- ): ScheduleWorkInterval[] {
382
- const exception = calendar.exceptions?.[dateKey];
383
-
384
- if (exception !== undefined) {
385
- return exception || [];
609
+ function mergeDayPeriods(periods: WorkCalendarDay['periods']): void {
610
+ if (periods.length < 2) {
611
+ return;
386
612
  }
387
613
 
388
- // Luxon weekdays run 1 (Monday) to 7 (Sunday); keys use 0 (Sunday) to 6
389
- const weekdayKey = String(weekday % 7) as keyof ScheduleWeekHoursObj;
614
+ periods.sort((a, b) => a.startMs - b.startMs);
615
+
616
+ let last = 0;
617
+
618
+ for (let i = 1; i < periods.length; i++) {
619
+ if (periods[i].startMs <= periods[last].endMs) {
620
+ periods[last].endMs = Math.max(periods[last].endMs, periods[i].endMs);
621
+ } else {
622
+ periods[++last] = periods[i];
623
+ }
624
+ }
390
625
 
391
- return calendar.weekHours?.[weekdayKey] || [];
626
+ periods.length = last + 1;
392
627
  }
393
628
 
394
629
  /*
395
- * Build one table row from a local midnight and the following one. Clock
396
- * times are placed on the day's own start; when the day holds no offset
397
- * change that is plain arithmetic, otherwise luxon resolves each bound so a
398
- * spring-forward gap moves a 02:30 boundary forward rather than dropping the
399
- * period. "24:00" ends exactly at the next day's start.
630
+ * Build one table row from a local midnight and the following one: the
631
+ * day's own periods plus the previous day's spill (from the previous day's
632
+ * exception, else its weekday), merged. Clock times are placed on the day's
633
+ * own start; when the day holds no offset change that is plain arithmetic,
634
+ * otherwise luxon resolves each bound so a spring-forward gap moves a 02:30
635
+ * boundary forward rather than dropping the period. "24:00", and the end of
636
+ * an interval that runs past midnight, end exactly at the next day's start.
400
637
  */
401
638
 
402
639
  function buildWorkCalendarDay(
@@ -412,7 +649,7 @@ function buildWorkCalendarDay(
412
649
  dayStart.offset === nextDayStart.offset;
413
650
 
414
651
  const toInstantMs = (minutes: number): number => {
415
- if (minutes === 1440) {
652
+ if (minutes === FILE_CONSTANTS.dayMinutes) {
416
653
  return nextDayStartMs;
417
654
  }
418
655
 
@@ -430,36 +667,39 @@ function buildWorkCalendarDay(
430
667
  .toMillis();
431
668
  };
432
669
 
670
+ // Luxon weekdays run 1 (Monday) to 7 (Sunday); rules use 0 (Sunday) to 6
671
+ const weekday = dayStart.weekday % 7;
672
+ const rules = getWorkDayRules(calendar);
673
+ // Without exceptions every lookup falls back to the weekday, so skip the date
674
+ const previous = getWorkDayRule(
675
+ rules,
676
+ rules.exceptions.size ? addScheduleDays(dateKey, -1) : '',
677
+ (weekday + 6) % 7,
678
+ );
433
679
  const periods: WorkCalendarDay['periods'] = [];
434
- let workingMs = 0;
435
-
436
- for (const [from, to] of getRawIntervalsForDay(
437
- calendar,
438
- dateKey,
439
- dayStart.weekday,
440
- )) {
441
- const fromMinutes = parseClockMinutes(from);
442
- const toMinutes = parseClockMinutes(to);
443
680
 
444
- if (
445
- fromMinutes === null ||
446
- toMinutes === null ||
447
- toMinutes <= fromMinutes
448
- ) {
449
- continue;
450
- }
681
+ if (previous.spillMinutes > 0) {
682
+ periods.push({
683
+ startMs: dayStartMs,
684
+ endMs: toInstantMs(previous.spillMinutes),
685
+ });
686
+ }
451
687
 
452
- const startMs = toInstantMs(fromMinutes);
453
- const endMs = toInstantMs(toMinutes);
688
+ for (const [from, to] of getWorkDayRule(rules, dateKey, weekday).own) {
689
+ const startMs = toInstantMs(from);
690
+ const endMs = toInstantMs(to);
454
691
 
455
692
  if (endMs > startMs) {
456
693
  periods.push({ startMs, endMs });
457
- workingMs += endMs - startMs;
458
694
  }
459
695
  }
460
696
 
461
- if (periods.length > 1) {
462
- periods.sort((a, b) => a.startMs - b.startMs);
697
+ mergeDayPeriods(periods);
698
+
699
+ let workingMs = 0;
700
+
701
+ for (const period of periods) {
702
+ workingMs += period.endMs - period.startMs;
463
703
  }
464
704
 
465
705
  return {
@@ -1295,28 +1535,6 @@ export function getWorkingDayIndicesBetween(
1295
1535
  return indices;
1296
1536
  }
1297
1537
 
1298
- /**
1299
- * Convert working minutes into calendar "days" for display.
1300
- */
1301
-
1302
- export function workingMinutesToDays(
1303
- calendar: ScheduleWorkCalendarDef,
1304
- minutes: number,
1305
- ): number {
1306
- return minutes / getWorkingMinutesPerDay(calendar);
1307
- }
1308
-
1309
- /**
1310
- * Convert calendar "days" into working minutes for storage.
1311
- */
1312
-
1313
- export function workingDaysToMinutes(
1314
- calendar: ScheduleWorkCalendarDef,
1315
- days: number,
1316
- ): number {
1317
- return Math.round(days * getWorkingMinutesPerDay(calendar));
1318
- }
1319
-
1320
1538
  /* Find a local-date row; outside dates return the corresponding table sentinel. */
1321
1539
  export function getDayIndexForDateKey(
1322
1540
  table: WorkCalendarTable,
@@ -1356,7 +1574,10 @@ export function getWorkingMinutesOnDayBetween(
1356
1574
  return minutes;
1357
1575
  }
1358
1576
 
1359
- /* Return merged working intervals intersecting a half-open instant range. */
1577
+ /*
1578
+ * Return merged working intervals intersecting a half-open instant range; an
1579
+ * interval running past midnight comes back whole (Fri 20:00 to Sat 02:00).
1580
+ */
1360
1581
  export function getWorkingIntervalsInRange(
1361
1582
  calendar: ScheduleWorkCalendarDef,
1362
1583
  from: Date,
@@ -1,8 +0,0 @@
1
- import { SCHEDULE_DEFAULTS_BY_OPERATION, SCHEDULE_DEFAULT_SURFACE } from '../constants/schedule.ts';
2
-
3
- /* Resolve an organization's preferred surface while leaving both scheduling tools available. */
4
- export function getScheduleDefaultSurface(operation?: string | null, settings?: {schedule?: {defaultSurface?: string | null} | null} | null): 'PROJECT' | 'COVERAGE' {
5
- const override = settings?.schedule?.defaultSurface;
6
- if (override === 'PROJECT' || override === 'COVERAGE') return override;
7
- return SCHEDULE_DEFAULTS_BY_OPERATION[operation as keyof typeof SCHEDULE_DEFAULTS_BY_OPERATION]?.defaultSurface || SCHEDULE_DEFAULT_SURFACE;
8
- }