@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.
- package/package.json +61 -0
- package/src/constants/schedule.ts +549 -0
- package/src/css.d.ts +7 -0
- package/src/libs/gantt-geometry.ts +771 -0
- package/src/libs/gantt-histogram.ts +124 -0
- package/src/libs/gantt-keyboard.ts +113 -0
- package/src/libs/gantt-state.ts +57 -0
- package/src/libs/gantt-url.ts +63 -0
- package/src/modules/Gantt.helpers.ts +138 -0
- package/src/modules/Gantt.tsx +719 -0
- package/src/types/schedule.d.ts +1149 -0
- package/src/ui/ActivityFormUI.tsx +133 -0
- package/src/ui/GanttEditorsUI.tsx +102 -0
- package/src/ui/GanttHistogramUI.tsx +236 -0
- package/src/ui/GanttUI.tsx +792 -0
- package/src/ui/ProjectFormUI.tsx +273 -0
- package/src/ui/ProjectMobileListUI.tsx +80 -0
- package/src/ui/ProjectToolbarUI.tsx +54 -0
- package/src/ui/RelationshipListUI.tsx +176 -0
- package/src/ui/ScheduleRunUI.tsx +173 -0
- package/src/ui/ScheduleSettingsUI.tsx +420 -0
- package/src/utils/coverage.helpers.ts +679 -0
- package/src/utils/coverage.ts +630 -0
- package/src/utils/cpm.helpers.ts +674 -0
- package/src/utils/cpm.ts +907 -0
- package/src/utils/cpmLeveling.helpers.ts +564 -0
- package/src/utils/cpmLeveling.ts +367 -0
- package/src/utils/defaults.ts +8 -0
- package/src/utils/eligibility.ts +457 -0
- package/src/utils/planCsv.ts +344 -0
- package/src/utils/predecessorText.ts +96 -0
- package/src/utils/recurrence.ts +616 -0
- package/src/utils/request.ts +153 -0
- package/src/utils/resource.ts +182 -0
- package/src/utils/rule.ts +216 -0
- package/src/utils/run.ts +43 -0
- package/src/utils/series.ts +161 -0
- package/src/utils/slot.ts +208 -0
- package/src/utils/workTime.ts +1382 -0
- package/tests/coverage.fixtures.ts +111 -0
- package/tests/coverage.test.ts +503 -0
- package/tests/cpm.bench.test.ts +154 -0
- package/tests/cpm.test.ts +354 -0
- package/tests/cpmCorrectness.test.ts +327 -0
- package/tests/cpmLeveling.test.ts +471 -0
- package/tests/eligibility.test.ts +320 -0
- package/tests/gantt-geometry.test.ts +367 -0
- package/tests/gantt-histogram.test.ts +78 -0
- package/tests/gantt-keyboard.test.ts +69 -0
- package/tests/helpers/cpmFixtures.ts +101 -0
- package/tests/projectInputs.test.ts +165 -0
- package/tests/recurrence.test.ts +68 -0
- package/tests/request.test.ts +99 -0
- package/tests/resource.test.ts +95 -0
- package/tests/rule.test.ts +98 -0
- package/tests/series.test.ts +120 -0
- package/tests/workTime.test.ts +1007 -0
- package/tests/workTimeContracts.test.ts +111 -0
- package/tsconfig.json +13 -0
- package/vitest.config.ts +8 -0
|
@@ -0,0 +1,1382 @@
|
|
|
1
|
+
import { DateTime, IANAZone } from 'luxon';
|
|
2
|
+
import {
|
|
3
|
+
SCHEDULE_STANDARD_WORK_CALENDAR_KEY,
|
|
4
|
+
SCHEDULE_WORK_TIME_MAX_SPAN_DAYS,
|
|
5
|
+
} from '../constants/schedule.ts';
|
|
6
|
+
import type {
|
|
7
|
+
ScheduleWeekHoursObj,
|
|
8
|
+
ScheduleWorkCalendarDef,
|
|
9
|
+
ScheduleWorkInterval,
|
|
10
|
+
} from '../types/schedule.d.ts';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Working-time arithmetic.
|
|
14
|
+
*
|
|
15
|
+
* A work calendar names the minutes that count as work: weekly hours per
|
|
16
|
+
* weekday plus dated exceptions (holidays, half days). Every duration in the
|
|
17
|
+
* critical-path engine is a number of WORKING minutes on such a calendar, so
|
|
18
|
+
* "five days" starting Wednesday finishes the following Tuesday, and a lag
|
|
19
|
+
* of one day across New Year skips the holiday.
|
|
20
|
+
*
|
|
21
|
+
* Two conventions keep start and finish dates readable to planners, and the
|
|
22
|
+
* engine relies on both:
|
|
23
|
+
*
|
|
24
|
+
* - a START snaps FORWARD to the next working instant (Friday 17:00 becomes
|
|
25
|
+
* Monday 08:00)
|
|
26
|
+
* - a FINISH snaps BACKWARD to the previous working instant (Saturday
|
|
27
|
+
* becomes Friday 17:00)
|
|
28
|
+
*
|
|
29
|
+
* Adding a positive duration snaps its origin forward first; adding a
|
|
30
|
+
* negative one snaps backward first. Adding zero returns the origin as given,
|
|
31
|
+
* so a milestone keeps whatever instant its logic produced.
|
|
32
|
+
*
|
|
33
|
+
* Instants are JS Dates (UTC); the calendar's IANA zone decides which local
|
|
34
|
+
* 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.
|
|
38
|
+
*
|
|
39
|
+
* 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.
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
/* An arithmetic request exceeds the supported forty-year calendar span. */
|
|
47
|
+
export class WorkTimeRangeError extends RangeError {
|
|
48
|
+
/* Keep the calendar identity available to engine diagnostics. */
|
|
49
|
+
constructor(
|
|
50
|
+
readonly calendarId: string,
|
|
51
|
+
message: string,
|
|
52
|
+
) {
|
|
53
|
+
super(message);
|
|
54
|
+
this.name = 'WorkTimeRangeError';
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/* A referenced work calendar contains no working intervals. */
|
|
59
|
+
export class WorkTimeEmptyCalendarError extends Error {
|
|
60
|
+
/* Describe the calendar that cannot schedule work. */
|
|
61
|
+
constructor(readonly calendarId: string) {
|
|
62
|
+
super(`Work calendar ${calendarId} has no working time`);
|
|
63
|
+
this.name = 'WorkTimeEmptyCalendarError';
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/* A calendar uses an unrecognized IANA time zone. */
|
|
68
|
+
export class WorkTimeInvalidZoneError extends Error {
|
|
69
|
+
/* Describe the invalid calendar zone without attempting calendar walks. */
|
|
70
|
+
constructor(
|
|
71
|
+
readonly calendarId: string,
|
|
72
|
+
zone: string,
|
|
73
|
+
) {
|
|
74
|
+
super(`Work calendar ${calendarId} has an invalid time zone "${zone}"`);
|
|
75
|
+
this.name = 'WorkTimeInvalidZoneError';
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/* Validate a zone without requiring the CPM engine to import Luxon. */
|
|
80
|
+
export function isValidWorkTimeZone(zone: string): boolean {
|
|
81
|
+
return typeof zone === 'string' && IANAZone.isValidZone(zone);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface WorkCalendarDay {
|
|
85
|
+
dayIndex: number;
|
|
86
|
+
dateKey: string;
|
|
87
|
+
dayStartMs: number;
|
|
88
|
+
periods: Array<{ startMs: number; endMs: number }>;
|
|
89
|
+
workingMinutes: number;
|
|
90
|
+
cumulativeMinutesAtDayStart: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface WorkCalendarTable {
|
|
94
|
+
calendar: ScheduleWorkCalendarDef;
|
|
95
|
+
// Ascending by dayStartMs; days[i].dayIndex === i
|
|
96
|
+
days: WorkCalendarDay[];
|
|
97
|
+
firstDayStartMs: number;
|
|
98
|
+
// Start of the local day after the last row (exclusive end of the table)
|
|
99
|
+
lastDayEndMs: number;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Per-calendar memo of the lazily extended day table
|
|
103
|
+
const TABLE_CACHE = new WeakMap<ScheduleWorkCalendarDef, WorkCalendarTable>();
|
|
104
|
+
|
|
105
|
+
const FILE_CONSTANTS = {
|
|
106
|
+
standardWeekHours: {
|
|
107
|
+
'1': [
|
|
108
|
+
['08:00', '12:00'],
|
|
109
|
+
['13:00', '17:00'],
|
|
110
|
+
],
|
|
111
|
+
'2': [
|
|
112
|
+
['08:00', '12:00'],
|
|
113
|
+
['13:00', '17:00'],
|
|
114
|
+
],
|
|
115
|
+
'3': [
|
|
116
|
+
['08:00', '12:00'],
|
|
117
|
+
['13:00', '17:00'],
|
|
118
|
+
],
|
|
119
|
+
'4': [
|
|
120
|
+
['08:00', '12:00'],
|
|
121
|
+
['13:00', '17:00'],
|
|
122
|
+
],
|
|
123
|
+
'5': [
|
|
124
|
+
['08:00', '12:00'],
|
|
125
|
+
['13:00', '17:00'],
|
|
126
|
+
],
|
|
127
|
+
} as ScheduleWeekHoursObj,
|
|
128
|
+
standardMinutesPerDay: 480,
|
|
129
|
+
fallbackMinutesPerDay: 480,
|
|
130
|
+
dayMs: 86_400_000,
|
|
131
|
+
minuteMs: 60_000,
|
|
132
|
+
// Days added around a requested range so nearby instants need no extension
|
|
133
|
+
tablePadDays: 90,
|
|
134
|
+
// Days an open-ended walk (snap, add) first extends by; doubled per retry
|
|
135
|
+
walkChunkDays: 366,
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Return the platform standard calendar (Monday to Friday, 08:00-12:00 and
|
|
140
|
+
* 13:00-17:00) in one time zone.
|
|
141
|
+
*/
|
|
142
|
+
|
|
143
|
+
export function getStandardWorkCalendarDef(
|
|
144
|
+
timeZone: string,
|
|
145
|
+
): ScheduleWorkCalendarDef {
|
|
146
|
+
return {
|
|
147
|
+
id: SCHEDULE_STANDARD_WORK_CALENDAR_KEY,
|
|
148
|
+
timeZone,
|
|
149
|
+
weekHours: FILE_CONSTANTS.standardWeekHours,
|
|
150
|
+
exceptions: null,
|
|
151
|
+
minutesPerDay: FILE_CONSTANTS.standardMinutesPerDay,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/*
|
|
156
|
+
* Coerce one value into a Date, throwing on anything unreadable: a bad
|
|
157
|
+
* instant inside the engine is a programming error, never user input.
|
|
158
|
+
*/
|
|
159
|
+
|
|
160
|
+
export function toWorkTimeDate(value: Date | string | number): Date {
|
|
161
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
162
|
+
|
|
163
|
+
if (Number.isNaN(date.getTime())) {
|
|
164
|
+
throw new Error(`Invalid instant: ${String(value)}`);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return date;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/*
|
|
171
|
+
* Parse "HH:mm" into minutes since local midnight; "24:00" is allowed as an
|
|
172
|
+
* exclusive end of day.
|
|
173
|
+
*/
|
|
174
|
+
|
|
175
|
+
function parseClockMinutes(value: string): number | null {
|
|
176
|
+
const match = /^(\d{1,2}):(\d{2})$/.exec(String(value || '').trim());
|
|
177
|
+
|
|
178
|
+
if (!match) {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const hours = Number(match[1]);
|
|
183
|
+
const minutes = Number(match[2]);
|
|
184
|
+
|
|
185
|
+
if (hours > 24 || minutes > 59 || (hours === 24 && minutes > 0)) {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return hours * 60 + minutes;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
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.
|
|
196
|
+
*/
|
|
197
|
+
|
|
198
|
+
export function validateWorkIntervals(input: unknown): {
|
|
199
|
+
intervals?: ScheduleWorkInterval[];
|
|
200
|
+
error?: string;
|
|
201
|
+
} {
|
|
202
|
+
if (!Array.isArray(input)) {
|
|
203
|
+
return { error: 'Working hours must be a list of [from, to] pairs.' };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const parsed: Array<[number, number]> = [];
|
|
207
|
+
|
|
208
|
+
for (const item of input) {
|
|
209
|
+
if (!Array.isArray(item) || item.length !== 2) {
|
|
210
|
+
return { error: 'Each working interval must be a [from, to] pair.' };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const from = parseClockMinutes(item[0]);
|
|
214
|
+
const to = parseClockMinutes(item[1]);
|
|
215
|
+
|
|
216
|
+
if (from === null || to === null) {
|
|
217
|
+
return {
|
|
218
|
+
error: `Working interval times must be "HH:mm": ${JSON.stringify(item)}.`,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
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
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const format = (minutes: number) =>
|
|
245
|
+
`${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
|
|
246
|
+
|
|
247
|
+
return {
|
|
248
|
+
intervals: merged.map(
|
|
249
|
+
([from, to]) => [format(from), format(to)] as ScheduleWorkInterval,
|
|
250
|
+
),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Validate a week-hours object (weekday key -> intervals).
|
|
256
|
+
*/
|
|
257
|
+
|
|
258
|
+
export function validateWeekHours(input: unknown): {
|
|
259
|
+
weekHours?: ScheduleWeekHoursObj;
|
|
260
|
+
error?: string;
|
|
261
|
+
} {
|
|
262
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
|
263
|
+
return {
|
|
264
|
+
error:
|
|
265
|
+
'Week hours must be an object keyed by weekday (0 = Sunday ... 6 = Saturday).',
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const weekHours: ScheduleWeekHoursObj = {};
|
|
270
|
+
|
|
271
|
+
for (const [key, value] of Object.entries(input as Record<string, unknown>)) {
|
|
272
|
+
if (!/^[0-6]$/.test(key)) {
|
|
273
|
+
return {
|
|
274
|
+
error: `Unknown weekday key "${key}"; use 0 (Sunday) to 6 (Saturday).`,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const result = validateWorkIntervals(value ?? []);
|
|
279
|
+
if (result.error) {
|
|
280
|
+
return { error: `Weekday ${key}: ${result.error}` };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (result.intervals?.length) {
|
|
284
|
+
weekHours[key as keyof ScheduleWeekHoursObj] = result.intervals;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
return { weekHours };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Check whether a calendar ever reaches working time. A calendar that does
|
|
293
|
+
* not would make every duration infinite, so the engine refuses it up front.
|
|
294
|
+
*/
|
|
295
|
+
|
|
296
|
+
export function isWorkingCalendar(calendar: ScheduleWorkCalendarDef): boolean {
|
|
297
|
+
const hasWeekHours = Object.values(calendar.weekHours || {}).some(
|
|
298
|
+
(intervals) => Array.isArray(intervals) && intervals.length > 0,
|
|
299
|
+
);
|
|
300
|
+
|
|
301
|
+
if (hasWeekHours) {
|
|
302
|
+
return true;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
return Object.values(calendar.exceptions || {}).some(
|
|
306
|
+
(intervals) => Array.isArray(intervals) && intervals.length > 0,
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Return how many working minutes one "day" of duration represents on a
|
|
312
|
+
* calendar: the explicit setting, else the longest working weekday.
|
|
313
|
+
*/
|
|
314
|
+
|
|
315
|
+
export function getWorkingMinutesPerDay(
|
|
316
|
+
calendar: ScheduleWorkCalendarDef,
|
|
317
|
+
): number {
|
|
318
|
+
if (calendar.minutesPerDay && calendar.minutesPerDay > 0) {
|
|
319
|
+
return calendar.minutesPerDay;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
let longest = 0;
|
|
323
|
+
|
|
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
|
+
}
|
|
336
|
+
}
|
|
337
|
+
longest = Math.max(longest, total);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return longest || FILE_CONSTANTS.fallbackMinutesPerDay;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/*
|
|
344
|
+
* Refuse to walk a calendar with no working time; the table span bound below
|
|
345
|
+
* is the second line of defence for a calendar whose only hours are
|
|
346
|
+
* exceptions far outside the built range.
|
|
347
|
+
*/
|
|
348
|
+
|
|
349
|
+
function assertWorkingCalendar(calendar: ScheduleWorkCalendarDef): void {
|
|
350
|
+
if (!isWorkingCalendar(calendar)) {
|
|
351
|
+
throw new WorkTimeEmptyCalendarError(calendar.id);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/*
|
|
356
|
+
* Build the error thrown when a span would need more table days than the
|
|
357
|
+
* engine allows.
|
|
358
|
+
*/
|
|
359
|
+
|
|
360
|
+
function getSpanError(
|
|
361
|
+
calendar: ScheduleWorkCalendarDef,
|
|
362
|
+
fromMs: number,
|
|
363
|
+
toMs: number,
|
|
364
|
+
): Error {
|
|
365
|
+
const days = Math.ceil((toMs - fromMs) / FILE_CONSTANTS.dayMs);
|
|
366
|
+
return new WorkTimeRangeError(
|
|
367
|
+
calendar.id,
|
|
368
|
+
`Work calendar ${calendar.id}: a span of ${days} days exceeds the ${SCHEDULE_WORK_TIME_MAX_SPAN_DAYS}-day limit`,
|
|
369
|
+
);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/*
|
|
373
|
+
* Resolve the raw "HH:mm" intervals that apply to one local date: a dated
|
|
374
|
+
* exception wins outright over the weekly pattern.
|
|
375
|
+
*/
|
|
376
|
+
|
|
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 || [];
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// Luxon weekdays run 1 (Monday) to 7 (Sunday); keys use 0 (Sunday) to 6
|
|
389
|
+
const weekdayKey = String(weekday % 7) as keyof ScheduleWeekHoursObj;
|
|
390
|
+
|
|
391
|
+
return calendar.weekHours?.[weekdayKey] || [];
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/*
|
|
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.
|
|
400
|
+
*/
|
|
401
|
+
|
|
402
|
+
function buildWorkCalendarDay(
|
|
403
|
+
calendar: ScheduleWorkCalendarDef,
|
|
404
|
+
dayStart: DateTime,
|
|
405
|
+
nextDayStart: DateTime,
|
|
406
|
+
): WorkCalendarDay {
|
|
407
|
+
const dayStartMs = dayStart.toMillis();
|
|
408
|
+
const nextDayStartMs = nextDayStart.toMillis();
|
|
409
|
+
const dateKey = dayStart.toISODate() as string;
|
|
410
|
+
const isUniformDay =
|
|
411
|
+
nextDayStartMs - dayStartMs === FILE_CONSTANTS.dayMs &&
|
|
412
|
+
dayStart.offset === nextDayStart.offset;
|
|
413
|
+
|
|
414
|
+
const toInstantMs = (minutes: number): number => {
|
|
415
|
+
if (minutes === 1440) {
|
|
416
|
+
return nextDayStartMs;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
if (isUniformDay) {
|
|
420
|
+
return dayStartMs + minutes * FILE_CONSTANTS.minuteMs;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
return dayStart
|
|
424
|
+
.set({
|
|
425
|
+
hour: Math.floor(minutes / 60),
|
|
426
|
+
minute: minutes % 60,
|
|
427
|
+
second: 0,
|
|
428
|
+
millisecond: 0,
|
|
429
|
+
})
|
|
430
|
+
.toMillis();
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
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
|
+
|
|
444
|
+
if (
|
|
445
|
+
fromMinutes === null ||
|
|
446
|
+
toMinutes === null ||
|
|
447
|
+
toMinutes <= fromMinutes
|
|
448
|
+
) {
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const startMs = toInstantMs(fromMinutes);
|
|
453
|
+
const endMs = toInstantMs(toMinutes);
|
|
454
|
+
|
|
455
|
+
if (endMs > startMs) {
|
|
456
|
+
periods.push({ startMs, endMs });
|
|
457
|
+
workingMs += endMs - startMs;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
if (periods.length > 1) {
|
|
462
|
+
periods.sort((a, b) => a.startMs - b.startMs);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
return {
|
|
466
|
+
dayIndex: 0,
|
|
467
|
+
dateKey,
|
|
468
|
+
dayStartMs,
|
|
469
|
+
periods,
|
|
470
|
+
workingMinutes: workingMs / FILE_CONSTANTS.minuteMs,
|
|
471
|
+
cumulativeMinutesAtDayStart: 0,
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/*
|
|
476
|
+
* Renumber every row and rebuild the cumulative minutes from the first day.
|
|
477
|
+
*/
|
|
478
|
+
|
|
479
|
+
function reindexWorkCalendarTable(table: WorkCalendarTable): void {
|
|
480
|
+
let cumulative = 0;
|
|
481
|
+
|
|
482
|
+
for (let i = 0; i < table.days.length; i++) {
|
|
483
|
+
const day = table.days[i];
|
|
484
|
+
day.dayIndex = i;
|
|
485
|
+
day.cumulativeMinutesAtDayStart = cumulative;
|
|
486
|
+
cumulative += day.workingMinutes;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
table.firstDayStartMs = table.days[0].dayStartMs;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/*
|
|
493
|
+
* Return the local midnight of one instant, throwing on an invalid zone so
|
|
494
|
+
* a bad calendar fails at once instead of spinning through empty rows.
|
|
495
|
+
*/
|
|
496
|
+
|
|
497
|
+
function getZonedDayStart(
|
|
498
|
+
calendar: ScheduleWorkCalendarDef,
|
|
499
|
+
atMs: number,
|
|
500
|
+
): DateTime {
|
|
501
|
+
const dayStart = DateTime.fromMillis(atMs, {
|
|
502
|
+
zone: calendar.timeZone,
|
|
503
|
+
}).startOf('day');
|
|
504
|
+
|
|
505
|
+
if (!dayStart.isValid) {
|
|
506
|
+
throw new WorkTimeInvalidZoneError(calendar.id, calendar.timeZone);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
return dayStart;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/*
|
|
513
|
+
* Append rows until the table covers "untilMs".
|
|
514
|
+
*/
|
|
515
|
+
|
|
516
|
+
function extendWorkCalendarTableForward(
|
|
517
|
+
table: WorkCalendarTable,
|
|
518
|
+
untilMs: number,
|
|
519
|
+
): void {
|
|
520
|
+
const { calendar, days } = table;
|
|
521
|
+
let dayStart = getZonedDayStart(calendar, table.lastDayEndMs);
|
|
522
|
+
let cumulative =
|
|
523
|
+
days[days.length - 1].cumulativeMinutesAtDayStart +
|
|
524
|
+
days[days.length - 1].workingMinutes;
|
|
525
|
+
|
|
526
|
+
while (dayStart.toMillis() <= untilMs) {
|
|
527
|
+
const nextDayStart = dayStart.plus({ days: 1 });
|
|
528
|
+
const day = buildWorkCalendarDay(calendar, dayStart, nextDayStart);
|
|
529
|
+
day.dayIndex = days.length;
|
|
530
|
+
day.cumulativeMinutesAtDayStart = cumulative;
|
|
531
|
+
cumulative += day.workingMinutes;
|
|
532
|
+
days.push(day);
|
|
533
|
+
dayStart = nextDayStart;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
table.lastDayEndMs = dayStart.toMillis();
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/*
|
|
540
|
+
* Prepend rows until the table covers "untilMs", then renumber.
|
|
541
|
+
*/
|
|
542
|
+
|
|
543
|
+
function extendWorkCalendarTableBackward(
|
|
544
|
+
table: WorkCalendarTable,
|
|
545
|
+
untilMs: number,
|
|
546
|
+
): void {
|
|
547
|
+
const { calendar } = table;
|
|
548
|
+
const rows: WorkCalendarDay[] = [];
|
|
549
|
+
let nextDayStart = getZonedDayStart(calendar, table.firstDayStartMs);
|
|
550
|
+
|
|
551
|
+
while (nextDayStart.toMillis() > untilMs) {
|
|
552
|
+
const dayStart = nextDayStart.minus({ days: 1 });
|
|
553
|
+
rows.push(buildWorkCalendarDay(calendar, dayStart, nextDayStart));
|
|
554
|
+
nextDayStart = dayStart;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
if (rows.length) {
|
|
558
|
+
rows.reverse();
|
|
559
|
+
table.days.unshift(...rows);
|
|
560
|
+
reindexWorkCalendarTable(table);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Build a day table covering every local day of the calendar's zone that
|
|
566
|
+
* touches [from, to]. Throws on an invalid time zone, a calendar with no
|
|
567
|
+
* working time, or a span beyond SCHEDULE_WORK_TIME_MAX_SPAN_DAYS. Tables
|
|
568
|
+
* built here are never mutated, so their day indices stay valid for as long
|
|
569
|
+
* as the caller holds them.
|
|
570
|
+
*/
|
|
571
|
+
|
|
572
|
+
export function buildWorkCalendarTable(
|
|
573
|
+
calendar: ScheduleWorkCalendarDef,
|
|
574
|
+
from: Date,
|
|
575
|
+
to: Date,
|
|
576
|
+
): WorkCalendarTable {
|
|
577
|
+
assertWorkingCalendar(calendar);
|
|
578
|
+
|
|
579
|
+
const fromMs = toWorkTimeDate(from).getTime();
|
|
580
|
+
const toMs = toWorkTimeDate(to).getTime();
|
|
581
|
+
|
|
582
|
+
if (toMs < fromMs) {
|
|
583
|
+
throw new Error(
|
|
584
|
+
`Work calendar ${calendar.id}: table range ends before it starts`,
|
|
585
|
+
);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
if (toMs - fromMs > SCHEDULE_WORK_TIME_MAX_SPAN_DAYS * FILE_CONSTANTS.dayMs) {
|
|
589
|
+
throw getSpanError(calendar, fromMs, toMs);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
const dayStart = getZonedDayStart(calendar, fromMs);
|
|
593
|
+
const nextDayStart = dayStart.plus({ days: 1 });
|
|
594
|
+
const firstDay = buildWorkCalendarDay(calendar, dayStart, nextDayStart);
|
|
595
|
+
const table: WorkCalendarTable = {
|
|
596
|
+
calendar,
|
|
597
|
+
days: [firstDay],
|
|
598
|
+
firstDayStartMs: firstDay.dayStartMs,
|
|
599
|
+
lastDayEndMs: nextDayStart.toMillis(),
|
|
600
|
+
};
|
|
601
|
+
|
|
602
|
+
extendWorkCalendarTableForward(table, toMs);
|
|
603
|
+
|
|
604
|
+
return table;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/**
|
|
608
|
+
* Return the memoized day table of one calendar, guaranteed to cover
|
|
609
|
+
* [at, through]. The table grows in place (rows appended or prepended, with
|
|
610
|
+
* cumulative minutes rebuilt) as instants fall outside it, up to
|
|
611
|
+
* SCHEDULE_WORK_TIME_MAX_SPAN_DAYS rows in total; a request that no longer
|
|
612
|
+
* fits beside the built rows starts a fresh table around the request, and one
|
|
613
|
+
* that cannot fit at all throws. Day indices are only stable between calls
|
|
614
|
+
* that do not extend the table: hold a table from buildWorkCalendarTable
|
|
615
|
+
* when indices must survive.
|
|
616
|
+
*/
|
|
617
|
+
|
|
618
|
+
export function getWorkCalendarTable(
|
|
619
|
+
calendar: ScheduleWorkCalendarDef,
|
|
620
|
+
at: Date,
|
|
621
|
+
through?: Date,
|
|
622
|
+
): WorkCalendarTable {
|
|
623
|
+
let fromMs = toWorkTimeDate(at).getTime();
|
|
624
|
+
let toMs = through ? toWorkTimeDate(through).getTime() : fromMs;
|
|
625
|
+
|
|
626
|
+
if (toMs < fromMs) {
|
|
627
|
+
[fromMs, toMs] = [toMs, fromMs];
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
const maxSpanMs = SCHEDULE_WORK_TIME_MAX_SPAN_DAYS * FILE_CONSTANTS.dayMs;
|
|
631
|
+
|
|
632
|
+
if (toMs - fromMs > maxSpanMs) {
|
|
633
|
+
throw getSpanError(calendar, fromMs, toMs);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const cached = TABLE_CACHE.get(calendar);
|
|
637
|
+
|
|
638
|
+
if (
|
|
639
|
+
cached &&
|
|
640
|
+
fromMs >= cached.firstDayStartMs &&
|
|
641
|
+
toMs < cached.lastDayEndMs
|
|
642
|
+
) {
|
|
643
|
+
return cached;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// Pad the request so the next nearby instant needs no extension, giving
|
|
647
|
+
// back as much padding as the span limit leaves room for
|
|
648
|
+
const padMs = Math.min(
|
|
649
|
+
FILE_CONSTANTS.tablePadDays * FILE_CONSTANTS.dayMs,
|
|
650
|
+
Math.floor((maxSpanMs - (toMs - fromMs)) / 2),
|
|
651
|
+
);
|
|
652
|
+
let buildFromMs = fromMs - padMs;
|
|
653
|
+
let buildToMs = toMs + padMs;
|
|
654
|
+
|
|
655
|
+
if (cached) {
|
|
656
|
+
buildFromMs = Math.min(buildFromMs, cached.firstDayStartMs);
|
|
657
|
+
buildToMs = Math.max(buildToMs, cached.lastDayEndMs - 1);
|
|
658
|
+
|
|
659
|
+
if (buildToMs - buildFromMs <= maxSpanMs) {
|
|
660
|
+
if (buildFromMs < cached.firstDayStartMs) {
|
|
661
|
+
extendWorkCalendarTableBackward(cached, buildFromMs);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
if (buildToMs >= cached.lastDayEndMs) {
|
|
665
|
+
extendWorkCalendarTableForward(cached, buildToMs);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
return cached;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// The built rows and the request cannot share one table: start over
|
|
672
|
+
buildFromMs = fromMs - padMs;
|
|
673
|
+
buildToMs = toMs + padMs;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
const table = buildWorkCalendarTable(
|
|
677
|
+
calendar,
|
|
678
|
+
new Date(buildFromMs),
|
|
679
|
+
new Date(buildToMs),
|
|
680
|
+
);
|
|
681
|
+
TABLE_CACHE.set(calendar, table);
|
|
682
|
+
|
|
683
|
+
return table;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/*
|
|
687
|
+
* Return the index of the day holding one instant: -1 before the first day,
|
|
688
|
+
* days.length at or after the table's end.
|
|
689
|
+
*/
|
|
690
|
+
|
|
691
|
+
function findDayIndexAtMs(table: WorkCalendarTable, atMs: number): number {
|
|
692
|
+
const { days } = table;
|
|
693
|
+
|
|
694
|
+
if (atMs < table.firstDayStartMs) {
|
|
695
|
+
return -1;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
if (atMs >= table.lastDayEndMs) {
|
|
699
|
+
return days.length;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
let low = 0;
|
|
703
|
+
let high = days.length - 1;
|
|
704
|
+
|
|
705
|
+
while (low < high) {
|
|
706
|
+
const mid = (low + high + 1) >> 1;
|
|
707
|
+
if (days[mid].dayStartMs <= atMs) {
|
|
708
|
+
low = mid;
|
|
709
|
+
} else {
|
|
710
|
+
high = mid - 1;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
return low;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Return the index of the local day holding one instant, by binary search on
|
|
719
|
+
* day starts: -1 when the instant precedes the table, days.length when it
|
|
720
|
+
* falls at or after the table's end.
|
|
721
|
+
*/
|
|
722
|
+
|
|
723
|
+
export function getDayIndexAt(table: WorkCalendarTable, at: Date): number {
|
|
724
|
+
return findDayIndexAtMs(table, toWorkTimeDate(at).getTime());
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/*
|
|
728
|
+
* Return the cumulative working minutes at the END of one day (0 for the
|
|
729
|
+
* imaginary day before the table).
|
|
730
|
+
*/
|
|
731
|
+
|
|
732
|
+
function getCumulativeMinutesAtDayEnd(
|
|
733
|
+
table: WorkCalendarTable,
|
|
734
|
+
dayIndex: number,
|
|
735
|
+
): number {
|
|
736
|
+
if (dayIndex < 0) {
|
|
737
|
+
return 0;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
const day = table.days[dayIndex];
|
|
741
|
+
|
|
742
|
+
return day.cumulativeMinutesAtDayStart + day.workingMinutes;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/*
|
|
746
|
+
* Return the index of the first day after "afterIndex" with working time, or
|
|
747
|
+
* -1 when the table has none. Binary search on the cumulative minutes at day
|
|
748
|
+
* ends: the first day whose end total exceeds the total at "afterIndex".
|
|
749
|
+
*/
|
|
750
|
+
|
|
751
|
+
function findNextWorkingDayIndex(
|
|
752
|
+
table: WorkCalendarTable,
|
|
753
|
+
afterIndex: number,
|
|
754
|
+
): number {
|
|
755
|
+
const { days } = table;
|
|
756
|
+
const target = getCumulativeMinutesAtDayEnd(table, afterIndex);
|
|
757
|
+
let low = afterIndex + 1;
|
|
758
|
+
let high = days.length;
|
|
759
|
+
|
|
760
|
+
while (low < high) {
|
|
761
|
+
const mid = (low + high) >> 1;
|
|
762
|
+
if (getCumulativeMinutesAtDayEnd(table, mid) > target) {
|
|
763
|
+
high = mid;
|
|
764
|
+
} else {
|
|
765
|
+
low = mid + 1;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
return low < days.length ? low : -1;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/*
|
|
773
|
+
* Return the index of the last day before "beforeIndex" with working time, or
|
|
774
|
+
* -1 when the table has none. Binary search on the cumulative minutes at day
|
|
775
|
+
* starts: the last day whose start total is below the total at
|
|
776
|
+
* "beforeIndex".
|
|
777
|
+
*/
|
|
778
|
+
|
|
779
|
+
function findPreviousWorkingDayIndex(
|
|
780
|
+
table: WorkCalendarTable,
|
|
781
|
+
beforeIndex: number,
|
|
782
|
+
): number {
|
|
783
|
+
const { days } = table;
|
|
784
|
+
const target =
|
|
785
|
+
beforeIndex < days.length
|
|
786
|
+
? days[beforeIndex].cumulativeMinutesAtDayStart
|
|
787
|
+
: getCumulativeMinutesAtDayEnd(table, days.length - 1);
|
|
788
|
+
let low = 0;
|
|
789
|
+
let high = Math.max(0, beforeIndex);
|
|
790
|
+
|
|
791
|
+
// First index in [0, beforeIndex) whose start total reaches the target
|
|
792
|
+
while (low < high) {
|
|
793
|
+
const mid = (low + high) >> 1;
|
|
794
|
+
if (days[mid].cumulativeMinutesAtDayStart >= target) {
|
|
795
|
+
high = mid;
|
|
796
|
+
} else {
|
|
797
|
+
low = mid + 1;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
return low - 1;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/*
|
|
805
|
+
* Return the working milliseconds of one day that precede an instant.
|
|
806
|
+
*/
|
|
807
|
+
|
|
808
|
+
function getWorkedMsBefore(day: WorkCalendarDay, atMs: number): number {
|
|
809
|
+
let worked = 0;
|
|
810
|
+
|
|
811
|
+
for (const period of day.periods) {
|
|
812
|
+
if (atMs <= period.startMs) {
|
|
813
|
+
break;
|
|
814
|
+
}
|
|
815
|
+
worked += Math.min(period.endMs, atMs) - period.startMs;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
return worked;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/*
|
|
822
|
+
* Return an instant's position on the table's working-time axis, in
|
|
823
|
+
* milliseconds of working time since the first day.
|
|
824
|
+
*/
|
|
825
|
+
|
|
826
|
+
function getWorkingPositionMs(table: WorkCalendarTable, atMs: number): number {
|
|
827
|
+
const dayIndex = findDayIndexAtMs(table, atMs);
|
|
828
|
+
|
|
829
|
+
if (dayIndex < 0) {
|
|
830
|
+
return 0;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
if (dayIndex >= table.days.length) {
|
|
834
|
+
return (
|
|
835
|
+
getCumulativeMinutesAtDayEnd(table, table.days.length - 1) *
|
|
836
|
+
FILE_CONSTANTS.minuteMs
|
|
837
|
+
);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
const day = table.days[dayIndex];
|
|
841
|
+
|
|
842
|
+
return (
|
|
843
|
+
day.cumulativeMinutesAtDayStart * FILE_CONSTANTS.minuteMs +
|
|
844
|
+
getWorkedMsBefore(day, atMs)
|
|
845
|
+
);
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/*
|
|
849
|
+
* Find the earliest working instant at or after "atMs" inside the table; null
|
|
850
|
+
* when the table holds none.
|
|
851
|
+
*/
|
|
852
|
+
|
|
853
|
+
function findNextWorkingInstantMs(
|
|
854
|
+
table: WorkCalendarTable,
|
|
855
|
+
atMs: number,
|
|
856
|
+
): number | null {
|
|
857
|
+
const { days } = table;
|
|
858
|
+
const dayIndex = findDayIndexAtMs(table, atMs);
|
|
859
|
+
|
|
860
|
+
if (dayIndex >= days.length) {
|
|
861
|
+
return null;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
if (dayIndex >= 0) {
|
|
865
|
+
for (const period of days[dayIndex].periods) {
|
|
866
|
+
if (atMs < period.endMs) {
|
|
867
|
+
return Math.max(atMs, period.startMs);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
const nextIndex = findNextWorkingDayIndex(table, dayIndex);
|
|
873
|
+
|
|
874
|
+
return nextIndex < 0 ? null : days[nextIndex].periods[0].startMs;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/*
|
|
878
|
+
* Find the latest working instant at or before "atMs" inside the table; null
|
|
879
|
+
* when the table holds none. The last period whose start precedes the
|
|
880
|
+
* instant wins, so an instant exactly at a period start belongs to the
|
|
881
|
+
* previous period.
|
|
882
|
+
*/
|
|
883
|
+
|
|
884
|
+
function findPreviousWorkingInstantMs(
|
|
885
|
+
table: WorkCalendarTable,
|
|
886
|
+
atMs: number,
|
|
887
|
+
): number | null {
|
|
888
|
+
const { days } = table;
|
|
889
|
+
const dayIndex = findDayIndexAtMs(table, atMs);
|
|
890
|
+
|
|
891
|
+
if (dayIndex < 0) {
|
|
892
|
+
return null;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
if (dayIndex < days.length) {
|
|
896
|
+
const { periods } = days[dayIndex];
|
|
897
|
+
for (let i = periods.length - 1; i >= 0; i--) {
|
|
898
|
+
if (atMs > periods[i].startMs) {
|
|
899
|
+
return Math.min(atMs, periods[i].endMs);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
const previousIndex = findPreviousWorkingDayIndex(table, dayIndex);
|
|
905
|
+
|
|
906
|
+
if (previousIndex < 0) {
|
|
907
|
+
return null;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
const { periods } = days[previousIndex];
|
|
911
|
+
|
|
912
|
+
return periods[periods.length - 1].endMs;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/*
|
|
916
|
+
* Resolve the instant at one position on the working-time axis when walking
|
|
917
|
+
* FORWARD: a position exactly at a period end resolves to that end.
|
|
918
|
+
*/
|
|
919
|
+
|
|
920
|
+
function resolveForwardPositionMs(
|
|
921
|
+
table: WorkCalendarTable,
|
|
922
|
+
positionMs: number,
|
|
923
|
+
): number | null {
|
|
924
|
+
const { days } = table;
|
|
925
|
+
|
|
926
|
+
if (
|
|
927
|
+
positionMs >
|
|
928
|
+
getCumulativeMinutesAtDayEnd(table, days.length - 1) *
|
|
929
|
+
FILE_CONSTANTS.minuteMs
|
|
930
|
+
) {
|
|
931
|
+
return null;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
// Last day whose start total is strictly below the position
|
|
935
|
+
let low = 0;
|
|
936
|
+
let high = days.length - 1;
|
|
937
|
+
|
|
938
|
+
while (low < high) {
|
|
939
|
+
const mid = (low + high + 1) >> 1;
|
|
940
|
+
if (
|
|
941
|
+
days[mid].cumulativeMinutesAtDayStart * FILE_CONSTANTS.minuteMs <
|
|
942
|
+
positionMs
|
|
943
|
+
) {
|
|
944
|
+
low = mid;
|
|
945
|
+
} else {
|
|
946
|
+
high = mid - 1;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
const day = days[low];
|
|
951
|
+
let remainingMs =
|
|
952
|
+
positionMs - day.cumulativeMinutesAtDayStart * FILE_CONSTANTS.minuteMs;
|
|
953
|
+
|
|
954
|
+
for (const period of day.periods) {
|
|
955
|
+
const lengthMs = period.endMs - period.startMs;
|
|
956
|
+
if (lengthMs >= remainingMs) {
|
|
957
|
+
return period.startMs + remainingMs;
|
|
958
|
+
}
|
|
959
|
+
remainingMs -= lengthMs;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
return null;
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/*
|
|
966
|
+
* Resolve the instant at one position on the working-time axis when walking
|
|
967
|
+
* BACKWARD: a position exactly at a period start resolves to that start.
|
|
968
|
+
*/
|
|
969
|
+
|
|
970
|
+
function resolveBackwardPositionMs(
|
|
971
|
+
table: WorkCalendarTable,
|
|
972
|
+
positionMs: number,
|
|
973
|
+
): number | null {
|
|
974
|
+
const { days } = table;
|
|
975
|
+
|
|
976
|
+
if (positionMs < 0) {
|
|
977
|
+
return null;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// Last day whose start total is at or below the position
|
|
981
|
+
let low = 0;
|
|
982
|
+
let high = days.length - 1;
|
|
983
|
+
|
|
984
|
+
while (low < high) {
|
|
985
|
+
const mid = (low + high + 1) >> 1;
|
|
986
|
+
if (
|
|
987
|
+
days[mid].cumulativeMinutesAtDayStart * FILE_CONSTANTS.minuteMs <=
|
|
988
|
+
positionMs
|
|
989
|
+
) {
|
|
990
|
+
low = mid;
|
|
991
|
+
} else {
|
|
992
|
+
high = mid - 1;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
const day = days[low];
|
|
997
|
+
let remainingMs =
|
|
998
|
+
positionMs - day.cumulativeMinutesAtDayStart * FILE_CONSTANTS.minuteMs;
|
|
999
|
+
|
|
1000
|
+
for (const period of day.periods) {
|
|
1001
|
+
const lengthMs = period.endMs - period.startMs;
|
|
1002
|
+
if (lengthMs > remainingMs) {
|
|
1003
|
+
return period.startMs + remainingMs;
|
|
1004
|
+
}
|
|
1005
|
+
remainingMs -= lengthMs;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
return null;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
/*
|
|
1012
|
+
* Grow the calendar's table in one direction from an origin until "resolve"
|
|
1013
|
+
* finds an answer, doubling the reach each round up to the scan limit.
|
|
1014
|
+
*/
|
|
1015
|
+
|
|
1016
|
+
function walkWithExtension(
|
|
1017
|
+
calendar: ScheduleWorkCalendarDef,
|
|
1018
|
+
originMs: number,
|
|
1019
|
+
direction: 1 | -1,
|
|
1020
|
+
resolve: (table: WorkCalendarTable) => number | null,
|
|
1021
|
+
buildError: () => Error,
|
|
1022
|
+
): number {
|
|
1023
|
+
const origin = new Date(originMs);
|
|
1024
|
+
let reachDays = 0;
|
|
1025
|
+
|
|
1026
|
+
for (;;) {
|
|
1027
|
+
const table =
|
|
1028
|
+
reachDays === 0
|
|
1029
|
+
? getWorkCalendarTable(calendar, origin)
|
|
1030
|
+
: getWorkCalendarTable(
|
|
1031
|
+
calendar,
|
|
1032
|
+
origin,
|
|
1033
|
+
new Date(originMs + direction * reachDays * FILE_CONSTANTS.dayMs),
|
|
1034
|
+
);
|
|
1035
|
+
const result = resolve(table);
|
|
1036
|
+
|
|
1037
|
+
if (result !== null) {
|
|
1038
|
+
return result;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
if (reachDays >= SCHEDULE_WORK_TIME_MAX_SPAN_DAYS) {
|
|
1042
|
+
throw buildError();
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
reachDays = Math.min(
|
|
1046
|
+
SCHEDULE_WORK_TIME_MAX_SPAN_DAYS,
|
|
1047
|
+
reachDays === 0 ? FILE_CONSTANTS.walkChunkDays : reachDays * 2,
|
|
1048
|
+
);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
/*
|
|
1053
|
+
* Build the error thrown when no working time exists within the scan limit.
|
|
1054
|
+
*/
|
|
1055
|
+
|
|
1056
|
+
function getNoWorkingTimeError(calendar: ScheduleWorkCalendarDef): Error {
|
|
1057
|
+
return new WorkTimeRangeError(
|
|
1058
|
+
calendar.id,
|
|
1059
|
+
`Work calendar ${calendar.id} has no working time within ${SCHEDULE_WORK_TIME_MAX_SPAN_DAYS} days`,
|
|
1060
|
+
);
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
/**
|
|
1064
|
+
* Return the earliest working instant at or after one instant.
|
|
1065
|
+
*/
|
|
1066
|
+
|
|
1067
|
+
export function snapToWorkingStart(
|
|
1068
|
+
calendar: ScheduleWorkCalendarDef,
|
|
1069
|
+
at: Date,
|
|
1070
|
+
): Date {
|
|
1071
|
+
assertWorkingCalendar(calendar);
|
|
1072
|
+
|
|
1073
|
+
const atMs = at.getTime();
|
|
1074
|
+
|
|
1075
|
+
return new Date(
|
|
1076
|
+
walkWithExtension(
|
|
1077
|
+
calendar,
|
|
1078
|
+
atMs,
|
|
1079
|
+
1,
|
|
1080
|
+
(table) => findNextWorkingInstantMs(table, atMs),
|
|
1081
|
+
() => getNoWorkingTimeError(calendar),
|
|
1082
|
+
),
|
|
1083
|
+
);
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
/**
|
|
1087
|
+
* Return the latest working instant at or before one instant.
|
|
1088
|
+
*/
|
|
1089
|
+
|
|
1090
|
+
export function snapToWorkingFinish(
|
|
1091
|
+
calendar: ScheduleWorkCalendarDef,
|
|
1092
|
+
at: Date,
|
|
1093
|
+
): Date {
|
|
1094
|
+
assertWorkingCalendar(calendar);
|
|
1095
|
+
|
|
1096
|
+
const atMs = at.getTime();
|
|
1097
|
+
|
|
1098
|
+
return new Date(
|
|
1099
|
+
walkWithExtension(
|
|
1100
|
+
calendar,
|
|
1101
|
+
atMs,
|
|
1102
|
+
-1,
|
|
1103
|
+
(table) => findPreviousWorkingInstantMs(table, atMs),
|
|
1104
|
+
() => getNoWorkingTimeError(calendar),
|
|
1105
|
+
),
|
|
1106
|
+
);
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/*
|
|
1110
|
+
* Build the error thrown when a duration does not fit within the scan limit.
|
|
1111
|
+
*/
|
|
1112
|
+
|
|
1113
|
+
function getCannotFitError(
|
|
1114
|
+
calendar: ScheduleWorkCalendarDef,
|
|
1115
|
+
minutes: number,
|
|
1116
|
+
): Error {
|
|
1117
|
+
return new WorkTimeRangeError(
|
|
1118
|
+
calendar.id,
|
|
1119
|
+
`Work calendar ${calendar.id} cannot fit ${minutes} working minutes within ${SCHEDULE_WORK_TIME_MAX_SPAN_DAYS} days`,
|
|
1120
|
+
);
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
/**
|
|
1124
|
+
* Add a signed number of working minutes to an instant. Positive values walk
|
|
1125
|
+
* forward from the next working instant; negative values walk backward from
|
|
1126
|
+
* the previous one; zero returns the instant unchanged.
|
|
1127
|
+
*/
|
|
1128
|
+
|
|
1129
|
+
export function addWorkingMinutes(
|
|
1130
|
+
calendar: ScheduleWorkCalendarDef,
|
|
1131
|
+
from: Date,
|
|
1132
|
+
minutes: number,
|
|
1133
|
+
): Date {
|
|
1134
|
+
if (!Number.isFinite(minutes) || minutes === 0) {
|
|
1135
|
+
return from;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
const deltaMs = minutes * FILE_CONSTANTS.minuteMs;
|
|
1139
|
+
|
|
1140
|
+
if (minutes > 0) {
|
|
1141
|
+
const startMs = snapToWorkingStart(calendar, from).getTime();
|
|
1142
|
+
|
|
1143
|
+
return new Date(
|
|
1144
|
+
walkWithExtension(
|
|
1145
|
+
calendar,
|
|
1146
|
+
startMs,
|
|
1147
|
+
1,
|
|
1148
|
+
(table) =>
|
|
1149
|
+
resolveForwardPositionMs(
|
|
1150
|
+
table,
|
|
1151
|
+
getWorkingPositionMs(table, startMs) + deltaMs,
|
|
1152
|
+
),
|
|
1153
|
+
() => getCannotFitError(calendar, minutes),
|
|
1154
|
+
),
|
|
1155
|
+
);
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
const finishMs = snapToWorkingFinish(calendar, from).getTime();
|
|
1159
|
+
|
|
1160
|
+
return new Date(
|
|
1161
|
+
walkWithExtension(
|
|
1162
|
+
calendar,
|
|
1163
|
+
finishMs,
|
|
1164
|
+
-1,
|
|
1165
|
+
(table) =>
|
|
1166
|
+
resolveBackwardPositionMs(
|
|
1167
|
+
table,
|
|
1168
|
+
getWorkingPositionMs(table, finishMs) + deltaMs,
|
|
1169
|
+
),
|
|
1170
|
+
() => getCannotFitError(calendar, -minutes),
|
|
1171
|
+
),
|
|
1172
|
+
);
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
/**
|
|
1176
|
+
* Return the signed working minutes between two instants on a calendar
|
|
1177
|
+
* (negative when "to" precedes "from"). Throws when the span exceeds
|
|
1178
|
+
* SCHEDULE_WORK_TIME_MAX_SPAN_DAYS rather than under-reporting it.
|
|
1179
|
+
*/
|
|
1180
|
+
|
|
1181
|
+
export function workingMinutesBetween(
|
|
1182
|
+
calendar: ScheduleWorkCalendarDef,
|
|
1183
|
+
from: Date,
|
|
1184
|
+
to: Date,
|
|
1185
|
+
): number {
|
|
1186
|
+
const fromMs = from.getTime();
|
|
1187
|
+
const toMs = to.getTime();
|
|
1188
|
+
|
|
1189
|
+
if (toMs === fromMs) {
|
|
1190
|
+
return 0;
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
if (toMs < fromMs) {
|
|
1194
|
+
return -workingMinutesBetween(calendar, to, from);
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
assertWorkingCalendar(calendar);
|
|
1198
|
+
|
|
1199
|
+
const table = getWorkCalendarTable(calendar, from, to);
|
|
1200
|
+
|
|
1201
|
+
return (
|
|
1202
|
+
(getWorkingPositionMs(table, toMs) - getWorkingPositionMs(table, fromMs)) /
|
|
1203
|
+
FILE_CONSTANTS.minuteMs
|
|
1204
|
+
);
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
/*
|
|
1208
|
+
* Return one table row, throwing on an index outside the table.
|
|
1209
|
+
*/
|
|
1210
|
+
|
|
1211
|
+
export function getDayEntry(
|
|
1212
|
+
table: WorkCalendarTable,
|
|
1213
|
+
dayIndex: number,
|
|
1214
|
+
): WorkCalendarDay {
|
|
1215
|
+
const day = table.days[dayIndex];
|
|
1216
|
+
|
|
1217
|
+
if (!day) {
|
|
1218
|
+
throw new RangeError(
|
|
1219
|
+
`Day index ${dayIndex} is outside the work calendar table (0..${table.days.length - 1})`,
|
|
1220
|
+
);
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
return day;
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
/**
|
|
1227
|
+
* Return the working minutes of one table day.
|
|
1228
|
+
*/
|
|
1229
|
+
|
|
1230
|
+
export function getWorkingMinutesOnDay(
|
|
1231
|
+
table: WorkCalendarTable,
|
|
1232
|
+
dayIndex: number,
|
|
1233
|
+
): number {
|
|
1234
|
+
return getDayEntry(table, dayIndex).workingMinutes;
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
/**
|
|
1238
|
+
* Return the UTC milliseconds of one table day's local midnight.
|
|
1239
|
+
*/
|
|
1240
|
+
|
|
1241
|
+
export function getDayStartMs(
|
|
1242
|
+
table: WorkCalendarTable,
|
|
1243
|
+
dayIndex: number,
|
|
1244
|
+
): number {
|
|
1245
|
+
return getDayEntry(table, dayIndex).dayStartMs;
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
/**
|
|
1249
|
+
* Return the "YYYY-MM-DD" key of one table day.
|
|
1250
|
+
*/
|
|
1251
|
+
|
|
1252
|
+
export function getDateKeyForDayIndex(
|
|
1253
|
+
table: WorkCalendarTable,
|
|
1254
|
+
dayIndex: number,
|
|
1255
|
+
): string {
|
|
1256
|
+
return getDayEntry(table, dayIndex).dateKey;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
/**
|
|
1260
|
+
* Return the indices of the table days whose working periods overlap
|
|
1261
|
+
* [from, to] by a positive amount, ascending; days outside the table are
|
|
1262
|
+
* ignored.
|
|
1263
|
+
*/
|
|
1264
|
+
|
|
1265
|
+
export function getWorkingDayIndicesBetween(
|
|
1266
|
+
table: WorkCalendarTable,
|
|
1267
|
+
from: Date,
|
|
1268
|
+
to: Date,
|
|
1269
|
+
): number[] {
|
|
1270
|
+
const fromMs = toWorkTimeDate(from).getTime();
|
|
1271
|
+
const toMs = toWorkTimeDate(to).getTime();
|
|
1272
|
+
const indices: number[] = [];
|
|
1273
|
+
|
|
1274
|
+
if (toMs <= fromMs) {
|
|
1275
|
+
return indices;
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
const firstIndex = Math.max(0, findDayIndexAtMs(table, fromMs));
|
|
1279
|
+
const lastIndex = Math.min(
|
|
1280
|
+
table.days.length - 1,
|
|
1281
|
+
findDayIndexAtMs(table, toMs),
|
|
1282
|
+
);
|
|
1283
|
+
|
|
1284
|
+
for (let i = firstIndex; i <= lastIndex; i++) {
|
|
1285
|
+
const overlaps = table.days[i].periods.some(
|
|
1286
|
+
(period) =>
|
|
1287
|
+
Math.min(period.endMs, toMs) > Math.max(period.startMs, fromMs),
|
|
1288
|
+
);
|
|
1289
|
+
|
|
1290
|
+
if (overlaps) {
|
|
1291
|
+
indices.push(i);
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
return indices;
|
|
1296
|
+
}
|
|
1297
|
+
|
|
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
|
+
/* Find a local-date row; outside dates return the corresponding table sentinel. */
|
|
1321
|
+
export function getDayIndexForDateKey(
|
|
1322
|
+
table: WorkCalendarTable,
|
|
1323
|
+
dateKey: string,
|
|
1324
|
+
): number {
|
|
1325
|
+
if (dateKey < table.days[0].dateKey) return -1;
|
|
1326
|
+
let low = 0;
|
|
1327
|
+
let high = table.days.length;
|
|
1328
|
+
while (low < high) {
|
|
1329
|
+
const mid = (low + high) >>> 1;
|
|
1330
|
+
if (table.days[mid].dateKey < dateKey) low = mid + 1;
|
|
1331
|
+
else high = mid;
|
|
1332
|
+
}
|
|
1333
|
+
return low;
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
/* Measure cumulative work at an instant, clamped to this immutable table. */
|
|
1337
|
+
export function getCumulativeMinutesAt(
|
|
1338
|
+
table: WorkCalendarTable,
|
|
1339
|
+
atMs: number,
|
|
1340
|
+
): number {
|
|
1341
|
+
return getWorkingPositionMs(table, atMs) / FILE_CONSTANTS.minuteMs;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/* Sum elapsed working minutes where a day's periods intersect a half-open range. */
|
|
1345
|
+
export function getWorkingMinutesOnDayBetween(
|
|
1346
|
+
day: WorkCalendarDay,
|
|
1347
|
+
aMs: number,
|
|
1348
|
+
bMs: number,
|
|
1349
|
+
): number {
|
|
1350
|
+
let minutes = 0;
|
|
1351
|
+
for (const period of day.periods) {
|
|
1352
|
+
minutes +=
|
|
1353
|
+
Math.max(0, Math.min(period.endMs, bMs) - Math.max(period.startMs, aMs)) /
|
|
1354
|
+
FILE_CONSTANTS.minuteMs;
|
|
1355
|
+
}
|
|
1356
|
+
return minutes;
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
/* Return merged working intervals intersecting a half-open instant range. */
|
|
1360
|
+
export function getWorkingIntervalsInRange(
|
|
1361
|
+
calendar: ScheduleWorkCalendarDef,
|
|
1362
|
+
from: Date,
|
|
1363
|
+
to: Date,
|
|
1364
|
+
): Array<{ startAt: number; endAt: number }> {
|
|
1365
|
+
const start = toWorkTimeDate(from).getTime();
|
|
1366
|
+
const end = toWorkTimeDate(to).getTime();
|
|
1367
|
+
if (end <= start || !isWorkingCalendar(calendar)) return [];
|
|
1368
|
+
const table = getWorkCalendarTable(calendar, from, to);
|
|
1369
|
+
const intervals: Array<{ startAt: number; endAt: number }> = [];
|
|
1370
|
+
for (const index of getWorkingDayIndicesBetween(table, from, to)) {
|
|
1371
|
+
for (const period of table.days[index].periods) {
|
|
1372
|
+
const startAt = Math.max(start, period.startMs);
|
|
1373
|
+
const endAt = Math.min(end, period.endMs);
|
|
1374
|
+
if (endAt <= startAt) continue;
|
|
1375
|
+
const last = intervals[intervals.length - 1];
|
|
1376
|
+
if (last && startAt <= last.endAt)
|
|
1377
|
+
last.endAt = Math.max(last.endAt, endAt);
|
|
1378
|
+
else intervals.push({ startAt, endAt });
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
return intervals;
|
|
1382
|
+
}
|