@managesome/eposmatic-toolkit 0.4.28 → 0.4.30

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 (89) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +9 -12
  2. package/esm/helpers/materialized-reports/index.js +2 -0
  3. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +178 -40
  4. package/esm/helpers/materialized-reports/materialized-day-input-signature.js +103 -0
  5. package/esm/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  6. package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +299 -227
  7. package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +20 -1
  8. package/esm/helpers/materialized-reports/materialized-discount-source-helpers.js +176 -0
  9. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +64 -0
  10. package/esm/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  11. package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  12. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  13. package/esm/helpers/materialized-reports/scope-helpers.js +27 -0
  14. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +400 -46
  15. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +28 -6
  16. package/esm/schemas/models/materialized_credit_bills.js +8 -0
  17. package/esm/schemas/models/materialized_report_drilldown_rows.js +39 -12
  18. package/esm/schemas/models/materialized_tenant_discount_entries.js +18 -12
  19. package/esm/schemas/models/materialized_tenant_discount_reports.js +9 -0
  20. package/esm/schemas/models/materialized_tenant_discount_sources.js +1 -1
  21. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
  22. package/esm/schemas/models/orders.js +5 -0
  23. package/esm/schemas/models/tenant_active_jobs.js +8 -0
  24. package/esm/schemas/models/tenant_calendar.js +12 -0
  25. package/lib/constants/MATERIALIZED_REPORTS.d.ts +9 -12
  26. package/lib/constants/MATERIALIZED_REPORTS.js +11 -14
  27. package/lib/helpers/materialized-reports/index.d.ts +2 -0
  28. package/lib/helpers/materialized-reports/index.js +2 -0
  29. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +66 -2
  30. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +179 -39
  31. package/lib/helpers/materialized-reports/materialized-day-input-signature.d.ts +66 -0
  32. package/lib/helpers/materialized-reports/materialized-day-input-signature.js +108 -0
  33. package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  34. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +41 -60
  35. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +298 -226
  36. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.d.ts +4 -4
  37. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +19 -0
  38. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.d.ts +17 -0
  39. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +178 -0
  40. package/lib/helpers/materialized-reports/materialized-index-bootstrap.d.ts +7 -0
  41. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +68 -0
  42. package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +3 -1
  43. package/lib/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  44. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.d.ts +2 -2
  45. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  46. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  47. package/lib/helpers/materialized-reports/scope-helpers.d.ts +22 -0
  48. package/lib/helpers/materialized-reports/scope-helpers.js +28 -0
  49. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +49 -3
  50. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +398 -44
  51. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +4 -1
  52. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +28 -6
  53. package/lib/schemas/models/materialized_credit_bills.d.ts +3 -0
  54. package/lib/schemas/models/materialized_credit_bills.js +8 -0
  55. package/lib/schemas/models/materialized_report_drilldown_rows.d.ts +40 -6
  56. package/lib/schemas/models/materialized_report_drilldown_rows.js +39 -12
  57. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +33 -29
  58. package/lib/schemas/models/materialized_tenant_discount_entries.js +18 -12
  59. package/lib/schemas/models/materialized_tenant_discount_reports.d.ts +3 -0
  60. package/lib/schemas/models/materialized_tenant_discount_reports.js +9 -0
  61. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +6 -6
  62. package/lib/schemas/models/materialized_tenant_discount_sources.js +1 -1
  63. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +3 -0
  64. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
  65. package/lib/schemas/models/orders.d.ts +5 -0
  66. package/lib/schemas/models/orders.js +5 -0
  67. package/lib/schemas/models/tenant_active_jobs.d.ts +3 -0
  68. package/lib/schemas/models/tenant_active_jobs.js +8 -0
  69. package/lib/schemas/models/tenant_calendar.d.ts +13 -0
  70. package/lib/schemas/models/tenant_calendar.js +13 -1
  71. package/lib/schemas/types/materialized_credit_bills.d.ts +6 -0
  72. package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +8 -0
  73. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +9 -5
  74. package/lib/schemas/types/materialized_tenant_discount_reports.d.ts +6 -0
  75. package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +9 -0
  76. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +14 -0
  77. package/lib/schemas/types/tenant_active_jobs.d.ts +8 -0
  78. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +56 -1
  79. package/lib/tests/materialized-reports/materialized-day-input-signature.test.d.ts +1 -0
  80. package/lib/tests/materialized-reports/materialized-day-input-signature.test.js +81 -0
  81. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +17 -0
  82. package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +148 -53
  83. package/lib/tests/materialized-reports/materialized-discount-entries-accumulation.test.js +14 -13
  84. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +76 -0
  85. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +11 -0
  86. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +2 -2
  87. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +311 -4
  88. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +89 -0
  89. package/package.json +1 -1
