@managesome/eposmatic-toolkit 0.4.7 → 0.4.9

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 (54) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +33 -0
  2. package/esm/constants/enums/communications.js +1 -0
  3. package/esm/helpers/materialized-reports/index.js +1 -0
  4. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +982 -0
  5. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +276 -33
  6. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +327 -41
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +118 -235
  9. package/esm/schemas/models/index.js +1 -0
  10. package/esm/schemas/models/materialized_credit_bills.js +265 -0
  11. package/esm/schemas/models/materialized_tenant_reports_iterations.js +13 -0
  12. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +39 -97
  13. package/esm/schemas/types/index.js +1 -0
  14. package/esm/schemas/types/materialized_credit_bills.js +1 -0
  15. package/lib/constants/MATERIALIZED_REPORTS.d.ts +28 -2
  16. package/lib/constants/MATERIALIZED_REPORTS.js +34 -1
  17. package/lib/constants/enums/communications.d.ts +1 -0
  18. package/lib/constants/enums/communications.js +2 -1
  19. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  20. package/lib/helpers/materialized-reports/index.js +1 -0
  21. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +307 -0
  22. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +1003 -0
  23. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +36 -2
  24. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +278 -34
  25. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +66 -8
  26. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +326 -40
  27. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +18 -2
  28. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  29. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +46 -37
  30. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +119 -238
  31. package/lib/helpers/types/materialized-reports-apis.d.ts +32 -5
  32. package/lib/schemas/models/index.d.ts +1 -0
  33. package/lib/schemas/models/index.js +1 -0
  34. package/lib/schemas/models/materialized_credit_bills.d.ts +337 -0
  35. package/lib/schemas/models/materialized_credit_bills.js +268 -0
  36. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +20 -6
  37. package/lib/schemas/models/materialized_tenant_reports_iterations.js +14 -1
  38. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +37 -165
  39. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +40 -98
  40. package/lib/schemas/types/index.d.ts +1 -0
  41. package/lib/schemas/types/index.js +1 -0
  42. package/lib/schemas/types/materialized_credit_bills.d.ts +139 -0
  43. package/lib/schemas/types/materialized_credit_bills.js +2 -0
  44. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +32 -77
  45. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.d.ts +1 -0
  46. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +715 -0
  47. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +96 -0
  48. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +9 -0
  49. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +23 -24
  50. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +327 -22
  51. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +27 -2
  52. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +12 -27
  53. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +79 -146
  54. package/package.json +1 -1
@@ -2,8 +2,8 @@ import mongoose from 'mongoose';
2
2
  import { PAYMENT_STATUS_ENUM, PAYMENT_TYPE_ENUM, REPORT_SALE_TYPE_ENUM } from '../../constants';
3
3
  import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX, SALES_OVERVIEW_KEY_FILTERS, } from '../../constants/MATERIALIZED_REPORTS';
4
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
5
  import { buildMaterializedReportKey } from './key-helpers';
6
+ import { buildCreditBillEventCandidatesFromOrder, buildCreditBillIssuedCandidatesFromOrder, isMaterializedCreditBillPayment, resolveOrderLocalHour, resolveReceivedLocalHour, } from './materialized-credit-bills-helpers';
7
7
  import { getDayIndexFromLocalDate, getMaterializedHourScopeField, getMaterializedPeriodScopeFields, parseMaterializedLocalDate, } from './scope-helpers';
8
8
  /* ------------------------------------------------------------------------ */
9
9
  /* Payment rules (twin of `sales-overview-reference.ts`) */
@@ -43,10 +43,9 @@ export function getMaterializedPaymentGross(payment) {
43
43
  }
