@managesome/eposmatic-toolkit 0.4.7 → 0.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +33 -0
  2. package/esm/constants/enums/communications.js +1 -0
  3. package/esm/helpers/materialized-reports/index.js +1 -0
  4. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +982 -0
  5. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +276 -33
  6. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +327 -41
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +118 -235
  9. package/esm/schemas/models/index.js +1 -0
  10. package/esm/schemas/models/materialized_credit_bills.js +265 -0
  11. package/esm/schemas/models/materialized_tenant_reports_iterations.js +13 -0
  12. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +39 -97
  13. package/esm/schemas/types/index.js +1 -0
  14. package/esm/schemas/types/materialized_credit_bills.js +1 -0
  15. package/lib/constants/MATERIALIZED_REPORTS.d.ts +28 -2
  16. package/lib/constants/MATERIALIZED_REPORTS.js +34 -1
  17. package/lib/constants/enums/communications.d.ts +1 -0
  18. package/lib/constants/enums/communications.js +2 -1
  19. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  20. package/lib/helpers/materialized-reports/index.js +1 -0
  21. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +307 -0
  22. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +1003 -0
  23. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +36 -2
  24. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +278 -34
  25. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +66 -8
  26. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +326 -40
  27. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +18 -2
  28. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  29. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +46 -37
  30. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +119 -238
  31. package/lib/helpers/types/materialized-reports-apis.d.ts +32 -5
  32. package/lib/schemas/models/index.d.ts +1 -0
  33. package/lib/schemas/models/index.js +1 -0
  34. package/lib/schemas/models/materialized_credit_bills.d.ts +337 -0
  35. package/lib/schemas/models/materialized_credit_bills.js +268 -0
  36. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +20 -6
  37. package/lib/schemas/models/materialized_tenant_reports_iterations.js +14 -1
  38. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +37 -165
  39. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +40 -98
  40. package/lib/schemas/types/index.d.ts +1 -0
  41. package/lib/schemas/types/index.js +1 -0
  42. package/lib/schemas/types/materialized_credit_bills.d.ts +139 -0
  43. package/lib/schemas/types/materialized_credit_bills.js +2 -0
  44. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +32 -77
  45. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.d.ts +1 -0
  46. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +715 -0
  47. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +96 -0
  48. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +9 -0
  49. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +23 -24
  50. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +327 -22
  51. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +27 -2
  52. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +12 -27
  53. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +79 -146
  54. package/package.json +1 -1
@@ -164,3 +164,99 @@ describe('isValidBusinessHourWindow', () => {
164
164
  expect((0, materialized_reports_selection_helpers_1.isValidBusinessHourWindow)(-1, 5)).toBe(false);
165
165
  });
166
166
  });