@@ -41,15 +41,13 @@ function closeInputs(day, state) {
41
41
  .map((ref) => `${ref.scope_context}|${ref.scope_field}`));
42
42
  return {
43
43
  existing: state.reports.filter((doc) => refKeys.has(key(doc))),
44
+ existingPeriodDayDocuments: state.reports.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field !== day),
44
45
  existingEntries: state.entries.filter((doc) => {
45
- if (refKeys.has(key(doc)))
46
- return true;
47
- if (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
46
+ if (!refKeys.has(key(doc)))
48
47
  return false;
49
- const dayRefs = (0, materialized_discount_close_day_helpers_1.getMaterializedDiscountScopeRefsForDay)(String(doc.scope_field));
50
- if (dayRefs == null)
51
- return false;
52
- return dayRefs.some((ref) => periodKeys.has(`${ref.scope_context}|${ref.scope_field}`));
48
+ const isDay = doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ||
49
+ doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR;
50
+ return isDay ? doc.page === 'all' : doc.page === day;
53
51
  }),
54
52
  };
55
53
  }
@@ -69,11 +67,12 @@ function applyPlan(reports, entries, plan) {
69
67
  byScope.set(`${write.report.scope_context}|${write.report.scope_field}`, write.report);
70
68
  for (const stale of plan.staleDocuments)
71
69
  byScope.delete(`${stale.scope_context}|${stale.scope_field}`);
72
- const entriesByScope = new Map(entries.map((doc) => [`${doc.scope_context}|${doc.scope_field}`, doc]));
70
+ const entryKey = (doc) => `${doc.scope_context}|${doc.scope_field}|${doc.page}`;
71
+ const entriesByScope = new Map(entries.map((doc) => [entryKey(doc), doc]));
73
72
  for (const write of plan.entryWrites)
74
- entriesByScope.set(`${write.report.scope_context}|${write.report.scope_field}`, write.report);
73
+ entriesByScope.set(entryKey(write.report), write.report);
75
74
  for (const stale of plan.staleEntryDocuments)
76
- entriesByScope.delete(`${stale.scope_context}|${stale.scope_field}`);
75
+ entriesByScope.delete(entryKey(stale));
77
76
  return { reports: [...byScope.values()], entries: [...entriesByScope.values()] };
78
77
  }
