@managesome/eposmatic-toolkit 0.4.3 → 0.4.5

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 (48) hide show
  1. package/esm/helpers/materialized-reports/index.js +1 -0
  2. package/esm/helpers/materialized-reports/materialized-reports-read-helpers.js +96 -22
  3. package/esm/helpers/materialized-reports/materialized-reports-scope-group-helpers.js +281 -0
  4. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +126 -7
  5. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +47 -1
  6. package/esm/helpers/order/generate-order.js +11 -0
  7. package/esm/helpers/store/common-order-actions.js +7 -3
  8. package/esm/helpers/types/materialized-reports-apis.js +1 -1
  9. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +20 -26
  10. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  11. package/lib/helpers/materialized-reports/index.js +1 -0
  12. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.d.ts +50 -21
  13. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.js +96 -21
  14. package/lib/helpers/materialized-reports/materialized-reports-scope-group-helpers.d.ts +58 -0
  15. package/lib/helpers/materialized-reports/materialized-reports-scope-group-helpers.js +286 -0
  16. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +24 -0
  17. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +127 -7
  18. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +47 -1
  19. package/lib/helpers/order/generate-order.d.ts +2 -0
  20. package/lib/helpers/order/generate-order.js +13 -0
  21. package/lib/helpers/store/common-order-actions.js +7 -3
  22. package/lib/helpers/types/materialized-reports-apis.d.ts +115 -25
  23. package/lib/helpers/types/materialized-reports-apis.js +1 -0
  24. package/lib/schemas/models/internal_invoices.d.ts +3 -3
  25. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +26 -34
  26. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +20 -26
  27. package/lib/schemas/models/orders.d.ts +692 -692
  28. package/lib/schemas/models/tenant_purchase_orders.d.ts +90 -90
  29. package/lib/schemas/models/tenants.d.ts +9 -9
  30. package/lib/schemas/models/warehouse_communications.d.ts +3 -3
  31. package/lib/schemas/models/warehouse_internal_movements.d.ts +48 -48
  32. package/lib/schemas/models/warehouse_purchase_order_rfqs.d.ts +63 -63
  33. package/lib/schemas/models/warehouse_purchase_orders.d.ts +96 -96
  34. package/lib/schemas/models/warehouse_sale_invoices.d.ts +3 -3
  35. package/lib/schemas/models/warehouse_sale_order_rfqs.d.ts +69 -69
  36. package/lib/schemas/models/warehouse_sale_orders.d.ts +45 -45
  37. package/lib/schemas/models/warehouses.d.ts +6 -6
  38. package/lib/tests/materialized-reports/materialized-reports-read-helpers.test.d.ts +1 -0
  39. package/lib/tests/materialized-reports/materialized-reports-read-helpers.test.js +100 -0
  40. package/lib/tests/materialized-reports/materialized-reports-scope-group-helpers.test.d.ts +1 -0
  41. package/lib/tests/materialized-reports/materialized-reports-scope-group-helpers.test.js +275 -0
  42. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +11 -0
  43. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.d.ts +1 -0
  44. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +143 -0
  45. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +22 -0
  46. package/lib/tests/num-of-guests-limit.test.d.ts +1 -0
  47. package/lib/tests/num-of-guests-limit.test.js +76 -0
  48. package/package.json +1 -1
