@managesome/eposmatic-toolkit 0.4.2 → 0.4.4

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 (20) hide show
  1. package/esm/helpers/materialized-reports/index.js +2 -0
  2. package/esm/helpers/materialized-reports/materialized-reports-read-helpers.js +152 -0
  3. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +379 -0
  4. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +16 -2
  5. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +20 -26
  6. package/lib/helpers/materialized-reports/index.d.ts +2 -0
  7. package/lib/helpers/materialized-reports/index.js +2 -0
  8. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.d.ts +79 -0
  9. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.js +159 -0
  10. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +136 -0
  11. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +382 -0
  12. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +4 -1
  13. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +16 -2
  14. package/lib/helpers/types/materialized-reports-apis.d.ts +3 -3
  15. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +17 -25
  16. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +20 -26
  17. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +11 -0
  18. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.d.ts +1 -0
  19. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +352 -0
  20. package/package.json +1 -1
@@ -1,5 +1,7 @@
1
1
  export * from './key-helpers';
2
+ export * from './materialized-reports-read-helpers';
2
3
  export * from './materialized-tenant-reports-iterations-helpers';
3
4
  export * from './scope-helpers';
4
5
  export * from './tenant-sales-overview-close-day-helpers';
6
+ export * from './tenant-sales-overview-formatter';
5
7
  export * from './tenant-sales-overview-helpers';
