@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,479 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildMaterializedReportScopeGroupsFromSelection = exports.isValidBusinessHourWindow = exports.getDayKeysFromCalendarSelection = void 0;
4
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
5
+ const REPORT_CALENDAR_1 = require("../../constants/REPORT_CALENDAR");
6
+ const materialized_reports_scope_group_helpers_1 = require("./materialized-reports-scope-group-helpers");
7
+ const scope_helpers_1 = require("./scope-helpers");
8
+ /**
9
+ * Calendar-selection DECODER for the materialized report READ APIs — the
10
+ * backend-side twin of the calendar: it maps one `IReportCalendarSelection`
11
+ * to the exact `scope_groups` a read request needs, so clients ship the
12
+ * selection (a few hundred bytes) instead of enumerating tens of thousands
13
+ * of scope values.
14
+ *
15
+ * Semantics (identical to what the frontend compiler produced before this
16
+ * moved server-side):
17
+ * - LIVE reads ONLY the running business day — all of its exact `localHour`
18
+ * labels (the calendar commits the running day as `rangeStart`); summed by
19
+ * the backend it yields the running day's metrics so far, finalized at day
20
+ * close;
21
+ * - day-based selections compile through the SMART compiler
22
+ * (`buildMaterializedReportScopeGroups`): contiguous day runs fold into the
23
+ * LARGEST exact periods they fully cover (week → month → quarter → semester
24
+ * → year; anything left stays `localDate`);
25
+ * - a time-of-day window compiles to `localHour` labels: a CONTINUOUS SPAN on
26
+ * range-like views (toggle), the SAME hours on each selected day otherwise
27
+ * (dedicated window view / discrete selections);
28
+ * - the weekday refinement degenerates the read to standalone day documents
29
+ * (`localDate` / `localHour` docs carry `day_index`; period docs do not):
30
+ * it filters the effective day set BEFORE hour-window expansion;
31
+ * - period views read their exact period keys directly (week starts, ISO week
32
+ * labels, months, quarters, semesters, years).
33
+ *
34
+ * Returns `null` (never throws) when the selection cannot be served (missing
35
+ * range on a range view, malformed keys, an invalid refinement window, or an
36
+ * unservable empty result). Group values are exact; empty groups are dropped.
37
+ */
38
+ /** Range-like views whose toggle window is a CONTINUOUS span. */
39
+ const SPAN_VIEWS = new Set([
40
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DATE_RANGE,
41
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK,
42
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK_OF_YEAR,
43
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MONTH,
44
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.QUARTER,
45
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.SEMESTER,
46
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.YEAR,
47
+ ]);
48
+ /** Views whose day set is one contiguous `rangeStart … rangeEnd` walk. */
49
+ const RANGE_LIKE_VIEWS = new Set([
50
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DATE_RANGE,
51
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DATE_RANGE_TIME_WINDOW,
52
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK,
53
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK_OF_YEAR,
54
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.QUARTER,
55
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.SEMESTER,
56
+ ]);
57
+ /* ==================== Date-key primitives ==================== */
58
+ // Local 'YYYY-MM-DD' key for a Date (NOT UTC — the tenant's local day).
59
+ const formatLocalDateKey = (date) => {
60
+ const year = date.getFullYear();
61
+ const month = `${date.getMonth() + 1}`.padStart(2, '0');
62
+ const day = `${date.getDate()}`.padStart(2, '0');
63
+ return `${year}-${month}-${day}`;
64
+ };
65
+ const getDateFromKey = (key) => {
66
+ const [year, month, day] = key.split('-').map(Number);
67
+ return new Date(year, month - 1, day);
68
+ };
69
+ const addDaysToKey = (dateKey, days) => {
70
+ const date = getDateFromKey(dateKey);
71
+ date.setDate(date.getDate() + days);
72
+ return formatLocalDateKey(date);
73
+ };
74
+ // 'YYYY-Qn' quarter start ('YYYY-MM-01') — accepts a quarter key
75
+ const getQuarterStartKey = (quarterKey) => {
76
+ const [year, quarter] = quarterKey.split('-');
77
+ const month = (Number(quarter.slice(1)) - 1) * 3 + 1;
78
+ return `${year}-${`${month}`.padStart(2, '0')}-01`;
79
+ };
80
+ // 'YYYY-Qn' quarter end (last day of the quarter) — accepts a quarter key
81
+ const getQuarterEndKey = (quarterKey) => {
82
+ const [year, quarter] = quarterKey.split('-');
83
+ return formatLocalDateKey(new Date(Number(year), Number(quarter.slice(1)) * 3, 0));
84
+ };
85
+ // 'YYYY-Sn' semester start ('YYYY-MM-01') — accepts a semester key
86
+ const getSemesterStartKey = (semesterKey) => {
87
+ const [year, semester] = semesterKey.split('-');
88
+ return `${year}-${semester === 'S1' ? '01' : '07'}-01`;
89
+ };
90
+ // 'YYYY-Sn' semester end — accepts a semester key
91
+ const getSemesterEndKey = (semesterKey) => {
92
+ const [year, semester] = semesterKey.split('-');
93
+ return semester === 'S1' ? `${year}-06-30` : `${year}-12-31`;
94
+ };
95
+ // Monday start of the ISO week containing the given day key
96
+ const getIsoWeekStartKey = (dateKey) => {
97
+ const date = getDateFromKey(dateKey);
98
+ const offset = (date.getDay() + 6) % 7; // days since Monday
99
+ date.setDate(date.getDate() - offset);
100
+ return formatLocalDateKey(date);
101
+ };
102
+ // 'YYYY-Wnn' ISO label of a day key — `YYYY` is the ISO week-year, so
103
+ // boundary weeks (e.g. 2027-01-01 → '2026-W53') label correctly.
104
+ const getIsoWeekKey = (dateKey) => (0, scope_helpers_1.getMaterializedPeriodScopeFields)(dateKey)?.[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR] ?? null;
105
+ // Monday day key of an ISO week label ('YYYY-Wnn'); null for malformed input
106
+ const getIsoWeekStartKeyFromLabel = (weekKey) => {
107
+ const match = /^(\d{4})-W(\d{2})$/.exec(weekKey);
108
+ if (!match)
109
+ return null;
110
+ const week = Number(match[2]);
111
+ if (week < 1 || week > 53)
112
+ return null;
113
+ // ISO week 1 is the week containing Jan 4 — its Monday anchors numbering
114
+ const weekOneMonday = getDateFromKey(getIsoWeekStartKey(`${match[1]}-01-04`));
115
+ weekOneMonday.setDate(weekOneMonday.getDate() + (week - 1) * 7);
116
+ return formatLocalDateKey(weekOneMonday);
117
+ };
118
+ /* ==================== Weekday refinement ==================== */
119
+ /**
120
+ * Active weekday refinement — `null` when unset (= every day). The decoder,
121
+ * the calendar's grid highlight and the selection summary all use the SAME
122
+ * effective-day semantics, so the UI can never claim days the report won't
123
+ * read.
124
+ */
125
+ const getActiveWeekdayFilter = (weekdays) => {
126
+ if (!Array.isArray(weekdays) || weekdays.length === 0)
127
+ return null;
128
+ if (weekdays.length >= 7)
129
+ return null;
130
+ return weekdays;
131
+ };
132
+ /** Whether a day key is kept by the active weekday refinement. */
133
+ const isDayKeptByWeekdayFilter = (dateKey, weekdays) => {
134
+ if (weekdays == null)
135
+ return true;
136
+ const dayIndex = (0, scope_helpers_1.getDayIndexFromLocalDate)(dateKey);
137
+ return dayIndex != null && weekdays.includes(dayIndex);
138
+ };
139
+ /* ==================== Effective day set ==================== */
140
+ // All day keys covered by the current selection — BEFORE the weekday
141
+ // refinement.
142
+ const getBaseSelectedDayKeys = (selection) => {
143
+ const { view, rangeStart, rangeEnd, selectedDates, selectedPeriods } = selection;
144
+ const expandRange = (start, end) => {
145
+ const keys = [];
146
+ let cursor = start;
147
+ while (cursor <= end) {
148
+ keys.push(cursor);
149
+ cursor = addDaysToKey(cursor, 1);
150
+ }
151
+ return keys;
152
+ };
153
+ if (RANGE_LIKE_VIEWS.has(view)) {
154
+ if (!rangeStart)
155
+ return [];
156
+ return expandRange(rangeStart, rangeEnd ?? rangeStart);
157
+ }
158
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MULTI_DATE)
159
+ return selectedDates;
160
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS) {
161
+ return selectedPeriods.flatMap((weekStart) => expandRange(weekStart, addDaysToKey(weekStart, 6)));
162
+ }
163
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR) {
164
+ return selectedPeriods.flatMap((weekKey) => {
165
+ const weekStart = getIsoWeekStartKeyFromLabel(weekKey);
166
+ return weekStart == null ? [] : expandRange(weekStart, addDaysToKey(weekStart, 6));
167
+ });
168
+ }
169
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MONTH || view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.YEAR) {
170
+ if (!rangeStart)
171
+ return [];
172
+ return expandRange(rangeStart, rangeEnd ?? rangeStart);
173
+ }
174
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS) {
175
+ return selectedPeriods.flatMap((monthKey) => {
176
+ const [year, month] = monthKey.split('-').map(Number);
177
+ return expandRange(`${monthKey}-01`, formatLocalDateKey(new Date(year, month, 0)));
178
+ });
179
+ }
180
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS) {
181
+ return selectedPeriods.flatMap((quarterKey) => expandRange(getQuarterStartKey(quarterKey), getQuarterEndKey(quarterKey)));
182
+ }
183
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS) {
184
+ return selectedPeriods.flatMap((semesterKey) => expandRange(getSemesterStartKey(semesterKey), getSemesterEndKey(semesterKey)));
185
+ }
186
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS) {
187
+ return selectedPeriods.flatMap((yearKey) => expandRange(`${yearKey}-01-01`, `${yearKey}-12-31`));
188
+ }
189
+ return [];
190
+ };
191
+ /**
192
+ * All day keys covered by a selection — keeps only days that match the
193
+ * active weekday refinement, so non-matching days never contribute to
194
+ * summaries, DateContext bounds, or requests.
195
+ */
196
+ const getDayKeysFromCalendarSelection = (selection) => {
197
+ const keys = getBaseSelectedDayKeys(selection);
198
+ const weekdays = getActiveWeekdayFilter(selection.weekdays);
199
+ if (weekdays == null)
200
+ return keys;
201
+ return keys.filter((key) => isDayKeptByWeekdayFilter(key, weekdays));
202
+ };
203
+ exports.getDayKeysFromCalendarSelection = getDayKeysFromCalendarSelection;
204
+ /* ==================== Hour-window validity ==================== */
205
+ /**
206
+ * Whether an hour window `[fromHour, toHour)` fits one business day
207
+ * (06:00 → 06:00) — mirrors the toolkit's materialized window rule
208
+ * (`getMaterializedHourWindowScopeFields`): whole-hour buckets, end-exclusive
209
+ * (18 → 20 = hours 18, 19), midnight wrap allowed (22 → 2), but never a walk
210
+ * crossing the 06:00 business-morning boundary (4 → 8 is invalid). The
211
+ * calendar's time field uses this to disable unservable picker options, so an
212
+ * invalid window can never be composed for the read request.
213
+ */
214
+ const isValidBusinessHourWindow = (fromHour, toHour) => {
215
+ if (!Number.isInteger(fromHour) || fromHour < 0 || fromHour > 23) {
216
+ return false;
217
+ }
218
+ if (!Number.isInteger(toHour) || toHour < 0 || toHour > 23)
219
+ return false;
220
+ const hourCount = (((toHour - fromHour) % 24) + 24) % 24;
221
+ if (hourCount === 0)
222
+ return false; // ambiguous empty window
223
+ const startPosition = (fromHour + 18) % 24;
224
+ return startPosition + hourCount <= 24;
225
+ };
226
+ exports.isValidBusinessHourWindow = isValidBusinessHourWindow;
227
+ /* ==================== Decode internals ==================== */
228
+ /** `'HH:mm'` → hour number (whole hours only). */
229
+ const hourOf = (time) => {
230
+ if (time == null)
231
+ return null;
232
+ const hour = Number.parseInt(time.split(':')[0] ?? '', 10);
233
+ return Number.isInteger(hour) && hour >= 0 && hour <= 23 ? hour : null;
234
+ };
235
+ /** Active time-of-day window (both ends set and servable) — else `null`. */
236
+ const resolveTimeOfDayWindow = (selection) => {
237
+ const fromHour = hourOf(selection.timeStart);
238
+ const toHour = hourOf(selection.timeEnd);
239
+ if (fromHour == null || toHour == null)
240
+ return null;
241
+ if (!(0, exports.isValidBusinessHourWindow)(fromHour, toHour))
242
+ return null;
243
+ return { fromHour, toHour };
244
+ };
245
+ const periodKeyOf = (dayKey, scope) => {
246
+ const fields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(dayKey);
247
+ if (fields == null)
248
+ return null;
249
+ switch (scope) {
250
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK:
251
+ return fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK];
252
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH:
253
+ return fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH];
254
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER:
255
+ return fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER];
256
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER:
257
+ return fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER];
258
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR:
259
+ return fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR];
260
+ default:
261
+ return null;
262
+ }
263
+ };
264
+ /** Groups with at least one value — dropped groups leave `null`. */
265
+ const usableGroups = (groups) => {
266
+ const usable = (groups ?? []).filter((group) => group.scope_field.length > 0);
267
+ return usable.length > 0 ? usable : null;
268
+ };
269
+ /** Groups with the exact period values of one scope (period views). */
270
+ const scopedGroups = (scope, values) => usableGroups([{ scope_context: scope, scope_field: values }]);
271
+ /** Business-hour order of one day's hour buckets — 06…23 then 00…05. */
272
+ 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];
273
+ /**
274
+ * Every exact `localHour` label of one business day — the LIVE read. Summed
275
+ * by the backend it yields the running day's metrics so far (the day close
276
+ * finalizes them); a closed day's hours sum to its `localDate` totals.
277
+ */
278
+ const runningDayHourLabels = (dayKey) => BUSINESS_DAY_HOURS.map((hour) => (0, scope_helpers_1.getMaterializedHourScopeField)(dayKey, hour)).filter((label) => label != null);
279
+ /** Week-start day keys from `startKey` to `endKey`, stepping 7 days. */
280
+ const enumerateWeekStarts = (startKey, endKey) => {
281
+ const keys = [];
282
+ let cursor = startKey;
283
+ while (cursor <= endKey) {
284
+ keys.push(cursor);
285
+ cursor = addDaysToKey(cursor, 7);
286
+ }
287
+ return keys;
288
+ };
289
+ /** ISO week labels ('YYYY-Wnn') covering `startDayKey` … `endDayKey`. */
290
+ const enumerateIsoWeeks = (startDayKey, endDayKey) => {
291
+ const keys = [];
292
+ const end = getIsoWeekStartKey(endDayKey);
293
+ let cursor = getIsoWeekStartKey(startDayKey);
294
+ while (cursor <= end) {
295
+ const label = getIsoWeekKey(cursor);
296
+ if (label != null)
297
+ keys.push(label);
298
+ cursor = addDaysToKey(cursor, 7);
299
+ }
300
+ return keys;
301
+ };
302
+ /** 'YYYY-MM' keys from `from` to `to` (inclusive). */
303
+ const enumerateMonths = (from, to) => {
304
+ const keys = [];
305
+ let [year, month] = from.split('-').map(Number);
306
+ const [endYear, endMonth] = to.split('-').map(Number);
307
+ while (year < endYear || (year === endYear && month <= endMonth)) {
308
+ keys.push(`${year}-${`${month}`.padStart(2, '0')}`);
309
+ month += 1;
310
+ if (month > 12) {
311
+ month = 1;
312
+ year += 1;
313
+ }
314
+ }
315
+ return keys;
316
+ };
317
+ /** 'YYYY-Qn' keys from `from` to `to` (inclusive). */
318
+ const enumerateQuarters = (from, to) => {
319
+ const asIndex = (key) => {
320
+ const [year, quarter] = key.split('-');
321
+ return Number(year) * 4 + (Number(quarter.slice(1)) - 1);
322
+ };
323
+ const keys = [];
324
+ for (let index = asIndex(from); index <= asIndex(to); index += 1) {
325
+ keys.push(`${Math.floor(index / 4)}-Q${(index % 4) + 1}`);
326
+ }
327
+ return keys;
328
+ };
329
+ /** 'YYYY-Sn' keys from `from` to `to` (inclusive). */
330
+ const enumerateSemesters = (from, to) => {
331
+ const asIndex = (key) => {
332
+ const [year, semester] = key.split('-');
333
+ return Number(year) * 2 + (Number(semester.slice(1)) - 1);
334
+ };
335
+ const keys = [];
336
+ for (let index = asIndex(from); index <= asIndex(to); index += 1) {
337
+ keys.push(`${Math.floor(index / 2)}-S${(index % 2) + 1}`);
338
+ }
339
+ return keys;
340
+ };
341
+ /** 'YYYY' keys from `from` to `to` (inclusive). */
342
+ const enumerateYears = (from, to) => Array.from({ length: Number(to) - Number(from) + 1 }, (_, index) => `${Number(from) + index}`);
343
+ /** Exact period keys covered by a contiguous range of the given scope. */
344
+ const periodRangeFields = (rangeStart, rangeEnd, scope) => {
345
+ if (rangeStart == null)
346
+ return [];
347
+ const from = periodKeyOf(rangeStart, scope);
348
+ const to = periodKeyOf(rangeEnd ?? rangeStart, scope);
349
+ if (from == null || to == null)
350
+ return [];
351
+ switch (scope) {
352
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK:
353
+ return enumerateWeekStarts(from, to);
354
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH:
355
+ return enumerateMonths(from, to);
356
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER:
357
+ return enumerateQuarters(from, to);
358
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER:
359
+ return enumerateSemesters(from, to);
360
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR:
361
+ return enumerateYears(from, to);
362
+ default:
363
+ return [];
364
+ }
365
+ };
366
+ /* ==================== Decode ==================== */
367
+ /**
368
+ * Maps a committed calendar selection to the exact `scope_groups` of the
369
+ * overview read. Returns `null` when the selection cannot be served (LIVE
370
+ * without a committed day, a malformed/empty selection, or unservable
371
+ * refinement input).
372
+ */
373
+ const buildMaterializedReportScopeGroupsFromSelection = (selection) => {
374
+ // LIVE reads ONLY the running business day — all of its exact hour labels
375
+ // (the calendar commits the running day as `rangeStart`). The backend sums
376
+ // them into one record; the day close finalizes the documents.
377
+ if (selection.mode === REPORT_CALENDAR_1.CALENDAR_MODE_ENUM.LIVE) {
378
+ const dayKey = selection.rangeStart ?? selection.rangeEnd;
379
+ if (dayKey == null)
380
+ return null;
381
+ return usableGroups([
382
+ {
383
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
384
+ scope_field: runningDayHourLabels(dayKey),
385
+ },
386
+ ]);
387
+ }
388
+ const { view, rangeStart, rangeEnd, selectedDates, selectedPeriods } = selection;
389
+ // =====================Refinements (every view)=====================
390
+ //
391
+ // Both refinements degenerate the read to standalone day/hour documents:
392
+ // - time window → `localHour`: the exact hour labels for the selected days;
393
+ // - weekday filter → `localDate`: the matching day keys (`localDate` /
394
+ // `localHour` docs carry `day_index`; period docs do not, hence the scope
395
+ // switch). The weekday refinement is applied inside the effective-day
396
+ // helper BEFORE hour-window expansion — the same helper feeds the
397
+ // calendar's grid highlight and summary aggregate, so UI and request can
398
+ // never disagree.
399
+ const window = resolveTimeOfDayWindow(selection);
400
+ const weekdayFilter = getActiveWeekdayFilter(selection.weekdays);
401
+ if (window != null || weekdayFilter != null) {
402
+ const days = (0, exports.getDayKeysFromCalendarSelection)(selection);
403
+ if (days.length === 0)
404
+ return null;
405
+ // Compile the effective days (+ window) into the minimal scope groups:
406
+ // day runs compact into the largest exact periods they fully cover, and
407
+ // a window becomes exact hour labels — a continuous SPAN on range-like
408
+ // views (toggle), the same hours on each selected day otherwise
409
+ // (dedicated window view / discrete selections).
410
+ const groups = (0, materialized_reports_scope_group_helpers_1.buildMaterializedReportScopeGroups)({
411
+ days,
412
+ ...(window != null
413
+ ? {
414
+ window: {
415
+ fromHour: window.fromHour,
416
+ toHour: window.toHour,
417
+ kind: SPAN_VIEWS.has(view)
418
+ ? materialized_reports_scope_group_helpers_1.MATERIALIZED_REPORT_WINDOW_KIND.SPAN
419
+ : materialized_reports_scope_group_helpers_1.MATERIALIZED_REPORT_WINDOW_KIND.RECURRING,
420
+ },
421
+ }
422
+ : {}),
423
+ });
424
+ if (groups != null) {
425
+ return usableGroups(groups);
426
+ }
427
+ // Uncompilable refinement selection (the picker mirrors the compiler
428
+ // rules, so this should be unreachable) — return `null` instead of
429
+ // silently dropping the window / weekday refinement and reading full
430
+ // days the UI never advertised.
431
+ return null;
432
+ }
433
+ // =====================Period views=====================
434
+ switch (view) {
435
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DATE_RANGE:
436
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DATE_RANGE_TIME_WINDOW:
437
+ // Every day of the range, compacted into the largest exact periods
438
+ // they fully cover; the dedicated window view without a complete
439
+ // window falls back here (same totals, no window).
440
+ return usableGroups((0, materialized_reports_scope_group_helpers_1.buildMaterializedReportScopeGroups)({
441
+ days: (0, exports.getDayKeysFromCalendarSelection)(selection),
442
+ }));
443
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MULTI_DATE:
444
+ // Discrete days still compact — adjacent runs that exactly cover a
445
+ // whole week / month / … fold into it, the rest stays `localDate`.
446
+ return usableGroups((0, materialized_reports_scope_group_helpers_1.buildMaterializedReportScopeGroups)({
447
+ days: Array.isArray(selectedDates) ? selectedDates : [],
448
+ }));
449
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK:
450
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK));
451
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS:
452
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, Array.isArray(selectedPeriods) ? selectedPeriods : []);
453
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK_OF_YEAR:
454
+ return rangeStart == null
455
+ ? null
456
+ : scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR, enumerateIsoWeeks(rangeStart, rangeEnd ?? rangeStart));
457
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR:
458
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR, Array.isArray(selectedPeriods) ? selectedPeriods : []);
459
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MONTH:
460
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH));
461
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS:
462
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, Array.isArray(selectedPeriods) ? selectedPeriods : []);
463
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.QUARTER:
464
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER));
465
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS:
466
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER, Array.isArray(selectedPeriods) ? selectedPeriods : []);
467
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.SEMESTER:
468
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER));
469
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS:
470
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER, Array.isArray(selectedPeriods) ? selectedPeriods : []);
471
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.YEAR:
472
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR));
473
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS:
474
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR, Array.isArray(selectedPeriods) ? selectedPeriods : []);
475
+ default:
476
+ return null;
477
+ }
478
+ };
479
+ exports.buildMaterializedReportScopeGroupsFromSelection = buildMaterializedReportScopeGroupsFromSelection;
@@ -1,5 +1,6 @@
1
1
  import { DAY_INDEX_ENUM } from '../../constants/ENUMS';