@@ -0,0 +1,286 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MATERIALIZED_REPORT_WINDOW_KIND = void 0;
4
+ exports.compactMaterializedReportDayKeys = compactMaterializedReportDayKeys;
5
+ exports.buildMaterializedReportScopeGroups = buildMaterializedReportScopeGroups;
6
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
7
+ const materialized_reports_read_helpers_1 = require("./materialized-reports-read-helpers");
8
+ /**
9
+ * Smart scope-group compiler for materialized-report reads — turns a
10
+ * selection into the FEWEST exact-scope groups the read needs
11
+ * (`IGetMaterializedReportScopeGroup[]`, the `scope_groups` body field):
12
+ *
13
+ * - **compaction**: a contiguous day set is folded into the largest EXACT
14
+ * periods (year → semester → quarter → month → week) before falling back
15
+ * to `localDate` values — e.g. Sep 1–30 becomes ONE `localMonth: ['2026-09']`
16
+ * instead of 30 day values (one document instead of 30);
17
+ * - **recurring window**: the same hours on every selected day → a single
18
+ * `localHour` group (the dedicated time-of-day-window read);
19
+ * - **span window**: from `x:00` on the first day CONTINUOUSLY through
20
+ * `y:00` on the last day — boundary days carry only their partial hour
21
+ * labels (business-day continuous: the start day runs to its 06:00
22
+ * boundary including the post-midnight tail, the end day starts at 06:00),
23
+ * the full days in between compact through the same period logic. What the
24
+ * span does NOT read (absent documents) counts as zero, and groups NEVER
25
+ * overlap — the backend simply unions them.
26
+ *
27
+ * `compactMaterializedReportDayKeys` is exported for direct testing.
28
+ *
29
+ * Returns `null` (never throws) for malformed input — `null` means the
30
+ * caller passed invalid data.
31
+ */
32
+ /** Window refinement kinds (see the module docblock). */
33
+ exports.MATERIALIZED_REPORT_WINDOW_KIND = {
34
+ RECURRING: 'RECURRING',
35
+ SPAN: 'SPAN',
36
+ };
37
+ /* ------------------------------------------------------------------------ */
38
+ /* Date-key math (UTC — keys are timezone-less) */
39
+ /* ------------------------------------------------------------------------ */
40
+ const KEY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
41
+ const keyToDate = (key) => {
42
+ if (typeof key !== 'string' || !KEY_PATTERN.test(key))
43
+ return null;
44
+ const [year, month, day] = key.split('-').map(Number);
45
+ const date = new Date(Date.UTC(year, month - 1, day));
46
+ // reject impossible dates (e.g. 2026-02-30)
47
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
48
+ return null;
49
+ }
50
+ return date;
51
+ };
52
+ const dateToKey = (date) => `${date.getUTCFullYear()}-${`${date.getUTCMonth() + 1}`.padStart(2, '0')}-${`${date.getUTCDate()}`.padStart(2, '0')}`;
53
+ const addDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
54
+ const DAY_MS = 86400000;
55
+ /** Whole days from `from` to `to` (negative when `to` precedes `from`). */
56
+ const daysBetween = (from, to) => Math.round((to.getTime() - from.getTime()) / DAY_MS);
57
+ /** Sunday-based week start (the `localWeek` bucket identity). */
58
+ const weekStartOf = (date) => addDays(date, -date.getUTCDay());
59
+ /**
60
+ * Periods that START exactly on `date`, largest first: year → semester →
61
+ * quarter → month → week (Sunday-based). Only exact starts are candidates —
62
+ * a run can only compact at its boundaries.
63
+ */
64
+ const periodCandidatesAt = (date) => {
65
+ const year = date.getUTCFullYear();
66
+ const month = date.getUTCMonth() + 1;
67
+ const day = date.getUTCDate();
68
+ const candidates = [];
69
+ const span = (startMonth, months) => {
70
+ const start = new Date(Date.UTC(year, startMonth - 1, 1));
71
+ const end = addDays(new Date(Date.UTC(year, startMonth - 1 + months, 1)), -1);
72
+ return { startKey: dateToKey(start), endKey: dateToKey(end) };
73
+ };
74
+ if (month === 1 && day === 1) {
75
+ const { startKey, endKey } = span(1, 12);
76
+ candidates.push({ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR, label: `${year}`, startKey, endKey });
77
+ }
78
+ if ((month === 1 || month === 7) && day === 1) {
79
+ const { startKey, endKey } = span(month, 6);
80
+ candidates.push({
81
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
82
+ label: `${year}-S${month === 1 ? 1 : 2}`,
83
+ startKey,
84
+ endKey,
85
+ });
86
+ }
87
+ if ([1, 4, 7, 10].includes(month) && day === 1) {
88
+ const { startKey, endKey } = span(month, 3);
89
+ candidates.push({
90
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
91
+ label: `${year}-Q${Math.floor((month - 1) / 3) + 1}`,
92
+ startKey,
93
+ endKey,
94
+ });
95
+ }
96
+ if (day === 1) {
97
+ const { startKey, endKey } = span(month, 1);
98
+ candidates.push({
99
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
100
+ label: `${year}-${`${month}`.padStart(2, '0')}`,
101
+ startKey,
102
+ endKey,
103
+ });
104
+ }
105
+ if (date.getUTCDay() === 0) {
106
+ const startKey = dateToKey(date);
107
+ const endKey = dateToKey(addDays(date, 6));
108
+ candidates.push({ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, label: startKey, startKey, endKey });
109
+ }
110
+ return candidates;
111
+ };
112
+ /* ------------------------------------------------------------------------ */
113
+ /* Compaction */
114
+ /* ------------------------------------------------------------------------ */
115
+ const GROUP_ORDER = [
116
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
117
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
118
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
119
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
120
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
121
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
122
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
123
+ ];
124
+ /** Ordered, deduped, non-empty groups from a context → values map. */
125
+ const toGroups = (values) => {
126
+ const groups = [];
127
+ for (const scope_context of GROUP_ORDER) {
128
+ const set = values.get(scope_context);
129
+ if (set != null && set.size > 0) {
130
+ groups.push({ scope_context, scope_field: [...set].sort() });
131
+ }
132
+ }
133
+ return groups;
134
+ };
135
+ const addValue = (values, scope_context, value) => {
136
+ const set = values.get(scope_context) ?? new Set();
137
+ set.add(value);
138
+ values.set(scope_context, set);
139
+ };
140
+ /**
141
+ * Folds a contiguous day set into the largest EXACT periods (year →
142
+ * semester → quarter → month → week) + `localDate` leftovers — never
143
+ * partial coverage: a period compacts only when the WHOLE period is inside
144
+ * a contiguous run. Returns `null` for malformed/empty input.
145
+ */
146
+ function compactMaterializedReportDayKeys(days) {
147
+ if (!Array.isArray(days) || days.length === 0)
148
+ return null;
149
+ const dates = [];
150
+ for (const day of days) {
151
+ const date = keyToDate(day);
152
+ if (date == null)
153
+ return null;
154
+ dates.push(date);
155
+ }
156
+ dates.sort((a, b) => a.getTime() - b.getTime());
157
+ const values = new Map();
158
+ let index = 0;
159
+ while (index < dates.length) {
160
+ // contiguous run [runStart..runEnd]
161
+ const runStart = dates[index];
162
+ let runEnd = runStart;
163
+ let next = index + 1;
164
+ while (next < dates.length && daysBetween(runEnd, dates[next]) === 1) {
165
+ runEnd = dates[next];
166
+ next += 1;
167
+ }
168
+ let cursor = runStart;
169
+ while (cursor.getTime() <= runEnd.getTime()) {
170
+ const candidate = periodCandidatesAt(cursor).find((entry) => keyToDate(entry.endKey).getTime() <= runEnd.getTime());
171
+ if (candidate != null) {
172
+ addValue(values, candidate.scope_context, candidate.label);
173
+ cursor = addDays(keyToDate(candidate.endKey), 1);
174
+ }
175
+ else {
176
+ addValue(values, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, dateToKey(cursor));
177
+ cursor = addDays(cursor, 1);
178
+ }
179
+ }
180
+ index = next;
181
+ }
182
+ return toGroups(values);
183
+ }
184
+ /* ------------------------------------------------------------------------ */
185
+ /* Scope groups */
186
+ /* ------------------------------------------------------------------------ */
187
+ const isValidHour = (hour, max) => Number.isInteger(hour) && hour >= 0 && hour <= max;
188
+ /**
189
+ * Builds the read's scope groups from a selection spec (see the module
190
+ * docblock). Returns `null` for malformed input or an unservable window.
191
+ */
192
+ function buildMaterializedReportScopeGroups(spec) {
193
+ if (spec == null)
194
+ return null;
195
+ const { days, window } = spec;
196
+ if (!Array.isArray(days) || days.length === 0)
197
+ return null;
198
+ const dates = [];
199
+ for (const day of days) {
200
+ const date = keyToDate(day);
201
+ if (date == null)
202
+ return null;
203
+ dates.push(date);
204
+ }
205
+ dates.sort((a, b) => a.getTime() - b.getTime());
206
+ const dayKeys = [...new Set(dates.map(dateToKey))];
207
+ const uniqueDates = dayKeys.map((key) => keyToDate(key));
208
+ // A SPAN window reads the CONTINUOUS interval first-day → last-day — a day
209
+ // set with gaps would silently pull the gap days in as full middle days.
210
+ if (window != null && window.kind === exports.MATERIALIZED_REPORT_WINDOW_KIND.SPAN) {
211
+ for (let index = 1; index < uniqueDates.length; index += 1) {
212
+ if (daysBetween(uniqueDates[index - 1], uniqueDates[index]) !== 1) {
213
+ return null;
214
+ }
215
+ }
216
+ }
217
+ // No window → compaction only.
218
+ if (window == null) {
219
+ return compactMaterializedReportDayKeys(dayKeys);
220
+ }
221
+ const { fromHour, toHour, kind } = window;
222
+ if (!isValidHour(fromHour, 23) || !isValidHour(toHour, 23))
223
+ return null;
224
+ // Recurring: the same hours on every selected day.
225
+ if (kind === exports.MATERIALIZED_REPORT_WINDOW_KIND.RECURRING) {
226
+ const labels = (0, materialized_reports_read_helpers_1.getMaterializedHourWindowScopeFields)(dayKeys, fromHour, toHour);
227
+ return labels == null ? null : [{ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: labels }];
228
+ }
229
+ // Span (business-day continuous).
230
+ const startDate = uniqueDates[0];
231
+ const endDate = uniqueDates[uniqueDates.length - 1];
232
+ const x = fromHour;
233
+ const y = toHour;
234
+ // Single calendar day, overnight window (e.g. 18:00 → 2:00): one business
235
+ // day covers it whole.
236
+ if (daysBetween(startDate, endDate) === 0 && x >= 6 && y <= 6) {
237
+ if (x === 6 && y === 6) {
238
+ return compactMaterializedReportDayKeys([dateToKey(startDate)]);
239
+ }
240
+ const labels = (0, materialized_reports_read_helpers_1.getMaterializedHourWindowScopeFields)([dateToKey(startDate)], x, y);
241
+ return labels == null ? null : [{ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: labels }];
242
+ }
243
+ // Boundary business days: a start before 06:00 belongs to the previous
244
+ // business day's tail; an end at/before 06:00 ends the previous business
245
+ // day.
246
+ const startBus = x >= 6 ? startDate : addDays(startDate, -1);
247
+ const endBus = y > 6 ? endDate : addDays(endDate, -1);
248
+ // One business day hosts both boundaries (e.g. a full day 06:00 → 06:00).
249
+ if (startBus.getTime() === endBus.getTime()) {
250
+ if (x === 6 && y === 6) {
251
+ return compactMaterializedReportDayKeys([dateToKey(startBus)]);
252
+ }
253
+ const labels = (0, materialized_reports_read_helpers_1.getMaterializedHourWindowScopeFields)([dateToKey(startBus)], x, y);
254
+ return labels == null ? null : [{ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: labels }];
255
+ }
256
+ const startLabels = x === 6 ? null : (0, materialized_reports_read_helpers_1.getMaterializedHourWindowScopeFields)([dateToKey(startBus)], x, 6);
257
+ const endLabels = y === 6 ? null : (0, materialized_reports_read_helpers_1.getMaterializedHourWindowScopeFields)([dateToKey(endBus)], 6, y);
258
+ if (x !== 6 && startLabels == null)
259
+ return null;
260
+ if (y !== 6 && endLabels == null)
261
+ return null;
262
+ const values = new Map();
263
+ // Full business days between the boundaries — compacted like any day set
264
+ // (a month-long span middle becomes period values, not day values).
265
+ const firstFullDate = x === 6 ? startBus : addDays(startBus, 1);
266
+ const lastFullDate = y === 6 ? endBus : addDays(endBus, -1);
267
+ if (firstFullDate.getTime() <= lastFullDate.getTime()) {
268
+ const fullDays = [];
269
+ for (let cursor = firstFullDate; cursor.getTime() <= lastFullDate.getTime(); cursor = addDays(cursor, 1)) {
270
+ fullDays.push(dateToKey(cursor));
271
+ }
272
+ const compacted = compactMaterializedReportDayKeys(fullDays);
273
+ if (compacted == null)
274
+ return null;
275
+ for (const group of compacted) {
276
+ for (const value of group.scope_field) {
277
+ addValue(values, group.scope_context, value);
278
+ }
279
+ }
280
+ }
281
+ for (const label of [...(startLabels ?? []), ...(endLabels ?? [])]) {
282
+ addValue(values, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, label);
283
+ }
284
+ const groups = toGroups(values);
285
+ return groups.length === 0 ? null : groups;
286
+ }
@@ -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;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getFormattedTenantSalesOverviewReporting = getFormattedTenantSalesOverviewReporting;
4
+ exports.getFormattedTenantSalesOverviewAggregatedReporting = getFormattedTenantSalesOverviewAggregatedReporting;
4
5
  const constants_1 = require("../../constants");
