@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
@@ -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));
@@ -638,3 +736,212 @@ describe('N2 backfill from CURRENT order state (settled-after-issue rule)', () =
638
736
  expect(patchedIssued?.settled_amount).toBe(1000);
639
737
  });
640
738
  });
739
+ /**
740
+ * DAY-INPUT SIGNATURE — the regression that motivated it.
741
+ *
742
+ * `source_watermark` is the MAX `orders.updatedAt` of the day's input. Delete
743
+ * an order and that maximum can REGRESS, so a watermark-only guard reports
744
+ * "nothing new" and leaves the deleted order's numbers in every report. The
745
+ * digest of the input SET catches it. These tests use the real compile + real
746
+ * plan, with no force flag anywhere.
747
+ */
748
+ describe('day-input signature change detection', () => {
749
+ const CT_A = new Date('2026-09-29T23:00:00.000Z');
750
+ const CT_B = new Date('2026-09-30T01:00:00.000Z');
751
+ const survivor = makeOrder({
752
+ orderId: 'order-survivor',
753
+ localDate: D1,
754
+ localHour: 10,
755
+ amount: 500,
756
+ updatedAt: '2026-09-29T10:00:00.000Z',
757
+ });
758
+ const victim = makeOrder({
759
+ orderId: 'order-victim',
760
+ localDate: D1,
761
+ localHour: 11,
762
+ amount: 700,
763
+ updatedAt: '2026-09-29T11:00:00.000Z',
764
+ });
765
+ it('stamps a deterministic digest on the compiled day / hour / period documents', () => {
766
+ const compile = compileDay(D1, [survivor, victim], CT_A);
767
+ const signatures = new Set(compile.materializedReports.map((doc) => doc.source_input_signature));
768
+ expect(signatures.size).toBe(1);
769
+ const signature = [...signatures][0];
770
+ expect(signature).toMatch(/^v1:2:[0-9a-f]{16}$/);
771
+ // Order-independent and stable.
772
+ const recompiled = compileDay(D1, [victim, survivor], CT_A);
773
+ expect(recompiled.materializedReports[0].source_input_signature).toBe(signature);
774
+ });
775
+ it('CORRECTS the day when the deleted order carried the maximum updatedAt', () => {
776
+ const firstPlan = closeDay(D1, [survivor, victim], EMPTY_WORLD, CT_A);
777
+ const world = persistPlan(EMPTY_WORLD, firstPlan);
778
+ const storedDate = expectNonNull(world.docs.find((doc) => doc.scope_context === LOCAL_DATE && doc.scope_field === D1));
779
+ const storedWatermark = new Date(storedDate.source_watermark).getTime();
780
+ expect(storedWatermark).toBe(new Date('2026-09-29T11:00:00.000Z').getTime());
781
+ // Re-close with the victim GONE: the incoming max updatedAt (10:00) is
782
+ // LOWER than the stored watermark — the pre-signature guard skipped here.
783
+ const secondCompile = compileDay(D1, [survivor], CT_B);
784
+ const incomingDate = expectNonNull(secondCompile.materializedReports.find((doc) => doc.scope_context === LOCAL_DATE && doc.scope_field === D1));
785
+ expect(new Date(incomingDate.source_watermark).getTime()).toBeLessThan(storedWatermark);
786
+ const plan = expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
787
+ tenantId: TENANT,
788
+ compile: secondCompile,
789
+ reason: 'TEST_RECLOSE',
790
+ existing: world.docs,
791
+ existingCreditBills: world.credit,
792
+ computedAt: CT_B,
793
+ }));
794
+ const dateWrite = expectNonNull(findWrite(plan, LOCAL_DATE, D1));
795
+ expect(getKeyMetrics(dateWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(1);
796
+ expect(getKeyMetrics(dateWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(500);
797
+ // The removed hour is DELETED, not left behind.
798
+ expect(plan.staleHourDocuments.map((doc) => doc.scope_field)).toEqual([`${D1} 11`]);
799
+ // The period documents are corrected by subtract(stored day) + add(compiled day).
800
+ const monthWrite = expectNonNull(findWrite(plan, LOCAL_MONTH, '2026-09'));
801
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(1);
802
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(500);
803
+ const after = persistPlan(world, plan);
804
+ expect(after.docs.some((doc) => doc.scope_context === LOCAL_HOUR && doc.scope_field === `${D1} 11`)).toBe(false);
805
+ });
806
+ it('still skips an identical re-close (no churn): the digest is unchanged', () => {
807
+ const firstPlan = closeDay(D1, [survivor], EMPTY_WORLD, CT_A);
808
+ const world = persistPlan(EMPTY_WORLD, firstPlan);
809
+ const secondPlan = closeDay(D1, [survivor], world, CT_B);
810
+ expect(secondPlan.writes).toEqual([]);
811
+ expect(secondPlan.staleHourDocuments).toEqual([]);
812
+ expect(secondPlan.skippedDocuments.length).toBeGreaterThan(0);
813
+ });
814
+ it('treats a legacy document WITHOUT a signature as needing one corrective write', () => {
815
+ const firstPlan = closeDay(D1, [survivor], EMPTY_WORLD, CT_A);
816
+ const world = persistPlan(EMPTY_WORLD, firstPlan);
817
+ const legacy = world.docs.map((doc) => {
818
+ const { source_input_signature: _ignored, ...rest } = doc;
819
+ return rest;
820
+ });
821
+ const plan = closeDay(D1, [survivor], { ...world, docs: legacy }, CT_B);
822
+ expect(plan.writes.length).toBeGreaterThan(0);
823
+ expect(expectNonNull(findWrite(plan, LOCAL_DATE, D1)).report.source_input_signature).toMatch(/^v1:1:/);
824
+ });
825
+ });
826
+ /**
827
+ * PERIOD REPAIR — a missing period document must be rebuilt from the DAY
828
+ * documents that still exist, not seeded with the closing day alone.
829
+ *
830
+ * Contract: for additive metrics, `localMonth` == Σ `localDate` of the month.
831
+ * The closing day itself is replaced by the fresh compile; every other stored
832
+ * day of the period is folded in.
833
+ */
834
+ describe('period document repair from sibling days', () => {
835
+ const CT_A = new Date('2026-09-29T23:00:00.000Z');
836
+ const CT_B = new Date('2026-09-30T01:00:00.000Z');
837
+ const D1_ORDER = makeOrder({
838
+ orderId: 'day-one-order',
839
+ localDate: D1,
840
+ localHour: 10,
841
+ amount: 500,
842
+ updatedAt: '2026-09-29T10:00:00.000Z',
843
+ });
844
+ const D2_ORDER = makeOrder({
845
+ orderId: 'day-two-order',
846
+ localDate: D2,
847
+ localHour: 12,
848
+ amount: 800,
849
+ updatedAt: '2026-09-30T12:00:00.000Z',
850
+ });
851
+ it('rebuilds a MISSING localMonth from the stored localDate documents', () => {
852
+ const dayOnePlan = closeDay(D1, [D1_ORDER], EMPTY_WORLD, CT_A);
853
+ const world = persistPlan(EMPTY_WORLD, dayOnePlan);
854
+ const monthScope = world.docs.find((doc) => doc.scope_context === LOCAL_MONTH);
855
+ expect(monthScope).toBeDefined();
856
+ // Simulate the period document being lost while the day document survives.
857
+ const withoutMonth = {
858
+ docs: world.docs.filter((doc) => doc.scope_context !== LOCAL_MONTH),
859
+ credit: world.credit.filter((doc) => doc.scope_context !== LOCAL_MONTH),
860
+ };
861
+ const siblingDays = withoutMonth.docs.filter((doc) => doc.scope_context === LOCAL_DATE);
862
+ const plan = expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
863
+ tenantId: TENANT,
864
+ compile: compileDay(D2, [D2_ORDER], CT_B),
865
+ reason: 'TEST_RECLOSE',
866
+ existing: withoutMonth.docs,
867
+ existingCreditBills: withoutMonth.credit,
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),
871
+ computedAt: CT_B,
872
+ }));
873
+ expect(plan.createdPeriodDocuments).toContainEqual({
874
+ scope_context: LOCAL_MONTH,
875
+ scope_field: '2026-09',
876
+ });
877
+ expect(plan.foldedPeriodDayDocuments).toBeGreaterThanOrEqual(1);
878
+ const monthWrite = expectNonNull(findWrite(plan, LOCAL_MONTH, '2026-09'));
879
+ // D1's 500 + D2's 800 — the lost month is repaired, not reseeded with D2 only.
880
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(2);
881
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(1300);
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
+ });
925
+ it('does NOT fold a sibling from another schema/key grammar (it cannot be summed)', () => {
926
+ const dayOnePlan = closeDay(D1, [D1_ORDER], EMPTY_WORLD, CT_A);
927
+ const world = persistPlan(EMPTY_WORLD, dayOnePlan);
928
+ const foreign = world.docs
929
+ .filter((doc) => doc.scope_context === LOCAL_DATE)
930
+ .map((doc) => ({ ...doc, schema_version: 999 }));
931
+ const plan = expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
932
+ tenantId: TENANT,
933
+ compile: compileDay(D2, [D2_ORDER], CT_B),
934
+ reason: 'TEST_RECLOSE',
935
+ existing: world.docs.filter((doc) => doc.scope_context !== LOCAL_MONTH),
936
+ existingCreditBills: world.credit,
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),
940
+ computedAt: CT_B,
941
+ }));
942
+ // The foreign day is ignored; the valid day one still folds.
943
+ expect(plan.foldedPeriodDayDocuments).toBe(1);
944
+ const monthWrite = expectNonNull(findWrite(plan, LOCAL_MONTH, '2026-09'));
945
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(2);
946
+ });
947
+ });
@@ -69,6 +69,95 @@ const makePayLaterOrder = (args) => ({
69
69
  },
70
70
  ],
