@managesome/eposmatic-toolkit 0.4.29 → 0.4.31

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 (66) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +9 -12
  2. package/esm/helpers/materialized-reports/index.js +1 -0
  3. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +129 -20
  4. package/esm/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  5. package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +251 -240
  6. package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +2 -1
  7. package/esm/helpers/materialized-reports/materialized-discount-source-helpers.js +176 -0
  8. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +83 -0
  9. package/esm/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  10. package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  11. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  12. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +284 -43
  13. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -4
  14. package/esm/schemas/models/materialized_report_drilldown_rows.js +39 -12
  15. package/esm/schemas/models/materialized_tenant_discount_entries.js +18 -12
  16. package/esm/schemas/models/materialized_tenant_discount_sources.js +1 -1
  17. package/esm/schemas/models/orders.js +5 -0
  18. package/esm/schemas/models/tenant_active_jobs.js +7 -0
  19. package/esm/schemas/models/tenant_calendar.js +12 -0
  20. package/lib/constants/MATERIALIZED_REPORTS.d.ts +9 -12
  21. package/lib/constants/MATERIALIZED_REPORTS.js +11 -14
  22. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  23. package/lib/helpers/materialized-reports/index.js +1 -0
  24. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +38 -0
  25. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +129 -19
  26. package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  27. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +23 -61
  28. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +250 -239
  29. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.d.ts +4 -4
  30. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +1 -0
  31. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.d.ts +17 -0
  32. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +178 -0
  33. package/lib/helpers/materialized-reports/materialized-index-bootstrap.d.ts +7 -0
  34. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +87 -0
  35. package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +3 -1
  36. package/lib/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  37. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.d.ts +2 -2
  38. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  39. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  40. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +8 -0
  41. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +283 -42
  42. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -4
  43. package/lib/schemas/models/materialized_report_drilldown_rows.d.ts +40 -6
  44. package/lib/schemas/models/materialized_report_drilldown_rows.js +39 -12
  45. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +33 -29
  46. package/lib/schemas/models/materialized_tenant_discount_entries.js +18 -12
  47. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +6 -6
  48. package/lib/schemas/models/materialized_tenant_discount_sources.js +1 -1
  49. package/lib/schemas/models/orders.d.ts +5 -0
  50. package/lib/schemas/models/orders.js +5 -0
  51. package/lib/schemas/models/tenant_active_jobs.d.ts +7 -0
  52. package/lib/schemas/models/tenant_active_jobs.js +8 -1
  53. package/lib/schemas/models/tenant_calendar.d.ts +13 -0
  54. package/lib/schemas/models/tenant_calendar.js +13 -1
  55. package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +8 -0
  56. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +9 -5
  57. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +56 -1
  58. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +17 -0
  59. package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +60 -54
  60. package/lib/tests/materialized-reports/materialized-discount-entries-accumulation.test.js +14 -13
  61. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +76 -0
  62. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +11 -0
  63. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +2 -2
  64. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +152 -7
  65. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +89 -0
  66. 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,44 +609,26 @@ 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());
625
632
  });
626
633
  });