5
6
  const ENUMS_1 = require("../../constants/ENUMS");
6
7
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
@@ -77,11 +78,10 @@ const matchesFilters = (components, keyFilters, filters) => {
77
78
  }
78
79
  return true;
79
80
  };
80
- /** Drops non-matching keys from a document's metric map (bills included). */
81
- const pruneReportForFilters = (doc, filters) => {
82
- const keyFilters = doc.sale_type_key_filters ?? [];
81
+ /** Drops non-matching keys from a key map (raw documents and aggregated records share this). */
82
+ const pruneMetricsMap = (keyFilters, metrics, filters) => {
83
83
  const kept = {};
84
- for (const [key, metric] of Object.entries(doc.sale_type_metrics ?? {})) {
84
+ for (const [key, metric] of Object.entries(metrics ?? {})) {
85
85
  const components = (0, key_helpers_1.parseMaterializedReportKey)(key);
86
86
  // Unparseable key — cannot be matched; skipping keeps the sums honest
87
87
  // (the write side rejects such keys, so this is defensive only).
@@ -91,6 +91,11 @@ const pruneReportForFilters = (doc, filters) => {
91
91
  continue;
92
92
  kept[key] = metric;
93
93
  }
94
+ return kept;
95
+ };
96
+ /** Drops non-matching keys from a document's metric map (bills included). */
97
+ const pruneReportForFilters = (doc, filters) => {
98
+ const kept = pruneMetricsMap(doc.sale_type_key_filters ?? [], doc.sale_type_metrics, filters);
94
99
  return { ...doc, sale_type_metrics: kept };
95
100
  };
96
101
  /* ------------------------------------------------------------------------ */
@@ -248,6 +253,17 @@ const buildPageDataForDocs = (docs, scopeContext, filters) => {
248
253
  const merged = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)(pruned, { allowTenantMismatch: true });
249
254
  if (merged == null)
250
255
  return null;
256
+ const supportsDayIndex = scopeContext != null && MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext);
257
+ return buildPageDataFromMetrics(merged, tenantIds, supportsDayIndex ? buildWeekdaySection(scopedDocs, filters) : null, scopeContext === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? buildHourlySection(scopedDocs, filters) : null);
258
+ };
259
+ /**
260
+ * Shared page assembly — identical for the raw read (one merged document) and
261
+ * the AGGREGATED read (one pipeline record): every section derives from the
262
+ * pruned key map. The slice-derived sections are inputs: the raw read passes
263
+ * the weekday / hourly grouping of its documents; the aggregated read passes
264
+ * `null` (its response carries no per-scope slices).
265
+ */
266
+ const buildPageDataFromMetrics = (merged, tenantIds, weekday, hourly) => {
251
267
  const keyFilters = merged.sale_type_key_filters ?? [];
252
268
  const summaryRaw = createRawOrderMetric();
253
269
  const collectedRaw = createRawOrderMetric();
@@ -307,7 +323,6 @@ const buildPageDataForDocs = (docs, scopeContext, filters) => {
307
323
  gross_amount: toDecimal(channel.gross_amount),
308
324
  }))
