@managesome/eposmatic-toolkit 0.4.4 → 0.4.7

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 (60) hide show
  1. package/esm/constants/REPORT_CALENDAR.js +47 -0
  2. package/esm/constants/index.js +1 -0
  3. package/esm/helpers/materialized-reports/index.js +2 -0
  4. package/esm/helpers/materialized-reports/materialized-reports-read-helpers.js +20 -21
  5. package/esm/helpers/materialized-reports/materialized-reports-scope-group-helpers.js +281 -0
  6. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +473 -0
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +126 -7
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +47 -1
  9. package/esm/helpers/order/generate-order.js +11 -0
  10. package/esm/helpers/store/common-order-actions.js +7 -3
  11. package/esm/helpers/types/index.js +1 -0
  12. package/esm/helpers/types/materialized-reports-apis.js +1 -1
  13. package/esm/helpers/types/report-calendar.js +1 -0
  14. package/lib/constants/REPORT_CALENDAR.d.ts +31 -0
  15. package/lib/constants/REPORT_CALENDAR.js +50 -0
  16. package/lib/constants/index.d.ts +1 -0
  17. package/lib/constants/index.js +1 -0
  18. package/lib/helpers/materialized-reports/index.d.ts +2 -0
  19. package/lib/helpers/materialized-reports/index.js +2 -0
  20. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.d.ts +20 -21
  21. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.js +20 -21
  22. package/lib/helpers/materialized-reports/materialized-reports-scope-group-helpers.d.ts +58 -0
  23. package/lib/helpers/materialized-reports/materialized-reports-scope-group-helpers.js +286 -0
  24. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +25 -0
  25. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +479 -0
  26. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +24 -0
  27. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +127 -7
  28. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +47 -1
  29. package/lib/helpers/order/generate-order.d.ts +2 -0
  30. package/lib/helpers/order/generate-order.js +13 -0
  31. package/lib/helpers/store/common-order-actions.js +7 -3
  32. package/lib/helpers/types/index.d.ts +1 -0
  33. package/lib/helpers/types/index.js +1 -0
  34. package/lib/helpers/types/materialized-reports-apis.d.ts +117 -25
  35. package/lib/helpers/types/materialized-reports-apis.js +1 -0
  36. package/lib/helpers/types/report-calendar.d.ts +20 -0
  37. package/lib/helpers/types/report-calendar.js +2 -0
  38. package/lib/schemas/models/internal_invoices.d.ts +3 -3
  39. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +6 -6
  40. package/lib/schemas/models/orders.d.ts +692 -692
  41. package/lib/schemas/models/tenant_purchase_orders.d.ts +90 -90
  42. package/lib/schemas/models/tenants.d.ts +9 -9
  43. package/lib/schemas/models/warehouse_communications.d.ts +3 -3
  44. package/lib/schemas/models/warehouse_internal_movements.d.ts +48 -48
  45. package/lib/schemas/models/warehouse_purchase_order_rfqs.d.ts +63 -63
  46. package/lib/schemas/models/warehouse_purchase_orders.d.ts +96 -96
  47. package/lib/schemas/models/warehouse_sale_invoices.d.ts +3 -3
  48. package/lib/schemas/models/warehouse_sale_order_rfqs.d.ts +69 -69
  49. package/lib/schemas/models/warehouse_sale_orders.d.ts +45 -45
  50. package/lib/schemas/models/warehouses.d.ts +6 -6
  51. package/lib/tests/materialized-reports/materialized-reports-scope-group-helpers.test.d.ts +1 -0
  52. package/lib/tests/materialized-reports/materialized-reports-scope-group-helpers.test.js +275 -0
  53. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.d.ts +1 -0
  54. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +166 -0
  55. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.d.ts +1 -0
  56. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +143 -0
  57. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +22 -0
  58. package/lib/tests/num-of-guests-limit.test.d.ts +1 -0
  59. package/lib/tests/num-of-guests-limit.test.js +76 -0
  60. package/package.json +1 -1
