@managesome/eposmatic-toolkit 0.3.11 → 0.4.0

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 (52) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +105 -0
  2. package/esm/helpers/materialized-reports/index.js +5 -0
  3. package/esm/helpers/materialized-reports/key-helpers.js +59 -0
  4. package/esm/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +60 -0
  5. package/esm/helpers/materialized-reports/scope-helpers.js +107 -0
  6. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +251 -0
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +860 -0
  8. package/esm/schemas/models/materialized_tenant_reports_iterations.js +82 -0
  9. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +399 -0
  10. package/esm/schemas/types/materialized_tenant_reports_iterations.js +1 -0
  11. package/esm/schemas/types/materialized_tenant_sales_overview_reports.js +1 -0
  12. package/lib/constants/MATERIALIZED_REPORTS.d.ts +96 -0
  13. package/lib/constants/MATERIALIZED_REPORTS.js +108 -0
  14. package/lib/helpers/materialized-reports/index.d.ts +5 -0
  15. package/lib/helpers/materialized-reports/index.js +21 -0
  16. package/lib/helpers/materialized-reports/key-helpers.d.ts +35 -0
  17. package/lib/helpers/materialized-reports/key-helpers.js +64 -0
  18. package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.d.ts +66 -0
  19. package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +63 -0
  20. package/lib/helpers/materialized-reports/scope-helpers.d.ts +57 -0
  21. package/lib/helpers/materialized-reports/scope-helpers.js +114 -0
  22. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +125 -0
  23. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +256 -0
  24. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +223 -0
  25. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +875 -0
  26. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +80 -0
  27. package/lib/schemas/models/materialized_tenant_reports_iterations.js +85 -0
  28. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +569 -0
  29. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +402 -0
  30. package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +62 -0
  31. package/lib/schemas/types/materialized_tenant_reports_iterations.js +2 -0
  32. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +242 -0
  33. package/lib/schemas/types/materialized_tenant_sales_overview_reports.js +3 -0
  34. package/lib/tests/materialized-reports/fixtures.d.ts +81 -0
  35. package/lib/tests/materialized-reports/fixtures.js +87 -0
  36. package/lib/tests/materialized-reports/fixtures.test.d.ts +1 -0
  37. package/lib/tests/materialized-reports/fixtures.test.js +123 -0
  38. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.d.ts +1 -0
  39. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.js +75 -0
  40. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.d.ts +1 -0
  41. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +73 -0
  42. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.d.ts +1 -0
  43. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +207 -0
  44. package/lib/tests/materialized-reports/sales-overview-baseline.test.d.ts +1 -0
  45. package/lib/tests/materialized-reports/sales-overview-baseline.test.js +326 -0
  46. package/lib/tests/materialized-reports/sales-overview-reference.d.ts +63 -0
  47. package/lib/tests/materialized-reports/sales-overview-reference.js +131 -0
  48. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.d.ts +1 -0
  49. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +335 -0
  50. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.d.ts +1 -0
  51. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +885 -0
  52. package/package.json +5 -2
