@managesome/eposmatic-toolkit 0.4.5 → 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 (68) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +33 -0
  2. package/esm/constants/REPORT_CALENDAR.js +47 -0
  3. package/esm/constants/index.js +1 -0
  4. package/esm/helpers/materialized-reports/index.js +2 -0
  5. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +982 -0
  6. package/esm/helpers/materialized-reports/materialized-reports-read-helpers.js +1 -76
  7. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +716 -0
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +327 -41
  9. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  10. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +118 -235
  11. package/esm/helpers/types/index.js +1 -0
  12. package/esm/schemas/models/index.js +1 -0
  13. package/esm/schemas/models/materialized_credit_bills.js +265 -0
  14. package/esm/schemas/models/materialized_tenant_reports_iterations.js +13 -0
  15. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +39 -97
  16. package/esm/schemas/types/index.js +1 -0
  17. package/esm/schemas/types/materialized_credit_bills.js +1 -0
  18. package/lib/constants/MATERIALIZED_REPORTS.d.ts +28 -2
  19. package/lib/constants/MATERIALIZED_REPORTS.js +34 -1
  20. package/lib/constants/REPORT_CALENDAR.d.ts +31 -0
  21. package/lib/constants/REPORT_CALENDAR.js +50 -0
  22. package/lib/constants/index.d.ts +1 -0
  23. package/lib/constants/index.js +1 -0
  24. package/lib/helpers/materialized-reports/index.d.ts +2 -0
  25. package/lib/helpers/materialized-reports/index.js +2 -0
  26. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +307 -0
  27. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +1003 -0
  28. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.d.ts +0 -30
  29. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.js +0 -76
  30. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +59 -0
  31. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +723 -0
  32. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +66 -8
  33. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +326 -40
  34. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +18 -2
  35. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  36. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +46 -37
  37. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +119 -238
  38. package/lib/helpers/types/index.d.ts +1 -0
  39. package/lib/helpers/types/index.js +1 -0
  40. package/lib/helpers/types/materialized-reports-apis.d.ts +46 -17
  41. package/lib/helpers/types/report-calendar.d.ts +20 -0
  42. package/lib/helpers/types/report-calendar.js +2 -0
  43. package/lib/schemas/models/index.d.ts +1 -0
  44. package/lib/schemas/models/index.js +1 -0
  45. package/lib/schemas/models/materialized_credit_bills.d.ts +337 -0
  46. package/lib/schemas/models/materialized_credit_bills.js +268 -0
  47. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +20 -6
  48. package/lib/schemas/models/materialized_tenant_reports_iterations.js +14 -1
  49. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +37 -165
  50. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +40 -98
  51. package/lib/schemas/types/index.d.ts +1 -0
  52. package/lib/schemas/types/index.js +1 -0
  53. package/lib/schemas/types/materialized_credit_bills.d.ts +139 -0
  54. package/lib/schemas/types/materialized_credit_bills.js +2 -0
  55. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +32 -77
  56. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.d.ts +1 -0
  57. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +715 -0
  58. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.d.ts +1 -0
  59. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +262 -0
  60. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +9 -0
  61. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +23 -24
  62. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +327 -22
  63. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +27 -2
  64. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +12 -27
  65. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +79 -146
  66. package/package.json +1 -1
  67. package/lib/tests/materialized-reports/materialized-reports-read-helpers.test.js +0 -100
  68. /package/{lib/tests/materialized-reports/materialized-reports-read-helpers.test.d.ts → esm/helpers/types/report-calendar.js} +0 -0