627
634
  /**
@@ -698,7 +705,6 @@ describe('materialized discounts — signature change detection + period repair'
698
705
  entries: [],
699
706
  existing: [],
700
707
  existingEntries: [],
701
- existingEntriesComplete: true,
702
708
  existingPeriodDayDocuments: [siblingDay],
703
709
  reason: 'TEST_RECLOSE',
704
710
  computedAt: new Date('2026-09-22T00:00:00.000Z'),
@@ -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();
@@ -70,6 +70,9 @@ const closeDay = (localDate, orders, world, computedAt, force = false) => expect
70
70
  reason: 'TEST_CLOSE',
71
71
  existing: world.docs,
72
72
  existingCreditBills: world.credit,
73
+ existingPeriodDayDocuments: world.docs.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE),
74
+ existingPeriodMonthDocuments: world.docs.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH),
75
+ existingPeriodDayCreditDocuments: world.credit.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE),
73
76
  force,
74
77
  computedAt,
75
78
  }));
@@ -310,13 +313,102 @@ describe('tenant sales overview close-day plan', () => {
310
313
  expect(forced.writes).toHaveLength(8);
311
314
  expect(forced.skippedDocuments).toHaveLength(0);
312
315
  });
313
- it('treats order-less days as a stable date marker (epoch watermark, no re-close churn)', () => {
316
+ it('writes an order-less date marker AND its zero period markers, with no re-close churn', () => {
314
317
  const emptyPlan = closeDay(D2, [], EMPTY_WORLD, CT1);
315
- expect(emptyPlan.writes.map((write) => write.report.scope_context)).toEqual([LOCAL_DATE]);
318
+ expect(emptyPlan.writes.map((write) => write.report.scope_context)).toEqual([
319
+ LOCAL_DATE,
320
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
321
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
322
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
323
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
324
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
325
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
326
+ ]);
316
327
  expect(emptyPlan.writes[0].report.source_watermark).toEqual(new Date(0));
317
328
  const emptyReClose = closeDay(D2, [], persistPlan(EMPTY_WORLD, emptyPlan), CT2);
318
329
  expect(emptyReClose.writes).toHaveLength(0);
319
- expect(emptyReClose.skippedDocuments).toHaveLength(1);
330
+ expect(emptyReClose.skippedDocuments).toHaveLength(7);
331
+ });
332
+ it('keeps a Sunday week that crosses a month boundary exact (Sep 30 + Oct 1)', () => {
333
+ const sep = makeOrder({
334
+ orderId: 'cross-sep',
335
+ localDate: '2026-09-30',
336
+ localHour: 12,
337
+ amount: 1000,
338
+ updatedAt: '2026-09-30T12:00:00.000Z',
339
+ });
340
+ const oct = makeOrder({
341
+ orderId: 'cross-oct',
342
+ localDate: '2026-10-01',
343
+ localHour: 12,
344
+ amount: 500,
345
+ updatedAt: '2026-10-01T12:00:00.000Z',
346
+ });
347
+ const first = closeDay('2026-09-30', [sep], EMPTY_WORLD, CT1);
348
+ const world = persistPlan(EMPTY_WORLD, first);
349
+ const second = closeDay('2026-10-01', [oct], world, CT2);
350
+ const week = expectNonNull(findWrite(second, LOCAL_WEEK, '2026-09-27'));
351
+ const metrics = getKeyMetrics(week.report);
352
+ expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(2);
353
+ expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(1500);
354
+ // September is NOT contaminated by the October day; October is its own month.
355
+ expect(findWrite(second, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, '2026-10')).toBeDefined();
356
+ });
357
+ it('fails loudly when a missing quarter has no month sibling (H2)', () => {
358
+ const compile = compileDay(D2, [cashD2], CT2);
359
+ const dateDoc = expectNonNull(compile.materializedReports.find((doc) => doc.scope_context === LOCAL_DATE));
360
+ expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
361
+ tenantId: TENANT,
362
+ compile,
363
+ reason: 'TEST_REPAIR',
364
+ existing: [dateDoc],
365
+ existingPeriodMonthDocuments: [],
366
+ computedAt: CT2,
367
+ })).toBeNull();
368
+ });
369
+ it('repairs a missing YEAR from all localMonth docs (H2)', () => {
370
+ const planA = closeDay(D1, [creditIssue], EMPTY_WORLD, CT1);
371
+ const worldA = persistPlan(EMPTY_WORLD, planA);
372
+ const withoutYear = {
373
+ ...worldA,
374
+ docs: worldA.docs.filter((doc) => doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR),
375
+ };
376
+ const plan = expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
377
+ tenantId: TENANT,
378
+ compile: compileDay(D2, [cashD2], CT2),
379
+ reason: 'TEST_REPAIR',
380
+ existing: withoutYear.docs,
381
+ existingCreditBills: withoutYear.credit,
382
+ existingPeriodDayDocuments: withoutYear.docs.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE),
383
+ existingPeriodMonthDocuments: withoutYear.docs.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH),
384
+ computedAt: CT2,
385
+ }));
386
+ const year = expectNonNull(plan.writes.find((write) => write.report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR));
387
+ const metrics = getKeyMetrics(year.report);
388
+ expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(2);
389
+ expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(2000);
390
+ });
391
+ it('repairs a missing QUARTER from localMonth docs, never from weeks/raw days', () => {
392
+ const planA = closeDay(D1, [creditIssue], EMPTY_WORLD, CT1);
393
+ const worldA = persistPlan(EMPTY_WORLD, planA);
394
+ const withoutQuarter = {
395
+ ...worldA,
396
+ docs: worldA.docs.filter((doc) => doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER),
397
+ };
398
+ const plan = expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
399
+ tenantId: TENANT,
400
+ compile: compileDay(D2, [cashD2], CT2),
401
+ reason: 'TEST_REPAIR',
402
+ existing: withoutQuarter.docs,
403
+ existingCreditBills: withoutQuarter.credit,
404
+ existingPeriodDayDocuments: withoutQuarter.docs.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE),
405
+ existingPeriodMonthDocuments: withoutQuarter.docs.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH),
406
+ computedAt: CT2,
407
+ }));
408
+ const quarter = expectNonNull(plan.writes.find((write) => write.report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER));
409
+ const metrics = getKeyMetrics(quarter.report);
410
+ expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(2);
411
+ expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(1200 + 800);
320
412
  });
321
413
  it('returns null for inconsistent input (never throws)', () => {
322
414
  expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)(null)).toBeNull();
@@ -346,12 +438,15 @@ describe('tenant sales overview close-day plan', () => {
346
438
  reason: 'TEST_CLOSE',
347
439
  existing: [dateDoc, duplicateRow],
348
440
  })).toBeNull();
349
- // Repeating the SAME document (overlapping fetch refs) is fine.
441
+ // Repeating the SAME document (overlapping fetch refs) is fine. The month
442
+ // sibling is required for the upper-period repair (H2).
443
+ const monthDoc = compile.materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
350
444
  expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
351
445
  tenantId: TENANT,
352
446
  compile,
353
447
  reason: 'TEST_CLOSE',
354
448
  existing: [dateDoc, dateDoc],
449
+ existingPeriodMonthDocuments: monthDoc == null ? [] : [monthDoc],
355
450
  })).not.toBeNull();
356
451
  });
357
452
  it('normalizes hydrated (mongoose-cast) stored docs when planning patches', () => {
@@ -621,6 +716,9 @@ describe('N2 backfill from CURRENT order state (settled-after-issue rule)', () =
621
716
  reason: 'TEST_CLOSE',
622
717
  existing: worldIssue.docs,
623
718
  existingCreditBills: worldIssue.credit,
719
+ existingPeriodDayDocuments: worldIssue.docs.filter((doc) => doc.scope_context === LOCAL_DATE),
720
+ existingPeriodMonthDocuments: worldIssue.docs.filter((doc) => doc.scope_context === LOCAL_MONTH),
721
+ existingPeriodDayCreditDocuments: worldIssue.credit.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE),
624
722
  computedAt: ct(C1),
625
723
  }));
626
724
  const c1Write = expectNonNull(findWrite(collectionPlan, LOCAL_DATE, C1));
@@ -768,6 +866,8 @@ describe('period document repair from sibling days', () => {
768
866
  existing: withoutMonth.docs,
769
867
  existingCreditBills: withoutMonth.credit,
770
868
  existingPeriodDayDocuments: siblingDays,
869
+ existingPeriodMonthDocuments: world.docs.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH),
870
+ existingPeriodDayCreditDocuments: withoutMonth.credit.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE),
771
871
  computedAt: CT_B,
772
872
  }));
773
873
  expect(plan.createdPeriodDocuments).toContainEqual({
@@ -780,6 +880,48 @@ describe('period document repair from sibling days', () => {
780
880
  expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(2);
781
881
  expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(1300);
782
882
  });
883
+ it('fails loudly for an EMPTY day whose lost date has no sibling evidence (H3)', () => {
884
+ const plan = closeDay(D1, [D1_ORDER], EMPTY_WORLD, CT_A);
885
+ const world = persistPlan(EMPTY_WORLD, plan);
886
+ const withoutDayEvidence = {
887
+ ...world,
888
+ docs: world.docs.filter((doc) => doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
889
+ doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR),
890
+ credit: world.credit.filter((doc) => doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
891
+ doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR),
892
+ };
893
+ expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
894
+ tenantId: TENANT,
895
+ compile: compileDay(D1, [], CT_B),
896
+ reason: 'TEST_REPAIR',
897
+ existing: withoutDayEvidence.docs,
898
+ existingCreditBills: withoutDayEvidence.credit,
899
+ existingPeriodDayDocuments: [],
900
+ existingPeriodMonthDocuments: [],
901
+ computedAt: CT_B,
902
+ })).toBeNull();
903
+ });
904
+ it('fails loudly when a period exists but the lost day has no sibling evidence (H3)', () => {
905
+ const plan = closeDay(D1, [D1_ORDER], EMPTY_WORLD, CT_A);
906
+ const world = persistPlan(EMPTY_WORLD, plan);
907
+ const withoutDayEvidence = {
908
+ ...world,
909
+ docs: world.docs.filter((doc) => doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
910
+ doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR),
911
+ credit: world.credit.filter((doc) => doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
912
+ doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR),
913
+ };
914
+ expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
915
+ tenantId: TENANT,
916
+ compile: compileDay(D1, [D1_ORDER], CT_B),
917
+ reason: 'TEST_REPAIR',
918
+ existing: withoutDayEvidence.docs,
919
+ existingCreditBills: withoutDayEvidence.credit,
920
+ existingPeriodDayDocuments: [],
921
+ existingPeriodMonthDocuments: [],
922
+ computedAt: CT_B,
923
+ })).toBeNull();
924
+ });
783
925
  it('does NOT fold a sibling from another schema/key grammar (it cannot be summed)', () => {
784
926
  const dayOnePlan = closeDay(D1, [D1_ORDER], EMPTY_WORLD, CT_A);
785
927
  const world = persistPlan(EMPTY_WORLD, dayOnePlan);
@@ -792,11 +934,14 @@ describe('period document repair from sibling days', () => {
792
934
  reason: 'TEST_RECLOSE',
793
935
  existing: world.docs.filter((doc) => doc.scope_context !== LOCAL_MONTH),
794
936
  existingCreditBills: world.credit,
795
- existingPeriodDayDocuments: foreign,
937
+ existingPeriodDayDocuments: [...world.docs.filter((doc) => doc.scope_context === LOCAL_DATE), ...foreign],
938
+ existingPeriodMonthDocuments: world.docs.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH),
939
+ existingPeriodDayCreditDocuments: world.credit.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE),
796
940
  computedAt: CT_B,
797
941
  }));
798
- expect(plan.foldedPeriodDayDocuments).toBe(0);
942
+ // The foreign day is ignored; the valid day one still folds.
943
+ expect(plan.foldedPeriodDayDocuments).toBe(1);
799
944
  const monthWrite = expectNonNull(findWrite(plan, LOCAL_MONTH, '2026-09'));
800
- expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(1);
945
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(2);
801
946
  });
802
947
  });