@managesome/eposmatic-toolkit 0.4.7 → 0.4.8

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 (51) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +33 -0
  2. package/esm/helpers/materialized-reports/index.js +1 -0
  3. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +982 -0
  4. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +276 -33
  5. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +327 -41
  6. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +118 -235
  8. package/esm/schemas/models/index.js +1 -0
  9. package/esm/schemas/models/materialized_credit_bills.js +265 -0
  10. package/esm/schemas/models/materialized_tenant_reports_iterations.js +13 -0
  11. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +39 -97
  12. package/esm/schemas/types/index.js +1 -0
  13. package/esm/schemas/types/materialized_credit_bills.js +1 -0
  14. package/lib/constants/MATERIALIZED_REPORTS.d.ts +28 -2
  15. package/lib/constants/MATERIALIZED_REPORTS.js +34 -1
  16. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  17. package/lib/helpers/materialized-reports/index.js +1 -0
  18. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +307 -0
  19. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +1003 -0
  20. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +36 -2
  21. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +278 -34
  22. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +66 -8
  23. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +326 -40
  24. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +18 -2
  25. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  26. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +46 -37
  27. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +119 -238
  28. package/lib/helpers/types/materialized-reports-apis.d.ts +32 -5
  29. package/lib/schemas/models/index.d.ts +1 -0
  30. package/lib/schemas/models/index.js +1 -0
  31. package/lib/schemas/models/materialized_credit_bills.d.ts +337 -0
  32. package/lib/schemas/models/materialized_credit_bills.js +268 -0
  33. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +20 -6
  34. package/lib/schemas/models/materialized_tenant_reports_iterations.js +14 -1
  35. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +37 -165
  36. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +40 -98
  37. package/lib/schemas/types/index.d.ts +1 -0
  38. package/lib/schemas/types/index.js +1 -0
  39. package/lib/schemas/types/materialized_credit_bills.d.ts +139 -0
  40. package/lib/schemas/types/materialized_credit_bills.js +2 -0
  41. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +32 -77
  42. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.d.ts +1 -0
  43. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +715 -0
  44. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +96 -0
  45. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +9 -0
  46. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +23 -24
  47. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +327 -22
  48. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +27 -2
  49. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +12 -27
  50. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +79 -146
  51. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { REPORT_SALE_TYPE_ENUM } from '../../constants';
2
2
  import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
3
+ import { buildMaterializedCreditBillDayReports, getMaterializedCreditBillScopeRefsForIssue, needsMaterializedCreditBillsReportWrite, resolveCreditBillDay, updateMaterializedCreditBillsReport, } from './materialized-credit-bills-helpers';
3
4
  import { buildMaterializedTenantReportIteration } from './materialized-tenant-reports-iterations-helpers';
4
5
  import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields } from './scope-helpers';
5
6
  import { normalizeMaterializedSaleTypeMetrics, updateMaterializedTenantSalesOverviewReport, } from './tenant-sales-overview-helpers';
@@ -18,7 +19,6 @@ const CLOSE_DAY_ACCUMULATED_SCOPES = [
18
19
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
19
20
  ];
20
21
  const materializedScopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
21
- const materializedCreditBillKey = (orderId, paymentId) => `${orderId}|${paymentId}`;
22
22
  const hasMaterializedMetrics = (doc) => Object.keys(normalizeMaterializedSaleTypeMetrics(doc.sale_type_metrics)).length > 0;