@@ -0,0 +1,47 @@
1
+ // Report Calendar selection model constants (see the Report Calendar
2
+ // concept doc §5). The calendar produces an `IReportCalendarSelection`;
3
+ // every materialized report read API decodes it server-side with the
4
+ // toolkit's `buildMaterializedReportScopeGroupsFromSelection` — the
5
+ // selection model is the SINGLE shared contract between the calendar UI and
6
+ // the read services.
7
+ export var CALENDAR_MODE_ENUM;
8
+ (function (CALENDAR_MODE_ENUM) {
9
+ CALENDAR_MODE_ENUM["LIVE"] = "LIVE";
10
+ CALENDAR_MODE_ENUM["HISTORICAL"] = "HISTORICAL";
11
+ })(CALENDAR_MODE_ENUM || (CALENDAR_MODE_ENUM = {}));
12
+ export const ALL_CALENDAR_MODE_ENUMS = Object.values(CALENDAR_MODE_ENUM);
13
+ // Historical selection modes (doc §4.2) — default = DATE_RANGE.
14
+ // Every materialized scope context is selectable: day/hour ranges, calendar
15
+ // weeks (Sun–Sat), ISO weeks of year (Mon–Sun), months, quarters, semesters
16
+ // and years — contiguous ranges plus discrete (DIFFERENT_*) picks.
17
+ // Two refinements apply to ANY historical view (they are modifiers, not
18
+ // modes): the time-of-day window (hour-level, own `localHour`
19
+ // materialization) and the weekday filter (`day_index`, applied by the
20
+ // decoder).
21
+ export var CALENDAR_VIEW_MODE_ENUM;
22
+ (function (CALENDAR_VIEW_MODE_ENUM) {
23
+ CALENDAR_VIEW_MODE_ENUM["DATE_RANGE"] = "DATE_RANGE";
24
+ CALENDAR_VIEW_MODE_ENUM["MULTI_DATE"] = "MULTI_DATE";
25
+ CALENDAR_VIEW_MODE_ENUM["DATE_RANGE_TIME_WINDOW"] = "DATE_RANGE_TIME_WINDOW";
26
+ CALENDAR_VIEW_MODE_ENUM["WEEK"] = "WEEK";
27
+ CALENDAR_VIEW_MODE_ENUM["DIFFERENT_WEEKS"] = "DIFFERENT_WEEKS";
28
+ CALENDAR_VIEW_MODE_ENUM["WEEK_OF_YEAR"] = "WEEK_OF_YEAR";
29
+ CALENDAR_VIEW_MODE_ENUM["DIFFERENT_WEEKS_OF_YEAR"] = "DIFFERENT_WEEKS_OF_YEAR";
30
+ CALENDAR_VIEW_MODE_ENUM["MONTH"] = "MONTH";
31
+ CALENDAR_VIEW_MODE_ENUM["DIFFERENT_MONTHS"] = "DIFFERENT_MONTHS";
32
+ CALENDAR_VIEW_MODE_ENUM["QUARTER"] = "QUARTER";
33
+ CALENDAR_VIEW_MODE_ENUM["DIFFERENT_QUARTERS"] = "DIFFERENT_QUARTERS";
34
+ CALENDAR_VIEW_MODE_ENUM["SEMESTER"] = "SEMESTER";
35
+ CALENDAR_VIEW_MODE_ENUM["DIFFERENT_SEMESTERS"] = "DIFFERENT_SEMESTERS";
36
+ CALENDAR_VIEW_MODE_ENUM["YEAR"] = "YEAR";
37
+ CALENDAR_VIEW_MODE_ENUM["DIFFERENT_YEARS"] = "DIFFERENT_YEARS";
38
+ })(CALENDAR_VIEW_MODE_ENUM || (CALENDAR_VIEW_MODE_ENUM = {}));
39
+ export const ALL_CALENDAR_VIEW_MODE_ENUMS = Object.values(CALENDAR_VIEW_MODE_ENUM);
40
+ /**
41
+ * Version of the `IReportCalendarSelection` spec carried by a materialized
42
+ * report READ body (`selection.spec_version`). Bump on any meaning-changing
43
+ * reshape of the selection model — the read API rejects unknown versions
44
+ * with a 400, so rolling deploys (old frontend → new backend) fail loudly
45
+ * instead of decoding a stale shape.
46
+ */
47
+ export const MATERIALIZED_REPORT_SELECTION_SPEC_VERSION = 1;
@@ -11,6 +11,7 @@ export * from './MATERIALIZED_REPORTS';
11
11
  export * from './NOTIFICATIONS';
