@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.
- package/esm/helpers/materialized-reports/index.js +2 -0
- package/esm/helpers/materialized-reports/materialized-reports-read-helpers.js +152 -0
- package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +379 -0
- package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +16 -2
- package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +20 -26
- package/lib/helpers/materialized-reports/index.d.ts +2 -0
- package/lib/helpers/materialized-reports/index.js +2 -0
- package/lib/helpers/materialized-reports/materialized-reports-read-helpers.d.ts +79 -0
- package/lib/helpers/materialized-reports/materialized-reports-read-helpers.js +159 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +136 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +382 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +4 -1
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +16 -2
- package/lib/helpers/types/materialized-reports-apis.d.ts +3 -3
- package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +17 -25
- package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +20 -26
- package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +11 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.d.ts +1 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +352 -0
- package/package.json +1 -1
|
@@ -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
|
+
}
|
|
@@ -149,10 +149,13 @@ export declare function convertMaterializedTenantSalesOverviewReportJsonToBson(r
|
|
|
149
149
|
*
|
|
150
150
|
* Returns `null` (never throws) when the inputs cannot be summed — empty list
|
|
151
151
|
* or mismatched tenant / brand / schema version / key filters. `null` means a
|
|
152
|
-
* data issue the caller must surface.
|
|
152
|
+
* data issue the caller must surface. Pass `allowTenantMismatch: true` for the
|
|
153
|
+
* brand-level combined read (cross-tenant sums; same brand / schema version /
|
|
154
|
+
* key filters required).
|
|
153
155
|
*/
|
|
154
156
|
export declare function sumMaterializedTenantSalesOverviewReports(reports: IMaterializedTenantSalesOverviewReport[], options?: {
|
|
155
157
|
computedAt?: Date;
|
|
158
|
+
allowTenantMismatch?: boolean;
|
|
156
159
|
}): IMaterializedTenantSalesOverviewReport | null;
|
|
157
160
|
/**
|
|
158
161
|
* Subtracts `subtrahend`'s metric tree from `minuend` — the first half of the
|
|
@@ -648,6 +648,14 @@ const canMergeMaterializedReports = (base, other) => base.tenant_id === other.te
|
|
|
648
648
|
base.brand_id === other.brand_id &&
|
|
649
649
|
base.schema_version === other.schema_version &&
|
|
650
650
|
base.sale_type_key_filters.join(':') === other.sale_type_key_filters.join(':');
|
|
651
|
+
/**
|
|
652
|
+
* Same brand / schema version / key filters — mergeable ACROSS tenants (the
|
|
653
|
+
* brand-level combined read). Order ids are unique across tenants, so the
|
|
654
|
+
* `(order_id, payment_id)` bill de-dupe stays correct.
|
|
655
|
+
*/
|
|
656
|
+
const canMergeMaterializedReportsIgnoringTenant = (base, other) => base.brand_id === other.brand_id &&
|
|
657
|
+
base.schema_version === other.schema_version &&
|
|
658
|
+
base.sale_type_key_filters.join(':') === other.sale_type_key_filters.join(':');
|
|
651
659
|
/** Sums one report's metric tree into a mutable accumulator. */
|
|
652
660
|
const applyReportAddition = (metrics, report) => {
|
|
653
661
|
for (const [key, metric] of Object.entries(normalizeMaterializedSaleTypeMetrics(report.sale_type_metrics))) {
|
|
@@ -725,15 +733,21 @@ const dedupeAllBillLedgers = (metrics) => {
|
|
|
725
733
|
*
|
|
726
734
|
* Returns `null` (never throws) when the inputs cannot be summed — empty list
|
|
727
735
|
* or mismatched tenant / brand / schema version / key filters. `null` means a
|
|
728
|
-
* data issue the caller must surface.
|
|
736
|
+
* data issue the caller must surface. Pass `allowTenantMismatch: true` for the
|
|
737
|
+
* brand-level combined read (cross-tenant sums; same brand / schema version /
|
|
738
|
+
* key filters required).
|
|
729
739
|
*/
|
|
730
740
|
function sumMaterializedTenantSalesOverviewReports(reports, options = {}) {
|
|
731
741
|
if (!Array.isArray(reports) || reports.length === 0) {
|
|
732
742
|
return null;
|
|
733
743
|
}
|
|
744
|
+
const allowTenantMismatch = options.allowTenantMismatch === true;
|
|
734
745
|
const [base, ...rest] = reports;
|
|
735
746
|
for (const report of rest) {
|
|
736
|
-
|
|
747
|
+
const mergeable = allowTenantMismatch
|
|
748
|
+
? canMergeMaterializedReportsIgnoringTenant(base, report)
|
|
749
|
+
: canMergeMaterializedReports(base, report);
|
|
750
|
+
if (!mergeable) {
|
|
737
751
|
return null;
|
|
738
752
|
}
|
|
739
753
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM } from '../../constants';
|
|
2
2
|
/**
|
|
3
3
|
* Request body contracts for the materialized reports READ APIs
|
|
4
|
-
* (operations-service, mounted at `/
|
|
4
|
+
* (operations-service, mounted at `/reports`) — shared between
|
|
5
5
|
* the backend service and the reports frontend so both sides agree on the
|
|
6
6
|
* wire shape.
|
|
7
7
|
*
|
|
@@ -12,7 +12,7 @@ import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM } from '.
|
|
|
12
12
|
* `IMaterializedTenantReportIteration`) — amounts are INTEGER CENTS.
|
|
13
13
|
*/
|
|
14
14
|
/**
|
|
15
|
-
* Body of `POST /
|
|
15
|
+
* Body of `POST /reports/overview` — materialized sales overview
|
|
16
16
|
* documents (`materialized_tenant_sales_overview_reports`).
|
|
17
17
|
*
|
|
18
18
|
* The scope query is either the exact `scope_field`, or the inclusive
|
|
@@ -41,7 +41,7 @@ export interface IGetMaterializedTenantSalesOverviewReportsBody {
|
|
|
41
41
|
to?: string;
|
|
42
42
|
}
|
|
43
43
|
/**
|
|
44
|
-
* Body of `POST /
|
|
44
|
+
* Body of `POST /reports/iterations` — the latest stored versions
|
|
45
45
|
* of ONE report document from `materialized_tenant_reports_iterations` (the
|
|
46
46
|
* shared version history of every materialized report collection). Rows
|
|
47
47
|
* return newest-first, each carrying the full post-write `snapshot`.
|
|
@@ -530,40 +530,32 @@ export declare const MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME
|
|
|
530
530
|
/**
|
|
531
531
|
* Describes the indexes for `materialized_tenant_sales_overview_reports`.
|
|
532
532
|
* Values are Mongo key patterns that can be passed straight to `.hint()`.
|
|
533
|
-
*
|
|
534
|
-
*
|
|
535
|
-
*
|
|
536
|
-
*
|
|
537
|
-
*
|
|
538
|
-
*
|
|
539
|
-
* - `
|
|
540
|
-
*
|
|
541
|
-
*
|
|
533
|
+
*
|
|
534
|
+
* ONE compound index carries the whole read story (plus `_id`):
|
|
535
|
+
* `tenant_id__scope_context__scope_field__day_index` — UNIQUE:
|
|
536
|
+
* - identity — one document per (tenant, scope context, scope value);
|
|
537
|
+
* `day_index` is a deterministic function of `scope_field` (null for period
|
|
538
|
+
* scopes), so including it keeps the uniqueness exactly on that identity;
|
|
539
|
+
* - the standardized read — the `{ tenant_id, scope_context, scope_field }`
|
|
540
|
+
* PREFIX serves single-tenant and `$in` tenant-list queries (exact or range
|
|
541
|
+
* on `scope_field`) without a second index;
|
|
542
|
+
* - weekday queries — a `scope_field` range bounded by the prefix, with
|
|
543
|
+
* `day_index` filtered straight from the index keys.
|
|
544
|
+
*
|
|
545
|
+
* There are NO `brand_id` indexes: brand-level reads always pass the brand's
|
|
546
|
+
* explicit tenant list (`tenant_id: { $in }` — including user-filtered tenant
|
|
547
|
+
* subsets, which a `brand_id` index could not serve at all). Add a brand
|
|
548
|
+
* index only if a future reader genuinely scans whole brands without a
|
|
549
|
+
* tenant list.
|
|
542
550
|
*/
|
|
543
551
|
export declare const MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_INDEXES: {
|
|
544
552
|
_id: {
|
|
545
553
|
_id: number;
|
|
546
554
|
};
|
|
547
|
-
tenant_id__scope_context__scope_field: {
|
|
548
|
-
tenant_id: number;
|
|
549
|
-
scope_context: number;
|
|
550
|
-
scope_field: number;
|
|
551
|
-
};
|
|
552
|
-
brand_id__scope_context__scope_field: {
|
|
553
|
-
brand_id: number;
|
|
554
|
-
scope_context: number;
|
|
555
|
-
scope_field: number;
|
|
556
|
-
};
|
|
557
555
|
tenant_id__scope_context__scope_field__day_index: {
|
|
558
556
|
tenant_id: number;
|
|
559
557
|
scope_context: number;
|
|
560
558
|
scope_field: number;
|
|
561
559
|
day_index: number;
|
|
562
560
|
};
|
|
563
|
-
brand_id__scope_context__scope_field__day_index: {
|
|
564
|
-
brand_id: number;
|
|
565
|
-
scope_context: number;
|
|
566
|
-
scope_field: number;
|
|
567
|
-
day_index: number;
|
|
568
|
-
};
|
|
569
561
|
};
|
|
@@ -365,38 +365,32 @@ exports.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME = 'materializ
|
|
|
365
365
|
/**
|
|
366
366
|
* Describes the indexes for `materialized_tenant_sales_overview_reports`.
|
|
367
367
|
* Values are Mongo key patterns that can be passed straight to `.hint()`.
|
|
368
|
-
*
|
|
369
|
-
*
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
*
|
|
373
|
-
*
|
|
374
|
-
* - `
|
|
375
|
-
*
|
|
376
|
-
*
|
|
368
|
+
*
|
|
369
|
+
* ONE compound index carries the whole read story (plus `_id`):
|
|
370
|
+
* `tenant_id__scope_context__scope_field__day_index` — UNIQUE:
|
|
371
|
+
* - identity — one document per (tenant, scope context, scope value);
|
|
372
|
+
* `day_index` is a deterministic function of `scope_field` (null for period
|
|
373
|
+
* scopes), so including it keeps the uniqueness exactly on that identity;
|
|
374
|
+
* - the standardized read — the `{ tenant_id, scope_context, scope_field }`
|
|
375
|
+
* PREFIX serves single-tenant and `$in` tenant-list queries (exact or range
|
|
376
|
+
* on `scope_field`) without a second index;
|
|
377
|
+
* - weekday queries — a `scope_field` range bounded by the prefix, with
|
|
378
|
+
* `day_index` filtered straight from the index keys.
|
|
379
|
+
*
|
|
380
|
+
* There are NO `brand_id` indexes: brand-level reads always pass the brand's
|
|
381
|
+
* explicit tenant list (`tenant_id: { $in }` — including user-filtered tenant
|
|
382
|
+
* subsets, which a `brand_id` index could not serve at all). Add a brand
|
|
383
|
+
* index only if a future reader genuinely scans whole brands without a
|
|
384
|
+
* tenant list.
|
|
377
385
|
*/
|
|
378
386
|
exports.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_INDEXES = {
|
|
379
387
|
_id: { _id: 1 }, // Unique Index
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
scope_context: 1,
|
|
383
|
-
scope_field: 1,
|
|
384
|
-
}, // unique — one document per (tenant, scope context, scope value)
|
|
385
|
-
brand_id__scope_context__scope_field: {
|
|
386
|
-
brand_id: 1,
|
|
387
|
-
scope_context: 1,
|
|
388
|
-
scope_field: 1,
|
|
389
|
-
}, // brand-level reads across the brand's tenants
|
|
388
|
+
// unique — one document per (tenant, scope context, scope value); the prefix
|
|
389
|
+
// serves the standardized query, the trailing day_index covers weekday reads
|
|
390
390
|
tenant_id__scope_context__scope_field__day_index: {
|
|
391
391
|
tenant_id: 1,
|
|
392
392
|
scope_context: 1,
|
|
393
393
|
scope_field: 1,
|
|
394
394
|
day_index: 1,
|
|
395
|
-
},
|
|
396
|
-
brand_id__scope_context__scope_field__day_index: {
|
|
397
|
-
brand_id: 1,
|
|
398
|
-
scope_context: 1,
|
|
399
|
-
scope_field: 1,
|
|
400
|
-
day_index: 1,
|
|
401
|
-
}, // brand-level weekday queries over LOCAL_HOUR / LOCAL_DATE slices
|
|
395
|
+
},
|
|
402
396
|
};
|
package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js
CHANGED
|
@@ -76,6 +76,17 @@ describe('materialized_tenant_sales_overview_reports schema', () => {
|
|
|
76
76
|
it('exposes the agreed collection name', () => {
|
|
77
77
|
expect(materialized_tenant_sales_overview_reports_1.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME).toBe('materialized_tenant_sales_overview_reports');
|
|
78
78
|
});
|
|
79
|
+
it('declares one compound tenant index — brand reads pass explicit tenant lists ($in)', () => {
|
|
80
|
+
expect(materialized_tenant_sales_overview_reports_1.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_INDEXES).toEqual({
|
|
81
|
+
_id: { _id: 1 },
|
|
82
|
+
tenant_id__scope_context__scope_field__day_index: {
|
|
83
|
+
tenant_id: 1,
|
|
84
|
+
scope_context: 1,
|
|
85
|
+
scope_field: 1,
|
|
86
|
+
day_index: 1,
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
});
|
|
79
90
|
it('validates a well-formed scope document and casts metrics to a Map', () => {
|
|
80
91
|
const doc = new Model(validDocument());
|
|
81
92
|
expect(doc.validateSync()).toBeUndefined();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|