@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
@@ -3,10 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.isMaterializedCreditBillPayment = void 0;
6
7
  exports.normalizeMaterializedPaymentType = normalizeMaterializedPaymentType;
7
8
  exports.isPaymentIncludedInMaterializedSalesOverview = isPaymentIncludedInMaterializedSalesOverview;
8
9
  exports.getMaterializedPaymentGross = getMaterializedPaymentGross;
9
- exports.isMaterializedCreditBillPayment = isMaterializedCreditBillPayment;
10
10
  exports.normalizeMaterializedSaleTypeMetrics = normalizeMaterializedSaleTypeMetrics;
11
11
  exports.convertOrdersToMaterializedTenantSalesOverviewReports = convertOrdersToMaterializedTenantSalesOverviewReports;
12
12
  exports.convertMaterializedTenantSalesOverviewReportJsonToBson = convertMaterializedTenantSalesOverviewReportJsonToBson;
@@ -17,8 +17,9 @@ const mongoose_1 = __importDefault(require("mongoose"));
17
17
  const constants_1 = require("../../constants");
18
18
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
19
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
20
  const key_helpers_1 = require("./key-helpers");
21
+ const materialized_credit_bills_helpers_1 = require("./materialized-credit-bills-helpers");
22
+ Object.defineProperty(exports, "isMaterializedCreditBillPayment", { enumerable: true, get: function () { return materialized_credit_bills_helpers_1.isMaterializedCreditBillPayment; } });
22
23
  const scope_helpers_1 = require("./scope-helpers");
23
24
  /* ------------------------------------------------------------------------ */
24
25
  /* Payment rules (twin of `sales-overview-reference.ts`) */
@@ -58,10 +59,6 @@ function getMaterializedPaymentGross(payment) {
58
59
  }