12
12
  export * from './ORDER';
13
13
  export * from './PRA_ENUMS';
14
+ export * from './REPORT_CALENDAR';
14
15
  export * from './REPORT_WEBVIEW';
15
16
  export * from './RFQ_GO';
16
17
  export * from './SMARTPAY_ENUMS';
@@ -1,5 +1,7 @@
1
1
  export * from './key-helpers';
2
2
  export * from './materialized-reports-read-helpers';
3
+ export * from './materialized-reports-scope-group-helpers';
4
+ export * from './materialized-reports-selection-helpers';
3
5
  export * from './materialized-tenant-reports-iterations-helpers';
4
6
  export * from './scope-helpers';
5
7
  export * from './tenant-sales-overview-close-day-helpers';
@@ -4,15 +4,16 @@ import { getMaterializedHourScopeField, parseMaterializedLocalDate } from './sco
4
4
  * Read-side helpers for materialized-report documents — the frontend-facing
5
5
  * half of the query story (see `MATERIALIZED_REPORTS.md` "Time scopes").
6
6
  *
7
- * The ops-service read API takes `{ scope_context, scope_field | from/to }`:
8
- * - contiguous selections go through `from`/`to` directly (callers can use
9
- * `getMaterializedScopeSpan` / `getMaterializedHourScopeSpan` to derive the
10
- * span of a set of keys);
11
- * - discrete selections fetch the min..max SPAN and keep the exact keys with
12
- * `filterMaterializedTenantSalesOverviewReportsByScopeFields`;
7
+ * The ops-service read API takes `{ scope_context, scope_field }` where
8
+ * `scope_field` is an EXACT value or an `$in` list of exact values — the
9
+ * request itself never carries ranges:
10
+ * - every selection (contiguous periods, discrete picks, hour windows,
11
+ * weekday filters) is compiled by the caller into the exact value list it
12
+ * wants;
13
13
  * - recurring hour windows (e.g. 6–8pm on every day of a range) expand to the
14
- * exact hour labels with `getMaterializedHourWindowScopeFields` (span-fetch
15
- * the full days first, then filter to the labels).
14
+ * exact hour labels with `getMaterializedHourWindowScopeFields`;
15
+ * - `getMaterializedScopeSpan` / `getMaterializedHourScopeSpan` remain as
16
+ * min..max bounds utilities for key sets (not part of the read path).
16
17
  *
17
18
  * Validation convention: helpers return `null` instead of throwing — `null`
18
19
  * means the caller passed invalid data.
@@ -94,12 +95,9 @@ export function getMaterializedHourWindowScopeFields(businessDays, fromHour, toH
94
95
  return labels;
95
96
  }
96
97
  /**
97
- * Full-day span of a list of business days for `localHour` reads: the
98
- * inclusive `{ from: '<first> 00', to: '<last> 23' }` range covers ALL 24
99
- * hour buckets of every label day in between (a label day's buckets are
100
- * `'D 00'`…`'D 23'`, spanning the post-midnight hours too). Filter the
101
- * fetched documents afterwards with `getMaterializedHourWindowScopeFields` /
102
- * `filterMaterializedTenantSalesOverviewReportsByScopeFields`.
98
+ * Min..max `localHour` bounds of a list of business days:
99
+ * `{ from: '<first> 00', to: '<last> 23' }`. A bounds utility for key sets —
100
+ * the READ API takes exact values / `$in` lists, never ranges.
103
101
  *
104
102
  * Returns `null` (never throws) for a malformed list.
105
103
  */
