@managesome/eposmatic-toolkit 0.4.28 → 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 (45) 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/tenant-sales-overview-close-day-helpers.test.js +162 -0
  45. 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
+ });
@@ -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.28",
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",