@@ -0,0 +1,152 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { getMaterializedHourScopeField, parseMaterializedLocalDate } from './scope-helpers';
3
+ /**
4
+ * Read-side helpers for materialized-report documents — the frontend-facing
5
+ * half of the query story (see `MATERIALIZED_REPORTS.md` "Time scopes").
6
+ *
7
+ * The ops-service read API takes `{ scope_context, scope_field | from/to }`:
8
+ * - contiguous selections go through `from`/`to` directly (callers can use
9
+ * `getMaterializedScopeSpan` / `getMaterializedHourScopeSpan` to derive the
10
+ * span of a set of keys);
11
+ * - discrete selections fetch the min..max SPAN and keep the exact keys with
12
+ * `filterMaterializedTenantSalesOverviewReportsByScopeFields`;
13
+ * - recurring hour windows (e.g. 6–8pm on every day of a range) expand to the
14
+ * exact hour labels with `getMaterializedHourWindowScopeFields` (span-fetch
15
+ * the full days first, then filter to the labels).
16
+ *
17
+ * Validation convention: helpers return `null` instead of throwing — `null`
18
+ * means the caller passed invalid data.
19
+ */
20
+ /**
21
+ * Chronological business-hour index of an hour bucket: a business day's hour
22
+ * sequence is `06…23, 00…05`, so index = `(hour + 18) % 24` (06 → 0 … 05 →
23
+ * 23). NEVER order hour buckets lexicographically — `'D 00'` sorts before
24
+ * `'D 06'` yet happens ~18 hours later.
25
+ *
26
+ * Returns `null` (never throws) for a non-integer / out-of-range hour.
27
+ */
28
+ export function getMaterializedBusinessHourIndex(hour) {
29
+ if (!Number.isInteger(hour) || hour < 0 || hour > 23) {
30
+ return null;
31
+ }
32
+ return (hour + 18) % 24;
33
+ }
34
+ /**
35
+ * Expands a RECURRING daily hour window into the exact `localHour` scope
36
+ * labels (`$in`-style reads): the same business hours on every day of the
37
+ * list, e.g. `4pm–8pm` on June 1–2 →
38
+ * `['2026-06-01 16', '2026-06-01 17', '2026-06-01 18', '2026-06-01 19', …]`.
39
+ *
40
+ * Semantics (see `MATERIALIZED_REPORTS.md`): whole-hour buckets, the window
41
+ * END is the exclusive hour boundary — `16 → 20` = buckets `16, 17, 18, 19`;
42
+ * windows may cross midnight WITHIN one business day — `22 → 2` = buckets
43
+ * `22, 23` (evening) plus `00, 01` (post-midnight), all labelled with the SAME
44
+ * business day. Windows must stay inside one business day: a walk crossing the
45
+ * 06:00 business-morning boundary (e.g. `4 → 8`) is rejected (`null`) rather
46
+ * than silently spanning two label days. `0 → 24` requests the full business
47
+ * day (buckets `00`–`23` of the label day).
48
+ *
49
+ * Returns `null` (never throws) for malformed days or hours; the result is
50
+ * ordered by day, then by the window's own hour order.
51
+ */
52
+ export function getMaterializedHourWindowScopeFields(businessDays, fromHour, toHour) {
53
+ if (!Array.isArray(businessDays) || businessDays.length === 0) {
54
+ return null;
55
+ }
56
+ if (!Number.isInteger(fromHour) || fromHour < 0 || fromHour > 23) {
57
+ return null;
58
+ }
59
+ if (!Number.isInteger(toHour) || toHour < 0 || toHour > 24) {
60
+ return null;
61
+ }
62
+ let hourCount;
63
+ if (toHour === 24) {
64
+ if (fromHour !== 0)
65
+ return null;
66
+ hourCount = 24;
67
+ }
68
+ else {
69
+ hourCount = (((toHour - fromHour) % 24) + 24) % 24;
70
+ if (hourCount === 0)
71
+ return null; // ambiguous empty window — caller must be explicit
72
+ }
73
+ // Reject walks crossing the 06:00 business-morning boundary — those span two
74
+ // label days and cannot be expressed with same-day labels.
75
+ if (hourCount < 24) {
76
+ const startPosition = getMaterializedBusinessHourIndex(fromHour);
77
+ if (startPosition == null || startPosition + hourCount > 24) {
78
+ return null;
79
+ }
80
+ }
81
+ const hours = Array.from({ length: hourCount }, (_, index) => (fromHour + index) % 24);
82
+ const labels = [];
83
+ for (const businessDay of businessDays) {
84
+ if (parseMaterializedLocalDate(businessDay) == null) {
85
+ return null;
86
+ }
87
+ for (const hour of hours) {
88
+ const label = getMaterializedHourScopeField(businessDay, hour);
89
+ if (label == null)
90
+ return null;
91
+ labels.push(label);
92
+ }
93
+ }
94
+ return labels;
95
+ }
96
+ /**
97
+ * Full-day span of a list of business days for `localHour` reads: the
98
+ * inclusive `{ from: '<first> 00', to: '<last> 23' }` range covers ALL 24
99
+ * hour buckets of every label day in between (a label day's buckets are
100
+ * `'D 00'`…`'D 23'`, spanning the post-midnight hours too). Filter the
101
+ * fetched documents afterwards with `getMaterializedHourWindowScopeFields` /
102
+ * `filterMaterializedTenantSalesOverviewReportsByScopeFields`.
103
+ *
104
+ * Returns `null` (never throws) for a malformed list.
105
+ */
106
+ export function getMaterializedHourScopeSpan(businessDays) {
107
+ if (!Array.isArray(businessDays) || businessDays.length === 0) {
108
+ return null;
109
+ }
110
+ for (const businessDay of businessDays) {
111
+ if (parseMaterializedLocalDate(businessDay) == null) {
112
+ return null;
113
+ }
114
+ }
115
+ const sorted = [...businessDays].sort();
116
+ return { from: `${sorted[0]} 00`, to: `${sorted[sorted.length - 1]} 23` };
117
+ }
118
+ /**
119
+ * Inclusive min..max span of exact non-hour scope values — the fetch range
120
+ * for discrete selections (all non-hour scope fields are fixed-width, so
121
+ * lexicographic order equals chronological order). Returns `null` (never
122
+ * throws) for the hour scope (use `getMaterializedHourScopeSpan`) or a
123
+ * malformed list.
124
+ */
125
+ export function getMaterializedScopeSpan(scope_context, scopeFields) {
126
+ if (scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
127
+ return null;
128
+ }
129
+ if (!Array.isArray(scopeFields) || scopeFields.length === 0) {
130
+ return null;
131
+ }
132
+ for (const scopeField of scopeFields) {
133
+ if (typeof scopeField !== 'string' || scopeField.length === 0) {
134
+ return null;
135
+ }
136
+ }
137
+ const sorted = [...scopeFields].sort();
138
+ return { from: sorted[0], to: sorted[sorted.length - 1] };
139
+ }
140
+ /**
141
+ * Keeps only the documents whose `scope_field` is one of the requested keys —
142
+ * the client-side refinement for discrete selections fetched as a span.
143
+ * Returns `null` (never throws) for malformed input; unknown keys simply match
144
+ * nothing (absence = zero).
145
+ */
146
+ export function filterMaterializedTenantSalesOverviewReportsByScopeFields(docs, scopeFields) {
147
+ if (!Array.isArray(docs) || !Array.isArray(scopeFields)) {
148
+ return null;
149
+ }
150
+ const wanted = new Set(scopeFields);
151
+ return docs.filter((doc) => doc != null && wanted.has(doc.scope_field));
152
+ }
@@ -0,0 +1,379 @@
1
+ import { ORDER_STATUS_ENUM, PAYMENT_TYPE_ENUM, PLATFORM_NAMES, REPORT_SALE_TYPE_ENUM } from '../../constants';
2
+ import { ALL_DAY_INDEX } from '../../constants/ENUMS';
3
+ import { MATERIALIZED_CREDIT_SETTLEMENT_PAYMENT_TYPE, MATERIALIZED_REPORT_KEY_FILTER_ENUM, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX, } from '../../constants/MATERIALIZED_REPORTS';
4
+ import { convertPriceFromCents } from '../utils/price-conversion';
5
+ import { parseMaterializedReportKey } from './key-helpers';
6
+ import { getMaterializedBusinessHourIndex } from './materialized-reports-read-helpers';
7
+ import { normalizeMaterializedPaymentType, sumMaterializedTenantSalesOverviewReports, } from './tenant-sales-overview-helpers';
8
+ /* ------------------------------------------------------------------------ */
9
+ /* Raw (cents) accumulators */
10
+ /* ------------------------------------------------------------------------ */
11
+ const createRawOrderMetric = () => ({
12
+ count: 0,
13
+ gross_amount: 0,
14
+ discount_amount: 0,
15
+ discount_by_type: { special_discount: 0, loyalty_discount: 0, voucher_discount: 0 },
16
+ gst_amount: 0,
17
+ tax_amount: 0,
18
+ tip_amount: 0,
19
+ tax_invoice_provider_charges: 0,
20
+ delivery_charges: 0,
21
+ });
22
+ const addRawOrderMetric = (target, source) => {
23
+ if (source == null)
24
+ return;
25
+ target.count += source.count ?? 0;
26
+ target.gross_amount += source.gross_amount ?? 0;
27
+ target.discount_amount += source.discount_amount ?? 0;
28
+ target.discount_by_type.special_discount += source.discount_by_type?.special_discount ?? 0;
29
+ target.discount_by_type.loyalty_discount += source.discount_by_type?.loyalty_discount ?? 0;
30
+ target.discount_by_type.voucher_discount += source.discount_by_type?.voucher_discount ?? 0;
31
+ target.gst_amount += source.gst_amount ?? 0;
32
+ target.tax_amount += source.tax_amount ?? 0;
33
+ target.tip_amount += source.tip_amount ?? 0;
34
+ target.tax_invoice_provider_charges += source.tax_invoice_provider_charges ?? 0;
35
+ target.delivery_charges += source.delivery_charges ?? 0;
36
+ };
37
+ const toDecimal = (cents) => convertPriceFromCents(cents ?? 0);
38
+ const formatRawOrderMetric = (raw) => ({
39
+ count: raw.count,
40
+ gross_amount: toDecimal(raw.gross_amount),
41
+ discount_amount: toDecimal(raw.discount_amount),
42
+ discount_by_type: {
43
+ special_discount: toDecimal(raw.discount_by_type.special_discount),
44
+ loyalty_discount: toDecimal(raw.discount_by_type.loyalty_discount),
45
+ voucher_discount: toDecimal(raw.discount_by_type.voucher_discount),
46
+ },
47
+ gst_amount: toDecimal(raw.gst_amount),
48
+ tax_amount: toDecimal(raw.tax_amount),
49
+ tip_amount: toDecimal(raw.tip_amount),
50
+ tax_invoice_provider_charges: toDecimal(raw.tax_invoice_provider_charges),
51
+ delivery_charges: toDecimal(raw.delivery_charges),
52
+ });
53
+ /* ------------------------------------------------------------------------ */
54
+ /* Key-map filtering */
55
+ /* ------------------------------------------------------------------------ */
56
+ const getKeyDimValue = (components, keyFilters, dim) => {
57
+ const index = keyFilters.indexOf(dim);
58
+ return index >= 0 ? (components[index] ?? null) : null;
59
+ };
60
+ const matchesFilters = (components, keyFilters, filters) => {
61
+ if (filters == null)
62
+ return true;
63
+ const platforms = filters.platforms;
64
+ if (Array.isArray(platforms) && platforms.length > 0) {
65
+ const platform = getKeyDimValue(components, keyFilters, MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM);
66
+ if (platform == null || !platforms.includes(platform))
67
+ return false;
68
+ }
69
+ const orderStatuses = filters.order_statuses;
70
+ if (Array.isArray(orderStatuses) && orderStatuses.length > 0) {
71
+ const status = getKeyDimValue(components, keyFilters, MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS);
72
+ if (status == null || !orderStatuses.includes(status))
73
+ return false;
74
+ }
75
+ return true;
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 ?? [];
80
+ const kept = {};
81
+ for (const [key, metric] of Object.entries(doc.sale_type_metrics ?? {})) {
82
+ const components = parseMaterializedReportKey(key);
83
+ // Unparseable key — cannot be matched; skipping keeps the sums honest
84
+ // (the write side rejects such keys, so this is defensive only).
85
+ if (components == null)
86
+ continue;
87
+ if (!matchesFilters(components, keyFilters, filters))
88
+ continue;
89
+ kept[key] = metric;
90
+ }
91
+ return { ...doc, sale_type_metrics: kept };
92
+ };
93
+ /* ------------------------------------------------------------------------ */
94
+ /* Section extraction */
95
+ /* ------------------------------------------------------------------------ */
96
+ const isCancelledKey = (components, keyFilters) => getKeyDimValue(components, keyFilters, MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS) ===
97
+ ORDER_STATUS_ENUM.CANCELLED;
98
+ /** Non-cancelled `TOTAL_SALES` aggregate of a merged document (cents). */
99
+ const extractNonCancelledTotalSales = (merged) => {
100
+ const raw = createRawOrderMetric();
101
+ const keyFilters = merged.sale_type_key_filters ?? [];
102
+ for (const [key, entry] of Object.entries(merged.sale_type_metrics ?? {})) {
103
+ const components = parseMaterializedReportKey(key);
104
+ if (components == null || isCancelledKey(components, keyFilters))
105
+ continue;
106
+ addRawOrderMetric(raw, entry[REPORT_SALE_TYPE_ENUM.TOTAL_SALES]?.orders);
107
+ }
108
+ return raw;
109
+ };
110
+ const addRawPayment = (map, payment) => {
111
+ const paymentType = normalizeMaterializedPaymentType(payment.payment_type);
112
+ const entry = map[paymentType] ??
113
+ (map[paymentType] = {
114
+ payment_type: paymentType,
115
+ count: 0,
116
+ gross_amount: 0,
117
+ amount_due: 0,
118
+ amount_paid: 0,
119
+ amount_refunded: 0,
120
+ card_charges: 0,
121
+ });
122
+ entry.count += payment.count ?? 0;
123
+ entry.gross_amount += payment.gross_amount ?? 0;
124
+ entry.amount_due += payment.amount_due ?? 0;
125
+ entry.amount_paid += payment.amount_paid ?? 0;
126
+ entry.amount_refunded += payment.amount_refunded ?? 0;
127
+ entry.card_charges += payment.card_charges ?? 0;
128
+ };
129
+ const formatRawPayment = (raw, derived) => ({
130
+ payment_type: raw.payment_type,
131
+ count: raw.count,
132
+ gross_amount: toDecimal(raw.gross_amount),
133
+ amount_due: toDecimal(raw.amount_due),
134
+ amount_paid: toDecimal(raw.amount_paid),
135
+ amount_refunded: toDecimal(raw.amount_refunded),
136
+ card_charges: toDecimal(raw.card_charges),
137
+ derived,
138
+ });
139
+ /** UNPAID first, then COMPLIMENTARY, then count desc / name asc. */
140
+ const orderPayments = (payments) => {
141
+ const unpaid = payments.filter((payment) => payment.payment_type === PAYMENT_TYPE_ENUM.UNPAID);
142
+ const complimentary = payments.filter((payment) => payment.payment_type === PAYMENT_TYPE_ENUM.COMPLIMENTARY);
143
+ const rest = payments
144
+ .filter((payment) => payment.payment_type !== PAYMENT_TYPE_ENUM.UNPAID && payment.payment_type !== PAYMENT_TYPE_ENUM.COMPLIMENTARY)
145
+ .sort((a, b) => b.count - a.count || a.payment_type.localeCompare(b.payment_type));
146
+ return [...unpaid, ...complimentary, ...rest];
147
+ };
148
+ const splitPlatformName = (platform) => {
149
+ const name = PLATFORM_NAMES[platform] ?? platform;
150
+ const [orderFrom, ...orderTypeParts] = name.split(' ');
151
+ return { order_from: orderFrom, order_type: orderTypeParts.join(' ') };
152
+ };
153
+ /* ------------------------------------------------------------------------ */
154
+ /* Page building */
155
+ /* ------------------------------------------------------------------------ */
156
+ const uniqueTenantIds = (docs) => {
157
+ const ids = new Set();
158
+ for (const doc of docs) {
159
+ if (typeof doc.tenant_id === 'string' && doc.tenant_id.length > 0)
160
+ ids.add(doc.tenant_id);
161
+ }
162
+ return [...ids].sort();
163
+ };
164
+ const buildEmptyOrderMetric = () => formatRawOrderMetric(createRawOrderMetric());
165
+ const buildEmptyPageData = (scopeContext, tenantIds) => ({
166
+ tenant_ids: tenantIds,
167
+ summary: buildEmptyOrderMetric(),
168
+ amount_collected: buildEmptyOrderMetric(),
169
+ cancelled: buildEmptyOrderMetric(),
170
+ payments: [],
171
+ channels: [],
172
+ credit_bills: {
173
+ issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
174
+ received: { count: 0, amount: 0 },
175
+ outstanding_amount: 0,
176
+ },
177
+ weekday: scopeContext != null && MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext) ? [] : null,
178
+ hourly: scopeContext === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? [] : null,
179
+ });
180
+ const buildWeekdaySection = (scopedDocs, filters) => {
181
+ const byDayIndex = new Map();
182
+ for (const doc of scopedDocs) {
183
+ if (doc.day_index == null)
184
+ continue;
185
+ const group = byDayIndex.get(doc.day_index) ?? [];
186
+ group.push(doc);
187
+ byDayIndex.set(doc.day_index, group);
188
+ }
189
+ const result = [];
190
+ for (const dayIndex of ALL_DAY_INDEX) {
191
+ const group = byDayIndex.get(dayIndex);
192
+ if (group == null)
193
+ continue;
194
+ const merged = sumMaterializedTenantSalesOverviewReports(group.map((doc) => pruneReportForFilters(doc, filters)), { allowTenantMismatch: true });
195
+ if (merged == null)
196
+ return [];
197
+ result.push({ day_index: dayIndex, metric: formatRawOrderMetric(extractNonCancelledTotalSales(merged)) });
198
+ }
199
+ return result;
200
+ };
201
+ const buildHourlySection = (scopedDocs, filters) => {
202
+ // Buckets are merged per `scope_field` — combined brand reads carry one
203
+ // document per tenant for the same hour, and the series must aggregate them.
204
+ const byScopeField = new Map();
205
+ for (const doc of scopedDocs) {
206
+ if (typeof doc.scope_field !== 'string' || doc.scope_field.length === 0)
207
+ continue;
208
+ const group = byScopeField.get(doc.scope_field) ?? [];
209
+ group.push(doc);
210
+ byScopeField.set(doc.scope_field, group);
211
+ }
212
+ const points = [];
213
+ for (const [scopeField, group] of byScopeField) {
214
+ const parts = scopeField.split(' ');
215
+ const localDate = parts[0];
216
+ const hour = Number.parseInt(parts[1] ?? '', 10);
217
+ const businessHourIndex = getMaterializedBusinessHourIndex(hour);
218
+ if (localDate == null || businessHourIndex == null)
219
+ continue;
220
+ const merged = sumMaterializedTenantSalesOverviewReports(group.map((doc) => pruneReportForFilters(doc, filters)), { allowTenantMismatch: true });
221
+ if (merged == null)
222
+ continue;
223
+ points.push({
224
+ local_date: localDate,
225
+ hour,
226
+ business_hour_index: businessHourIndex,
227
+ metric: formatRawOrderMetric(extractNonCancelledTotalSales(merged)),
228
+ });
229
+ }
230
+ return points.sort((a, b) => a.local_date.localeCompare(b.local_date) || a.business_hour_index - b.business_hour_index);
231
+ };
232
+ const buildPageDataForDocs = (docs, scopeContext, filters) => {
233
+ // Weekday filter is a document-level predicate (date/hour scopes only).
234
+ const dayIndexes = filters?.day_indexes;
235
+ const scopedDocs = Array.isArray(dayIndexes) && dayIndexes.length > 0
236
+ ? docs.filter((doc) => doc.day_index != null && dayIndexes.includes(doc.day_index))
237
+ : docs;
238
+ const tenantIds = uniqueTenantIds(scopedDocs);
239
+ if (scopedDocs.length === 0) {
240
+ return buildEmptyPageData(scopeContext, tenantIds);
241
+ }
242
+ // Filter the key map FIRST so the merge (and the bill ledger) only sees the
243
+ // requested slices.
244
+ const pruned = scopedDocs.map((doc) => pruneReportForFilters(doc, filters));
245
+ const merged = sumMaterializedTenantSalesOverviewReports(pruned, { allowTenantMismatch: true });
246
+ if (merged == null)
247
+ return null;
248
+ const keyFilters = merged.sale_type_key_filters ?? [];
249
+ const summaryRaw = createRawOrderMetric();
250
+ const collectedRaw = createRawOrderMetric();
251
+ const cancelledRaw = createRawOrderMetric();
252
+ const paymentsMap = {};
253
+ const channelsMap = {};
254
+ const issuedRaw = { count: 0, amount: 0, settled_count: 0, settled_amount: 0 };
255
+ const receivedRaw = { count: 0, amount: 0 };
256
+ for (const [key, entry] of Object.entries(merged.sale_type_metrics ?? {})) {
257
+ const components = parseMaterializedReportKey(key);
258
+ if (components == null)
259
+ continue;
260
+ const totalSales = entry[REPORT_SALE_TYPE_ENUM.TOTAL_SALES];
261
+ const amountCollected = entry[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED];
262
+ const creditBills = entry[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
263
+ // Cancelled facet: cancelled orders are materialized under `CANCELLED:*`
264
+ // keys and excluded from every other facet (payments included).
265
+ if (isCancelledKey(components, keyFilters)) {
266
+ addRawOrderMetric(cancelledRaw, totalSales?.orders);
267
+ continue;
268
+ }
269
+ addRawOrderMetric(summaryRaw, totalSales?.orders);
270
+ addRawOrderMetric(collectedRaw, amountCollected?.orders);
271
+ for (const payment of totalSales?.payments ?? []) {
272
+ addRawPayment(paymentsMap, payment);
273
+ }
274
+ issuedRaw.count += creditBills?.issued?.count ?? 0;
275
+ issuedRaw.amount += creditBills?.issued?.amount ?? 0;
276
+ issuedRaw.settled_count += creditBills?.issued?.settled_count ?? 0;
277
+ issuedRaw.settled_amount += creditBills?.issued?.settled_amount ?? 0;
278
+ receivedRaw.count += creditBills?.received?.count ?? 0;
279
+ receivedRaw.amount += creditBills?.received?.amount ?? 0;
280
+ const platform = getKeyDimValue(components, keyFilters, MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM) ?? '';
281
+ const channel = channelsMap[platform] ?? (channelsMap[platform] = { platform, count: 0, gross_amount: 0 });
282
+ channel.count += totalSales?.orders?.count ?? 0;
283
+ channel.gross_amount += totalSales?.orders?.gross_amount ?? 0;
284
+ }
285
+ const payments = orderPayments(Object.values(paymentsMap).map((raw) => formatRawPayment(raw, false)));
286
+ // Derived settlement line — composed ONLY from the ledger's `received`
287
+ // bucket (the formatter counts a receipt exactly once).
288
+ if (receivedRaw.count > 0 || receivedRaw.amount !== 0) {
289
+ payments.push(formatRawPayment({
290
+ payment_type: MATERIALIZED_CREDIT_SETTLEMENT_PAYMENT_TYPE,
291
+ count: receivedRaw.count,
292
+ gross_amount: receivedRaw.amount,
293
+ amount_due: 0,
294
+ amount_paid: 0,
295
+ amount_refunded: 0,
296
+ card_charges: 0,
297
+ }, true));
298
+ }
299
+ const channels = Object.values(channelsMap)
300
+ .map((channel) => ({
301
+ platform: channel.platform,
302
+ ...splitPlatformName(channel.platform),
303
+ count: channel.count,
304
+ gross_amount: toDecimal(channel.gross_amount),
305
+ }))
306
+ .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
+ return {
309
+ tenant_ids: tenantIds,
310
+ summary: formatRawOrderMetric(summaryRaw),
311
+ amount_collected: formatRawOrderMetric(collectedRaw),
312
+ cancelled: formatRawOrderMetric(cancelledRaw),
313
+ payments,
314
+ channels,
315
+ credit_bills: {
316
+ issued: {
317
+ count: issuedRaw.count,
318
+ amount: toDecimal(issuedRaw.amount),
319
+ settled_count: issuedRaw.settled_count,
320
+ settled_amount: toDecimal(issuedRaw.settled_amount),
321
+ },
322
+ received: { count: receivedRaw.count, amount: toDecimal(receivedRaw.amount) },
323
+ outstanding_amount: toDecimal(issuedRaw.amount - issuedRaw.settled_amount),
324
+ },
325
+ weekday: supportsDayIndex ? buildWeekdaySection(scopedDocs, filters) : null,
326
+ hourly: scopeContext === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? buildHourlySection(scopedDocs, filters) : null,
327
+ };
328
+ };
329
+ /* ------------------------------------------------------------------------ */
330
+ /* Public API */
331
+ /* ------------------------------------------------------------------------ */
332
+ /**
333
+ * Formats materialized overview documents into page-ready data (see the
334
+ * module docblock for the full contract). Returns
335
+ * `[formattedPageData[], null]` — with `separate_view_per_tenant: true` one
336
+ * entry per tenant (comparative view seam; the analysis result is TBD), the
337
+ * default mode returns a single combined entry. Returns `null` (never throws)
338
+ * when the documents cannot be formatted together.
339
+ */
340
+ export function getFormattedTenantSalesOverviewReporting(docs, filters = null, separate_view_per_tenant = false) {
341
+ if (!Array.isArray(docs) || docs.some((doc) => doc == null)) {
342
+ return null;
343
+ }
344
+ const scopeContext = docs.length > 0 ? docs[0].scope_context : null;
345
+ if (docs.length > 0) {
346
+ const first = docs[0];
347
+ const keyFilterSignature = (first.sale_type_key_filters ?? []).join(':');
348
+ for (const doc of docs) {
349
+ if (doc.scope_context !== first.scope_context ||
350
+ doc.schema_version !== first.schema_version ||
351
+ (doc.sale_type_key_filters ?? []).join(':') !== keyFilterSignature) {
352
+ return null;
353
+ }
354
+ }
355
+ }
356
+ const groups = [];
357
+ if (separate_view_per_tenant) {
358
+ const byTenant = new Map();
359
+ for (const doc of docs) {
360
+ const group = byTenant.get(doc.tenant_id) ?? [];
361
+ group.push(doc);
362
+ byTenant.set(doc.tenant_id, group);
363
+ }
364
+ for (const tenantId of [...byTenant.keys()].sort()) {
365
+ groups.push(byTenant.get(tenantId));
366
+ }
367
+ }
368
+ else {
369
+ groups.push(docs);
370
+ }
371
+ const results = [];
372
+ for (const group of groups) {
373
+ const pageData = buildPageDataForDocs(group, scopeContext, filters);
374
+ if (pageData == null)
375
+ return null;
376
+ results.push(pageData);
377
+ }
378
+ return [results, null];
379
+ }
@@ -633,6 +633,14 @@ const canMergeMaterializedReports = (base, other) => base.tenant_id === other.te
633
633
  base.brand_id === other.brand_id &&
634
634
  base.schema_version === other.schema_version &&
635
635
  base.sale_type_key_filters.join(':') === other.sale_type_key_filters.join(':');
636
+ /**
637
+ * Same brand / schema version / key filters — mergeable ACROSS tenants (the
638
+ * brand-level combined read). Order ids are unique across tenants, so the
639
+ * `(order_id, payment_id)` bill de-dupe stays correct.
640
+ */
641
+ const canMergeMaterializedReportsIgnoringTenant = (base, other) => base.brand_id === other.brand_id &&
642
+ base.schema_version === other.schema_version &&
643
+ base.sale_type_key_filters.join(':') === other.sale_type_key_filters.join(':');
636
644
  /** Sums one report's metric tree into a mutable accumulator. */
637
645
  const applyReportAddition = (metrics, report) => {
638
646
  for (const [key, metric] of Object.entries(normalizeMaterializedSaleTypeMetrics(report.sale_type_metrics))) {
@@ -710,15 +718,21 @@ const dedupeAllBillLedgers = (metrics) => {
710
718
  *
711
719
  * Returns `null` (never throws) when the inputs cannot be summed — empty list
712
720
  * or mismatched tenant / brand / schema version / key filters. `null` means a
713
- * data issue the caller must surface.
721
+ * data issue the caller must surface. Pass `allowTenantMismatch: true` for the
722
+ * brand-level combined read (cross-tenant sums; same brand / schema version /
723
+ * key filters required).
714
724
  */
715
725
  export function sumMaterializedTenantSalesOverviewReports(reports, options = {}) {
716
726
  if (!Array.isArray(reports) || reports.length === 0) {
717
727
  return null;
718
728
  }
729
+ const allowTenantMismatch = options.allowTenantMismatch === true;
719
730
  const [base, ...rest] = reports;
720
731
  for (const report of rest) {
721
- if (!canMergeMaterializedReports(base, report)) {
732
+ const mergeable = allowTenantMismatch
733
+ ? canMergeMaterializedReportsIgnoringTenant(base, report)
734
+ : canMergeMaterializedReports(base, report);
735
+ if (!mergeable) {
722
736
  return null;
723
737
  }
724
738
  }
@@ -362,38 +362,32 @@ export const MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME = 'mater
362
362
  /**
363
363
  * Describes the indexes for `materialized_tenant_sales_overview_reports`.
364
364
  * Values are Mongo key patterns that can be passed straight to `.hint()`.
365
- * - `_id`: unique primary key.
366
- * - `tenant_id__scope_context__scope_field`: UNIQUE index — one document per
367
- * (tenant, scope context, scope value); also serves the standardized query
368
- * (`tenant_id` + `scope_context` + `scope_field`).
369
- * - `brand_id__scope_context__scope_field`: brand-level reads across the
370
- * brand's tenants (sum across their tenant documents).
371
- * - `tenant_id__scope_context__day_index__scope_field` (+ brand variant):
372
- * weekday queries over LOCAL_HOUR / LOCAL_DATE slices
373
- * (`day_index` + `scope_field` range).
365
+ *
366
+ * ONE compound index carries the whole read story (plus `_id`):
367
+ * `tenant_id__scope_context__scope_field__day_index` — UNIQUE:
368
+ * - identity — one document per (tenant, scope context, scope value);
369
+ * `day_index` is a deterministic function of `scope_field` (null for period
370
+ * scopes), so including it keeps the uniqueness exactly on that identity;
371
+ * - the standardized read — the `{ tenant_id, scope_context, scope_field }`
372
+ * PREFIX serves single-tenant and `$in` tenant-list queries (exact or range
373
+ * on `scope_field`) without a second index;
374
+ * - weekday queries — a `scope_field` range bounded by the prefix, with
375
+ * `day_index` filtered straight from the index keys.
376
+ *
377
+ * There are NO `brand_id` indexes: brand-level reads always pass the brand's
378
+ * explicit tenant list (`tenant_id: { $in }` — including user-filtered tenant
379
+ * subsets, which a `brand_id` index could not serve at all). Add a brand
380
+ * index only if a future reader genuinely scans whole brands without a
381
+ * tenant list.
374
382
  */
375
383
  export const MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_INDEXES = {
376
384
  _id: { _id: 1 }, // Unique Index
377
- tenant_id__scope_context__scope_field: {
378
- tenant_id: 1,
379
- scope_context: 1,
380
- scope_field: 1,
381
- }, // unique — one document per (tenant, scope context, scope value)
382
- brand_id__scope_context__scope_field: {
383
- brand_id: 1,
384
- scope_context: 1,
385
- scope_field: 1,
386
- }, // brand-level reads across the brand's tenants
385
+ // unique — one document per (tenant, scope context, scope value); the prefix
386
+ // serves the standardized query, the trailing day_index covers weekday reads
387
387
  tenant_id__scope_context__scope_field__day_index: {
388
388
  tenant_id: 1,
389
389
  scope_context: 1,
390
390
  scope_field: 1,
391
391
  day_index: 1,
392
- }, // weekday queries over LOCAL_HOUR / LOCAL_DATE slices
393
- brand_id__scope_context__scope_field__day_index: {
394
- brand_id: 1,
395
- scope_context: 1,
396
- scope_field: 1,
397
- day_index: 1,
398
- }, // brand-level weekday queries over LOCAL_HOUR / LOCAL_DATE slices
392
+ },
399
393
  };
@@ -1,5 +1,7 @@
1
1
  export * from './key-helpers';
2
+ export * from './materialized-reports-read-helpers';
2
3
  export * from './materialized-tenant-reports-iterations-helpers';
3
4
  export * from './scope-helpers';
4
5
  export * from './tenant-sales-overview-close-day-helpers';
6
+ export * from './tenant-sales-overview-formatter';
5
7
  export * from './tenant-sales-overview-helpers';
@@ -15,7 +15,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./key-helpers"), exports);
18
+ __exportStar(require("./materialized-reports-read-helpers"), exports);
18
19
  __exportStar(require("./materialized-tenant-reports-iterations-helpers"), exports);
19
20
  __exportStar(require("./scope-helpers"), exports);
20
21
  __exportStar(require("./tenant-sales-overview-close-day-helpers"), exports);
22
+ __exportStar(require("./tenant-sales-overview-formatter"), exports);
21
23
  __exportStar(require("./tenant-sales-overview-helpers"), exports);