167
+ describe('selection input hardening (F3 / F10 / F11)', () => {
168
+ test('malformed date keys cannot be served — no string-walk loops', () => {
169
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ rangeStart: 'A', rangeEnd: 'Z' }))).toBeNull();
170
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK_OF_YEAR, rangeStart: 'A', rangeEnd: 'Z' }))).toBeNull();
171
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ rangeStart: '2026-02-31' }))).toBeNull();
172
+ // the shared day helper is bounded too — the same input can never hang
173
+ expect((0, materialized_reports_selection_helpers_1.getDayKeysFromCalendarSelection)(selection({ rangeStart: 'A', rangeEnd: 'Z' }))).toEqual([]);
174
+ });
175
+ test('oversized spans are rejected before any expansion', () => {
176
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ rangeStart: '2026-01-01', rangeEnd: '9999-12-31' }))).toBeNull();
177
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ rangeStart: '1000-01-01', rangeEnd: '9998-12-31' }))).toBeNull();
178
+ // ~10 years of days is still servable
179
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ rangeStart: '2026-01-01', rangeEnd: '2035-12-31' }))).not.toBeNull();
180
+ });
181
+ test('period keys are validated per view (bad keys → null, never a 200 no-data read)', () => {
182
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS, selectedPeriods: ['2026-13'] }))).toBeNull();
183
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS, selectedPeriods: ['2026'] }))).toBeNull();
184
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS, selectedPeriods: ['2026-S3'] }))).toBeNull();
185
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR, selectedPeriods: ['2027-W53'] }))).toBeNull();
186
+ // …while semantically valid picks still decode.
187
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR, selectedPeriods: ['2026-W53'] }))).toEqual([{ scope_context: 'localWeekOfYear', scope_field: ['2026-W53'] }]);
188
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS, selectedPeriods: ['2026-Q4'] }))).toEqual([{ scope_context: 'localQuarter', scope_field: ['2026-Q4'] }]);
189
+ });
190
+ test('minute-level time keys are rejected instead of silently truncating', () => {
191
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ rangeStart: '2026-09-10', timeStart: '18:45', timeEnd: '20:00' }))).toBeNull();
192
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ rangeStart: '2026-09-10', timeStart: '18:00', timeEnd: '20:00' }))).not.toBeNull();
193
+ });
194
+ test('malformed weekday entries are rejected', () => {
195
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({ rangeStart: '2026-09-10', weekdays: ['MONDAY'] }))).toBeNull();
196
+ });
197
+ test('weekday + window on range views compiles RECURRING — never a dead end (F9)', () => {
198
+ const groups = (0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({
199
+ rangeStart: '2026-09-01',
200
+ rangeEnd: '2026-09-30',
201
+ weekdays: [ENUMS_1.DAY_INDEX_ENUM.MON],
202
+ timeStart: '18:00',
203
+ timeEnd: '20:00',
204
+ }));
205
+ expect(groups).not.toBeNull();
206
+ const labels = (groups ?? []).flatMap((group) => group.scope_field);
207
+ // Sep 2026 Mondays (7/14/21/28) × hours 18–19 — one label per bucket.
208
+ expect(labels).toHaveLength(8);
209
+ expect(labels).toContain('2026-09-07 18');
210
+ expect(labels).toContain('2026-09-28 19');
211
+ });
212
+ });
213
+ describe('validateMaterializedReportSelectionInput', () => {
214
+ test('distinguishes tooLarge from invalid and approves servable selections', () => {
215
+ expect((0, materialized_reports_selection_helpers_1.validateMaterializedReportSelectionInput)(selection({ rangeStart: '2026-01-01', rangeEnd: '9999-12-31' }))).toEqual({ ok: false, reason: 'tooLarge' });
216
+ expect((0, materialized_reports_selection_helpers_1.validateMaterializedReportSelectionInput)(selection({ rangeStart: 'A' }))).toEqual({
217
+ ok: false,
218
+ reason: 'invalid',
219
+ });
220
+ expect((0, materialized_reports_selection_helpers_1.validateMaterializedReportSelectionInput)(selection({ rangeStart: '2026-09-10' }))).toEqual({ ok: true });
221
+ });
222
+ });
223
+ describe('N5 — canonical decode + reason parity', () => {
224
+ test('duplicate period picks decode once (first-occurrence order)', () => {
225
+ const groups = (0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({
226
+ view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS,
227
+ selectedPeriods: ['2026-09', '2026-09', '2026-10'],
228
+ }));
229
+ expect(groups).toEqual([{ scope_context: 'localMonth', scope_field: ['2026-09', '2026-10'] }]);
230
+ });
231
+ test('weekday-filtered multi-year selections count EFFECTIVE days, not raw ones', () => {
232
+ const bigWeekdaySelection = selection({
233
+ view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS,
234
+ selectedPeriods: Array.from({ length: 11 }, (_, index) => `${2015 + index}`),
235
+ weekdays: [ENUMS_1.DAY_INDEX_ENUM.MON],
236
+ });
237
+ // 11 years ≈ 4 018 raw days but only ~573 effective Mondays — servable.
238
+ expect((0, materialized_reports_selection_helpers_1.validateMaterializedReportSelectionInput)(bigWeekdaySelection)).toEqual({ ok: true });
239
+ const groups = (0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(bigWeekdaySelection);
240
+ expect(groups).not.toBeNull();
241
+ const labels = (groups ?? []).flatMap((group) => group.scope_field);
242
+ expect(labels.length).toBeGreaterThan(560);
243
+ expect(labels.length).toBeLessThan(590);
244
+ });
245
+ test('oversize DIFFERENT_* expansions classify as tooLarge (not "invalid")', () => {
246
+ const tooManyYears = selection({
247
+ view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS,
248
+ selectedPeriods: Array.from({ length: 200 }, (_, index) => `${1900 + index}`),
249
+ });
250
+ // 200 raw years ≈ 73 000 days > the 3 660-day bound — tooLarge, and the
251
+ // decoder agrees (null), so ops never mislabels it as "Invalid request".
252
+ expect((0, materialized_reports_selection_helpers_1.validateMaterializedReportSelectionInput)(tooManyYears)).toEqual({ ok: false, reason: 'tooLarge' });
253
+ expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(tooManyYears)).toBeNull();
254
+ // With the weekday refinement the EFFECTIVE set is still beyond the bound
255
+ // (200 × ~52 ≈ 10 400 Mondays).
256
+ expect((0, materialized_reports_selection_helpers_1.validateMaterializedReportSelectionInput)(selection({
257
+ view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS,
258
+ selectedPeriods: tooManyYears.selectedPeriods,
259
+ weekdays: [ENUMS_1.DAY_INDEX_ENUM.MON],
260
+ }))).toEqual({ ok: false, reason: 'tooLarge' });
261
+ });
262
+ });
@@ -70,4 +70,13 @@ describe('materialized_tenant_reports_iterations schema', () => {
70
70
  });
71
71
  expect(MATERIALIZED_REPORTS_1.ALL_MATERIALIZED_REPORT_TYPES).toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW);
72
72
  });
73
+ it('exports UNIQUE index options for the materializer to CREATE (F12)', () => {
74
+ expect(materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_INDEX_OPTIONS).toEqual([
75
+ {
76
+ key: { report_id: 1, iteration: -1 },
77
+ name: 'report_id__iteration',
78
+ unique: true,
79
+ },
80
+ ]);
81
+ });
73
82
  });
