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