59
60
  return -(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
60
61
  }
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
62
  const createEmptyOrderMetric = () => ({
66
63
  count: 0,
67
64
  gross_amount: 0,
@@ -80,7 +77,10 @@ const createEmptySaleTypeMetric = () => ({
80
77
  const createEmptyKeyMetrics = () => ({
81
78
  [constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: createEmptySaleTypeMetric(),
82
79
  [constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]: createEmptySaleTypeMetric(),
83
- [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: { issued: { bills: [] }, received: { bills: [] } },
80
+ [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: {
81
+ issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
82
+ received: { count: 0, amount: 0 },
83
+ },
84
84
  });
85
85
  function getOrCreateKeyMetrics(metrics, key) {
86
86
  if (metrics[key] == null) {
@@ -104,10 +104,15 @@ function accumulateOrderIntoOrderMetric(metric, order) {
104
104
  metric.tax_invoice_provider_charges += order.tax_invoice_provider_charges ?? 0;
105
105
  metric.delivery_charges += order.delivery_details?.delivery_cost ?? 0;
106
106
  }
107
- function accumulateOrderPayments(metric, order) {
107
+ function accumulateOrderPayments(metric, order, options = {}) {
108
108
  for (const payment of order.payments ?? []) {
109
109
  if (!isPaymentIncludedInMaterializedSalesOverview(payment))
110
110
  continue;
111
+ // PAY_LATER money is represented by the CREDIT_BILLS ledger (issued +
112
+ // receipt events) and the derived CREDIT_SETTLEMENT line — when excluded,
113
+ // it must never also feed the collected-payments buckets (F7).
114
+ if (options.excludeCreditBills === true && (0, materialized_credit_bills_helpers_1.isMaterializedCreditBillPayment)(payment))
115
+ continue;
111
116
  const paymentType = normalizeMaterializedPaymentType(payment.payment_type);
112
117
  if (metric.payments[paymentType] == null) {
113
118
  metric.payments[paymentType] = {
@@ -135,8 +140,17 @@ function accumulateOrder(metrics, key, order) {
135
140
  accumulateOrderIntoOrderMetric(keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders, order);
136
141
  accumulateOrderPayments(keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES], order);
137
142
  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);
143
+ // F7: money collected against a PAY_LATER bill (the receipt events) must
144
+ // never appear BOTH here and in the credit-bill ledger — a re-close of
145
+ // the issue day with the now-settled order would otherwise add it to
146
+ // this slot again (backfilled history must equal incremental history).
147
+ // The slot counts collected money EXCLUDING credit receipts and its
148
+ // payment rows skip PAY_LATER entirely.
149
+ const collectedCreditBills = (order.payments ?? []).reduce((sum, payment) => ((0, materialized_credit_bills_helpers_1.isMaterializedCreditBillPayment)(payment) ? sum + (payment.amount_paid ?? 0) : sum), 0);
150
+ if ((order.amount_collected ?? 0) - collectedCreditBills > 0) {
151
+ accumulateOrderIntoOrderMetric(keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders, order);
152
+ accumulateOrderPayments(keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED], order, { excludeCreditBills: true });
153
+ }
140
154
  }
141
155
  }
142
156
  /* ------------------------------------------------------------------------ */
@@ -159,85 +173,18 @@ function accumulateOrder(metrics, key, order) {
159
173
  * Bills are keyed by `payment_id` (fallback: the payment subdocument `_id`);
160
174
  * a `PAY_LATER` payment carrying neither is a data issue → `null` (the
161
175
  * ledger's `(order_id, payment_id)` keys must never collapse).
176
+ *
177
+ * `received_at_issue` = what the payment had received when the compiled day
178
+ * closed (the true at-issue value on a FIRST close; the close-day plan
179
+ * carries the stored value forward on re-closes, so a re-close after
180
+ * collection can never re-anchor it).
162
181
  */
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
182
  /* ------------------------------------------------------------------------ */
219
183
  /* Serialization */
220
184
  /* ------------------------------------------------------------------------ */
221
185
  function sumNumbers(values) {
222
186
  return values.reduce((total, value) => total + (value ?? 0), 0);
223
187
  }
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
188
  function finalizeSaleTypeMetric(metric) {
242
189
  const payments = Object.values(metric.payments).sort((a, b) => b.count - a.count || a.payment_type.localeCompare(b.payment_type));
243
190
  return { orders: metric.orders, payments };
@@ -249,8 +196,8 @@ function finalizeMetrics(metrics) {
249
196
  [constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: finalizeSaleTypeMetric(metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]),
250
197
  [constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]: finalizeSaleTypeMetric(metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]),
251
198
  [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),
199
+ issued: { ...metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued },
200
+ received: { ...metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received },
254
201
  },
255
202
  };
256
203
  }
@@ -293,8 +240,12 @@ const pruneZeroReportKeys = (metrics) => {
293
240
  totalSales.payments.every(isZeroPaymentMetric) &&
294
241
  isZeroOrderReportMetric(amountCollected.orders) &&
295
242
  (amountCollected.payments ?? []).every(isZeroPaymentMetric) &&
296
- creditBills.issued.bills.length === 0 &&
297
- creditBills.received.bills.length === 0;
243
+ isZeroNumber(creditBills.issued.count) &&
244
+ isZeroNumber(creditBills.issued.amount) &&
245
+ isZeroNumber(creditBills.issued.settled_count) &&
246
+ isZeroNumber(creditBills.issued.settled_amount) &&
247
+ isZeroNumber(creditBills.received.count) &&
248
+ isZeroNumber(creditBills.received.amount);
298
249
  if (!isZero)
299
250
  pruned[key] = metric;
300
251
  }
@@ -341,7 +292,7 @@ function normalizeMaterializedSaleTypeMetrics(metrics) {
341
292
  }
342
293
  return normalized;
343
294
  }
344
- /** JSON report → mutable accumulator tree (bills / payments cloned). */
295
+ /** JSON report → mutable accumulator tree (counters / payments cloned). */
345
296
  function toMutableMetrics(metrics) {
346
297
  const mutable = {};
347
298
  for (const [key, metric] of Object.entries(normalizeMaterializedSaleTypeMetrics(metrics))) {
@@ -367,10 +318,8 @@ function toMutableMetrics(metrics) {
367
318
  ])),
368
319
  },
369
320
  [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: {
370
- issued: { bills: (metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills ?? []).map((bill) => ({ ...bill })) },
371
- received: {
372
- bills: (metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills ?? []).map((bill) => ({ ...bill })),
373
- },
321
+ issued: { ...metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued },
322
+ received: { ...metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received },
374
323
  },
375
324
  };
376
325
  }
@@ -383,45 +332,6 @@ function cloneReport(report) {
383
332
  /* ------------------------------------------------------------------------ */
384
333
  /* 1. Orders → JSON documents */
385
334
  /* ------------------------------------------------------------------------ */
386
- const resolveOrderLocalHour = (order, localDate, gmtOffset) => {
387
- if (typeof order.localHour === 'number' && order.localHour >= 0 && order.localHour <= 23) {
388
- return order.localHour;
389
- }
390
- if (typeof gmtOffset === 'number') {
391
- const fields = (0, time_helpers_1.getLocalFieldsFromLocalDate)(order.localDate ?? localDate, gmtOffset, order.order_settled_at ?? order.createdAt);
392
- return fields.localHour;
393
- }
394
- if (typeof order.order_settled_at_mins === 'number' && order.order_settled_at_mins >= 0) {
395
- return Math.min(23, Math.floor(order.order_settled_at_mins / 60));
396
- }
397
- return null;
398
- };
399
- /**
400
- * Hour bucket of a credit-bill COLLECTION event (an earlier-day order settling
401
- * on the compiled day): the SETTLEMENT anchor resolves the hour — never the
402
- * punch hour, so hour views / the derived credit-settlement line sit at the
403
- * moment the money was collected. Chain: `gmtOffset` + `order_settled_at`
404
- * (tenant-local hour) → `order_settled_at_mins ÷ 60` → the settlement
405
- * timestamp's UTC hour (the mins convention is UTC-based too) → punch-hour
406
- * fallback (last resort).
407
- */
408
- const resolveReceivedLocalHour = (order, localDate, gmtOffset) => {
409
- if (typeof gmtOffset === 'number' && order.order_settled_at != null) {
410
- const settledAt = new Date(order.order_settled_at);
411
- if (!Number.isNaN(settledAt.getTime()))
412
- return (0, time_helpers_1.getLocalDocumentFields)(gmtOffset, settledAt).localHour;
413
- }
414
- if (typeof order.order_settled_at_mins === 'number' && order.order_settled_at_mins >= 0) {
415
- return Math.min(23, Math.floor(order.order_settled_at_mins / 60));
416
- }
417
- // Still settlement-anchored (the mins convention above is UTC-based too).
418
- if (order.order_settled_at != null) {
419
- const settledUtc = new Date(order.order_settled_at);
420
- if (!Number.isNaN(settledUtc.getTime()))
421
- return settledUtc.getUTCHours();
422
- }
423
- return resolveOrderLocalHour(order, localDate, gmtOffset);
424
- };
425
335
  const createEmptyReportDocument = (args) => {
426
336
  const { tenantId, brandId, scopeContext, scopeField, now } = args;
427
337
  const dayIndex = MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext)
@@ -473,12 +383,13 @@ function convertOrdersToMaterializedTenantSalesOverviewReports(localDate, orders
473
383
  const tenantIds = Array.from(new Set((orders ?? []).map((order) => order.tenant_id)));
474
384
  if (tenantIds.length === 0) {
475
385
  if (options.tenantId == null) {
476
- return { materializedReports: [], received_payments: [] };
386
+ return { materializedReports: [], credit_bill_issues: [], credit_bill_events: [] };
477
387
  }
478
388
  tenantIds.push(options.tenantId);
479
389
  }
480
390
  const materializedReports = [];
481
- const receivedPayments = [];
391
+ const creditBillIssues = [];
392
+ const creditEventCandidates = [];
482
393
  const periodScopeFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
483
394
  if (periodScopeFields == null)
484
395
  return null;
@@ -493,13 +404,7 @@ function convertOrdersToMaterializedTenantSalesOverviewReports(localDate, orders
493
404
  continue; // live facets materialize `is_deleted: false` only
494
405
  const orderLocalDate = order.localDate ?? localDate;
495
406
  if (orderLocalDate !== localDate) {
496
- const collected = buildReceivedCreditBills(order, orderLocalDate);
497
- if (collected == null)
498
- return null; // un-keyable bill — data issue
499
- if (collected.length > 0) {
500
- receivedEntries.push({ order, orderLocalDate });
501
- receivedPayments.push(...collected);
502
- }
407
+ receivedEntries.push({ order, orderLocalDate });
503
408
  continue;
504
409
  }
505
410
  salesOrders.push(order);
@@ -539,14 +444,14 @@ function convertOrdersToMaterializedTenantSalesOverviewReports(localDate, orders
539
444
  // The hour document for each order / collection event.
540
445
  const salesHours = new Map();
541
446
  for (const order of salesOrders) {
542
- const hour = resolveOrderLocalHour(order, localDate, options.gmtOffset);
447
+ const hour = (0, materialized_credit_bills_helpers_1.resolveOrderLocalHour)(order, localDate, options.gmtOffset);
543
448
  if (hour != null)
544
449
  getHourDoc(hour);
545
450
  salesHours.set(order, hour);
546
451
  }
547
452
  const receivedHours = new Map();
548
453
  for (const { order } of receivedEntries) {
549
- const hour = resolveReceivedLocalHour(order, localDate, options.gmtOffset);
454
+ const hour = (0, materialized_credit_bills_helpers_1.resolveReceivedLocalHour)(order, localDate, options.gmtOffset);
550
455
  if (hour != null)
551
456
  getHourDoc(hour);
552
457
  receivedHours.set(order, hour);
@@ -564,29 +469,49 @@ function convertOrdersToMaterializedTenantSalesOverviewReports(localDate, orders
564
469
  for (const target of targets) {
565
470
  accumulateOrder(target.metrics, key, order);
566
471
  }
567
- const issuedBills = buildIssuedCreditBills(order, now);
568
- if (issuedBills == null)
472
+ const issuedCandidates = (0, materialized_credit_bills_helpers_1.buildCreditBillIssuedCandidatesFromOrder)(order, localDate, {
473
+ now,
474
+ gmtOffset: options.gmtOffset,
475
+ });
476
+ if (issuedCandidates == null)
569
477
  return null; // un-keyable bill — data issue
570
- if (issuedBills.length > 0) {
478
+ if (issuedCandidates.length > 0) {
479
+ creditBillIssues.push(...issuedCandidates);
571
480
  for (const target of targets) {
572
- const keyMetrics = getOrCreateKeyMetrics(target.metrics, key);
573
- keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills.push(...issuedBills.map((bill) => ({ ...bill })));
481
+ const credit = getOrCreateKeyMetrics(target.metrics, key)[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
482
+ for (const candidate of issuedCandidates) {
483
+ credit.issued.count += 1;
484
+ credit.issued.amount += candidate.amount;
485
+ if (candidate.settled_at != null) {
486
+ credit.issued.settled_count += 1;
487
+ credit.issued.settled_amount += candidate.amount;
488
+ }
489
+ }
574
490
  }
575
491
  }
576
492
  }
577
493
  for (const { order } of receivedEntries) {
578
- const collected = buildReceivedCreditBills(order, order.localDate ?? localDate);
579
- if (collected == null)
494
+ const candidates = (0, materialized_credit_bills_helpers_1.buildCreditBillEventCandidatesFromOrder)(order, localDate, {
495
+ now,
496
+ gmtOffset: options.gmtOffset,
497
+ });
498
+ if (candidates == null)
580
499
  return null; // un-keyable bill — data issue
581
- if (collected.length === 0)
500
+ if (candidates.length === 0)
582
501
  continue;
502
+ creditEventCandidates.push(...candidates);
583
503
  const key = (0, key_helpers_1.buildMaterializedReportKey)([order.order_status, order.platform]);
584
504
  if (key == null)
585
505
  return null; // un-keyable order fields — data issue
506
+ // The key must exist on the collection day's scopes even before the
507
+ // close-day plan resolves the receipt deltas (it fills the `received`
508
+ // AMOUNT later); `getOrCreateKeyMetrics` keeps the key alive through
509
+ // the planner's zero-pruning until then. The event COUNT is
510
+ // order-pure — the compile counts it now, resolution only prices it.
586
511
  const targets = targetsForHour(receivedHours.get(order) ?? null);
587
512
  for (const target of targets) {
588
- const keyMetrics = getOrCreateKeyMetrics(target.metrics, key);
589
- keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills.push(...collected.map((bill) => ({ ...bill })));
513
+ const credit = getOrCreateKeyMetrics(target.metrics, key)[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
514
+ credit.received.count += candidates.length;
590
515
  }
591
516
  }
592
517
  // `source_watermark` = max `order.updatedAt` folded in; a day with no
@@ -602,7 +527,7 @@ function convertOrdersToMaterializedTenantSalesOverviewReports(localDate, orders
602
527
  materializedReports.push(doc);
603
528
  }
604
529
  }
605
- return { materializedReports, received_payments: receivedPayments };
530
+ return { materializedReports, credit_bill_issues: creditBillIssues, credit_bill_events: creditEventCandidates };
606
531
  }
607
532
  /* ------------------------------------------------------------------------ */
608
533
  /* 2. JSON → BSON (mongoose document) */
@@ -682,10 +607,23 @@ const subtractPayments = (target, source) => {
682
607
  delete target[payment.payment_type];
683
608
  }
684
609
  };
685
- /** Removes bills by `(order_id, payment_id)` — the subtraction primitive. */
686
- const subtractBillsByKey = (bills, removed) => {
687
- const removedKeys = new Set(removed.map((bill) => `${bill.order_id}|${bill.payment_id}`));
688
- return bills.filter((bill) => !removedKeys.has(`${bill.order_id}|${bill.payment_id}`));
610
+ /** Sums credit-bill COUNTERS (numbers only — documents hold no bill rows). */
611
+ const sumCreditBillCounters = (target, source) => {
612
+ target.issued.count += source.issued?.count ?? 0;
613
+ target.issued.amount += source.issued?.amount ?? 0;
614
+ target.issued.settled_count += source.issued?.settled_count ?? 0;
615
+ target.issued.settled_amount += source.issued?.settled_amount ?? 0;
616
+ target.received.count += source.received?.count ?? 0;
617
+ target.received.amount += source.received?.amount ?? 0;
618
+ };
619
+ /** Subtracts credit-bill COUNTERS (numbers only — documents hold no bill rows). */
620
+ const subtractCreditBillCounters = (target, source) => {
621
+ target.issued.count -= source.issued?.count ?? 0;
622
+ target.issued.amount -= source.issued?.amount ?? 0;
623
+ target.issued.settled_count -= source.issued?.settled_count ?? 0;
624
+ target.issued.settled_amount -= source.issued?.settled_amount ?? 0;
625
+ target.received.count -= source.received?.count ?? 0;
626
+ target.received.amount -= source.received?.amount ?? 0;
689
627
  };
690
628
  /** Same tenant / brand / schema version / key filters — reports that may merge. */
691
629
  const canMergeMaterializedReports = (base, other) => base.tenant_id === other.tenant_id &&
@@ -708,8 +646,7 @@ const applyReportAddition = (metrics, report) => {
708
646
  sumPayments(target[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments, metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments);
709
647
  sumOrderMetrics(target[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders, metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders);
710
648
  sumPayments(target[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments, metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments);
711
- 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 })));
712
- 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 })));
649
+ sumCreditBillCounters(target[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS], metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]);
713
650
  }
714
651
  };
715
652
  /** Subtracts one report's metric tree from a mutable accumulator. */
@@ -722,46 +659,7 @@ const applyReportSubtraction = (metrics, report) => {
722
659
  subtractPayments(target[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments, metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments);
723
660
  subtractOrderMetrics(target[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders, metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders);
724
661
  subtractPayments(target[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments, metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].payments);
725
- 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 ?? []);
726
- 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 ?? []);
727
- }
728
- };
729
- const dedupeIssuedBills = (bills) => {
730
- const byBill = new Map();
731
- for (const bill of bills) {
732
- const billKey = `${bill.order_id}|${bill.payment_id}`;
733
- const existing = byBill.get(billKey);
734
- if (existing == null) {
735
- byBill.set(billKey, { ...bill });
736
- continue;
737
- }
738
- // Same bill compiled twice (overlapping scopes): keep the most-collected state.
739
- existing.received_amount = Math.max(existing.received_amount ?? 0, bill.received_amount ?? 0);
740
- existing.settled_at = existing.settled_at ?? bill.settled_at;
741
- existing.credit_note = existing.credit_note ?? bill.credit_note;
742
- }
743
- return [...byBill.values()];
744
- };
745
- const dedupeReceivedBills = (bills) => {
746
- const byBill = new Map();
747
- for (const bill of bills) {
748
- const billKey = `${bill.order_id}|${bill.payment_id}`;
749
- const existing = byBill.get(billKey);
750
- if (existing == null) {
751
- byBill.set(billKey, { ...bill });
752
- continue;
753
- }
754
- existing.received_amount = Math.max(existing.received_amount ?? 0, bill.received_amount ?? 0);
755
- existing.credit_note = existing.credit_note ?? bill.credit_note;
756
- existing.settled_at = existing.settled_at ?? bill.settled_at;
757
- }
758
- return [...byBill.values()];
759
- };
760
- /** De-duplicates both bill ledgers of every key (overlapping compiles). */
761
- const dedupeAllBillLedgers = (metrics) => {
762
- for (const metric of Object.values(metrics)) {
763
- metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills = dedupeIssuedBills(metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills);
764
- metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills = dedupeReceivedBills(metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills);
662
+ subtractCreditBillCounters(target[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS], metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]);
765
663
  }
766
664
  };
767
665
  /**
@@ -770,10 +668,9 @@ const dedupeAllBillLedgers = (metrics) => {
770
668
  * the period document (month / quarter / year …) FIRST so the result keeps its
771
669
  * identity while day documents are accumulated into it.
772
670
  *
773
- * Metric trees are summed per key; credit-bill bills are concatenated and
774
- * de-duplicated by `(order_id, payment_id)` keeping the most-collected state,
775
- * then all ledger counters are recomputed from the itemized bills — so
776
- * overlapping compiles never double-count.
671
+ * Metric trees are summed per key — including the credit-bill COUNTERS
672
+ * (`issued` / `settled` / `received` numbers; the itemized ledger lives in
673
+ * `materialized_tenant_credit_bills` and is not part of these documents).
777
674
  *
778
675
  * Returns `null` (never throws) when the inputs cannot be summed — empty list
779
676
  * or mismatched tenant / brand / schema version / key filters. `null` means a
@@ -799,7 +696,6 @@ function sumMaterializedTenantSalesOverviewReports(reports, options = {}) {
799
696
  for (const report of reports) {
800
697
  applyReportAddition(metrics, report);
801
698
  }
802
- dedupeAllBillLedgers(metrics);
803
699
  const computedAt = options.computedAt ?? new Date();
804
700
  const watermark = reports.reduce((latest, report) => {
805
701
  const reportWatermark = new Date(report.source_watermark ?? 0);
@@ -821,8 +717,9 @@ function sumMaterializedTenantSalesOverviewReports(reports, options = {}) {
821
717
  * the stored `localDate` doc of day D IS the delta previously folded into the
822
718
  * period docs.
823
719
  *
824
- * Bills are removed by `(order_id, payment_id)`; ledger counters are recomputed
825
- * from the remaining bills. Returns `null` (never throws) on mismatched inputs.
720
+ * Credit-bill counters are subtracted numerically (numbers only — these
721
+ * documents carry no bill rows). Returns `null` (never throws) on mismatched
722
+ * inputs.
826
723
  */
827
724
  function subtractMaterializedTenantSalesOverviewReports(minuend, subtrahend) {
828
725
  if (minuend == null || subtrahend == null || !canMergeMaterializedReports(minuend, subtrahend)) {
@@ -839,15 +736,15 @@ function subtractMaterializedTenantSalesOverviewReports(minuend, subtrahend) {
839
736
  * 1. metrics: `replacement` swaps the tree wholesale (day/hour docs);
840
737
  * otherwise `subtract` first (previously applied deltas), then `additions`
841
738
  * (newly calculated ones) — the reconcile/retry pattern;
842
- * 2. `received_payments` patches matching `issued` bills (`received_amount`
843
- * cumulative, `credit_note`, `settled_at` — the received entry's true
844
- * collection timestamp, falling back to `computedAt`, stamped when
845
- * `received_amount >= amount`);
739
+ * 2. `settled_credit_bills` patches the SETTLED counters of matching keys
740
+ * (`settled_count` +1 / `settled_amount` + `amount` — counters only, the
741
+ * itemized ledger lives in `materialized_tenant_credit_bills`);
846
742
  * 3. versioning: metric writes (`replacement` / `subtract` / `additions`) AND
847
- * received-payment patches that change the ledger bump `iteration` — the
848
- * returned document is recorded as a `materialized_tenant_reports_iterations`
849
- * row by the caller (`buildMaterializedTenantReportIteration`); no-op
850
- * patches bump nothing, so replays stay churn-free;
743
+ * settlement counter patches that change the counters bump `iteration` —
744
+ * the returned document is recorded as a
745
+ * `materialized_tenant_reports_iterations` row by the caller
746
+ * (`buildMaterializedTenantReportIteration`); no-op patches bump nothing,
747
+ * so replays stay churn-free;
851
748
  * 4. `source_watermark` advances to the max of the existing and the incoming
852
749
  * (`replacement` / `additions`) watermarks — monotonic, never regressed
853
750
  * (rollbacks / replays keep the previously folded maximum).
@@ -858,9 +755,9 @@ function updateMaterializedTenantSalesOverviewReport(existing, updates, options
858
755
  const computedAt = options.computedAt ?? new Date();
859
756
  const subtract = updates.subtract ?? [];
860
757
  const additions = updates.additions ?? [];
861
- const receivedPayments = updates.received_payments ?? [];
758
+ const settledCreditBills = updates.settled_credit_bills ?? [];
862
759
  const hasMetricsUpdate = updates.replacement != null || subtract.length > 0 || additions.length > 0;
863
- if (!hasMetricsUpdate && receivedPayments.length === 0) {
760
+ if (!hasMetricsUpdate && settledCreditBills.length === 0) {
864
761
  return cloneReport(existing);
865
762
  }
866
763
  let metrics;
@@ -882,31 +779,15 @@ function updateMaterializedTenantSalesOverviewReport(existing, updates, options
882
779
  return null;
883
780
  applyReportAddition(metrics, delta);
884
781
  }
885
- dedupeAllBillLedgers(metrics);
886
782
  }
887
783
  let ledgerPatched = false;
888
- for (const collected of receivedPayments) {
889
- for (const keyMetrics of Object.values(metrics)) {
890
- for (const bill of keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills) {
891
- if (bill.order_id !== collected.order_id || bill.payment_id !== collected.payment_id)
892
- continue;
893
- const nextReceived = Math.max(bill.received_amount ?? 0, collected.received_amount ?? 0);
894
- const nextNote = bill.credit_note ?? collected.credit_note;
895
- let nextSettledAt = bill.settled_at ?? null;
896
- if (bill.settled_at == null && nextReceived >= bill.amount) {
897
- // Prefer the true collection timestamp carried by the received entry.
898
- nextSettledAt = collected.settled_at ?? computedAt;
899
- }
900
- if (nextReceived !== (bill.received_amount ?? 0) ||
901
- (nextSettledAt?.getTime() ?? null) !== (bill.settled_at?.getTime() ?? null) ||
902
- (nextNote ?? null) !== (bill.credit_note ?? null)) {
903
- ledgerPatched = true;
904
- }
905
- bill.received_amount = nextReceived;
906
- bill.credit_note = nextNote;
907
- bill.settled_at = nextSettledAt;
908
- }
909
- }
784
+ for (const settled of settledCreditBills) {
785
+ const keyMetrics = metrics[settled.key];
786
+ if (keyMetrics == null)
787
+ continue;
788
+ keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_count += 1;
789
+ keyMetrics[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_amount += settled.amount;
790
+ ledgerPatched = true;
910
791
  }
911
792
  // The watermark is monotonic ("max source `updatedAt` folded so far"):
912
793
  // structural writes only ever advance it — never regress it.
@@ -108,11 +108,30 @@ export interface IMaterializedTenantSalesOverviewAggregatedKeyMetrics {
108
108
  issued: {
109
109
  count: number;
110
110
  amount: number;
111
+ /** Fully settled BY THE SELECTION END (range-pure — see `computeMaterializedCreditBillTotals`). */
111
112
  settled_count: number;
113
+ /** Σ `amount` of those bills. */
112
114
  settled_amount: number;
115
+ /** Issued-in-selection bills NOT fully settled by the selection end. */
116
+ outstanding_count: number;
117
+ /** Per-bill `max(0, amount − received_at_issue − Σ in-selection deltas)` — owed at the selection end. */
118
+ outstanding_amount: number;
119
+ /** Today's state: issued-in-selection bills whose CURRENT cumulative is below `amount`. */
120
+ outstanding_now_count: number;
121
+ /** Per-bill `max(0, amount − received_now)` — owed now. */
122
+ outstanding_now_amount: number;
123
+ /**
124
+ * Money in hand AT ISSUE (Σ `received_at_issue` of issued-in-selection
125
+ * bills): same-day settled credit + prepaid partials. Added to
126
+ * `received.amount` for the Amount Collected KPI (N4).
127
+ */
128
+ collected_at_issue_count: number;
129
+ collected_at_issue_amount: number;
113
130
  };
114
131
  received: {
132
+ /** Distinct bills with a receipt event in the selection. */
115
133
  count: number;
134
+ /** Money received IN the selection (Σ `received_delta`). */
116
135
  amount: number;
117
136
  };
118
137
  };
@@ -128,15 +147,23 @@ export interface IMaterializedTenantSalesOverviewAggregatedKeyMetrics {
128
147
  * still apply its platform / order-status filters client-side on a single
129
148
  * record — via `getFormattedTenantSalesOverviewAggregatedReporting`.
130
149
  *
131
- * NOT part of the stored schema: carries no `_id`, `iteration`,
132
- * `schema_version`, `source_watermark`, `computed_at` or timestamps — only
133
- * the report values plus the read context (`matched_documents` and the
134
- * `scope_field` span) useful for debugging. No `scope_context`: a span read
135
- * mixes several.
150
+ * NOT part of the stored schema: carries no `_id`, `schema_version`,
151
+ * `source_watermark` or `computed_at` — the report values, the read context,
152
+ * plus the freshness STAMPS of the folded documents (`max_iteration` /
153
+ * `max_updated_at`), because past documents MUTATE (settlement patches,
154
+ * re-closes) and consumers must be able to show "as of" and key caches.
155
+ * No `scope_context`: a span read mixes several.
136
156
  */
137
157
  export interface IMaterializedTenantSalesOverviewAggregatedReport {
138
158
  tenant_id: string;
139
159
  brand_id: string;
160
+ /**
161
+ * Freshness of the folded data: the max `iteration` across the matched
162
+ * documents and their newest `updatedAt` — the response has no other
163
+ * version marker.
164
+ */
165
+ max_iteration: number;
166
+ max_updated_at: Date | null;
140
167
  /**
141
168
  * How many stored scope documents were folded into this record — an EXACT
142
169
  * count, independent of the key map (documents with disjoint key sets
@@ -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';
@@ -43,6 +43,7 @@ __exportStar(require("./inventory_transactions"), exports);
43
43
  __exportStar(require("./item_transactions"), exports);
44
44
  __exportStar(require("./items"), exports);
45
45
  __exportStar(require("./marketing_fingerprints"), exports);
46
+ __exportStar(require("./materialized_credit_bills"), exports);
46
47
  __exportStar(require("./materialized_tenant_reports_iterations"), exports);
47
48
  __exportStar(require("./materialized_tenant_sales_overview_reports"), exports);
48
49
  __exportStar(require("./menus"), exports);