@@ -0,0 +1,875 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.normalizeMaterializedPaymentType = normalizeMaterializedPaymentType;
7
+ exports.isPaymentIncludedInMaterializedSalesOverview = isPaymentIncludedInMaterializedSalesOverview;
8
+ exports.getMaterializedPaymentGross = getMaterializedPaymentGross;
9
+ exports.isMaterializedCreditBillPayment = isMaterializedCreditBillPayment;
10
+ exports.normalizeMaterializedSaleTypeMetrics = normalizeMaterializedSaleTypeMetrics;
11
+ exports.convertOrdersToMaterializedTenantSalesOverviewReports = convertOrdersToMaterializedTenantSalesOverviewReports;
12
+ exports.convertMaterializedTenantSalesOverviewReportJsonToBson = convertMaterializedTenantSalesOverviewReportJsonToBson;
13
+ exports.sumMaterializedTenantSalesOverviewReports = sumMaterializedTenantSalesOverviewReports;
14
+ exports.subtractMaterializedTenantSalesOverviewReports = subtractMaterializedTenantSalesOverviewReports;
15
+ exports.updateMaterializedTenantSalesOverviewReport = updateMaterializedTenantSalesOverviewReport;
16
+ const mongoose_1 = __importDefault(require("mongoose"));
17
+ const constants_1 = require("../../constants");
18
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
19
+ const materialized_tenant_sales_overview_reports_1 = require("../../schemas/models/materialized_tenant_sales_overview_reports");
20
+ const time_helpers_1 = require("../utils/time-helpers");
21
+ const key_helpers_1 = require("./key-helpers");
22
+ const scope_helpers_1 = require("./scope-helpers");
23
+ /* ------------------------------------------------------------------------ */
24
+ /* Payment rules (twin of `sales-overview-reference.ts`) */
25
+ /* ------------------------------------------------------------------------ */
26
+ /** `PAY_LATER` is reported as `UNPAID` (live-aggregation behavior). */
27
+ function normalizeMaterializedPaymentType(paymentType) {
28
+ return paymentType === constants_1.PAYMENT_TYPE_ENUM.PAY_LATER ? constants_1.PAYMENT_TYPE_ENUM.UNPAID : paymentType;
29
+ }
30
+ /**
31
+ * Payment-level inclusion rule of the `TOTAL_PAYMENT_SALES` facet:
32
+ * settled/refunded payments, plus pending `UNPAID`/`PAY_LATER` (credit)
33
+ * payments.
34
+ */
35
+ function isPaymentIncludedInMaterializedSalesOverview(payment) {
36
+ if (payment.payment_status === constants_1.PAYMENT_STATUS_ENUM.SETTLED ||
37
+ payment.payment_status === constants_1.PAYMENT_STATUS_ENUM.REFUNDED) {
38
+ return true;
39
+ }
40
+ return (payment.payment_status === constants_1.PAYMENT_STATUS_ENUM.PENDING &&
41
+ (payment.payment_type === constants_1.PAYMENT_TYPE_ENUM.UNPAID || payment.payment_type === constants_1.PAYMENT_TYPE_ENUM.PAY_LATER));
42
+ }
43
+ /**
44
+ * Payment gross contribution in cents (mirrors the live aggregation):
45
+ * - no refund: `amount_due` for UNPAID, else `min(amount_paid, amount_due)`;
46
+ * card charges subtracted when `card_details` is present;
47
+ * - refunded: negative — `-amount_due` for UNPAID, else `-amount_refunded`.
48
+ */
49
+ function getMaterializedPaymentGross(payment) {
50
+ const reportedType = normalizeMaterializedPaymentType(payment.payment_type);
51
+ const isUnpaid = reportedType === constants_1.PAYMENT_TYPE_ENUM.UNPAID;
52
+ if ((payment.amount_refunded ?? 0) === 0) {
53
+ let gross = isUnpaid ? (payment.amount_due ?? 0) : Math.min(payment.amount_paid ?? 0, payment.amount_due ?? 0);
54
+ if (payment.card_details != null) {
55
+ gross -= payment.card_details.card_charges ?? 0;
56
+ }
57
+ return gross;
58
+ }
59
+ return -(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
60
+ }
61
+ /** Whether a payment row represents a credit bill (`PAY_LATER`). */
62
+ function isMaterializedCreditBillPayment(payment) {
63
+ return payment.payment_type === constants_1.PAYMENT_TYPE_ENUM.PAY_LATER;
64
+ }
65
+ const createEmptyOrderMetric = () => ({
66
+ count: 0,
67
+ gross_amount: 0,
68
+ discount_amount: 0,
69
+ discount_by_type: { special_discount: 0, loyalty_discount: 0, voucher_discount: 0 },
70
+ gst_amount: 0,
71
+ tax_amount: 0,
72
+ tip_amount: 0,
73
+ tax_invoice_provider_charges: 0,
74
+ delivery_charges: 0,
75
+ });
76
+ const createEmptySaleTypeMetric = () => ({
77
+ orders: createEmptyOrderMetric(),
78
+ payments: {},
79
+ });
80
+ const createEmptyKeyMetrics = () => ({
81
+ [constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: createEmptySaleTypeMetric(),
82
+ [constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]: createEmptySaleTypeMetric(),
83
+ [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: { issued: { bills: [] }, received: { bills: [] } },
84
+ });
85
+ function getOrCreateKeyMetrics(metrics, key) {
86
+ if (metrics[key] == null) {
87
+ metrics[key] = createEmptyKeyMetrics();
88
+ }
89
+ return metrics[key];
90
+ }
91
+ /* ------------------------------------------------------------------------ */
92
+ /* Accumulation */
93
+ /* ------------------------------------------------------------------------ */
94
+ function accumulateOrderIntoOrderMetric(metric, order) {
95
+ metric.count += 1;
96
+ metric.gross_amount += order.amount_earned ?? 0;
97
+ metric.discount_amount += order.total_discount_applied ?? order.order_discount_details?.total_discount ?? 0;
98
+ metric.discount_by_type.special_discount += order.order_discount_details?.special_discount ?? 0;
99
+ metric.discount_by_type.loyalty_discount += order.order_discount_details?.loyalty_discount ?? 0;
100
+ metric.discount_by_type.voucher_discount += order.order_discount_details?.voucher_discount ?? 0;
101
+ metric.gst_amount += order.gst_amount ?? 0;
102
+ metric.tax_amount += order.tax_amount ?? 0;
103
+ metric.tip_amount += order.tip_amount ?? 0;
104
+ metric.tax_invoice_provider_charges += order.tax_invoice_provider_charges ?? 0;
105
+ metric.delivery_charges += order.delivery_details?.delivery_cost ?? 0;
106
+ }
107
+ function accumulateOrderPayments(metric, order) {
108
+ for (const payment of order.payments ?? []) {
109
+ if (!isPaymentIncludedInMaterializedSalesOverview(payment))
110
+ continue;
111
+ const paymentType = normalizeMaterializedPaymentType(payment.payment_type);
112
+ if (metric.payments[paymentType] == null) {
113
+ metric.payments[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
+ }
123
+ const entry = metric.payments[paymentType];
124
+ entry.count += 1;
125
+ entry.gross_amount += getMaterializedPaymentGross(payment);
126
+ entry.amount_due += payment.amount_due ?? 0;
127
+ entry.amount_paid += payment.amount_paid ?? 0;
128
+ entry.amount_refunded += payment.amount_refunded ?? 0;
129
+ entry.card_charges += payment.card_details?.card_charges ?? 0;
130
+ }
131
+ }
132
+ /** Accumulates one order into one scope document's metric tree (pre-built key). */
133
+ function accumulateOrder(metrics, key, order) {
134
+ const keyMetrics = getOrCreateKeyMetrics(metrics, key);
135
+ accumulateOrderIntoOrderMetric(keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders, order);
136
+ accumulateOrderPayments(keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES], order);
137
+ if ((order.amount_collected ?? 0) > 0) {
138
+ accumulateOrderIntoOrderMetric(keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders, order);
139
+ accumulateOrderPayments(keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED], order);
140
+ }
141
+ }
142
+ /* ------------------------------------------------------------------------ */
143
+ /* Credit bills (PAY_LATER) */
144
+ /* ------------------------------------------------------------------------ */
145
+ /**
146
+ * Bills issued by an order (the order's business day is the compiled day):
147
+ * one entry per `PAY_LATER` payment. `received_amount` reflects what the
148
+ * payment has received so far (normally 0 at issue time).
149
+ *
150
+ * Timestamp anchors are deliberately different: `issued_at` is the order's
151
+ * punch time (`createdAt`) — `order_settled_at` must NEVER anchor it, because
152
+ * for a deferred bill collected on a later day that field holds the COLLECTION
153
+ * moment (a backfill close would otherwise stamp the issue-day bill with its
154
+ * later settlement time). `settled_at` follows the documented settled rule
155
+ * (`received_amount >= amount`) and uses the true settlement timestamp when
156
+ * present, falling back to the compile time (`now` — deterministic per run,
157
+ * never `Date.now()`).
158
+ *
159
+ * Bills are keyed by `payment_id` (fallback: the payment subdocument `_id`);
160
+ * a `PAY_LATER` payment carrying neither is a data issue → `null` (the
161
+ * ledger's `(order_id, payment_id)` keys must never collapse).
162
+ */
163
+ function buildIssuedCreditBills(order, now) {
164
+ const bills = [];
165
+ const issuedAt = new Date(order.createdAt ?? order.order_settled_at ?? now);
166
+ const settledAt = order.order_settled_at != null ? new Date(order.order_settled_at) : null;
167
+ for (const payment of order.payments ?? []) {
168
+ if (!isMaterializedCreditBillPayment(payment))
169
+ continue;
170
+ const paymentId = payment.payment_id ?? payment._id ?? null;
171
+ if (paymentId == null || paymentId.length === 0)
172
+ return null; // un-keyable bill — data issue
173
+ const amount = payment.amount_due ?? 0;
174
+ const receivedAmount = payment.amount_paid ?? 0;
175
+ bills.push({
176
+ order_id: order._id,
177
+ payment_id: paymentId,
178
+ amount,
179
+ received_amount: receivedAmount,
180
+ credit_note: payment.note ?? undefined,
181
+ issued_at: issuedAt,
182
+ // Documented settled rule (same as the collection patch): received covers the bill.
183
+ settled_at: receivedAmount >= amount ? (settledAt ?? now) : null,
184
+ });
185
+ }
186
+ return bills;
187
+ }
188
+ /**
189
+ * Credit bills collected by an order whose business day is BEFORE the compiled
190
+ * day (the caller detected the settlement event). `received_amount` is the
191
+ * cumulative amount received for the bill as of this compile; only payments
192
+ * that actually received money are emitted (a `SETTLED` payment with nothing
193
+ * paid is a data anomaly, not a collection event). Un-keyable bills → `null`.
194
+ */
195
+ function buildReceivedCreditBills(order, orderLocalDate) {
196
+ const received = [];
197
+ for (const payment of order.payments ?? []) {
198
+ if (!isMaterializedCreditBillPayment(payment))
199
+ continue;
200
+ const receivedAmount = payment.amount_paid ?? 0;
201
+ if (receivedAmount <= 0)
202
+ continue; // nothing collected yet
203
+ const paymentId = payment.payment_id ?? payment._id ?? null;
204
+ if (paymentId == null || paymentId.length === 0)
205
+ return null; // un-keyable bill — data issue
206
+ received.push({
207
+ order_id: order._id,
208
+ payment_id: paymentId,
209
+ amount: payment.amount_due ?? 0,
210
+ received_amount: receivedAmount,
211
+ credit_note: payment.note ?? undefined,
212
+ issued_local_date: orderLocalDate,
213
+ settled_at: order.order_settled_at != null ? new Date(order.order_settled_at) : null,
214
+ });
215
+ }
216
+ return received;
217
+ }
218
+ /* ------------------------------------------------------------------------ */
219
+ /* Serialization */
220
+ /* ------------------------------------------------------------------------ */
221
+ function sumNumbers(values) {
222
+ return values.reduce((total, value) => total + (value ?? 0), 0);
223
+ }
224
+ function finalizeIssuedLedger(bills) {
225
+ return {
226
+ count: bills.length,
227
+ amount: sumNumbers(bills.map((bill) => bill.amount)),
228
+ // Fully-collected bills / total received so far — tracking numbers.
229
+ settled_count: bills.filter((bill) => bill.settled_at != null).length,
230
+ settled_amount: sumNumbers(bills.map((bill) => bill.received_amount ?? 0)),
231
+ bills,
232
+ };
233
+ }
234
+ function finalizeReceivedLedger(bills) {
235
+ return {
236
+ count: bills.length,
237
+ amount: sumNumbers(bills.map((bill) => bill.received_amount ?? 0)),
238
+ bills,
239
+ };
240
+ }
241
+ function finalizeSaleTypeMetric(metric) {
242
+ const payments = Object.values(metric.payments).sort((a, b) => b.count - a.count || a.payment_type.localeCompare(b.payment_type));
243
+ return { orders: metric.orders, payments };
244
+ }
245
+ function finalizeMetrics(metrics) {
246
+ const finalized = {};
247
+ for (const [key, metric] of Object.entries(metrics)) {
248
+ finalized[key] = {
249
+ [constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: finalizeSaleTypeMetric(metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]),
250
+ [constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]: finalizeSaleTypeMetric(metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]),
251
+ [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: {
252
+ issued: finalizeIssuedLedger(metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills),
253
+ received: finalizeReceivedLedger(metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills),
254
+ },
255
+ };
256
+ }
257
+ return finalized;
258
+ }
259
+ /**
260
+ * Deep plain-value conversion for mongoose-hydrated values: subdocuments
261
+ * (`toObject()`), nested `Map`s and document arrays. Plain JSON values are
262
+ * returned as-is (zero-copy happy path).
263
+ */
264
+ const toPlainMaterializedMetricsValue = (value) => {
265
+ if (value == null)
266
+ return value;
267
+ if (value instanceof Map) {
268
+ return Object.fromEntries(Array.from(value.entries(), ([entryKey, entry]) => [entryKey, toPlainMaterializedMetricsValue(entry)]));
269
+ }
270
+ if (Array.isArray(value))
271
+ return value.map((entry) => toPlainMaterializedMetricsValue(entry));
272
+ if (typeof value === 'object' && typeof value.toObject === 'function') {
273
+ const plain = value.toObject({
274
+ flattenMaps: true,
275
+ });
276
+ return toPlainMaterializedMetricsValue(plain);
277
+ }
278
+ return value;
279
+ };
280
+ /**
281
+ * Plain-record view of a report's `sale_type_metrics`. The schema stores the
282
+ * map as a mongoose `Map` of subdocuments, so a hydrated document
283
+ * (`Model.find()` / the json→BSON cast) carries non-plain values — and
284
+ * `Object.entries` on the raw `Map` is EMPTY, which would silently wipe the
285
+ * stored metrics. This guard deep-converts hydrated shapes (Map container,
286
+ * subdocument values, document arrays) into plain values. Callers should still
287
+ * pass plain JSON (`.lean()`); this guard is the defensive net, not the
288
+ * contract.
289
+ */
290
+ function normalizeMaterializedSaleTypeMetrics(metrics) {
291
+ if (metrics == null)
292
+ return {};
293
+ const plain = toPlainMaterializedMetricsValue(metrics);
294
+ const normalized = {};
295
+ for (const [key, value] of Object.entries(plain)) {
296
+ normalized[key] = toPlainMaterializedMetricsValue(value);
297
+ }
298
+ return normalized;
299
+ }
300
+ /** JSON report → mutable accumulator tree (bills / payments cloned). */
301
+ function toMutableMetrics(metrics) {
302
+ const mutable = {};
303
+ for (const [key, metric] of Object.entries(normalizeMaterializedSaleTypeMetrics(metrics))) {
304
+ mutable[key] = {
305
+ [constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: {
306
+ orders: {
307
+ ...metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders,
308
+ discount_by_type: { ...metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.discount_by_type },
309
+ },
310
+ payments: Object.fromEntries((metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments ?? []).map((payment) => [
311
+ payment.payment_type,
312
+ { ...payment },
313
+ ])),
314
+ },
315
+ [constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]: {
316
+ orders: {
317
+ ...metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders,
318
+ discount_by_type: { ...metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders.discount_by_type },
319
+ },
320
+ payments: Object.fromEntries((metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments ?? []).map((payment) => [
321
+ payment.payment_type,
322
+ { ...payment },
323
+ ])),
324
+ },
325
+ [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: {
326
+ issued: { bills: (metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills ?? []).map((bill) => ({ ...bill })) },
327
+ received: {
328
+ bills: (metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills ?? []).map((bill) => ({ ...bill })),
329
+ },
330
+ },
331
+ };
332
+ }
333
+ return mutable;
334
+ }
335
+ /** Clone of a JSON report with fresh metric objects (safe to mutate). */
336
+ function cloneReport(report) {
337
+ return { ...report, sale_type_metrics: finalizeMetrics(toMutableMetrics(report.sale_type_metrics)) };
338
+ }
339
+ /* ------------------------------------------------------------------------ */
340
+ /* 1. Orders → JSON documents */
341
+ /* ------------------------------------------------------------------------ */
342
+ const resolveOrderLocalHour = (order, localDate, gmtOffset) => {
343
+ if (typeof order.localHour === 'number' && order.localHour >= 0 && order.localHour <= 23) {
344
+ return order.localHour;
345
+ }
346
+ if (typeof gmtOffset === 'number') {
347
+ const fields = (0, time_helpers_1.getLocalFieldsFromLocalDate)(order.localDate ?? localDate, gmtOffset, order.order_settled_at ?? order.createdAt);
348
+ return fields.localHour;
349
+ }
350
+ if (typeof order.order_settled_at_mins === 'number' && order.order_settled_at_mins >= 0) {
351
+ return Math.min(23, Math.floor(order.order_settled_at_mins / 60));
352
+ }
353
+ return null;
354
+ };
355
+ /**
356
+ * Hour bucket of a credit-bill COLLECTION event (an earlier-day order settling
357
+ * on the compiled day): the SETTLEMENT anchor resolves the hour — never the
358
+ * punch hour, so hour views / the derived credit-settlement line sit at the
359
+ * moment the money was collected. Chain: `gmtOffset` + `order_settled_at`
360
+ * (tenant-local hour) → `order_settled_at_mins ÷ 60` → the settlement
361
+ * timestamp's UTC hour (the mins convention is UTC-based too) → punch-hour
362
+ * fallback (last resort).
363
+ */
364
+ const resolveReceivedLocalHour = (order, localDate, gmtOffset) => {
365
+ if (typeof gmtOffset === 'number' && order.order_settled_at != null) {
366
+ const settledAt = new Date(order.order_settled_at);
367
+ if (!Number.isNaN(settledAt.getTime()))
368
+ return (0, time_helpers_1.getLocalDocumentFields)(gmtOffset, settledAt).localHour;
369
+ }
370
+ if (typeof order.order_settled_at_mins === 'number' && order.order_settled_at_mins >= 0) {
371
+ return Math.min(23, Math.floor(order.order_settled_at_mins / 60));
372
+ }
373
+ // Still settlement-anchored (the mins convention above is UTC-based too).
374
+ if (order.order_settled_at != null) {
375
+ const settledUtc = new Date(order.order_settled_at);
376
+ if (!Number.isNaN(settledUtc.getTime()))
377
+ return settledUtc.getUTCHours();
378
+ }
379
+ return resolveOrderLocalHour(order, localDate, gmtOffset);
380
+ };
381
+ const createEmptyReportDocument = (args) => {
382
+ const { tenantId, brandId, scopeContext, scopeField, now } = args;
383
+ const dayIndex = MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext)
384
+ ? (0, scope_helpers_1.getDayIndexFromLocalDate)(scopeField.split(' ')[0])
385
+ : null;
386
+ return {
387
+ _id: new mongoose_1.default.Types.ObjectId().toString(),
388
+ tenant_id: tenantId,
389
+ brand_id: brandId,
390
+ scope_context: scopeContext,
391
+ scope_field: scopeField,
392
+ day_index: dayIndex,
393
+ sale_type_key_filters: [...MATERIALIZED_REPORTS_1.SALES_OVERVIEW_KEY_FILTERS],
394
+ sale_type_metrics: {},
395
+ // First materialization — explicit so a raw `replaceOne` upsert (which
396
+ // does not run mongoose defaults) persists a schema-conformant document
397
+ // matching its history row.
398
+ iteration: 1,
399
+ schema_version: materialized_tenant_sales_overview_reports_1.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_SCHEMA_VERSION,
400
+ source_watermark: now,
401
+ computed_at: now,
402
+ createdAt: now,
403
+ updatedAt: now,
404
+ };
405
+ };
406
+ /**
407
+ * Compiles one tenant-day of orders into materialized scope documents:
408
+ *
409
+ * - one `localHour` document for every hour with activity (never more than 24);
410
+ * - one document per period scope (`localDate` … `localYear`) — always emitted,
411
+ * even for order-less days (empty metrics map), so reconcile/watermark
412
+ * comparisons stay uniform;
413
+ * - `day_index` is set on the `localHour` / `localDate` documents only;
414
+ * - `CREDIT_BILLS`: bills issued by the day's orders are itemized on every
415
+ * scope document of the day; bills collected that day (orders whose business
416
+ * `order.localDate` is earlier) itemize into `received` and are returned as
417
+ * `received_payments` so the caller can patch the issue-day documents.
418
+ *
419
+ * All outputs are plain JSON (dates are `Date` instances — JSON-serializable).
420
+ * Returns `null` (never throws) when the input is invalid — a malformed
421
+ * `localDate` or an order that cannot be keyed (`order_status` / `platform`
422
+ * missing or containing reserved characters) — `null` means a data issue.
423
+ */
424
+ function convertOrdersToMaterializedTenantSalesOverviewReports(localDate, orders, options = {}) {
425
+ if ((0, scope_helpers_1.parseMaterializedLocalDate)(localDate) == null)
426
+ return null;
427
+ const now = options.computedAt ?? new Date();
428
+ const brandId = options.brandId ?? '';
429
+ const tenantIds = Array.from(new Set((orders ?? []).map((order) => order.tenant_id)));
430
+ if (tenantIds.length === 0) {
431
+ if (options.tenantId == null) {
432
+ return { materializedReports: [], received_payments: [] };
433
+ }
434
+ tenantIds.push(options.tenantId);
435
+ }
436
+ const materializedReports = [];
437
+ const receivedPayments = [];
438
+ const periodScopeFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
439
+ if (periodScopeFields == null)
440
+ return null;
441
+ for (const tenantId of tenantIds) {
442
+ const tenantOrders = (orders ?? []).filter((order) => order.tenant_id === tenantId);
443
+ // Business-day split: same-day orders contribute sales; orders with an
444
+ // earlier business day contribute only credit-bill collections.
445
+ const salesOrders = [];
446
+ const receivedEntries = [];
447
+ for (const order of tenantOrders) {
448
+ if (order.is_deleted !== false)
449
+ continue; // live facets materialize `is_deleted: false` only
450
+ const orderLocalDate = order.localDate ?? localDate;
451
+ if (orderLocalDate !== localDate) {
452
+ const collected = buildReceivedCreditBills(order, orderLocalDate);
453
+ if (collected == null)
454
+ return null; // un-keyable bill — data issue
455
+ if (collected.length > 0) {
456
+ receivedEntries.push({ order, orderLocalDate });
457
+ receivedPayments.push(...collected);
458
+ }
459
+ continue;
460
+ }
461
+ salesOrders.push(order);
462
+ }
463
+ // Scope documents: period scopes first, then one document per active hour.
464
+ const periodDocs = Object.entries(periodScopeFields).map(([scopeContext, scopeField]) => ({
465
+ doc: createEmptyReportDocument({
466
+ tenantId,
467
+ brandId,
468
+ scopeContext: scopeContext,
469
+ scopeField,
470
+ now,
471
+ }),
472
+ metrics: {},
473
+ }));
474
+ const hourDocs = new Map();
475
+ const getHourDoc = (hour) => {
476
+ if (!Number.isInteger(hour) || hour < 0 || hour > 23)
477
+ return null;
478
+ if (!hourDocs.has(hour)) {
479
+ const scopeField = (0, scope_helpers_1.getMaterializedHourScopeField)(localDate, hour);
480
+ if (scopeField == null)
481
+ return null;
482
+ hourDocs.set(hour, {
483
+ doc: createEmptyReportDocument({
484
+ tenantId,
485
+ brandId,
486
+ scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
487
+ scopeField,
488
+ now,
489
+ }),
490
+ metrics: {},
491
+ });
492
+ }
493
+ return hourDocs.get(hour) ?? null;
494
+ };
495
+ // The hour document for each order / collection event.
496
+ const salesHours = new Map();
497
+ for (const order of salesOrders) {
498
+ const hour = resolveOrderLocalHour(order, localDate, options.gmtOffset);
499
+ if (hour != null)
500
+ getHourDoc(hour);
501
+ salesHours.set(order, hour);
502
+ }
503
+ const receivedHours = new Map();
504
+ for (const { order } of receivedEntries) {
505
+ const hour = resolveReceivedLocalHour(order, localDate, options.gmtOffset);
506
+ if (hour != null)
507
+ getHourDoc(hour);
508
+ receivedHours.set(order, hour);
509
+ }
510
+ // Every order / event lands on its hour document plus each period document.
511
+ const targetsForHour = (hour) => {
512
+ const hourDoc = hour != null ? hourDocs.get(hour) : undefined;
513
+ return hourDoc != null ? [hourDoc, ...periodDocs] : [...periodDocs];
514
+ };
515
+ for (const order of salesOrders) {
516
+ const key = (0, key_helpers_1.buildMaterializedReportKey)([order.order_status, order.platform]);
517
+ if (key == null)
518
+ return null; // un-keyable order fields — data issue
519
+ const targets = targetsForHour(salesHours.get(order) ?? null);
520
+ for (const target of targets) {
521
+ accumulateOrder(target.metrics, key, order);
522
+ }
523
+ const issuedBills = buildIssuedCreditBills(order, now);
524
+ if (issuedBills == null)
525
+ return null; // un-keyable bill — data issue
526
+ if (issuedBills.length > 0) {
527
+ for (const target of targets) {
528
+ const keyMetrics = getOrCreateKeyMetrics(target.metrics, key);
529
+ keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills.push(...issuedBills.map((bill) => ({ ...bill })));
530
+ }
531
+ }
532
+ }
533
+ for (const { order } of receivedEntries) {
534
+ const collected = buildReceivedCreditBills(order, order.localDate ?? localDate);
535
+ if (collected == null)
536
+ return null; // un-keyable bill — data issue
537
+ if (collected.length === 0)
538
+ continue;
539
+ const key = (0, key_helpers_1.buildMaterializedReportKey)([order.order_status, order.platform]);
540
+ if (key == null)
541
+ return null; // un-keyable order fields — data issue
542
+ const targets = targetsForHour(receivedHours.get(order) ?? null);
543
+ for (const target of targets) {
544
+ const keyMetrics = getOrCreateKeyMetrics(target.metrics, key);
545
+ keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills.push(...collected.map((bill) => ({ ...bill })));
546
+ }
547
+ }
548
+ // `source_watermark` = max `order.updatedAt` folded in; a day with no
549
+ // orders folds nothing → epoch. Stable across recompiles, so the
550
+ // watermark guard skips unchanged (order-less) days instead of churning.
551
+ const watermark = tenantOrders.reduce((latest, order) => {
552
+ const updatedAt = new Date(order.updatedAt ?? now);
553
+ return updatedAt.getTime() > latest.getTime() ? updatedAt : latest;
554
+ }, new Date(0));
555
+ for (const { doc, metrics } of [...periodDocs, ...hourDocs.values()]) {
556
+ doc.sale_type_metrics = finalizeMetrics(metrics);
557
+ doc.source_watermark = watermark;
558
+ materializedReports.push(doc);
559
+ }
560
+ }
561
+ return { materializedReports, received_payments: receivedPayments };
562
+ }
563
+ /* ------------------------------------------------------------------------ */
564
+ /* 2. JSON → BSON (mongoose document) */
565
+ /* ------------------------------------------------------------------------ */
566
+ function getMaterializedTenantSalesOverviewReportModel() {
567
+ return (mongoose_1.default.models[materialized_tenant_sales_overview_reports_1.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME] ??
568
+ mongoose_1.default.model(materialized_tenant_sales_overview_reports_1.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME, materialized_tenant_sales_overview_reports_1.MaterializedTenantSalesOverviewReportSchema, materialized_tenant_sales_overview_reports_1.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME));
569
+ }
570
+ /**
571
+ * Casts a JSON materialized report through the collection's mongoose schema,
572
+ * returning a hydrated document ready to be saved / bulk-written (the
573
+ * `sale_type_metrics` plain object becomes a `Map`, date strings become
574
+ * `Date` instances, etc.).
575
+ *
576
+ * The document is NOT validated here — `save()` / `Model.validate()` still
577
+ * runs the schema validators.
578
+ */
579
+ function convertMaterializedTenantSalesOverviewReportJsonToBson(report) {
580
+ return new (getMaterializedTenantSalesOverviewReportModel())(report);
581
+ }
582
+ /* ------------------------------------------------------------------------ */
583
+ /* 3. Summing documents (period accumulation) */
584
+ /* ------------------------------------------------------------------------ */
585
+ const sumOrderMetrics = (target, source) => {
586
+ target.count += source.count ?? 0;
587
+ target.gross_amount += source.gross_amount ?? 0;
588
+ target.discount_amount += source.discount_amount ?? 0;
589
+ target.discount_by_type.special_discount += source.discount_by_type?.special_discount ?? 0;
590
+ target.discount_by_type.loyalty_discount += source.discount_by_type?.loyalty_discount ?? 0;
591
+ target.discount_by_type.voucher_discount += source.discount_by_type?.voucher_discount ?? 0;
592
+ target.gst_amount += source.gst_amount ?? 0;
593
+ target.tax_amount += source.tax_amount ?? 0;
594
+ target.tip_amount += source.tip_amount ?? 0;
595
+ target.tax_invoice_provider_charges += source.tax_invoice_provider_charges ?? 0;
596
+ target.delivery_charges += source.delivery_charges ?? 0;
597
+ };
598
+ const sumPayments = (target, source) => {
599
+ for (const payment of source ?? []) {
600
+ if (target[payment.payment_type] == null) {
601
+ target[payment.payment_type] = { ...payment };
602
+ continue;
603
+ }
604
+ const entry = target[payment.payment_type];
605
+ entry.count += payment.count ?? 0;
606
+ entry.gross_amount += payment.gross_amount ?? 0;
607
+ entry.amount_due += payment.amount_due ?? 0;
608
+ entry.amount_paid += payment.amount_paid ?? 0;
609
+ entry.amount_refunded += payment.amount_refunded ?? 0;
610
+ entry.card_charges += payment.card_charges ?? 0;
611
+ }
612
+ };
613
+ const subtractOrderMetrics = (target, source) => {
614
+ target.count -= source.count ?? 0;
615
+ target.gross_amount -= source.gross_amount ?? 0;
616
+ target.discount_amount -= source.discount_amount ?? 0;
617
+ target.discount_by_type.special_discount -= source.discount_by_type?.special_discount ?? 0;
618
+ target.discount_by_type.loyalty_discount -= source.discount_by_type?.loyalty_discount ?? 0;
619
+ target.discount_by_type.voucher_discount -= source.discount_by_type?.voucher_discount ?? 0;
620
+ target.gst_amount -= source.gst_amount ?? 0;
621
+ target.tax_amount -= source.tax_amount ?? 0;
622
+ target.tip_amount -= source.tip_amount ?? 0;
623
+ target.tax_invoice_provider_charges -= source.tax_invoice_provider_charges ?? 0;
624
+ target.delivery_charges -= source.delivery_charges ?? 0;
625
+ };
626
+ const subtractPayments = (target, source) => {
627
+ for (const payment of source ?? []) {
628
+ const entry = target[payment.payment_type];
629
+ if (entry == null)
630
+ continue;
631
+ entry.count -= payment.count ?? 0;
632
+ entry.gross_amount -= payment.gross_amount ?? 0;
633
+ entry.amount_due -= payment.amount_due ?? 0;
634
+ entry.amount_paid -= payment.amount_paid ?? 0;
635
+ entry.amount_refunded -= payment.amount_refunded ?? 0;
636
+ entry.card_charges -= payment.card_charges ?? 0;
637
+ if (entry.count <= 0)
638
+ delete target[payment.payment_type];
639
+ }
640
+ };
641
+ /** Removes bills by `(order_id, payment_id)` — the subtraction primitive. */
642
+ const subtractBillsByKey = (bills, removed) => {
643
+ const removedKeys = new Set(removed.map((bill) => `${bill.order_id}|${bill.payment_id}`));
644
+ return bills.filter((bill) => !removedKeys.has(`${bill.order_id}|${bill.payment_id}`));
645
+ };
646
+ /** Same tenant / brand / schema version / key filters — reports that may merge. */
647
+ const canMergeMaterializedReports = (base, other) => base.tenant_id === other.tenant_id &&
648
+ base.brand_id === other.brand_id &&
649
+ base.schema_version === other.schema_version &&
650
+ base.sale_type_key_filters.join(':') === other.sale_type_key_filters.join(':');
651
+ /** Sums one report's metric tree into a mutable accumulator. */
652
+ const applyReportAddition = (metrics, report) => {
653
+ for (const [key, metric] of Object.entries(normalizeMaterializedSaleTypeMetrics(report.sale_type_metrics))) {
654
+ const target = getOrCreateKeyMetrics(metrics, key);
655
+ sumOrderMetrics(target[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders, metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders);
656
+ sumPayments(target[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments, metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments);
657
+ sumOrderMetrics(target[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders, metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders);
658
+ sumPayments(target[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments, metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments);
659
+ target[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills.push(...(metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills ?? []).map((bill) => ({ ...bill })));
660
+ target[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills.push(...(metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills ?? []).map((bill) => ({ ...bill })));
661
+ }
662
+ };
663
+ /** Subtracts one report's metric tree from a mutable accumulator. */
664
+ const applyReportSubtraction = (metrics, report) => {
665
+ for (const [key, metric] of Object.entries(normalizeMaterializedSaleTypeMetrics(report.sale_type_metrics))) {
666
+ const target = metrics[key];
667
+ if (target == null)
668
+ continue;
669
+ subtractOrderMetrics(target[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders, metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders);
670
+ subtractPayments(target[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments, metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments);
671
+ subtractOrderMetrics(target[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders, metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders);
672
+ subtractPayments(target[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments, metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments);
673
+ target[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills = subtractBillsByKey(target[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills, metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills ?? []);
674
+ target[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills = subtractBillsByKey(target[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills, metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills ?? []);
675
+ }
676
+ };
677
+ const dedupeIssuedBills = (bills) => {
678
+ const byBill = new Map();
679
+ for (const bill of bills) {
680
+ const billKey = `${bill.order_id}|${bill.payment_id}`;
681
+ const existing = byBill.get(billKey);
682
+ if (existing == null) {
683
+ byBill.set(billKey, { ...bill });
684
+ continue;
685
+ }
686
+ // Same bill compiled twice (overlapping scopes): keep the most-collected state.
687
+ existing.received_amount = Math.max(existing.received_amount ?? 0, bill.received_amount ?? 0);
688
+ existing.settled_at = existing.settled_at ?? bill.settled_at;
689
+ existing.credit_note = existing.credit_note ?? bill.credit_note;
690
+ }
691
+ return [...byBill.values()];
692
+ };
693
+ const dedupeReceivedBills = (bills) => {
694
+ const byBill = new Map();
695
+ for (const bill of bills) {
696
+ const billKey = `${bill.order_id}|${bill.payment_id}`;
697
+ const existing = byBill.get(billKey);
698
+ if (existing == null) {
699
+ byBill.set(billKey, { ...bill });
700
+ continue;
701
+ }
702
+ existing.received_amount = Math.max(existing.received_amount ?? 0, bill.received_amount ?? 0);
703
+ existing.credit_note = existing.credit_note ?? bill.credit_note;
704
+ existing.settled_at = existing.settled_at ?? bill.settled_at;
705
+ }
706
+ return [...byBill.values()];
707
+ };
708
+ /** De-duplicates both bill ledgers of every key (overlapping compiles). */
709
+ const dedupeAllBillLedgers = (metrics) => {
710
+ for (const metric of Object.values(metrics)) {
711
+ metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills = dedupeIssuedBills(metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills);
712
+ metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills = dedupeReceivedBills(metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills);
713
+ }
714
+ };
715
+ /**
716
+ * Sums materialized reports that share the same tenant, brand, key filters and
717
+ * `schema_version` — the period accumulation path. The scope MAY differ: pass
718
+ * the period document (month / quarter / year …) FIRST so the result keeps its
719
+ * identity while day documents are accumulated into it.
720
+ *
721
+ * Metric trees are summed per key; credit-bill bills are concatenated and
722
+ * de-duplicated by `(order_id, payment_id)` keeping the most-collected state,
723
+ * then all ledger counters are recomputed from the itemized bills — so
724
+ * overlapping compiles never double-count.
725
+ *
726
+ * Returns `null` (never throws) when the inputs cannot be summed — empty list
727
+ * or mismatched tenant / brand / schema version / key filters. `null` means a
728
+ * data issue the caller must surface.
729
+ */
730
+ function sumMaterializedTenantSalesOverviewReports(reports, options = {}) {
731
+ if (!Array.isArray(reports) || reports.length === 0) {
732
+ return null;
733
+ }
734
+ const [base, ...rest] = reports;
735
+ for (const report of rest) {
736
+ if (!canMergeMaterializedReports(base, report)) {
737
+ return null;
738
+ }
739
+ }
740
+ const metrics = {};
741
+ for (const report of reports) {
742
+ applyReportAddition(metrics, report);
743
+ }
744
+ dedupeAllBillLedgers(metrics);
745
+ const computedAt = options.computedAt ?? new Date();
746
+ const watermark = reports.reduce((latest, report) => {
747
+ const reportWatermark = new Date(report.source_watermark ?? 0);
748
+ return reportWatermark.getTime() > latest.getTime() ? reportWatermark : latest;
749
+ }, new Date(0));
750
+ return {
751
+ ...base,
752
+ day_index: base.day_index ?? null,
753
+ sale_type_metrics: finalizeMetrics(metrics),
754
+ source_watermark: watermark,
755
+ computed_at: computedAt,
756
+ updatedAt: computedAt,
757
+ };
758
+ }
759
+ /**
760
+ * Subtracts `subtrahend`'s metric tree from `minuend` — the first half of the
761
+ * reconcile/retry flow
762
+ * (`update(periodDoc, { subtract: [previousDayDoc], additions: [newDayDoc] })`):
763
+ * the stored `localDate` doc of day D IS the delta previously folded into the
764
+ * period docs.
765
+ *
766
+ * Bills are removed by `(order_id, payment_id)`; ledger counters are recomputed
767
+ * from the remaining bills. Returns `null` (never throws) on mismatched inputs.
768
+ */
769
+ function subtractMaterializedTenantSalesOverviewReports(minuend, subtrahend) {
770
+ if (minuend == null || subtrahend == null || !canMergeMaterializedReports(minuend, subtrahend)) {
771
+ return null;
772
+ }
773
+ const metrics = toMutableMetrics(minuend.sale_type_metrics);
774
+ applyReportSubtraction(metrics, subtrahend);
775
+ return { ...minuend, sale_type_metrics: finalizeMetrics(metrics) };
776
+ }
777
+ /**
778
+ * Versioned write on an existing JSON report (never throws; `null` on
779
+ * mismatched inputs) — the single place that mutates a stored document:
780
+ *
781
+ * 1. metrics: `replacement` swaps the tree wholesale (day/hour docs);
782
+ * otherwise `subtract` first (previously applied deltas), then `additions`
783
+ * (newly calculated ones) — the reconcile/retry pattern;
784
+ * 2. `received_payments` patches matching `issued` bills (`received_amount`
785
+ * cumulative, `credit_note`, `settled_at` — the received entry's true
786
+ * collection timestamp, falling back to `computedAt`, stamped when
787
+ * `received_amount >= amount`);
788
+ * 3. versioning: metric writes (`replacement` / `subtract` / `additions`) AND
789
+ * received-payment patches that change the ledger bump `iteration` — the
790
+ * returned document is recorded as a `materialized_tenant_reports_iterations`
791
+ * row by the caller (`buildMaterializedTenantReportIteration`); no-op
792
+ * patches bump nothing, so replays stay churn-free;
793
+ * 4. `source_watermark` advances to the max of the existing and the incoming
794
+ * (`replacement` / `additions`) watermarks — monotonic, never regressed
795
+ * (rollbacks / replays keep the previously folded maximum).
796
+ *
797
+ * Returns a new JSON report; the input is not mutated.
798
+ */
799
+ function updateMaterializedTenantSalesOverviewReport(existing, updates, options = {}) {
800
+ const computedAt = options.computedAt ?? new Date();
801
+ const subtract = updates.subtract ?? [];
802
+ const additions = updates.additions ?? [];
803
+ const receivedPayments = updates.received_payments ?? [];
804
+ const hasMetricsUpdate = updates.replacement != null || subtract.length > 0 || additions.length > 0;
805
+ if (!hasMetricsUpdate && receivedPayments.length === 0) {
806
+ return cloneReport(existing);
807
+ }
808
+ let metrics;
809
+ let sourceWatermark = existing.source_watermark;
810
+ if (updates.replacement != null) {
811
+ if (!canMergeMaterializedReports(existing, updates.replacement))
812
+ return null;
813
+ metrics = toMutableMetrics(updates.replacement.sale_type_metrics);
814
+ }
815
+ else {
816
+ metrics = toMutableMetrics(existing.sale_type_metrics);
817
+ for (const delta of subtract) {
818
+ if (!canMergeMaterializedReports(existing, delta))
819
+ return null;
820
+ applyReportSubtraction(metrics, delta);
821
+ }
822
+ for (const delta of additions) {
823
+ if (!canMergeMaterializedReports(existing, delta))
824
+ return null;
825
+ applyReportAddition(metrics, delta);
826
+ }
827
+ dedupeAllBillLedgers(metrics);
828
+ }
829
+ let ledgerPatched = false;
830
+ for (const collected of receivedPayments) {
831
+ for (const keyMetrics of Object.values(metrics)) {
832
+ for (const bill of keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills) {
833
+ if (bill.order_id !== collected.order_id || bill.payment_id !== collected.payment_id)
834
+ continue;
835
+ const nextReceived = Math.max(bill.received_amount ?? 0, collected.received_amount ?? 0);
836
+ const nextNote = bill.credit_note ?? collected.credit_note;
837
+ let nextSettledAt = bill.settled_at ?? null;
838
+ if (bill.settled_at == null && nextReceived >= bill.amount) {
839
+ // Prefer the true collection timestamp carried by the received entry.
840
+ nextSettledAt = collected.settled_at ?? computedAt;
841
+ }
842
+ if (nextReceived !== (bill.received_amount ?? 0) ||
843
+ (nextSettledAt?.getTime() ?? null) !== (bill.settled_at?.getTime() ?? null) ||
844
+ (nextNote ?? null) !== (bill.credit_note ?? null)) {
845
+ ledgerPatched = true;
846
+ }
847
+ bill.received_amount = nextReceived;
848
+ bill.credit_note = nextNote;
849
+ bill.settled_at = nextSettledAt;
850
+ }
851
+ }
852
+ }
853
+ // The watermark is monotonic ("max source `updatedAt` folded so far"):
854
+ // structural writes only ever advance it — never regress it.
855
+ const watermarkSources = updates.replacement != null ? [updates.replacement] : additions;
856
+ for (const source of watermarkSources) {
857
+ if (source?.source_watermark == null)
858
+ continue;
859
+ const incomingTime = new Date(source.source_watermark).getTime();
860
+ if (!Number.isNaN(incomingTime) && incomingTime > new Date(sourceWatermark).getTime()) {
861
+ sourceWatermark = source.source_watermark;
862
+ }
863
+ }
864
+ return {
865
+ ...existing,
866
+ sale_type_metrics: finalizeMetrics(metrics),
867
+ // Version metric writes AND ledger-changing received-payment patches (both
868
+ // append a history row via the caller). No-op patches bump nothing, so
869
+ // replays stay churn-free.
870
+ iteration: hasMetricsUpdate || ledgerPatched ? (existing.iteration ?? 1) + 1 : (existing.iteration ?? 1),
871
+ source_watermark: sourceWatermark,
872
+ computed_at: computedAt,
873
+ updatedAt: computedAt,
874
+ };
875
+ }