@jsb188/schedule 1.1.11 → 1.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +34 -14
  3. package/src/constants/schedule.ts +710 -306
  4. package/src/modules/Gantt.helpers.ts +11 -30
  5. package/src/modules/Gantt.tsx +46 -181
  6. package/src/types/schedule.d.ts +1827 -456
  7. package/src/ui/ProjectFormUI.tsx +8 -31
  8. package/src/ui/ScheduleSettingsUI.tsx +21 -23
  9. package/src/utils/autofill.ts +469 -0
  10. package/src/utils/availability.ts +167 -0
  11. package/src/utils/candidates.ts +447 -0
  12. package/src/utils/coverage.helpers.ts +509 -554
  13. package/src/utils/coverage.ts +1121 -526
  14. package/src/utils/cpm.helpers.ts +27 -29
  15. package/src/utils/cpm.ts +53 -41
  16. package/src/utils/cpmLeveling.helpers.ts +89 -16
  17. package/src/utils/cpmLeveling.ts +28 -26
  18. package/src/utils/cycle.ts +325 -0
  19. package/src/utils/demand.ts +239 -0
  20. package/src/utils/eligibility.ts +553 -400
  21. package/src/utils/ids.ts +47 -0
  22. package/src/utils/laborRules.ts +740 -0
  23. package/src/utils/localTime.ts +312 -0
  24. package/src/utils/offer.ts +300 -0
  25. package/src/utils/planCsv.ts +73 -19
  26. package/src/utils/predicate.ts +111 -0
  27. package/src/utils/request.ts +212 -114
  28. package/src/utils/resource.ts +412 -112
  29. package/src/utils/rule.ts +697 -163
  30. package/src/utils/rulePresets.ts +116 -0
  31. package/src/utils/run.ts +0 -8
  32. package/src/utils/scheduleText.ts +4074 -0
  33. package/src/utils/shiftChange.ts +279 -0
  34. package/src/utils/standing.ts +730 -0
  35. package/src/utils/template.ts +619 -0
  36. package/src/utils/violation.ts +184 -0
  37. package/src/utils/workTime.ts +341 -120
  38. package/src/utils/defaults.ts +0 -8
  39. package/src/utils/recurrence.ts +0 -616
  40. package/src/utils/series.ts +0 -161
  41. package/src/utils/slot.ts +0 -208
  42. package/tests/coverage.fixtures.ts +0 -111
  43. package/tests/coverage.test.ts +0 -503
  44. package/tests/cpm.bench.test.ts +0 -154
  45. package/tests/cpm.test.ts +0 -354
  46. package/tests/cpmCorrectness.test.ts +0 -327
  47. package/tests/cpmLeveling.test.ts +0 -471
  48. package/tests/eligibility.test.ts +0 -320
  49. package/tests/gantt-geometry.test.ts +0 -367
  50. package/tests/gantt-histogram.test.ts +0 -78
  51. package/tests/gantt-keyboard.test.ts +0 -69
  52. package/tests/helpers/cpmFixtures.ts +0 -101
  53. package/tests/projectInputs.test.ts +0 -165
  54. package/tests/recurrence.test.ts +0 -68
  55. package/tests/request.test.ts +0 -99
  56. package/tests/resource.test.ts +0 -95
  57. package/tests/rule.test.ts +0 -98
  58. package/tests/series.test.ts +0 -120
  59. package/tests/workTime.test.ts +0 -1007
  60. package/tests/workTimeContracts.test.ts +0 -111
  61. package/tsconfig.json +0 -13
  62. package/vitest.config.ts +0 -8
