@managesome/eposmatic-toolkit 0.4.27 → 0.4.29

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 (51) hide show
  1. package/esm/helpers/materialized-reports/index.js +1 -0
  2. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +49 -20
  3. package/esm/helpers/materialized-reports/materialized-day-input-signature.js +103 -0
  4. package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +63 -2
  5. package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +18 -0
  6. package/esm/helpers/materialized-reports/scope-helpers.js +27 -0
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +122 -9
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +24 -2
  9. package/esm/schemas/models/materialized_credit_bills.js +8 -0
  10. package/esm/schemas/models/materialized_tenant_discount_reports.js +9 -0
  11. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
  12. package/esm/schemas/models/tenant_active_jobs.js +8 -0
  13. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  14. package/lib/helpers/materialized-reports/index.js +1 -0
  15. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +28 -2
  16. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +50 -20
  17. package/lib/helpers/materialized-reports/materialized-day-input-signature.d.ts +66 -0
  18. package/lib/helpers/materialized-reports/materialized-day-input-signature.js +108 -0
  19. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +20 -1
  20. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +63 -2
  21. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +18 -0
  22. package/lib/helpers/materialized-reports/scope-helpers.d.ts +22 -0
  23. package/lib/helpers/materialized-reports/scope-helpers.js +28 -0
  24. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +41 -3
  25. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +120 -7
  26. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +4 -1
  27. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +24 -2
  28. package/lib/schemas/models/materialized_credit_bills.d.ts +3 -0
  29. package/lib/schemas/models/materialized_credit_bills.js +8 -0
  30. package/lib/schemas/models/materialized_tenant_discount_reports.d.ts +3 -0
  31. package/lib/schemas/models/materialized_tenant_discount_reports.js +9 -0
  32. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +3 -0
  33. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
  34. package/lib/schemas/models/tenant_active_jobs.d.ts +3 -0
  35. package/lib/schemas/models/tenant_active_jobs.js +8 -0
  36. package/lib/schemas/types/materialized_credit_bills.d.ts +6 -0
  37. package/lib/schemas/types/materialized_tenant_discount_reports.d.ts +6 -0
  38. package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +9 -0
  39. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +14 -0
  40. package/lib/schemas/types/tenant_active_jobs.d.ts +8 -0
  41. package/lib/tests/materialized-reports/materialized-day-input-signature.test.d.ts +1 -0
  42. package/lib/tests/materialized-reports/materialized-day-input-signature.test.js +81 -0
  43. package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +89 -0
  44. package/lib/tests/materialized-reports/materialized-discount-scenarios.test.d.ts +1 -0
  45. package/lib/tests/materialized-reports/materialized-discount-scenarios.test.js +676 -0
  46. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +134 -0
  47. package/lib/tests/materialized-reports/real-discount-orders.test.d.ts +1 -0
  48. package/lib/tests/materialized-reports/real-discount-orders.test.js +110 -0
  49. package/lib/tests/materialized-reports/tenant-discount-source-formatter.test.js +11 -2
  50. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +162 -0
  51. package/package.json +1 -1
@@ -485,3 +485,137 @@ describe('complimentary full/partial accumulator', () => {
485
485
  expect(comp.complimentary_full).toBe(true);
486
486
  });
487
487
  });
