@managesome/eposmatic-toolkit 0.4.7 → 0.4.8

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 (51) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +33 -0
  2. package/esm/helpers/materialized-reports/index.js +1 -0
  3. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +982 -0
  4. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +276 -33
  5. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +327 -41
  6. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +118 -235
  8. package/esm/schemas/models/index.js +1 -0
  9. package/esm/schemas/models/materialized_credit_bills.js +265 -0
  10. package/esm/schemas/models/materialized_tenant_reports_iterations.js +13 -0
  11. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +39 -97
  12. package/esm/schemas/types/index.js +1 -0
  13. package/esm/schemas/types/materialized_credit_bills.js +1 -0
  14. package/lib/constants/MATERIALIZED_REPORTS.d.ts +28 -2
  15. package/lib/constants/MATERIALIZED_REPORTS.js +34 -1
  16. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  17. package/lib/helpers/materialized-reports/index.js +1 -0
  18. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +307 -0
  19. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +1003 -0
  20. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +36 -2
  21. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +278 -34
  22. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +66 -8
  23. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +326 -40
  24. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +18 -2
  25. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  26. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +46 -37
  27. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +119 -238
  28. package/lib/helpers/types/materialized-reports-apis.d.ts +32 -5
  29. package/lib/schemas/models/index.d.ts +1 -0
  30. package/lib/schemas/models/index.js +1 -0
  31. package/lib/schemas/models/materialized_credit_bills.d.ts +337 -0
  32. package/lib/schemas/models/materialized_credit_bills.js +268 -0
  33. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +20 -6
  34. package/lib/schemas/models/materialized_tenant_reports_iterations.js +14 -1
  35. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +37 -165
  36. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +40 -98
  37. package/lib/schemas/types/index.d.ts +1 -0
  38. package/lib/schemas/types/index.js +1 -0
  39. package/lib/schemas/types/materialized_credit_bills.d.ts +139 -0
  40. package/lib/schemas/types/materialized_credit_bills.js +2 -0
  41. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +32 -77
  42. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.d.ts +1 -0
  43. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +715 -0
  44. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +96 -0
  45. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +9 -0
  46. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +23 -24
  47. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +327 -22
  48. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +27 -2
  49. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +12 -27
  50. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +79 -146
  51. package/package.json +1 -1
@@ -1,7 +1,8 @@
1
+ import { ALL_DAY_INDEX } from '../../constants/ENUMS';
1
2
  import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
3
  import { CALENDAR_MODE_ENUM, CALENDAR_VIEW_MODE_ENUM } from '../../constants/REPORT_CALENDAR';
3
4
  import { MATERIALIZED_REPORT_WINDOW_KIND, buildMaterializedReportScopeGroups, } from './materialized-reports-scope-group-helpers';
4
- import { getDayIndexFromLocalDate, getMaterializedHourScopeField, getMaterializedPeriodScopeFields, } from './scope-helpers';
5
+ import { getDayIndexFromLocalDate, getMaterializedHourScopeField, getMaterializedPeriodScopeFields, parseMaterializedLocalDate, } from './scope-helpers';
5
6
  /**
6
7
  * Calendar-selection DECODER for the materialized report READ APIs — the
7
8
  * backend-side twin of the calendar: it maps one `IReportCalendarSelection`
@@ -28,6 +29,13 @@ import { getDayIndexFromLocalDate, getMaterializedHourScopeField, getMaterialize
28
29
  * - period views read their exact period keys directly (week starts, ISO week
29
30
  * labels, months, quarters, semesters, years).
30
31
  *
32
+ * Validation: the raw selection is validated FIRST
33
+ * (`validateMaterializedReportSelectionInput`) — every date/period/time key
34
+ * must be well-formed (real calendar dates, exact period keys, whole-hour
35
+ * times) and the raw day span is bounded by
36
+ * `MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN`; malformed or oversized
37
+ * selections return `null` before any walk allocates anything.
38
+ *
31
39
  * Returns `null` (never throws) when the selection cannot be served (missing
32
40
  * range on a range view, malformed keys, an invalid refinement window, or an
33
41
  * unservable empty result). Group values are exact; empty groups are dropped.
@@ -51,6 +59,13 @@ const RANGE_LIKE_VIEWS = new Set([
51
59
  CALENDAR_VIEW_MODE_ENUM.QUARTER,
52
60
  CALENDAR_VIEW_MODE_ENUM.SEMESTER,
53
61
  ]);
62
+ /**
63
+ * Upper bound on the raw day span one selection may cover (~10 years).
64
+ * Bounds every date-walk expansion in the decoder; read services surface an
65
+ * over-bound selection as `selectionTooLarge` (400 "narrow the selection")
66
+ * BEFORE any decoding work happens.
67
+ */
68
+ export const MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN = 3660;
54
69
  /* ==================== Date-key primitives ==================== */