@@ -116,11 +114,11 @@ export function getMaterializedHourScopeSpan(businessDays) {
116
114
  return { from: `${sorted[0]} 00`, to: `${sorted[sorted.length - 1]} 23` };
117
115
  }
118
116
  /**
119
- * Inclusive min..max span of exact non-hour scope values — the fetch range
120
- * for discrete selections (all non-hour scope fields are fixed-width, so
121
- * lexicographic order equals chronological order). Returns `null` (never
122
- * throws) for the hour scope (use `getMaterializedHourScopeSpan`) or a
123
- * malformed list.
117
+ * Inclusive min..max bounds of exact non-hour scope values (all non-hour
118
+ * scope fields are fixed-width, so lexicographic order equals chronological
119
+ * order). A bounds utility for key sets — the READ API takes exact values /
120
+ * `$in` lists, never ranges. Returns `null` (never throws) for the hour
121
+ * scope or a malformed list.
124
122
  */
125
123
  export function getMaterializedScopeSpan(scope_context, scopeFields) {
126
124
  if (scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
@@ -139,8 +137,9 @@ export function getMaterializedScopeSpan(scope_context, scopeFields) {
139
137
  }
140
138
  /**
141
139
  * Keeps only the documents whose `scope_field` is one of the requested keys —
142
- * the client-side refinement for discrete selections fetched as a span.
143
- * Returns `null` (never throws) for malformed input; unknown keys simply match
140
+ * a client-side refinement utility for arbitrary document sets (the read API
141
+ * returns exactly the requested values, so it needs no refinement). Returns
142
+ * `null` (never throws) for malformed input; unknown keys simply match
144
143
  * nothing (absence = zero).
145
144
  */
146
145
  export function filterMaterializedTenantSalesOverviewReportsByScopeFields(docs, scopeFields) {
@@ -0,0 +1,281 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { getMaterializedHourWindowScopeFields } from './materialized-reports-read-helpers';
3
+ /**
4
+ * Smart scope-group compiler for materialized-report reads — turns a
5
+ * selection into the FEWEST exact-scope groups the read needs
6
+ * (`IGetMaterializedReportScopeGroup[]`, the `scope_groups` body field):
7
+ *
8
+ * - **compaction**: a contiguous day set is folded into the largest EXACT
9
+ * periods (year → semester → quarter → month → week) before falling back
10
+ * to `localDate` values — e.g. Sep 1–30 becomes ONE `localMonth: ['2026-09']`
11
+ * instead of 30 day values (one document instead of 30);
12
+ * - **recurring window**: the same hours on every selected day → a single
13
+ * `localHour` group (the dedicated time-of-day-window read);
14
+ * - **span window**: from `x:00` on the first day CONTINUOUSLY through
15
+ * `y:00` on the last day — boundary days carry only their partial hour
16
+ * labels (business-day continuous: the start day runs to its 06:00
17
+ * boundary including the post-midnight tail, the end day starts at 06:00),
18
+ * the full days in between compact through the same period logic. What the
19
+ * span does NOT read (absent documents) counts as zero, and groups NEVER
20
+ * overlap — the backend simply unions them.
21
+ *
22
+ * `compactMaterializedReportDayKeys` is exported for direct testing.
23
+ *
24
+ * Returns `null` (never throws) for malformed input — `null` means the
25
+ * caller passed invalid data.
26
+ */
27
+ /** Window refinement kinds (see the module docblock). */
28
+ export const MATERIALIZED_REPORT_WINDOW_KIND = {
29
+ RECURRING: 'RECURRING',
30
+ SPAN: 'SPAN',
31
+ };
32
+ /* ------------------------------------------------------------------------ */
33
+ /* Date-key math (UTC — keys are timezone-less) */
34
+ /* ------------------------------------------------------------------------ */
35
+ const KEY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
36
+ const keyToDate = (key) => {
37
+ if (typeof key !== 'string' || !KEY_PATTERN.test(key))
38
+ return null;
39
+ const [year, month, day] = key.split('-').map(Number);
40
+ const date = new Date(Date.UTC(year, month - 1, day));
41
+ // reject impossible dates (e.g. 2026-02-30)
42
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
43
+ return null;
44
+ }
45
+ return date;
46
+ };
47
+ const dateToKey = (date) => `${date.getUTCFullYear()}-${`${date.getUTCMonth() + 1}`.padStart(2, '0')}-${`${date.getUTCDate()}`.padStart(2, '0')}`;
48
+ const addDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
49
+ const DAY_MS = 86400000;
50
+ /** Whole days from `from` to `to` (negative when `to` precedes `from`). */
51
+ const daysBetween = (from, to) => Math.round((to.getTime() - from.getTime()) / DAY_MS);
52
+ /** Sunday-based week start (the `localWeek` bucket identity). */
53
+ const weekStartOf = (date) => addDays(date, -date.getUTCDay());
54
+ /**
55
+ * Periods that START exactly on `date`, largest first: year → semester →
56
+ * quarter → month → week (Sunday-based). Only exact starts are candidates —
57
+ * a run can only compact at its boundaries.
58
+ */
59
+ const periodCandidatesAt = (date) => {
60
+ const year = date.getUTCFullYear();
61
+ const month = date.getUTCMonth() + 1;
62
+ const day = date.getUTCDate();
63
+ const candidates = [];
64
+ const span = (startMonth, months) => {
65
+ const start = new Date(Date.UTC(year, startMonth - 1, 1));
66
+ const end = addDays(new Date(Date.UTC(year, startMonth - 1 + months, 1)), -1);
67
+ return { startKey: dateToKey(start), endKey: dateToKey(end) };
68
+ };
69
+ if (month === 1 && day === 1) {
70
+ const { startKey, endKey } = span(1, 12);
71
+ candidates.push({ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR, label: `${year}`, startKey, endKey });
72
+ }
73
+ if ((month === 1 || month === 7) && day === 1) {
74
+ const { startKey, endKey } = span(month, 6);
75
+ candidates.push({
76
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
77
+ label: `${year}-S${month === 1 ? 1 : 2}`,
78
+ startKey,
79
+ endKey,
80
+ });
81
+ }
82
+ if ([1, 4, 7, 10].includes(month) && day === 1) {
83
+ const { startKey, endKey } = span(month, 3);
84
+ candidates.push({
85
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
86
+ label: `${year}-Q${Math.floor((month - 1) / 3) + 1}`,
87
+ startKey,
88
+ endKey,
89
+ });
90
+ }
91
+ if (day === 1) {
92
+ const { startKey, endKey } = span(month, 1);
93
+ candidates.push({
94
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
95
+ label: `${year}-${`${month}`.padStart(2, '0')}`,
96
+ startKey,
97
+ endKey,
98
+ });
99
+ }
100
+ if (date.getUTCDay() === 0) {
101
+ const startKey = dateToKey(date);
102
+ const endKey = dateToKey(addDays(date, 6));
103
+ candidates.push({ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, label: startKey, startKey, endKey });
104
+ }
105
+ return candidates;
106
+ };
107
+ /* ------------------------------------------------------------------------ */
108
+ /* Compaction */
109
+ /* ------------------------------------------------------------------------ */
110
+ const GROUP_ORDER = [
111
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
112
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
113
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
114
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
115
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
116
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
117
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
118
+ ];
119
+ /** Ordered, deduped, non-empty groups from a context → values map. */
120
+ const toGroups = (values) => {
121
+ const groups = [];
122
+ for (const scope_context of GROUP_ORDER) {
123
+ const set = values.get(scope_context);
124
+ if (set != null && set.size > 0) {
125
+ groups.push({ scope_context, scope_field: [...set].sort() });
126
+ }
127
+ }
128
+ return groups;
129
+ };
130
+ const addValue = (values, scope_context, value) => {
131
+ const set = values.get(scope_context) ?? new Set();
132
+ set.add(value);
133
+ values.set(scope_context, set);
134
+ };
135
+ /**
136
+ * Folds a contiguous day set into the largest EXACT periods (year →
137
+ * semester → quarter → month → week) + `localDate` leftovers — never
138
+ * partial coverage: a period compacts only when the WHOLE period is inside
139
+ * a contiguous run. Returns `null` for malformed/empty input.
140
+ */
141
+ export function compactMaterializedReportDayKeys(days) {
142
+ if (!Array.isArray(days) || days.length === 0)
143
+ return null;
144
+ const dates = [];
145
+ for (const day of days) {
146
+ const date = keyToDate(day);
147
+ if (date == null)
148
+ return null;
149
+ dates.push(date);
150
+ }
151
+ dates.sort((a, b) => a.getTime() - b.getTime());
152
+ const values = new Map();
153
+ let index = 0;
154
+ while (index < dates.length) {
155
+ // contiguous run [runStart..runEnd]
156
+ const runStart = dates[index];
157
+ let runEnd = runStart;
158
+ let next = index + 1;
159
+ while (next < dates.length && daysBetween(runEnd, dates[next]) === 1) {
160
+ runEnd = dates[next];
161
+ next += 1;
162
+ }
163
+ let cursor = runStart;
164
+ while (cursor.getTime() <= runEnd.getTime()) {
165
+ const candidate = periodCandidatesAt(cursor).find((entry) => keyToDate(entry.endKey).getTime() <= runEnd.getTime());
166
+ if (candidate != null) {
167
+ addValue(values, candidate.scope_context, candidate.label);
168
+ cursor = addDays(keyToDate(candidate.endKey), 1);
169
+ }
170
+ else {
171
+ addValue(values, MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, dateToKey(cursor));
172
+ cursor = addDays(cursor, 1);
173
+ }
174
+ }
175
+ index = next;
176
+ }
177
+ return toGroups(values);
178
+ }
179
+ /* ------------------------------------------------------------------------ */
180
+ /* Scope groups */
181
+ /* ------------------------------------------------------------------------ */
182
+ const isValidHour = (hour, max) => Number.isInteger(hour) && hour >= 0 && hour <= max;
183
+ /**
184
+ * Builds the read's scope groups from a selection spec (see the module
185
+ * docblock). Returns `null` for malformed input or an unservable window.
186
+ */
187
+ export function buildMaterializedReportScopeGroups(spec) {
188
+ if (spec == null)
189
+ return null;
190
+ const { days, window } = spec;
191
+ if (!Array.isArray(days) || days.length === 0)
192
+ return null;
193
+ const dates = [];
194
+ for (const day of days) {
195
+ const date = keyToDate(day);
196
+ if (date == null)
197
+ return null;
198
+ dates.push(date);
199
+ }
200
+ dates.sort((a, b) => a.getTime() - b.getTime());
201
+ const dayKeys = [...new Set(dates.map(dateToKey))];
202
+ const uniqueDates = dayKeys.map((key) => keyToDate(key));
203
+ // A SPAN window reads the CONTINUOUS interval first-day → last-day — a day
204
+ // set with gaps would silently pull the gap days in as full middle days.
205
+ if (window != null && window.kind === MATERIALIZED_REPORT_WINDOW_KIND.SPAN) {
206
+ for (let index = 1; index < uniqueDates.length; index += 1) {
207
+ if (daysBetween(uniqueDates[index - 1], uniqueDates[index]) !== 1) {
208
+ return null;
209
+ }
210
+ }
211
+ }
212
+ // No window → compaction only.
213
+ if (window == null) {
214
+ return compactMaterializedReportDayKeys(dayKeys);
215
+ }
216
+ const { fromHour, toHour, kind } = window;
217
+ if (!isValidHour(fromHour, 23) || !isValidHour(toHour, 23))
218
+ return null;
219
+ // Recurring: the same hours on every selected day.
220
+ if (kind === MATERIALIZED_REPORT_WINDOW_KIND.RECURRING) {
221
+ const labels = getMaterializedHourWindowScopeFields(dayKeys, fromHour, toHour);
222
+ return labels == null ? null : [{ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: labels }];
223
+ }
224
+ // Span (business-day continuous).
225
+ const startDate = uniqueDates[0];
226
+ const endDate = uniqueDates[uniqueDates.length - 1];
227
+ const x = fromHour;
228
+ const y = toHour;
229
+ // Single calendar day, overnight window (e.g. 18:00 → 2:00): one business
230
+ // day covers it whole.
231
+ if (daysBetween(startDate, endDate) === 0 && x >= 6 && y <= 6) {
232
+ if (x === 6 && y === 6) {
233
+ return compactMaterializedReportDayKeys([dateToKey(startDate)]);
234
+ }
235
+ const labels = getMaterializedHourWindowScopeFields([dateToKey(startDate)], x, y);
236
+ return labels == null ? null : [{ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: labels }];
237
+ }
238
+ // Boundary business days: a start before 06:00 belongs to the previous
239
+ // business day's tail; an end at/before 06:00 ends the previous business
240
+ // day.
241
+ const startBus = x >= 6 ? startDate : addDays(startDate, -1);
242
+ const endBus = y > 6 ? endDate : addDays(endDate, -1);
243
+ // One business day hosts both boundaries (e.g. a full day 06:00 → 06:00).
244
+ if (startBus.getTime() === endBus.getTime()) {
245
+ if (x === 6 && y === 6) {
246
+ return compactMaterializedReportDayKeys([dateToKey(startBus)]);
247
+ }
248
+ const labels = getMaterializedHourWindowScopeFields([dateToKey(startBus)], x, y);
249
+ return labels == null ? null : [{ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: labels }];
250
+ }
251
+ const startLabels = x === 6 ? null : getMaterializedHourWindowScopeFields([dateToKey(startBus)], x, 6);
252
+ const endLabels = y === 6 ? null : getMaterializedHourWindowScopeFields([dateToKey(endBus)], 6, y);
253
+ if (x !== 6 && startLabels == null)
254
+ return null;
255
+ if (y !== 6 && endLabels == null)
256
+ return null;
257
+ const values = new Map();
258
+ // Full business days between the boundaries — compacted like any day set
259
+ // (a month-long span middle becomes period values, not day values).
260
+ const firstFullDate = x === 6 ? startBus : addDays(startBus, 1);
261
+ const lastFullDate = y === 6 ? endBus : addDays(endBus, -1);
262
+ if (firstFullDate.getTime() <= lastFullDate.getTime()) {
263
+ const fullDays = [];
264
+ for (let cursor = firstFullDate; cursor.getTime() <= lastFullDate.getTime(); cursor = addDays(cursor, 1)) {
265
+ fullDays.push(dateToKey(cursor));
266
+ }
267
+ const compacted = compactMaterializedReportDayKeys(fullDays);
268
+ if (compacted == null)
269
+ return null;
270
+ for (const group of compacted) {
271
+ for (const value of group.scope_field) {
272
+ addValue(values, group.scope_context, value);
273
+ }
274
+ }
275
+ }
276
+ for (const label of [...(startLabels ?? []), ...(endLabels ?? [])]) {
277
+ addValue(values, MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, label);
278
+ }
279
+ const groups = toGroups(values);
280
+ return groups.length === 0 ? null : groups;
281
+ }