23
23
  /**
24
24
  * Every stored scope the fan-out of one local day needs: the six period
@@ -68,27 +68,6 @@ export function needsMaterializedTenantSalesOverviewReportWrite(existing, incomi
68
68
  return true;
69
69
  return incomingTime > existingTime;
70
70
  }
71
- /** Would a received-payment patch change the stored bill? (settlement/note/received) */
72
- const creditBillWouldChange = (bill, collected) => {
73
- const received = Math.max(bill.received_amount ?? 0, collected.received_amount ?? 0);
74
- if (received !== (bill.received_amount ?? 0))
75
- return true;
76
- const note = bill.credit_note ?? collected.credit_note;
77
- if ((note ?? null) !== (bill.credit_note ?? null))
78
- return true;
79
- return bill.settled_at == null && received >= (bill.amount ?? 0);
80
- };
81
- /** Does the document hold an issued bill that one of the collected payments would change? */
82
- const documentHoldsUnpatchedCreditBill = (doc, collectedByBill) => {
83
- for (const keyMetrics of Object.values(normalizeMaterializedSaleTypeMetrics(doc.sale_type_metrics))) {
84
- for (const bill of keyMetrics?.[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]?.issued?.bills ?? []) {
85
- const collected = collectedByBill.get(materializedCreditBillKey(bill.order_id, bill.payment_id));
86
- if (collected != null && creditBillWouldChange(bill, collected))
87
- return true;
88
- }
89
- }
90
- return false;
91
- };
92
71
  /**
93
72
  * Builds the close-day write plan for ONE tenant-day (see the module docs).
94
73
  * Returns `null` (never throws) when the input is inconsistent — compiled
@@ -141,6 +120,100 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
141
120
  if (String(prior._id) !== String(doc._id))
142
121
  return null;
143
122
  }
123
+ // ------------------------------------------------------------------
124
+ // Resolve THIS day against the stored credit ledger documents — the only
125
+ // stateful step (receipt deltas, carried anchors, settlements), executed
126
+ // ONCE and shared by the report counters and the credit documents below
127
+ // (single writer: the two collections can never drift).
128
+ // - receipt events: a stored same-day event keeps its own `received_delta`
129
+ // (idempotent re-closes); a new event's delta resolves as the compile
130
+ // cumulative minus the stored cumulative (clamped at 0). Out-of-order
131
+ // backfills of a MISSED day can still misattribute a large delta to that
132
+ // day — closes are assumed to run chronologically per tenant (documented).
133
+ // - issued bills: `received_at_issue` / settlement anchors carry forward —
134
+ // a re-close AFTER collection never re-anchors them.
135
+ const creditResolution = resolveCreditBillDay({
136
+ tenantId,
137
+ localDate,
138
+ issued: compile.credit_bill_issues,
139
+ events: compile.credit_bill_events,
140
+ stored: input.existingCreditBills,
141
+ computedAt,
142
+ });
143
+ if (creditResolution == null)
144
+ return null;
145
+ // Fill the compiled collection-day documents' `received` COUNTERS from the
146
+ // resolved deltas (the compile cannot know them): hour docs take their
147
+ // event's hour, period docs the whole day; null-hour events count on the
148
+ // day-shaped scopes only (never on an hour doc).
149
+ const periodFieldsNow = getMaterializedPeriodScopeFields(localDate);
150
+ if (periodFieldsNow == null)
151
+ return null;
152
+ const receivedByScopeKey = new Map();
153
+ for (const resolved of creditResolution.received_events) {
154
+ const key = resolved.key;
155
+ const delta = resolved.entry.received_delta ?? 0;
156
+ const scopeFields = Object.entries(periodFieldsNow).map(([scopeContext, scopeField]) => ({
157
+ scope_context: scopeContext,
158
+ scope_field: scopeField,
159
+ }));
160
+ if (resolved.entry.event_local_hour != null) {
161
+ scopeFields.push({
162
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
163
+ scope_field: resolved.entry.event_local_hour,
164
+ });
165
+ }
166
+ for (const scope of scopeFields) {
167
+ const mapKey = `${scope.scope_context}|${scope.scope_field}|${key}`;
168
+ const entry = receivedByScopeKey.get(mapKey) ?? { count: 0, amount: 0 };
169
+ entry.count += 1;
170
+ entry.amount += delta;
171
+ receivedByScopeKey.set(mapKey, entry);
172
+ }
173
+ }
174
+ for (const compiledDoc of compiledReports) {
175
+ const metrics = compiledDoc.sale_type_metrics;
176
+ for (const [key, metric] of Object.entries(metrics ?? {})) {
177
+ const entry = receivedByScopeKey.get(`${compiledDoc.scope_context}|${compiledDoc.scope_field}|${key}`);
178
+ metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received = entry != null ? { ...entry } : { count: 0, amount: 0 };
179
+ }
180
+ }
181
+ // The compile derives ISSUED counters from the CURRENT order state — a
182
+ // never-settled view — so an ISSUE-DAY re-close after collection would
183
+ // regress the settled counters (and the N2 rule reads settled-later bills
184
+ // as unsettled at issue). The resolution carries the stored settlement
185
+ // anchors forward: OVERWRITE the compiled day's settled counters from the
186
+ // resolved issued entries (all of today's issues by construction).
187
+ //
188
+ // SEMANTICS (audit R5-4): these REPORT counters are EVER-SETTLED (NOW
189
+ // state) — a bill settled on any later day counts here. The range-pure
190
+ // as-of-end answer (`settled_local_date <= selection end`) comes from
191
+ // `computeMaterializedCreditBillTotalsFromReports` over the credit
192
+ // documents; the two legitimately differ for historical ranges and must
193
+ // never be rendered side-by-side without labeling (Phase C).
194
+ const settledByKey = new Map();
195
+ for (const resolved of creditResolution.issued) {
196
+ const entry = resolved.entry;
197
+ if (entry.settled_at == null && entry.settled_local_date == null)
198
+ continue;
199
+ const totals = settledByKey.get(resolved.key) ?? { count: 0, amount: 0 };
200
+ totals.count += 1;
201
+ totals.amount += entry.amount ?? 0;
202
+ settledByKey.set(resolved.key, totals);
203
+ }
204
+ for (const compiledDoc of compiledReports) {
205
+ const metrics = compiledDoc.sale_type_metrics;
206
+ for (const [key, metric] of Object.entries(metrics ?? {})) {
207
+ const entry = settledByKey.get(key);
208
+ metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_count = entry?.count ?? 0;
209
+ metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_amount = entry?.amount ?? 0;
210
+ }
211
+ }
212
+ // Bills that settled on a LATER day than their issue day need the issue-day
213
+ // documents' SETTLED counters patched (the itemized ledger lives in
214
+ // `materialized_tenant_credit_bills`; report documents keep constant-size
215
+ // counters). The resolution emits each settlement exactly once.
216
+ const settledTransitions = creditResolution.settled_bills;
144
217
  const storedDateDoc = existingByScope.get(materializedScopeKey(compiledDateDoc)) ?? null;
145
218
  const dayChanged = force || needsMaterializedTenantSalesOverviewReportWrite(storedDateDoc, compiledDateDoc);
146
219
  const dayDeltaEmpty = !hasMaterializedMetrics(compiledDateDoc);
@@ -224,28 +297,241 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
224
297
  postWriteByScope.set(materializedScopeKey(write.report), write.report);
225
298
  for (const stale of staleHourDocuments)
226
299
  postWriteByScope.delete(materializedScopeKey(stale));
300
+ // Batch the settled-counter deltas per document first — several transitions
301
+ // can hit one document, and every patch must be computed from the same
302
+ // pre-patch state with ALL deltas applied in a single update.
303
+ const settledDeltasByDoc = new Map();
304
+ for (const transition of settledTransitions) {
305
+ const billKey = transition.key;
306
+ const issuePeriodFields = getMaterializedPeriodScopeFields(transition.issued_local_date);
307
+ if (issuePeriodFields == null)
308
+ return null; // malformed issue date — data issue
309
+ const issueScopeValues = new Set([transition.issued_local_date, ...Object.values(issuePeriodFields)]);
310
+ for (const [scopeKey, doc] of postWriteByScope) {
311
+ const scopeOnIssueDay = issueScopeValues.has(doc.scope_field) ||
312
+ (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
313
+ typeof doc.scope_field === 'string' &&
314
+ doc.scope_field.startsWith(`${transition.issued_local_date} `));
315
+ if (!scopeOnIssueDay)
316
+ continue;
317
+ const metrics = normalizeMaterializedSaleTypeMetrics(doc.sale_type_metrics);
318
+ if (metrics[billKey]?.[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS] == null)
319
+ continue;
320
+ const entries = settledDeltasByDoc.get(scopeKey) ?? [];
321
+ entries.push({ key: billKey, amount: transition.amount });
322
+ settledDeltasByDoc.set(scopeKey, entries);
323
+ }
324
+ }
227
325
  const receivedPatches = [];
228
- const receivedPayments = compile.received_payments ?? [];
229
- if (receivedPayments.length > 0) {
230
- const collectedByBill = new Map();
231
- for (const collected of receivedPayments) {
232
- collectedByBill.set(materializedCreditBillKey(collected.order_id, collected.payment_id), collected);
233
- }
234
- for (const doc of postWriteByScope.values()) {
235
- if (!documentHoldsUnpatchedCreditBill(doc, collectedByBill))
326
+ for (const [scopeKey, entries] of settledDeltasByDoc) {
327
+ const doc = postWriteByScope.get(scopeKey);
328
+ if (doc == null)
329
+ continue;
330
+ const patched = updateMaterializedTenantSalesOverviewReport(doc, { settled_credit_bills: entries }, { computedAt });
331
+ if (patched == null)
332
+ return null;
333
+ const iteration = buildMaterializedTenantReportIteration(patched, {
334
+ reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
335
+ reason,
336
+ computedAt,
337
+ });
338
+ if (iteration == null)
339
+ return null;
340
+ receivedPatches.push({ report: patched, iteration });
341
+ }
342
+ // ------------------------------------------------------------------
343
+ // Credit-bill documents (`materialized_tenant_credit_bills`) — materialized
344
+ // from the SAME resolution as the counters above (single writer): the
345
+ // month-capped scopes only (hour/date/week/ISO-week/month), so no document
346
+ // can grow unbounded while year/multi-year reads cover their range with the
347
+ // month documents.
348
+ // ------------------------------------------------------------------
349
+ const creditDayScopes = [
350
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
351
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
352
+ ];
353
+ const creditAccumulatedScopes = [
354
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
355
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
356
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
357
+ ];
358
+ const creditCompiledDocs = buildMaterializedCreditBillDayReports({
359
+ tenantId,
360
+ brandId: compiledDateDoc.brand_id,
361
+ localDate,
362
+ resolution: creditResolution,
363
+ computedAt,
364
+ });
365
+ if (creditCompiledDocs == null)
366
+ return null;
367
+ const creditExistingByScope = new Map();
368
+ for (const doc of input.existingCreditBills ?? []) {
369
+ if (doc == null || doc.tenant_id !== tenantId)
370
+ continue;
371
+ const key = materializedScopeKey(doc);
372
+ const prior = creditExistingByScope.get(key);
373
+ if (prior == null) {
374
+ creditExistingByScope.set(key, doc);
375
+ continue;
376
+ }
377
+ if (String(prior._id) !== String(doc._id))
378
+ return null; // duplicate rows — data issue
379
+ }
380
+ const creditWrites = [];
381
+ const creditSkippedDocuments = [];
382
+ const creditStaleHourDocuments = [];
383
+ const creditSettlementPatches = [];
384
+ const addCreditWrite = (report) => {
385
+ const iteration = buildMaterializedTenantReportIteration(report, {
386
+ reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_CREDIT_BILLS,
387
+ reason,
388
+ computedAt,
389
+ });
390
+ if (iteration == null)
391
+ return false;
392
+ creditWrites.push({ report, iteration });
393
+ return true;
394
+ };
395
+ const creditStoredDateDoc = creditExistingByScope.get(`${MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
396
+ if (creditCompiledDocs.length === 0) {
397
+ // Orders deleted / moved left the day with NO credit activity: subtract
398
+ // the stored day from the period docs and drop the day/hour documents.
399
+ if (creditStoredDateDoc != null) {
400
+ for (const doc of creditExistingByScope.values()) {
401
+ if (!creditAccumulatedScopes.includes(doc.scope_context))
402
+ continue;
403
+ const updated = updateMaterializedCreditBillsReport(doc, { subtract: [creditStoredDateDoc] }, { computedAt });
404
+ if (updated == null)
405
+ return null;
406
+ if ((updated.iteration ?? 1) === (doc.iteration ?? 1))
407
+ continue; // day not in this doc — no-op
408
+ if (!addCreditWrite(updated))
409
+ return null;
410
+ }
411
+ for (const doc of creditExistingByScope.values()) {
412
+ const onDay = doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
413
+ ? doc.scope_field === localDate
414
+ : doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
415
+ typeof doc.scope_field === 'string' &&
416
+ doc.scope_field.startsWith(`${localDate} `);
417
+ if (onDay)
418
+ creditStaleHourDocuments.push(doc);
419
+ }
420
+ }
421
+ }
422
+ else {
423
+ const creditCompiledByScope = new Map();
424
+ for (const doc of creditCompiledDocs) {
425
+ const key = materializedScopeKey(doc);
426
+ if (creditCompiledByScope.has(key))
427
+ return null; // duplicate scope doc — data issue
428
+ creditCompiledByScope.set(key, doc);
429
+ }
430
+ const creditDateDoc = creditCompiledByScope.get(`${MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
431
+ if (creditDateDoc == null)
432
+ return null;
433
+ const creditDayChanged = force || needsMaterializedCreditBillsReportWrite(creditStoredDateDoc, creditDateDoc);
434
+ for (const compiledCreditDoc of creditCompiledDocs) {
435
+ const existing = creditExistingByScope.get(materializedScopeKey(compiledCreditDoc)) ?? null;
436
+ if (creditDayScopes.includes(compiledCreditDoc.scope_context)) {
437
+ if (!creditDayChanged) {
438
+ if (existing != null)
439
+ creditSkippedDocuments.push(existing);
440
+ // Partial-failure repair: the day is up to date but this doc was never persisted.
441
+ else if (!addCreditWrite(compiledCreditDoc))
442
+ return null;
443
+ continue;
444
+ }
445
+ if (existing == null) {
446
+ if (!addCreditWrite(compiledCreditDoc))
447
+ return null;
448
+ }
449
+ else {
450
+ const updated = updateMaterializedCreditBillsReport(existing, { replacement: compiledCreditDoc }, { computedAt });
451
+ if (updated == null || !addCreditWrite(updated))
452
+ return null;
453
+ }
236
454
  continue;
237
- const patched = updateMaterializedTenantSalesOverviewReport(doc, { received_payments: receivedPayments }, { computedAt });
238
- if (patched == null)
239
- return null;
240
- const iteration = buildMaterializedTenantReportIteration(patched, {
241
- reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
242
- reason,
243
- computedAt,
244
- });
245
- if (iteration == null)
455
+ }
456
+ if (!creditAccumulatedScopes.includes(compiledCreditDoc.scope_context))
457
+ return null; // unknown scope — data issue
458
+ if (existing == null) {
459
+ if (!addCreditWrite(compiledCreditDoc))
460
+ return null;
461
+ continue;
462
+ }
463
+ if (!creditDayChanged) {
464
+ creditSkippedDocuments.push(existing);
465
+ continue;
466
+ }
467
+ const updated = updateMaterializedCreditBillsReport(existing, { subtract: creditStoredDateDoc != null ? [creditStoredDateDoc] : [], additions: [compiledCreditDoc] }, { computedAt });
468
+ if (updated == null || !addCreditWrite(updated))
246
469
  return null;
247
- receivedPatches.push({ report: patched, iteration });
470
+ }
471
+ if (creditDayChanged) {
472
+ for (const doc of creditExistingByScope.values()) {
473
+ if (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
474
+ typeof doc.scope_field === 'string' &&
475
+ doc.scope_field.startsWith(`${localDate} `) &&
476
+ !creditCompiledByScope.has(materializedScopeKey(doc))) {
477
+ creditStaleHourDocuments.push(doc);
478
+ }
479
+ }
480
+ }
481
+ // Settlements patch the ISSUE scopes exactly once — computed against the
482
+ // POST-write credit documents (persist after `creditWrites`), batched per
483
+ // document so several settlements apply in one versioned update.
484
+ if (creditResolution.settled_bills.length > 0) {
485
+ const creditPostWriteByScope = new Map();
486
+ for (const doc of creditExistingByScope.values())
487
+ creditPostWriteByScope.set(materializedScopeKey(doc), doc);
488
+ for (const write of creditWrites)
489
+ creditPostWriteByScope.set(materializedScopeKey(write.report), write.report);
490
+ for (const stale of creditStaleHourDocuments)
491
+ creditPostWriteByScope.delete(materializedScopeKey(stale));
492
+ const settlementsByScope = new Map();
493
+ for (const settlement of creditResolution.settled_bills) {
494
+ const refs = getMaterializedCreditBillScopeRefsForIssue(settlement.issued_local_date, settlement.issued_local_hour);
495
+ if (refs == null)
496
+ return null; // malformed issue date — data issue
497
+ for (const ref of refs) {
498
+ const scopeKey = `${ref.scope_context}|${ref.scope_field}`;
499
+ if (!creditPostWriteByScope.has(scopeKey))
500
+ continue;
501
+ const entries = settlementsByScope.get(scopeKey) ?? [];
502
+ entries.push(settlement);
503
+ settlementsByScope.set(scopeKey, entries);
504
+ }
505
+ }
506
+ for (const [scopeKey, settlements] of settlementsByScope) {
507
+ const doc = creditPostWriteByScope.get(scopeKey);
508
+ if (doc == null)
509
+ continue;
510
+ const patched = updateMaterializedCreditBillsReport(doc, { settled_bills: settlements }, { computedAt });
511
+ if (patched == null)
512
+ return null;
513
+ if ((patched.iteration ?? 1) === (doc.iteration ?? 1))
514
+ continue; // this doc holds none of the bills — no-op
515
+ const iteration = buildMaterializedTenantReportIteration(patched, {
516
+ reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_CREDIT_BILLS,
517
+ reason,
518
+ computedAt,
519
+ });
520
+ if (iteration == null)
521
+ return null;
522
+ creditSettlementPatches.push({ report: patched, iteration });
523
+ }
248
524
  }
249
525
  }
250
- return { writes, staleHourDocuments, receivedPatches, skippedDocuments, createdPeriodDocuments };
526
+ return {
527
+ writes,
528
+ staleHourDocuments,
529
+ receivedPatches,
530
+ creditWrites,
531
+ creditStaleHourDocuments,
532
+ creditSettlementPatches,
533
+ creditSkippedDocuments,
534
+ skippedDocuments,
535
+ createdPeriodDocuments,
536
+ };
251
537
  }
@@ -89,7 +89,7 @@ const pruneMetricsMap = (keyFilters, metrics, filters) => {
89
89
  }
90
90
  return kept;
91
91
  };
92
- /** Drops non-matching keys from a document's metric map (bills included). */
92
+ /** Drops non-matching keys from a document's metric map (credit counters included). */
93
93
  const pruneReportForFilters = (doc, filters) => {
94
94
  const kept = pruneMetricsMap(doc.sale_type_key_filters ?? [], doc.sale_type_metrics, filters);
95
95
  return { ...doc, sale_type_metrics: kept };
@@ -176,7 +176,12 @@ const buildEmptyPageData = (scopeContext, tenantIds) => ({
176
176
  credit_bills: {
177
177
  issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
178
178
  received: { count: 0, amount: 0 },
179
+ outstanding_count: 0,
179
180
  outstanding_amount: 0,
181
+ outstanding_now_count: 0,
182
+ outstanding_now_amount: 0,
183
+ collected_at_issue_count: 0,
184
+ collected_at_issue_amount: 0,
180
185
  },
181
186
  weekday: scopeContext != null && MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext) ? [] : null,
182
187
  hourly: scopeContext === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? [] : null,
@@ -252,6 +257,7 @@ const buildPageDataForDocs = (docs, scopeContext, filters) => {
252
257
  const supportsDayIndex = scopeContext != null && MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext);
253
258
  return buildPageDataFromMetrics(merged, tenantIds, supportsDayIndex ? buildWeekdaySection(scopedDocs, filters) : null, scopeContext === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? buildHourlySection(scopedDocs, filters) : null);
254
259
  };
260
+ const creditLedgerCountersOf = (entry) => entry[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS] ?? {};
255
261
  /**
256
262
  * Shared page assembly — identical for the raw read (one merged document) and
257
263
  * the AGGREGATED read (one pipeline record): every section derives from the
@@ -266,7 +272,18 @@ const buildPageDataFromMetrics = (merged, tenantIds, weekday, hourly) => {
266
272
  const cancelledRaw = createRawOrderMetric();
267
273
  const paymentsMap = {};
268
274
  const channelsMap = {};
269
- const issuedRaw = { count: 0, amount: 0, settled_count: 0, settled_amount: 0 };
275
+ const issuedRaw = {
276
+ count: 0,
277
+ amount: 0,
278
+ settled_count: 0,
279
+ settled_amount: 0,
280
+ outstanding_count: 0,
281
+ outstanding_amount: 0,
282
+ outstanding_now_count: 0,
283
+ outstanding_now_amount: 0,
284
+ collected_at_issue_count: 0,
285
+ collected_at_issue_amount: 0,
286
+ };
270
287
  const receivedRaw = { count: 0, amount: 0 };
271
288
  for (const [key, entry] of Object.entries(merged.sale_type_metrics ?? {})) {
272
289
  const components = parseMaterializedReportKey(key);
@@ -274,7 +291,7 @@ const buildPageDataFromMetrics = (merged, tenantIds, weekday, hourly) => {
274
291
  continue;
275
292
  const totalSales = entry[REPORT_SALE_TYPE_ENUM.TOTAL_SALES];
276
293
  const amountCollected = entry[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED];
277
- const creditBills = entry[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
294
+ const creditBills = creditLedgerCountersOf(entry);
278
295
  // Cancelled facet: cancelled orders are materialized under `CANCELLED:*`
279
296
  // keys and excluded from every other facet (payments included).
280
297
  if (isCancelledKey(components, keyFilters)) {
@@ -286,12 +303,30 @@ const buildPageDataFromMetrics = (merged, tenantIds, weekday, hourly) => {
286
303
  for (const payment of totalSales?.payments ?? []) {
287
304
  addRawPayment(paymentsMap, payment);
288
305
  }
289
- issuedRaw.count += creditBills?.issued?.count ?? 0;
290
- issuedRaw.amount += creditBills?.issued?.amount ?? 0;
291
- issuedRaw.settled_count += creditBills?.issued?.settled_count ?? 0;
292
- issuedRaw.settled_amount += creditBills?.issued?.settled_amount ?? 0;
293
- receivedRaw.count += creditBills?.received?.count ?? 0;
294
- receivedRaw.amount += creditBills?.received?.amount ?? 0;
306
+ const issuedCounters = creditBills.issued ?? {};
307
+ const receivedCounters = creditBills.received ?? {};
308
+ // Stored documents carry COUNTERS only (the itemized ledger lives in
309
+ // `materialized_tenant_credit_bills`) — sum them per KEPT key (client-side
310
+ // filters included). Range-pure extras (`outstanding*`,
311
+ // `collected_at_issue_*`) ride only on AGGREGATED records; stored
312
+ // documents fall back to the ever-settled / zero basis (direct-
313
+ // inspection seam only — the aggregation is the canonical read).
314
+ issuedRaw.count += issuedCounters.count ?? 0;
315
+ issuedRaw.amount += issuedCounters.amount ?? 0;
316
+ issuedRaw.settled_count += issuedCounters.settled_count ?? 0;
317
+ issuedRaw.settled_amount += issuedCounters.settled_amount ?? 0;
318
+ const outstandingCountFallback = Math.max(0, (issuedCounters.count ?? 0) - (issuedCounters.settled_count ?? 0));
319
+ const outstandingAmountFallback = Math.max(0, (issuedCounters.amount ?? 0) - (issuedCounters.settled_amount ?? 0));
320
+ issuedRaw.outstanding_count += issuedCounters.outstanding_count ?? outstandingCountFallback;
321
+ issuedRaw.outstanding_amount += issuedCounters.outstanding_amount ?? outstandingAmountFallback;
322
+ issuedRaw.outstanding_now_count +=
323
+ issuedCounters.outstanding_now_count ?? issuedCounters.outstanding_count ?? outstandingCountFallback;
324
+ issuedRaw.outstanding_now_amount +=
325
+ issuedCounters.outstanding_now_amount ?? issuedCounters.outstanding_amount ?? outstandingAmountFallback;
326
+ issuedRaw.collected_at_issue_count += issuedCounters.collected_at_issue_count ?? 0;
327
+ issuedRaw.collected_at_issue_amount += issuedCounters.collected_at_issue_amount ?? 0;
328
+ receivedRaw.count += receivedCounters.count ?? 0;
329
+ receivedRaw.amount += receivedCounters.amount ?? 0;
295
330
  const platform = getKeyDimValue(components, keyFilters, MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM) ?? '';
296
331
  const channel = channelsMap[platform] ?? (channelsMap[platform] = { platform, count: 0, gross_amount: 0 });
297
332
  channel.count += totalSales?.orders?.count ?? 0;
@@ -334,7 +369,12 @@ const buildPageDataFromMetrics = (merged, tenantIds, weekday, hourly) => {
334
369
  settled_amount: toDecimal(issuedRaw.settled_amount),
335
370
  },
336
371
  received: { count: receivedRaw.count, amount: toDecimal(receivedRaw.amount) },
337
- outstanding_amount: toDecimal(issuedRaw.amount - issuedRaw.settled_amount),
372
+ outstanding_count: issuedRaw.outstanding_count,
373
+ outstanding_amount: toDecimal(issuedRaw.outstanding_amount),
374
+ outstanding_now_count: issuedRaw.outstanding_now_count,
375
+ outstanding_now_amount: toDecimal(issuedRaw.outstanding_now_amount),
376
+ collected_at_issue_count: issuedRaw.collected_at_issue_count,
377
+ collected_at_issue_amount: toDecimal(issuedRaw.collected_at_issue_amount),
338
378
  },
339
379
  weekday,
340
380
  hourly,
@@ -407,7 +447,18 @@ const mergeAggregatedKeyMetrics = (reports) => {
407
447
  [TOTAL_SALES]: { orders: createRawOrderMetric(), payments: [] },
408
448
  [AMOUNT_COLLECTED]: { orders: createRawOrderMetric() },
409
449
  [CREDIT_BILLS]: {
410
- issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
450
+ issued: {
451
+ count: 0,
452
+ amount: 0,
453
+ settled_count: 0,
454
+ settled_amount: 0,
455
+ outstanding_count: 0,
456
+ outstanding_amount: 0,
457
+ outstanding_now_count: 0,
458
+ outstanding_now_amount: 0,
459
+ collected_at_issue_count: 0,
460
+ collected_at_issue_amount: 0,
461
+ },
411
462
  received: { count: 0, amount: 0 },
412
463
  },
413
464
  });
@@ -420,6 +471,16 @@ const mergeAggregatedKeyMetrics = (reports) => {
420
471
  entry[CREDIT_BILLS].issued.amount += metrics[CREDIT_BILLS]?.issued?.amount ?? 0;
421
472
  entry[CREDIT_BILLS].issued.settled_count += metrics[CREDIT_BILLS]?.issued?.settled_count ?? 0;
422
473
  entry[CREDIT_BILLS].issued.settled_amount += metrics[CREDIT_BILLS]?.issued?.settled_amount ?? 0;
474
+ entry[CREDIT_BILLS].issued.outstanding_count += metrics[CREDIT_BILLS]?.issued?.outstanding_count ?? 0;
475
+ entry[CREDIT_BILLS].issued.outstanding_amount += metrics[CREDIT_BILLS]?.issued?.outstanding_amount ?? 0;
476
+ entry[CREDIT_BILLS].issued.outstanding_now_count += metrics[CREDIT_BILLS]?.issued?.outstanding_now_count ?? 0;
477
+ entry[CREDIT_BILLS].issued.outstanding_now_amount += metrics[CREDIT_BILLS]?.issued?.outstanding_now_amount ?? 0;
478
+ // At-issue money rides as a COUNTER on aggregated records (derived from
479
+ // the ledger rows server-side); stored documents degrade to 0.
480
+ entry[CREDIT_BILLS].issued.collected_at_issue_count +=
481
+ metrics[CREDIT_BILLS]?.issued?.collected_at_issue_count ?? 0;
482
+ entry[CREDIT_BILLS].issued.collected_at_issue_amount +=
483
+ metrics[CREDIT_BILLS]?.issued?.collected_at_issue_amount ?? 0;
423
484
  entry[CREDIT_BILLS].received.count += metrics[CREDIT_BILLS]?.received?.count ?? 0;
424
485
  entry[CREDIT_BILLS].received.amount += metrics[CREDIT_BILLS]?.received?.amount ?? 0;
425
486
  }