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