55
70
  // Local 'YYYY-MM-DD' key for a Date (NOT UTC — the tenant's local day).
56
71
  const formatLocalDateKey = (date) => {
@@ -134,34 +149,64 @@ const isDayKeptByWeekdayFilter = (dateKey, weekdays) => {
134
149
  return dayIndex != null && weekdays.includes(dayIndex);
135
150
  };
136
151
  /* ==================== Effective day set ==================== */
137
- // All day keys covered by the current selection — BEFORE the weekday
138
- // refinement.
139
- const getBaseSelectedDayKeys = (selection) => {
152
+ // All day keys covered by the current selection — the weekday refinement is
153
+ // applied INSIDE the walks so the cap counts the EFFECTIVE day set (a
154
+ // weekday-filtered multi-year selection stays servable while its raw day
155
+ // count exceeds the bound). Every walk is iteration-guarded; an over-bound
156
+ // expansion yields `null` (the decoder maps it to `[]` — unservable; the
157
+ // selection validator classifies it as `tooLarge`).
158
+ const getBaseSelectedDayKeys = (selection, weekdays) => {
140
159
  const { view, rangeStart, rangeEnd, selectedDates, selectedPeriods } = selection;
160
+ const keys = [];
161
+ const appendWithinCap = (list) => {
162
+ for (const key of list) {
163
+ keys.push(key);
164
+ if (keys.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
165
+ return false;
166
+ }
167
+ return true;
168
+ };
141
169
  const expandRange = (start, end) => {
142
- const keys = [];
170
+ const expanded = [];
143
171
  let cursor = start;
144
172
  while (cursor <= end) {
145
- keys.push(cursor);
173
+ if (weekdays == null || isDayKeptByWeekdayFilter(cursor, weekdays)) {
174
+ expanded.push(cursor);
175
+ if (expanded.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
176
+ return null;
177
+ }
146
178
  cursor = addDaysToKey(cursor, 1);
147
179
  }
148
- return keys;
180
+ return expanded;
149
181
  };
150
182
  if (RANGE_LIKE_VIEWS.has(view)) {
151
183
  if (!rangeStart)
152
184
  return [];
153
185
  return expandRange(rangeStart, rangeEnd ?? rangeStart);
154
186
  }
155
- if (view === CALENDAR_VIEW_MODE_ENUM.MULTI_DATE)
156
- return selectedDates;
187
+ if (view === CALENDAR_VIEW_MODE_ENUM.MULTI_DATE) {
188
+ if (selectedDates.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
189
+ return null;
190
+ return weekdays == null ? selectedDates : selectedDates.filter((key) => isDayKeptByWeekdayFilter(key, weekdays));
191
+ }
157
192
  if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS) {
158
- return selectedPeriods.flatMap((weekStart) => expandRange(weekStart, addDaysToKey(weekStart, 6)));
193
+ for (const weekStart of selectedPeriods) {
194
+ const days = expandRange(weekStart, addDaysToKey(weekStart, 6));
195
+ if (days == null || !appendWithinCap(days))
196
+ return null;
197
+ }
198
+ return keys;
159
199
  }
160
200
  if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR) {
161
- return selectedPeriods.flatMap((weekKey) => {
201
+ for (const weekKey of selectedPeriods) {
162
202
  const weekStart = getIsoWeekStartKeyFromLabel(weekKey);
163
- return weekStart == null ? [] : expandRange(weekStart, addDaysToKey(weekStart, 6));
164
- });
203
+ if (weekStart == null)
204
+ continue;
205
+ const days = expandRange(weekStart, addDaysToKey(weekStart, 6));
206
+ if (days == null || !appendWithinCap(days))
207
+ return null;
208
+ }
209
+ return keys;
165
210
  }
166
211
  if (view === CALENDAR_VIEW_MODE_ENUM.MONTH || view === CALENDAR_VIEW_MODE_ENUM.YEAR) {
167
212
  if (!rangeStart)
@@ -169,19 +214,37 @@ const getBaseSelectedDayKeys = (selection) => {
169
214
  return expandRange(rangeStart, rangeEnd ?? rangeStart);
170
215
  }
171
216
  if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS) {
172
- return selectedPeriods.flatMap((monthKey) => {
217
+ for (const monthKey of selectedPeriods) {
173
218
  const [year, month] = monthKey.split('-').map(Number);
174
- return expandRange(`${monthKey}-01`, formatLocalDateKey(new Date(year, month, 0)));
175
- });
219
+ const days = expandRange(`${monthKey}-01`, formatLocalDateKey(new Date(year, month, 0)));
220
+ if (days == null || !appendWithinCap(days))
221
+ return null;
222
+ }
223
+ return keys;
176
224
  }
177
225
  if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS) {
178
- return selectedPeriods.flatMap((quarterKey) => expandRange(getQuarterStartKey(quarterKey), getQuarterEndKey(quarterKey)));
226
+ for (const quarterKey of selectedPeriods) {
227
+ const days = expandRange(getQuarterStartKey(quarterKey), getQuarterEndKey(quarterKey));
228
+ if (days == null || !appendWithinCap(days))
229
+ return null;
230
+ }
231
+ return keys;
179
232
  }
180
233
  if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS) {
181
- return selectedPeriods.flatMap((semesterKey) => expandRange(getSemesterStartKey(semesterKey), getSemesterEndKey(semesterKey)));
234
+ for (const semesterKey of selectedPeriods) {
235
+ const days = expandRange(getSemesterStartKey(semesterKey), getSemesterEndKey(semesterKey));
236
+ if (days == null || !appendWithinCap(days))
237
+ return null;
238
+ }
239
+ return keys;
182
240
  }
183
241
  if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS) {
184
- return selectedPeriods.flatMap((yearKey) => expandRange(`${yearKey}-01-01`, `${yearKey}-12-31`));
242
+ for (const yearKey of selectedPeriods) {
243
+ const days = expandRange(`${yearKey}-01-01`, `${yearKey}-12-31`);
244
+ if (days == null || !appendWithinCap(days))
245
+ return null;
246
+ }
247
+ return keys;
185
248
  }
186
249
  return [];
187
250
  };
