@managesome/eposmatic-toolkit 0.4.5 → 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 (68) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +33 -0
  2. package/esm/constants/REPORT_CALENDAR.js +47 -0
  3. package/esm/constants/index.js +1 -0
  4. package/esm/helpers/materialized-reports/index.js +2 -0
  5. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +982 -0
  6. package/esm/helpers/materialized-reports/materialized-reports-read-helpers.js +1 -76
  7. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +716 -0
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +327 -41
  9. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  10. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +118 -235
  11. package/esm/helpers/types/index.js +1 -0
  12. package/esm/schemas/models/index.js +1 -0
  13. package/esm/schemas/models/materialized_credit_bills.js +265 -0
  14. package/esm/schemas/models/materialized_tenant_reports_iterations.js +13 -0
  15. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +39 -97
  16. package/esm/schemas/types/index.js +1 -0
  17. package/esm/schemas/types/materialized_credit_bills.js +1 -0
  18. package/lib/constants/MATERIALIZED_REPORTS.d.ts +28 -2
  19. package/lib/constants/MATERIALIZED_REPORTS.js +34 -1
  20. package/lib/constants/REPORT_CALENDAR.d.ts +31 -0
  21. package/lib/constants/REPORT_CALENDAR.js +50 -0
  22. package/lib/constants/index.d.ts +1 -0
  23. package/lib/constants/index.js +1 -0
  24. package/lib/helpers/materialized-reports/index.d.ts +2 -0
  25. package/lib/helpers/materialized-reports/index.js +2 -0
  26. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +307 -0
  27. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +1003 -0
  28. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.d.ts +0 -30
  29. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.js +0 -76
  30. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +59 -0
  31. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +723 -0
  32. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +66 -8
  33. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +326 -40
  34. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +18 -2
  35. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  36. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +46 -37
  37. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +119 -238
  38. package/lib/helpers/types/index.d.ts +1 -0
  39. package/lib/helpers/types/index.js +1 -0
  40. package/lib/helpers/types/materialized-reports-apis.d.ts +46 -17
  41. package/lib/helpers/types/report-calendar.d.ts +20 -0
  42. package/lib/helpers/types/report-calendar.js +2 -0
  43. package/lib/schemas/models/index.d.ts +1 -0
  44. package/lib/schemas/models/index.js +1 -0
  45. package/lib/schemas/models/materialized_credit_bills.d.ts +337 -0
  46. package/lib/schemas/models/materialized_credit_bills.js +268 -0
  47. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +20 -6
  48. package/lib/schemas/models/materialized_tenant_reports_iterations.js +14 -1
  49. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +37 -165
  50. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +40 -98
  51. package/lib/schemas/types/index.d.ts +1 -0
  52. package/lib/schemas/types/index.js +1 -0
  53. package/lib/schemas/types/materialized_credit_bills.d.ts +139 -0
  54. package/lib/schemas/types/materialized_credit_bills.js +2 -0
  55. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +32 -77
  56. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.d.ts +1 -0
  57. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +715 -0
  58. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.d.ts +1 -0
  59. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +262 -0
  60. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +9 -0
  61. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +23 -24
  62. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +327 -22
  63. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +27 -2
  64. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +12 -27
  65. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +79 -146
  66. package/package.json +1 -1
  67. package/lib/tests/materialized-reports/materialized-reports-read-helpers.test.js +0 -100
  68. /package/{lib/tests/materialized-reports/materialized-reports-read-helpers.test.d.ts → esm/helpers/types/report-calendar.js} +0 -0
@@ -1,4 +1,5 @@
1
1
  import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { IMaterializedTenantCreditBillsReport } from '../../schemas/types/materialized_credit_bills';
2
3
  import { IMaterializedTenantReportIterationInput } from '../../schemas/types/materialized_tenant_reports_iterations';
3
4
  import { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
4
5
  import { IConvertOrdersToMaterializedReportsResult } from './tenant-sales-overview-helpers';
@@ -8,7 +9,9 @@ import { IConvertOrdersToMaterializedReportsResult } from './tenant-sales-overvi
8
9
  *
9
10
  * The day-close job compiles one tenant-day (`convertOrdersTo…`), fetches the
10
11
  * stored documents the plan needs (`getMaterializedTenantSalesOverviewScopeRefsForDay`
11
- * + the issue-day docs of collected bills), and asks this module for the
12
+ * + `getMaterializedCreditBillScopeRefsForDay` of the compiled day and, for
13
+ * every collected bill's issue day,
14
+ * `getMaterializedCreditBillScopeRefsForIssue`), and asks this module for the
12
15
  * complete write plan:
13
16
  *
14
17
  * - **`writes`** — hour + date documents (insert, or `replacement` when stored
@@ -18,12 +21,32 @@ import { IConvertOrdersToMaterializedReportsResult } from './tenant-sales-overvi
18
21
  * `materialized_tenant_reports_iterations` history row; persist both.
19
22
  * - **`staleHourDocuments`** — stored `localHour` docs of the day with no
20
23
  * activity anymore (orders deleted / moved) — delete by `_id`.
21
- * - **`receivedPatches`** — issue-day docs holding bills collected on the
22
- * compiled day, patched through `update(…, { received_payments })`. A
23
- * ledger-changing patch is a versioned write, so each patched document
24
- * comes with its history row; computed against the POST-write documents,
25
- * so a period doc that both accumulates the day and holds an earlier bill
26
- * keeps the accumulation — persist them AFTER `writes`.
24
+ * - **`creditWrites`** — the day's `materialized_tenant_credit_bills`
25
+ * documents (month-capped scopes: hour/date/week/ISO-week/month), fed by the
26
+ * SAME resolution as the counters (single writer — the two collections can
27
+ * never drift). The ledger is single-source: report documents hold credit
28
+ * COUNTERS only.
29
+ * - **`creditSettlementPatches`** — issue-scope credit documents patched with
30
+ * settlement anchors (`received_amount` + `settled_*` + note) exactly once
31
+ * per settlement; versioned writes, persist AFTER `creditWrites`.
32
+ * - **`creditStaleHourDocuments`** — stored credit hour docs of the day with
33
+ * no entries anymore (orders deleted / moved; an emptied day also drops its
34
+ * date doc) — delete by `_id`.
35
+ * - **`creditSkippedDocuments`** — credit documents already up to date.
36
+ * - **`receivedPatches`** — issued-day documents patched with SETTLED
37
+ * COUNTER deltas (`settled_count` +1 / `settled_amount` + `amount`) when a
38
+ * stored ledger row passes its unsettled→settled transition; counters only,
39
+ * a versioned write each, computed against the POST-write documents — so a
40
+ * period doc that both accumulates the day and holds an earlier bill keeps
41
+ * the accumulation; persist them AFTER `writes`.
42
+ * - **resolution (the only stateful step)** — `resolveCreditBillDay` resolves
43
+ * each receipt event's `received_delta` against the stored credit DOCUMENTS
44
+ * (a stored same-day event's delta is preserved → idempotent re-closes),
45
+ * carries each bill's `received_at_issue` / settlement anchors forward (a
46
+ * re-close after collection must never re-anchor them) and emits the
47
+ * settlements the close must patch. The plan fills the compiled
48
+ * collection-day documents' `received` COUNTERS and builds the credit
49
+ * documents from that ONE resolution.
27
50
  * - **`skippedDocuments`** — already up to date (see
28
51
  * `needsMaterializedTenantSalesOverviewReportWrite`).
29
52
  * - **`createdPeriodDocuments`** — period docs that were absent from
@@ -58,6 +81,17 @@ export interface IBuildTenantSalesOverviewCloseDayPlanInput {
58
81
  * fetch refs) is fine; two different rows for one scope key → `null`.
59
82
  */
60
83
  existing?: IMaterializedTenantSalesOverviewReport[];
84
+ /**
85
+ * Stored `materialized_tenant_credit_bills` documents the job fetched: the
86
+ * compiled day's scopes (`getMaterializedCreditBillScopeRefsForDay`) PLUS
87
+ * the issue scopes of every collected bill
88
+ * (`getMaterializedCreditBillScopeRefsForIssue`). The close plan resolves
89
+ * receipt deltas and carries settlement anchors forward against THESE
90
+ * documents, then materializes the day's credit documents from the same
91
+ * resolution. Repeating the SAME document is fine; two different rows for
92
+ * one scope key → `null`.
93
+ */
94
+ existingCreditBills?: IMaterializedTenantCreditBillsReport[];
61
95
  /** Force structural writes even when the watermarks are up to date. */
62
96
  force?: boolean;
63
97
  /** Override for write timestamps (tests, replays). */
@@ -70,13 +104,37 @@ export interface ITenantSalesOverviewCloseDayWrite {
70
104
  /** `materialized_tenant_reports_iterations` row — upsert by `(report_id, iteration)`. */
71
105
  iteration: IMaterializedTenantReportIterationInput;
72
106
  }
107
+ /** One versioned credit write (structural write or settlement patch): persist `report` + upsert its history row. */
108
+ export interface ITenantCreditBillsCloseDayWrite {
109
+ /** Post-write document (stored `_id` kept for replacements). */
110
+ report: IMaterializedTenantCreditBillsReport;
111
+ /** `materialized_tenant_reports_iterations` row — upsert by `(report_id, iteration)`. */
112
+ iteration: IMaterializedTenantReportIterationInput<IMaterializedTenantCreditBillsReport>;
113
+ }
73
114
  /** The complete close-day write plan (see the module docs). */
74
115
  export interface ITenantSalesOverviewCloseDayPlan {
75
116
  /** Structural writes (report + history row) — persist in any order. */
76
117
  writes: ITenantSalesOverviewCloseDayWrite[];
77
118
  /** Stored hour docs of the compiled day no longer backed by activity — delete by `_id`. */
78
119
  staleHourDocuments: IMaterializedTenantSalesOverviewReport[];
79
- /** Issued-ledger patches (versioned writes) — persist AFTER `writes`. */
120
+ /**
121
+ * `materialized_tenant_credit_bills` writes (month-capped scopes) — the
122
+ * itemized ledger; persist BEFORE the settlement patches below.
123
+ */
124
+ creditWrites: ITenantCreditBillsCloseDayWrite[];
125
+ /** Stored credit hour/docs of the day no longer backed by entries — delete by `_id`. */
126
+ creditStaleHourDocuments: IMaterializedTenantCreditBillsReport[];
127
+ /** Credit documents already up to date (freshness proven by the watermark guard). */
128
+ creditSkippedDocuments: IMaterializedTenantCreditBillsReport[];
129
+ /**
130
+ * Issue-scope settlement patches (versioned credit writes) — persist AFTER
131
+ * `creditWrites` (computed against the post-write documents).
132
+ */
133
+ creditSettlementPatches: ITenantCreditBillsCloseDayWrite[];
134
+ /**
135
+ * Issued-day SETTLED counter patches (versioned writes, counters only) —
136
+ * persist AFTER `writes` (computed against the post-write documents).
137
+ */
80
138
  receivedPatches: ITenantSalesOverviewCloseDayWrite[];
81
139
  /** Stored docs that were already up to date (job logging). */
82
140
  skippedDocuments: IMaterializedTenantSalesOverviewReport[];
@@ -5,6 +5,7 @@ exports.needsMaterializedTenantSalesOverviewReportWrite = needsMaterializedTenan
5
5
  exports.buildTenantSalesOverviewCloseDayPlan = buildTenantSalesOverviewCloseDayPlan;
6
6
  const constants_1 = require("../../constants");
7
7
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
8
+ const materialized_credit_bills_helpers_1 = require("./materialized-credit-bills-helpers");
8
9
  const materialized_tenant_reports_iterations_helpers_1 = require("./materialized-tenant-reports-iterations-helpers");
9
10
  const scope_helpers_1 = require("./scope-helpers");
10
11
  const tenant_sales_overview_helpers_1 = require("./tenant-sales-overview-helpers");
@@ -23,7 +24,6 @@ const CLOSE_DAY_ACCUMULATED_SCOPES = [
23
24
  MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
24
25
  ];
25
26
  const materializedScopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
26
- const materializedCreditBillKey = (orderId, paymentId) => `${orderId}|${paymentId}`;
27
27
  const hasMaterializedMetrics = (doc) => Object.keys((0, tenant_sales_overview_helpers_1.normalizeMaterializedSaleTypeMetrics)(doc.sale_type_metrics)).length > 0;
28
28
  /**
29
29
  * Every stored scope the fan-out of one local day needs: the six period
@@ -73,27 +73,6 @@ function needsMaterializedTenantSalesOverviewReportWrite(existing, incoming) {
73
73
  return true;
74
74
  return incomingTime > existingTime;
75
75
  }
76
- /** Would a received-payment patch change the stored bill? (settlement/note/received) */
77
- const creditBillWouldChange = (bill, collected) => {
78
- const received = Math.max(bill.received_amount ?? 0, collected.received_amount ?? 0);
79
- if (received !== (bill.received_amount ?? 0))
80
- return true;
81
- const note = bill.credit_note ?? collected.credit_note;
82
- if ((note ?? null) !== (bill.credit_note ?? null))
83
- return true;
84
- return bill.settled_at == null && received >= (bill.amount ?? 0);
85
- };
86
- /** Does the document hold an issued bill that one of the collected payments would change? */
87
- const documentHoldsUnpatchedCreditBill = (doc, collectedByBill) => {
88
- for (const keyMetrics of Object.values((0, tenant_sales_overview_helpers_1.normalizeMaterializedSaleTypeMetrics)(doc.sale_type_metrics))) {
89
- for (const bill of keyMetrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]?.issued?.bills ?? []) {
90
- const collected = collectedByBill.get(materializedCreditBillKey(bill.order_id, bill.payment_id));
91
- if (collected != null && creditBillWouldChange(bill, collected))
92
- return true;
93
- }
94
- }
95
- return false;
96
- };
97
76
  /**
98
77
  * Builds the close-day write plan for ONE tenant-day (see the module docs).
99
78
  * Returns `null` (never throws) when the input is inconsistent — compiled
@@ -146,6 +125,100 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
146
125
  if (String(prior._id) !== String(doc._id))
147
126
  return null;
148
127
  }
128
+ // ------------------------------------------------------------------
129
+ // Resolve THIS day against the stored credit ledger documents — the only
130
+ // stateful step (receipt deltas, carried anchors, settlements), executed
131
+ // ONCE and shared by the report counters and the credit documents below
132
+ // (single writer: the two collections can never drift).
133
+ // - receipt events: a stored same-day event keeps its own `received_delta`
134
+ // (idempotent re-closes); a new event's delta resolves as the compile
135
+ // cumulative minus the stored cumulative (clamped at 0). Out-of-order
136
+ // backfills of a MISSED day can still misattribute a large delta to that
137
+ // day — closes are assumed to run chronologically per tenant (documented).
138
+ // - issued bills: `received_at_issue` / settlement anchors carry forward —
139
+ // a re-close AFTER collection never re-anchors them.
140
+ const creditResolution = (0, materialized_credit_bills_helpers_1.resolveCreditBillDay)({
141
+ tenantId,
142
+ localDate,
143
+ issued: compile.credit_bill_issues,
144
+ events: compile.credit_bill_events,
145
+ stored: input.existingCreditBills,
146
+ computedAt,
147
+ });
148
+ if (creditResolution == null)
149
+ return null;
150
+ // Fill the compiled collection-day documents' `received` COUNTERS from the
151
+ // resolved deltas (the compile cannot know them): hour docs take their
152
+ // event's hour, period docs the whole day; null-hour events count on the
153
+ // day-shaped scopes only (never on an hour doc).
154
+ const periodFieldsNow = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
155
+ if (periodFieldsNow == null)
156
+ return null;
157
+ const receivedByScopeKey = new Map();
158
+ for (const resolved of creditResolution.received_events) {
159
+ const key = resolved.key;
160
+ const delta = resolved.entry.received_delta ?? 0;
161
+ const scopeFields = Object.entries(periodFieldsNow).map(([scopeContext, scopeField]) => ({
162
+ scope_context: scopeContext,
163
+ scope_field: scopeField,
164
+ }));
165
+ if (resolved.entry.event_local_hour != null) {
166
+ scopeFields.push({
167
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
168
+ scope_field: resolved.entry.event_local_hour,
169
+ });
170
+ }
171
+ for (const scope of scopeFields) {
172
+ const mapKey = `${scope.scope_context}|${scope.scope_field}|${key}`;
173
+ const entry = receivedByScopeKey.get(mapKey) ?? { count: 0, amount: 0 };
174
+ entry.count += 1;
175
+ entry.amount += delta;
176
+ receivedByScopeKey.set(mapKey, entry);
177
+ }
178
+ }
179
+ for (const compiledDoc of compiledReports) {
180
+ const metrics = compiledDoc.sale_type_metrics;
181
+ for (const [key, metric] of Object.entries(metrics ?? {})) {
182
+ const entry = receivedByScopeKey.get(`${compiledDoc.scope_context}|${compiledDoc.scope_field}|${key}`);
183
+ metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received = entry != null ? { ...entry } : { count: 0, amount: 0 };
184
+ }
185
+ }
186
+ // The compile derives ISSUED counters from the CURRENT order state — a
187
+ // never-settled view — so an ISSUE-DAY re-close after collection would
188
+ // regress the settled counters (and the N2 rule reads settled-later bills
189
+ // as unsettled at issue). The resolution carries the stored settlement
190
+ // anchors forward: OVERWRITE the compiled day's settled counters from the
191
+ // resolved issued entries (all of today's issues by construction).
192
+ //
193
+ // SEMANTICS (audit R5-4): these REPORT counters are EVER-SETTLED (NOW
194
+ // state) — a bill settled on any later day counts here. The range-pure
195
+ // as-of-end answer (`settled_local_date <= selection end`) comes from
196
+ // `computeMaterializedCreditBillTotalsFromReports` over the credit
197
+ // documents; the two legitimately differ for historical ranges and must
198
+ // never be rendered side-by-side without labeling (Phase C).
199
+ const settledByKey = new Map();
200
+ for (const resolved of creditResolution.issued) {
201
+ const entry = resolved.entry;
202
+ if (entry.settled_at == null && entry.settled_local_date == null)
203
+ continue;
204
+ const totals = settledByKey.get(resolved.key) ?? { count: 0, amount: 0 };
205
+ totals.count += 1;
206
+ totals.amount += entry.amount ?? 0;
207
+ settledByKey.set(resolved.key, totals);
208
+ }
209
+ for (const compiledDoc of compiledReports) {
210
+ const metrics = compiledDoc.sale_type_metrics;
211
+ for (const [key, metric] of Object.entries(metrics ?? {})) {
212
+ const entry = settledByKey.get(key);
213
+ metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_count = entry?.count ?? 0;
214
+ metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_amount = entry?.amount ?? 0;
215
+ }
216
+ }
217
+ // Bills that settled on a LATER day than their issue day need the issue-day
218
+ // documents' SETTLED counters patched (the itemized ledger lives in
219
+ // `materialized_tenant_credit_bills`; report documents keep constant-size
220
+ // counters). The resolution emits each settlement exactly once.
221
+ const settledTransitions = creditResolution.settled_bills;
149
222
  const storedDateDoc = existingByScope.get(materializedScopeKey(compiledDateDoc)) ?? null;
150
223
  const dayChanged = force || needsMaterializedTenantSalesOverviewReportWrite(storedDateDoc, compiledDateDoc);
151
224
  const dayDeltaEmpty = !hasMaterializedMetrics(compiledDateDoc);
@@ -229,28 +302,241 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
229
302
  postWriteByScope.set(materializedScopeKey(write.report), write.report);
230
303
  for (const stale of staleHourDocuments)
231
304
  postWriteByScope.delete(materializedScopeKey(stale));
305
+ // Batch the settled-counter deltas per document first — several transitions
306
+ // can hit one document, and every patch must be computed from the same
307
+ // pre-patch state with ALL deltas applied in a single update.
308
+ const settledDeltasByDoc = new Map();
309
+ for (const transition of settledTransitions) {
310
+ const billKey = transition.key;
311
+ const issuePeriodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(transition.issued_local_date);
312
+ if (issuePeriodFields == null)
313
+ return null; // malformed issue date — data issue
314
+ const issueScopeValues = new Set([transition.issued_local_date, ...Object.values(issuePeriodFields)]);
315
+ for (const [scopeKey, doc] of postWriteByScope) {
316
+ const scopeOnIssueDay = issueScopeValues.has(doc.scope_field) ||
317
+ (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
318
+ typeof doc.scope_field === 'string' &&
319
+ doc.scope_field.startsWith(`${transition.issued_local_date} `));
320
+ if (!scopeOnIssueDay)
321
+ continue;
322
+ const metrics = (0, tenant_sales_overview_helpers_1.normalizeMaterializedSaleTypeMetrics)(doc.sale_type_metrics);
323
+ if (metrics[billKey]?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS] == null)
324
+ continue;
325
+ const entries = settledDeltasByDoc.get(scopeKey) ?? [];
326
+ entries.push({ key: billKey, amount: transition.amount });
327
+ settledDeltasByDoc.set(scopeKey, entries);
328
+ }
329
+ }
232
330
  const receivedPatches = [];
233
- const receivedPayments = compile.received_payments ?? [];
234
- if (receivedPayments.length > 0) {
235
- const collectedByBill = new Map();
236
- for (const collected of receivedPayments) {
237
- collectedByBill.set(materializedCreditBillKey(collected.order_id, collected.payment_id), collected);
331
+ for (const [scopeKey, entries] of settledDeltasByDoc) {
332
+ const doc = postWriteByScope.get(scopeKey);
333
+ if (doc == null)
334
+ continue;
335
+ const patched = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(doc, { settled_credit_bills: entries }, { computedAt });
336
+ if (patched == null)
337
+ return null;
338
+ const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(patched, {
339
+ reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
340
+ reason,
341
+ computedAt,
342
+ });
343
+ if (iteration == null)
344
+ return null;
345
+ receivedPatches.push({ report: patched, iteration });
346
+ }
347
+ // ------------------------------------------------------------------
348
+ // Credit-bill documents (`materialized_tenant_credit_bills`) — materialized
349
+ // from the SAME resolution as the counters above (single writer): the
350
+ // month-capped scopes only (hour/date/week/ISO-week/month), so no document
351
+ // can grow unbounded while year/multi-year reads cover their range with the
352
+ // month documents.
353
+ // ------------------------------------------------------------------
354
+ const creditDayScopes = [
355
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
356
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
357
+ ];
358
+ const creditAccumulatedScopes = [
359
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
360
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
361
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
362
+ ];
363
+ const creditCompiledDocs = (0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillDayReports)({
364
+ tenantId,
365
+ brandId: compiledDateDoc.brand_id,
366
+ localDate,
367
+ resolution: creditResolution,
368
+ computedAt,
369
+ });
370
+ if (creditCompiledDocs == null)
371
+ return null;
372
+ const creditExistingByScope = new Map();
373
+ for (const doc of input.existingCreditBills ?? []) {
374
+ if (doc == null || doc.tenant_id !== tenantId)
375
+ continue;
376
+ const key = materializedScopeKey(doc);
377
+ const prior = creditExistingByScope.get(key);
378
+ if (prior == null) {
379
+ creditExistingByScope.set(key, doc);
380
+ continue;
381
+ }
382
+ if (String(prior._id) !== String(doc._id))
383
+ return null; // duplicate rows — data issue
384
+ }
385
+ const creditWrites = [];
386
+ const creditSkippedDocuments = [];
387
+ const creditStaleHourDocuments = [];
388
+ const creditSettlementPatches = [];
389
+ const addCreditWrite = (report) => {
390
+ const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(report, {
391
+ reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_CREDIT_BILLS,
392
+ reason,
393
+ computedAt,
394
+ });
395
+ if (iteration == null)
396
+ return false;
397
+ creditWrites.push({ report, iteration });
398
+ return true;
399
+ };
400
+ const creditStoredDateDoc = creditExistingByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
401
+ if (creditCompiledDocs.length === 0) {
402
+ // Orders deleted / moved left the day with NO credit activity: subtract
403
+ // the stored day from the period docs and drop the day/hour documents.
404
+ if (creditStoredDateDoc != null) {
405
+ for (const doc of creditExistingByScope.values()) {
406
+ if (!creditAccumulatedScopes.includes(doc.scope_context))
407
+ continue;
408
+ const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(doc, { subtract: [creditStoredDateDoc] }, { computedAt });
409
+ if (updated == null)
410
+ return null;
411
+ if ((updated.iteration ?? 1) === (doc.iteration ?? 1))
412
+ continue; // day not in this doc — no-op
413
+ if (!addCreditWrite(updated))
414
+ return null;
415
+ }
416
+ for (const doc of creditExistingByScope.values()) {
417
+ const onDay = doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
418
+ ? doc.scope_field === localDate
419
+ : doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
420
+ typeof doc.scope_field === 'string' &&
421
+ doc.scope_field.startsWith(`${localDate} `);
422
+ if (onDay)
423
+ creditStaleHourDocuments.push(doc);
424
+ }
425
+ }
426
+ }
427
+ else {
428
+ const creditCompiledByScope = new Map();
429
+ for (const doc of creditCompiledDocs) {
430
+ const key = materializedScopeKey(doc);
431
+ if (creditCompiledByScope.has(key))
432
+ return null; // duplicate scope doc — data issue
433
+ creditCompiledByScope.set(key, doc);
238
434
  }
239
- for (const doc of postWriteByScope.values()) {
240
- if (!documentHoldsUnpatchedCreditBill(doc, collectedByBill))
435
+ const creditDateDoc = creditCompiledByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
436
+ if (creditDateDoc == null)
437
+ return null;
438
+ const creditDayChanged = force || (0, materialized_credit_bills_helpers_1.needsMaterializedCreditBillsReportWrite)(creditStoredDateDoc, creditDateDoc);
439
+ for (const compiledCreditDoc of creditCompiledDocs) {
440
+ const existing = creditExistingByScope.get(materializedScopeKey(compiledCreditDoc)) ?? null;
441
+ if (creditDayScopes.includes(compiledCreditDoc.scope_context)) {
442
+ if (!creditDayChanged) {
443
+ if (existing != null)
444
+ creditSkippedDocuments.push(existing);
445
+ // Partial-failure repair: the day is up to date but this doc was never persisted.
446
+ else if (!addCreditWrite(compiledCreditDoc))
447
+ return null;
448
+ continue;
449
+ }
450
+ if (existing == null) {
451
+ if (!addCreditWrite(compiledCreditDoc))
452
+ return null;
453
+ }
454
+ else {
455
+ const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { replacement: compiledCreditDoc }, { computedAt });
456
+ if (updated == null || !addCreditWrite(updated))
457
+ return null;
458
+ }
241
459
  continue;
242
- const patched = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(doc, { received_payments: receivedPayments }, { computedAt });
243
- if (patched == null)
244
- return null;
245
- const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(patched, {
246
- reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
247
- reason,
248
- computedAt,
249
- });
250
- if (iteration == null)
460
+ }
461
+ if (!creditAccumulatedScopes.includes(compiledCreditDoc.scope_context))
462
+ return null; // unknown scope — data issue
463
+ if (existing == null) {
464
+ if (!addCreditWrite(compiledCreditDoc))
465
+ return null;
466
+ continue;
467
+ }
468
+ if (!creditDayChanged) {
469
+ creditSkippedDocuments.push(existing);
470
+ continue;
471
+ }
472
+ const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { subtract: creditStoredDateDoc != null ? [creditStoredDateDoc] : [], additions: [compiledCreditDoc] }, { computedAt });
473
+ if (updated == null || !addCreditWrite(updated))
251
474
  return null;
252
- receivedPatches.push({ report: patched, iteration });
475
+ }
476
+ if (creditDayChanged) {
477
+ for (const doc of creditExistingByScope.values()) {
478
+ if (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
479
+ typeof doc.scope_field === 'string' &&
480
+ doc.scope_field.startsWith(`${localDate} `) &&
481
+ !creditCompiledByScope.has(materializedScopeKey(doc))) {
482
+ creditStaleHourDocuments.push(doc);
483
+ }
484
+ }
485
+ }
486
+ // Settlements patch the ISSUE scopes exactly once — computed against the
487
+ // POST-write credit documents (persist after `creditWrites`), batched per
488
+ // document so several settlements apply in one versioned update.
489
+ if (creditResolution.settled_bills.length > 0) {
490
+ const creditPostWriteByScope = new Map();
491
+ for (const doc of creditExistingByScope.values())
492
+ creditPostWriteByScope.set(materializedScopeKey(doc), doc);
493
+ for (const write of creditWrites)
494
+ creditPostWriteByScope.set(materializedScopeKey(write.report), write.report);
495
+ for (const stale of creditStaleHourDocuments)
496
+ creditPostWriteByScope.delete(materializedScopeKey(stale));
497
+ const settlementsByScope = new Map();
498
+ for (const settlement of creditResolution.settled_bills) {
499
+ const refs = (0, materialized_credit_bills_helpers_1.getMaterializedCreditBillScopeRefsForIssue)(settlement.issued_local_date, settlement.issued_local_hour);
500
+ if (refs == null)
501
+ return null; // malformed issue date — data issue
502
+ for (const ref of refs) {
503
+ const scopeKey = `${ref.scope_context}|${ref.scope_field}`;
504
+ if (!creditPostWriteByScope.has(scopeKey))
505
+ continue;
506
+ const entries = settlementsByScope.get(scopeKey) ?? [];
507
+ entries.push(settlement);
508
+ settlementsByScope.set(scopeKey, entries);
509
+ }
510
+ }
511
+ for (const [scopeKey, settlements] of settlementsByScope) {
512
+ const doc = creditPostWriteByScope.get(scopeKey);
513
+ if (doc == null)
514
+ continue;
515
+ const patched = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(doc, { settled_bills: settlements }, { computedAt });
516
+ if (patched == null)
517
+ return null;
518
+ if ((patched.iteration ?? 1) === (doc.iteration ?? 1))
519
+ continue; // this doc holds none of the bills — no-op
520
+ const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(patched, {
521
+ reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_CREDIT_BILLS,
522
+ reason,
523
+ computedAt,
524
+ });
525
+ if (iteration == null)
526
+ return null;
527
+ creditSettlementPatches.push({ report: patched, iteration });
528
+ }
253
529
  }
254
530
  }
255
- return { writes, staleHourDocuments, receivedPatches, skippedDocuments, createdPeriodDocuments };
531
+ return {
532
+ writes,
533
+ staleHourDocuments,
534
+ receivedPatches,
535
+ creditWrites,
536
+ creditStaleHourDocuments,
537
+ creditSettlementPatches,
538
+ creditSkippedDocuments,
539
+ skippedDocuments,
540
+ createdPeriodDocuments,
541
+ };
256
542
  }
@@ -18,7 +18,8 @@ import { IMaterializedTenantSalesOverviewAggregatedReport } from '../types/mater
18
18
  * scopes only) and hour series are ordered by business-hour index
19
19
  * (`06…23, 00…05`) — never lexicographically;
20
20
  * - the brand-level combined view sums across tenants (`allowTenantMismatch`
21
- * on the sum helper; bills stay de-duplicated by `(order_id, payment_id)`).
21
+ * on the sum helper; credit COUNTERS sum by key — the itemized ledger
22
+ * lives in `materialized_tenant_credit_bills`).
22
23
  *
23
24
  * Validation convention: returns `null` instead of throwing when the input
24
25
  * cannot be formatted (non-array, mixed scopes / key filters / schema
@@ -82,15 +83,30 @@ export interface IFormattedSalesOverviewCreditBills {
82
83
  issued: {
83
84
  count: number;
84
85
  amount: number;
86
+ /** Fully settled BY THE SELECTION END (range-pure on aggregated reads). */
85
87
  settled_count: number;
88
+ /** Σ `amount` of fully settled bills — partial receipts never count here. */
86
89
  settled_amount: number;
87
90
  };
88
91
  received: {
89
92
  count: number;
90
93
  amount: number;
91
94
  };
92
- /** `issued.amount − issued.settled_amount` — still outstanding. */
95
+ /**
96
+ * Money in hand AT ISSUE across the issued-in-selection bills (Σ
97
+ * `received_at_issue`): same-day settled credit + the prepaid part of
98
+ * partial bills. The Amount Collected KPI adds this to `received.amount`
99
+ * (later-day receipt events) — together they are ALL credit money in.
100
+ */
101
+ collected_at_issue_count: number;
102
+ collected_at_issue_amount: number;
103
+ /** Issued-in-selection bills NOT fully settled by the selection end. */
104
+ outstanding_count: number;
105
+ /** Owed at the selection end (per-bill remainder, clamped at 0). */
93
106
  outstanding_amount: number;
107
+ /** Today's state — see the module contract. */
108
+ outstanding_now_count: number;
109
+ outstanding_now_amount: number;
94
110
  }
95
111
  /** Weekday grouping (date/hour scopes only). */
96
112
  export interface IFormattedSalesOverviewWeekday {