309
325
  .sort((a, b) => b.count - a.count || a.platform.localeCompare(b.platform));
310
- const supportsDayIndex = scopeContext != null && MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext);
311
326
  return {
312
327
  tenant_ids: tenantIds,
313
328
  summary: formatRawOrderMetric(summaryRaw),
@@ -325,8 +340,8 @@ const buildPageDataForDocs = (docs, scopeContext, filters) => {
325
340
  received: { count: receivedRaw.count, amount: toDecimal(receivedRaw.amount) },
326
341
  outstanding_amount: toDecimal(issuedRaw.amount - issuedRaw.settled_amount),
327
342
  },
328
- weekday: supportsDayIndex ? buildWeekdaySection(scopedDocs, filters) : null,
329
- hourly: scopeContext === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? buildHourlySection(scopedDocs, filters) : null,
343
+ weekday,
344
+ hourly,
330
345
  };
331
346
  };
332
347
  /* ------------------------------------------------------------------------ */
@@ -380,3 +395,108 @@ function getFormattedTenantSalesOverviewReporting(docs, filters = null, separate
380
395
  }
381
396
  return [results, null];
382
397
  }
398
+ /* ------------------------------------------------------------------------ */
399
+ /* Aggregated read (pipeline records) */
400
+ /* ------------------------------------------------------------------------ */
401
+ /** Folds a group of aggregated records into ONE combined key-map slice. */
402
+ const mergeAggregatedKeyMetrics = (reports) => {
403
+ const merged = {};
404
+ const TOTAL_SALES = constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES;
405
+ const AMOUNT_COLLECTED = constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED;
406
+ const CREDIT_BILLS = constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS;
407
+ for (const report of reports) {
408
+ for (const [key, metrics] of Object.entries(report.sale_type_metrics ?? {})) {
409
+ const entry = merged[key] ??
410
+ (merged[key] = {
411
+ [TOTAL_SALES]: { orders: createRawOrderMetric(), payments: [] },
412
+ [AMOUNT_COLLECTED]: { orders: createRawOrderMetric() },
413
+ [CREDIT_BILLS]: {
414
+ issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
415
+ received: { count: 0, amount: 0 },
416
+ },
417
+ });
418
+ addRawOrderMetric(entry[TOTAL_SALES].orders, metrics[TOTAL_SALES]?.orders);
419
+ addRawOrderMetric(entry[AMOUNT_COLLECTED].orders, metrics[AMOUNT_COLLECTED]?.orders);
420
+ for (const payment of metrics[TOTAL_SALES]?.payments ?? []) {
421
+ entry[TOTAL_SALES].payments.push(payment);
422
+ }
423
+ entry[CREDIT_BILLS].issued.count += metrics[CREDIT_BILLS]?.issued?.count ?? 0;
424
+ entry[CREDIT_BILLS].issued.amount += metrics[CREDIT_BILLS]?.issued?.amount ?? 0;
425
+ entry[CREDIT_BILLS].issued.settled_count += metrics[CREDIT_BILLS]?.issued?.settled_count ?? 0;
426
+ entry[CREDIT_BILLS].issued.settled_amount += metrics[CREDIT_BILLS]?.issued?.settled_amount ?? 0;
427
+ entry[CREDIT_BILLS].received.count += metrics[CREDIT_BILLS]?.received?.count ?? 0;
428
+ entry[CREDIT_BILLS].received.amount += metrics[CREDIT_BILLS]?.received?.amount ?? 0;
429
+ }
430
+ }
431
+ return {
432
+ sale_type_key_filters: reports[0]?.sale_type_key_filters ?? [],
433
+ sale_type_metrics: merged,
434
+ };
435
+ };
436
+ /**
437
+ * Frontend formatter for the overview response —
438
+ * `IMaterializedTenantSalesOverviewAggregatedReport[]` (one pipeline-computed
439
+ * record per tenant — the shape of every read).
440
+ *
441
+ * Same page-ready output as `getFormattedTenantSalesOverviewReporting`, with
442
+ * the platform / order-status filters applied client-side on the records'
443
+ * preserved key maps (zero refetches). Differences, by construction:
444
+ * - the slice-derived sections are ALWAYS `null`: `weekday` and `hourly`
445
+ * need per-scope documents — the aggregated record has none (most recent
446
+ * period reads must use the raw response if those sections are ever
447
+ * rendered);
448
+ * - an explicit `day_indexes` filter is REJECTED (`null`): the weekday
449
+ * refinement must narrow the request scope (the calendar selection),
450
+ * never the response;
451
+ * - the combined view (default) folds the tenants' records together; with
452
+ * `separate_view_per_tenant: true` each tenant keeps its own entry.
453
+ *
454
+ * Returns `null` (never throws) when the records cannot be formatted
455
+ * together (mixed key grammars, mismatched brands in the combined view,
456
+ * unsupported filter).
457
+ */
458
+ function getFormattedTenantSalesOverviewAggregatedReporting(reports, filters = null, separate_view_per_tenant = false) {
459
+ if (!Array.isArray(reports) || reports.some((report) => report == null)) {
460
+ return null;
461
+ }
462
+ if (filters != null && Array.isArray(filters.day_indexes) && filters.day_indexes.length > 0) {
463
+ return null;
464
+ }
465
+ if (reports.length > 0) {
466
+ const keyFilterSignature = (reports[0].sale_type_key_filters ?? []).join(':');
467
+ for (const report of reports) {
468
+ // The combined view folds the tenants' records together — same guard as
469
+ // the raw merge (`canMergeMaterializedReportsIgnoringTenant`): one brand.
470
+ // Per-tenant views (`separate_view_per_tenant`) never cross brands.
471
+ if (!separate_view_per_tenant && report.brand_id !== reports[0].brand_id)
472
+ return null;
473
+ if ((report.sale_type_key_filters ?? []).join(':') !== keyFilterSignature)
474
+ return null;
475
+ }
476
+ }
477
+ if (reports.length === 0) {
478
+ return [[buildEmptyPageData(null, [])], null];
479
+ }
480
+ const groups = [];
481
+ if (separate_view_per_tenant) {
482
+ const byTenant = new Map();
483
+ for (const report of reports) {
484
+ const group = byTenant.get(report.tenant_id) ?? [];
485
+ group.push(report);
486
+ byTenant.set(report.tenant_id, group);
487
+ }
488
+ for (const tenantId of [...byTenant.keys()].sort()) {
489
+ groups.push(byTenant.get(tenantId));
490
+ }
491
+ }
492
+ else {
493
+ groups.push(reports);
494
+ }
495
+ const results = [];
496
+ for (const group of groups) {
497
+ const merged = mergeAggregatedKeyMetrics(group);
498
+ const pruned = pruneMetricsMap(merged.sale_type_key_filters, merged.sale_type_metrics, filters);
499
+ results.push(buildPageDataFromMetrics({ sale_type_key_filters: merged.sale_type_key_filters, sale_type_metrics: pruned }, uniqueTenantIds(group), null, null));
500
+ }
501
+ return [results, null];
502
+ }
@@ -256,6 +256,50 @@ function finalizeMetrics(metrics) {
256
256
  }
