@managesome/eposmatic-toolkit 0.4.26 → 0.4.28

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 (60) hide show
  1. package/esm/helpers/materialized-reports/index.js +1 -0
  2. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +9 -4
  3. package/esm/helpers/materialized-reports/materialized-delivery-classification-helpers.js +25 -9
  4. package/esm/helpers/materialized-reports/materialized-delivery-compile-helpers.js +8 -5
  5. package/esm/helpers/materialized-reports/materialized-discount-accumulator-helpers.js +13 -1
  6. package/esm/helpers/materialized-reports/materialized-discount-source-helpers.js +0 -3
  7. package/esm/helpers/materialized-reports/materialized-integer-contract.js +142 -0
  8. package/esm/helpers/materialized-reports/materialized-payments-comparison-accumulator-helpers.js +7 -1
  9. package/esm/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +9 -2
  10. package/esm/helpers/materialized-reports/materialized-sales-comparison-accumulator-helpers.js +17 -7
  11. package/esm/helpers/materialized-reports/tenant-discount-source-formatter.js +29 -29
  12. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -2
  13. package/esm/helpers/utils/duration-conversion.js +31 -0
  14. package/esm/helpers/utils/index.js +2 -0
  15. package/esm/helpers/utils/percentage-conversion.js +69 -0
  16. package/esm/schemas/models/materialized_tenant_discount_sources.js +5 -1
  17. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  18. package/lib/helpers/materialized-reports/index.js +1 -0
  19. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +9 -4
  20. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.js +25 -9
  21. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +8 -5
  22. package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.d.ts +18 -0
  23. package/lib/helpers/materialized-reports/materialized-discount-accumulator-helpers.js +14 -2
  24. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +0 -3
  25. package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +68 -0
  26. package/lib/helpers/materialized-reports/materialized-integer-contract.js +147 -0
  27. package/lib/helpers/materialized-reports/materialized-payments-comparison-accumulator-helpers.js +7 -1
  28. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +9 -2
  29. package/lib/helpers/materialized-reports/materialized-sales-comparison-accumulator-helpers.js +17 -7
  30. package/lib/helpers/materialized-reports/tenant-discount-source-formatter.d.ts +12 -30
  31. package/lib/helpers/materialized-reports/tenant-discount-source-formatter.js +29 -30
  32. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -2
  33. package/lib/helpers/types/materialized-reports-apis.d.ts +11 -3
  34. package/lib/helpers/utils/duration-conversion.d.ts +19 -0
  35. package/lib/helpers/utils/duration-conversion.js +37 -0
  36. package/lib/helpers/utils/index.d.ts +2 -0
  37. package/lib/helpers/utils/index.js +2 -0
  38. package/lib/helpers/utils/percentage-conversion.d.ts +49 -0
  39. package/lib/helpers/utils/percentage-conversion.js +76 -0
  40. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +0 -3
  41. package/lib/schemas/models/materialized_tenant_discount_sources.js +5 -1
  42. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +11 -4
  43. package/lib/schemas/types/materialized_tenant_discount_sources.d.ts +23 -4
  44. package/lib/tests/materialized-reports/fixtures.d.ts +15 -1
  45. package/lib/tests/materialized-reports/fixtures.js +118 -8
  46. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +34 -24
  47. package/lib/tests/materialized-reports/materialized-discount-scenarios.test.d.ts +1 -0
  48. package/lib/tests/materialized-reports/materialized-discount-scenarios.test.js +676 -0
  49. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +148 -10
  50. package/lib/tests/materialized-reports/materialized-integer-contract.test.d.ts +1 -0
  51. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +223 -0
  52. package/lib/tests/materialized-reports/materialized-write-paths-inventory.test.d.ts +1 -0
  53. package/lib/tests/materialized-reports/materialized-write-paths-inventory.test.js +58 -0
  54. package/lib/tests/materialized-reports/materialized-writers-integer-only.test.d.ts +1 -0
  55. package/lib/tests/materialized-reports/materialized-writers-integer-only.test.js +150 -0
  56. package/lib/tests/materialized-reports/real-discount-orders.test.d.ts +1 -0
  57. package/lib/tests/materialized-reports/real-discount-orders.test.js +110 -0
  58. package/lib/tests/materialized-reports/sales-overview-baseline.test.js +51 -51
  59. package/lib/tests/materialized-reports/tenant-discount-source-formatter.test.js +89 -41
  60. package/package.json +1 -1
