@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
@@ -144,6 +144,7 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
144
144
  } | null | undefined;
145
145
  };
146
146
  }>;
147
+ source_input_signature?: string | null | undefined;
147
148
  }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
148
149
  createdAt: NativeDate;
149
150
  updatedAt: NativeDate;
@@ -259,6 +260,7 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
259
260
  } | null | undefined;
260
261
  };
261
262
  }>;
263
+ source_input_signature?: string | null | undefined;
262
264
  }>> & import("mongoose").FlatRecord<{
263
265
  createdAt: NativeDate;
264
266
  updatedAt: NativeDate;
@@ -374,6 +376,7 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
374
376
  } | null | undefined;
375
377
  };
376
378
  }>;
379
+ source_input_signature?: string | null | undefined;
377
380
  }> & Required<{
378
381
  _id: import("mongoose").Types.ObjectId;
379
382
  }> & {
@@ -267,6 +267,15 @@ exports.MaterializedTenantSalesOverviewReportSchema = new mongoose_1.Schema({
267
267
  type: mongoose_1.Schema.Types.Date,
268
268
  required: true,
269
269
  },
270
+ // Day-input digest (`v1:<count>:<hash>`) — the SET-shaped half of change
271
+ // detection. A delete / move can lower the incoming watermark; the digest
272
+ // changes instead, so the close still performs the corrective writes.
273
+ // Optional: documents written before it existed are rewritten once.
274
+ source_input_signature: {
275
+ type: String,
276
+ required: false,
277
+ default: undefined,
278
+ },
270
279
  computed_at: {
271
280
  type: mongoose_1.Schema.Types.Date,
272
281
  required: true,
@@ -19,6 +19,7 @@ export declare const TenantActiveJobSchema: Schema<any, import("mongoose").Model
19
19
  failed_jobs: string[];
20
20
  started_at: NativeDate;
21
21
  last_heartbeat_at: NativeDate;
22
+ lease_id?: string | null | undefined;
22
23
  }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
23
24
  createdAt: NativeDate;
24
25
  updatedAt: NativeDate;
@@ -35,6 +36,7 @@ export declare const TenantActiveJobSchema: Schema<any, import("mongoose").Model
35
36
  failed_jobs: string[];
36
37
  started_at: NativeDate;
37
38
  last_heartbeat_at: NativeDate;
39
+ lease_id?: string | null | undefined;
38
40
  }>> & import("mongoose").FlatRecord<{
39
41
  createdAt: NativeDate;
40
42
  updatedAt: NativeDate;
@@ -51,6 +53,7 @@ export declare const TenantActiveJobSchema: Schema<any, import("mongoose").Model
51
53
  failed_jobs: string[];
52
54
  started_at: NativeDate;
53
55
  last_heartbeat_at: NativeDate;
56
+ lease_id?: string | null | undefined;
54
57
  }> & Required<{
55
58
  _id: import("mongoose").Types.ObjectId;
56
59
  }> & {
@@ -30,6 +30,14 @@ exports.TenantActiveJobSchema = new mongoose_1.Schema({
30
30
  enum: constants_1.ALL_TENANT_ACTIVE_JOBS_NAMES,
31
31
  default: null,
32
32
  },
33
+ // Fencing token of the current owner — fresh per acquisition. Updates,
34
+ // completion and failure filter on it so a stale owner cannot touch the
35
+ // job after a takeover. `null` when the job is free.
36
+ lease_id: {
37
+ type: String,
38
+ required: false,
39
+ default: null,
40
+ },
33
41
  failed_jobs: {
34
42
  type: [String],
35
43
  enum: constants_1.ALL_TENANT_ACTIVE_JOBS_NAMES,
@@ -132,6 +132,12 @@ export interface IMaterializedTenantCreditBillsReport {
132
132
  schema_version: number;
133
133
  /** Max source `orders.updatedAt` folded into this document. */
134
134
  source_watermark: Date;
135
+ /**
136
+ * Day-input digest (`v1:<count>:<hash>`, see
137
+ * `buildMaterializedDayInputSignature`) — the SET-shaped half of change
138
+ * detection. Optional: legacy documents are re-materialized once.
139
+ */
140
+ source_input_signature?: string;
135
141
  /** When the materializer last rebuilt this document. */
136
142
  computed_at: Date;
137
143
  createdAt: Date;
@@ -201,6 +201,12 @@ export interface IMaterializedTenantDiscountReport {
201
201
  schema_version: number;
202
202
  /** Max source `orders.updatedAt` folded into this document. */
203
203
  source_watermark: Date;
204
+ /**
205
+ * Day-input digest (`v1:<count>:<hash>`, see
206
+ * `buildMaterializedDayInputSignature`) — the SET-shaped half of change
207
+ * detection. Optional: legacy documents are re-materialized once.
208
+ */
209
+ source_input_signature?: string;
204
210
  /** When the materializer last rebuilt this document. */
205
211
  computed_at: Date;
206
212
  createdAt: Date;
@@ -20,6 +20,15 @@ import { IMaterializedTenantSalesOverviewReport } from './materialized_tenant_sa
20
20
  * Rows are append-only: a replay rewrites the SAME `(report_id, iteration)`
21
21
  * row (idempotent), and a rollback re-applies an older snapshot as a NEW
22
22
  * versioned write (with its own row) — the audit trail is never rewritten.
23
+ *
24
+ * COVERAGE (explicit decision — see `MATERIALIZED_REPORTS.md`, “History
25
+ * coverage matrix”): history exists for REPORT documents (the versioned metric
26
+ * carriers: overview date/hour/period, credit ledger, discount counters,
27
+ * discount entries). Derived projections (`materialized_tenant_discount_sources`,
28
+ * `materialized_report_drilldown_rows` / `..._scopes`) are rebuilt from their
29
+ * parent documents in the SAME transaction and deliberately have no
30
+ * independent history. Document DELETES are not updates: the last snapshot row
31
+ * remains as the final state and is never removed.
23
32
  */
24
33
  /**
25
34
  * Every materialized report document shape a history row can snapshot —
@@ -197,6 +197,20 @@ export interface IMaterializedTenantSalesOverviewReport {
197
197
  * detection and watermark-guarded upserts.
198
198
  */
199
199
  source_watermark: Date;
200
+ /**
201
+ * Deterministic digest of the exact order set (`id|updatedAt`) the document
202
+ * was compiled from (`v1:<count>:<hash>`; see
203
+ * `buildMaterializedDayInputSignature`).
204
+ *
205
+ * Change detection uses BOTH signals: the watermark only advances, so a
206
+ * delete / move that lowers the day's max `updatedAt` would otherwise be
207
+ * skipped and leave the removed order's numbers in the reports. A different
208
+ * signature forces the corrective writes even when the watermark regresses.
209
+ *
210
+ * Optional for backward compatibility: documents written before the field
211
+ * existed read as "unknown" and are re-materialized once by the guard.
212
+ */
213
+ source_input_signature?: string;
200
214
  /** When the materializer last rebuilt this document. */
201
215
  computed_at: Date;
202
216
  createdAt: Date;
@@ -5,6 +5,14 @@ export interface ITenantActiveJob {
5
5
  localDate: string;
6
6
  jobs_status: Record<TENANT_ACTIVE_JOBS_ENUM, boolean>;
7
7
  active_job: TENANT_ACTIVE_JOBS_ENUM | null;
8
+ /**
9
+ * Fencing token of the CURRENT owner: generated fresh on every acquisition
10
+ * (and on a stale takeover / explicit reset). Every progress update,
11
+ * completion and failure must match `tenant_id + lease_id`; an owner whose
12
+ * lease was taken over gets a `LeaseLostError` instead of mutating the new
13
+ * run's job. `null` when no run owns the job.
14
+ */
15
+ lease_id?: string | null;
8
16
  failed_jobs: TENANT_ACTIVE_JOBS_ENUM[];
9
17
  progress: number;
10
18
  started_at: Date | null;
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const materialized_day_input_signature_1 = require("../../helpers/materialized-reports/materialized-day-input-signature");
4
+ const materialized_credit_bills_helpers_1 = require("../../helpers/materialized-reports/materialized-credit-bills-helpers");
5
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
6
+ const order = (id, updatedAt, isDeleted = false) => ({
7
+ _id: id,
8
+ tenant_id: 'tenant-1',
9
+ is_deleted: isDeleted,
10
+ updatedAt: new Date(updatedAt),
11
+ });
12
+ describe('materialized day-input signature', () => {
13
+ it('is deterministic, order-independent and versioned', () => {
14
+ const a = order('a', '2026-09-10T10:00:00.000Z');
15
+ const b = order('b', '2026-09-10T11:00:00.000Z');
16
+ const first = (0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)([a, b]);
17
+ expect(first).toBe((0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)([b, a]));
18
+ expect(first).toMatch(new RegExp(`^${materialized_day_input_signature_1.MATERIALIZED_DAY_INPUT_SIGNATURE_VERSION}:2:[0-9a-f]{16}$`));
19
+ // A repeat of the same object list is stable (re-closes must not churn).
20
+ expect((0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)([a, b])).toBe(first);
21
+ });
22
+ it('changes when the SET changes (delete) or a member version changes', () => {
23
+ const a = order('a', '2026-09-10T10:00:00.000Z');
24
+ const b = order('b', '2026-09-10T11:00:00.000Z');
25
+ const both = (0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)([a, b]);
26
+ const onlyA = (0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)([a]);
27
+ const aUpdated = (0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)([order('a', '2026-09-10T12:00:00.000Z'), b]);
28
+ expect(onlyA).not.toBe(both);
29
+ expect(aUpdated).not.toBe(both);
30
+ // The count component is a cheap first signal.
31
+ expect(onlyA).toContain(':1:');
32
+ expect(both).toContain(':2:');
33
+ });
34
+ it('has a stable empty value distinct from "no signature"', () => {
35
+ const empty = (0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)([]);
36
+ expect(empty).toBe((0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)([]));
37
+ expect(empty).toContain(':0:');
38
+ expect((0, materialized_day_input_signature_1.materializedDayInputSignatureChanged)(undefined, empty)).toBe(true);
39
+ expect((0, materialized_day_input_signature_1.materializedDayInputSignatureChanged)(undefined, undefined)).toBe(false);
40
+ expect((0, materialized_day_input_signature_1.materializedDayInputSignatureChanged)(empty, empty)).toBe(false);
41
+ expect((0, materialized_day_input_signature_1.materializedDayInputSignatureChanged)(empty, null)).toBe(true);
42
+ expect((0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)(null)).toBeNull();
43
+ });
44
+ it('is not a numeric string, so it cannot trip the integer-only storage contract', () => {
45
+ const signature = (0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)([]);
46
+ expect(Number.isNaN(Number(signature))).toBe(true);
47
+ });
48
+ });
49
+ describe('credit ledger signature guard', () => {
50
+ const doc = (overrides = {}) => ({
51
+ _id: 'credit-1',
52
+ tenant_id: 'tenant-1',
53
+ brand_id: 'brand-1',
54
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
55
+ scope_field: '2026-09-10',
56
+ day_index: 'THU',
57
+ sale_type_key_filters: ['ORDER_STATUS', 'PLATFORM'],
58
+ credit_bills: {},
59
+ iteration: 1,
60
+ schema_version: 1,
61
+ source_watermark: new Date('2026-09-10T20:00:00.000Z'),
62
+ source_input_signature: 'v1:2:aaaaaaaaaaaaaaaa',
63
+ computed_at: new Date('2026-09-10T21:00:00.000Z'),
64
+ createdAt: new Date('2026-09-10T21:00:00.000Z'),
65
+ updatedAt: new Date('2026-09-10T21:00:00.000Z'),
66
+ ...overrides,
67
+ });
68
+ it('forces a write when the digest changed even if the watermark regressed', () => {
69
+ const stored = doc();
70
+ const incoming = doc({
71
+ source_watermark: new Date('2026-09-10T10:00:00.000Z'),
72
+ source_input_signature: 'v1:1:bbbbbbbbbbbbbbbb',
73
+ });
74
+ expect((0, materialized_credit_bills_helpers_1.needsMaterializedCreditBillsReportWrite)(stored, incoming)).toBe(true);
75
+ });
76
+ it('keeps the watermark path for an unchanged digest', () => {
77
+ const stored = doc();
78
+ expect((0, materialized_credit_bills_helpers_1.needsMaterializedCreditBillsReportWrite)(stored, doc({ source_watermark: new Date('2026-09-10T10:00:00.000Z') }))).toBe(false);
79
+ expect((0, materialized_credit_bills_helpers_1.needsMaterializedCreditBillsReportWrite)(stored, doc({ source_watermark: new Date('2026-09-10T22:00:00.000Z') }))).toBe(true);
80
+ });
81
+ });
@@ -624,3 +624,92 @@ describe('materialized discounts — close-day plan', () => {
624
624
  expect({ month: monthRows(state), dayRows }).toEqual({ month: dayRows, dayRows });
625
625
  });
626
626
  });
627
+ /**
628
+ * DAY-INPUT SIGNATURE + PERIOD REPAIR for the discount COUNTER documents.
629
+ *
630
+ * The counter guard is watermark-based for UPDATEs, which cannot see an order
631
+ * being DELETED: the removed order may have carried the day's maximum
632
+ * `updatedAt`, so the incoming watermark regresses and the correction would be
633
+ * skipped. The compiled documents now carry the input-set digest and the guard
634
+ * checks it first.
635
+ */
636
+ describe('materialized discounts — signature change detection + period repair', () => {
637
+ const signatureDoc = (overrides = {}) => ({
638
+ _id: 'sig-doc',
639
+ tenant_id: TENANT,
640
+ brand_id: BRAND,
641
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
642
+ scope_field: '2026-09-13',
643
+ day_index: 'SUN',
644
+ sale_type_key_filters: [
645
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS,
646
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM,
647
+ ],
648
+ discount_counters: null,
649
+ discount_counter_rows: null,
650
+ top_sources: null,
651
+ schema_version: 1,
652
+ iteration: 1,
653
+ source_watermark: new Date('2026-09-13T20:00:00.000Z'),
654
+ source_input_signature: 'v1:2:aaaaaaaaaaaaaaaa',
655
+ computed_at: new Date('2026-09-13T21:00:00.000Z'),
656
+ createdAt: new Date('2026-09-13T21:00:00.000Z'),
657
+ updatedAt: new Date('2026-09-13T21:00:00.000Z'),
658
+ ...overrides,
659
+ });
660
+ it('asks for a write when the input-set digest changed, even on a lower watermark', () => {
661
+ const stored = signatureDoc();
662
+ const deletedMaxOrder = signatureDoc({
663
+ source_watermark: new Date('2026-09-13T10:00:00.000Z'), // regressed
664
+ source_input_signature: 'v1:1:bbbbbbbbbbbbbbbb',
665
+ });
666
+ expect((0, materialized_discount_close_day_helpers_1.needsMaterializedDiscountReportWrite)(stored, deletedMaxOrder)).toBe(true);
667
+ // Same digest + older watermark + same schema → no write (no churn).
668
+ const unchangedOlder = signatureDoc({
669
+ source_watermark: new Date('2026-09-13T10:00:00.000Z'),
670
+ });
671
+ expect((0, materialized_discount_close_day_helpers_1.needsMaterializedDiscountReportWrite)(stored, unchangedOlder)).toBe(false);
672
+ });
673
+ it('rebuilds a MISSING period counter document from the sibling day counters', () => {
674
+ const counter = (count) => ({ COMPLETED_POS_TABLE: { count } });
675
+ const compiledDay = signatureDoc({
676
+ _id: 'compiled-day',
677
+ scope_field: '2026-09-21',
678
+ source_input_signature: 'v1:1:cccccccccccccccc',
679
+ discount_counters: counter(1),
680
+ });
681
+ const month = (field, docId) => signatureDoc({
682
+ _id: docId,
683
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
684
+ scope_field: '2026-09',
685
+ discount_counters: counter(1),
686
+ });
687
+ // Only the day's own date document exists as a sibling (D1 is in the same
688
+ // month but a different week); the month document was lost.
689
+ const siblingDay = signatureDoc({
690
+ _id: 'sibling-day',
691
+ scope_field: '2026-09-07',
692
+ discount_counters: counter(2),
693
+ });
694
+ const plan = (0, materialized_discount_close_day_helpers_1.buildTenantDiscountCloseDayPlan)({
695
+ tenantId: TENANT,
696
+ localDate: '2026-09-21',
697
+ reports: [compiledDay, month('month-compiled', 'compiled-month')],
698
+ entries: [],
699
+ existing: [],
700
+ existingEntries: [],
701
+ existingEntriesComplete: true,
702
+ existingPeriodDayDocuments: [siblingDay],
703
+ reason: 'TEST_RECLOSE',
704
+ computedAt: new Date('2026-09-22T00:00:00.000Z'),
705
+ });
706
+ expect(plan).not.toBeNull();
707
+ expect(plan.foldedPeriodDayDocuments).toBeGreaterThanOrEqual(1);
708
+ const monthWrite = plan.writes.find((write) => write.report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
709
+ expect(monthWrite).toBeDefined();
710
+ const counters = monthWrite.report.discount_counters;
711
+ // 2 (sibling D1) + 1 (closing day) — the lost period is repaired, not reseeded.
712
+ expect(counters.COMPLETED_POS_TABLE.count).toBe(3);
713
+ expect(monthWrite.report.iteration).toBe(1);
714
+ });
715
+ });