@@ -34,22 +34,6 @@ const saleTypeMetric = () => ({
34
34
  orders: orderMetric(),
35
35
  payments: [paymentMetric('CASH')],
36
36
  });
37
- const creditBill = () => ({
38
- order_id: new mongoose_1.default.Types.ObjectId().toString(),
39
- payment_id: new mongoose_1.default.Types.ObjectId().toString(),
40
- amount: 1200,
41
- received_amount: 600, // partially collected
42
- issued_at: new Date('2026-09-29T22:10:00.000Z'),
43
- settled_at: null,
44
- });
45
- const receivedCreditBill = () => ({
46
- order_id: new mongoose_1.default.Types.ObjectId().toString(),
47
- payment_id: new mongoose_1.default.Types.ObjectId().toString(),
48
- amount: 1200,
49
- received_amount: 1200,
50
- credit_note: 'CN-2026-09-30',
51
- issued_local_date: '2026-09-29',
52
- });
53
37
  const validDocument = () => ({
54
38
  _id: new mongoose_1.default.Types.ObjectId().toString(),
55
39
  tenant_id: 'z2-isb',
@@ -63,8 +47,8 @@ const validDocument = () => ({
63
47
  [constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: saleTypeMetric(),
64
48
  [constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]: saleTypeMetric(),
65
49
  [constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: {
66
- issued: { count: 1, amount: 1200, settled_count: 0, settled_amount: 600, bills: [creditBill()] },
67
- received: { count: 1, amount: 1200, bills: [receivedCreditBill()] },
50
+ issued: { count: 1, amount: 1200, settled_count: 0, settled_amount: 0 },
51
+ received: { count: 1, amount: 600 },
68
52
  },
69
53
  },
70
54
  },
@@ -87,6 +71,15 @@ describe('materialized_tenant_sales_overview_reports schema', () => {
87
71
  },
88
72
  });
89
73
  });
74
+ it('exports UNIQUE index options for the materializer to CREATE (F12)', () => {
75
+ expect(materialized_tenant_sales_overview_reports_1.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_INDEX_OPTIONS).toEqual([
76
+ {
77
+ key: { tenant_id: 1, scope_context: 1, scope_field: 1, day_index: 1 },
78
+ name: 'tenant_id__scope_context__scope_field__day_index',
79
+ unique: true,
80
+ },
81
+ ]);
82
+ });
90
83
  it('validates a well-formed scope document and casts metrics to a Map', () => {
91
84
  const doc = new Model(validDocument());
92
85
  expect(doc.validateSync()).toBeUndefined();
@@ -134,16 +127,22 @@ describe('materialized_tenant_sales_overview_reports schema', () => {
134
127
  ];
135
128
  expect(new Model(document).validateSync()).toBeUndefined();
136
129
  });
137
- it('validates the per-key credit-bill ledger and applies zero defaults when omitted', () => {
130
+ it('validates the per-key credit-bill COUNTERS and applies zero defaults when omitted', () => {
138
131
  const doc = new Model(validDocument());
139
132
  expect(doc.validateSync()).toBeUndefined();
140
133
  const metrics = doc.get('sale_type_metrics');
141
134
  const entry = metrics.get('COMPLETED:POS_TAKE-AWAY');
142
135
  expect(entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.count).toBe(1);
143
- expect(entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills[0].received_amount).toBe(600);
144
- expect(entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills[0].settled_at).toBeNull();
145
- expect(entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills[0].received_amount).toBe(1200);
146
- expect(entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.bills[0].credit_note).toBe('CN-2026-09-30');
136
+ expect(entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.amount).toBe(1200);
137
+ expect(entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_count).toBe(0);
138
+ expect(entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_amount).toBe(0);
139
+ expect(entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.count).toBe(1);
140
+ expect(entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.amount).toBe(600);
141
+ // The itemized ledger lives in `materialized_tenant_credit_bills` — report
142
+ // documents must carry numbers only (unknown paths are strict-mode
143
+ // stripped, so a stray `bills` array can never round-trip).
144
+ expect('bills' in (entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued ?? {})).toBe(false);
145
+ expect('bills' in (entry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received ?? {})).toBe(false);
147
146
  const minimal = { ...validDocument() };
148
147
  const minimalMetrics = minimal.sale_type_metrics;
149
148
  delete minimalMetrics['COMPLETED:POS_TAKE-AWAY'][constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
@@ -155,8 +154,8 @@ describe('materialized_tenant_sales_overview_reports schema', () => {
155
154
  expect(defaultEntry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.amount).toBe(0);
156
155
  expect(defaultEntry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_count).toBe(0);
157
156
  expect(defaultEntry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_amount).toBe(0);
158
- expect(defaultEntry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills).toEqual([]);
159
157
  expect(defaultEntry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.count).toBe(0);
158
+ expect(defaultEntry?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.amount).toBe(0);
160
159
  });
161
160
  it('accepts an empty metrics map (day with no orders) and applies key-filter defaults', () => {
162
161
  const document = { ...validDocument(), sale_type_metrics: {} };
@@ -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
+ });