@@ -74,7 +74,7 @@ describe('discount source identity', () => {
74
74
  expect(identity.level).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ORDER);
75
75
  });
76
76
  it('groups every manual order amount under ONE source', () => {
77
- const a = (0, materialized_discount_source_helpers_1.classifyDiscountEntrySource)(entry({ discount_id: 'MANUAL_50%', rate: 50, name: 'Discount' }));
77
+ const a = (0, materialized_discount_source_helpers_1.classifyDiscountEntrySource)(entry({ discount_id: 'MANUAL_50%', rate: 5000, name: 'Discount' }));
78
78
  const b = (0, materialized_discount_source_helpers_1.classifyDiscountEntrySource)(entry({ discount_id: 'MANUAL_Rs 500', rate: 500, name: 'Apply Discount', is_percentage: false }));
79
79
  expect(a.source_key).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SOURCE_KEY.MANUAL_ORDER);
80
80
  expect(b.source_key).toBe(a.source_key);
@@ -86,7 +86,7 @@ describe('discount source identity', () => {
86
86
  level: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM,
87
87
  item_id: 'item-1',
88
88
  discount_id: 'MANUAL_25%',
89
- rate: 25,
89
+ rate: 2500,
90
90
  }));
91
91
  expect(identity.source_key).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SOURCE_KEY.MANUAL_ITEM);
92
92
  expect(identity.source_name).toBe('Manual item discount');
@@ -96,7 +96,7 @@ describe('discount source identity', () => {
96
96
  expect((0, materialized_discount_source_helpers_1.normalizeDiscountSourceKeyPart)('VISA CARD')).toBe('visa_card');
97
97
  const identity = (0, materialized_discount_source_helpers_1.classifyDiscountEntrySource)(entry({
98
98
  discount_id: 'MANUAL_10%',
99
- rate: 10,
99
+ rate: 1000,
100
100
  name: 'MANUAL_10%',
101
101
  reason: 'Discount applied for VISA CARD',
102
102
  }));
@@ -150,7 +150,7 @@ describe('discount source identity', () => {
150
150
  sub_kind: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM.OFFER,
151
151
  discount_id: offer,
152
152
  name: 'Z2 Party 10% Offer',
153
- rate: 10,
153
+ rate: 1000,
154
154
  }));
155
155
  expect(offerIdentity.source_key).toBe(`loyalty:offer:${offer}`);
156
156
  expect(offerIdentity.source_class).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM.LOYALTY);