257
257
  return finalized;
258
258
  }
259
+ /** True for a number that is zero (or broken beyond being distinguishable). */
260
+ const isZeroNumber = (value) => !value;
261
+ const isZeroPaymentMetric = (payment) => isZeroNumber(payment.count) &&
262
+ isZeroNumber(payment.gross_amount) &&
263
+ isZeroNumber(payment.amount_due) &&
264
+ isZeroNumber(payment.amount_paid) &&
265
+ isZeroNumber(payment.amount_refunded) &&
266
+ isZeroNumber(payment.card_charges);
267
+ const isZeroOrderReportMetric = (orders) => isZeroNumber(orders.count) &&
268
+ isZeroNumber(orders.gross_amount) &&
269
+ isZeroNumber(orders.discount_amount) &&
270
+ isZeroNumber(orders.discount_by_type.special_discount) &&
271
+ isZeroNumber(orders.discount_by_type.loyalty_discount) &&
272
+ isZeroNumber(orders.discount_by_type.voucher_discount) &&
273
+ isZeroNumber(orders.gst_amount) &&
274
+ isZeroNumber(orders.tax_amount) &&
275
+ isZeroNumber(orders.tip_amount) &&
276
+ isZeroNumber(orders.tax_invoice_provider_charges) &&
277
+ isZeroNumber(orders.delivery_charges);
278
+ /**
279
+ * Reconcile-time cleanup: subtracting a day can zero a key out while leaving
280
+ * it behind — a "zombie" key that would make accumulated period documents
281
+ * diverge from day / hour reads (which simply lose the key). Compile output
282
+ * never carries all-zero keys, so pruning only removes reconcile artifacts.
283
+ * A key whose payments are all zero-valued counts as empty (subtraction can
284
+ * leave zero-count payment entries behind).
285
+ */
286
+ const pruneZeroReportKeys = (metrics) => {
287
+ const pruned = {};
288
+ for (const [key, metric] of Object.entries(metrics)) {
289
+ const totalSales = metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES];
290
+ const amountCollected = metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED];
291
+ const creditBills = metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
292
+ const isZero = isZeroOrderReportMetric(totalSales.orders) &&
293
+ totalSales.payments.every(isZeroPaymentMetric) &&
294
+ isZeroOrderReportMetric(amountCollected.orders) &&
295
+ (amountCollected.payments ?? []).every(isZeroPaymentMetric) &&
296
+ creditBills.issued.bills.length === 0 &&
297
+ creditBills.received.bills.length === 0;
298
+ if (!isZero)
299
+ pruned[key] = metric;
300
+ }
301
+ return pruned;
302
+ };
259
303
  /**
260
304
  * Deep plain-value conversion for mongoose-hydrated values: subdocuments
261
305
  * (`toObject()`), nested `Map`s and document arrays. Plain JSON values are
@@ -877,7 +921,9 @@ function updateMaterializedTenantSalesOverviewReport(existing, updates, options
877
921
  }
878
922
  return {
879
923
  ...existing,
880
- sale_type_metrics: finalizeMetrics(metrics),
924
+ // Reconcile artifacts: a fully-subtracted key is pruned so accumulated
925
+ // period documents keep the same key set as day / hour reads.
926
+ sale_type_metrics: pruneZeroReportKeys(finalizeMetrics(metrics)),
881
927
  // Version metric writes AND ledger-changing received-payment patches (both
882
928
  // append a history row via the caller). No-op patches bump nothing, so
883
929
  // replays stay churn-free.
@@ -1,5 +1,7 @@
1
1
  import Mongoose from 'mongoose';
2
2
  import { IOrder } from '../../schemas';
3
+ export declare const MAX_NUM_OF_GUESTS = 1000;
4
+ export declare function getValidNumOfGuests(num_of_guests?: number | null): number;
3
5
  export declare function generateOrderDineinDetails(dinein_details?: IOrder['dinein_details']): IOrder['dinein_details'];
4
6
  export declare function generateOrderCategories(categories?: IOrder['categories']): IOrder['categories'];
5
7
  export declare function generateOrderOnCreate<T extends IOrder | Partial<IOrder>>(order: T, withIterations?: boolean): T;
@@ -3,12 +3,24 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MAX_NUM_OF_GUESTS = void 0;
7
+ exports.getValidNumOfGuests = getValidNumOfGuests;
6
8
  exports.generateOrderDineinDetails = generateOrderDineinDetails;
7
9
  exports.generateOrderCategories = generateOrderCategories;
8
10
  exports.generateOrderOnCreate = generateOrderOnCreate;
9
11
  exports.generateOrderOnUpdate = generateOrderOnUpdate;
10
12
  const mongoose_1 = __importDefault(require("mongoose"));
11
13
  const constants_1 = require("../../constants");
14
+ // num_of_guests is persisted as a BSON int32 (orders collection validator: bsonType 'int', minimum 1).
15
+ // Corrupt client values (e.g. 3257330333) serialize as a double and make the whole order write fail
16
+ // document validation — clamp to a sane range on every normalization pass.
17
+ exports.MAX_NUM_OF_GUESTS = 1000;
18
+ function getValidNumOfGuests(num_of_guests) {
19
+ const numOfGuests = Number(num_of_guests);
20
+ if (!Number.isFinite(numOfGuests) || numOfGuests < 1)
21
+ return 1;
22
+ return Math.min(Math.floor(numOfGuests), exports.MAX_NUM_OF_GUESTS);
23
+ }
12
24
  function generateOrderDineinDetails(dinein_details) {
13
25
  if (!dinein_details)
14
26
  return null;
@@ -16,6 +28,7 @@ function generateOrderDineinDetails(dinein_details) {
16
28
  ...dinein_details,
17
29
  floor_id: new mongoose_1.default.Types.ObjectId(dinein_details.floor_id),
18
30
  table_id: new mongoose_1.default.Types.ObjectId(dinein_details.table_id),
31
+ num_of_guests: getValidNumOfGuests(dinein_details.num_of_guests),
19
32
  reservation_time: new Date(dinein_details.reservation_time),
20
33
  start_time: new Date(dinein_details.start_time),
21
34
  };
@@ -24,6 +24,7 @@ exports.getVoidItemsWithReason = getVoidItemsWithReason;
24
24
  exports.getSplitOrdersFromOrder = getSplitOrdersFromOrder;
25
25
  const bson_objectid_1 = __importDefault(require("bson-objectid"));
26
26
  const constants_1 = require("../../constants");
27
+ const generate_order_1 = require("../order/generate-order");
27
28
  const utils_1 = require("../utils");
28
29
  const cart_actions_1 = require("./cart-actions");
29
30
  /* ======================>Order Object<====================== */
