@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
@@ -0,0 +1,715 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../../constants");
4
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
5
+ const materialized_credit_bills_helpers_1 = require("../../helpers/materialized-reports/materialized-credit-bills-helpers");
6
+ const materialized_credit_bills_1 = require("../../schemas/models/materialized_credit_bills");
7
+ /** Narrows helper results that are `null` on invalid data (tests expect valid data). */
8
+ const expectNonNull = (value) => {
9
+ if (value == null)
10
+ throw new Error('expected a non-null helper result');
11
+ return value;
12
+ };
13
+ const TENANT = 'z2-isb';
14
+ const KEY = 'COMPLETED:POS_WALK-IN';
15
+ const NOW = new Date('2026-10-03T23:00:00.000Z');
16
+ const makeOrder = (args) => ({
17
+ _id: args.orderId,
18
+ tenant_id: TENANT,
19
+ platform: 'POS_WALK-IN',
20
+ order_status: constants_1.ORDER_STATUS_ENUM.COMPLETED,
21
+ amount_earned: args.amountDue,
22
+ amount_collected: args.amountPaid,
23
+ total_discount_applied: 0,
24
+ gst_amount: 0,
25
+ tax_amount: 0,
26
+ tip_amount: 0,
27
+ tax_invoice_provider_charges: 0,
28
+ is_deleted: false,
29
+ deferred_settlement: true,
30
+ localDate: args.localDate,
31
+ localHour: args.localHour,
32
+ order_settled_at: args.settledAt != null ? new Date(args.settledAt) : undefined,
33
+ createdAt: args.createdAt != null ? new Date(args.createdAt) : undefined,
34
+ updatedAt: new Date(args.updatedAt ?? args.settledAt ?? `${args.localDate}T20:00:00.000Z`),
35
+ payments: [
36
+ {
37
+ payment_id: 'pay-1',
38
+ payment_type: args.paymentType ?? constants_1.PAYMENT_TYPE_ENUM.PAY_LATER,
39
+ payment_status: args.paymentStatus ?? constants_1.PAYMENT_STATUS_ENUM.PENDING,
40
+ amount_due: args.amountDue,
41
+ amount_paid: args.amountPaid,
42
+ amount_refunded: 0,
43
+ card_details: null,
44
+ note: args.note ?? null,
45
+ },
46
+ ],
47
+ });
48
+ const makeIssuedCandidate = (over = {}) => ({
49
+ order_id: 'order-1',
50
+ payment_id: 'pay-1',
51
+ order_status: constants_1.ORDER_STATUS_ENUM.COMPLETED,
52
+ platform: 'POS_WALK-IN',
53
+ amount: 1000,
54
+ issued_at: new Date('2026-10-01T20:00:00.000Z'),
55
+ issued_local_hour: '2026-10-01 20',
56
+ received_at_issue: 0,
57
+ received_amount: 0,
58
+ settled_at: null,
59
+ settled_local_date: null,
60
+ credit_note: null,
61
+ source_watermark: new Date('2026-10-01T20:00:00.000Z'),
62
+ ...over,
63
+ });
64
+ const makeEventCandidate = (over = {}) => ({
65
+ order_id: 'order-1',
66
+ payment_id: 'pay-1',
67
+ order_status: constants_1.ORDER_STATUS_ENUM.COMPLETED,
68
+ platform: 'POS_WALK-IN',
69
+ amount: 1000,
70
+ issued_at: new Date('2026-10-01T20:00:00.000Z'),
71
+ issued_local_date: '2026-10-01',
72
+ issued_local_hour: '2026-10-01 20',
73
+ candidate_cumulative: 400,
74
+ event: {
75
+ event_local_date: '2026-10-03',
76
+ event_local_hour: '2026-10-03 10',
77
+ received_delta: 0,
78
+ event_type: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM.RECEIPT,
79
+ credit_note: null,
80
+ settled_at: null,
81
+ },
82
+ source_watermark: new Date('2026-10-03T10:00:00.000Z'),
83
+ ...over,
84
+ });
85
+ const issuedEntry = (over = {}) => ({
86
+ order_id: 'order-1',
87
+ payment_id: 'pay-1',
88
+ amount: 1000,
89
+ issued_at: new Date('2026-10-01T20:00:00.000Z'),
90
+ issued_local_hour: '2026-10-01 20',
91
+ received_at_issue: 0,
92
+ received_amount: 0,
93
+ settled_at: null,
94
+ settled_local_date: null,
95
+ credit_note: null,
96
+ ...over,
97
+ });
98
+ const receivedEntry = (over = {}) => ({
99
+ order_id: 'order-1',
100
+ payment_id: 'pay-1',
101
+ event_local_date: '2026-10-03',
102
+ amount: 1000,
103
+ received_amount: 400,
104
+ received_delta: 400,
105
+ received_at: null,
106
+ event_local_hour: '2026-10-03 10',
107
+ credit_note: null,
108
+ issued_local_date: '2026-10-01',
109
+ ...over,
110
+ });
111
+ const makeCreditDoc = (scope, field, sections = {}) => ({
112
+ _id: `id-${scope}-${field}`,
113
+ tenant_id: TENANT,
114
+ brand_id: 'brand-1',
115
+ scope_context: scope,
116
+ scope_field: field,
117
+ day_index: null,
118
+ sale_type_key_filters: [...MATERIALIZED_REPORTS_1.SALES_OVERVIEW_KEY_FILTERS],
119
+ credit_bills: sections,
120
+ iteration: 1,
121
+ schema_version: materialized_credit_bills_1.MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION,
122
+ source_watermark: new Date('2026-10-01T20:00:00.000Z'),
123
+ computed_at: new Date('2026-10-01T23:00:00.000Z'),
124
+ createdAt: new Date('2026-10-01T23:00:00.000Z'),
125
+ updatedAt: new Date('2026-10-01T23:00:00.000Z'),
126
+ });
127
+ describe('buildCreditBillIssuedCandidatesFromOrder', () => {
128
+ it('emits the issue entry with same-day settlement anchors (money in hand at issue)', () => {
129
+ const order = makeOrder({
130
+ orderId: 'order-cash-credit',
131
+ localDate: '2026-10-01',
132
+ localHour: 20,
133
+ amountDue: 1000,
134
+ amountPaid: 1000,
135
+ paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
136
+ settledAt: '2026-10-01T18:00:00.000Z',
137
+ });
138
+ const candidates = expectNonNull((0, materialized_credit_bills_helpers_1.buildCreditBillIssuedCandidatesFromOrder)(order, '2026-10-01', { now: NOW, gmtOffset: 5 }));
139
+ expect(candidates).toHaveLength(1);
140
+ expect(candidates[0]).toMatchObject({
141
+ order_id: 'order-cash-credit',
142
+ payment_id: 'pay-1',
143
+ amount: 1000,
144
+ received_at_issue: 1000,
145
+ received_amount: 1000,
146
+ settled_local_date: '2026-10-01',
147
+ issued_local_hour: '2026-10-01 20',
148
+ });
149
+ expect(candidates[0].settled_at).toEqual(new Date('2026-10-01T18:00:00.000Z'));
150
+ });
151
+ it('N2: a settlement on a LATER local day reads UNPAID at issue (backfill from current state)', () => {
152
+ const order = makeOrder({
153
+ orderId: 'order-late',
154
+ localDate: '2026-10-01',
155
+ amountDue: 1000,
156
+ amountPaid: 1000,
157
+ paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
158
+ settledAt: '2026-10-03T05:00:00.000Z', // 10:00 tenant-local (+5) on the LATER day
159
+ });
160
+ const rows = expectNonNull((0, materialized_credit_bills_helpers_1.buildCreditBillIssuedCandidatesFromOrder)(order, '2026-10-01', { now: NOW, gmtOffset: 5 }));
161
+ expect(rows[0]).toMatchObject({
162
+ received_at_issue: 0,
163
+ received_amount: 0,
164
+ settled_at: null,
165
+ settled_local_date: null,
166
+ });
167
+ // Without gmtOffset the settlement-day comparison is skipped (live closes
168
+ // never need it — the bill is not settled yet at its day's close).
169
+ const withoutOffset = expectNonNull((0, materialized_credit_bills_helpers_1.buildCreditBillIssuedCandidatesFromOrder)(order, '2026-10-01', { now: NOW }));
170
+ expect(withoutOffset[0]).toMatchObject({ received_at_issue: 1000, settled_local_date: '2026-10-01' });
171
+ });
172
+ it('anchors issued_at to createdAt → order_settled_at → compile time; skips cash; rejects un-keyable', () => {
173
+ const bare = makeOrder({
174
+ orderId: 'order-bare',
175
+ localDate: '2026-10-01',
176
+ amountDue: 300,
177
+ amountPaid: 0,
178
+ createdAt: null,
179
+ settledAt: null,
180
+ });
181
+ expect(expectNonNull((0, materialized_credit_bills_helpers_1.buildCreditBillIssuedCandidatesFromOrder)(bare, '2026-10-01', { now: NOW }))[0].issued_at).toEqual(NOW);
182
+ const unkeyable = makeOrder({ orderId: 'order-unkeyable', localDate: '2026-10-01', amountDue: 300, amountPaid: 0 });
183
+ unkeyable.payments[0].payment_id = null;
184
+ expect((0, materialized_credit_bills_helpers_1.buildCreditBillIssuedCandidatesFromOrder)(unkeyable, '2026-10-01', { now: NOW })).toBeNull();
185
+ const cashOrder = makeOrder({
186
+ orderId: 'order-cash',
187
+ localDate: '2026-10-01',
188
+ amountDue: 500,
189
+ amountPaid: 500,
190
+ paymentType: constants_1.PAYMENT_TYPE_ENUM.CASH,
191
+ paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
192
+ settledAt: '2026-10-01T10:00:00.000Z',
193
+ });
194
+ expect(expectNonNull((0, materialized_credit_bills_helpers_1.buildCreditBillIssuedCandidatesFromOrder)(cashOrder, '2026-10-01', { now: NOW }))).toEqual([]);
195
+ });
196
+ });
197
+ describe('buildCreditBillEventCandidatesFromOrder', () => {
198
+ it('emits a receipt shell per collected PAY_LATER payment (delta resolves at close time)', () => {
199
+ const order = makeOrder({
200
+ orderId: 'order-collected',
201
+ localDate: '2026-10-01',
202
+ localHour: 20,
203
+ amountDue: 1000,
204
+ amountPaid: 400,
205
+ settledAt: '2026-10-03T05:00:00.000Z',
206
+ note: 'CN-PARTIAL',
207
+ });
208
+ const candidates = expectNonNull((0, materialized_credit_bills_helpers_1.buildCreditBillEventCandidatesFromOrder)(order, '2026-10-03', { now: NOW, gmtOffset: 5 }));
209
+ expect(candidates).toHaveLength(1);
210
+ expect(candidates[0]).toMatchObject({
211
+ order_id: 'order-collected',
212
+ payment_id: 'pay-1',
213
+ amount: 1000,
214
+ candidate_cumulative: 400,
215
+ issued_local_date: '2026-10-01',
216
+ });
217
+ expect(candidates[0].event).toMatchObject({
218
+ event_local_date: '2026-10-03',
219
+ event_local_hour: '2026-10-03 10', // settlement anchor (+5), not the punch hour
220
+ received_delta: 0, // order-pure: resolved by the close plan
221
+ credit_note: 'CN-PARTIAL',
222
+ });
223
+ const unpaid = makeOrder({ orderId: 'order-unpaid', localDate: '2026-10-01', amountDue: 1000, amountPaid: 0 });
224
+ expect(expectNonNull((0, materialized_credit_bills_helpers_1.buildCreditBillEventCandidatesFromOrder)(unpaid, '2026-10-03', { now: NOW }))).toEqual([]);
225
+ });
226
+ });
227
+ describe('resolveCreditBillDay (delta resolution + carry-forward + settlements)', () => {
228
+ it('resolves a first-seen event delta against the stored cumulative and emits the settlement once', () => {
229
+ const stored = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-01', {
230
+ [KEY]: { issued: [issuedEntry()], received: [] },
231
+ });
232
+ const resolution = expectNonNull((0, materialized_credit_bills_helpers_1.resolveCreditBillDay)({
233
+ tenantId: TENANT,
234
+ localDate: '2026-10-03',
235
+ issued: [],
236
+ events: [makeEventCandidate({ candidate_cumulative: 1000 })],
237
+ stored: [stored],
238
+ computedAt: NOW,
239
+ }));
240
+ expect(resolution.received_events).toHaveLength(1);
241
+ expect(resolution.received_events[0].entry).toMatchObject({
242
+ received_delta: 1000,
243
+ received_amount: 1000,
244
+ event_local_date: '2026-10-03',
245
+ });
246
+ expect(resolution.received_events[0].settled).toBe(true);
247
+ expect(resolution.settled_bills).toHaveLength(1);
248
+ expect(resolution.settled_bills[0]).toMatchObject({
249
+ key: KEY,
250
+ amount: 1000,
251
+ received_amount: 1000,
252
+ settled_local_date: '2026-10-03',
253
+ issued_local_date: '2026-10-01',
254
+ issued_local_hour: '2026-10-01 20',
255
+ });
256
+ });
257
+ it('keeps a stored same-day delta and never re-emits a settled transition (idempotent re-close)', () => {
258
+ const stored = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-03', {
259
+ [KEY]: {
260
+ issued: [
261
+ issuedEntry({
262
+ received_amount: 1000,
263
+ settled_at: new Date('2026-10-03T10:00:00.000Z'),
264
+ settled_local_date: '2026-10-03',
265
+ }),
266
+ ],
267
+ received: [receivedEntry({ received_delta: 400, received_amount: 400 })],
268
+ },
269
+ });
270
+ const resolution = expectNonNull((0, materialized_credit_bills_helpers_1.resolveCreditBillDay)({
271
+ tenantId: TENANT,
272
+ localDate: '2026-10-03',
273
+ issued: [],
274
+ events: [makeEventCandidate({ candidate_cumulative: 400 })],
275
+ stored: [stored],
276
+ computedAt: NOW,
277
+ }));
278
+ expect(resolution.received_events[0].entry.received_delta).toBe(400);
279
+ expect(resolution.settled_bills).toEqual([]); // already settled — no transition to patch
280
+ });
281
+ it('carries issue anchors forward on a re-merge (never re-anchors to the current payment state)', () => {
282
+ const stored = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-01', {
283
+ [KEY]: {
284
+ issued: [
285
+ issuedEntry({
286
+ received_amount: 1000,
287
+ settled_at: new Date('2026-10-05T08:00:00.000Z'),
288
+ settled_local_date: '2026-10-05',
289
+ }),
290
+ ],
291
+ received: [],
292
+ },
293
+ });
294
+ const resolution = expectNonNull((0, materialized_credit_bills_helpers_1.resolveCreditBillDay)({
295
+ tenantId: TENANT,
296
+ localDate: '2026-10-01',
297
+ issued: [makeIssuedCandidate()], // current state claims nothing received
298
+ events: [],
299
+ stored: [stored],
300
+ computedAt: NOW,
301
+ }));
302
+ expect(resolution.issued[0].entry).toMatchObject({
303
+ received_at_issue: 0,
304
+ received_amount: 1000, // carried forward, not regressed to 0
305
+ settled_local_date: '2026-10-05',
306
+ });
307
+ });
308
+ it('returns null for invalid input (never throws)', () => {
309
+ expect((0, materialized_credit_bills_helpers_1.resolveCreditBillDay)(null)).toBeNull();
310
+ expect((0, materialized_credit_bills_helpers_1.resolveCreditBillDay)({
311
+ tenantId: '',
312
+ localDate: '2026-10-03',
313
+ issued: [],
314
+ events: [],
315
+ stored: [],
316
+ computedAt: NOW,
317
+ })).toBeNull();
318
+ });
319
+ });
320
+ describe('buildMaterializedCreditBillDayReports (month-capped scopes)', () => {
321
+ // Both entries belong to the COMPILED day (the compile only ever passes
322
+ // that day's issues + receipts) — 2026-10-03: issue at hour 20, receipt at
323
+ // hour 10.
324
+ const resolution = {
325
+ issued: [
326
+ {
327
+ key: KEY,
328
+ entry: issuedEntry({ issued_local_hour: '2026-10-03 20' }),
329
+ source_watermark: new Date('2026-10-03T20:00:00.000Z'),
330
+ },
331
+ ],
332
+ received_events: [
333
+ {
334
+ key: KEY,
335
+ entry: receivedEntry({ event_local_date: '2026-10-03', event_local_hour: '2026-10-03 10' }),
336
+ received_at: null,
337
+ credit_note: null,
338
+ settled: false,
339
+ settled_at: null,
340
+ settled_local_date: '2026-10-03',
341
+ source_watermark: new Date('2026-10-03T10:00:00.000Z'),
342
+ },
343
+ ],
344
+ settled_bills: [],
345
+ };
346
+ it('materializes hour/date/week/ISO-week/month documents with the entries on every scope', () => {
347
+ const docs = expectNonNull((0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillDayReports)({
348
+ tenantId: TENANT,
349
+ brandId: 'brand-1',
350
+ localDate: '2026-10-03',
351
+ resolution,
352
+ computedAt: NOW,
353
+ }));
354
+ expect(docs.map((doc) => `${doc.scope_context}|${doc.scope_field}`)).toEqual([
355
+ `${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR}|2026-10-03 10`,
356
+ `${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR}|2026-10-03 20`,
357
+ `${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|2026-10-03`,
358
+ `${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK}|2026-09-27`,
359
+ `${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR}|2026-W40`,
360
+ `${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH}|2026-10`,
361
+ ]);
362
+ const dateDoc = expectNonNull(docs.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE));
363
+ expect(dateDoc.credit_bills?.[KEY]?.issued).toHaveLength(1);
364
+ expect(dateDoc.credit_bills?.[KEY]?.received).toHaveLength(1);
365
+ // Hour documents take only their own anchor: the receipt hour carries the
366
+ // receipt, the punch hour the issue entry.
367
+ const receiptHour = expectNonNull(docs.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR && doc.scope_field === '2026-10-03 10'));
368
+ expect(receiptHour.credit_bills?.[KEY]?.issued).toEqual([]);
369
+ expect(receiptHour.credit_bills?.[KEY]?.received).toHaveLength(1);
370
+ const punchHour = expectNonNull(docs.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR && doc.scope_field === '2026-10-03 20'));
371
+ expect(punchHour.credit_bills?.[KEY]?.issued).toHaveLength(1);
372
+ expect(punchHour.credit_bills?.[KEY]?.received).toEqual([]);
373
+ const monthDoc = expectNonNull(docs.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH));
374
+ expect(monthDoc.day_index).toBeNull();
375
+ expect(dateDoc.day_index).not.toBeNull();
376
+ // Watermark = max of the folded sources.
377
+ expect(dateDoc.source_watermark).toEqual(new Date('2026-10-03T20:00:00.000Z'));
378
+ });
379
+ it('returns an empty list for a day with no credit activity', () => {
380
+ const docs = expectNonNull((0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillDayReports)({
381
+ tenantId: TENANT,
382
+ brandId: 'brand-1',
383
+ localDate: '2026-10-01',
384
+ resolution: { issued: [], received_events: [], settled_bills: [] },
385
+ computedAt: NOW,
386
+ }));
387
+ expect(docs).toEqual([]);
388
+ });
389
+ });
390
+ describe('updateMaterializedCreditBillsReport', () => {
391
+ it('replaces the payload and bumps the iteration when it changed', () => {
392
+ const existing = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-01', {
393
+ [KEY]: { issued: [issuedEntry()], received: [] },
394
+ });
395
+ const replacement = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-01', {
396
+ [KEY]: { issued: [issuedEntry({ received_amount: 200 })], received: [] },
397
+ });
398
+ const updated = expectNonNull((0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { replacement }, { computedAt: NOW }));
399
+ expect(updated.credit_bills?.[KEY]?.issued[0].received_amount).toBe(200);
400
+ expect(updated.iteration).toBe(2);
401
+ expect(updated.updatedAt).toEqual(NOW);
402
+ });
403
+ it('subtracts the stored day and folds the recompiled entries back in (period accumulation)', () => {
404
+ const existing = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, '2026-10', {
405
+ [KEY]: {
406
+ issued: [issuedEntry({ received_amount: 100 })],
407
+ received: [receivedEntry({ received_delta: 100, received_amount: 100 })],
408
+ },
409
+ });
410
+ const storedDay = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-03', {
411
+ [KEY]: {
412
+ issued: [issuedEntry({ received_amount: 100 })],
413
+ received: [receivedEntry({ received_delta: 100, received_amount: 100 })],
414
+ },
415
+ });
416
+ // Additions arrive as the COMPILED PERIOD document (same scope as the
417
+ // existing one) — the stored DAY is subtracted by entry identity.
418
+ const recompiledMonth = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, '2026-10', {
419
+ [KEY]: {
420
+ issued: [issuedEntry({ received_amount: 500 })],
421
+ received: [receivedEntry({ received_delta: 500, received_amount: 500 })],
422
+ },
423
+ });
424
+ const updated = expectNonNull((0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { subtract: [storedDay], additions: [recompiledMonth] }, { computedAt: NOW }));
425
+ expect(updated.credit_bills?.[KEY]?.issued[0].received_amount).toBe(500);
426
+ expect(updated.credit_bills?.[KEY]?.received[0].received_delta).toBe(500);
427
+ expect(updated.iteration).toBe(2);
428
+ });
429
+ it('applies settlement patches once (second application is a no-op)', () => {
430
+ const existing = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-01', {
431
+ [KEY]: { issued: [issuedEntry()], received: [] },
432
+ });
433
+ const settlement = {
434
+ key: KEY,
435
+ order_id: 'order-1',
436
+ payment_id: 'pay-1',
437
+ amount: 1000,
438
+ received_amount: 1000,
439
+ settled_at: new Date('2026-10-03T10:00:00.000Z'),
440
+ settled_local_date: '2026-10-03',
441
+ credit_note: 'CN-1',
442
+ issued_local_date: '2026-10-01',
443
+ issued_local_hour: '2026-10-01 20',
444
+ };
445
+ const patched = expectNonNull((0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { settled_bills: [settlement] }, { computedAt: NOW }));
446
+ expect(patched.credit_bills?.[KEY]?.issued[0]).toMatchObject({
447
+ received_amount: 1000,
448
+ settled_local_date: '2026-10-03',
449
+ credit_note: 'CN-1',
450
+ });
451
+ expect(patched.iteration).toBe(2);
452
+ const replayed = expectNonNull((0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(patched, { settled_bills: [settlement] }, { computedAt: NOW }));
453
+ expect(replayed.iteration ?? 1).toBe(2); // settled already — no version bump
454
+ });
455
+ it('prunes keys emptied by a full subtraction', () => {
456
+ const existing = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, '2026-10', {
457
+ [KEY]: { issued: [issuedEntry()], received: [] },
458
+ });
459
+ const storedDay = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-01', {
460
+ [KEY]: { issued: [issuedEntry()], received: [] },
461
+ });
462
+ const updated = expectNonNull((0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { subtract: [storedDay] }, { computedAt: NOW }));
463
+ expect(updated.credit_bills).toEqual({});
464
+ });
465
+ });
466
+ describe('computeMaterializedCreditBillTotalsFromReports (range-pure counters)', () => {
467
+ const selection = (labels, endLabel, granularity = 'day') => ({
468
+ granularity,
469
+ labels: new Set(labels),
470
+ end_label: endLabel,
471
+ });
472
+ it('derives settled / outstanding at the window end and today', () => {
473
+ const doc = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-01', {
474
+ [KEY]: {
475
+ issued: [
476
+ issuedEntry({
477
+ order_id: 'b-settled',
478
+ payment_id: 'p1',
479
+ received_amount: 1000,
480
+ settled_local_date: '2026-10-01',
481
+ }),
482
+ issuedEntry({ order_id: 'b-partial', payment_id: 'p2', received_at_issue: 200, received_amount: 700 }),
483
+ issuedEntry({
484
+ order_id: 'b-prepaid',
485
+ payment_id: 'p3',
486
+ received_at_issue: 400,
487
+ received_amount: 1000,
488
+ settled_local_date: '2026-10-08', // settles AFTER the window end
489
+ }),
490
+ ],
491
+ received: [
492
+ receivedEntry({
493
+ order_id: 'b-settled',
494
+ payment_id: 'p1',
495
+ event_local_date: '2026-10-01',
496
+ received_delta: 1000,
497
+ received_amount: 1000,
498
+ }),
499
+ receivedEntry({
500
+ order_id: 'b-partial',
501
+ payment_id: 'p2',
502
+ event_local_date: '2026-10-05',
503
+ received_delta: 300,
504
+ received_amount: 500,
505
+ }),
506
+ receivedEntry({
507
+ order_id: 'b-partial',
508
+ payment_id: 'p2',
509
+ event_local_date: '2026-10-07',
510
+ received_delta: 200,
511
+ received_amount: 700,
512
+ }),
513
+ ],
514
+ },
515
+ });
516
+ const totals = (0, materialized_credit_bills_helpers_1.computeMaterializedCreditBillTotalsFromReports)([doc], selection(['2026-10-01', '2026-10-05', '2026-10-07'], '2026-10-07'));
517
+ expect(totals.received).toEqual({ count: 3, amount: 1500 }); // receipt entries: b-settled 1 + b-partial 2
518
+ expect(totals.issued.count).toBe(3);
519
+ expect(totals.issued.amount).toBe(3000);
520
+ expect(totals.issued.settled_count).toBe(1);
521
+ expect(totals.issued.settled_amount).toBe(1000);
522
+ // b-partial owes 300 (700/1000); b-prepaid owes 600 (400/1000 at the end)
523
+ expect(totals.issued.outstanding_count).toBe(2);
524
+ expect(totals.issued.outstanding_amount).toBe(900);
525
+ // today: b-prepaid has since been fully collected
526
+ expect(totals.issued.outstanding_now_count).toBe(1);
527
+ expect(totals.issued.outstanding_now_amount).toBe(300);
528
+ expect(totals.collected_at_issue_count).toBe(2);
529
+ expect(totals.collected_at_issue_amount).toBe(600);
530
+ });
531
+ it('R5-1: month-granular reads expand the boundary to the LAST DAY of the month', () => {
532
+ const monthDoc = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, '2026-10', {
533
+ [KEY]: {
534
+ issued: [
535
+ issuedEntry({
536
+ order_id: 'b-in-month',
537
+ payment_id: 'p1',
538
+ received_amount: 1000,
539
+ settled_local_date: '2026-10-15',
540
+ }),
541
+ issuedEntry({
542
+ order_id: 'b-after',
543
+ payment_id: 'p2',
544
+ received_amount: 1000,
545
+ settled_local_date: '2026-11-02',
546
+ }),
547
+ ],
548
+ received: [
549
+ receivedEntry({
550
+ order_id: 'b-in-month',
551
+ payment_id: 'p1',
552
+ event_local_date: '2026-10-15',
553
+ received_delta: 1000,
554
+ received_amount: 1000,
555
+ }),
556
+ ],
557
+ },
558
+ });
559
+ // A caller passing the highest scope_field ('2026-10') must still get the
560
+ // as-of-end math of '2026-10-31' — a raw month string is lexicographically
561
+ // GREATER than every day inside it (audit R5-1).
562
+ const totals = (0, materialized_credit_bills_helpers_1.computeMaterializedCreditBillTotalsFromReports)([monthDoc], {
563
+ granularity: 'day',
564
+ labels: new Set(['2026-10']),
565
+ end_label: '2026-10',
566
+ });
567
+ expect(totals.issued.count).toBe(2);
568
+ expect(totals.issued.settled_count).toBe(1); // settled on 10-15 — inside October
569
+ expect(totals.issued.outstanding_count).toBe(1); // settles 11-02 — outstanding at the month end
570
+ expect(totals.received).toEqual({ count: 1, amount: 1000 }); // the 10-15 receipt is ≤ end
571
+ });
572
+ it('exposes the money collected AT ISSUE (N4 — same-day settled + prepaid)', () => {
573
+ const doc = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-01', {
574
+ [KEY]: {
575
+ issued: [
576
+ issuedEntry({ order_id: 'b-same-day', received_at_issue: 200, received_amount: 200 }),
577
+ issuedEntry({ order_id: 'b-prepaid', received_at_issue: 300, received_amount: 300 }),
578
+ issuedEntry({ order_id: 'b-open' }),
579
+ ],
580
+ received: [],
581
+ },
582
+ });
583
+ const totals = (0, materialized_credit_bills_helpers_1.computeMaterializedCreditBillTotalsFromReports)([doc], selection(['2026-10-01'], '2026-10-01'));
584
+ expect(totals.collected_at_issue_count).toBe(2);
585
+ expect(totals.collected_at_issue_amount).toBe(500);
586
+ expect(totals.received).toEqual({ count: 0, amount: 0 });
587
+ });
588
+ it('matches by document scope — hour selections take hour documents, day selections date documents', () => {
589
+ const dateDoc = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-05', {
590
+ [KEY]: {
591
+ issued: [issuedEntry({ issued_local_hour: null })],
592
+ received: [
593
+ receivedEntry({
594
+ event_local_date: '2026-10-05',
595
+ event_local_hour: null,
596
+ received_delta: 250,
597
+ received_amount: 250,
598
+ }),
599
+ ],
600
+ },
601
+ });
602
+ const hourDoc = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, '2026-10-05 10', {
603
+ [KEY]: {
604
+ issued: [],
605
+ received: [
606
+ receivedEntry({
607
+ event_local_date: '2026-10-05',
608
+ event_local_hour: '2026-10-05 10',
609
+ received_delta: 250,
610
+ received_amount: 250,
611
+ }),
612
+ ],
613
+ },
614
+ });
615
+ const dayTotals = (0, materialized_credit_bills_helpers_1.computeMaterializedCreditBillTotalsFromReports)([dateDoc], selection(['2026-10-05'], '2026-10-05'));
616
+ expect(dayTotals.issued.count).toBe(1);
617
+ expect(dayTotals.received).toEqual({ count: 1, amount: 250 });
618
+ const hourTotals = (0, materialized_credit_bills_helpers_1.computeMaterializedCreditBillTotalsFromReports)([hourDoc], selection(['2026-10-05 10'], '2026-10-05 23', 'hour'));
619
+ expect(hourTotals.issued.count).toBe(0); // the date document is not part of an hour selection
620
+ expect(hourTotals.received).toEqual({ count: 1, amount: 250 });
621
+ });
622
+ it('ByKey: the per-key breakdown sums to the aggregate totals', () => {
623
+ const doc = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-01', {
624
+ [KEY]: {
625
+ issued: [
626
+ issuedEntry({ order_id: 'b-a', payment_id: 'p1', received_amount: 1000, settled_local_date: '2026-10-01' }),
627
+ ],
628
+ received: [
629
+ receivedEntry({
630
+ order_id: 'b-a',
631
+ payment_id: 'p1',
632
+ event_local_date: '2026-10-01',
633
+ received_delta: 1000,
634
+ received_amount: 1000,
635
+ }),
636
+ ],
637
+ },
638
+ 'CANCELLED:POS_WALK-IN': {
639
+ issued: [issuedEntry({ order_id: 'b-b', payment_id: 'p2' })],
640
+ received: [],
641
+ },
642
+ });
643
+ const sel = selection(['2026-10-01'], '2026-10-01');
644
+ const aggregate = (0, materialized_credit_bills_helpers_1.computeMaterializedCreditBillTotalsFromReports)([doc], sel);
645
+ const byKey = (0, materialized_credit_bills_helpers_1.computeMaterializedCreditBillTotalsFromReportsByKey)([doc], sel);
646
+ expect(Object.keys(byKey)).toEqual(['CANCELLED:POS_WALK-IN', KEY]); // ordered by key
647
+ expect(byKey[KEY].issued.settled_count).toBe(1);
648
+ expect(byKey['CANCELLED:POS_WALK-IN'].issued.settled_count).toBe(0);
649
+ expect(byKey['CANCELLED:POS_WALK-IN'].issued.outstanding_count).toBe(1);
650
+ // Summing the per-key values reproduces the aggregate result.
651
+ expect(byKey[KEY].issued.count + byKey['CANCELLED:POS_WALK-IN'].issued.count).toBe(aggregate.issued.count);
652
+ expect(aggregate.issued.count).toBe(2); // non-vacuous
653
+ expect(byKey[KEY].issued.settled_amount + byKey['CANCELLED:POS_WALK-IN'].issued.settled_amount).toBe(aggregate.issued.settled_amount);
654
+ expect(byKey[KEY].received.amount + byKey['CANCELLED:POS_WALK-IN'].received.amount).toBe(aggregate.received.amount);
655
+ expect(byKey[KEY].received.count + byKey['CANCELLED:POS_WALK-IN'].received.count).toBe(aggregate.received.count);
656
+ });
657
+ it('returns zeroed totals for an empty document set', () => {
658
+ const totals = (0, materialized_credit_bills_helpers_1.computeMaterializedCreditBillTotalsFromReports)([], selection(['2026-10-05'], '2026-10-05'));
659
+ expect(totals.issued).toEqual({
660
+ count: 0,
661
+ amount: 0,
662
+ settled_count: 0,
663
+ settled_amount: 0,
664
+ outstanding_count: 0,
665
+ outstanding_amount: 0,
666
+ outstanding_now_count: 0,
667
+ outstanding_now_amount: 0,
668
+ });
669
+ expect(totals.received).toEqual({ count: 0, amount: 0 });
670
+ expect(totals.collected_at_issue_count).toBe(0);
671
+ expect(totals.collected_at_issue_amount).toBe(0);
672
+ });
673
+ });
674
+ describe('buildMaterializedCreditBillSelectionFromScopeGroups', () => {
675
+ it('expands quarter groups into month docs and keeps 1:1 contexts + as-of-end day', () => {
676
+ const mapped = expectNonNull((0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillSelectionFromScopeGroups)([
677
+ { scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER, scope_field: ['2026-Q3'] },
678
+ { scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, scope_field: ['2026-10-05'] },
679
+ ]));
680
+ expect(mapped.credit_groups).toEqual([
681
+ { scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, scope_field: ['2026-10-05'] },
682
+ {
683
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
684
+ scope_field: ['2026-07', '2026-08', '2026-09'],
685
+ },
686
+ ]);
687
+ expect([...mapped.labels].sort()).toEqual(['2026-07', '2026-08', '2026-09', '2026-10-05']);
688
+ expect(mapped.selection.labels).toBe(mapped.labels);
689
+ expect(mapped.selection.granularity).toBe('day');
690
+ expect(mapped.selection.end_label).toBe('2026-10-05');
691
+ });
692
+ it('ends week and ISO-week labels on their last covered day (never the start/day passthrough)', () => {
693
+ const week = expectNonNull((0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillSelectionFromScopeGroups)([
694
+ { scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, scope_field: ['2026-10-11'] },
695
+ ]));
696
+ expect(week.selection.end_label).toBe('2026-10-17'); // Sunday start + 6
697
+ expect(week.labels.has('2026-10-11')).toBe(true);
698
+ const isoWeek = expectNonNull((0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillSelectionFromScopeGroups)([
699
+ { scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR, scope_field: ['2026-W42'] },
700
+ ]));
701
+ expect(isoWeek.selection.end_label).toBe('2026-10-18'); // ISO week Sunday
702
+ });
703
+ it('anchors hour reads on the last covered hour and rejects malformed input', () => {
704
+ const hourly = expectNonNull((0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillSelectionFromScopeGroups)([
705
+ { scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: ['2026-10-16 09', '2026-10-16 14'] },
706
+ ]));
707
+ expect(hourly.selection.granularity).toBe('hour');
708
+ expect(hourly.selection.end_label).toBe('2026-10-16 14');
709
+ expect((0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillSelectionFromScopeGroups)(null)).toBeNull();
710
+ expect((0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillSelectionFromScopeGroups)([])).toBeNull();
711
+ expect((0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillSelectionFromScopeGroups)([
712
+ { scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, scope_field: ['not-a-week'] },
713
+ ])).toBeNull();
714
+ });
715
+ });