488
+ describe('missing discount mechanisms (synthetic coverage)', () => {
489
+ it('classifies an order-level loyalty offer', () => {
490
+ const identity = (0, materialized_discount_source_helpers_1.classifyDiscountEntrySource)(entry({
491
+ slot: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SLOT_ENUM.LOYALTY,
492
+ sub_kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER,
493
+ level: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER,
494
+ discount_id: 'offer-order-1',
495
+ name: 'Order Loyalty Offer',
496
+ amount: 500,
497
+ }));
498
+ expect(identity.source_key).toBe('loyalty:offer:offer-order-1');
499
+ expect(identity.source_class).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.LOYALTY);
500
+ expect(identity.level).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER);
501
+ });
502
+ it('classifies an item-level voucher and keeps its reference', () => {
503
+ const identity = (0, materialized_discount_source_helpers_1.classifyDiscountEntrySource)(entry({
504
+ slot: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SLOT_ENUM.VOUCHER,
505
+ sub_kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER,
506
+ level: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM,
507
+ discount_id: 'voucher-item-1',
508
+ reference_number: 'ITEM-CODE',
509
+ name: 'Item Voucher',
510
+ amount: 500,
511
+ }));
512
+ expect(identity.source_key).toBe('voucher:voucher-item-1');
513
+ expect(identity.source_class).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.VOUCHER);
514
+ expect(identity.level).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM);
515
+ });
516
+ it('classifies a gift card from loyalty evidence/reference', () => {
517
+ const identity = (0, materialized_discount_source_helpers_1.classifyDiscountEntrySource)(entry({
518
+ slot: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SLOT_ENUM.LOYALTY,
519
+ sub_kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER,
520
+ level: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER,
521
+ discount_id: 'gift-card-1',
522
+ reference_number: 'GIFT-CODE-1',
523
+ name: 'Gift Card',
524
+ amount: 500,
525
+ }));
526
+ expect(identity.source_key).toBe('loyalty:gift_card:gift-card-1');
527
+ expect(identity.source_class).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.LOYALTY);
528
+ expect(identity.sub_kind).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.GIFT_CARD);
529
+ });
530
+ it('classifies order and item collection discounts at either level', () => {
531
+ const id = '69f1c56ef9c86581b0ae9e36';
532
+ const order = (0, materialized_discount_source_helpers_1.classifyDiscountEntrySource)(entry({
533
+ sub_kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.COLLECTION,
534
+ level: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER,
535
+ discount_id: id,
536
+ rate: 1500,
537
+ name: 'Order Bank Discount',
538
+ }));
539
+ const item = (0, materialized_discount_source_helpers_1.classifyDiscountEntrySource)(entry({
540
+ sub_kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.COLLECTION,
541
+ level: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM,
542
+ item_id: 'item-1',
543
+ discount_id: id,
544
+ rate: 500,
545
+ is_percentage: false,
546
+ name: 'Item Bank Discount',
547
+ }));
548
+ expect(order.source_key).toBe(`discount:${id}`);
549
+ expect(item.source_key).toBe(`discount:${id}`);
550
+ expect(order.level).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER);
551
+ expect(item.level).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM);
552
+ });
553
+ });
554
+ describe('synthetic multi-source and comp combinations', () => {
555
+ const baseOrder = (over = {}) => ({
556
+ _id: 'order-combined',
557
+ tenant_id: 'tenant-a',
558
+ platform: 'POS_WALK-IN',
559
+ order_status: 'COMPLETED',
560
+ order_number: 99,
561
+ categories: [],
562
+ payments: [],
563
+ order_discount_details: null,
564
+ total_discount_applied: 0,
565
+ grand_total: 1000,
566
+ amount_earned: 1000,
567
+ amount_collected: 0,
568
+ createdAt: new Date('2026-09-15T13:00:00.000Z'),
569
+ updatedAt: new Date('2026-09-15T13:00:00.000Z'),
570
+ staff_details: null,
571
+ order_taker_details: null,
572
+ wallet_redemptions: null,
573
+ ...over,
574
+ });
575
+ it('keeps an order-level discount and a complimentary tender together', () => {
576
+ const result = (0, materialized_discount_accumulator_helpers_1.accumulateOrderDiscounts)(baseOrder({
577
+ order_discount_details: {
578
+ special_discount: 500,
579
+ special_discount_id: 'MANUAL_Rs 5',
580
+ special_discount_name: 'Apply Discount',
581
+ is_special_discount_percentage: false,
582
+ total_discount: 500,
583
+ },
584
+ payments: [
585
+ {
586
+ _id: 'p1',
587
+ payment_type: 'COMPLIMENTARY',
588
+ payment_status: 'SETTLED',
589
+ amount_due: 500,
590
+ amount_paid: 500,
591
+ amount_refunded: 0,
592
+ card_details: null,
593
+ payment_id: 'pay-comp',
594
+ },
595
+ ],
596
+ }), CONTEXT);
597
+ expect(result.entries.some((row) => row.kind === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT)).toBe(true);
598
+ expect(result.entries.some((row) => row.kind === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.COMPLIMENTARY)).toBe(true);
599
+ expect(result.counters.complimentary.payment_count).toBe(1);
600
+ });
601
+ it('keeps multiple order-level slots as independent source rows', () => {
602
+ const result = (0, materialized_discount_accumulator_helpers_1.accumulateOrderDiscounts)(baseOrder({
603
+ total_discount_applied: 800,
604
+ order_discount_details: {
605
+ special_discount: 500,
606
+ special_discount_id: 'MANUAL_Rs 5',
607
+ special_discount_name: 'Apply Discount',
608
+ is_special_discount_percentage: false,
609
+ loyalty_discount: 300,
610
+ loyalty_discount_id: 'loyalty-offer-1',
611
+ loyalty_discount_name: 'Loyalty Offer',
612
+ is_loyalty_discount_percentage: false,
613
+ total_discount: 800,
614
+ },
615
+ }), CONTEXT);
616
+ const orderRows = result.entries.filter((row) => row.level === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER &&
617
+ row.kind === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT);
618
+ expect(orderRows).toHaveLength(2);
619
+ expect(new Set(orderRows.map((row) => row.discount_id))).toEqual(new Set(['MANUAL_Rs 5', 'loyalty-offer-1']));
620
+ });
621
+ });
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const strict_1 = __importDefault(require("node:assert/strict"));
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const globals_1 = require("@jest/globals");
10
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
11
+ const materialized_discount_compile_helpers_1 = require("../../helpers/materialized-reports/materialized-discount-compile-helpers");
12
+ const materialized_discount_source_helpers_1 = require("../../helpers/materialized-reports/materialized-discount-source-helpers");
13
+ const materialized_integer_contract_1 = require("../../helpers/materialized-reports/materialized-integer-contract");
14
+ const ORDERS = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(__dirname, '..', 'real-discount-orders-2026-10-23.json'), 'utf8'));
15
+ const TENANT = 'thailemon.uae';
16
+ const BRAND = 'thailemon.co.nz';
17
+ const DAY = '2026-10-23';
18
+ const MONTH = '2026-10';
19
+ const compile = () => (0, materialized_discount_compile_helpers_1.compileTenantDiscountReports)({
20
+ tenantId: TENANT,
21
+ brandId: BRAND,
22
+ localDate: DAY,
23
+ orders: ORDERS,
24
+ gmtOffset: 5,
25
+ computedAt: new Date('2026-10-23T23:59:00.000Z'),
26
+ });
27
+ const sourcesForMonth = () => {
28
+ const compiled = compile();
29
+ const entry = compiled.entries.find((e) => e.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
30
+ return {
31
+ compiled,
32
+ sources: (0, materialized_discount_source_helpers_1.buildDiscountSourcesForScope)({
33
+ tenantId: TENANT,
34
+ brandId: BRAND,
35
+ scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
36
+ scopeField: MONTH,
37
+ dayIndex: null,
38
+ sections: entry.discount_entries,
39
+ computedAt: new Date('2026-10-23T23:59:00.000Z'),
40
+ sourceWatermark: null,
41
+ }),
42
+ };
43
+ };
44
+ (0, globals_1.describe)('real 2026-10-23 discount orders', () => {
45
+ (0, globals_1.it)('contains all 19 reference orders, including the no-discount control', () => {
46
+ strict_1.default.equal(ORDERS.length, 19);
47
+ strict_1.default.deepEqual(ORDERS.map((order) => order.order_number).sort((a, b) => a - b), Array.from({ length: 19 }, (_, index) => 55 + index));
48
+ });
49
+ (0, globals_1.it)('compiles 18 contributing orders and reconciles source money to report money', () => {
50
+ const { compiled, sources } = sourcesForMonth();
51
+ strict_1.default.equal(compiled.contributingOrders, 18);
52
+ const monthReport = compiled.reports.find((report) => report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
53
+ const reportTotal = Object.values(monthReport.discount_counters ?? {}).reduce((sum, counters) => sum + (counters.amount ?? 0), 0);
54
+ const sourceTotal = sources.reduce((sum, source) => sum + source.discount_amount, 0);
55
+ strict_1.default.equal(reportTotal, 311490);
56
+ strict_1.default.equal(sourceTotal, 311490);
57
+ strict_1.default.equal(sources.filter((source) => source.source_class === 'COMPLIMENTARY').length, 2);
58
+ strict_1.default.equal(sources.filter((source) => source.kind === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.FREE_ITEM).length, 2);
59
+ strict_1.default.equal(sources.reduce((sum, source) => sum + source.free_item_count, 0), 4);
60
+ });
61
+ (0, globals_1.it)('keeps the expected source rows and distinct order counts', () => {
62
+ const { sources } = sourcesForMonth();
63
+ const byKey = new Map(sources.map((source) => [`${source.source_key}|${source.level}`, source]));
64
+ const expected = [
65
+ ['manual:order', MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER, 3, 90000],
66
+ ['manual:item', MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM, 4, 43490],
67
+ ['price_override:item', MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM, 1, 25000],
68
+ ['catalog:auto', MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM, 3, 70000],
69
+ ['loyalty:wallet_cashback', MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER, 1, 50000],
70
+ ['discount:68cbaf10f365eb45bdbee96d', MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM, 1, 15000],
71
+ ['discount:6adb1adfa5fa4b8c498e65ec', MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER, 1, 10000],
72
+ ['voucher:6abf432e5e03cc49e2462a62', MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER, 1, 5000],
73
+ ['loyalty:offer:6ad9fa14ae19ab3c25c18a8a', MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM, 1, 2000],
74
+ ['loyalty:offer:6ad9f91eae19ab3c25c18a89', MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM, 1, 1000],
75
+ ];
76
+ for (const [key, level, orderCount, amount] of expected) {
77
+ const source = byKey.get(`${key}|${level}`);
78
+ strict_1.default.ok(source, `missing ${key}`);
79
+ strict_1.default.equal(source.order_count, orderCount, String(key));
80
+ strict_1.default.equal(source.discount_amount, amount, String(key));
81
+ }
82
+ strict_1.default.equal(byKey.get('complimentary:full|PAYMENT')?.covered_amount, 50000);
83
+ strict_1.default.equal(byKey.get('complimentary:partial|PAYMENT')?.covered_amount, 25000);
84
+ strict_1.default.equal(byKey.get('complimentary:full|PAYMENT')?.complimentary_full, true);
85
+ strict_1.default.equal(byKey.get('complimentary:partial|PAYMENT')?.complimentary_full, false);
86
+ });
87
+ (0, globals_1.it)('derives rates from integer sum/count only and never stores an average', () => {
88
+ const { sources } = sourcesForMonth();
89
+ for (const source of sources) {
90
+ strict_1.default.equal('rate' in source, false, `${source.source_key} stored rate`);
91
+ strict_1.default.ok(Number.isInteger(source.percentage_rate_sum));
92
+ strict_1.default.ok(Number.isInteger(source.percentage_row_count));
93
+ strict_1.default.ok(Number.isInteger(source.discount_amount));
94
+ }
95
+ const manualItem = sources.find((source) => source.source_key === 'manual:item');
96
+ strict_1.default.equal(manualItem.percentage_rate_sum, 18000);
97
+ strict_1.default.equal(manualItem.percentage_row_count, 4);
98
+ strict_1.default.equal(manualItem.rate_kind, 'PERCENTAGE');
99
+ const manualOrder = sources.find((source) => source.source_key === 'manual:order');
100
+ strict_1.default.equal(manualOrder.rate_kind, 'MIXED');
101
+ strict_1.default.equal(manualOrder.percentage_rate_sum, 10000);
102
+ strict_1.default.equal(manualOrder.percentage_row_count, 2);
103
+ });
104
+ (0, globals_1.it)('passes the recursive integer-only contract for reports, entries and sources', () => {
105
+ const { compiled, sources } = sourcesForMonth();
106
+ (0, materialized_integer_contract_1.assertIntegerOnlyDocuments)(compiled.reports, { collection: 'reports' });
107
+ (0, materialized_integer_contract_1.assertIntegerOnlyDocuments)(compiled.entries, { collection: 'entries' });
108
+ (0, materialized_integer_contract_1.assertIntegerOnlyDocuments)(sources, { collection: 'sources' });
109
+ });
110
+ });
@@ -85,7 +85,11 @@ describe('getFormattedTenantDiscountSources', () => {
85
85
  it('renders rate labels: percentage, mixed and fixed', () => {
86
86
  const formatted = (0, tenant_discount_source_formatter_1.getFormattedTenantDiscountSources)([
87
87
  report([
88
- row({ percentage_rate_sum: 15000, percentage_row_count: 10, rate_kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.PERCENTAGE }),
88
+ row({
89
+ percentage_rate_sum: 15000,
90
+ percentage_row_count: 10,
91
+ rate_kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.PERCENTAGE,
92
+ }),
89
93
  row({
90
94
  source_key: 'manual:item',
91
95
  percentage_rate_sum: null,
@@ -157,7 +161,12 @@ describe('getFormattedTenantDiscountSources', () => {
157
161
  it('keeps "mixed" and "—" when normalising (the rate kind wins)', () => {
158
162
  const formatted = (0, tenant_discount_source_formatter_1.getFormattedTenantDiscountSources)([
159
163
  report([
160
- row({ source_key: 'discount:a', percentage_rate_sum: null, percentage_row_count: null, rate_kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.MIXED }),
164
+ row({
165
+ source_key: 'discount:a',
166
+ percentage_rate_sum: null,
167
+ percentage_row_count: null,
168
+ rate_kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.MIXED,
169
+ }),
161
170
  row({
162
171
  source_key: 'discount:b',
163
172
  percentage_rate_sum: null,
@@ -638,3 +638,165 @@ describe('N2 backfill from CURRENT order state (settled-after-issue rule)', () =
638
638
  expect(patchedIssued?.settled_amount).toBe(1000);
639
639
  });
640
640
  });
641
+ /**
642
+ * DAY-INPUT SIGNATURE — the regression that motivated it.
643
+ *
644
+ * `source_watermark` is the MAX `orders.updatedAt` of the day's input. Delete
645
+ * an order and that maximum can REGRESS, so a watermark-only guard reports
646
+ * "nothing new" and leaves the deleted order's numbers in every report. The
647
+ * digest of the input SET catches it. These tests use the real compile + real
648
+ * plan, with no force flag anywhere.
649
+ */
650
+ describe('day-input signature change detection', () => {
651
+ const CT_A = new Date('2026-09-29T23:00:00.000Z');
652
+ const CT_B = new Date('2026-09-30T01:00:00.000Z');
653
+ const survivor = makeOrder({
654
+ orderId: 'order-survivor',
655
+ localDate: D1,
656
+ localHour: 10,
657
+ amount: 500,
658
+ updatedAt: '2026-09-29T10:00:00.000Z',
659
+ });
660
+ const victim = makeOrder({
661
+ orderId: 'order-victim',
662
+ localDate: D1,
663
+ localHour: 11,
664
+ amount: 700,
665
+ updatedAt: '2026-09-29T11:00:00.000Z',
666
+ });
667
+ it('stamps a deterministic digest on the compiled day / hour / period documents', () => {
668
+ const compile = compileDay(D1, [survivor, victim], CT_A);
669
+ const signatures = new Set(compile.materializedReports.map((doc) => doc.source_input_signature));
670
+ expect(signatures.size).toBe(1);
671
+ const signature = [...signatures][0];
672
+ expect(signature).toMatch(/^v1:2:[0-9a-f]{16}$/);
673
+ // Order-independent and stable.
674
+ const recompiled = compileDay(D1, [victim, survivor], CT_A);
675
+ expect(recompiled.materializedReports[0].source_input_signature).toBe(signature);
676
+ });
677
+ it('CORRECTS the day when the deleted order carried the maximum updatedAt', () => {
678
+ const firstPlan = closeDay(D1, [survivor, victim], EMPTY_WORLD, CT_A);
679
+ const world = persistPlan(EMPTY_WORLD, firstPlan);
680
+ const storedDate = expectNonNull(world.docs.find((doc) => doc.scope_context === LOCAL_DATE && doc.scope_field === D1));
681
+ const storedWatermark = new Date(storedDate.source_watermark).getTime();
682
+ expect(storedWatermark).toBe(new Date('2026-09-29T11:00:00.000Z').getTime());
683
+ // Re-close with the victim GONE: the incoming max updatedAt (10:00) is
684
+ // LOWER than the stored watermark — the pre-signature guard skipped here.
685
+ const secondCompile = compileDay(D1, [survivor], CT_B);
686
+ const incomingDate = expectNonNull(secondCompile.materializedReports.find((doc) => doc.scope_context === LOCAL_DATE && doc.scope_field === D1));
687
+ expect(new Date(incomingDate.source_watermark).getTime()).toBeLessThan(storedWatermark);
688
+ const plan = expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
689
+ tenantId: TENANT,
690
+ compile: secondCompile,
691
+ reason: 'TEST_RECLOSE',
692
+ existing: world.docs,
693
+ existingCreditBills: world.credit,
694
+ computedAt: CT_B,
695
+ }));
696
+ const dateWrite = expectNonNull(findWrite(plan, LOCAL_DATE, D1));
697
+ expect(getKeyMetrics(dateWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(1);
698
+ expect(getKeyMetrics(dateWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(500);
699
+ // The removed hour is DELETED, not left behind.
700
+ expect(plan.staleHourDocuments.map((doc) => doc.scope_field)).toEqual([`${D1} 11`]);
701
+ // The period documents are corrected by subtract(stored day) + add(compiled day).
702
+ const monthWrite = expectNonNull(findWrite(plan, LOCAL_MONTH, '2026-09'));
703
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(1);
704
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(500);
705
+ const after = persistPlan(world, plan);
706
+ expect(after.docs.some((doc) => doc.scope_context === LOCAL_HOUR && doc.scope_field === `${D1} 11`)).toBe(false);
707
+ });
708
+ it('still skips an identical re-close (no churn): the digest is unchanged', () => {
709
+ const firstPlan = closeDay(D1, [survivor], EMPTY_WORLD, CT_A);
710
+ const world = persistPlan(EMPTY_WORLD, firstPlan);
711
+ const secondPlan = closeDay(D1, [survivor], world, CT_B);
712
+ expect(secondPlan.writes).toEqual([]);
713
+ expect(secondPlan.staleHourDocuments).toEqual([]);
714
+ expect(secondPlan.skippedDocuments.length).toBeGreaterThan(0);
715
+ });
716
+ it('treats a legacy document WITHOUT a signature as needing one corrective write', () => {
717
+ const firstPlan = closeDay(D1, [survivor], EMPTY_WORLD, CT_A);
718
+ const world = persistPlan(EMPTY_WORLD, firstPlan);
719
+ const legacy = world.docs.map((doc) => {
720
+ const { source_input_signature: _ignored, ...rest } = doc;
721
+ return rest;
722
+ });
723
+ const plan = closeDay(D1, [survivor], { ...world, docs: legacy }, CT_B);
724
+ expect(plan.writes.length).toBeGreaterThan(0);
725
+ expect(expectNonNull(findWrite(plan, LOCAL_DATE, D1)).report.source_input_signature).toMatch(/^v1:1:/);
726
+ });
727
+ });
728
+ /**
729
+ * PERIOD REPAIR — a missing period document must be rebuilt from the DAY
730
+ * documents that still exist, not seeded with the closing day alone.
731
+ *
732
+ * Contract: for additive metrics, `localMonth` == Σ `localDate` of the month.
733
+ * The closing day itself is replaced by the fresh compile; every other stored
734
+ * day of the period is folded in.
735
+ */
736
+ describe('period document repair from sibling days', () => {
737
+ const CT_A = new Date('2026-09-29T23:00:00.000Z');
738
+ const CT_B = new Date('2026-09-30T01:00:00.000Z');
739
+ const D1_ORDER = makeOrder({
740
+ orderId: 'day-one-order',
741
+ localDate: D1,
742
+ localHour: 10,
743
+ amount: 500,
744
+ updatedAt: '2026-09-29T10:00:00.000Z',
745
+ });
746
+ const D2_ORDER = makeOrder({
747
+ orderId: 'day-two-order',
748
+ localDate: D2,
749
+ localHour: 12,
750
+ amount: 800,
751
+ updatedAt: '2026-09-30T12:00:00.000Z',
752
+ });
753
+ it('rebuilds a MISSING localMonth from the stored localDate documents', () => {
754
+ const dayOnePlan = closeDay(D1, [D1_ORDER], EMPTY_WORLD, CT_A);
755
+ const world = persistPlan(EMPTY_WORLD, dayOnePlan);
756
+ const monthScope = world.docs.find((doc) => doc.scope_context === LOCAL_MONTH);
757
+ expect(monthScope).toBeDefined();
758
+ // Simulate the period document being lost while the day document survives.
759
+ const withoutMonth = {
760
+ docs: world.docs.filter((doc) => doc.scope_context !== LOCAL_MONTH),
761
+ credit: world.credit.filter((doc) => doc.scope_context !== LOCAL_MONTH),
762
+ };
763
+ const siblingDays = withoutMonth.docs.filter((doc) => doc.scope_context === LOCAL_DATE);
764
+ const plan = expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
765
+ tenantId: TENANT,
766
+ compile: compileDay(D2, [D2_ORDER], CT_B),
767
+ reason: 'TEST_RECLOSE',
768
+ existing: withoutMonth.docs,
769
+ existingCreditBills: withoutMonth.credit,
770
+ existingPeriodDayDocuments: siblingDays,
771
+ computedAt: CT_B,
772
+ }));
773
+ expect(plan.createdPeriodDocuments).toContainEqual({
774
+ scope_context: LOCAL_MONTH,
775
+ scope_field: '2026-09',
776
+ });
777
+ expect(plan.foldedPeriodDayDocuments).toBeGreaterThanOrEqual(1);
778
+ const monthWrite = expectNonNull(findWrite(plan, LOCAL_MONTH, '2026-09'));
779
+ // D1's 500 + D2's 800 — the lost month is repaired, not reseeded with D2 only.
780
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(2);
781
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(1300);
782
+ });
783
+ it('does NOT fold a sibling from another schema/key grammar (it cannot be summed)', () => {
784
+ const dayOnePlan = closeDay(D1, [D1_ORDER], EMPTY_WORLD, CT_A);
785
+ const world = persistPlan(EMPTY_WORLD, dayOnePlan);
786
+ const foreign = world.docs
787
+ .filter((doc) => doc.scope_context === LOCAL_DATE)
788
+ .map((doc) => ({ ...doc, schema_version: 999 }));
789
+ const plan = expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
790
+ tenantId: TENANT,
791
+ compile: compileDay(D2, [D2_ORDER], CT_B),
792
+ reason: 'TEST_RECLOSE',
793
+ existing: world.docs.filter((doc) => doc.scope_context !== LOCAL_MONTH),
794
+ existingCreditBills: world.credit,
795
+ existingPeriodDayDocuments: foreign,
796
+ computedAt: CT_B,
797
+ }));
798
+ expect(plan.foldedPeriodDayDocuments).toBe(0);
799
+ 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);
801
+ });
802
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.4.27",
3
+ "version": "0.4.29",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "module": "esm/index.js",