@managesome/eposmatic-toolkit 0.4.2 → 0.4.3

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.
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMaterializedBusinessHourIndex = getMaterializedBusinessHourIndex;
4
+ exports.getMaterializedHourWindowScopeFields = getMaterializedHourWindowScopeFields;
5
+ exports.getMaterializedHourScopeSpan = getMaterializedHourScopeSpan;
6
+ exports.getMaterializedScopeSpan = getMaterializedScopeSpan;
7
+ exports.filterMaterializedTenantSalesOverviewReportsByScopeFields = filterMaterializedTenantSalesOverviewReportsByScopeFields;
8
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
9
+ const scope_helpers_1 = require("./scope-helpers");
10
+ /**
11
+ * Read-side helpers for materialized-report documents — the frontend-facing
12
+ * half of the query story (see `MATERIALIZED_REPORTS.md` "Time scopes").
13
+ *
14
+ * The ops-service read API takes `{ scope_context, scope_field | from/to }`:
15
+ * - contiguous selections go through `from`/`to` directly (callers can use
16
+ * `getMaterializedScopeSpan` / `getMaterializedHourScopeSpan` to derive the
17
+ * span of a set of keys);
18
+ * - discrete selections fetch the min..max SPAN and keep the exact keys with
19
+ * `filterMaterializedTenantSalesOverviewReportsByScopeFields`;
20
+ * - recurring hour windows (e.g. 6–8pm on every day of a range) expand to the
21
+ * exact hour labels with `getMaterializedHourWindowScopeFields` (span-fetch
22
+ * the full days first, then filter to the labels).
23
+ *
24
+ * Validation convention: helpers return `null` instead of throwing — `null`
25
+ * means the caller passed invalid data.
26
+ */
27
+ /**
28
+ * Chronological business-hour index of an hour bucket: a business day's hour
29
+ * sequence is `06…23, 00…05`, so index = `(hour + 18) % 24` (06 → 0 … 05 →
30
+ * 23). NEVER order hour buckets lexicographically — `'D 00'` sorts before
31
+ * `'D 06'` yet happens ~18 hours later.
32
+ *
33
+ * Returns `null` (never throws) for a non-integer / out-of-range hour.
34
+ */
35
+ function getMaterializedBusinessHourIndex(hour) {
36
+ if (!Number.isInteger(hour) || hour < 0 || hour > 23) {
37
+ return null;
38
+ }
39
+ return (hour + 18) % 24;
40
+ }
41
+ /**
42
+ * Expands a RECURRING daily hour window into the exact `localHour` scope
43
+ * labels (`$in`-style reads): the same business hours on every day of the
44
+ * list, e.g. `4pm–8pm` on June 1–2 →
45
+ * `['2026-06-01 16', '2026-06-01 17', '2026-06-01 18', '2026-06-01 19', …]`.
46
+ *
47
+ * Semantics (see `MATERIALIZED_REPORTS.md`): whole-hour buckets, the window
48
+ * END is the exclusive hour boundary — `16 → 20` = buckets `16, 17, 18, 19`;
49
+ * windows may cross midnight WITHIN one business day — `22 → 2` = buckets
50
+ * `22, 23` (evening) plus `00, 01` (post-midnight), all labelled with the SAME
51
+ * business day. Windows must stay inside one business day: a walk crossing the
52
+ * 06:00 business-morning boundary (e.g. `4 → 8`) is rejected (`null`) rather
53
+ * than silently spanning two label days. `0 → 24` requests the full business
54
+ * day (buckets `00`–`23` of the label day).
55
+ *
56
+ * Returns `null` (never throws) for malformed days or hours; the result is
57
+ * ordered by day, then by the window's own hour order.
58
+ */
59
+ function getMaterializedHourWindowScopeFields(businessDays, fromHour, toHour) {
60
+ if (!Array.isArray(businessDays) || businessDays.length === 0) {
61
+ return null;
62
+ }
63
+ if (!Number.isInteger(fromHour) || fromHour < 0 || fromHour > 23) {
64
+ return null;
65
+ }
66
+ if (!Number.isInteger(toHour) || toHour < 0 || toHour > 24) {
67
+ return null;
68
+ }
69
+ let hourCount;
70
+ if (toHour === 24) {
71
+ if (fromHour !== 0)
72
+ return null;
73
+ hourCount = 24;
74
+ }
75
+ else {
76
+ hourCount = (((toHour - fromHour) % 24) + 24) % 24;
77
+ if (hourCount === 0)
78
+ return null; // ambiguous empty window — caller must be explicit
79
+ }
80
+ // Reject walks crossing the 06:00 business-morning boundary — those span two
81
+ // label days and cannot be expressed with same-day labels.
82
+ if (hourCount < 24) {
83
+ const startPosition = getMaterializedBusinessHourIndex(fromHour);
84
+ if (startPosition == null || startPosition + hourCount > 24) {
85
+ return null;
86
+ }
87
+ }
88
+ const hours = Array.from({ length: hourCount }, (_, index) => (fromHour + index) % 24);
89
+ const labels = [];
90
+ for (const businessDay of businessDays) {
91
+ if ((0, scope_helpers_1.parseMaterializedLocalDate)(businessDay) == null) {
92
+ return null;
93
+ }
94
+ for (const hour of hours) {
95
+ const label = (0, scope_helpers_1.getMaterializedHourScopeField)(businessDay, hour);
96
+ if (label == null)
97
+ return null;
98
+ labels.push(label);
99
+ }
100
+ }
101
+ return labels;
102
+ }
103
+ /**
104
+ * Full-day span of a list of business days for `localHour` reads: the
105
+ * inclusive `{ from: '<first> 00', to: '<last> 23' }` range covers ALL 24
106
+ * hour buckets of every label day in between (a label day's buckets are
107
+ * `'D 00'`…`'D 23'`, spanning the post-midnight hours too). Filter the
108
+ * fetched documents afterwards with `getMaterializedHourWindowScopeFields` /
109
+ * `filterMaterializedTenantSalesOverviewReportsByScopeFields`.
110
+ *
111
+ * Returns `null` (never throws) for a malformed list.
112
+ */
113
+ function getMaterializedHourScopeSpan(businessDays) {
114
+ if (!Array.isArray(businessDays) || businessDays.length === 0) {
115
+ return null;
116
+ }
117
+ for (const businessDay of businessDays) {
118
+ if ((0, scope_helpers_1.parseMaterializedLocalDate)(businessDay) == null) {
119
+ return null;
120
+ }
121
+ }
122
+ const sorted = [...businessDays].sort();
123
+ return { from: `${sorted[0]} 00`, to: `${sorted[sorted.length - 1]} 23` };
124
+ }
125
+ /**
126
+ * Inclusive min..max span of exact non-hour scope values — the fetch range
127
+ * for discrete selections (all non-hour scope fields are fixed-width, so
128
+ * lexicographic order equals chronological order). Returns `null` (never
129
+ * throws) for the hour scope (use `getMaterializedHourScopeSpan`) or a
130
+ * malformed list.
131
+ */
132
+ function getMaterializedScopeSpan(scope_context, scopeFields) {
133
+ if (scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
134
+ return null;
135
+ }
136
+ if (!Array.isArray(scopeFields) || scopeFields.length === 0) {
137
+ return null;
138
+ }
139
+ for (const scopeField of scopeFields) {
140
+ if (typeof scopeField !== 'string' || scopeField.length === 0) {
141
+ return null;
142
+ }
143
+ }
144
+ const sorted = [...scopeFields].sort();
145
+ return { from: sorted[0], to: sorted[sorted.length - 1] };
146
+ }
147
+ /**
148
+ * Keeps only the documents whose `scope_field` is one of the requested keys —
149
+ * the client-side refinement for discrete selections fetched as a span.
150
+ * Returns `null` (never throws) for malformed input; unknown keys simply match
151
+ * nothing (absence = zero).
152
+ */
153
+ function filterMaterializedTenantSalesOverviewReportsByScopeFields(docs, scopeFields) {
154
+ if (!Array.isArray(docs) || !Array.isArray(scopeFields)) {
155
+ return null;
156
+ }
157
+ const wanted = new Set(scopeFields);
158
+ return docs.filter((doc) => doc != null && wanted.has(doc.scope_field));
159
+ }
@@ -0,0 +1,136 @@
1
+ import { DAY_INDEX_ENUM } from '../../constants/ENUMS';
2
+ import { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
3
+ /**
4
+ * Frontend formatter for `materialized_tenant_sales_overview_reports` (see
5
+ * `MATERIALIZED_REPORTS.md` "Frontend consumption").
6
+ *
7
+ * The backend returns raw documents unchanged; this formatter derives all
8
+ * view shaping:
9
+ * - money is converted from CENTS to decimals (`/100`), counts stay integers;
10
+ * - platform / order-status filters are applied to the key map (zero
11
+ * re-fetches — the documents already carry every dimension);
12
+ * - the cancelled facet is split out of the `CANCELLED:*` keys;
13
+ * - payments merge by `payment_type` with the read-time `PAY_LATER → UNPAID`
14
+ * remap, and the dedicated `CREDIT_SETTLEMENT` line is DERIVED from the
15
+ * `CREDIT_BILLS.received` ledger (never from the stored payments);
16
+ * - weekday views group on the denormalized `day_index` field (date/hour
17
+ * scopes only) and hour series are ordered by business-hour index
18
+ * (`06…23, 00…05`) — never lexicographically;
19
+ * - the brand-level combined view sums across tenants (`allowTenantMismatch`
20
+ * on the sum helper; bills stay de-duplicated by `(order_id, payment_id)`).
21
+ *
22
+ * Validation convention: returns `null` instead of throwing when the input
23
+ * cannot be formatted (non-array, mixed scopes / key filters / schema
24
+ * versions, unresolved merges) — `null` means a data issue the caller must
25
+ * surface. An EMPTY document list is valid and yields a zero-filled page.
26
+ */
27
+ /** Filters applied to the metric key map client-side (empty = no constraint). */
28
+ export interface IFormattedSalesOverviewFilters {
29
+ /** Platform component values (e.g. `POS_WALK-IN`); empty or omitted = all. */
30
+ platforms?: string[] | null;
31
+ /** Order-status component values (e.g. `COMPLETED`); empty or omitted = all. */
32
+ order_statuses?: string[] | null;
33
+ /**
34
+ * Weekday filter for date/hour scopes — documents without a `day_index`
35
+ * are dropped when a non-empty list is given.
36
+ */
37
+ day_indexes?: DAY_INDEX_ENUM[] | null;
38
+ }
39
+ /** One order metric after cents → decimals conversion. */
40
+ export interface IFormattedSalesOverviewOrderMetric {
41
+ count: number;
42
+ gross_amount: number;
43
+ discount_amount: number;
44
+ discount_by_type: {
45
+ special_discount: number;
46
+ loyalty_discount: number;
47
+ voucher_discount: number;
48
+ };
49
+ gst_amount: number;
50
+ tax_amount: number;
51
+ tip_amount: number;
52
+ tax_invoice_provider_charges: number;
53
+ delivery_charges: number;
54
+ }
55
+ /** One payment-type line after cents → decimals conversion. */
56
+ export interface IFormattedSalesOverviewPayment {
57
+ /** Raw / UNPAID-normalized payment type, or `CREDIT_SETTLEMENT`. */
58
+ payment_type: string;
59
+ count: number;
60
+ gross_amount: number;
61
+ amount_due: number;
62
+ amount_paid: number;
63
+ amount_refunded: number;
64
+ card_charges: number;
65
+ /** `true` for the derived `CREDIT_SETTLEMENT` line. */
66
+ derived: boolean;
67
+ }
68
+ /** One platform's share (channel / collection split source). */
69
+ export interface IFormattedSalesOverviewChannel {
70
+ /** Platform value (e.g. `POS_WALK-IN`). */
71
+ platform: string;
72
+ /** `PLATFORM_NAMES` split — e.g. `'Pos'`. */
73
+ order_from: string;
74
+ /** `PLATFORM_NAMES` split — e.g. `'Walk-in'`. */
75
+ order_type: string;
76
+ count: number;
77
+ gross_amount: number;
78
+ }
79
+ /** Credit-bill ledger view (`CREDIT_BILLS` sale-type numbers). */
80
+ export interface IFormattedSalesOverviewCreditBills {
81
+ issued: {
82
+ count: number;
83
+ amount: number;
84
+ settled_count: number;
85
+ settled_amount: number;
86
+ };
87
+ received: {
88
+ count: number;
89
+ amount: number;
90
+ };
91
+ /** `issued.amount − issued.settled_amount` — still outstanding. */
92
+ outstanding_amount: number;
93
+ }
94
+ /** Weekday grouping (date/hour scopes only). */
95
+ export interface IFormattedSalesOverviewWeekday {
96
+ day_index: DAY_INDEX_ENUM;
97
+ metric: IFormattedSalesOverviewOrderMetric;
98
+ }
99
+ /** One hour bucket point (hour scope only), business-hour ordered. */
100
+ export interface IFormattedSalesOverviewHourPoint {
101
+ /** Business-day label (`YYYY-MM-DD`) — hours `00`–`05` are the next morning. */
102
+ local_date: string;
103
+ hour: number;
104
+ /** `(hour + 18) % 24` — chronological position within the business day. */
105
+ business_hour_index: number;
106
+ metric: IFormattedSalesOverviewOrderMetric;
107
+ }
108
+ /** One formatted page result (combined view: a single entry). */
109
+ export interface IFormattedSalesOverviewPageData {
110
+ /** All tenants folded into this result (`[tenant]` in single-tenant reads). */
111
+ tenant_ids: string[];
112
+ /** Non-cancelled sales (filtered) — the headline numbers. */
113
+ summary: IFormattedSalesOverviewOrderMetric;
114
+ /** `AMOUNT_COLLECTED` slot of the same filters. */
115
+ amount_collected: IFormattedSalesOverviewOrderMetric;
116
+ /** Orders materialized under `CANCELLED:*` keys. */
117
+ cancelled: IFormattedSalesOverviewOrderMetric;
118
+ /** Payments: UNPAID first, then COMPLIMENTARY, then the rest; settlement appended. */
119
+ payments: IFormattedSalesOverviewPayment[];
120
+ /** Per-platform breakdown, `count` desc. */
121
+ channels: IFormattedSalesOverviewChannel[];
122
+ credit_bills: IFormattedSalesOverviewCreditBills;
123
+ /** Date/hour scopes only (`null` for period scopes); ordered SUN…SAT. */
124
+ weekday: IFormattedSalesOverviewWeekday[] | null;
125
+ /** Hour scope only (`null` otherwise); ordered by business-hour index. */
126
+ hourly: IFormattedSalesOverviewHourPoint[] | null;
127
+ }
128
+ /**
129
+ * Formats materialized overview documents into page-ready data (see the
130
+ * module docblock for the full contract). Returns
131
+ * `[formattedPageData[], null]` — with `separate_view_per_tenant: true` one
132
+ * entry per tenant (comparative view seam; the analysis result is TBD), the
133
+ * default mode returns a single combined entry. Returns `null` (never throws)
134
+ * when the documents cannot be formatted together.
135
+ */
136
+ export declare function getFormattedTenantSalesOverviewReporting(docs: IMaterializedTenantSalesOverviewReport[], filters?: IFormattedSalesOverviewFilters | null, separate_view_per_tenant?: boolean): [IFormattedSalesOverviewPageData[], null] | null;
@@ -0,0 +1,382 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getFormattedTenantSalesOverviewReporting = getFormattedTenantSalesOverviewReporting;
4
+ const constants_1 = require("../../constants");
5
+ const ENUMS_1 = require("../../constants/ENUMS");
6
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
7
+ const price_conversion_1 = require("../utils/price-conversion");
8
+ const key_helpers_1 = require("./key-helpers");
9
+ const materialized_reports_read_helpers_1 = require("./materialized-reports-read-helpers");
10
+ const tenant_sales_overview_helpers_1 = require("./tenant-sales-overview-helpers");
11
+ /* ------------------------------------------------------------------------ */
12
+ /* Raw (cents) accumulators */
13
+ /* ------------------------------------------------------------------------ */
14
+ const createRawOrderMetric = () => ({
15
+ count: 0,
16
+ gross_amount: 0,
17
+ discount_amount: 0,
18
+ discount_by_type: { special_discount: 0, loyalty_discount: 0, voucher_discount: 0 },
19
+ gst_amount: 0,
20
+ tax_amount: 0,
21
+ tip_amount: 0,
22
+ tax_invoice_provider_charges: 0,
23
+ delivery_charges: 0,
24
+ });
25
+ const addRawOrderMetric = (target, source) => {
26
+ if (source == null)
27
+ return;
28
+ target.count += source.count ?? 0;
29
+ target.gross_amount += source.gross_amount ?? 0;
30
+ target.discount_amount += source.discount_amount ?? 0;
31
+ target.discount_by_type.special_discount += source.discount_by_type?.special_discount ?? 0;
32
+ target.discount_by_type.loyalty_discount += source.discount_by_type?.loyalty_discount ?? 0;
33
+ target.discount_by_type.voucher_discount += source.discount_by_type?.voucher_discount ?? 0;
34
+ target.gst_amount += source.gst_amount ?? 0;
35
+ target.tax_amount += source.tax_amount ?? 0;
36
+ target.tip_amount += source.tip_amount ?? 0;
37
+ target.tax_invoice_provider_charges += source.tax_invoice_provider_charges ?? 0;
38
+ target.delivery_charges += source.delivery_charges ?? 0;
39
+ };
40
+ const toDecimal = (cents) => (0, price_conversion_1.convertPriceFromCents)(cents ?? 0);
41
+ const formatRawOrderMetric = (raw) => ({
42
+ count: raw.count,
43
+ gross_amount: toDecimal(raw.gross_amount),
44
+ discount_amount: toDecimal(raw.discount_amount),
45
+ discount_by_type: {
46
+ special_discount: toDecimal(raw.discount_by_type.special_discount),
47
+ loyalty_discount: toDecimal(raw.discount_by_type.loyalty_discount),
48
+ voucher_discount: toDecimal(raw.discount_by_type.voucher_discount),
49
+ },
50
+ gst_amount: toDecimal(raw.gst_amount),
51
+ tax_amount: toDecimal(raw.tax_amount),
52
+ tip_amount: toDecimal(raw.tip_amount),
53
+ tax_invoice_provider_charges: toDecimal(raw.tax_invoice_provider_charges),
54
+ delivery_charges: toDecimal(raw.delivery_charges),
55
+ });
56
+ /* ------------------------------------------------------------------------ */
57
+ /* Key-map filtering */
58
+ /* ------------------------------------------------------------------------ */
59
+ const getKeyDimValue = (components, keyFilters, dim) => {
60
+ const index = keyFilters.indexOf(dim);
61
+ return index >= 0 ? (components[index] ?? null) : null;
62
+ };
63
+ const matchesFilters = (components, keyFilters, filters) => {
64
+ if (filters == null)
65
+ return true;
66
+ const platforms = filters.platforms;
67
+ if (Array.isArray(platforms) && platforms.length > 0) {
68
+ const platform = getKeyDimValue(components, keyFilters, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM);
69
+ if (platform == null || !platforms.includes(platform))
70
+ return false;
71
+ }
72
+ const orderStatuses = filters.order_statuses;
73
+ if (Array.isArray(orderStatuses) && orderStatuses.length > 0) {
74
+ const status = getKeyDimValue(components, keyFilters, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS);
75
+ if (status == null || !orderStatuses.includes(status))
76
+ return false;
77
+ }
78
+ return true;
79
+ };
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 ?? [];
83
+ const kept = {};
84
+ for (const [key, metric] of Object.entries(doc.sale_type_metrics ?? {})) {
85
+ const components = (0, key_helpers_1.parseMaterializedReportKey)(key);
86
+ // Unparseable key — cannot be matched; skipping keeps the sums honest
87
+ // (the write side rejects such keys, so this is defensive only).
88
+ if (components == null)
89
+ continue;
90
+ if (!matchesFilters(components, keyFilters, filters))
91
+ continue;
92
+ kept[key] = metric;
93
+ }
94
+ return { ...doc, sale_type_metrics: kept };
95
+ };
96
+ /* ------------------------------------------------------------------------ */
97
+ /* Section extraction */
98
+ /* ------------------------------------------------------------------------ */
99
+ const isCancelledKey = (components, keyFilters) => getKeyDimValue(components, keyFilters, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS) ===
100
+ constants_1.ORDER_STATUS_ENUM.CANCELLED;
101
+ /** Non-cancelled `TOTAL_SALES` aggregate of a merged document (cents). */
102
+ const extractNonCancelledTotalSales = (merged) => {
103
+ const raw = createRawOrderMetric();
104
+ const keyFilters = merged.sale_type_key_filters ?? [];
105
+ for (const [key, entry] of Object.entries(merged.sale_type_metrics ?? {})) {
106
+ const components = (0, key_helpers_1.parseMaterializedReportKey)(key);
107
+ if (components == null || isCancelledKey(components, keyFilters))
108
+ continue;
109
+ addRawOrderMetric(raw, entry[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]?.orders);
110
+ }
111
+ return raw;
112
+ };
113
+ const addRawPayment = (map, payment) => {
114
+ const paymentType = (0, tenant_sales_overview_helpers_1.normalizeMaterializedPaymentType)(payment.payment_type);
115
+ const entry = map[paymentType] ??
116
+ (map[paymentType] = {
117
+ payment_type: paymentType,
118
+ count: 0,
119
+ gross_amount: 0,
120
+ amount_due: 0,
121
+ amount_paid: 0,
122
+ amount_refunded: 0,
123
+ card_charges: 0,
124
+ });
125
+ entry.count += payment.count ?? 0;
126
+ entry.gross_amount += payment.gross_amount ?? 0;
127
+ entry.amount_due += payment.amount_due ?? 0;
128
+ entry.amount_paid += payment.amount_paid ?? 0;
129
+ entry.amount_refunded += payment.amount_refunded ?? 0;
130
+ entry.card_charges += payment.card_charges ?? 0;
131
+ };
132
+ const formatRawPayment = (raw, derived) => ({
133
+ payment_type: raw.payment_type,
134
+ count: raw.count,
135
+ gross_amount: toDecimal(raw.gross_amount),
136
+ amount_due: toDecimal(raw.amount_due),
137
+ amount_paid: toDecimal(raw.amount_paid),
138
+ amount_refunded: toDecimal(raw.amount_refunded),
139
+ card_charges: toDecimal(raw.card_charges),
140
+ derived,
141
+ });
142
+ /** UNPAID first, then COMPLIMENTARY, then count desc / name asc. */
143
+ const orderPayments = (payments) => {
144
+ const unpaid = payments.filter((payment) => payment.payment_type === constants_1.PAYMENT_TYPE_ENUM.UNPAID);
145
+ const complimentary = payments.filter((payment) => payment.payment_type === constants_1.PAYMENT_TYPE_ENUM.COMPLIMENTARY);
146
+ const rest = payments
147
+ .filter((payment) => payment.payment_type !== constants_1.PAYMENT_TYPE_ENUM.UNPAID && payment.payment_type !== constants_1.PAYMENT_TYPE_ENUM.COMPLIMENTARY)
148
+ .sort((a, b) => b.count - a.count || a.payment_type.localeCompare(b.payment_type));
149
+ return [...unpaid, ...complimentary, ...rest];
150
+ };
151
+ const splitPlatformName = (platform) => {
152
+ const name = constants_1.PLATFORM_NAMES[platform] ?? platform;
153
+ const [orderFrom, ...orderTypeParts] = name.split(' ');
154
+ return { order_from: orderFrom, order_type: orderTypeParts.join(' ') };
155
+ };
156
+ /* ------------------------------------------------------------------------ */
157
+ /* Page building */
158
+ /* ------------------------------------------------------------------------ */
159
+ const uniqueTenantIds = (docs) => {
160
+ const ids = new Set();
161
+ for (const doc of docs) {
162
+ if (typeof doc.tenant_id === 'string' && doc.tenant_id.length > 0)
163
+ ids.add(doc.tenant_id);
164
+ }
165
+ return [...ids].sort();
166
+ };
167
+ const buildEmptyOrderMetric = () => formatRawOrderMetric(createRawOrderMetric());
168
+ const buildEmptyPageData = (scopeContext, tenantIds) => ({
169
+ tenant_ids: tenantIds,
170
+ summary: buildEmptyOrderMetric(),
171
+ amount_collected: buildEmptyOrderMetric(),
172
+ cancelled: buildEmptyOrderMetric(),
173
+ payments: [],
174
+ channels: [],
175
+ credit_bills: {
176
+ issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
177
+ received: { count: 0, amount: 0 },
178
+ outstanding_amount: 0,
179
+ },
180
+ weekday: scopeContext != null && MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext) ? [] : null,
181
+ hourly: scopeContext === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? [] : null,
182
+ });
183
+ const buildWeekdaySection = (scopedDocs, filters) => {
184
+ const byDayIndex = new Map();
185
+ for (const doc of scopedDocs) {
186
+ if (doc.day_index == null)
187
+ continue;
188
+ const group = byDayIndex.get(doc.day_index) ?? [];
189
+ group.push(doc);
190
+ byDayIndex.set(doc.day_index, group);
191
+ }
192
+ const result = [];
193
+ for (const dayIndex of ENUMS_1.ALL_DAY_INDEX) {
194
+ const group = byDayIndex.get(dayIndex);
195
+ if (group == null)
196
+ continue;
197
+ const merged = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)(group.map((doc) => pruneReportForFilters(doc, filters)), { allowTenantMismatch: true });
198
+ if (merged == null)
199
+ return [];
200
+ result.push({ day_index: dayIndex, metric: formatRawOrderMetric(extractNonCancelledTotalSales(merged)) });
201
+ }
202
+ return result;
203
+ };
204
+ const buildHourlySection = (scopedDocs, filters) => {
205
+ // Buckets are merged per `scope_field` — combined brand reads carry one
206
+ // document per tenant for the same hour, and the series must aggregate them.
207
+ const byScopeField = new Map();
208
+ for (const doc of scopedDocs) {
209
+ if (typeof doc.scope_field !== 'string' || doc.scope_field.length === 0)
210
+ continue;
211
+ const group = byScopeField.get(doc.scope_field) ?? [];
212
+ group.push(doc);
213
+ byScopeField.set(doc.scope_field, group);
214
+ }
215
+ const points = [];
216
+ for (const [scopeField, group] of byScopeField) {
217
+ const parts = scopeField.split(' ');
218
+ const localDate = parts[0];
219
+ const hour = Number.parseInt(parts[1] ?? '', 10);
220
+ const businessHourIndex = (0, materialized_reports_read_helpers_1.getMaterializedBusinessHourIndex)(hour);
221
+ if (localDate == null || businessHourIndex == null)
222
+ continue;
223
+ const merged = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)(group.map((doc) => pruneReportForFilters(doc, filters)), { allowTenantMismatch: true });
224
+ if (merged == null)
225
+ continue;
226
+ points.push({
227
+ local_date: localDate,
228
+ hour,
229
+ business_hour_index: businessHourIndex,
230
+ metric: formatRawOrderMetric(extractNonCancelledTotalSales(merged)),
231
+ });
232
+ }
233
+ return points.sort((a, b) => a.local_date.localeCompare(b.local_date) || a.business_hour_index - b.business_hour_index);
234
+ };
235
+ const buildPageDataForDocs = (docs, scopeContext, filters) => {
236
+ // Weekday filter is a document-level predicate (date/hour scopes only).
237
+ const dayIndexes = filters?.day_indexes;
238
+ const scopedDocs = Array.isArray(dayIndexes) && dayIndexes.length > 0
239
+ ? docs.filter((doc) => doc.day_index != null && dayIndexes.includes(doc.day_index))
240
+ : docs;
241
+ const tenantIds = uniqueTenantIds(scopedDocs);
242
+ if (scopedDocs.length === 0) {
243
+ return buildEmptyPageData(scopeContext, tenantIds);
244
+ }
245
+ // Filter the key map FIRST so the merge (and the bill ledger) only sees the
246
+ // requested slices.
247
+ const pruned = scopedDocs.map((doc) => pruneReportForFilters(doc, filters));
248
+ const merged = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)(pruned, { allowTenantMismatch: true });
249
+ if (merged == null)
250
+ return null;
251
+ const keyFilters = merged.sale_type_key_filters ?? [];
252
+ const summaryRaw = createRawOrderMetric();
253
+ const collectedRaw = createRawOrderMetric();
254
+ const cancelledRaw = createRawOrderMetric();
255
+ const paymentsMap = {};
256
+ const channelsMap = {};
257
+ const issuedRaw = { count: 0, amount: 0, settled_count: 0, settled_amount: 0 };
258
+ const receivedRaw = { count: 0, amount: 0 };
259
+ for (const [key, entry] of Object.entries(merged.sale_type_metrics ?? {})) {
260
+ const components = (0, key_helpers_1.parseMaterializedReportKey)(key);
261
+ if (components == null)
262
+ continue;
263
+ const totalSales = entry[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES];
264
+ const amountCollected = entry[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED];
265
+ const creditBills = entry[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
266
+ // Cancelled facet: cancelled orders are materialized under `CANCELLED:*`
267
+ // keys and excluded from every other facet (payments included).
268
+ if (isCancelledKey(components, keyFilters)) {
269
+ addRawOrderMetric(cancelledRaw, totalSales?.orders);
270
+ continue;
271
+ }
272
+ addRawOrderMetric(summaryRaw, totalSales?.orders);
273
+ addRawOrderMetric(collectedRaw, amountCollected?.orders);
274
+ for (const payment of totalSales?.payments ?? []) {
275
+ addRawPayment(paymentsMap, payment);
276
+ }
277
+ issuedRaw.count += creditBills?.issued?.count ?? 0;
278
+ issuedRaw.amount += creditBills?.issued?.amount ?? 0;
279
+ issuedRaw.settled_count += creditBills?.issued?.settled_count ?? 0;
280
+ issuedRaw.settled_amount += creditBills?.issued?.settled_amount ?? 0;
281
+ receivedRaw.count += creditBills?.received?.count ?? 0;
282
+ receivedRaw.amount += creditBills?.received?.amount ?? 0;
283
+ const platform = getKeyDimValue(components, keyFilters, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM) ?? '';
284
+ const channel = channelsMap[platform] ?? (channelsMap[platform] = { platform, count: 0, gross_amount: 0 });
285
+ channel.count += totalSales?.orders?.count ?? 0;
286
+ channel.gross_amount += totalSales?.orders?.gross_amount ?? 0;
287
+ }
288
+ const payments = orderPayments(Object.values(paymentsMap).map((raw) => formatRawPayment(raw, false)));
289
+ // Derived settlement line — composed ONLY from the ledger's `received`
290
+ // bucket (the formatter counts a receipt exactly once).
291
+ if (receivedRaw.count > 0 || receivedRaw.amount !== 0) {
292
+ payments.push(formatRawPayment({
293
+ payment_type: MATERIALIZED_REPORTS_1.MATERIALIZED_CREDIT_SETTLEMENT_PAYMENT_TYPE,
294
+ count: receivedRaw.count,
295
+ gross_amount: receivedRaw.amount,
296
+ amount_due: 0,
297
+ amount_paid: 0,
298
+ amount_refunded: 0,
299
+ card_charges: 0,
300
+ }, true));
301
+ }
302
+ const channels = Object.values(channelsMap)
303
+ .map((channel) => ({
304
+ platform: channel.platform,
305
+ ...splitPlatformName(channel.platform),
306
+ count: channel.count,
307
+ gross_amount: toDecimal(channel.gross_amount),
308
+ }))
309
+ .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
+ return {
312
+ tenant_ids: tenantIds,
313
+ summary: formatRawOrderMetric(summaryRaw),
314
+ amount_collected: formatRawOrderMetric(collectedRaw),
315
+ cancelled: formatRawOrderMetric(cancelledRaw),
316
+ payments,
317
+ channels,
318
+ credit_bills: {
319
+ issued: {
320
+ count: issuedRaw.count,
321
+ amount: toDecimal(issuedRaw.amount),
322
+ settled_count: issuedRaw.settled_count,
323
+ settled_amount: toDecimal(issuedRaw.settled_amount),
324
+ },
325
+ received: { count: receivedRaw.count, amount: toDecimal(receivedRaw.amount) },
326
+ outstanding_amount: toDecimal(issuedRaw.amount - issuedRaw.settled_amount),
327
+ },
328
+ weekday: supportsDayIndex ? buildWeekdaySection(scopedDocs, filters) : null,
329
+ hourly: scopeContext === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? buildHourlySection(scopedDocs, filters) : null,
330
+ };
331
+ };
332
+ /* ------------------------------------------------------------------------ */
333
+ /* Public API */
334
+ /* ------------------------------------------------------------------------ */
335
+ /**
336
+ * Formats materialized overview documents into page-ready data (see the
337
+ * module docblock for the full contract). Returns
338
+ * `[formattedPageData[], null]` — with `separate_view_per_tenant: true` one
339
+ * entry per tenant (comparative view seam; the analysis result is TBD), the
340
+ * default mode returns a single combined entry. Returns `null` (never throws)
341
+ * when the documents cannot be formatted together.
342
+ */
343
+ function getFormattedTenantSalesOverviewReporting(docs, filters = null, separate_view_per_tenant = false) {
344
+ if (!Array.isArray(docs) || docs.some((doc) => doc == null)) {
345
+ return null;
346
+ }
347
+ const scopeContext = docs.length > 0 ? docs[0].scope_context : null;
348
+ if (docs.length > 0) {
349
+ const first = docs[0];
350
+ const keyFilterSignature = (first.sale_type_key_filters ?? []).join(':');
351
+ for (const doc of docs) {
352
+ if (doc.scope_context !== first.scope_context ||
353
+ doc.schema_version !== first.schema_version ||
354
+ (doc.sale_type_key_filters ?? []).join(':') !== keyFilterSignature) {
355
+ return null;
356
+ }
357
+ }
358
+ }
359
+ const groups = [];
360
+ if (separate_view_per_tenant) {
361
+ const byTenant = new Map();
362
+ for (const doc of docs) {
363
+ const group = byTenant.get(doc.tenant_id) ?? [];
364
+ group.push(doc);
365
+ byTenant.set(doc.tenant_id, group);
366
+ }
367
+ for (const tenantId of [...byTenant.keys()].sort()) {
368
+ groups.push(byTenant.get(tenantId));
369
+ }
370
+ }
371
+ else {
372
+ groups.push(docs);
373
+ }
374
+ const results = [];
375
+ for (const group of groups) {
376
+ const pageData = buildPageDataForDocs(group, scopeContext, filters);
377
+ if (pageData == null)
378
+ return null;
379
+ results.push(pageData);
380
+ }
381
+ return [results, null];
382
+ }