@@ -0,0 +1,716 @@
1
+ import { ALL_DAY_INDEX } from '../../constants/ENUMS';
2
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
3
+ import { CALENDAR_MODE_ENUM, CALENDAR_VIEW_MODE_ENUM } from '../../constants/REPORT_CALENDAR';
4
+ import { MATERIALIZED_REPORT_WINDOW_KIND, buildMaterializedReportScopeGroups, } from './materialized-reports-scope-group-helpers';
5
+ import { getDayIndexFromLocalDate, getMaterializedHourScopeField, getMaterializedPeriodScopeFields, parseMaterializedLocalDate, } from './scope-helpers';
6
+ /**
7
+ * Calendar-selection DECODER for the materialized report READ APIs — the
8
+ * backend-side twin of the calendar: it maps one `IReportCalendarSelection`
9
+ * to the exact `scope_groups` a read request needs, so clients ship the
10
+ * selection (a few hundred bytes) instead of enumerating tens of thousands
11
+ * of scope values.
12
+ *
13
+ * Semantics (identical to what the frontend compiler produced before this
14
+ * moved server-side):
15
+ * - LIVE reads ONLY the running business day — all of its exact `localHour`
16
+ * labels (the calendar commits the running day as `rangeStart`); summed by
17
+ * the backend it yields the running day's metrics so far, finalized at day
18
+ * close;
19
+ * - day-based selections compile through the SMART compiler
20
+ * (`buildMaterializedReportScopeGroups`): contiguous day runs fold into the
21
+ * LARGEST exact periods they fully cover (week → month → quarter → semester
22
+ * → year; anything left stays `localDate`);
23
+ * - a time-of-day window compiles to `localHour` labels: a CONTINUOUS SPAN on
24
+ * range-like views (toggle), the SAME hours on each selected day otherwise
25
+ * (dedicated window view / discrete selections);
26
+ * - the weekday refinement degenerates the read to standalone day documents
27
+ * (`localDate` / `localHour` docs carry `day_index`; period docs do not):
28
+ * it filters the effective day set BEFORE hour-window expansion;
29
+ * - period views read their exact period keys directly (week starts, ISO week
30
+ * labels, months, quarters, semesters, years).
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
+ *
39
+ * Returns `null` (never throws) when the selection cannot be served (missing
40
+ * range on a range view, malformed keys, an invalid refinement window, or an
41
+ * unservable empty result). Group values are exact; empty groups are dropped.
42
+ */
43
+ /** Range-like views whose toggle window is a CONTINUOUS span. */
44
+ const SPAN_VIEWS = new Set([
45
+ CALENDAR_VIEW_MODE_ENUM.DATE_RANGE,
46
+ CALENDAR_VIEW_MODE_ENUM.WEEK,
47
+ CALENDAR_VIEW_MODE_ENUM.WEEK_OF_YEAR,
48
+ CALENDAR_VIEW_MODE_ENUM.MONTH,
49
+ CALENDAR_VIEW_MODE_ENUM.QUARTER,
50
+ CALENDAR_VIEW_MODE_ENUM.SEMESTER,
51
+ CALENDAR_VIEW_MODE_ENUM.YEAR,
52
+ ]);
53
+ /** Views whose day set is one contiguous `rangeStart … rangeEnd` walk. */
54
+ const RANGE_LIKE_VIEWS = new Set([
55
+ CALENDAR_VIEW_MODE_ENUM.DATE_RANGE,
56
+ CALENDAR_VIEW_MODE_ENUM.DATE_RANGE_TIME_WINDOW,
57
+ CALENDAR_VIEW_MODE_ENUM.WEEK,
58
+ CALENDAR_VIEW_MODE_ENUM.WEEK_OF_YEAR,
59
+ CALENDAR_VIEW_MODE_ENUM.QUARTER,
60
+ CALENDAR_VIEW_MODE_ENUM.SEMESTER,
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;
69
+ /* ==================== Date-key primitives ==================== */
70
+ // Local 'YYYY-MM-DD' key for a Date (NOT UTC — the tenant's local day).
71
+ const formatLocalDateKey = (date) => {
72
+ const year = date.getFullYear();
73
+ const month = `${date.getMonth() + 1}`.padStart(2, '0');
74
+ const day = `${date.getDate()}`.padStart(2, '0');
75
+ return `${year}-${month}-${day}`;
76
+ };
77
+ const getDateFromKey = (key) => {
78
+ const [year, month, day] = key.split('-').map(Number);
79
+ return new Date(year, month - 1, day);
80
+ };
81
+ const addDaysToKey = (dateKey, days) => {
82
+ const date = getDateFromKey(dateKey);
83
+ date.setDate(date.getDate() + days);
84
+ return formatLocalDateKey(date);
85
+ };
86
+ // 'YYYY-Qn' quarter start ('YYYY-MM-01') — accepts a quarter key
87
+ const getQuarterStartKey = (quarterKey) => {
88
+ const [year, quarter] = quarterKey.split('-');
89
+ const month = (Number(quarter.slice(1)) - 1) * 3 + 1;
90
+ return `${year}-${`${month}`.padStart(2, '0')}-01`;
91
+ };
92
+ // 'YYYY-Qn' quarter end (last day of the quarter) — accepts a quarter key
93
+ const getQuarterEndKey = (quarterKey) => {
94
+ const [year, quarter] = quarterKey.split('-');
95
+ return formatLocalDateKey(new Date(Number(year), Number(quarter.slice(1)) * 3, 0));
96
+ };
97
+ // 'YYYY-Sn' semester start ('YYYY-MM-01') — accepts a semester key
98
+ const getSemesterStartKey = (semesterKey) => {
99
+ const [year, semester] = semesterKey.split('-');
100
+ return `${year}-${semester === 'S1' ? '01' : '07'}-01`;
101
+ };
102
+ // 'YYYY-Sn' semester end — accepts a semester key
103
+ const getSemesterEndKey = (semesterKey) => {
104
+ const [year, semester] = semesterKey.split('-');
105
+ return semester === 'S1' ? `${year}-06-30` : `${year}-12-31`;
106
+ };
107
+ // Monday start of the ISO week containing the given day key
108
+ const getIsoWeekStartKey = (dateKey) => {
109
+ const date = getDateFromKey(dateKey);
110
+ const offset = (date.getDay() + 6) % 7; // days since Monday
111
+ date.setDate(date.getDate() - offset);
112
+ return formatLocalDateKey(date);
113
+ };
114
+ // 'YYYY-Wnn' ISO label of a day key — `YYYY` is the ISO week-year, so
115
+ // boundary weeks (e.g. 2027-01-01 → '2026-W53') label correctly.
116
+ const getIsoWeekKey = (dateKey) => getMaterializedPeriodScopeFields(dateKey)?.[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR] ?? null;
117
+ // Monday day key of an ISO week label ('YYYY-Wnn'); null for malformed input
118
+ const getIsoWeekStartKeyFromLabel = (weekKey) => {
119
+ const match = /^(\d{4})-W(\d{2})$/.exec(weekKey);
120
+ if (!match)
121
+ return null;
122
+ const week = Number(match[2]);
123
+ if (week < 1 || week > 53)
124
+ return null;
125
+ // ISO week 1 is the week containing Jan 4 — its Monday anchors numbering
126
+ const weekOneMonday = getDateFromKey(getIsoWeekStartKey(`${match[1]}-01-04`));
127
+ weekOneMonday.setDate(weekOneMonday.getDate() + (week - 1) * 7);
128
+ return formatLocalDateKey(weekOneMonday);
129
+ };
130
+ /* ==================== Weekday refinement ==================== */
131
+ /**
132
+ * Active weekday refinement — `null` when unset (= every day). The decoder,
133
+ * the calendar's grid highlight and the selection summary all use the SAME
134
+ * effective-day semantics, so the UI can never claim days the report won't
135
+ * read.
136
+ */
137
+ const getActiveWeekdayFilter = (weekdays) => {
138
+ if (!Array.isArray(weekdays) || weekdays.length === 0)
139
+ return null;
140
+ if (weekdays.length >= 7)
141
+ return null;
142
+ return weekdays;
143
+ };
144
+ /** Whether a day key is kept by the active weekday refinement. */
145
+ const isDayKeptByWeekdayFilter = (dateKey, weekdays) => {
146
+ if (weekdays == null)
147
+ return true;
148
+ const dayIndex = getDayIndexFromLocalDate(dateKey);
149
+ return dayIndex != null && weekdays.includes(dayIndex);
150
+ };
151
+ /* ==================== Effective day set ==================== */
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) => {
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
+ };
169
+ const expandRange = (start, end) => {
170
+ const expanded = [];
171
+ let cursor = start;
172
+ while (cursor <= end) {
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
+ }
178
+ cursor = addDaysToKey(cursor, 1);
179
+ }
180
+ return expanded;
181
+ };
182
+ if (RANGE_LIKE_VIEWS.has(view)) {
183
+ if (!rangeStart)
184
+ return [];
185
+ return expandRange(rangeStart, rangeEnd ?? rangeStart);
186
+ }
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
+ }
192
+ if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS) {
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;
199
+ }
200
+ if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR) {
201
+ for (const weekKey of selectedPeriods) {
202
+ const weekStart = getIsoWeekStartKeyFromLabel(weekKey);
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;
210
+ }
211
+ if (view === CALENDAR_VIEW_MODE_ENUM.MONTH || view === CALENDAR_VIEW_MODE_ENUM.YEAR) {
212
+ if (!rangeStart)
213
+ return [];
214
+ return expandRange(rangeStart, rangeEnd ?? rangeStart);
215
+ }
216
+ if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS) {
217
+ for (const monthKey of selectedPeriods) {
218
+ const [year, month] = monthKey.split('-').map(Number);
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;
224
+ }
225
+ if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS) {
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;
232
+ }
233
+ if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS) {
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;
240
+ }
241
+ if (view === CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS) {
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;
248
+ }
249
+ return [];
250
+ };
251
+ /**
252
+ * All day keys covered by a selection — keeps only days that match the
253
+ * active weekday refinement, so non-matching days never contribute to
254
+ * summaries, DateContext bounds, or requests.
255
+ */
256
+ export const getDayKeysFromCalendarSelection = (selection) => {
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
+ }
267
+ };
268
+ /* ==================== Hour-window validity ==================== */
269
+ /**
270
+ * Whether an hour window `[fromHour, toHour)` fits one business day
271
+ * (06:00 → 06:00) — mirrors the toolkit's materialized window rule
272
+ * (`getMaterializedHourWindowScopeFields`): whole-hour buckets, end-exclusive
273
+ * (18 → 20 = hours 18, 19), midnight wrap allowed (22 → 2), but never a walk
274
+ * crossing the 06:00 business-morning boundary (4 → 8 is invalid). The
275
+ * calendar's time field uses this to disable unservable picker options, so an
276
+ * invalid window can never be composed for the read request.
277
+ */
278
+ export const isValidBusinessHourWindow = (fromHour, toHour) => {
279
+ if (!Number.isInteger(fromHour) || fromHour < 0 || fromHour > 23) {
280
+ return false;
281
+ }
282
+ if (!Number.isInteger(toHour) || toHour < 0 || toHour > 23)
283
+ return false;
284
+ const hourCount = (((toHour - fromHour) % 24) + 24) % 24;
285
+ if (hourCount === 0)
286
+ return false; // ambiguous empty window
287
+ const startPosition = (fromHour + 18) % 24;
288
+ return startPosition + hourCount <= 24;
289
+ };
290
+ /* ==================== Decode internals ==================== */
291
+ /** `'HH:mm'` → hour number — whole `:00` hours only (minute keys are not servable). */
292
+ const hourOf = (time) => {
293
+ if (time == null)
294
+ return 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;
300
+ };
301
+ /** Active time-of-day window (both ends set and servable) — else `null`. */
302
+ const resolveTimeOfDayWindow = (selection) => {
303
+ const fromHour = hourOf(selection.timeStart);
304
+ const toHour = hourOf(selection.timeEnd);
305
+ if (fromHour == null || toHour == null)
306
+ return null;
307
+ if (!isValidBusinessHourWindow(fromHour, toHour))
308
+ return null;
309
+ return { fromHour, toHour };
310
+ };
311
+ const periodKeyOf = (dayKey, scope) => {
312
+ const fields = getMaterializedPeriodScopeFields(dayKey);
313
+ if (fields == null)
314
+ return null;
315
+ switch (scope) {
316
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK:
317
+ return fields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK];
318
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH:
319
+ return fields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH];
320
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER:
321
+ return fields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER];
322
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER:
323
+ return fields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER];
324
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR:
325
+ return fields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR];
326
+ default:
327
+ return null;
328
+ }
329
+ };
330
+ /** Groups with at least one value — dropped groups leave `null`. */
331
+ const usableGroups = (groups) => {
332
+ const usable = (groups ?? []).filter((group) => group.scope_field.length > 0);
333
+ return usable.length > 0 ? usable : null;
334
+ };
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)] }]);
341
+ /** Business-hour order of one day's hour buckets — 06…23 then 00…05. */
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];
343
+ /**
344
+ * Every exact `localHour` label of one business day — the LIVE read. Summed
345
+ * by the backend it yields the running day's metrics so far (the day close
346
+ * finalizes them); a closed day's hours sum to its `localDate` totals.
347
+ */
348
+ const runningDayHourLabels = (dayKey) => BUSINESS_DAY_HOURS.map((hour) => getMaterializedHourScopeField(dayKey, hour)).filter((label) => label != null);
349
+ /** Week-start day keys from `startKey` to `endKey`, stepping 7 days. */
350
+ const enumerateWeekStarts = (startKey, endKey) => {
351
+ const keys = [];
352
+ let cursor = startKey;
353
+ while (cursor <= endKey) {
354
+ keys.push(cursor);
355
+ if (keys.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
356
+ return [];
357
+ cursor = addDaysToKey(cursor, 7);
358
+ }
359
+ return keys;
360
+ };
361
+ /** ISO week labels ('YYYY-Wnn') covering `startDayKey` … `endDayKey`. */
362
+ const enumerateIsoWeeks = (startDayKey, endDayKey) => {
363
+ const keys = [];
364
+ const end = getIsoWeekStartKey(endDayKey);
365
+ let cursor = getIsoWeekStartKey(startDayKey);
366
+ while (cursor <= end) {
367
+ const label = getIsoWeekKey(cursor);
368
+ if (label != null)
369
+ keys.push(label);
370
+ if (keys.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
371
+ return [];
372
+ cursor = addDaysToKey(cursor, 7);
373
+ }
374
+ return keys;
375
+ };
376
+ /** 'YYYY-MM' keys from `from` to `to` (inclusive). */
377
+ const enumerateMonths = (from, to) => {
378
+ const keys = [];
379
+ let [year, month] = from.split('-').map(Number);
380
+ const [endYear, endMonth] = to.split('-').map(Number);
381
+ while (year < endYear || (year === endYear && month <= endMonth)) {
382
+ keys.push(`${year}-${`${month}`.padStart(2, '0')}`);
383
+ if (keys.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
384
+ return [];
385
+ month += 1;
386
+ if (month > 12) {
387
+ month = 1;
388
+ year += 1;
389
+ }
390
+ }
391
+ return keys;
392
+ };
393
+ /** 'YYYY-Qn' keys from `from` to `to` (inclusive). */
394
+ const enumerateQuarters = (from, to) => {
395
+ const asIndex = (key) => {
396
+ const [year, quarter] = key.split('-');
397
+ return Number(year) * 4 + (Number(quarter.slice(1)) - 1);
398
+ };
399
+ const keys = [];
400
+ for (let index = asIndex(from); index <= asIndex(to); index += 1) {
401
+ keys.push(`${Math.floor(index / 4)}-Q${(index % 4) + 1}`);
402
+ if (keys.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
403
+ return [];
404
+ }
405
+ return keys;
406
+ };
407
+ /** 'YYYY-Sn' keys from `from` to `to` (inclusive). */
408
+ const enumerateSemesters = (from, to) => {
409
+ const asIndex = (key) => {
410
+ const [year, semester] = key.split('-');
411
+ return Number(year) * 2 + (Number(semester.slice(1)) - 1);
412
+ };
413
+ const keys = [];
414
+ for (let index = asIndex(from); index <= asIndex(to); index += 1) {
415
+ keys.push(`${Math.floor(index / 2)}-S${(index % 2) + 1}`);
416
+ if (keys.length > MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
417
+ return [];
418
+ }
419
+ return keys;
420
+ };
421
+ /** 'YYYY' keys from `from` to `to` (inclusive). */
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
+ };
428
+ /** Exact period keys covered by a contiguous range of the given scope. */
429
+ const periodRangeFields = (rangeStart, rangeEnd, scope) => {
430
+ if (rangeStart == null)
431
+ return [];
432
+ const from = periodKeyOf(rangeStart, scope);
433
+ const to = periodKeyOf(rangeEnd ?? rangeStart, scope);
434
+ if (from == null || to == null)
435
+ return [];
436
+ switch (scope) {
437
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK:
438
+ return enumerateWeekStarts(from, to);
439
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH:
440
+ return enumerateMonths(from, to);
441
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER:
442
+ return enumerateQuarters(from, to);
443
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER:
444
+ return enumerateSemesters(from, to);
445
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR:
446
+ return enumerateYears(from, to);
447
+ default:
448
+ return [];
449
+ }
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
+ };
586
+ /* ==================== Decode ==================== */
587
+ /**
588
+ * Maps a committed calendar selection to the exact `scope_groups` of the
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
593
+ * refinement input).
594
+ */
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) => {
609
+ // LIVE reads ONLY the running business day — all of its exact hour labels
610
+ // (the calendar commits the running day as `rangeStart`). The backend sums
611
+ // them into one record; the day close finalizes the documents.
612
+ if (selection.mode === CALENDAR_MODE_ENUM.LIVE) {
613
+ const dayKey = selection.rangeStart ?? selection.rangeEnd;
614
+ if (dayKey == null)
615
+ return null;
616
+ return usableGroups([
617
+ {
618
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
619
+ scope_field: runningDayHourLabels(dayKey),
620
+ },
621
+ ]);
622
+ }
623
+ const { view, rangeStart, rangeEnd, selectedDates, selectedPeriods } = selection;
624
+ // =====================Refinements (every view)=====================
625
+ //
626
+ // Both refinements degenerate the read to standalone day/hour documents:
627
+ // - time window → `localHour`: the exact hour labels for the selected days;
628
+ // - weekday filter → `localDate`: the matching day keys (`localDate` /
629
+ // `localHour` docs carry `day_index`; period docs do not, hence the scope
630
+ // switch). The weekday refinement is applied inside the effective-day
631
+ // helper BEFORE hour-window expansion — the same helper feeds the
632
+ // calendar's grid highlight and summary aggregate, so UI and request can
633
+ // never disagree.
634
+ const window = resolveTimeOfDayWindow(selection);
635
+ const weekdayFilter = getActiveWeekdayFilter(selection.weekdays);
636
+ if (window != null || weekdayFilter != null) {
637
+ const days = getDayKeysFromCalendarSelection(selection);
638
+ if (days.length === 0)
639
+ return null;
640
+ // Compile the effective days (+ window) into the minimal scope groups:
641
+ // day runs compact into the largest exact periods they fully cover, and
642
+ // a window becomes exact hour labels — a continuous SPAN on range-like
643
+ // views (toggle), the same hours on each selected day otherwise
644
+ // (dedicated window view / discrete selections).
645
+ const groups = buildMaterializedReportScopeGroups({
646
+ days,
647
+ ...(window != null
648
+ ? {
649
+ window: {
650
+ fromHour: window.fromHour,
651
+ toHour: window.toHour,
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
656
+ ? MATERIALIZED_REPORT_WINDOW_KIND.SPAN
657
+ : MATERIALIZED_REPORT_WINDOW_KIND.RECURRING,
658
+ },
659
+ }
660
+ : {}),
661
+ });
662
+ if (groups != null) {
663
+ return usableGroups(groups);
664
+ }
665
+ // Uncompilable refinement selection (the picker mirrors the compiler
666
+ // rules, so this should be unreachable) — return `null` instead of
667
+ // silently dropping the window / weekday refinement and reading full
668
+ // days the UI never advertised.
669
+ return null;
670
+ }
671
+ // =====================Period views=====================
672
+ switch (view) {
673
+ case CALENDAR_VIEW_MODE_ENUM.DATE_RANGE:
674
+ case CALENDAR_VIEW_MODE_ENUM.DATE_RANGE_TIME_WINDOW:
675
+ // Every day of the range, compacted into the largest exact periods
676
+ // they fully cover; the dedicated window view without a complete
677
+ // window falls back here (same totals, no window).
678
+ return usableGroups(buildMaterializedReportScopeGroups({
679
+ days: getDayKeysFromCalendarSelection(selection),
680
+ }));
681
+ case CALENDAR_VIEW_MODE_ENUM.MULTI_DATE:
682
+ // Discrete days still compact — adjacent runs that exactly cover a
683
+ // whole week / month / … fold into it, the rest stays `localDate`.
684
+ return usableGroups(buildMaterializedReportScopeGroups({
685
+ days: Array.isArray(selectedDates) ? selectedDates : [],
686
+ }));
687
+ case CALENDAR_VIEW_MODE_ENUM.WEEK:
688
+ return scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK));
689
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS:
690
+ return scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, Array.isArray(selectedPeriods) ? selectedPeriods : []);
691
+ case CALENDAR_VIEW_MODE_ENUM.WEEK_OF_YEAR:
692
+ return rangeStart == null
693
+ ? null
694
+ : scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR, enumerateIsoWeeks(rangeStart, rangeEnd ?? rangeStart));
695
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR:
696
+ return scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR, Array.isArray(selectedPeriods) ? selectedPeriods : []);
697
+ case CALENDAR_VIEW_MODE_ENUM.MONTH:
698
+ return scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH));
699
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS:
700
+ return scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, Array.isArray(selectedPeriods) ? selectedPeriods : []);
701
+ case CALENDAR_VIEW_MODE_ENUM.QUARTER:
702
+ return scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER));
703
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS:
704
+ return scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER, Array.isArray(selectedPeriods) ? selectedPeriods : []);
705
+ case CALENDAR_VIEW_MODE_ENUM.SEMESTER:
706
+ return scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER));
707
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS:
708
+ return scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER, Array.isArray(selectedPeriods) ? selectedPeriods : []);
709
+ case CALENDAR_VIEW_MODE_ENUM.YEAR:
710
+ return scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR));
711
+ case CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS:
712
+ return scopedGroups(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR, Array.isArray(selectedPeriods) ? selectedPeriods : []);
713
+ default:
714
+ return null;
715
+ }
716
+ };