@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
@@ -4,6 +4,7 @@ const constants_1 = require("../../constants");
4
4
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
5
5
  const tenant_sales_overview_close_day_helpers_1 = require("../../helpers/materialized-reports/tenant-sales-overview-close-day-helpers");
6
6
  const tenant_sales_overview_helpers_1 = require("../../helpers/materialized-reports/tenant-sales-overview-helpers");
7
+ const materialized_credit_bills_helpers_1 = require("../../helpers/materialized-reports/materialized-credit-bills-helpers");
7
8
  /** Narrows helper results that are `null` on invalid data (tests expect valid data). */
8
9
  const expectNonNull = (value) => {
9
10
  if (value == null)
@@ -18,6 +19,7 @@ const KEY = 'COMPLETED:POS_WALK-IN';
18
19
  const LOCAL_DATE = MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE;
19
20
  const LOCAL_HOUR = MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR;
20
21
  const LOCAL_WEEK = MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK;
22
+ const LOCAL_WEEK_OF_YEAR = MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR;
21
23
  const LOCAL_MONTH = MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH;
22
24
  const makeOrder = (args) => {
23
25
  const paymentType = args.paymentType ?? constants_1.PAYMENT_TYPE_ENUM.CASH;
@@ -61,28 +63,64 @@ const compileDay = (localDate, orders, computedAt) => expectNonNull((0, tenant_s
61
63
  tenantId: TENANT,
62
64
  computedAt,
63
65
  }));
64
- const closeDay = (localDate, orders, existing, computedAt, force = false) => expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
66
+ const EMPTY_WORLD = { docs: [], credit: [] };
67
+ const closeDay = (localDate, orders, world, computedAt, force = false) => expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
65
68
  tenantId: TENANT,
66
69
  compile: compileDay(localDate, orders, computedAt),
67
70
  reason: 'TEST_CLOSE',
68
- existing,
71
+ existing: world.docs,
72
+ existingCreditBills: world.credit,
69
73
  force,
70
74
  computedAt,
71
75
  }));
72
76
  const scopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
77
+ /** One stored/written credit document by scope (null when absent). */
78
+ const creditDoc = (world, scope, field) => world.credit.find((doc) => doc.scope_context === scope && doc.scope_field === field);
79
+ /** The bill's ISSUE entry across the credit documents (the same entry sits on every scope of its day). */
80
+ const issueEntryOf = (world, orderId) => {
81
+ for (const doc of world.credit) {
82
+ for (const section of Object.values(doc.credit_bills ?? {})) {
83
+ const entry = (section?.issued ?? []).find((candidate) => candidate.order_id === orderId);
84
+ if (entry != null)
85
+ return entry;
86
+ }
87
+ }
88
+ return undefined;
89
+ };
90
+ /** Distinct receipt deltas of one bill (each event sits on every scope document of its day). */
91
+ const receivedDeltasOf = (world, orderId) => {
92
+ const byEventDate = new Map();
93
+ for (const doc of world.credit) {
94
+ for (const section of Object.values(doc.credit_bills ?? {})) {
95
+ for (const entry of section?.received ?? []) {
96
+ if (entry.order_id === orderId)
97
+ byEventDate.set(entry.event_local_date, entry.received_delta ?? 0);
98
+ }
99
+ }
100
+ }
101
+ return Array.from(byEventDate.values()).sort((a, b) => a - b);
102
+ };
73
103
  /** Mongoose applies the schema default (`iteration: 1`) on the first insert. */
74
104
  const withDefaultIteration = (doc) => doc.iteration == null ? { ...doc, iteration: 1 } : doc;