@@ -0,0 +1,312 @@
1
+ import { DateTime, IANAZone } from 'luxon';
2
+
3
+ /**
4
+ * Time primitives shared by every staff-schedule module.
5
+ *
6
+ * - A local date is a 'YYYY-MM-DD' key. Date arithmetic on keys is plain
7
+ * calendar arithmetic (UTC), so it never meets a DST change.
8
+ * - A clock time is 'HH:mm', or 'HH:mm:ss' with zero seconds as Postgres TIME
9
+ * columns return it; it is held as minutes since local midnight (0..1439).
10
+ * - A local interval (template item, availability, demand, staffing window,
11
+ * quiet hours) whose end is at or before its start ends on the next day, so
12
+ * '00:00'-'00:00' is the whole day. Wall-clock bounds are placed on their
13
+ * local date in the zone; a bound inside a spring-forward gap moves forward
14
+ * by the gap (luxon's rule), and an ambiguous fall-back time takes its first
15
+ * occurrence (the offset in force when the local day starts), whatever the
16
+ * current date is. workTime.ts resolves work-calendar hours the same way.
17
+ * - Weekdays use the JavaScript convention: 0 = Sunday ... 6 = Saturday.
18
+ */
19
+
20
+ const FILE_CONSTANTS = {
21
+ dayMs: 86_400_000,
22
+ // UTC offsets never exceed +14h, so a wall-clock date's UTC midnight minus
23
+ // this is at or before that date's local midnight in every zone
24
+ dayStartLeadMs: 14 * 3_600_000,
25
+ // Placements are pure (luxon's zone data is fixed for the process); each
26
+ // memo is cleared when it passes this many entries
27
+ memoMaxEntries: 20_000,
28
+ };
29
+
30
+ // Memoized luxon placements: zone|instant ms -> date key, zone|date|minutes ->
31
+ // epoch ms. Eligibility and coverage place the same instants many times.
32
+ const LOCAL_TIME_MEMO = {
33
+ dates: new Map<string, string>(),
34
+ instants: new Map<string, number>(),
35
+ };
36
+
37
+ /*
38
+ * Read an instant as epoch milliseconds; NaN when it is unreadable. Callers
39
+ * that need null for an absent value or a throw for a bad one wrap this.
40
+ */
41
+ export function toScheduleTimeMs(value: Date | string | number): number {
42
+ if (value instanceof Date) return value.getTime();
43
+ if (typeof value === 'number') return value;
44
+ return Date.parse(value);
45
+ }
46
+
47
+ /*
48
+ * Parse a local date key into its UTC midnight in milliseconds, or NaN when
49
+ * the key is malformed or names a day that does not exist (2026-02-30).
50
+ */
51
+ function getDateKeyUtcMs(value: string): number {
52
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
53
+ if (!match) return Number.NaN;
54
+ const ms = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
55
+ return new Date(ms).toISOString().slice(0, 10) === value ? ms : Number.NaN;
56
+ }
57
+
58
+ /*
59
+ * Format a UTC-midnight millisecond value back into a local date key.
60
+ */
61
+ function formatUtcMsAsDateKey(ms: number): string {
62
+ return new Date(ms).toISOString().slice(0, 10);
63
+ }
64
+
65
+ /*
66
+ * Check that a value is a real 'YYYY-MM-DD' calendar date.
67
+ */
68
+ export function isScheduleDateKey(value: unknown): value is string {
69
+ return typeof value === 'string' && Number.isFinite(getDateKeyUtcMs(value));
70
+ }
71
+
72
+ /*
73
+ * Normalize a DATE column value (a Date at UTC midnight, or a string) to a
74
+ * date key; null when it is unreadable.
75
+ */
76
+ export function toScheduleDateKey(value: Date | string): string | null {
77
+ const key =
78
+ value instanceof Date
79
+ ? Number.isFinite(value.getTime())
80
+ ? value.toISOString().slice(0, 10)
81
+ : ''
82
+ : String(value).slice(0, 10);
83
+ return isScheduleDateKey(key) ? key : null;
84
+ }
85
+
86
+ /*
87
+ * Shift a date key by whole days (negative moves back).
88
+ */
89
+ export function addScheduleDays(dateKey: string, days: number): string {
90
+ return formatUtcMsAsDateKey(
91
+ getDateKeyUtcMs(dateKey) + days * FILE_CONSTANTS.dayMs,
92
+ );
93
+ }
94
+
95
+ /*
96
+ * Count whole days from one date key to another (negative when toDate is
97
+ * earlier).
98
+ */
99
+ export function getScheduleDaysBetween(
100
+ fromDate: string,
101
+ toDate: string,
102
+ ): number {
103
+ return Math.round(
104
+ (getDateKeyUtcMs(toDate) - getDateKeyUtcMs(fromDate)) /
105
+ FILE_CONSTANTS.dayMs,
106
+ );
107
+ }
108
+
109
+ /*
110
+ * List every date key from fromDate to toDate inclusive ([] when toDate is
111
+ * earlier than fromDate).
112
+ */
113
+ export function listScheduleDates(fromDate: string, toDate: string): string[] {
114
+ const count = getScheduleDaysBetween(fromDate, toDate);
115
+ const dates: string[] = [];
116
+ for (let index = 0; index <= count; index++)
117
+ dates.push(addScheduleDays(fromDate, index));
118
+ return dates;
119
+ }
120
+
121
+ /*
122
+ * Return the weekday of a date key (0 = Sunday ... 6 = Saturday).
123
+ */
124
+ export function getScheduleWeekday(dateKey: string): number {
125
+ return new Date(getDateKeyUtcMs(dateKey)).getUTCDay();
126
+ }
127
+
128
+ /*
129
+ * Return the first day of the week containing a date, for weeks starting on
130
+ * payWeekStart (0 = Sunday ... 6 = Saturday). Weeks, pay weeks and periods
131
+ * all start on the organization's payWeekStart.
132
+ */
133
+ export function getScheduleWeekStart(
134
+ dateKey: string,
135
+ payWeekStart: number,
136
+ ): string {
137
+ return addScheduleDays(
138
+ dateKey,
139
+ -((getScheduleWeekday(dateKey) - payWeekStart + 7) % 7),
140
+ );
141
+ }
142
+
143
+ /*
144
+ * Parse 'HH:mm' or 'HH:mm:ss' (zero seconds only) into minutes since local
145
+ * midnight, 0..1439; null when malformed. '24:00' is not a clock time: an end
146
+ * at or before its start already means the next day.
147
+ */
148
+ export function parseScheduleClockTime(value: string): number | null {
149
+ const match = /^(\d{2}):(\d{2})(?::(\d{2}))?$/.exec(String(value ?? ''));
150
+ if (!match) return null;
151
+ const hours = Number(match[1]);
152
+ const minutes = Number(match[2]);
153
+ if (hours > 23 || minutes > 59 || (match[3] && match[3] !== '00'))
154
+ return null;
155
+ return hours * 60 + minutes;
156
+ }
157
+
158
+ /*
159
+ * Format minutes since local midnight (0..1439) as 'HH:mm'.
160
+ */
161
+ export function formatScheduleClockTime(minutes: number): string {
162
+ const hours = Math.floor(minutes / 60);
163
+ return `${String(hours).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
164
+ }
165
+
166
+ /*
167
+ * Normalize a clock time to 'HH:mm' (drops ':00' seconds); null when
168
+ * malformed.
169
+ */
170
+ export function normalizeScheduleClockTime(value: string): string | null {
171
+ const minutes = parseScheduleClockTime(value);
172
+ return minutes === null ? null : formatScheduleClockTime(minutes);
173
+ }
174
+
175
+ /*
176
+ * Return the luxon zone of an IANA name, throwing on an unknown zone (zones
177
+ * are validated on write, so this is a programming error). luxon caches one
178
+ * zone per name with its validity, so the check runs once per zone instead of
179
+ * building an Intl.DateTimeFormat on every call.
180
+ */
181
+ function getScheduleZone(timeZone: string): IANAZone {
182
+ const zone = IANAZone.create(timeZone);
183
+ if (!zone.isValid) throw new RangeError(`Invalid time zone: ${timeZone}`);
184
+ return zone;
185
+ }
186
+
187
+ /*
188
+ * Read an instant in a zone as a luxon DateTime.
189
+ */
190
+ function getZonedDateTime(at: Date | string, timeZone: string): DateTime {
191
+ return DateTime.fromMillis(toScheduleTimeMs(at), {
192
+ zone: getScheduleZone(timeZone),
193
+ });
194
+ }
195
+
196
+ /*
197
+ * Return the local date key of an instant in a zone (a seat's shiftDate is
198
+ * the local date of its startAt in the calendar's zone).
199
+ */
200
+ export function getScheduleLocalDate(
201
+ at: Date | string,
202
+ timeZone: string,
203
+ ): string {
204
+ const ms = toScheduleTimeMs(at);
205
+ if (!Number.isFinite(ms)) {
206
+ return getZonedDateTime(at, timeZone).toISODate() as string;
207
+ }
208
+ const key = `${timeZone}|${ms}`;
209
+ const cached = LOCAL_TIME_MEMO.dates.get(key);
210
+ if (cached !== undefined) return cached;
211
+ const dateKey = getZonedDateTime(at, timeZone).toISODate() as string;
212
+ rememberScheduleLocalTime(LOCAL_TIME_MEMO.dates, key, dateKey);
213
+ return dateKey;
214
+ }
215
+
216
+ /*
217
+ * Store one memoized placement, clearing the memo first when it is full.
218
+ */
219
+ function rememberScheduleLocalTime<T>(
220
+ memo: Map<string, T>,
221
+ key: string,
222
+ value: T,
223
+ ): void {
224
+ if (memo.size >= FILE_CONSTANTS.memoMaxEntries) memo.clear();
225
+ memo.set(key, value);
226
+ }
227
+
228
+ /*
229
+ * Return the local 'HH:mm' clock time of an instant in a zone.
230
+ */
231
+ export function getScheduleLocalClockTime(
232
+ at: Date | string,
233
+ timeZone: string,
234
+ ): string {
235
+ return getZonedDateTime(at, timeZone).toFormat('HH:mm');
236
+ }
237
+
238
+ /*
239
+ * Place a wall-clock time (minutes since midnight) on a local date in a zone.
240
+ * A time inside a spring-forward gap moves forward by the gap; an ambiguous
241
+ * fall-back time takes its first occurrence.
242
+ */
243
+ export function getScheduleLocalInstant(
244
+ dateKey: string,
245
+ minutes: number,
246
+ timeZone: string,
247
+ ): Date {
248
+ const key = `${timeZone}|${dateKey}|${minutes}`;
249
+ const cached = LOCAL_TIME_MEMO.instants.get(key);
250
+ // A new Date each call: callers never share one
251
+ if (cached !== undefined) return new Date(cached);
252
+ const placed = placeScheduleLocalInstant(dateKey, minutes, timeZone);
253
+ const ms = placed.getTime();
254
+ if (Number.isFinite(ms)) {
255
+ rememberScheduleLocalTime(LOCAL_TIME_MEMO.instants, key, ms);
256
+ }
257
+ return placed;
258
+ }
259
+
260
+ /*
261
+ * Place a wall-clock time on a local date in a zone with luxon (the body of
262
+ * getScheduleLocalInstant, without the memo).
263
+ */
264
+ function placeScheduleLocalInstant(
265
+ dateKey: string,
266
+ minutes: number,
267
+ timeZone: string,
268
+ ): Date {
269
+ const [year, month, day] = dateKey.split('-').map(Number);
270
+ // luxon resolves a wall time from the offset of the DateTime it is set on
271
+ // (DateTime.fromObject would use today's offset), so start from an instant
272
+ // before the local day begins: the result never depends on the clock
273
+ return DateTime.fromMillis(
274
+ Date.UTC(year, month - 1, day) - FILE_CONSTANTS.dayStartLeadMs,
275
+ { zone: getScheduleZone(timeZone) },
276
+ )
277
+ .set({
278
+ year,
279
+ month,
280
+ day,
281
+ hour: Math.floor(minutes / 60),
282
+ minute: minutes % 60,
283
+ second: 0,
284
+ millisecond: 0,
285
+ })
286
+ .toJSDate();
287
+ }
288
+
289
+ /*
290
+ * Place a local interval that starts on dateKey: an end at or before the
291
+ * start ends on the next day ('00:00'-'00:00' = the whole day). Returns null
292
+ * when either clock time is malformed.
293
+ */
294
+ export function getScheduleLocalInterval(
295
+ dateKey: string,
296
+ startTime: string,
297
+ endTime: string,
298
+ timeZone: string,
299
+ ): { startAt: Date; endAt: Date } | null {
300
+ const start = parseScheduleClockTime(startTime);
301
+ const end = parseScheduleClockTime(endTime);
302
+ if (start === null || end === null || !isScheduleDateKey(dateKey))
303
+ return null;
304
+ return {
305
+ startAt: getScheduleLocalInstant(dateKey, start, timeZone),
306
+ endAt: getScheduleLocalInstant(
307
+ end <= start ? addScheduleDays(dateKey, 1) : dateKey,
308
+ end,
309
+ timeZone,
310
+ ),
311
+ };
312
+ }
@@ -0,0 +1,300 @@
1
+ import {
2
+ SCHEDULE_OFFER_MESSAGE_MAX_LENGTH,
3
+ SCHEDULE_OFFER_MIN_LEAD_MINUTES,
4
+ SCHEDULE_OFFER_URGENT_HOURS,
5
+ } from '../constants/schedule.ts';
6
+ import type {
7
+ ScheduleOfferDefaultsObj,
8
+ ScheduleQuietHoursObj,
9
+ } from '../types/schedule.d.ts';
10
+ import {
11
+ addScheduleDays,
12
+ getScheduleLocalDate,
13
+ getScheduleLocalInterval,
14
+ toScheduleTimeMs,
15
+ } from './localTime.ts';
16
+ import { isScheduleRecord } from './resource.ts';
17
+ import { toScheduleGsmText } from './scheduleText.ts';
18
+
19
+ /**
20
+ * Offers (IMPLEMENTATION §1.8): the options a manager may set on one
21
+ * offer, quiet hours, and the waves an offer's ranked candidates are texted
22
+ * in. Pure: `now` is always an input.
23
+ *
24
+ * - Wave k is sent one response window after wave k - 1 (wave 1 at `now`),
25
+ * each send time moved out of the calendar's quiet hours unless the seat
26
+ * starts within SCHEDULE_OFFER_URGENT_HOURS. Waves are spaced from the
27
+ * previous wave's actual send time, so waves that fall in quiet hours stay
28
+ * a response window apart after them instead of all going out at once.
29
+ * - A candidate whose send time is at or after the offer's expiry is not
30
+ * asked.
31
+ */
32
+
33
+ // The validated options of one offer
34
+ export interface ScheduleOfferOptionsObj {
35
+ waveSize: number;
36
+ responseWindowMinutes: number;
37
+ autoApprove: boolean;
38
+ expiresAt: Date;
39
+ message: string | null;
40
+ }
41
+
42
+ const FILE_CONSTANTS = {
43
+ keys: [
44
+ 'waveSize',
45
+ 'responseWindowMinutes',
46
+ 'autoApprove',
47
+ 'expiresAt',
48
+ 'message',
49
+ ],
50
+ // schedule_offers_wave_size_check and schedule_offers_window_check
51
+ minWaveSize: 1,
52
+ maxWaveSize: 50,
53
+ minResponseWindowMinutes: 5,
54
+ maxResponseWindowMinutes: 1440,
55
+ minuteMs: 60_000,
56
+ hourMs: 3_600_000,
57
+ };
58
+
59
+ /*
60
+ * Whether a value is an integer within [min, max].
61
+ */
62
+ function isIntegerInRange(value: unknown, min: number, max: number): boolean {
63
+ return (
64
+ typeof value === 'number' &&
65
+ Number.isInteger(value) &&
66
+ value >= min &&
67
+ value <= max
68
+ );
69
+ }
70
+
71
+ /*
72
+ * Validate an offer's expiry against `now` and the seat's start: missing
73
+ * means the seat's start; earlier than SCHEDULE_OFFER_MIN_LEAD_MINUTES from
74
+ * now is an error; later than the seat's start is clamped to it.
75
+ */
76
+ function validateOfferExpiry(
77
+ value: unknown,
78
+ shiftStartMs: number,
79
+ nowMs: number,
80
+ ): { value?: Date; error?: string } {
81
+ if (value == null) return { value: new Date(shiftStartMs) };
82
+ const ms =
83
+ typeof value === 'string' || value instanceof Date
84
+ ? toScheduleTimeMs(value)
85
+ : Number.NaN;
86
+ if (!Number.isFinite(ms))
87
+ return { error: 'expiresAt must be an ISO date and time.' };
88
+ if (ms - nowMs < SCHEDULE_OFFER_MIN_LEAD_MINUTES * FILE_CONSTANTS.minuteMs)
89
+ return {
90
+ error: `expiresAt must be at least ${SCHEDULE_OFFER_MIN_LEAD_MINUTES} minutes from now.`,
91
+ };
92
+ return { value: new Date(Math.min(ms, shiftStartMs)) };
93
+ }
94
+
95
+ /*
96
+ * Validate an offer's message: a string, GSM-7 punctuation folded, trimmed,
97
+ * at most SCHEDULE_OFFER_MESSAGE_MAX_LENGTH characters; empty or missing is
98
+ * null.
99
+ */
100
+ function validateOfferMessage(value: unknown): {
101
+ value?: string | null;
102
+ error?: string;
103
+ } {
104
+ if (value == null) return { value: null };
105
+ if (typeof value !== 'string') return { error: 'message must be a string.' };
106
+ const message = toScheduleGsmText(value).trim();
107
+ if (message.length > SCHEDULE_OFFER_MESSAGE_MAX_LENGTH)
108
+ return {
109
+ error: `message must be at most ${SCHEDULE_OFFER_MESSAGE_MAX_LENGTH} characters.`,
110
+ };
111
+ return { value: message || null };
112
+ }
113
+
114
+ /*
115
+ * Validate the numeric and boolean options, each falling back to the
116
+ * calendar's offer defaults when missing (undefined or null).
117
+ */
118
+ function validateOfferSettings(
119
+ raw: Record<string, unknown>,
120
+ defaults: ScheduleOfferDefaultsObj,
121
+ ): {
122
+ value?: Pick<
123
+ ScheduleOfferOptionsObj,
124
+ 'waveSize' | 'responseWindowMinutes' | 'autoApprove'
125
+ >;
126
+ error?: string;
127
+ } {
128
+ const waveSize = raw.waveSize ?? defaults.waveSize;
129
+ const responseWindowMinutes =
130
+ raw.responseWindowMinutes ?? defaults.responseWindowMinutes;
131
+ const autoApprove = raw.autoApprove ?? defaults.autoApprove;
132
+ if (
133
+ !isIntegerInRange(
134
+ waveSize,
135
+ FILE_CONSTANTS.minWaveSize,
136
+ FILE_CONSTANTS.maxWaveSize,
137
+ )
138
+ )
139
+ return {
140
+ error: `waveSize must be a whole number from ${FILE_CONSTANTS.minWaveSize} to ${FILE_CONSTANTS.maxWaveSize}.`,
141
+ };
142
+ if (
143
+ !isIntegerInRange(
144
+ responseWindowMinutes,
145
+ FILE_CONSTANTS.minResponseWindowMinutes,
146
+ FILE_CONSTANTS.maxResponseWindowMinutes,
147
+ )
148
+ )
149
+ return {
150
+ error: `responseWindowMinutes must be a whole number from ${FILE_CONSTANTS.minResponseWindowMinutes} to ${FILE_CONSTANTS.maxResponseWindowMinutes}.`,
151
+ };
152
+ if (typeof autoApprove !== 'boolean')
153
+ return { error: 'autoApprove must be true or false.' };
154
+ return {
155
+ value: {
156
+ waveSize: waveSize as number,
157
+ responseWindowMinutes: responseWindowMinutes as number,
158
+ autoApprove,
159
+ },
160
+ };
161
+ }
162
+
163
+ /*
164
+ * Validate the options of one offer (keys waveSize 1..50,
165
+ * responseWindowMinutes 5..1440, autoApprove, expiresAt, message). Missing
166
+ * keys (undefined or null) come from the calendar's offer defaults; a
167
+ * missing expiresAt is the seat's start. Unknown keys, a seat starting within
168
+ * SCHEDULE_OFFER_MIN_LEAD_MINUTES and any invalid value are errors.
169
+ */
170
+ export function validateScheduleOfferInput(
171
+ input: unknown,
172
+ args: {
173
+ defaults: ScheduleOfferDefaultsObj;
174
+ shiftStartAt: Date | string;
175
+ now: Date | string;
176
+ },
177
+ ): { value?: ScheduleOfferOptionsObj; error?: string } {
178
+ const raw = input == null ? {} : input;
179
+ if (!isScheduleRecord(raw))
180
+ return { error: 'Offer options must be an object.' };
181
+ const unknown = Object.keys(raw).find(
182
+ (key) => !FILE_CONSTANTS.keys.includes(key),
183
+ );
184
+ if (unknown) return { error: `Unknown offer option: ${unknown}.` };
185
+ const shiftStartMs = toScheduleTimeMs(args.shiftStartAt);
186
+ const nowMs = toScheduleTimeMs(args.now);
187
+ if (
188
+ !(
189
+ shiftStartMs - nowMs >=
190
+ SCHEDULE_OFFER_MIN_LEAD_MINUTES * FILE_CONSTANTS.minuteMs
191
+ )
192
+ )
193
+ return { error: 'The shift starts too soon to offer.' };
194
+ const settings = validateOfferSettings(raw, args.defaults);
195
+ if (settings.error) return { error: settings.error };
196
+ const expiresAt = validateOfferExpiry(raw.expiresAt, shiftStartMs, nowMs);
197
+ if (expiresAt.error) return { error: expiresAt.error };
198
+ const message = validateOfferMessage(raw.message);
199
+ if (message.error) return { error: message.error };
200
+ return {
201
+ value: {
202
+ ...settings.value!,
203
+ expiresAt: expiresAt.value!,
204
+ message: message.value ?? null,
205
+ },
206
+ };
207
+ }
208
+
209
+ /*
210
+ * Return the end of the local quiet interval holding `at` (the one starting
211
+ * on its local day or the day before, since quiet hours usually cross
212
+ * midnight), or null when `at` is outside quiet hours. Equal or unreadable
213
+ * bounds mean no quiet hours.
214
+ */
215
+ function getQuietIntervalEnd(
216
+ at: Date,
217
+ quietHours: ScheduleQuietHoursObj,
218
+ timeZone: string,
219
+ ): Date | null {
220
+ if (quietHours.start === quietHours.end) return null;
221
+ const atMs = at.getTime();
222
+ const date = getScheduleLocalDate(at, timeZone);
223
+ for (const day of [addScheduleDays(date, -1), date]) {
224
+ const interval = getScheduleLocalInterval(
225
+ day,
226
+ quietHours.start,
227
+ quietHours.end,
228
+ timeZone,
229
+ );
230
+ if (
231
+ interval &&
232
+ interval.startAt.getTime() <= atMs &&
233
+ atMs < interval.endAt.getTime()
234
+ )
235
+ return interval.endAt;
236
+ }
237
+ return null;
238
+ }
239
+
240
+ /*
241
+ * When to send a text planned for `at`: the local end of the quiet interval
242
+ * holding it, unless there are no quiet hours, `at` is outside them, or the
243
+ * seat starts less than SCHEDULE_OFFER_URGENT_HOURS after `at` (an urgent
244
+ * seat ignores quiet hours). DST-safe: local times are placed in the zone.
245
+ */
246
+ export function getScheduleQuietHoursSendAt(args: {
247
+ at: Date;
248
+ quietHours: ScheduleQuietHoursObj | null;
249
+ timeZone: string;
250
+ shiftStartAt: Date | string;
251
+ }): Date {
252
+ if (!args.quietHours) return args.at;
253
+ if (
254
+ toScheduleTimeMs(args.shiftStartAt) - args.at.getTime() <
255
+ SCHEDULE_OFFER_URGENT_HOURS * FILE_CONSTANTS.hourMs
256
+ )
257
+ return args.at;
258
+ return (
259
+ getQuietIntervalEnd(args.at, args.quietHours, args.timeZone) ?? args.at
260
+ );
261
+ }
262
+
263
+ /*
264
+ * Plan the waves of an offer for its reachable eligible candidates (best
265
+ * first): candidate i is in wave floor(i / waveSize) + 1. Wave 1 is sent at
266
+ * `now`, each later wave responseWindowMinutes after the previous wave's send
267
+ * time; every send time is moved out of quiet hours. Candidates whose send
268
+ * time is at or after expiresAt are dropped.
269
+ */
270
+ export function getScheduleOfferWaves(args: {
271
+ resourceIds: string[];
272
+ waveSize: number;
273
+ responseWindowMinutes: number;
274
+ quietHours: ScheduleQuietHoursObj | null;
275
+ timeZone: string;
276
+ shiftStartAt: Date | string;
277
+ expiresAt: Date | string;
278
+ now: Date | string;
279
+ }): Array<{ resourceId: string; wave: number; sendAt: Date }> {
280
+ const waveSize = Math.max(1, Math.floor(args.waveSize));
281
+ const gapMs =
282
+ Math.max(0, args.responseWindowMinutes) * FILE_CONSTANTS.minuteMs;
283
+ const expiresMs = toScheduleTimeMs(args.expiresAt);
284
+ const waves: Array<{ resourceId: string; wave: number; sendAt: Date }> = [];
285
+ let sendAt = new Date(toScheduleTimeMs(args.now));
286
+ for (let index = 0; index < args.resourceIds.length; index += waveSize) {
287
+ const wave = index / waveSize + 1;
288
+ const planned = wave === 1 ? sendAt : new Date(sendAt.getTime() + gapMs);
289
+ sendAt = getScheduleQuietHoursSendAt({
290
+ at: planned,
291
+ quietHours: args.quietHours,
292
+ timeZone: args.timeZone,
293
+ shiftStartAt: args.shiftStartAt,
294
+ });
295
+ if (!(sendAt.getTime() < expiresMs)) break;
296
+ for (const resourceId of args.resourceIds.slice(index, index + waveSize))
297
+ waves.push({ resourceId, wave, sendAt: new Date(sendAt) });
298
+ }
299
+ return waves;
300
+ }