79
78
  describe('materialized discounts — close-day plan', () => {
@@ -128,6 +127,34 @@ describe('materialized discounts — close-day plan', () => {
128
127
  expect(isoBoundary).toContain('2027-01-03');
129
128
  expect((0, materialized_discount_close_day_helpers_1.getMaterializedDiscountPeriodDayScopeFields)('nope')).toBeNull();
130
129
  });
130
+ it('compiles page=all for day/hour and page=localDate for periods', () => {
131
+ const compiled = compileDay('2026-09-13');
132
+ expect(compiled.entries.length).toBeGreaterThan(0);
133
+ for (const entry of compiled.entries) {
134
+ if (entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ||
135
+ entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
136
+ expect(entry.page).toBe('all');
137
+ }
138
+ else {
139
+ expect(entry.page).toBe('2026-09-13');
140
+ }
141
+ }
142
+ });
143
+ it('refuses an entry document without a page', () => {
144
+ const compiled = compileDay('2026-09-13');
145
+ const dayEntry = compiled.entries.find((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
146
+ const plan = (0, materialized_discount_close_day_helpers_1.buildTenantDiscountCloseDayPlan)({
147
+ tenantId: TENANT,
148
+ reports: compiled.reports,
149
+ entries: compiled.entries,
150
+ localDate: '2026-09-13',
151
+ existingEntries: [{ ...dayEntry, page: undefined }],
152
+ existing: [],
153
+ reason: 'TEST',
154
+ computedAt: AT,
155
+ });
156
+ expect(plan).toBeNull();
157
+ });
131
158
  it('first close writes the day with a history row per write', () => {
132
159
  const localDate = '2026-09-13';
133
160
  const compiled = compileDay(localDate);
@@ -349,8 +376,7 @@ describe('materialized discounts — close-day plan', () => {
349
376
  reports: compiled.reports,
350
377
  entries: compiled.entries,
351
378
  localDate: day,
352
- existing: first.reports,
353
- existingEntries: first.entries,
379
+ ...closeInputs(day, first),
354
380
  reason: 'NEW_DAY',
355
381
  computedAt: AT,
356
382
  });
@@ -383,8 +409,12 @@ describe('materialized discounts — close-day plan', () => {
383
409
  expect(pair).toHaveLength(2);
384
410
  const [a, b] = pair;
385
411
  const rowsOf = (doc) => Object.values(doc?.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
386
- const monthEntry = (state) => state.entries.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
387
- const dayEntry = (state, day) => state.entries.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === day);
412
+ const monthRows = (state) => state.entries
413
+ .filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)
414
+ .reduce((sum, doc) => sum + rowsOf(doc), 0);
415
+ const dayEntry = (state, day) => state.entries.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
416
+ doc.scope_field === day &&
417
+ doc.page === 'all');
388
418
  let state = applyPlan([], [], (0, materialized_discount_close_day_helpers_1.buildTenantDiscountCloseDayPlan)({
389
419
  tenantId: TENANT,
390
420
  reports: compileDay(a).reports,
@@ -402,7 +432,7 @@ describe('materialized discounts — close-day plan', () => {
402
432
  reason: 'NEW_DAY',
403
433
  computedAt: AT,
404
434
  }));
405
- const monthBefore = rowsOf(monthEntry(state));
435
+ const monthBefore = monthRows(state);
406
436
  const aRows = rowsOf(dayEntry(state, a));
407
437
  const bRows = rowsOf(dayEntry(state, b));
408
438
  expect(aRows).toBeGreaterThan(0);
@@ -418,11 +448,12 @@ describe('materialized discounts — close-day plan', () => {
418
448
  reason: 'CORRECTION',
419
449
  computedAt: AT,
420
450
  });
421
- expect(plan.staleEntryDocuments.some((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)).toBe(false);
422
- expect(plan.entryWrites.some((write) => write.report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)).toBe(true);
451
+ // A's own period page is deleted; B's page is a different page and survives.
452
+ expect(plan.staleEntryDocuments.some((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH && doc.page === a)).toBe(true);
453
+ expect(plan.entryWrites.some((write) => write.report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)).toBe(false);
423
454
  const after = applyPlan(state.reports, state.entries, plan);
424
- // A's rows are gone from the month; B's rows survive untouched.
425
- expect(rowsOf(monthEntry(after))).toBe(bRows);
455
+ // A's page is gone from the month; B's page survives untouched.
456
+ expect(monthRows(after)).toBe(bRows);
426
457
  expect(dayEntry(after, a)).toBeUndefined();
427
458
  expect(rowsOf(dayEntry(after, b))).toBe(bRows);
428
459
  });
@@ -560,13 +591,7 @@ describe('materialized discounts — close-day plan', () => {
560
591
  fullMonth,
561
592
  });
562
593
  });
563
- it('AUDIT F3: a MISSING period entry document is rebuilt from the DAY documents', () => {
564
- // Round-4 review finding, third instance of one architectural cause. Discount period
565
- // entries ACCUMULATE each day in, so a period document that was never persisted (a
566
- // partial failure between the counter writes and the entry writes) used to be rebuilt
567
- // from the CLOSING DAY alone - dropping every sibling day from the period drill-down
568
- // even though their documents were right there. The counters already repaired this
569
- // case explicitly; the entries did not.
594
+ it('AUDIT F3: period pages are independent; a missing page is not rebuilt', () => {
570
595
  const allDays = [...new Set((0, fixtures_1.loadOrdersDataset)('basha').map((o) => o.localDate))]
571
596
  .filter((d) => typeof d === 'string')
572
597
  .sort();
@@ -584,43 +609,113 @@ describe('materialized discounts — close-day plan', () => {
584
609
  entries: compiled.entries,
585
610
  localDate: day,
586
611
  ...closeInputs(day, state),
587
- existingEntriesComplete: true,
588
612
  reason: 'NEW_DAY',
589
613
  computedAt: AT,
590
614
  });
591
615
  return applyPlan(state.reports, state.entries, plan);
592
616
  };
593
- const monthRows = (state) => rowsOf(state.entries.find((doc) => doc.scope_context === 'localMonth'));
617
+ const monthPages = (state) => state.entries.filter((doc) => doc.scope_context === 'localMonth');
594
618
  let state = close({ reports: [], entries: [] }, a);
595
619
  state = close(state, b);
596
- expect(monthRows(state)).toBeGreaterThan(0);
597
- // The period ENTRY document is lost; the day documents survive.
620
+ expect(monthPages(state)
621
+ .map((doc) => doc.page)
622
+ .sort()).toEqual([a, b].sort());
623
+ // Losing ONE page must not make the next close rebuild it from siblings.
598
624
  state = {
599
625
  ...state,
600
- entries: state.entries.filter((doc) => doc.scope_context !== 'localMonth'),
626
+ entries: state.entries.filter((doc) => !(doc.scope_context === 'localMonth' && doc.page === a)),
601
627
  };
602
- expect(monthRows(state)).toBe(0);
603
- // Without an explicit acknowledgement that the period day set was fetched,
604
- // the plan must refuse to guess.
605
- {
606
- const compiled = compileDay(c);
607
- const unsafePlan = (0, materialized_discount_close_day_helpers_1.buildTenantDiscountCloseDayPlan)({
608
- tenantId: TENANT,
609
- reports: compiled.reports,
610
- entries: compiled.entries,
611
- localDate: c,
612
- ...closeInputs(c, state),
613
- reason: 'NEW_DAY',
614
- computedAt: AT,
615
- });
616
- expect(unsafePlan).toBeNull();
617
- }
618
628
  state = close(state, c);
619
- const dayRows = daysWithRows.reduce((sum, day) => {
620
- const doc = state.entries.find((entry) => entry.scope_context === 'localDate' && entry.scope_field === day);
621
- return sum + rowsOf(doc);
622
- }, 0);
623
- // The rebuilt period must carry EVERY day still on hand, not just the closing one.
624
- expect({ month: monthRows(state), dayRows }).toEqual({ month: dayRows, dayRows });
629
+ expect(monthPages(state)
630
+ .map((doc) => doc.page)
631
+ .sort()).toEqual([b, c].sort());
632
+ });
633
+ });
634
+ /**
635
+ * DAY-INPUT SIGNATURE + PERIOD REPAIR for the discount COUNTER documents.
636
+ *
637
+ * The counter guard is watermark-based for UPDATEs, which cannot see an order
638
+ * being DELETED: the removed order may have carried the day's maximum
639
+ * `updatedAt`, so the incoming watermark regresses and the correction would be
640
+ * skipped. The compiled documents now carry the input-set digest and the guard
641
+ * checks it first.
642
+ */
643
+ describe('materialized discounts — signature change detection + period repair', () => {
644
+ const signatureDoc = (overrides = {}) => ({
645
+ _id: 'sig-doc',
646
+ tenant_id: TENANT,
647
+ brand_id: BRAND,
648
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
649
+ scope_field: '2026-09-13',
650
+ day_index: 'SUN',
651
+ sale_type_key_filters: [
652
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS,
653
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM,
654
+ ],
655
+ discount_counters: null,
656
+ discount_counter_rows: null,
657
+ top_sources: null,
658
+ schema_version: 1,
659
+ iteration: 1,
660
+ source_watermark: new Date('2026-09-13T20:00:00.000Z'),
661
+ source_input_signature: 'v1:2:aaaaaaaaaaaaaaaa',
662
+ computed_at: new Date('2026-09-13T21:00:00.000Z'),
663
+ createdAt: new Date('2026-09-13T21:00:00.000Z'),
664
+ updatedAt: new Date('2026-09-13T21:00:00.000Z'),
665
+ ...overrides,
666
+ });
667
+ it('asks for a write when the input-set digest changed, even on a lower watermark', () => {
668
+ const stored = signatureDoc();
669
+ const deletedMaxOrder = signatureDoc({
670
+ source_watermark: new Date('2026-09-13T10:00:00.000Z'), // regressed
671
+ source_input_signature: 'v1:1:bbbbbbbbbbbbbbbb',
672
+ });
673
+ expect((0, materialized_discount_close_day_helpers_1.needsMaterializedDiscountReportWrite)(stored, deletedMaxOrder)).toBe(true);
674
+ // Same digest + older watermark + same schema → no write (no churn).
675
+ const unchangedOlder = signatureDoc({
676
+ source_watermark: new Date('2026-09-13T10:00:00.000Z'),
677
+ });
678
+ expect((0, materialized_discount_close_day_helpers_1.needsMaterializedDiscountReportWrite)(stored, unchangedOlder)).toBe(false);
679
+ });
680
+ it('rebuilds a MISSING period counter document from the sibling day counters', () => {
681
+ const counter = (count) => ({ COMPLETED_POS_TABLE: { count } });
682
+ const compiledDay = signatureDoc({
683
+ _id: 'compiled-day',
684
+ scope_field: '2026-09-21',
685
+ source_input_signature: 'v1:1:cccccccccccccccc',
686
+ discount_counters: counter(1),
687
+ });
688
+ const month = (field, docId) => signatureDoc({
689
+ _id: docId,
690
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
691
+ scope_field: '2026-09',
692
+ discount_counters: counter(1),
693
+ });
694
+ // Only the day's own date document exists as a sibling (D1 is in the same
695
+ // month but a different week); the month document was lost.
696
+ const siblingDay = signatureDoc({
697
+ _id: 'sibling-day',
698
+ scope_field: '2026-09-07',
699
+ discount_counters: counter(2),
700
+ });
701
+ const plan = (0, materialized_discount_close_day_helpers_1.buildTenantDiscountCloseDayPlan)({
702
+ tenantId: TENANT,
703
+ localDate: '2026-09-21',
704
+ reports: [compiledDay, month('month-compiled', 'compiled-month')],
705
+ entries: [],
706
+ existing: [],
707
+ existingEntries: [],
708
+ existingPeriodDayDocuments: [siblingDay],
709
+ reason: 'TEST_RECLOSE',
710
+ computedAt: new Date('2026-09-22T00:00:00.000Z'),
711
+ });
712
+ expect(plan).not.toBeNull();
713
+ expect(plan.foldedPeriodDayDocuments).toBeGreaterThanOrEqual(1);
714
+ const monthWrite = plan.writes.find((write) => write.report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
715
+ expect(monthWrite).toBeDefined();
716
+ const counters = monthWrite.report.discount_counters;
717
+ // 2 (sibling D1) + 1 (closing day) — the lost period is repaired, not reseeded.
718
+ expect(counters.COMPLETED_POS_TABLE.count).toBe(3);
719
+ expect(monthWrite.report.iteration).toBe(1);
625
720
  });
626
721
  });
@@ -45,6 +45,7 @@ const entriesDoc = (over = {}) => ({
45
45
  brand_id: 'brand-a',
46
46
  scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
47
47
  scope_field: '2026-09',
48
+ page: '2026-09-13',
48
49
  day_index: null,
49
50
  sale_type_key_filters: ['ORDER_STATUS', 'PLATFORM'],
50
51
  discount_entries: { [KEY]: section(row()) },
@@ -90,36 +91,36 @@ describe('mergeMaterializedDiscountEntrySections', () => {
90
91
  expect(merged).toEqual({});
91
92
  });
92
93
  });
93
- describe('updateMaterializedDiscountEntries — period vs day semantics', () => {
94
- it('REPLACES for a DAY scope (the day is the whole truth)', () => {
94
+ describe('updateMaterializedDiscountEntries — full page replacement', () => {
95
+ it('REPLACES a DAY page (the day is the whole truth)', () => {
95
96
  const existing = entriesDoc({
96
97
  scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
97
98
  scope_field: '2026-09-13',
99
+ page: 'all',
98
100
  });
99
101
  const compiled = entriesDoc({
100
102
  scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
101
103
  scope_field: '2026-09-13',
104
+ page: 'all',
102
105
  discount_entries: { [KEY]: section(row({ order_id: 'fresh' })) },
103
106
  });
104
- const updated = (0, materialized_discount_close_day_helpers_1.updateMaterializedDiscountEntries)(existing, compiled, {
105
- mergePeriodRows: false,
106
- });
107
+ const updated = (0, materialized_discount_close_day_helpers_1.updateMaterializedDiscountEntries)(existing, compiled);
108
+ expect(updated.page).toBe('all');
107
109
  expect(updated.discount_entries[KEY].rows.map((r) => r.order_id)).toEqual(['fresh']);
108
110
  });
109
- it('MERGES for a PERIOD scope (the month keeps every day)', () => {
111
+ it('REPLACES one PERIOD page without merging another day into it', () => {
110
112
  const existing = entriesDoc();
111
113
  const compiled = entriesDoc({
112
114
  discount_entries: { [KEY]: section(row({ order_id: 'day2' })) },
113
115
  });
114
- const updated = (0, materialized_discount_close_day_helpers_1.updateMaterializedDiscountEntries)(existing, compiled, {
115
- mergePeriodRows: true,
116
- });
117
- expect(updated.discount_entries[KEY].rows.map((r) => r.order_id).sort()).toEqual(['day2', 'order-1']);
116
+ const updated = (0, materialized_discount_close_day_helpers_1.updateMaterializedDiscountEntries)(existing, compiled);
117
+ expect(updated.page).toBe('2026-09-13');
118
+ expect(updated.discount_entries[KEY].rows.map((r) => r.order_id)).toEqual(['day2']);
118
119
  expect(updated.iteration).toBe(2);
119
120
  });
120
- it('still REFUSES documents that disagree on scope (data issue)', () => {
121
+ it('REFUSES documents that disagree on scope or page', () => {
121
122
  const existing = entriesDoc();
122
- const compiled = entriesDoc({ scope_field: '2026-10' });
123
- expect((0, materialized_discount_close_day_helpers_1.updateMaterializedDiscountEntries)(existing, compiled, { mergePeriodRows: true })).toBeNull();
123
+ expect((0, materialized_discount_close_day_helpers_1.updateMaterializedDiscountEntries)(existing, entriesDoc({ scope_field: '2026-10' }))).toBeNull();
124
+ expect((0, materialized_discount_close_day_helpers_1.updateMaterializedDiscountEntries)(existing, entriesDoc({ page: '2026-09-14' }))).toBeNull();
124
125
  });
125
126
  });
@@ -619,3 +619,79 @@ describe('synthetic multi-source and comp combinations', () => {
619
619
  expect(new Set(orderRows.map((row) => row.discount_id))).toEqual(new Set(['MANUAL_Rs 5', 'loyalty-offer-1']));
620
620
  });
621
621
  });
622
+ describe('incremental source deltas', () => {
623
+ const NOW = new Date('2026-09-15T23:00:00.000Z');
624
+ const row = (over) => ({
625
+ order_id: 'order-1',
626
+ entry_key: 'entry-1',
627
+ created_at: new Date('2026-09-15T20:00:00.000Z'),
628
+ kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT,
629
+ slot: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SLOT_ENUM.SPECIAL,
630
+ level: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER,
631
+ sub_kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.MANUAL,
632
+ is_percentage: true,
633
+ rate: 1000,
634
+ amount: 100,
635
+ item_value: 1000,
636
+ name: 'Manual discount',
637
+ discount_id: 'MANUAL_Rs 10',
638
+ reference_number: null,
639
+ ...over,
640
+ });
641
+ const sourceForSections = (sections) => {
642
+ const docs = (0, materialized_discount_source_helpers_1.buildDiscountSourcesForScope)({
643
+ tenantId: 'tenant-source-delta',
644
+ brandId: 'brand-source-delta',
645
+ scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
646
+ scopeField: '2026-09-15',
647
+ sections,
648
+ computedAt: NOW,
649
+ sourceWatermark: NOW,
650
+ });
651
+ return docs.find((doc) => doc.source_key === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SOURCE_KEY.MANUAL_ORDER);
652
+ };
653
+ const sourceFor = (entry) => sourceForSections({ 'COMPLETED:POS_WALK-IN': { rows: [entry] } });
654
+ it('subtracts the stored day, adds the fresh day, and recomputes rate_kind', () => {
655
+ const oldPercentage = sourceFor(row({ entry_key: 'old', is_percentage: true, rate: 1000, amount: 100 }));
656
+ const freshFixed = sourceFor(row({ entry_key: 'new', is_percentage: false, rate: 200, amount: 200 }));
657
+ expect(oldPercentage.rate_kind).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.PERCENTAGE);
658
+ expect((0, materialized_discount_source_helpers_1.applyDiscountSourceDelta)(oldPercentage, oldPercentage, -1, NOW)).toBeNull();
659
+ const replaced = (0, materialized_discount_source_helpers_1.applyDiscountSourceDelta)(null, freshFixed, 1, NOW);
660
+ expect(replaced?.rate_kind).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.FIXED);
661
+ expect(replaced?.discount_amount).toBe(200);
662
+ expect(replaced?.percentage_row_count).toBe(0);
663
+ });
664
+ it('subtracts one key contribution while a second key metric survives', () => {
665
+ const old = sourceForSections({
666
+ 'COMPLETED:POS_WALK-IN': {
667
+ rows: [row({ order_id: 'order-a', entry_key: 'a', amount: 100 })],
668
+ },
669
+ 'COMPLETED:APP_DINE-IN': {
670
+ rows: [row({ order_id: 'order-b', entry_key: 'b', amount: 200, is_percentage: false, rate: 200 })],
671
+ },
672
+ });
673
+ const removed = sourceForSections({
674
+ 'COMPLETED:POS_WALK-IN': {
675
+ rows: [row({ order_id: 'order-a', entry_key: 'a', amount: 100 })],
676
+ },
677
+ });
678
+ const remaining = (0, materialized_discount_source_helpers_1.applyDiscountSourceDelta)(old, removed, -1, NOW);
679
+ expect(remaining?.discount_amount).toBe(200);
680
+ expect(remaining?.row_count).toBe(1);
681
+ expect(remaining?.key_metrics.map((metric) => metric.key)).toEqual(['COMPLETED:APP_DINE-IN']);
682
+ const fresh = sourceForSections({
683
+ 'COMPLETED:POS_WALK-IN': {
684
+ rows: [row({ order_id: 'order-c', entry_key: 'c', amount: 50 })],
685
+ },
686
+ });
687
+ const merged = (0, materialized_discount_source_helpers_1.applyDiscountSourceDelta)(remaining, fresh, 1, NOW);
688
+ expect(merged?.discount_amount).toBe(250);
689
+ expect(merged?.key_metrics).toHaveLength(2);
690
+ });
691
+ it('is idempotent for a new day (add) and removes a source that reaches zero', () => {
692
+ const fresh = sourceFor(row({ entry_key: 'new', amount: 200, is_percentage: false, rate: 200 }));
693
+ const added = (0, materialized_discount_source_helpers_1.applyDiscountSourceDelta)(null, fresh, 1, NOW);
694
+ expect(added.discount_amount).toBe(200);
695
+ expect((0, materialized_discount_source_helpers_1.applyDiscountSourceDelta)(added, fresh, -1, NOW)).toBeNull();
696
+ });
697
+ });
@@ -49,6 +49,17 @@ describe('findNonIntegerNumericLeaves', () => {
49
49
  expect(violations).toHaveLength(3);
50
50
  expect(violations.every((violation) => violation.reason === 'non-finite')).toBe(true);
51
51
  });
52
+ it('rejects numeric BSON values, while still ignoring ObjectId identity', () => {
53
+ const violations = (0, materialized_integer_contract_1.findNonIntegerNumericLeaves)({
54
+ decimal: { _bsontype: 'Decimal128' },
55
+ long: { _bsontype: 'Long' },
56
+ double: { _bsontype: 'Double' },
57
+ id: { _bsontype: 'ObjectId' },
58
+ reference_number: '12345', // human code, not money
59
+ });
60
+ expect(violations.map((violation) => violation.path)).toEqual(['decimal', 'long', 'double']);
61
+ expect(violations.every((violation) => violation.reason === 'bson-numeric')).toBe(true);
62
+ });
52
63
  it('rejects a decimal smuggled in as a string, but not an identifier', () => {
53
64
  const violations = (0, materialized_integer_contract_1.findNonIntegerNumericLeaves)({
54
65
  amount: '131.25',
@@ -141,14 +141,14 @@ describe('buildMaterializedReportScopeGroupsFromSelection', () => {
141
141
  },
142
142
  ]);
143
143
  });
144
- test('an incomplete dedicated window falls back to the plain range read', () => {
144
+ test('an invalid dedicated window is rejected, never served as the full period', () => {
145
145
  expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection({
146
146
  view: REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DATE_RANGE_TIME_WINDOW,
147
147
  rangeStart: '2026-09-01',
148
148
  rangeEnd: '2026-09-30',
149
149
  timeStart: '04:00',
150
150
  timeEnd: '08:00', // crosses the 06:00 business-morning boundary → unservable
151
- }))).toEqual([{ scope_context: 'localMonth', scope_field: ['2026-09'] }]);
151
+ }))).toBeNull();
152
152
  });
153
153
  test('an empty selection cannot be served', () => {
154
154
  expect((0, materialized_reports_selection_helpers_1.buildMaterializedReportScopeGroupsFromSelection)(selection())).toBeNull();