@@ -248,7 +248,7 @@ describe('discount source identity', () => {
248
248
  describe('buildDiscountSourcesForScope', () => {
249
249
  it('groups two manual order rows into one source with distinct orders', () => {
250
250
  const docs = (0, materialized_discount_source_helpers_1.buildDiscountSourcesForScope)(scopeInput([
251
- entry({ order_id: 'o1', discount_id: 'MANUAL_50%', rate: 50, amount: 500 }),
251
+ entry({ order_id: 'o1', discount_id: 'MANUAL_50%', rate: 5000, amount: 500 }),
252
252
  entry({ order_id: 'o2', discount_id: 'MANUAL_Rs 200', rate: 200, is_percentage: false, amount: 200 }),
253
253
  ]));
254
254
  expect(docs).toHaveLength(1);
@@ -257,7 +257,11 @@ describe('buildDiscountSourcesForScope', () => {
257
257
  expect(docs[0].row_count).toBe(2);
258
258
  expect(docs[0].discount_amount).toBe(700);
259
259
  expect(docs[0].rate_kind).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.MIXED);
260
- expect(docs[0].rate).toBe(50);
260
+ // NO stored average rate: the source keeps the integer sum/count and the
261
+ // average is derived at the read boundary.
262
+ expect(docs[0]).not.toHaveProperty('rate');
263
+ expect(docs[0].percentage_rate_sum).toBe(5000);
264
+ expect(docs[0].percentage_row_count).toBe(1);
261
265
  });
262
266
  it('counts an order ONCE per source even with several item rows', () => {
263
267
  const docs = (0, materialized_discount_source_helpers_1.buildDiscountSourcesForScope)(scopeInput([
@@ -267,7 +271,7 @@ describe('buildDiscountSourcesForScope', () => {
267
271
  item_id: 'i1',
268
272
  entry_key: 'item:i1:special',
269
273
  discount_id: 'MANUAL_25%',
270
- rate: 25,
274
+ rate: 2500,
271
275
  amount: 250,
272
276
  }),
273
277
  entry({
@@ -276,7 +280,7 @@ describe('buildDiscountSourcesForScope', () => {
276
280
  item_id: 'i2',
277
281
  entry_key: 'item:i2:special',
278
282
  discount_id: 'MANUAL_25%',
279
- rate: 25,
283
+ rate: 2500,
280
284
  amount: 250,
281
285
  }),
282
286
  ]));
@@ -291,7 +295,7 @@ describe('buildDiscountSourcesForScope', () => {
291
295
  item_id: 'i1',
292
296
  entry_key: 'item:i1:special',
293
297
  level: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM,
294
- rate: 100,
298
+ rate: 10000,
295
299
  amount: 500,
296
300
  item_value: 500,
297
301
  });
@@ -308,7 +312,7 @@ describe('buildDiscountSourcesForScope', () => {
308
312
  item_id: 'i2',
309
313
  entry_key: 'item:i2:special',
310
314
  level: MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_LEVEL_ENUM.ITEM,
311
- rate: 50,
315
+ rate: 5000,
312
316
  amount: 100,
313
317
  }),
314
318
  ]));
@@ -481,3 +485,137 @@ describe('complimentary full/partial accumulator', () => {
481
485
  expect(comp.complimentary_full).toBe(true);
482
486
  });
483
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,223 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
4
+ const materialized_integer_contract_1 = require("../../helpers/materialized-reports/materialized-integer-contract");
5
+ const materialized_report_drilldown_rows_1 = require("../../helpers/materialized-reports/materialized-report-drilldown-rows");
6
+ const materialized_discount_compile_helpers_1 = require("../../helpers/materialized-reports/materialized-discount-compile-helpers");
7
+ const materialized_discount_source_helpers_1 = require("../../helpers/materialized-reports/materialized-discount-source-helpers");
8
+ const fixtures_1 = require("./fixtures");
9
+ /**
10
+ * THE integer-only storage contract.
11
+ *
12
+ * A materialized document may only hold integers:
13
+ * - money in CENTS,
14
+ * - percentage rates in BASIS POINTS (1% = 100 bps),
15
+ * - durations in whole MINUTES,
16
+ * - counts / iterations / schema versions as integers,
17
+ * - NO stored share, average or ratio (they are derived in the formatter).
18
+ *
19
+ * These tests are the ENFORCEMENT: the validator is the gate every writer
20
+ * passes through, and it must catch a decimal wherever it hides — a nested
21
+ * counter, a key-metric map, a flat `data` payload or an iteration snapshot.
22
+ */
23
+ describe('findNonIntegerNumericLeaves', () => {
24
+ it('accepts a document of integers', () => {
25
+ expect((0, materialized_integer_contract_1.findNonIntegerNumericLeaves)({
26
+ _id: 'a',
27
+ tenant_id: 't',
28
+ amount: 13125,
29
+ nested: { count: 3, rows: [{ amount: 1, rate: 5000 }] },
30
+ createdAt: new Date('2026-09-15T00:00:00.000Z'),
31
+ flag: true,
32
+ empty: null,
33
+ })).toEqual([]);
34
+ });
35
+ it('rejects a decimal number and names its path', () => {
36
+ const violations = (0, materialized_integer_contract_1.findNonIntegerNumericLeaves)({
37
+ amount: 131.25,
38
+ nested: { rows: [{ rate: 0.2 }] },
39
+ });
40
+ expect(violations.map((violation) => violation.path)).toEqual(['amount', 'nested.rows[0].rate']);
41
+ expect(violations.every((violation) => violation.reason === 'decimal')).toBe(true);
42
+ });
43
+ it('rejects NaN and Infinity', () => {
44
+ const violations = (0, materialized_integer_contract_1.findNonIntegerNumericLeaves)({
45
+ a: Number.NaN,
46
+ b: Number.POSITIVE_INFINITY,
47
+ c: Number.NEGATIVE_INFINITY,
48
+ });
49
+ expect(violations).toHaveLength(3);
50
+ expect(violations.every((violation) => violation.reason === 'non-finite')).toBe(true);
51
+ });
52
+ it('rejects a decimal smuggled in as a string, but not an identifier', () => {
53
+ const violations = (0, materialized_integer_contract_1.findNonIntegerNumericLeaves)({
54
+ amount: '131.25',
55
+ count: '7',
56
+ // A scope field legitimately holds a numeric-looking string.
57
+ scope_field: '2026',
58
+ day_index: '2026-09-15',
59
+ order_id: '12345',
60
+ });
61
+ expect(violations.map((violation) => violation.path)).toEqual(['amount', 'count']);
62
+ expect(violations.every((violation) => violation.reason === 'numeric-string')).toBe(true);
63
+ });
64
+ it('ignores dates, object ids, booleans and null', () => {
65
+ expect((0, materialized_integer_contract_1.findNonIntegerNumericLeaves)({
66
+ computed_at: new Date(),
67
+ _id: { _bsontype: 'ObjectId', value: 'abc' },
68
+ deleted: false,
69
+ missing: null,
70
+ })).toEqual([]);
71
+ });
72
+ });
73
+ describe('assertIntegerOnlyDocument', () => {
74
+ it('throws with the offending path', () => {
75
+ expect(() => (0, materialized_integer_contract_1.assertIntegerOnlyDocument)({ amount: 1.5 }, { collection: 'demo' })).toThrow(/demo.*amount=1\.5 \(decimal\)/s);
76
+ });
77
+ it('passes an integer document', () => {
78
+ expect(() => (0, materialized_integer_contract_1.assertIntegerOnlyDocument)({ amount: 15, rate: 5000 })).not.toThrow();
79
+ });
80
+ it('checks every document of a batch', () => {
81
+ expect(() => (0, materialized_integer_contract_1.assertIntegerOnlyDocuments)([{ amount: 1 }, { amount: 2.5 }], { collection: 'demo' })).toThrow(/demo\[1\]/);
82
+ });
83
+ });
84
+ describe('the gate catches a decimal wherever it hides', () => {
85
+ it('rejects a decimal in a TOP-LEVEL field', () => {
86
+ expect(() => (0, materialized_integer_contract_1.assertIntegerOnlyDocument)({ discount_amount: 131.25 })).toThrow(/discount_amount=131\.25/);
87
+ });
88
+ it('rejects a decimal in a NESTED Mixed map (discount_counters / sale_type_metrics)', () => {
89
+ expect(() => (0, materialized_integer_contract_1.assertIntegerOnlyDocument)({
90
+ discount_counters: {
91
+ 'COMPLETED:POS_DINE-IN': { amount: 1085.77, count: 3 },
92
+ },
93
+ })).toThrow(/discount_counters\.COMPLETED:POS_DINE-IN\.amount=1085\.77/);
94
+ expect(() => (0, materialized_integer_contract_1.assertIntegerOnlyDocument)({
95
+ sale_type_metrics: {
96
+ 'COMPLETED:POS_DINE-IN': { gross_amount: 220.6896 },
97
+ },
98
+ })).toThrow(/sale_type_metrics\.COMPLETED:POS_DINE-IN\.gross_amount=220\.6896/);
99
+ });
100
+ it('rejects a decimal in a FLAT-ROW `data` payload', () => {
101
+ expect(() => (0, materialized_integer_contract_1.assertIntegerOnlyDocument)({
102
+ tenant_id: 'tenant-a',
103
+ key: 'COMPLETED:POS_DINE-IN',
104
+ data: { amount: 131.25, rate: 5000, item_value: 420.5 },
105
+ })).toThrow(/data\.amount=131\.25/);
106
+ });
107
+ it('rejects a decimal in an ITERATION snapshot', () => {
108
+ expect(() => (0, materialized_integer_contract_1.assertIntegerOnlyDocument)({
109
+ report_id: 'r1',
110
+ iteration: 2,
111
+ schema_version: 1,
112
+ snapshot: { discount_counters: { 'COMPLETED:POS_DINE-IN': { amount: 1.5 } } },
113
+ })).toThrow(/snapshot\.discount_counters\.COMPLETED:POS_DINE-IN\.amount=1\.5/);
114
+ });
115
+ it('rejects a decimal in a source key_metrics map', () => {
116
+ expect(() => (0, materialized_integer_contract_1.assertIntegerOnlyDocument)({
117
+ source_key: 'manual:order',
118
+ key_metrics: {
119
+ 'COMPLETED:POS_DINE-IN': { discount_amount: 87.175, order_count: 1 },
120
+ },
121
+ })).toThrow(/key_metrics\.COMPLETED:POS_DINE-IN\.discount_amount=87\.175/);
122
+ });
123
+ it('passes a document whose every nested map is integral', () => {
124
+ expect(() => (0, materialized_integer_contract_1.assertIntegerOnlyDocument)({
125
+ discount_counters: { 'COMPLETED:POS_DINE-IN': { amount: 108577, count: 3 } },
126
+ sale_type_metrics: { 'COMPLETED:POS_DINE-IN': { gross_amount: 22069 } },
127
+ key_metrics: { 'COMPLETED:POS_DINE-IN': { discount_amount: 8718 } },
128
+ data: { amount: 13125, rate: 5000 },
129
+ snapshot: { amount: 1 },
130
+ schema_version: 1,
131
+ iteration: 2,
132
+ })).not.toThrow();
133
+ });
134
+ });
135
+ describe('the discount documents are integer-only', () => {
136
+ const entry = (over = {}) => ({
137
+ kind: 'DISCOUNT',
138
+ slot: 'SPECIAL',
139
+ sub_kind: 'MANUAL',
140
+ level: 'ORDER',
141
+ entry_key: 'order:special',
142
+ order_id: 'o1',
143
+ amount: 13125,
144
+ rate: 5000,
145
+ is_percentage: true,
146
+ created_at: new Date('2026-09-15T10:00:00.000Z'),
147
+ local_hour: '2026-09-15 10',
148
+ ...over,
149
+ });
150
+ it('the drill-down projection (a Mixed `data` payload) is integer-only', () => {
151
+ const built = (0, materialized_report_drilldown_rows_1.buildMaterializedDrilldownRows)(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DISCOUNT_ENTRIES, {
152
+ tenant_id: 'tenant-a',
153
+ brand_id: 'brand-a',
154
+ scope_context: 'localDate',
155
+ scope_field: '2026-09-15',
156
+ day_index: '2026-09-15',
157
+ computed_at: new Date('2026-09-15T23:00:00.000Z'),
158
+ discount_entries: {
159
+ 'COMPLETED:POS_WALK-IN': { rows: [entry(), entry({ entry_key: 'order:special:2', rate: 2000 })] },
160
+ },
161
+ });
162
+ expect(built.rows.length).toBe(2);
163
+ // The `data` blob is a Mixed payload — the schema cannot cover it, so the
164
+ // validator is the only gate.
165
+ (0, materialized_integer_contract_1.assertIntegerOnlyDocuments)(built.rows, { collection: 'materialized_report_drilldown_rows' });
166
+ const scope = (0, materialized_report_drilldown_rows_1.buildMaterializedDrilldownScope)(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DISCOUNT_ENTRIES, { tenant_id: 'tenant-a', brand_id: 'brand-a', scope_context: 'localDate', scope_field: '2026-09-15' }, built.rows);
167
+ (0, materialized_integer_contract_1.assertIntegerOnlyDocument)(scope, { collection: 'materialized_report_drilldown_scopes' });
168
+ });
169
+ it('a rate is stored in BASIS POINTS, so a mixed source keeps "mixed"', () => {
170
+ // 5000 bps = 50%, 2000 bps = 20% -> the average is 3500 bps.
171
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.MIXED).toBe('MIXED');
172
+ });
173
+ });
174
+ describe('a FULL discount document set is integer-only', () => {
175
+ const TENANT = 'basha-istanbul-f7';
176
+ const BRAND = 'basha-istanbul-f7';
177
+ const AT = new Date('2026-09-30T23:00:00.000Z');
178
+ it('the reports, the entries, the sources and the drill-down rows hold no decimal', () => {
179
+ const orders = (0, fixtures_1.loadOrdersDataset)('basha').filter((order) => order.localDate === '2026-09-13');
180
+ expect(orders.length).toBeGreaterThan(0);
181
+ const compiled = (0, materialized_discount_compile_helpers_1.compileTenantDiscountReports)({
182
+ tenantId: TENANT,
183
+ brandId: BRAND,
184
+ localDate: '2026-09-13',
185
+ orders,
186
+ gmtOffset: 5,
187
+ computedAt: AT,
188
+ });
189
+ // 1. the counters
190
+ (0, materialized_integer_contract_1.assertIntegerOnlyDocuments)(compiled.reports, {
191
+ collection: 'materialized_tenant_discount_reports',
192
+ });
193
+ // 2. the drill-down rows
194
+ (0, materialized_integer_contract_1.assertIntegerOnlyDocuments)(compiled.entries, {
195
+ collection: 'materialized_tenant_discount_entries',
196
+ });
197
+ // 3. the source projection, built from the compiled entries
198
+ const sources = (0, materialized_discount_source_helpers_1.buildDiscountSourcesForScope)({
199
+ tenantId: TENANT,
200
+ brandId: BRAND,
201
+ scopeContext: compiled.entries[0].scope_context,
202
+ scopeField: compiled.entries[0].scope_field,
203
+ dayIndex: compiled.entries[0].day_index ?? null,
204
+ sections: compiled.entries[0].discount_entries,
205
+ computedAt: AT,
206
+ sourceWatermark: compiled.entries[0].source_watermark ?? null,
207
+ });
208
+ (0, materialized_integer_contract_1.assertIntegerOnlyDocuments)(sources, {
209
+ collection: 'materialized_tenant_discount_sources',
210
+ });
211
+ // 4. the flat drill-down projection (a Mixed `data` payload)
212
+ const rows = (0, materialized_report_drilldown_rows_1.buildMaterializedDrilldownRows)(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DISCOUNT_ENTRIES, compiled.entries[0]).rows;
213
+ (0, materialized_integer_contract_1.assertIntegerOnlyDocuments)(rows, { collection: 'materialized_report_drilldown_rows' });
214
+ // 5. NO stored average rate, and NO fractional average anywhere: the
215
+ // source keeps the integer SUM (basis points) and the integer COUNT.
216
+ for (const source of sources) {
217
+ expect(source).not.toHaveProperty('rate');
218
+ expect(source.percentage_rate_sum % 1).toBe(0);
219
+ expect(source.percentage_row_count % 1).toBe(0);
220
+ expect(source.fixed_row_count % 1).toBe(0);
221
+ }
222
+ });
223
+ });
@@ -0,0 +1,58 @@
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 fs_1 = __importDefault(require("fs"));
7
+ const path_1 = __importDefault(require("path"));
8
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
9
+ /**
10
+ * THE integer-only storage contract, enforced at EVERY materialized write path.
11
+ *
12
+ * The runtime gate lives in the toolkit
13
+ * (`assertIntegerOnlyDocument` / `assertIntegerOnlyDocuments`); the workers
14
+ * service has the matching inventory suite for its own write paths.
15
+ *
16
+ * This suite is the INVENTORY for the SIMULATION / DEMO upload paths — the
17
+ * scripts that write materialized collections into a database. A write site
18
+ * that loses its gate would otherwise stay invisible until a decimal reached
19
+ * Mongo.
20
+ *
21
+ * A `deleteMany` carries no document, so it is not a gated write.
22
+ */
23
+ const SIMULATIONS_DIR = path_1.default.resolve(__dirname, '../../../simulations');
24
+ /** The materialized write paths of the demo/simulation scripts. */
25
+ const WRITE_PATHS = [
26
+ 'generate-demo-materialized-data.ts',
27
+ 'upload-demo-materialized-data.ts',
28
+ 'upload-drilldown-demo-only.ts',
29
+ ];
30
+ /** Writes that carry documents into a collection (and therefore need a gate). */
31
+ const DOCUMENT_WRITES = ['insertMany(', 'insertOne(', 'bulkWrite(', 'replaceOne(', 'updateOne('];
32
+ /** The gate calls. */
33
+ const GATES = ['assertIntegerOnly(', 'assertIntegerOnlyDocuments(', 'assertIntegerOnlyDocument('];
34
+ const countOccurrences = (source, needles) => needles.reduce((total, needle) => {
35
+ let count = 0;
36
+ let index = source.indexOf(needle);
37
+ while (index !== -1) {
38
+ count += 1;
39
+ index = source.indexOf(needle, index + needle.length);
40
+ }
41
+ return total + count;
42
+ }, 0);
43
+ describe('every materialized write path is gated', () => {
44
+ for (const fileName of WRITE_PATHS) {
45
+ it(`${fileName} gates every document-carrying write`, () => {
46
+ const source = fs_1.default.readFileSync(path_1.default.join(SIMULATIONS_DIR, fileName), 'utf8');
47
+ const writes = countOccurrences(source, DOCUMENT_WRITES);
48
+ const gates = countOccurrences(source, GATES);
49
+ expect(writes).toBeGreaterThan(0);
50
+ expect(gates).toBeGreaterThanOrEqual(writes);
51
+ });
52
+ }
53
+ it('the rate kind label is unchanged by the rate removal', () => {
54
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.MIXED).toBe('MIXED');
55
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.PERCENTAGE).toBe('PERCENTAGE');
56
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM.FIXED).toBe('FIXED');
57
+ });
58
+ });