71
71
  });
72
+ describe('legacy Amount Collected inputs under the UNPAID invariant', () => {
73
+ const makeOrder = (over = {}) => ({
74
+ _id: 'amount-collected-order',
75
+ tenant_id: 'tenant-amount-collected',
76
+ brand_id: 'brand-amount-collected',
77
+ platform: 'POS_WALK-IN',
78
+ order_status: constants_1.ORDER_STATUS_ENUM.COMPLETED,
79
+ order_number: 1,
80
+ amount_earned: 1000,
81
+ amount_collected: 1000,
82
+ grand_total: 1000,
83
+ total_discount_applied: 0,
84
+ gst_amount: 0,
85
+ tax_amount: 0,
86
+ tip_amount: 0,
87
+ tax_invoice_provider_charges: 0,
88
+ is_deleted: false,
89
+ localDate: '2026-09-30',
90
+ createdAt: new Date('2026-09-30T12:00:00.000Z'),
91
+ updatedAt: new Date('2026-09-30T12:00:00.000Z'),
92
+ payments: [],
93
+ ...over,
94
+ });
95
+ const compile = (order) => {
96
+ const compiled = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)('2026-09-30', [order], {
97
+ tenantId: 'tenant-amount-collected',
98
+ brandId: 'brand-amount-collected',
99
+ gmtOffset: 0,
100
+ computedAt: new Date('2026-09-30T23:00:00.000Z'),
101
+ }));
102
+ const dateDoc = compiled.materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
103
+ return getKeyMetrics(expectNonNull(dateDoc), 'COMPLETED:POS_WALK-IN');
104
+ };
105
+ it('keeps amount_earned as the sales basis, excluding the card charge from grand_total', () => {
106
+ const metrics = compile(makeOrder({
107
+ grand_total: 1100,
108
+ amount_earned: 1000,
109
+ amount_collected: 1100,
110
+ payments: [
111
+ {
112
+ _id: 'card-1',
113
+ payment_id: 'card-1',
114
+ payment_type: constants_1.PAYMENT_TYPE_ENUM.CARD,
115
+ payment_status: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
116
+ amount_due: 1100,
117
+ amount_paid: 1100,
118
+ amount_refunded: 0,
119
+ card_details: { payment_provider: 'STRIPE', card_charges: 100 },
120
+ },
121
+ ],
122
+ }));
123
+ expect(metrics[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(1000);
124
+ expect(metrics[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders.gross_amount).toBe(1000);
125
+ });
126
+ it('legacy Amount Collected = sales - UNPAID balance when the invariant holds', () => {
127
+ const metrics = compile(makeOrder({
128
+ amount_earned: 1000,
129
+ amount_collected: 400,
130
+ payments: [
131
+ {
132
+ _id: 'cash-1',
133
+ payment_id: 'cash-1',
134
+ payment_type: constants_1.PAYMENT_TYPE_ENUM.CASH,
135
+ payment_status: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
136
+ amount_due: 400,
137
+ amount_paid: 400,
138
+ amount_refunded: 0,
139
+ card_details: null,
140
+ },
141
+ {
142
+ _id: 'unpaid-1',
143
+ payment_id: null,
144
+ payment_type: constants_1.PAYMENT_TYPE_ENUM.UNPAID,
145
+ payment_status: constants_1.PAYMENT_STATUS_ENUM.PENDING,
146
+ amount_due: 600,
147
+ amount_paid: 0,
148
+ amount_refunded: 0,
149
+ card_details: null,
150
+ },
151
+ ],
152
+ }));
153
+ const salesAmount = metrics[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount;
154
+ const unpaidGross = metrics[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments.find((payment) => payment.payment_type === constants_1.PAYMENT_TYPE_ENUM.UNPAID)?.gross_amount ?? 0;
155
+ expect(unpaidGross).toBe(600);
156
+ // The legacy UI formula with zero credit receipts:
157
+ const legacyAmountCollected = salesAmount - unpaidGross + 0 + 0;
158
+ expect(legacyAmountCollected).toBe(400);
159
+ });
160
+ });
72
161
  describe('materialized report key helpers', () => {
73
162
  it('builds and parses the ordered key grammar', () => {
74
163
  expect((0, key_helpers_1.buildMaterializedReportKey)(['COMPLETED', 'POS_TAKE-AWAY'])).toBe('COMPLETED:POS_TAKE-AWAY');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.4.28",
3
+ "version": "0.4.30",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "module": "esm/index.js",