@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,325 @@
1
+ import { SCHEDULE_CYCLE_MAX_WEEKS } from '../constants/schedule.ts';
2
+ import type {
3
+ SchedulePeriodBaselineWeekObj,
4
+ SchedulePeriodObj,
5
+ SchedulePeriodWeekObj,
6
+ ScheduleTemplateRotationObj,
7
+ } from '../types/schedule.d.ts';
8
+ import {
9
+ addScheduleDays,
10
+ getScheduleDaysBetween,
11
+ getScheduleLocalInstant,
12
+ getScheduleWeekStart,
13
+ isScheduleDateKey,
14
+ } from './localTime.ts';
15
+ import { getRotationWeek } from './template.ts';
16
+
17
+ /**
18
+ * The preparation cycle (IMPLEMENTATION §1.12, PLAN §4.4): which period
19
+ * is prepared next, when it is due, the pay weeks it covers with their
20
+ * rotation weeks, and the published weeks each of them is compared with.
21
+ *
22
+ * - Periods are consecutive blocks of `weeks` pay weeks (weeks start on the
23
+ * organization's payWeekStart). The next one continues from the later of
24
+ * preparedThrough and the last published date while that reaches today,
25
+ * else it starts at the first pay week after today.
26
+ * - A start that is not a pay-week start (payWeekStart changed, or a custom
27
+ * range was prepared) gives one transitional period: the partial week plus
28
+ * `weeks` full weeks, so no date is ever skipped and the next period is
29
+ * aligned again.
30
+ * - Pure: `today` is an input; dates are calendar-local 'YYYY-MM-DD'.
31
+ */
32
+
33
+ /*
34
+ * Throw a RangeError unless a value is a real 'YYYY-MM-DD' date.
35
+ */
36
+ function assertScheduleDateKey(value: unknown, name: string): string {
37
+ if (!isScheduleDateKey(value))
38
+ throw new RangeError(`${name} must be a date (YYYY-MM-DD)`);
39
+ return value;
40
+ }
41
+
42
+ /*
43
+ * Throw a RangeError unless a value is a whole number from min to max.
44
+ */
45
+ function assertScheduleWholeNumber(
46
+ value: unknown,
47
+ min: number,
48
+ max: number,
49
+ name: string,
50
+ ): number {
51
+ if (
52
+ !Number.isInteger(value) ||
53
+ (value as number) < min ||
54
+ (value as number) > max
55
+ )
56
+ throw new RangeError(
57
+ `${name} must be a whole number from ${min} to ${max}`,
58
+ );
59
+ return value as number;
60
+ }
61
+
62
+ /*
63
+ * Return the later of two optional date keys (null when both are null).
64
+ */
65
+ function getLaterScheduleDate(
66
+ a: string | null,
67
+ b: string | null,
68
+ ): string | null {
69
+ if (a === null) return b;
70
+ if (b === null) return a;
71
+ return a > b ? a : b;
72
+ }
73
+
74
+ /*
75
+ * The date a calendar's published run is read from: the later of
76
+ * preparedThrough and yesterday (a run must reach today to continue the
77
+ * cycle).
78
+ */
79
+ export function getSchedulePublishedRunAfterDate(
80
+ preparedThrough: string | null,
81
+ today: string,
82
+ ): string {
83
+ const yesterday = addScheduleDays(assertScheduleDateKey(today, 'today'), -1);
84
+ return preparedThrough && preparedThrough > yesterday
85
+ ? preparedThrough
86
+ : yesterday;
87
+ }
88
+
89
+ /*
90
+ * The last date of the published run that continues a date: the calendar's
91
+ * published ranges (local dates, any order, overlaps allowed) are walked from
92
+ * afterDate, each range starting no later than the day after the run's end
93
+ * extending it. Null when the day after afterDate is not published. A range
94
+ * published far ahead (a holiday published early) is not part of the run, so
95
+ * the cycle never skips the weeks before it. Throws a RangeError on a
96
+ * malformed afterDate; malformed ranges are ignored.
97
+ */
98
+ export function getSchedulePublishedRunEnd(args: {
99
+ afterDate: string;
100
+ ranges: SchedulePeriodObj[];
101
+ }): string | null {
102
+ const afterDate = assertScheduleDateKey(args.afterDate, 'afterDate');
103
+ const ranges = args.ranges
104
+ .filter(
105
+ (range) =>
106
+ isScheduleDateKey(range.fromDate) &&
107
+ isScheduleDateKey(range.toDate) &&
108
+ range.fromDate <= range.toDate,
109
+ )
110
+ .sort((a, b) =>
111
+ a.fromDate < b.fromDate ? -1 : a.fromDate > b.fromDate ? 1 : 0,
112
+ );
113
+ let end = afterDate;
114
+ for (const range of ranges) {
115
+ if (range.toDate <= end) continue;
116
+ if (range.fromDate > addScheduleDays(end, 1)) break;
117
+ end = range.toDate;
118
+ }
119
+ return end > afterDate ? end : null;
120
+ }
121
+
122
+ /*
123
+ * The next period of a calendar's cycle. base = the later of
124
+ * preparedThrough and lastPublishedDate (the end of the published run that
125
+ * continues preparedThrough or yesterday, getSchedulePublishedRunEnd; never a
126
+ * bare latest publication). It starts the day after base when
127
+ * base reaches today (continuity), else on the first pay-week start after
128
+ * today. It ends with its `weeks`-th full pay week, so a start that is not a
129
+ * pay-week start adds its partial week. Throws a RangeError on a malformed
130
+ * date, payWeekStart or `weeks` outside 1..SCHEDULE_CYCLE_MAX_WEEKS.
131
+ */
132
+ export function getScheduleNextPeriod(args: {
133
+ weeks: number;
134
+ payWeekStart: number;
135
+ preparedThrough: string | null;
136
+ lastPublishedDate: string | null;
137
+ today: string;
138
+ }): SchedulePeriodObj {
139
+ const weeks = assertScheduleWholeNumber(
140
+ args.weeks,
141
+ 1,
142
+ SCHEDULE_CYCLE_MAX_WEEKS,
143
+ 'weeks',
144
+ );
145
+ const payWeekStart = assertScheduleWholeNumber(
146
+ args.payWeekStart,
147
+ 0,
148
+ 6,
149
+ 'payWeekStart',
150
+ );
151
+ const today = assertScheduleDateKey(args.today, 'today');
152
+ const base = getLaterScheduleDate(
153
+ args.preparedThrough === null
154
+ ? null
155
+ : assertScheduleDateKey(args.preparedThrough, 'preparedThrough'),
156
+ args.lastPublishedDate === null
157
+ ? null
158
+ : assertScheduleDateKey(args.lastPublishedDate, 'lastPublishedDate'),
159
+ );
160
+ const fromDate =
161
+ base !== null && base >= today
162
+ ? addScheduleDays(base, 1)
163
+ : addScheduleDays(getScheduleWeekStart(today, payWeekStart), 7);
164
+ const weekStart = getScheduleWeekStart(fromDate, payWeekStart);
165
+ const firstFull =
166
+ weekStart === fromDate ? fromDate : addScheduleDays(weekStart, 7);
167
+ return { fromDate, toDate: addScheduleDays(firstFull, 7 * weeks - 1) };
168
+ }
169
+
170
+ /*
171
+ * When a period is due for preparation: prepareAtHour:00 local time,
172
+ * prepareDaysBefore days before its first day (a time inside a
173
+ * spring-forward gap moves forward). Throws a RangeError on a malformed
174
+ * date, day count or hour, or an unknown zone.
175
+ */
176
+ export function getSchedulePeriodDueAt(args: {
177
+ fromDate: string;
178
+ prepareDaysBefore: number;
179
+ prepareAtHour: number;
180
+ timeZone: string;
181
+ }): Date {
182
+ const fromDate = assertScheduleDateKey(args.fromDate, 'fromDate');
183
+ const days = assertScheduleWholeNumber(
184
+ args.prepareDaysBefore,
185
+ 0,
186
+ Number.MAX_SAFE_INTEGER,
187
+ 'prepareDaysBefore',
188
+ );
189
+ const hour = assertScheduleWholeNumber(
190
+ args.prepareAtHour,
191
+ 0,
192
+ 23,
193
+ 'prepareAtHour',
194
+ );
195
+ return getScheduleLocalInstant(
196
+ addScheduleDays(fromDate, -days),
197
+ hour * 60,
198
+ args.timeZone,
199
+ );
200
+ }
201
+
202
+ /*
203
+ * Return the rotation that names weeks: one of two or more weeks, else null
204
+ * (a one-week standing schedule has no week A / week B).
205
+ */
206
+ function getNamedScheduleRotation(
207
+ rotation: ScheduleTemplateRotationObj | null,
208
+ ): ScheduleTemplateRotationObj | null {
209
+ return rotation && rotation.rotationWeeks > 1 ? rotation : null;
210
+ }
211
+
212
+ /*
213
+ * List the pay weeks a period touches (each starting on payWeekStart), with
214
+ * the standing schedule's rotation week of each, or null without a rotation
215
+ * of two or more weeks.
216
+ */
217
+ export function getSchedulePeriodWeeks(args: {
218
+ fromDate: string;
219
+ toDate: string;
220
+ payWeekStart: number;
221
+ rotation: ScheduleTemplateRotationObj | null;
222
+ }): SchedulePeriodWeekObj[] {
223
+ const rotation = getNamedScheduleRotation(args.rotation);
224
+ const weeks: SchedulePeriodWeekObj[] = [];
225
+ for (
226
+ let weekStart = getScheduleWeekStart(args.fromDate, args.payWeekStart);
227
+ weekStart <= args.toDate;
228
+ weekStart = addScheduleDays(weekStart, 7)
229
+ )
230
+ weeks.push({
231
+ weekStart,
232
+ rotationWeek: rotation
233
+ ? getRotationWeek(weekStart, rotation, args.payWeekStart)
234
+ : null,
235
+ });
236
+ return weeks;
237
+ }
238
+
239
+ /*
240
+ * List the period's dates inside one pay week (its first and last week may
241
+ * be partial).
242
+ */
243
+ function getSchedulePeriodWeekDates(
244
+ weekStart: string,
245
+ fromDate: string,
246
+ toDate: string,
247
+ ): string[] {
248
+ const dates: string[] = [];
249
+ for (let offset = 0; offset < 7; offset++) {
250
+ const date = addScheduleDays(weekStart, offset);
251
+ if (date >= fromDate && date <= toDate) dates.push(date);
252
+ }
253
+ return dates;
254
+ }
255
+
256
+ /*
257
+ * The diff baseline of each pay week of a period: the latest
258
+ * pay week before the period's first week that holds a published date and
259
+ * has the same rotation week (any such week without a rotation of two or
260
+ * more weeks). baselineDates are the week's period dates moved to the
261
+ * baseline week, so a partial week compares the same weekdays. A week with
262
+ * no such baseline has baselineWeekStart null and baselineDates [].
263
+ */
264
+ export function getSchedulePeriodBaselineWeeks(args: {
265
+ fromDate: string;
266
+ toDate: string;
267
+ payWeekStart: number;
268
+ rotation: ScheduleTemplateRotationObj | null;
269
+ publishedDates: string[];
270
+ }): SchedulePeriodBaselineWeekObj[] {
271
+ const rotation = getNamedScheduleRotation(args.rotation);
272
+ const firstWeekStart = getScheduleWeekStart(args.fromDate, args.payWeekStart);
273
+ // Candidate weeks, latest first
274
+ const candidates = [
275
+ ...new Set(
276
+ args.publishedDates
277
+ .filter(isScheduleDateKey)
278
+ .map((date) => getScheduleWeekStart(date, args.payWeekStart))
279
+ .filter((weekStart) => weekStart < firstWeekStart),
280
+ ),
281
+ ].sort((a, b) => (a < b ? 1 : a > b ? -1 : 0));
282
+ return getSchedulePeriodWeeks({
283
+ fromDate: args.fromDate,
284
+ toDate: args.toDate,
285
+ payWeekStart: args.payWeekStart,
286
+ rotation,
287
+ }).map((week) => {
288
+ const dates = getSchedulePeriodWeekDates(
289
+ week.weekStart,
290
+ args.fromDate,
291
+ args.toDate,
292
+ );
293
+ const baselineWeekStart =
294
+ candidates.find(
295
+ (candidate) =>
296
+ !rotation ||
297
+ getRotationWeek(candidate, rotation, args.payWeekStart) ===
298
+ week.rotationWeek,
299
+ ) ?? null;
300
+ const days =
301
+ baselineWeekStart === null
302
+ ? 0
303
+ : getScheduleDaysBetween(week.weekStart, baselineWeekStart);
304
+ return {
305
+ weekStart: week.weekStart,
306
+ dates,
307
+ baselineWeekStart,
308
+ baselineDates:
309
+ baselineWeekStart === null
310
+ ? []
311
+ : dates.map((date) => addScheduleDays(date, days)),
312
+ };
313
+ });
314
+ }
315
+
316
+ /*
317
+ * Check whether a prepared range covers the first day of the calendar's next
318
+ * period (only then does preparedThrough move to the range's end).
319
+ */
320
+ export function coversScheduleNextPeriod(
321
+ range: SchedulePeriodObj,
322
+ next: SchedulePeriodObj,
323
+ ): boolean {
324
+ return range.fromDate <= next.fromDate && next.fromDate <= range.toDate;
325
+ }
@@ -0,0 +1,239 @@
1
+ import type {
2
+ CoverageDemandOverrideInput,
3
+ CoverageDemandPatternInput,
4
+ ScheduleDemandIntervalObj,
5
+ } from '../types/schedule.d.ts';
6
+ import { compareScheduleIds } from './ids.ts';
7
+ import {
8
+ getScheduleLocalInterval,
9
+ getScheduleWeekday,
10
+ isScheduleDateKey,
11
+ listScheduleDates,
12
+ } from './localTime.ts';
13
+ import {
14
+ getScheduleId,
15
+ getScheduleKey,
16
+ getUnknownScheduleKey,
17
+ isScheduleRecord,
18
+ isScheduleWeekday,
19
+ validateScheduleClockTimesInput,
20
+ validateScheduleEffectiveDatesInput,
21
+ } from './resource.ts';
22
+
23
+ /**
24
+ * Demand: expected children per room and age group, in calendar-local time.
25
+ *
26
+ * - A pattern repeats on a weekday inside its effective dates.
27
+ * - An override is dated. Any override row for (room, key, date) replaces
28
+ * that date's pattern rows for that room and key entirely; quantity 0
29
+ * means nobody that day.
30
+ * - A window whose end is at or before its start ends the next day, and
31
+ * belongs to the date it starts on. Callers expand from one day before
32
+ * their window so the previous evening's spill is included.
33
+ */
34
+
35
+ const FILE_CONSTANTS = {
36
+ patternKeys: [
37
+ 'resourceId',
38
+ 'key',
39
+ 'weekday',
40
+ 'startTime',
41
+ 'endTime',
42
+ 'quantity',
43
+ 'effectiveFrom',
44
+ 'effectiveTo',
45
+ ],
46
+ overrideKeys: [
47
+ 'resourceId',
48
+ 'key',
49
+ 'date',
50
+ 'startTime',
51
+ 'endTime',
52
+ 'quantity',
53
+ ],
54
+ // NUMERIC(12, 2)
55
+ maxQuantity: 1e10,
56
+ };
57
+
58
+ type DemandRow = CoverageDemandPatternInput | CoverageDemandOverrideInput;
59
+
60
+ /*
61
+ * Check that a demand quantity is a finite number, at least 0, below the
62
+ * column bound, with at most two decimals.
63
+ */
64
+ function isScheduleDemandQuantity(value: unknown): value is number {
65
+ return (
66
+ typeof value === 'number' &&
67
+ Number.isFinite(value) &&
68
+ value >= 0 &&
69
+ value < FILE_CONSTANTS.maxQuantity &&
70
+ Math.abs(value * 100 - Math.round(value * 100)) <= 1e-7
71
+ );
72
+ }
73
+
74
+ /*
75
+ * Validate the fields patterns and overrides share: the room id, the
76
+ * age-group key, the wall-clock times and the quantity.
77
+ */
78
+ function validateScheduleDemandFields(input: Record<string, unknown>): {
79
+ fields?: Pick<
80
+ CoverageDemandPatternInput,
81
+ 'resourceId' | 'key' | 'startTime' | 'endTime' | 'quantity'
82
+ >;
83
+ error?: string;
84
+ } {
85
+ const resourceId = getScheduleId(input.resourceId);
86
+ if (!resourceId) return { error: 'Demand needs a room (resourceId).' };
87
+ const key = getScheduleKey(input.key);
88
+ if (!key) return { error: 'Demand needs an age-group key.' };
89
+ const { times, error } = validateScheduleClockTimesInput(input);
90
+ if (!times) return { error };
91
+ if (!isScheduleDemandQuantity(input.quantity))
92
+ return {
93
+ error:
94
+ 'Demand quantity must be a number, 0 or more, with at most two decimal places.',
95
+ };
96
+ return { fields: { resourceId, key, ...times, quantity: input.quantity } };
97
+ }
98
+
99
+ /*
100
+ * Validate a recurring demand pattern write: room, key, weekday 0..6, times
101
+ * normalized to 'HH:mm', quantity, and effective dates.
102
+ */
103
+ export function validateScheduleDemandPatternInput(input: unknown): {
104
+ pattern?: Omit<CoverageDemandPatternInput, 'id'>;
105
+ error?: string;
106
+ } {
107
+ if (!isScheduleRecord(input))
108
+ return { error: 'A demand pattern must be an object.' };
109
+ const unknown = getUnknownScheduleKey(input, FILE_CONSTANTS.patternKeys);
110
+ if (unknown) return { error: `Unknown demand pattern field: ${unknown}.` };
111
+ const { fields, error } = validateScheduleDemandFields(input);
112
+ if (!fields) return { error };
113
+ if (!isScheduleWeekday(input.weekday))
114
+ return { error: 'The weekday must be 0 (Sunday) to 6 (Saturday).' };
115
+ const { dates, error: datesError } =
116
+ validateScheduleEffectiveDatesInput(input);
117
+ if (!dates) return { error: datesError };
118
+ return { pattern: { ...fields, weekday: input.weekday, ...dates } };
119
+ }
120
+
121
+ /*
122
+ * Validate a dated demand override write: room, key, the calendar-local date
123
+ * it replaces, times normalized to 'HH:mm', and quantity (0 = nobody).
124
+ */
125
+ export function validateScheduleDemandOverrideInput(input: unknown): {
126
+ override?: Omit<CoverageDemandOverrideInput, 'id'>;
127
+ error?: string;
128
+ } {
129
+ if (!isScheduleRecord(input))
130
+ return { error: 'A demand override must be an object.' };
131
+ const unknown = getUnknownScheduleKey(input, FILE_CONSTANTS.overrideKeys);
132
+ if (unknown) return { error: `Unknown demand override field: ${unknown}.` };
133
+ const { fields, error } = validateScheduleDemandFields(input);
134
+ if (!fields) return { error };
135
+ if (!isScheduleDateKey(input.date))
136
+ return { error: 'The override date must be a date (YYYY-MM-DD).' };
137
+ return { override: { ...fields, date: input.date } };
138
+ }
139
+
140
+ /*
141
+ * Build the lookup key of one (room, age group, date).
142
+ */
143
+ function getDemandDayKey(
144
+ resourceId: string,
145
+ key: string,
146
+ date: string,
147
+ ): string {
148
+ return `${resourceId}\u0000${key}\u0000${date}`;
149
+ }
150
+
151
+ /*
152
+ * Place one demand row on the local date it starts; null when its times are
153
+ * malformed or it has nobody (NUMERIC columns may arrive as strings, so the
154
+ * quantity is read as a number).
155
+ */
156
+ function getScheduleDemandInterval(
157
+ row: DemandRow,
158
+ date: string,
159
+ source: ScheduleDemandIntervalObj['source'],
160
+ timeZone: string,
161
+ ): ScheduleDemandIntervalObj | null {
162
+ const quantity = Number(row.quantity);
163
+ const interval = getScheduleLocalInterval(
164
+ date,
165
+ row.startTime,
166
+ row.endTime,
167
+ timeZone,
168
+ );
169
+ if (!interval || !(quantity > 0)) return null;
170
+ return {
171
+ resourceId: row.resourceId,
172
+ key: row.key,
173
+ quantity,
174
+ startAt: interval.startAt,
175
+ endAt: interval.endAt,
176
+ source,
177
+ sourceId: row.id,
178
+ };
179
+ }
180
+
181
+ /*
182
+ * Order demand intervals by startAt, room, key, source id and source.
183
+ */
184
+ function compareScheduleDemandIntervals(
185
+ a: ScheduleDemandIntervalObj,
186
+ b: ScheduleDemandIntervalObj,
187
+ ): number {
188
+ return (
189
+ a.startAt.getTime() - b.startAt.getTime() ||
190
+ compareScheduleIds(a.resourceId, b.resourceId) ||
191
+ (a.key < b.key ? -1 : a.key > b.key ? 1 : 0) ||
192
+ compareScheduleIds(a.sourceId, b.sourceId) ||
193
+ (a.source < b.source ? -1 : a.source > b.source ? 1 : 0)
194
+ );
195
+ }
196
+
197
+ /*
198
+ * Expand demand into intervals for every local start date in
199
+ * [fromDate, toDate] in the calendar zone. A date with any override for
200
+ * (room, key) takes only its overrides; otherwise the patterns whose weekday
201
+ * matches and whose effective dates contain it. Rows with quantity 0 emit
202
+ * nothing. Sorted by startAt, room, key, source id.
203
+ */
204
+ export function expandScheduleDemand(args: {
205
+ patterns: CoverageDemandPatternInput[];
206
+ overrides: CoverageDemandOverrideInput[];
207
+ fromDate: string;
208
+ toDate: string;
209
+ timeZone: string;
210
+ }): ScheduleDemandIntervalObj[] {
211
+ const { fromDate, toDate, timeZone } = args;
212
+ const overrides = args.overrides.filter(
213
+ (row) => row.date >= fromDate && row.date <= toDate,
214
+ );
215
+ const overridden = new Set(
216
+ overrides.map((row) => getDemandDayKey(row.resourceId, row.key, row.date)),
217
+ );
218
+ const intervals: Array<ScheduleDemandIntervalObj | null> = overrides.map(
219
+ (row) => getScheduleDemandInterval(row, row.date, 'OVERRIDE', timeZone),
220
+ );
221
+
222
+ for (const date of listScheduleDates(fromDate, toDate)) {
223
+ const weekday = getScheduleWeekday(date);
224
+ for (const row of args.patterns) {
225
+ if (
226
+ row.weekday !== weekday ||
227
+ date < row.effectiveFrom ||
228
+ (row.effectiveTo !== null && date > row.effectiveTo) ||
229
+ overridden.has(getDemandDayKey(row.resourceId, row.key, date))
230
+ )
231
+ continue;
232
+ intervals.push(getScheduleDemandInterval(row, date, 'PATTERN', timeZone));
233
+ }
234
+ }
235
+
236
+ return intervals
237
+ .filter((interval): interval is ScheduleDemandIntervalObj => !!interval)
238
+ .sort(compareScheduleDemandIntervals);
239
+ }