44
44
  return -(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
45
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
- }
46
+ // `isMaterializedCreditBillPayment` moved to `./materialized-credit-bills-helpers`
47
+ // (imported above) — re-exported here for API stability.
48
+ export { isMaterializedCreditBillPayment };
50
49
  const createEmptyOrderMetric = () => ({
51
50
  count: 0,
52
51
  gross_amount: 0,
@@ -65,7 +64,10 @@ const createEmptySaleTypeMetric = () => ({
65
64
  const createEmptyKeyMetrics = () => ({
66
65
  [REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: createEmptySaleTypeMetric(),
67
66
  [REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]: createEmptySaleTypeMetric(),
68
- [REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: { issued: { bills: [] }, received: { bills: [] } },
67
+ [REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: {
68
+ issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
69
+ received: { count: 0, amount: 0 },
70
+ },
69
71
  });
70
72
  function getOrCreateKeyMetrics(metrics, key) {
71
73
  if (metrics[key] == null) {
@@ -89,10 +91,15 @@ function accumulateOrderIntoOrderMetric(metric, order) {
89
91
  metric.tax_invoice_provider_charges += order.tax_invoice_provider_charges ?? 0;
90
92
  metric.delivery_charges += order.delivery_details?.delivery_cost ?? 0;
91
93
  }
92
- function accumulateOrderPayments(metric, order) {
94
+ function accumulateOrderPayments(metric, order, options = {}) {
93
95
  for (const payment of order.payments ?? []) {
94
96
  if (!isPaymentIncludedInMaterializedSalesOverview(payment))
95
97
  continue;
98
+ // PAY_LATER money is represented by the CREDIT_BILLS ledger (issued +
99
+ // receipt events) and the derived CREDIT_SETTLEMENT line — when excluded,
100
+ // it must never also feed the collected-payments buckets (F7).
101
+ if (options.excludeCreditBills === true && isMaterializedCreditBillPayment(payment))
102
+ continue;
96
103
  const paymentType = normalizeMaterializedPaymentType(payment.payment_type);
97
104
  if (metric.payments[paymentType] == null) {
98
105
  metric.payments[paymentType] = {
@@ -120,8 +127,17 @@ function accumulateOrder(metrics, key, order) {
120
127
  accumulateOrderIntoOrderMetric(keyMetrics[REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders, order);
121
128
  accumulateOrderPayments(keyMetrics[REPORT_SALE_TYPE_ENUM.TOTAL_SALES], order);
122
129
  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);
130
+ // F7: money collected against a PAY_LATER bill (the receipt events) must
131
+ // never appear BOTH here and in the credit-bill ledger — a re-close of
132
+ // the issue day with the now-settled order would otherwise add it to
133
+ // this slot again (backfilled history must equal incremental history).
134
+ // The slot counts collected money EXCLUDING credit receipts and its
135
+ // payment rows skip PAY_LATER entirely.
136
+ const collectedCreditBills = (order.payments ?? []).reduce((sum, payment) => (isMaterializedCreditBillPayment(payment) ? sum + (payment.amount_paid ?? 0) : sum), 0);
137
+ if ((order.amount_collected ?? 0) - collectedCreditBills > 0) {
138
+ accumulateOrderIntoOrderMetric(keyMetrics[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders, order);
139
+ accumulateOrderPayments(keyMetrics[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED], order, { excludeCreditBills: true });
140
+ }
125
141
  }
126
142
  }
127
143
  /* ------------------------------------------------------------------------ */
@@ -144,85 +160,18 @@ function accumulateOrder(metrics, key, order) {
144
160
  * Bills are keyed by `payment_id` (fallback: the payment subdocument `_id`);
145
161
  * a `PAY_LATER` payment carrying neither is a data issue → `null` (the
146
162
  * ledger's `(order_id, payment_id)` keys must never collapse).
163
+ *
164
+ * `received_at_issue` = what the payment had received when the compiled day
165
+ * closed (the true at-issue value on a FIRST close; the close-day plan
166
+ * carries the stored value forward on re-closes, so a re-close after
167
+ * collection can never re-anchor it).
147
168
  */
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
169
  /* ------------------------------------------------------------------------ */
204
170
  /* Serialization */
205
171
  /* ------------------------------------------------------------------------ */
206
172
  function sumNumbers(values) {
207
173
  return values.reduce((total, value) => total + (value ?? 0), 0);
208
174
  }
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
175
  function finalizeSaleTypeMetric(metric) {
227
176
  const payments = Object.values(metric.payments).sort((a, b) => b.count - a.count || a.payment_type.localeCompare(b.payment_type));
228
177
  return { orders: metric.orders, payments };
@@ -234,8 +183,8 @@ function finalizeMetrics(metrics) {
234
183
  [REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: finalizeSaleTypeMetric(metric[REPORT_SALE_TYPE_ENUM.TOTAL_SALES]),
235
184
  [REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]: finalizeSaleTypeMetric(metric[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]),
236
185
  [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),
186
+ issued: { ...metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued },
187
+ received: { ...metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received },
239
188
  },
240
189
  };
241
190
  }
@@ -278,8 +227,12 @@ const pruneZeroReportKeys = (metrics) => {
278
227
  totalSales.payments.every(isZeroPaymentMetric) &&
279
228
  isZeroOrderReportMetric(amountCollected.orders) &&
280
229
  (amountCollected.payments ?? []).every(isZeroPaymentMetric) &&
281
- creditBills.issued.bills.length === 0 &&
282
- creditBills.received.bills.length === 0;
230
+ isZeroNumber(creditBills.issued.count) &&
231
+ isZeroNumber(creditBills.issued.amount) &&
232
+ isZeroNumber(creditBills.issued.settled_count) &&
233
+ isZeroNumber(creditBills.issued.settled_amount) &&
234
+ isZeroNumber(creditBills.received.count) &&
235
+ isZeroNumber(creditBills.received.amount);
283
236
  if (!isZero)
284
237
  pruned[key] = metric;
285
238
  }
@@ -326,7 +279,7 @@ export function normalizeMaterializedSaleTypeMetrics(metrics) {
326
279
  }
327
280
  return normalized;
328
281
  }
329
- /** JSON report → mutable accumulator tree (bills / payments cloned). */
282
+ /** JSON report → mutable accumulator tree (counters / payments cloned). */
330
283
  function toMutableMetrics(metrics) {
331
284
  const mutable = {};
332
285
  for (const [key, metric] of Object.entries(normalizeMaterializedSaleTypeMetrics(metrics))) {
@@ -352,10 +305,8 @@ function toMutableMetrics(metrics) {
352
305
  ])),
353
306
  },
354
307
  [REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: {
355
- issued: { bills: (metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills ?? []).map((bill) => ({ ...bill })) },
356
- received: {
357
- bills: (metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills ?? []).map((bill) => ({ ...bill })),
358
- },
308
+ issued: { ...metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued },
309
+ received: { ...metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received },
359
310
  },
360
311
  };
361
312
  }
@@ -368,45 +319,6 @@ function cloneReport(report) {
368
319
  /* ------------------------------------------------------------------------ */
369
320
  /* 1. Orders → JSON documents */
370
321
  /* ------------------------------------------------------------------------ */
371
- const resolveOrderLocalHour = (order, localDate, gmtOffset) => {
372
- if (typeof order.localHour === 'number' && order.localHour >= 0 && order.localHour <= 23) {
373
- return order.localHour;
374
- }
375
- if (typeof gmtOffset === 'number') {
376
- const fields = getLocalFieldsFromLocalDate(order.localDate ?? localDate, gmtOffset, order.order_settled_at ?? order.createdAt);
377
- return fields.localHour;
378
- }
379
- if (typeof order.order_settled_at_mins === 'number' && order.order_settled_at_mins >= 0) {
380
- return Math.min(23, Math.floor(order.order_settled_at_mins / 60));
381
- }
382
- return null;
383
- };
384
- /**
385
- * Hour bucket of a credit-bill COLLECTION event (an earlier-day order settling
386
- * on the compiled day): the SETTLEMENT anchor resolves the hour — never the
387
- * punch hour, so hour views / the derived credit-settlement line sit at the
388
- * moment the money was collected. Chain: `gmtOffset` + `order_settled_at`
389
- * (tenant-local hour) → `order_settled_at_mins ÷ 60` → the settlement
390
- * timestamp's UTC hour (the mins convention is UTC-based too) → punch-hour
391
- * fallback (last resort).
392
- */
393
- const resolveReceivedLocalHour = (order, localDate, gmtOffset) => {
394
- if (typeof gmtOffset === 'number' && order.order_settled_at != null) {
395
- const settledAt = new Date(order.order_settled_at);
396
- if (!Number.isNaN(settledAt.getTime()))
397
- return getLocalDocumentFields(gmtOffset, settledAt).localHour;
398
- }
399
- if (typeof order.order_settled_at_mins === 'number' && order.order_settled_at_mins >= 0) {
400
- return Math.min(23, Math.floor(order.order_settled_at_mins / 60));
401
- }
402
- // Still settlement-anchored (the mins convention above is UTC-based too).
403
- if (order.order_settled_at != null) {
404
- const settledUtc = new Date(order.order_settled_at);
405
- if (!Number.isNaN(settledUtc.getTime()))
406
- return settledUtc.getUTCHours();
407
- }
408
- return resolveOrderLocalHour(order, localDate, gmtOffset);
409
- };
410
322
  const createEmptyReportDocument = (args) => {
411
323
  const { tenantId, brandId, scopeContext, scopeField, now } = args;
412
324
  const dayIndex = MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext)
@@ -458,12 +370,13 @@ export function convertOrdersToMaterializedTenantSalesOverviewReports(localDate,
458
370
  const tenantIds = Array.from(new Set((orders ?? []).map((order) => order.tenant_id)));
459
371
  if (tenantIds.length === 0) {
460
372
  if (options.tenantId == null) {
461
- return { materializedReports: [], received_payments: [] };
373
+ return { materializedReports: [], credit_bill_issues: [], credit_bill_events: [] };
462
374
  }
463
375
  tenantIds.push(options.tenantId);
464
376
  }
465
377
  const materializedReports = [];
466
- const receivedPayments = [];
378
+ const creditBillIssues = [];
379
+ const creditEventCandidates = [];
467
380
  const periodScopeFields = getMaterializedPeriodScopeFields(localDate);
468
381
  if (periodScopeFields == null)
469
382
  return null;
@@ -478,13 +391,7 @@ export function convertOrdersToMaterializedTenantSalesOverviewReports(localDate,
478
391
  continue; // live facets materialize `is_deleted: false` only
479
392
  const orderLocalDate = order.localDate ?? localDate;
480
393
  if (orderLocalDate !== localDate) {
481
- const collected = buildReceivedCreditBills(order, orderLocalDate);
482
- if (collected == null)
483
- return null; // un-keyable bill — data issue
484
- if (collected.length > 0) {
485
- receivedEntries.push({ order, orderLocalDate });
486
- receivedPayments.push(...collected);
487
- }
394
+ receivedEntries.push({ order, orderLocalDate });
488
395
  continue;
489
396
  }
490
397
  salesOrders.push(order);
@@ -549,29 +456,49 @@ export function convertOrdersToMaterializedTenantSalesOverviewReports(localDate,
549
456
  for (const target of targets) {
550
457
  accumulateOrder(target.metrics, key, order);
551
458
  }
552
- const issuedBills = buildIssuedCreditBills(order, now);
553
- if (issuedBills == null)
459
+ const issuedCandidates = buildCreditBillIssuedCandidatesFromOrder(order, localDate, {
460
+ now,
461
+ gmtOffset: options.gmtOffset,
462
+ });
463
+ if (issuedCandidates == null)
554
464
  return null; // un-keyable bill — data issue
555
- if (issuedBills.length > 0) {
465
+ if (issuedCandidates.length > 0) {
466
+ creditBillIssues.push(...issuedCandidates);
556
467
  for (const target of targets) {
557
- const keyMetrics = getOrCreateKeyMetrics(target.metrics, key);
558
- keyMetrics[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills.push(...issuedBills.map((bill) => ({ ...bill })));
468
+ const credit = getOrCreateKeyMetrics(target.metrics, key)[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
469
+ for (const candidate of issuedCandidates) {
470
+ credit.issued.count += 1;
471
+ credit.issued.amount += candidate.amount;
472
+ if (candidate.settled_at != null) {
473
+ credit.issued.settled_count += 1;
474
+ credit.issued.settled_amount += candidate.amount;
475
+ }
476
+ }
559
477
  }
560
478
  }
561
479
  }
562
480
  for (const { order } of receivedEntries) {
563
- const collected = buildReceivedCreditBills(order, order.localDate ?? localDate);
564
- if (collected == null)
481
+ const candidates = buildCreditBillEventCandidatesFromOrder(order, localDate, {
482
+ now,
483
+ gmtOffset: options.gmtOffset,
484
+ });
485
+ if (candidates == null)
565
486
  return null; // un-keyable bill — data issue
566
- if (collected.length === 0)
487
+ if (candidates.length === 0)
567
488
  continue;
489
+ creditEventCandidates.push(...candidates);
568
490
  const key = buildMaterializedReportKey([order.order_status, order.platform]);
569
491
  if (key == null)
570
492
  return null; // un-keyable order fields — data issue
493
+ // The key must exist on the collection day's scopes even before the
494
+ // close-day plan resolves the receipt deltas (it fills the `received`
495
+ // AMOUNT later); `getOrCreateKeyMetrics` keeps the key alive through
496
+ // the planner's zero-pruning until then. The event COUNT is
497
+ // order-pure — the compile counts it now, resolution only prices it.
571
498
  const targets = targetsForHour(receivedHours.get(order) ?? null);
572
499
  for (const target of targets) {
573
- const keyMetrics = getOrCreateKeyMetrics(target.metrics, key);
574
- keyMetrics[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills.push(...collected.map((bill) => ({ ...bill })));
500
+ const credit = getOrCreateKeyMetrics(target.metrics, key)[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
501
+ credit.received.count += candidates.length;
575
502
  }
576
503
  }
577
504
  // `source_watermark` = max `order.updatedAt` folded in; a day with no
@@ -587,7 +514,7 @@ export function convertOrdersToMaterializedTenantSalesOverviewReports(localDate,
587
514
  materializedReports.push(doc);
588
515
  }
589
516
  }
590
- return { materializedReports, received_payments: receivedPayments };
517
+ return { materializedReports, credit_bill_issues: creditBillIssues, credit_bill_events: creditEventCandidates };
591
518
  }
592
519
  /* ------------------------------------------------------------------------ */
593
520
  /* 2. JSON → BSON (mongoose document) */
@@ -667,10 +594,23 @@ const subtractPayments = (target, source) => {
667
594
  delete target[payment.payment_type];
668
595
  }
669
596
  };
670
- /** Removes bills by `(order_id, payment_id)` — the subtraction primitive. */
671
- const subtractBillsByKey = (bills, removed) => {
672
- const removedKeys = new Set(removed.map((bill) => `${bill.order_id}|${bill.payment_id}`));
673
- return bills.filter((bill) => !removedKeys.has(`${bill.order_id}|${bill.payment_id}`));
597
+ /** Sums credit-bill COUNTERS (numbers only — documents hold no bill rows). */
598
+ const sumCreditBillCounters = (target, source) => {
599
+ target.issued.count += source.issued?.count ?? 0;
600
+ target.issued.amount += source.issued?.amount ?? 0;
601
+ target.issued.settled_count += source.issued?.settled_count ?? 0;
602
+ target.issued.settled_amount += source.issued?.settled_amount ?? 0;
603
+ target.received.count += source.received?.count ?? 0;
604
+ target.received.amount += source.received?.amount ?? 0;
605
+ };
606
+ /** Subtracts credit-bill COUNTERS (numbers only — documents hold no bill rows). */
607
+ const subtractCreditBillCounters = (target, source) => {
608
+ target.issued.count -= source.issued?.count ?? 0;
609
+ target.issued.amount -= source.issued?.amount ?? 0;
610
+ target.issued.settled_count -= source.issued?.settled_count ?? 0;
611
+ target.issued.settled_amount -= source.issued?.settled_amount ?? 0;
612
+ target.received.count -= source.received?.count ?? 0;
613
+ target.received.amount -= source.received?.amount ?? 0;
674
614
  };
675
615
  /** Same tenant / brand / schema version / key filters — reports that may merge. */
676
616
  const canMergeMaterializedReports = (base, other) => base.tenant_id === other.tenant_id &&
@@ -693,8 +633,7 @@ const applyReportAddition = (metrics, report) => {
693
633
  sumPayments(target[REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments, metric[REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments);
694
634
  sumOrderMetrics(target[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders, metric[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders);
695
635
  sumPayments(target[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments, metric[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments);
696
- target[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills.push(...(metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills ?? []).map((bill) => ({ ...bill })));
697
- target[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills.push(...(metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills ?? []).map((bill) => ({ ...bill })));
636
+ sumCreditBillCounters(target[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS], metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]);
698
637
  }
699
638
  };
700
639
  /** Subtracts one report's metric tree from a mutable accumulator. */
@@ -707,46 +646,7 @@ const applyReportSubtraction = (metrics, report) => {
707
646
  subtractPayments(target[REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments, metric[REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments);
708
647
  subtractOrderMetrics(target[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders, metric[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders);
709
648
  subtractPayments(target[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments, metric[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments);
710
- 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 ?? []);
711
- 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 ?? []);
712
- }
713
- };
714
- const dedupeIssuedBills = (bills) => {
715
- const byBill = new Map();
716
- for (const bill of bills) {
717
- const billKey = `${bill.order_id}|${bill.payment_id}`;
718
- const existing = byBill.get(billKey);
719
- if (existing == null) {
720
- byBill.set(billKey, { ...bill });
721
- continue;
722
- }
723
- // Same bill compiled twice (overlapping scopes): keep the most-collected state.
724
- existing.received_amount = Math.max(existing.received_amount ?? 0, bill.received_amount ?? 0);
725
- existing.settled_at = existing.settled_at ?? bill.settled_at;
726
- existing.credit_note = existing.credit_note ?? bill.credit_note;
727
- }
728
- return [...byBill.values()];
729
- };
730
- const dedupeReceivedBills = (bills) => {
731
- const byBill = new Map();
732
- for (const bill of bills) {
733
- const billKey = `${bill.order_id}|${bill.payment_id}`;
734
- const existing = byBill.get(billKey);
735
- if (existing == null) {
736
- byBill.set(billKey, { ...bill });
737
- continue;
738
- }
739
- existing.received_amount = Math.max(existing.received_amount ?? 0, bill.received_amount ?? 0);
740
- existing.credit_note = existing.credit_note ?? bill.credit_note;
741
- existing.settled_at = existing.settled_at ?? bill.settled_at;
742
- }
743
- return [...byBill.values()];
744
- };
745
- /** De-duplicates both bill ledgers of every key (overlapping compiles). */
746
- const dedupeAllBillLedgers = (metrics) => {
747
- for (const metric of Object.values(metrics)) {
748
- metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills = dedupeIssuedBills(metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills);
749
- metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills = dedupeReceivedBills(metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills);
649
+ subtractCreditBillCounters(target[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS], metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]);
750
650
  }
751
651
  };
752
652
  /**
@@ -755,10 +655,9 @@ const dedupeAllBillLedgers = (metrics) => {
755
655
  * the period document (month / quarter / year …) FIRST so the result keeps its
756
656
  * identity while day documents are accumulated into it.
757
657
  *
758
- * Metric trees are summed per key; credit-bill bills are concatenated and
759
- * de-duplicated by `(order_id, payment_id)` keeping the most-collected state,
760
- * then all ledger counters are recomputed from the itemized bills — so
761
- * overlapping compiles never double-count.
658
+ * Metric trees are summed per key — including the credit-bill COUNTERS
659
+ * (`issued` / `settled` / `received` numbers; the itemized ledger lives in
660
+ * `materialized_tenant_credit_bills` and is not part of these documents).
762
661
  *
763
662
  * Returns `null` (never throws) when the inputs cannot be summed — empty list
764
663
  * or mismatched tenant / brand / schema version / key filters. `null` means a
@@ -784,7 +683,6 @@ export function sumMaterializedTenantSalesOverviewReports(reports, options = {})
784
683
  for (const report of reports) {
785
684
  applyReportAddition(metrics, report);
786
685
  }
787
- dedupeAllBillLedgers(metrics);
788
686
  const computedAt = options.computedAt ?? new Date();
789
687
  const watermark = reports.reduce((latest, report) => {
790
688
  const reportWatermark = new Date(report.source_watermark ?? 0);
@@ -806,8 +704,9 @@ export function sumMaterializedTenantSalesOverviewReports(reports, options = {})
806
704
  * the stored `localDate` doc of day D IS the delta previously folded into the
807
705
  * period docs.
808
706
  *
809
- * Bills are removed by `(order_id, payment_id)`; ledger counters are recomputed
810
- * from the remaining bills. Returns `null` (never throws) on mismatched inputs.
707
+ * Credit-bill counters are subtracted numerically (numbers only — these
708
+ * documents carry no bill rows). Returns `null` (never throws) on mismatched
709
+ * inputs.
811
710
  */
812
711
  export function subtractMaterializedTenantSalesOverviewReports(minuend, subtrahend) {
813
712
  if (minuend == null || subtrahend == null || !canMergeMaterializedReports(minuend, subtrahend)) {
@@ -824,15 +723,15 @@ export function subtractMaterializedTenantSalesOverviewReports(minuend, subtrahe
824
723
  * 1. metrics: `replacement` swaps the tree wholesale (day/hour docs);
825
724
  * otherwise `subtract` first (previously applied deltas), then `additions`
826
725
  * (newly calculated ones) — the reconcile/retry pattern;
827
- * 2. `received_payments` patches matching `issued` bills (`received_amount`
828
- * cumulative, `credit_note`, `settled_at` — the received entry's true
829
- * collection timestamp, falling back to `computedAt`, stamped when
830
- * `received_amount >= amount`);
726
+ * 2. `settled_credit_bills` patches the SETTLED counters of matching keys
727
+ * (`settled_count` +1 / `settled_amount` + `amount` — counters only, the
728
+ * itemized ledger lives in `materialized_tenant_credit_bills`);
831
729
  * 3. versioning: metric writes (`replacement` / `subtract` / `additions`) AND
832
- * received-payment patches that change the ledger bump `iteration` — the
833
- * returned document is recorded as a `materialized_tenant_reports_iterations`
834
- * row by the caller (`buildMaterializedTenantReportIteration`); no-op
835
- * patches bump nothing, so replays stay churn-free;
730
+ * settlement counter patches that change the counters bump `iteration` —
731
+ * the returned document is recorded as a
732
+ * `materialized_tenant_reports_iterations` row by the caller
733
+ * (`buildMaterializedTenantReportIteration`); no-op patches bump nothing,
734
+ * so replays stay churn-free;
836
735
  * 4. `source_watermark` advances to the max of the existing and the incoming
837
736
  * (`replacement` / `additions`) watermarks — monotonic, never regressed
838
737
  * (rollbacks / replays keep the previously folded maximum).
@@ -843,9 +742,9 @@ export function updateMaterializedTenantSalesOverviewReport(existing, updates, o
843
742
  const computedAt = options.computedAt ?? new Date();
844
743
  const subtract = updates.subtract ?? [];
845
744
  const additions = updates.additions ?? [];
846
- const receivedPayments = updates.received_payments ?? [];
745
+ const settledCreditBills = updates.settled_credit_bills ?? [];
847
746
  const hasMetricsUpdate = updates.replacement != null || subtract.length > 0 || additions.length > 0;
848
- if (!hasMetricsUpdate && receivedPayments.length === 0) {
747
+ if (!hasMetricsUpdate && settledCreditBills.length === 0) {
849
748
  return cloneReport(existing);
850
749
  }
851
750
  let metrics;
@@ -867,31 +766,15 @@ export function updateMaterializedTenantSalesOverviewReport(existing, updates, o
867
766
  return null;
868
767
  applyReportAddition(metrics, delta);
869
768
  }
870
- dedupeAllBillLedgers(metrics);
871
769
  }
872
770
  let ledgerPatched = false;
873
- for (const collected of receivedPayments) {
874
- for (const keyMetrics of Object.values(metrics)) {
875
- for (const bill of keyMetrics[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills) {
876
- if (bill.order_id !== collected.order_id || bill.payment_id !== collected.payment_id)
877
- continue;
878
- const nextReceived = Math.max(bill.received_amount ?? 0, collected.received_amount ?? 0);
879
- const nextNote = bill.credit_note ?? collected.credit_note;
880
- let nextSettledAt = bill.settled_at ?? null;
881
- if (bill.settled_at == null && nextReceived >= bill.amount) {
882
- // Prefer the true collection timestamp carried by the received entry.
883
- nextSettledAt = collected.settled_at ?? computedAt;
884
- }
885
- if (nextReceived !== (bill.received_amount ?? 0) ||
886
- (nextSettledAt?.getTime() ?? null) !== (bill.settled_at?.getTime() ?? null) ||
887
- (nextNote ?? null) !== (bill.credit_note ?? null)) {
888
- ledgerPatched = true;
889
- }
890
- bill.received_amount = nextReceived;
891
- bill.credit_note = nextNote;
892
- bill.settled_at = nextSettledAt;
893
- }
894
- }
771
+ for (const settled of settledCreditBills) {
772
+ const keyMetrics = metrics[settled.key];
773
+ if (keyMetrics == null)
774
+ continue;
775
+ keyMetrics[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_count += 1;
776
+ keyMetrics[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_amount += settled.amount;
777
+ ledgerPatched = true;
895
778
  }
896
779
  // The watermark is monotonic ("max source `updatedAt` folded so far"):
897
780
  // structural writes only ever advance it — never regress it.
@@ -27,6 +27,7 @@ export * from './inventory_transactions';
27
27
  export * from './item_transactions';
28
28
  export * from './items';
29
29
  export * from './marketing_fingerprints';
30
+ export * from './materialized_credit_bills';
30
31
  export * from './materialized_tenant_reports_iterations';
31
32
  export * from './materialized_tenant_sales_overview_reports';
32
33
  export * from './menus';