@@ -201,7 +202,7 @@ function getOrderWithPrice(order, toCents) {
201
202
  ? {
202
203
  dinein_details: {
203
204
  ...order.dinein_details,
204
- num_of_guests: order.dinein_details.num_of_guests || 1,
205
+ num_of_guests: (0, generate_order_1.getValidNumOfGuests)(order.dinein_details.num_of_guests),
205
206
  },
206
207
  }
207
208
  : {}),
@@ -259,9 +260,12 @@ function getCommonOptionalBoolFields(order, partial) {
259
260
  }
260
261
  function getCommonOptionalNullFields(order, partial) {
261
262
  const defaultValue = partial ? undefined : null;
263
+ const dineinDetails = order['dinein_details'];
262
264
  return {
263
265
  delivery_details: order['delivery_details'] || defaultValue,
264
- dinein_details: order['dinein_details'] || defaultValue,
266
+ dinein_details: dineinDetails != null
267
+ ? { ...dineinDetails, num_of_guests: (0, generate_order_1.getValidNumOfGuests)(dineinDetails.num_of_guests) }
268
+ : defaultValue,
265
269
  takeaway_details: order['takeaway_details'] || defaultValue,
266
270
  staff_details: order['staff_details'] || defaultValue,
267
271
  order_taker_details: order['order_taker_details'] || defaultValue,
@@ -533,7 +537,7 @@ function syncDineinCoursesOnSplit(dinein_details, swapedItemIdsMap, totalChecks,
533
537
  }
534
538
  const result = {
535
539
  ...dinein_details,
536
- num_of_guests,
540
+ num_of_guests: (0, generate_order_1.getValidNumOfGuests)(num_of_guests),
537
541
  courses: newCourses,
538
542
  };
539
543
  return result;