2
2
  import { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
3
+ import { IMaterializedTenantSalesOverviewAggregatedReport } from '../types/materialized-reports-apis';
3
4
  /**
4
5
  * Frontend formatter for `materialized_tenant_sales_overview_reports` (see
5
6
  * `MATERIALIZED_REPORTS.md` "Frontend consumption").
@@ -134,3 +135,26 @@ export interface IFormattedSalesOverviewPageData {
134
135
  * when the documents cannot be formatted together.
135
136
  */
136
137
  export declare function getFormattedTenantSalesOverviewReporting(docs: IMaterializedTenantSalesOverviewReport[], filters?: IFormattedSalesOverviewFilters | null, separate_view_per_tenant?: boolean): [IFormattedSalesOverviewPageData[], null] | null;
138
+ /**
139
+ * Frontend formatter for the overview response —
140
+ * `IMaterializedTenantSalesOverviewAggregatedReport[]` (one pipeline-computed
141
+ * record per tenant — the shape of every read).
142
+ *
143
+ * Same page-ready output as `getFormattedTenantSalesOverviewReporting`, with
144
+ * the platform / order-status filters applied client-side on the records'
145
+ * preserved key maps (zero refetches). Differences, by construction:
146
+ * - the slice-derived sections are ALWAYS `null`: `weekday` and `hourly`
147
+ * need per-scope documents — the aggregated record has none (most recent
148
+ * period reads must use the raw response if those sections are ever
149
+ * rendered);
150
+ * - an explicit `day_indexes` filter is REJECTED (`null`): the weekday
151
+ * refinement must narrow the request scope (the calendar selection),
152
+ * never the response;
153
+ * - the combined view (default) folds the tenants' records together; with
154
+ * `separate_view_per_tenant: true` each tenant keeps its own entry.
155
+ *
156
+ * Returns `null` (never throws) when the records cannot be formatted
157
+ * together (mixed key grammars, mismatched brands in the combined view,
158
+ * unsupported filter).
159
+ */
160
+ export declare function getFormattedTenantSalesOverviewAggregatedReporting(reports: IMaterializedTenantSalesOverviewAggregatedReport[], filters?: IFormattedSalesOverviewFilters | null, separate_view_per_tenant?: boolean): [IFormattedSalesOverviewPageData[], null] | null;