@@ -191,11 +254,16 @@ const getBaseSelectedDayKeys = (selection) => {
191
254
  * summaries, DateContext bounds, or requests.
192
255
  */
193
256
  export const getDayKeysFromCalendarSelection = (selection) => {
194
- const keys = getBaseSelectedDayKeys(selection);
195
- const weekdays = getActiveWeekdayFilter(selection.weekdays);
196
- if (weekdays == null)
197
- return keys;
198
- return keys.filter((key) => isDayKeptByWeekdayFilter(key, weekdays));
257
+ try {
258
+ if (!validateMaterializedReportSelectionInput(selection).ok)
259
+ return [];
260
+ // The base walk already applies the weekday refinement, so its cap counts
261
+ // the EFFECTIVE day set — `null` = over-bound → unservable.
262
+ return getBaseSelectedDayKeys(selection, getActiveWeekdayFilter(selection.weekdays)) ?? [];
263
+ }
264
+ catch {
265
+ return [];
266
+ }
199
267
  };
200
268
  /* ==================== Hour-window validity ==================== */
201
269
  /**
@@ -220,12 +288,15 @@ export const isValidBusinessHourWindow = (fromHour, toHour) => {
220
288
  return startPosition + hourCount <= 24;
221
289
  };
222
290
  /* ==================== Decode internals ==================== */
223
- /** `'HH:mm'` → hour number (whole hours only). */
291
+ /** `'HH:mm'` → hour number — whole `:00` hours only (minute keys are not servable). */
224
292
  const hourOf = (time) => {
225
293
  if (time == null)
226
294
  return null;
227
- const hour = Number.parseInt(time.split(':')[0] ?? '', 10);
228
- return Number.isInteger(hour) && hour >= 0 && hour <= 23 ? hour : null;
295
+ const match = /^(\d{2}):(\d{2})$/.exec(time);
296
+ if (match == null || match[2] !== '00')
297
+ return null;
298
+ const hour = Number(match[1]);
299
+ return hour >= 0 && hour <= 23 ? hour : null;
229
300
  };
230
301
  /** Active time-of-day window (both ends set and servable) — else `null`. */
231
302
  const resolveTimeOfDayWindow = (selection) => {
@@ -261,8 +332,12 @@ const usableGroups = (groups) => {
261
332
  const usable = (groups ?? []).filter((group) => group.scope_field.length > 0);
262
333
  return usable.length > 0 ? usable : null;
263
334
  };
264
- /** Groups with the exact period values of one scope (period views). */
265
- const scopedGroups = (scope, values) => usableGroups([{ scope_context: scope, scope_field: values }]);
335
+ /**
336
+ * Groups with the exact period values of one scope (period views) — the
337
+ * values are canonicalized (first-occurrence order) so duplicate picks never
338
+ * reach the read as duplicate `$in` entries.
339
+ */
340
+ const scopedGroups = (scope, values) => usableGroups([{ scope_context: scope, scope_field: [...new Set(values)] }]);
266
341
  /** Business-hour order of one day's hour buckets — 06…23 then 00…05. */
267
342
  const BUSINESS_DAY_HOURS = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5];
268
343
  /**
@@ -277,6 +352,8 @@ const enumerateWeekStarts = (startKey, endKey) => {
277
352
  let cursor = startKey;
278
353
  while (cursor <= endKey) {
279
354
  keys.push(cursor);
355
+ if (keys.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
356
+ return [];
280
357
  cursor = addDaysToKey(cursor, 7);
281
358
  }
282
359
  return keys;
@@ -290,6 +367,8 @@ const enumerateIsoWeeks = (startDayKey, endDayKey) => {
290
367
  const label = getIsoWeekKey(cursor);
291
368
  if (label != null)
292
369
  keys.push(label);
370
+ if (keys.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
371
+ return [];
293
372
  cursor = addDaysToKey(cursor, 7);
294
373
  }
295
374
  return keys;
@@ -301,6 +380,8 @@ const enumerateMonths = (from, to) => {
301
380
  const [endYear, endMonth] = to.split('-').map(Number);
302
381
  while (year < endYear || (year === endYear && month <= endMonth)) {
303
382
  keys.push(`${year}-${`${month}`.padStart(2, '0')}`);
383
+ if (keys.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
384
+ return [];
304
385
  month += 1;
305
386
  if (month > 12) {
306
387
  month = 1;
@@ -318,6 +399,8 @@ const enumerateQuarters = (from, to) => {
318
399
  const keys = [];
319
400
  for (let index = asIndex(from); index <= asIndex(to); index += 1) {
320
401
  keys.push(`${Math.floor(index / 4)}-Q${(index % 4) + 1}`);
402
+ if (keys.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
403
+ return [];
321
404
  }
322
405
  return keys;
323
406
  };
@@ -330,11 +413,18 @@ const enumerateSemesters = (from, to) => {
330
413
  const keys = [];
331
414
  for (let index = asIndex(from); index <= asIndex(to); index += 1) {
332
415
  keys.push(`${Math.floor(index / 2)}-S${(index % 2) + 1}`);
416
+ if (keys.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
417
+ return [];
333
418
  }
334
419
  return keys;
335
420
  };
336
421
  /** 'YYYY' keys from `from` to `to` (inclusive). */
337
- const enumerateYears = (from, to) => Array.from({ length: Number(to) - Number(from) + 1 }, (_, index) => `${Number(from) + index}`);
422
+ const enumerateYears = (from, to) => {
423
+ const count = Number(to) - Number(from) + 1;
424
+ if (!Number.isFinite(count) || count < 0 || count > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
425
+ return [];
426
+ return Array.from({ length: count }, (_, index) => `${Number(from) + index}`);
427
+ };
338
428
  /** Exact period keys covered by a contiguous range of the given scope. */
339
429
  const periodRangeFields = (rangeStart, rangeEnd, scope) => {
340
430
  if (rangeStart == null)
@@ -358,14 +448,164 @@ const periodRangeFields = (rangeStart, rangeEnd, scope) => {
358
448
  return [];
359
449
  }
360
450
  };
451
+ /** Whole-hour `'HH:00'` time key — minute-level keys are not servable. */
452
+ const WHOLE_HOUR_TIME_PATTERN = /^([01]\d|2[0-3]):00$/;
453
+ const isRealLocalDateKey = (key) => parseMaterializedLocalDate(key) != null;
454
+ const epochDayOfLocalDateKey = (key) => {
455
+ const parts = parseMaterializedLocalDate(key);
456
+ if (parts == null)
457
+ return null;
458
+ return Date.UTC(parts.year, parts.month - 1, parts.day) / 86400000;
459
+ };
460
+ /** ISO week count (52/53) of an ISO week-year — Dec 28 is always in its last ISO week. */
461
+ const getIsoWeeksInYear = (isoYear) => {
462
+ const label = getIsoWeekKey(`${isoYear}-12-28`);
463
+ const match = label == null ? null : /W(\d{2})$/.exec(label);
464
+ return match == null ? 52 : Number(match[1]);
465
+ };
466
+ /** Views whose day set is one contiguous `rangeStart … rangeEnd` walk (incl. MONTH/YEAR). */
467
+ const RANGE_EXPANDING_VIEWS = new Set([
468
+ ...RANGE_LIKE_VIEWS,
469
+ CALENDAR_VIEW_MODE_ENUM.MONTH,
470
+ CALENDAR_VIEW_MODE_ENUM.YEAR,
471
+ ]);
472
+ /**
473
+ * Validates the RAW calendar selection BEFORE any decoding work happens:
474
+ * - time keys, when present, must be whole `'HH:00'` hours (minute-level keys
475
+ * are malformed wire values — they must never silently truncate);
476
+ * - the weekday refinement must carry real `DAY_INDEX_ENUM` entries;
477
+ * - every date key (`rangeStart` / `rangeEnd` / `selectedDates` / week-start
478
+ * picks) must be a REAL `'YYYY-MM-DD'` calendar date;
479
+ * - `selectedPeriods` picks must match their view's period grammar and
480
+ * semantics (months 01–12, ISO weeks within the year's week count,
481
+ * quarters Q1–Q4, semesters S1–S2, four-digit years);
482
+ * - contiguous range walks may not cover more than
483
+ * `MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN` days, and discrete picks may
484
+ * not exceed that count — both are `tooLarge` (narrow the selection).
485
+ *
486
+ * The decoder calls this first and maps BOTH failures to `null`; read
487
+ * services call it (via their read parser) to answer a clean 400 before the
488
+ * decoder is ever entered — a malformed request can never reach a date walk.
489
+ */
490
+ export const validateMaterializedReportSelectionInput = (selection) => {
491
+ const invalid = { ok: false, reason: 'invalid' };
492
+ const tooLarge = { ok: false, reason: 'tooLarge' };
493
+ if (selection == null || typeof selection !== 'object')
494
+ return invalid;
495
+ const { view, rangeStart, rangeEnd, selectedDates, selectedPeriods } = selection;
496
+ // Whole-hour time keys only — `'18:45'` must not silently read 18:00–18:44.
497
+ if (selection.timeStart != null && !WHOLE_HOUR_TIME_PATTERN.test(selection.timeStart))
498
+ return invalid;
499
+ if (selection.timeEnd != null && !WHOLE_HOUR_TIME_PATTERN.test(selection.timeEnd))
500
+ return invalid;
501
+ // Weekday refinement entries must be real day-index keys.
502
+ const weekdays = Array.isArray(selection.weekdays) ? selection.weekdays : [];
503
+ if (!weekdays.every((entry) => ALL_DAY_INDEX.includes(entry)))
504
+ return invalid;
505
+ // Every date key that could reach a date walk must be a REAL calendar date.
506
+ const dates = Array.isArray(selectedDates) ? selectedDates : [];
507
+ const dateKeys = [rangeStart, rangeEnd, ...dates];
508
+ if (dateKeys.some((key) => key != null && !isRealLocalDateKey(key)))
509
+ return invalid;
510
+ if (view === CALENDAR_VIEW_MODE_ENUM.MULTI_DATE && dates.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN) {
511
+ return tooLarge;
512
+ }
513
+ // Period picks — strict per-view grammar + semantics (a bad key would
514
+ // otherwise surface as a 200 "No Data" instead of a 400).
515
+ const periods = Array.isArray(selectedPeriods) ? selectedPeriods : [];
516
+ const overPicked = periods.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN ? tooLarge : null;
517
+ switch (view) {
518
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS:
519
+ if (overPicked != null)
520
+ return overPicked;
521
+ if (!periods.every((key) => isRealLocalDateKey(key)))
522
+ return invalid;
523
+ break;
524
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR:
525
+ if (overPicked != null)
526
+ return overPicked;
527
+ for (const key of periods) {
528
+ const match = /^(\d{4})-W(\d{2})$/.exec(key);
529
+ if (match == null)
530
+ return invalid;
531
+ const week = Number(match[2]);
532
+ if (week < 1 || week > getIsoWeeksInYear(Number(match[1])))
533
+ return invalid;
534
+ }
535
+ break;
536
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS:
537
+ if (overPicked != null)
538
+ return overPicked;
539
+ if (!periods.every((key) => /^\d{4}-(0[1-9]|1[0-2])$/.test(key)))
540
+ return invalid;
541
+ break;
542
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS:
543
+ if (overPicked != null)
544
+ return overPicked;
545
+ if (!periods.every((key) => /^\d{4}-Q[1-4]$/.test(key)))
546
+ return invalid;
547
+ break;
548
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS:
549
+ if (overPicked != null)
550
+ return overPicked;
551
+ if (!periods.every((key) => /^\d{4}-S[12]$/.test(key)))
552
+ return invalid;
553
+ break;
554
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS:
555
+ if (overPicked != null)
556
+ return overPicked;
557
+ if (!periods.every((key) => /^\d{4}$/.test(key)))
558
+ return invalid;
559
+ break;
560
+ default:
561
+ break;
562
+ }
563
+ // Contiguous range walks are bounded by the raw day span (~10 years).
564
+ if (RANGE_EXPANDING_VIEWS.has(view) && rangeStart != null && rangeEnd != null) {
565
+ const start = epochDayOfLocalDateKey(rangeStart);
566
+ const end = epochDayOfLocalDateKey(rangeEnd);
567
+ if (start != null && end != null && Math.abs(end - start) > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN - 1) {
568
+ return tooLarge;
569
+ }
570
+ }
571
+ // DIFFERENT_* picks expand to REAL days at decode time — with the weekday
572
+ // refinement applied. The decode caps the EFFECTIVE day set, so an
573
+ // oversize expansion must classify as `tooLarge` HERE instead of surfacing
574
+ // downstream as an unexplained "invalid" (the decoder maps it to `null`).
575
+ const expandsPicksToDays = view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS ||
576
+ view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR ||
577
+ view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS ||
578
+ view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS ||
579
+ view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS ||
580
+ view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS;
581
+ if (expandsPicksToDays && getBaseSelectedDayKeys(selection, getActiveWeekdayFilter(selection.weekdays)) == null) {
582
+ return tooLarge;
583
+ }
584
+ return { ok: true };
585
+ };
361
586
  /* ==================== Decode ==================== */
362
587
  /**
363
588
  * Maps a committed calendar selection to the exact `scope_groups` of the
364
- * overview read. Returns `null` when the selection cannot be served (LIVE
365
- * without a committed day, a malformed/empty selection, or unservable
589
+ * overview read — the PUBLIC decoder: it validates the raw selection
590
+ * (`validateMaterializedReportSelectionInput`) first and NEVER throws.
591
+ * Returns `null` when the selection cannot be served (LIVE without a
592
+ * committed day, a malformed/oversized/empty selection, or unservable
366
593
  * refinement input).
367
594
  */
368
595
  export const buildMaterializedReportScopeGroupsFromSelection = (selection) => {
596
+ try {
597
+ if (selection == null || typeof selection !== 'object')
598
+ return null;
599
+ if (!validateMaterializedReportSelectionInput(selection).ok)
600
+ return null;
601
+ return decodeMaterializedReportScopeGroups(selection);
602
+ }
603
+ catch {
604
+ return null;
605
+ }
606
+ };
607
+ /** Internal decode — the public entry above validates + backstops first. */
608
+ const decodeMaterializedReportScopeGroups = (selection) => {
369
609
  // LIVE reads ONLY the running business day — all of its exact hour labels
370
610
  // (the calendar commits the running day as `rangeStart`). The backend sums
371
611
  // them into one record; the day close finalizes the documents.
@@ -409,7 +649,10 @@ export const buildMaterializedReportScopeGroupsFromSelection = (selection) => {
409
649
  window: {
410
650
  fromHour: window.fromHour,
411
651
  toHour: window.toHour,
412
- kind: SPAN_VIEWS.has(view)
652
+ // A weekday-refined day set is GAPPED — a continuous SPAN can
653
+ // never compile it. Weekday + window therefore always compiles
654
+ // RECURRING (the same hours on each matching weekday).
655
+ kind: SPAN_VIEWS.has(view) && weekdayFilter == null
413
656
  ? MATERIALIZED_REPORT_WINDOW_KIND.SPAN
414
657
  : MATERIALIZED_REPORT_WINDOW_KIND.RECURRING,
415
658
  },