75
- /** Simulates the job persisting a plan (structural writes, then patches, minus stale deletions). */
76
- const persistPlan = (stored, plan) => {
77
- const byKey = new Map(stored.map((doc) => [scopeKey(doc), doc]));
105
+ /** Simulates the job persisting a plan (report writes/patches, credit writes/patches, stale deletions). */
106
+ const persistPlan = (world, plan) => {
107
+ const byKey = new Map(world.docs.map((doc) => [scopeKey(doc), doc]));
78
108
  for (const write of plan.writes)
79
109
  byKey.set(scopeKey(write.report), withDefaultIteration(write.report));
80
110
  for (const patch of plan.receivedPatches)
81
111
  byKey.set(scopeKey(patch.report), patch.report);
82
112
  for (const stale of plan.staleHourDocuments)
83
113
  byKey.delete(scopeKey(stale));
84
- return Array.from(byKey.values());
114
+ const creditByKey = new Map(world.credit.map((doc) => [scopeKey(doc), doc]));
115
+ for (const write of plan.creditWrites)
116
+ creditByKey.set(scopeKey(write.report), write.report);
117
+ for (const patch of plan.creditSettlementPatches)
118
+ creditByKey.set(scopeKey(patch.report), patch.report);
119
+ for (const stale of plan.creditStaleHourDocuments)
120
+ creditByKey.delete(scopeKey(stale));
121
+ return { docs: Array.from(byKey.values()), credit: Array.from(creditByKey.values()) };
85
122
  };
123
+ const findCreditWrite = (plan, scope, field) => plan.creditWrites.find((write) => write.report.scope_context === scope && write.report.scope_field === field);
86
124
  const findWrite = (plan, scope, field) => plan.writes.find((write) => write.report.scope_context === scope && write.report.scope_field === field);
87
125
  const getKeyMetrics = (doc, key = KEY) => doc.sale_type_metrics?.[key];
88
126
  describe('tenant sales overview close-day plan', () => {
@@ -135,13 +173,13 @@ describe('tenant sales overview close-day plan', () => {
135
173
  isDeleted: true,
136
174
  });
137
175
  // Lifecycle: close D1 → close D2 (collecting the D1 bill) → re-close D2.
138
- const plan1 = closeDay(D1, [creditIssue], [], CT1);
139
- const stored1 = persistPlan([], plan1);
140
- const plan2 = closeDay(D2, [cashD2, collectedCredit], stored1, CT2);
141
- const stored2 = persistPlan(stored1, plan2);
142
- const plan3 = closeDay(D2, [cashD2, collectedCredit], stored2, CT3);
143
- const plan4 = closeDay(D2, [cashD2, collectedCredit, extraD2], stored2, CT4);
144
- const plan5 = closeDay(D1, [deletedIssue], stored1, CT5);
176
+ const plan1 = closeDay(D1, [creditIssue], EMPTY_WORLD, CT1);
177
+ const world1 = persistPlan(EMPTY_WORLD, plan1);
178
+ const plan2 = closeDay(D2, [cashD2, collectedCredit], world1, CT2);
179
+ const world2 = persistPlan(world1, plan2);
180
+ const plan3 = closeDay(D2, [cashD2, collectedCredit], world2, CT3);
181
+ const plan4 = closeDay(D2, [cashD2, collectedCredit, extraD2], world2, CT4);
182
+ const plan5 = closeDay(D1, [deletedIssue], world1, CT5);
145
183
  it('plans the first close: hour + date + period day-deltas, each with an iteration-1 history row', () => {
146
184
  expect(plan1.writes).toHaveLength(8); // 1 hour + 7 period scopes
147
185
  expect(plan1.staleHourDocuments).toEqual([]);
@@ -173,6 +211,29 @@ describe('tenant sales overview close-day plan', () => {
173
211
  expect(findWrite(plan1, LOCAL_HOUR, `${D1} 20`)).toBeDefined();
174
212
  expect(findWrite(plan1, LOCAL_WEEK, '2026-09-27')).toBeDefined();
175
213
  expect(findWrite(plan1, LOCAL_MONTH, '2026-09')).toBeDefined();
214
+ // The itemized ledger lives in month-capped scope documents — the issue
215
+ // entry lands on every credit document of the day.
216
+ const creditDateWrite = expectNonNull(findCreditWrite(plan1, LOCAL_DATE, D1));
217
+ const issuedEntry = creditDateWrite.report.credit_bills?.[KEY]?.issued[0];
218
+ expect(issuedEntry).toMatchObject({
219
+ order_id: 'order-credit-1',
220
+ payment_id: 'pay-1',
221
+ amount: 1200,
222
+ received_at_issue: 0,
223
+ received_amount: 0,
224
+ settled_at: null,
225
+ settled_local_date: null,
226
+ issued_local_hour: `${D1} 20`,
227
+ });
228
+ expect(creditDateWrite.report.credit_bills?.[KEY]?.received).toEqual([]);
229
+ expect(plan1.creditSettlementPatches).toEqual([]);
230
+ expect(plan1.creditWrites.map((write) => write.report.scope_context)).toEqual([
231
+ LOCAL_HOUR,
232
+ LOCAL_DATE,
233
+ LOCAL_WEEK,
234
+ LOCAL_WEEK_OF_YEAR,
235
+ LOCAL_MONTH,
236
+ ]);
176
237
  });
177
238
  it('plans the collection day: accumulates periods and patches the issue-day ledger', () => {
178
239
  expect(plan2.writes).toHaveLength(8); // date + 1 hour (sales 12 and the collection bucket at 12) + 6 periods
@@ -194,13 +255,21 @@ describe('tenant sales overview close-day plan', () => {
194
255
  expect(plan2.receivedPatches).toHaveLength(8);
195
256
  expect(plan2.receivedPatches.some((write) => write.report.scope_context === LOCAL_HOUR)).toBe(true);
196
257
  const patchedDate = expectNonNull(plan2.receivedPatches.find((write) => write.report.scope_context === LOCAL_DATE && write.report.scope_field === D1));
197
- const issued = getKeyMetrics(patchedDate.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued;
198
- expect(issued?.settled_count).toBe(1);
199
- expect(issued?.settled_amount).toBe(1200);
200
- expect(issued?.bills[0]).toMatchObject({
258
+ const patchedIssued = getKeyMetrics(patchedDate.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued;
259
+ expect(patchedIssued?.settled_count).toBe(1);
260
+ expect(patchedIssued?.settled_amount).toBe(1200);
261
+ // The credit documents carry the resolved receipt + settlement anchors
262
+ // (the issue scopes were patched — persisted state lives in world2).
263
+ const receiptEntry = creditDoc(world2, LOCAL_DATE, D2)?.credit_bills?.[KEY]?.received[0];
264
+ expect(receiptEntry).toMatchObject({ received_delta: 1200, received_amount: 1200, event_local_date: D2 });
265
+ const settledIssue = expectNonNull(issueEntryOf(world2, 'order-credit-1'));
266
+ expect(settledIssue).toMatchObject({
201
267
  received_amount: 1200,
202
268
  credit_note: 'CN-2026-09-30',
269
+ settled_local_date: D2,
203
270
  });
271
+ expect(settledIssue.received_at_issue).toBe(0);
272
+ expect(plan2.creditSettlementPatches).toHaveLength(5); // D1: date + hour + week + wow + month
204
273
  expect(patchedDate.report.iteration).toBe(2); // was 1 — the patch bumped it
205
274
  expect(patchedDate.iteration.iteration).toBe(2); // history row for the patched version
206
275
  expect(patchedDate.iteration.reason).toBe('TEST_CLOSE');
@@ -212,6 +281,9 @@ describe('tenant sales overview close-day plan', () => {
212
281
  expect(plan3.receivedPatches).toEqual([]);
213
282
  expect(plan3.staleHourDocuments).toEqual([]);
214
283
  expect(plan3.skippedDocuments).toHaveLength(8); // date + 1 hour + 6 periods
284
+ expect(plan3.creditWrites).toEqual([]); // no credit activity changed — all documents skipped
285
+ expect(plan3.creditSkippedDocuments).toHaveLength(5);
286
+ expect(plan3.creditSettlementPatches).toEqual([]);
215
287
  });
216
288
  it('re-closes a changed day: subtracts the stored delta, adds the recalculated one', () => {
217
289
  expect(plan4.writes).toHaveLength(9); // date + 2 hours (12 merged collection, 18 extra) + 6 periods
@@ -234,15 +306,15 @@ describe('tenant sales overview close-day plan', () => {
234
306
  expect(plan5.receivedPatches).toEqual([]);
235
307
  });
236
308
  it('rewrites everything on force even when the watermark says up to date', () => {
237
- const forced = closeDay(D2, [cashD2, collectedCredit], stored2, CT3, true);
309
+ const forced = closeDay(D2, [cashD2, collectedCredit], world2, CT3, true);
238
310
  expect(forced.writes).toHaveLength(8);
239
311
  expect(forced.skippedDocuments).toHaveLength(0);
240
312
  });
241
313
  it('treats order-less days as a stable date marker (epoch watermark, no re-close churn)', () => {
242
- const emptyPlan = closeDay(D2, [], [], CT1);
314
+ const emptyPlan = closeDay(D2, [], EMPTY_WORLD, CT1);
243
315
  expect(emptyPlan.writes.map((write) => write.report.scope_context)).toEqual([LOCAL_DATE]);
244
316
  expect(emptyPlan.writes[0].report.source_watermark).toEqual(new Date(0));
245
- const emptyReClose = closeDay(D2, [], persistPlan([], emptyPlan), CT2);
317
+ const emptyReClose = closeDay(D2, [], persistPlan(EMPTY_WORLD, emptyPlan), CT2);
246
318
  expect(emptyReClose.writes).toHaveLength(0);
247
319
  expect(emptyReClose.skippedDocuments).toHaveLength(1);
248
320
  });
@@ -285,10 +357,10 @@ describe('tenant sales overview close-day plan', () => {
285
357
  it('normalizes hydrated (mongoose-cast) stored docs when planning patches', () => {
286
358
  // Real hydration shape: `Model.find()` docs carry the `sale_type_metrics` Map
287
359
  // with mongoose subdocument values (NOT plain objects).
288
- const hydratedStored = stored1.map((doc) => doc.scope_context === LOCAL_DATE && doc.scope_field === D1
360
+ const hydratedStored = world1.docs.map((doc) => doc.scope_context === LOCAL_DATE && doc.scope_field === D1
289
361
  ? (0, tenant_sales_overview_helpers_1.convertMaterializedTenantSalesOverviewReportJsonToBson)(doc).toObject()
290
362
  : doc);
291
- const plan = closeDay(D2, [cashD2, collectedCredit], hydratedStored, CT2);
363
+ const plan = closeDay(D2, [cashD2, collectedCredit], { docs: hydratedStored, credit: world1.credit }, CT2);
292
364
  expect(plan.receivedPatches).toHaveLength(8); // the hydrated D1 date doc is still detected + patched
293
365
  expect(plan.receivedPatches.some((write) => write.report.scope_field === D1)).toBe(true);
294
366
  expect(JSON.stringify(plan.receivedPatches)).not.toContain('$__'); // no mongoose internals leak through
@@ -333,3 +405,236 @@ describe('getMaterializedTenantSalesOverviewScopeRefsForDay', () => {
333
405
  expect((0, tenant_sales_overview_close_day_helpers_1.getMaterializedTenantSalesOverviewScopeRefsForDay)('2026-9-30')).toBeNull();
334
406
  });
335
407
  });
408
+ describe('credit-bill receipt events (C-lite regressions)', () => {
409
+ const I1 = '2026-10-01'; // issue day
410
+ const C1 = '2026-10-02'; // first (partial) collection day
411
+ const C2 = '2026-10-03'; // final collection day
412
+ const ct = (day) => new Date(`${day}T23:00:00.000Z`);
413
+ const issueOrder = makeOrder({
414
+ orderId: 'bill-1',
415
+ localDate: I1,
416
+ localHour: 20,
417
+ amount: 1000,
418
+ paymentType: constants_1.PAYMENT_TYPE_ENUM.PAY_LATER,
419
+ paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING,
420
+ updatedAt: `${I1}T20:00:00.000Z`,
421
+ });
422
+ // 400 arrived on C1 …
423
+ const partialOrder = makeOrder({
424
+ orderId: 'bill-1',
425
+ localDate: I1,
426
+ localHour: 20,
427
+ amount: 1000,
428
+ amountPaid: 400,
429
+ paymentType: constants_1.PAYMENT_TYPE_ENUM.PAY_LATER,
430
+ paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING,
431
+ updatedAt: `${C1}T10:00:00.000Z`,
432
+ note: 'CN-PARTIAL',
433
+ });
434
+ // … the remaining 600 on C2 (same order fetched again, cumulative 1000).
435
+ const finalOrder = makeOrder({
436
+ orderId: 'bill-1',
437
+ localDate: I1,
438
+ localHour: 20,
439
+ amount: 1000,
440
+ amountPaid: 1000,
441
+ paymentType: constants_1.PAYMENT_TYPE_ENUM.PAY_LATER,
442
+ paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
443
+ updatedAt: `${C2}T10:00:00.000Z`,
444
+ note: 'CN-FINAL',
445
+ });
446
+ const planIssue = closeDay(I1, [issueOrder], EMPTY_WORLD, ct(I1));
447
+ const worldIssue = persistPlan(EMPTY_WORLD, planIssue);
448
+ const planC1 = closeDay(C1, [partialOrder], worldIssue, ct(C1));
449
+ const worldC1 = persistPlan(worldIssue, planC1);
450
+ const planC2 = closeDay(C2, [finalOrder], worldC1, ct(C2));
451
+ const worldC2 = persistPlan(worldC1, planC2);
452
+ // A forced re-close of C1 AFTER C2 — the F2 corruption scenario.
453
+ const planC1Re = closeDay(C1, [partialOrder], worldC2, new Date(`${C1}T23:30:00.000Z`), true);
454
+ const worldC1Re = persistPlan(worldC2, planC1Re);
455
+ const storedDoc = (docs, scope, field) => docs.find((doc) => doc.scope_context === scope && doc.scope_field === field);
456
+ /** Deltas of a bill's receipt events (sorted ascending). */
457
+ const deltasOf = (world, orderId) => receivedDeltasOf(world, orderId);
458
+ /**
459
+ * R5-3 drift guard: the report documents' credit COUNTERS must equal the
460
+ * read spec's totals over the credit DOCUMENTS for the same selection
461
+ * (issued + settled + received; `outstanding*` / `collected_at_issue_*` are
462
+ * aggregation-only extras, not stored counters). Settled parity holds when
463
+ * the selection end is at/beyond every settlement in the world (here: the
464
+ * last collection day) — the report counter is ever-settled (NOW) and the
465
+ * read spec is as-of-end (audit R5-4).
466
+ */
467
+ const expectParity = (world, dates, endLabel) => {
468
+ const labels = new Set(dates);
469
+ const totals = (0, materialized_credit_bills_helpers_1.computeMaterializedCreditBillTotalsFromReports)(world.credit, {
470
+ granularity: 'day',
471
+ labels,
472
+ end_label: endLabel,
473
+ });
474
+ let issuedCount = 0;
475
+ let issuedAmount = 0;
476
+ let settledCount = 0;
477
+ let settledAmount = 0;
478
+ let receivedCount = 0;
479
+ let receivedAmount = 0;
480
+ for (const doc of world.docs) {
481
+ if (doc.scope_context !== LOCAL_DATE || !labels.has(doc.scope_field))
482
+ continue;
483
+ const credit = doc.sale_type_metrics?.[KEY]?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
484
+ if (credit == null)
485
+ continue;
486
+ issuedCount += credit.issued.count;
487
+ issuedAmount += credit.issued.amount;
488
+ settledCount += credit.issued.settled_count;
489
+ settledAmount += credit.issued.settled_amount;
490
+ receivedCount += credit.received.count;
491
+ receivedAmount += credit.received.amount;
492
+ }
493
+ expect(totals.issued.count).toBe(issuedCount);
494
+ expect(totals.issued.amount).toBe(issuedAmount);
495
+ expect(totals.issued.settled_count).toBe(settledCount);
496
+ expect(totals.issued.settled_amount).toBe(settledAmount);
497
+ expect(totals.received.count).toBe(receivedCount);
498
+ expect(totals.received.amount).toBe(receivedAmount);
499
+ // Non-vacuous guard: this scenario carries exactly ONE bill, settled by
500
+ // the last collection day — a green run must have real numbers behind it.
501
+ expect(issuedCount).toBe(1);
502
+ expect(settledCount).toBe(1);
503
+ expect(receivedCount).toBe(2); // two installments (400 + 600)
504
+ };
505
+ it("resolves each receipt event's delta against the stored pre-event state", () => {
506
+ const c1Write = expectNonNull(findWrite(planC1, LOCAL_DATE, C1));
507
+ const c1Metrics = expectNonNull(getKeyMetrics(c1Write.report));
508
+ expect(c1Metrics[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.amount).toBe(400); // counters mirror the resolved ledger
509
+ expect(c1Metrics[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.count).toBe(1);
510
+ const issueAfterC1 = expectNonNull(issueEntryOf(worldC1, 'bill-1'));
511
+ expect(issueAfterC1.settled_local_date).toBeNull(); // 400 < 1000 — not settled
512
+ expect(receivedDeltasOf(worldC1, 'bill-1')).toEqual([400]);
513
+ const c2Write = expectNonNull(findWrite(planC2, LOCAL_DATE, C2));
514
+ const c2Metrics = expectNonNull(getKeyMetrics(c2Write.report));
515
+ // prev = 400 (the stored day's receipt) → delta = 1000 − 400.
516
+ expect(c2Metrics[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.amount).toBe(600);
517
+ const issueAfterC2 = expectNonNull(issueEntryOf(worldC2, 'bill-1'));
518
+ expect(issueAfterC2.received_amount).toBe(1000); // patched on settlement
519
+ expect(issueAfterC2.settled_local_date).toBe(C2);
520
+ expect(deltasOf(worldC2, 'bill-1')).toEqual([400, 600]);
521
+ // The issue-day documents got the SETTLED counters (counters only — the
522
+ // itemized receipt lives in the ledger row).
523
+ const patchedIssue = planC2.receivedPatches.find((write) => write.report.scope_context === LOCAL_DATE && write.report.scope_field === I1);
524
+ const issued = getKeyMetrics(expectNonNull(patchedIssue).report)?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued;
525
+ expect(issued?.settled_count).toBe(1);
526
+ expect(issued?.settled_amount).toBe(1000);
527
+ });
528
+ it('keeps BOTH events in the ledger and re-closes C1 without losing C2 (F2)', () => {
529
+ expect(deltasOf(worldC2, 'bill-1')).toEqual([400, 600]);
530
+ const monthAfterC2 = expectNonNull(storedDoc(worldC2.docs, LOCAL_MONTH, '2026-10'));
531
+ expect(getKeyMetrics(monthAfterC2)?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.amount).toBe(1000);
532
+ // The re-close resolves the SAME delta for C1 (the stored same-day event
533
+ // keeps its delta) — C2's event SURVIVES and the money stays.
534
+ expect(deltasOf(worldC1Re, 'bill-1')).toEqual([400, 600]);
535
+ const monthAfterRe = expectNonNull(storedDoc(worldC1Re.docs, LOCAL_MONTH, '2026-10'));
536
+ expect(getKeyMetrics(monthAfterRe)?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.amount).toBe(1000);
537
+ // Idempotent: the re-close resolves the SAME receipt (no settlement is
538
+ // re-emitted) and the document counter nets to zero (compiled C1 counters
539
+ // subtracted against the stored day state).
540
+ expect(planC1Re.creditSettlementPatches).toEqual([]);
541
+ const c1ReWrite = expectNonNull(findWrite(planC1Re, LOCAL_DATE, C1));
542
+ expect(getKeyMetrics(c1ReWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.amount).toBe(400);
543
+ });
544
+ it('carries received_at_issue / settled_local_date forward on an issue-day re-close', () => {
545
+ // A CURRENT-state fetch of the issue day — the order is fully collected now.
546
+ const reClose = closeDay(I1, [finalOrder], worldC2, new Date(`${C2}T23:30:00.000Z`), true);
547
+ const write = expectNonNull(findWrite(reClose, LOCAL_DATE, I1));
548
+ const issued = getKeyMetrics(write.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued;
549
+ expect(issued?.count).toBe(1);
550
+ expect(issued?.settled_count).toBe(1); // carried from the ledger row — NOT regressed by the compile view
551
+ expect(issued?.settled_amount).toBe(1000);
552
+ // The stored entry keeps its anchors — a re-close never re-anchors them.
553
+ const entry = expectNonNull(issueEntryOf(worldC2, 'bill-1'));
554
+ expect(entry.received_at_issue).toBe(0); // NOT re-anchored to the paid amount
555
+ expect(entry.settled_local_date).toBe(C2); // carried from the collection close
556
+ });
557
+ it('R5-3 harness: report counters == read spec over the credit docs (full lifecycle)', () => {
558
+ expectParity(worldC2, [I1, C1, C2], C2);
559
+ });
560
+ it('R5-3 harness: parity survives the F2 re-close', () => {
561
+ expectParity(worldC1Re, [I1, C1, C2], C2);
562
+ });
563
+ });
564
+ describe('N2 backfill from CURRENT order state (settled-after-issue rule)', () => {
565
+ const I1 = '2026-10-01'; // issue day
566
+ const C1 = '2026-10-03'; // collection day (later than the business day)
567
+ const ct = (day) => new Date(`${day}T23:00:00.000Z`);
568
+ const compileWithOffset = (localDate, orders, computedAt) => expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(localDate, orders, {
569
+ brandId: BRAND,
570
+ tenantId: TENANT,
571
+ gmtOffset: 5,
572
+ computedAt,
573
+ }));
574
+ // The order AS CURRENT STATE shows it: fully collected, with
575
+ // `order_settled_at` stamped on a LATER day than its business day — the
576
+ // from-`orders` backfill input that must NOT read as paid-at-issue.
577
+ const currentStateOrder = {
578
+ ...makeOrder({
579
+ orderId: 'n2-bill',
580
+ localDate: I1,
581
+ localHour: 20,
582
+ amount: 1000,
583
+ amountPaid: 1000,
584
+ paymentType: constants_1.PAYMENT_TYPE_ENUM.PAY_LATER,
585
+ paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
586
+ updatedAt: `${C1}T10:00:00.000Z`,
587
+ }),
588
+ order_settled_at: new Date(`${C1}T10:00:00.000Z`),
589
+ };
590
+ it('backfilled issue day reads UNPAID-at-issue; the collection day carries the full delta', () => {
591
+ const issueCompile = compileWithOffset(I1, [currentStateOrder], ct(I1));
592
+ const issueDateDoc = issueCompile.materializedReports.find((doc) => doc.scope_context === LOCAL_DATE && doc.scope_field === I1);
593
+ const issueCounters = getKeyMetrics(expectNonNull(issueDateDoc))?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
594
+ expect(issueCounters?.issued.count).toBe(1);
595
+ expect(issueCounters?.issued.settled_count).toBe(0); // N2: settled-later reads unpaid at issue
596
+ const issuePlan = expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
597
+ tenantId: TENANT,
598
+ compile: issueCompile,
599
+ reason: 'TEST_CLOSE',
600
+ existing: [],
601
+ existingCreditBills: [],
602
+ computedAt: ct(I1),
603
+ }));
604
+ const issueWrite = expectNonNull(findCreditWrite(issuePlan, LOCAL_DATE, I1));
605
+ const issueRow = issueWrite.report.credit_bills?.[KEY]?.issued[0];
606
+ expect(issueRow).toMatchObject({
607
+ order_id: 'n2-bill',
608
+ received_at_issue: 0,
609
+ received_amount: 0,
610
+ settled_at: null,
611
+ settled_local_date: null,
612
+ });
613
+ const worldIssue = persistPlan(EMPTY_WORLD, issuePlan);
614
+ // Collection-day close: the order's business day is earlier → received
615
+ // ledger; the delta resolves 1000 − 0 (before the rule the bill read as
616
+ // settled-at-issue and the delta collapsed to 0 — audit N2).
617
+ const collectionCompile = compileWithOffset(C1, [currentStateOrder], ct(C1));
618
+ const collectionPlan = expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
619
+ tenantId: TENANT,
620
+ compile: collectionCompile,
621
+ reason: 'TEST_CLOSE',
622
+ existing: worldIssue.docs,
623
+ existingCreditBills: worldIssue.credit,
624
+ computedAt: ct(C1),
625
+ }));
626
+ const c1Write = expectNonNull(findWrite(collectionPlan, LOCAL_DATE, C1));
627
+ expect(getKeyMetrics(c1Write.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.amount).toBe(1000);
628
+ const receiptEntry = findCreditWrite(collectionPlan, LOCAL_DATE, C1)?.report.credit_bills?.[KEY]?.received[0];
629
+ expect(receiptEntry).toMatchObject({ received_delta: 1000, received_amount: 1000, event_local_date: C1 });
630
+ // …and the issue-scope settlement patch lands the anchors exactly once.
631
+ const issueSettlement = collectionPlan.creditSettlementPatches.find((write) => write.report.scope_context === LOCAL_DATE && write.report.scope_field === I1);
632
+ const settledEntry = expectNonNull(issueSettlement).report.credit_bills?.[KEY]?.issued[0];
633
+ expect(settledEntry).toMatchObject({ received_at_issue: 0, received_amount: 1000, settled_local_date: C1 });
634
+ // …and the issue-day document patch lands the SETTLED counters.
635
+ const patched = collectionPlan.receivedPatches.find((write) => write.report.scope_context === LOCAL_DATE && write.report.scope_field === I1);
636
+ const patchedIssued = getKeyMetrics(expectNonNull(patched).report)?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued;
637
+ expect(patchedIssued?.settled_count).toBe(1);
638
+ expect(patchedIssued?.settled_amount).toBe(1000);
639
+ });
640
+ });
@@ -34,7 +34,16 @@ const keyMetrics = (over = {}) => ({
34
34
  TOTAL_SALES: { orders: orderMetric(), payments: [] },
35
35
  AMOUNT_COLLECTED: { orders: orderMetric() },
36
36
  CREDIT_BILLS: {
37
- issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
37
+ issued: {
38
+ count: 0,
39
+ amount: 0,
40
+ settled_count: 0,
41
+ settled_amount: 0,
42
+ outstanding_count: 0,
43
+ outstanding_amount: 0,
44
+ outstanding_now_count: 0,
45
+ outstanding_now_amount: 0,
46
+ },
38
47
  received: { count: 0, amount: 0 },
39
48
  },
40
49
  ...over,
@@ -42,6 +51,8 @@ const keyMetrics = (over = {}) => ({
42
51
  const makeRecord = (over = {}) => ({
43
52
  tenant_id: 'tenant-a',
44
53
  brand_id: 'brand-1',
54
+ max_iteration: 2,
55
+ max_updated_at: new Date('2026-09-03T23:00:00.000Z'),
45
56
  matched_documents: 3,
46
57
  first_scope_field: '2026-09-01',
47
58
  last_scope_field: '2026-09-03',
@@ -54,7 +65,16 @@ const makeRecord = (over = {}) => ({
54
65
  },
55
66
  AMOUNT_COLLECTED: { orders: orderMetric({ count: 4, gross_amount: 200000 }) },
56
67
  CREDIT_BILLS: {
57
- issued: { count: 1, amount: 100000, settled_count: 1, settled_amount: 100000 },
68
+ issued: {
69
+ count: 1,
70
+ amount: 100000,
71
+ settled_count: 1,
72
+ settled_amount: 100000,
73
+ outstanding_count: 0,
74
+ outstanding_amount: 0,
75
+ outstanding_now_count: 0,
76
+ outstanding_now_amount: 0,
77
+ },
58
78
  received: { count: 1, amount: 5000 },
59
79
  },
60
80
  }),
@@ -103,7 +123,12 @@ describe('getFormattedTenantSalesOverviewAggregatedReporting', () => {
103
123
  expect(page?.credit_bills).toEqual({
104
124
  issued: { count: 1, amount: 1000, settled_count: 1, settled_amount: 1000 },
105
125
  received: { count: 1, amount: 50 },
126
+ outstanding_count: 0,
106
127
  outstanding_amount: 0,
128
+ outstanding_now_count: 0,
129
+ outstanding_now_amount: 0,
130
+ collected_at_issue_count: 0,
131
+ collected_at_issue_amount: 0,
107
132
  });
108
133
  // slice-derived sections are never available on aggregated records
109
134
  expect(page?.weekday).toBeNull();
@@ -28,11 +28,11 @@ const makePayment = (over = {}) => ({
28
28
  card_charges: 0,
29
29
  ...over,
30
30
  });
31
- // Ledger counters are recomputed from the itemized bills during the merge —
32
- // fixtures only need to carry the bills.
33
- const makeCreditBills = (issuedBills = [], receivedBills = []) => ({
34
- issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0, bills: issuedBills },
35
- received: { count: 0, amount: 0, bills: receivedBills },
31
+ // Credit-bill counters are stored directly on the documents (the itemized
32
+ // ledger lives in `materialized_tenant_credit_bills`) — fixtures set them explicitly.
33
+ const makeCreditBills = (issued = {}, received = {}) => ({
34
+ issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0, ...issued },
35
+ received: { count: 0, amount: 0, ...received },
36
36
  });
37
37
  const makeKeyMetrics = (orders, over = {}) => ({
38
38
  [constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: { orders, payments: [] },
@@ -57,22 +57,6 @@ const makeDoc = (over = {}) => ({
57
57
  updatedAt: new Date('2026-10-01T10:00:00.000Z'),
58
58
  ...over,
59
59
  });
60
- const issuedBill = {
61
- order_id: 'o1',
62
- payment_id: 'p1',
63
- amount: 11000,
64
- received_amount: 0,
65
- issued_at: new Date('2026-10-01T18:00:00.000Z'),
66
- settled_at: null,
67
- };
68
- // Same receipt recorded in two documents — the merge must count it ONCE.
69
- const receivedBill = {
70
- order_id: 'o9',
71
- payment_id: 'p9',
72
- amount: 11000,
73
- received_amount: 11000,
74
- issued_local_date: '2026-09-30',
75
- };
76
60
  const docA = makeDoc({
77
61
  _id: 'docA',
78
62
  tenant_id: 't1',
@@ -99,7 +83,7 @@ const docA = makeDoc({
99
83
  orders: makeOrderMetric({ count: 1, gross_amount: 9000 }),
100
84
  payments: [],
101
85
  },
102
- [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: makeCreditBills([issuedBill], [receivedBill]),
86
+ [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: makeCreditBills({ count: 1, amount: 11000 }, { count: 1, amount: 11000 }),
103
87
  },
104
88
  'CANCELLED:POS_WALK-IN': makeKeyMetrics(makeOrderMetric({ count: 1, gross_amount: 5000 })),
105
89
  },
@@ -121,9 +105,9 @@ const docB = makeDoc({
121
105
  },
122
106
  [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: makeCreditBills(),
123
107
  },
124
- // Same receipt under the SAME key as in docA — the overlapping-compile case
125
- // (e.g. a day document and a period document both carrying the key); the
126
- // merge de-duplicates it by (order_id, payment_id).
108
+ // The same key on another tenant's document — credit counters SUM (reads
109
+ // never mix overlapping scopes; the aggregation selects non-overlapping
110
+ // scope documents, so per-document counters never double-count a bill).
127
111
  'COMPLETED:POS_WALK-IN': {
128
112
  [constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: {
129
113
  orders: makeOrderMetric({ count: 0, gross_amount: 0 }),
@@ -133,7 +117,7 @@ const docB = makeDoc({
133
117
  orders: makeOrderMetric({ count: 0, gross_amount: 0 }),
134
118
  payments: [],
135
119
  },
136
- [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: makeCreditBills([], [receivedBill]),
120
+ [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: makeCreditBills(),
137
121
  },
138
122
  },
139
123
  });
@@ -185,7 +169,8 @@ describe('getFormattedTenantSalesOverviewReporting', () => {
185
169
  expect(settlement.derived).toBe(true);
186
170
  expect(settlement.count).toBe(1); // de-duplicated across documents
187
171
  expect(settlement.gross_amount).toBe(110);
188
- // Credit-bill ledger (counters recomputed from the de-duplicated bills).
172
+ // Credit-bill counters (summed per key across the selected documents;
173
+ // the derived settlement line counts the `received` bucket once).
189
174
  expect(data.credit_bills.issued).toEqual({
190
175
  count: 1,
191
176
  amount: 110,