@managesome/eposmatic-toolkit 0.4.28 → 0.4.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +9 -12
  2. package/esm/helpers/materialized-reports/index.js +2 -0
  3. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +178 -40
  4. package/esm/helpers/materialized-reports/materialized-day-input-signature.js +103 -0
  5. package/esm/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  6. package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +299 -227
  7. package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +20 -1
  8. package/esm/helpers/materialized-reports/materialized-discount-source-helpers.js +176 -0
  9. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +64 -0
  10. package/esm/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  11. package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  12. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  13. package/esm/helpers/materialized-reports/scope-helpers.js +27 -0
  14. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +400 -46
  15. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +28 -6
  16. package/esm/schemas/models/materialized_credit_bills.js +8 -0
  17. package/esm/schemas/models/materialized_report_drilldown_rows.js +39 -12
  18. package/esm/schemas/models/materialized_tenant_discount_entries.js +18 -12
  19. package/esm/schemas/models/materialized_tenant_discount_reports.js +9 -0
  20. package/esm/schemas/models/materialized_tenant_discount_sources.js +1 -1
  21. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
  22. package/esm/schemas/models/orders.js +5 -0
  23. package/esm/schemas/models/tenant_active_jobs.js +8 -0
  24. package/esm/schemas/models/tenant_calendar.js +12 -0
  25. package/lib/constants/MATERIALIZED_REPORTS.d.ts +9 -12
  26. package/lib/constants/MATERIALIZED_REPORTS.js +11 -14
  27. package/lib/helpers/materialized-reports/index.d.ts +2 -0
  28. package/lib/helpers/materialized-reports/index.js +2 -0
  29. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +66 -2
  30. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +179 -39
  31. package/lib/helpers/materialized-reports/materialized-day-input-signature.d.ts +66 -0
  32. package/lib/helpers/materialized-reports/materialized-day-input-signature.js +108 -0
  33. package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  34. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +41 -60
  35. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +298 -226
  36. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.d.ts +4 -4
  37. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +19 -0
  38. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.d.ts +17 -0
  39. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +178 -0
  40. package/lib/helpers/materialized-reports/materialized-index-bootstrap.d.ts +7 -0
  41. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +68 -0
  42. package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +3 -1
  43. package/lib/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  44. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.d.ts +2 -2
  45. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  46. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  47. package/lib/helpers/materialized-reports/scope-helpers.d.ts +22 -0
  48. package/lib/helpers/materialized-reports/scope-helpers.js +28 -0
  49. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +49 -3
  50. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +398 -44
  51. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +4 -1
  52. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +28 -6
  53. package/lib/schemas/models/materialized_credit_bills.d.ts +3 -0
  54. package/lib/schemas/models/materialized_credit_bills.js +8 -0
  55. package/lib/schemas/models/materialized_report_drilldown_rows.d.ts +40 -6
  56. package/lib/schemas/models/materialized_report_drilldown_rows.js +39 -12
  57. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +33 -29
  58. package/lib/schemas/models/materialized_tenant_discount_entries.js +18 -12
  59. package/lib/schemas/models/materialized_tenant_discount_reports.d.ts +3 -0
  60. package/lib/schemas/models/materialized_tenant_discount_reports.js +9 -0
  61. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +6 -6
  62. package/lib/schemas/models/materialized_tenant_discount_sources.js +1 -1
  63. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +3 -0
  64. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
  65. package/lib/schemas/models/orders.d.ts +5 -0
  66. package/lib/schemas/models/orders.js +5 -0
  67. package/lib/schemas/models/tenant_active_jobs.d.ts +3 -0
  68. package/lib/schemas/models/tenant_active_jobs.js +8 -0
  69. package/lib/schemas/models/tenant_calendar.d.ts +13 -0
  70. package/lib/schemas/models/tenant_calendar.js +13 -1
  71. package/lib/schemas/types/materialized_credit_bills.d.ts +6 -0
  72. package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +8 -0
  73. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +9 -5
  74. package/lib/schemas/types/materialized_tenant_discount_reports.d.ts +6 -0
  75. package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +9 -0
  76. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +14 -0
  77. package/lib/schemas/types/tenant_active_jobs.d.ts +8 -0
  78. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +56 -1
  79. package/lib/tests/materialized-reports/materialized-day-input-signature.test.d.ts +1 -0
  80. package/lib/tests/materialized-reports/materialized-day-input-signature.test.js +81 -0
  81. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +17 -0
  82. package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +148 -53
  83. package/lib/tests/materialized-reports/materialized-discount-entries-accumulation.test.js +14 -13
  84. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +76 -0
  85. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +11 -0
  86. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +2 -2
  87. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +311 -4
  88. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +89 -0
  89. package/package.json +1 -1
@@ -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,
@@ -16870,6 +16870,11 @@ export declare const ORDERS_COLLECTION_INDEXES: {
16870
16870
  localDate: number;
16871
16871
  createdAt: number;
16872
16872
  };
16873
+ tenant_id__is_deleted__order_settled_at: {
16874
+ tenant_id: number;
16875
+ is_deleted: number;
16876
+ order_settled_at: number;
16877
+ };
16873
16878
  tenant_id__is_deleted__consumer_phone__createdAt: {
16874
16879
  tenant_id: number;
16875
16880
  is_deleted: number;
@@ -1038,6 +1038,11 @@ exports.ORDERS_COLLECTION_INDEXES = {
1038
1038
  localDate: 1,
1039
1039
  createdAt: -1,
1040
1040
  }, // partial index (partialFilterExpression: { localDate: { $exists: true } }) — per-tenant local-date order lookups filtered by is_deleted, newest first
1041
+ tenant_id__is_deleted__order_settled_at: {
1042
+ tenant_id: 1,
1043
+ is_deleted: 1,
1044
+ order_settled_at: -1,
1045
+ }, // deployed settlement-window index — prior-day credit bills collected in a day's window
1041
1046
  tenant_id__is_deleted__consumer_phone__createdAt: {
1042
1047
  tenant_id: 1,
1043
1048
  is_deleted: 1,
@@ -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,
@@ -85,3 +85,16 @@ export declare const TENANT_CALENDAR_COLLECTION_INDEXES: {
85
85
  localYear: number;
86
86
  };
87
87
  };
88
+ /**
89
+ * Index OPTIONS the bootstrapper must create. `tenant_calendar` has no report
90
+ * history, but it DOES need the unique (tenant_id, localYear) invariant: a
91
+ * concurrent/retried upsert must never create a second year document.
92
+ */
93
+ export declare const TENANT_CALENDAR_INDEX_OPTIONS: {
94
+ key: {
95
+ tenant_id: number;
96
+ localYear: number;
97
+ };
98
+ name: string;
99
+ unique: boolean;
100
+ }[];
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TENANT_CALENDAR_COLLECTION_INDEXES = exports.TENANT_CALENDAR_COLLECTION_NAME = exports.TenantCalendarSchema = void 0;
3
+ exports.TENANT_CALENDAR_INDEX_OPTIONS = exports.TENANT_CALENDAR_COLLECTION_INDEXES = exports.TENANT_CALENDAR_COLLECTION_NAME = exports.TenantCalendarSchema = void 0;
4
4
  const mongoose_1 = require("mongoose");
5
5
  const TenantCalendarDaySchema = new mongoose_1.Schema({
6
6
  total_orders: {
@@ -90,3 +90,15 @@ exports.TENANT_CALENDAR_COLLECTION_INDEXES = {
90
90
  _id: { _id: 1 }, // Unique Index
91
91
  tenant_id__localYear: { tenant_id: 1, localYear: -1 }, // unique per (tenant_id, localYear)
92
92
  };
93
+ /**
94
+ * Index OPTIONS the bootstrapper must create. `tenant_calendar` has no report
95
+ * history, but it DOES need the unique (tenant_id, localYear) invariant: a
96
+ * concurrent/retried upsert must never create a second year document.
97
+ */
98
+ exports.TENANT_CALENDAR_INDEX_OPTIONS = [
99
+ {
100
+ key: { tenant_id: 1, localYear: -1 },
101
+ name: 'tenant_id__localYear',
102
+ unique: true,
103
+ },
104
+ ];
@@ -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;
@@ -38,6 +38,12 @@ export interface IMaterializedReportDrilldownRow {
38
38
  time: Date;
39
39
  /** The original row payload, unchanged. */
40
40
  data: Record<string, unknown>;
41
+ /**
42
+ * The business day this row's contribution belongs to. Day/hour rows equal
43
+ * their own day; period rows equal the day whose close added them. Added for
44
+ * incremental flat rebuilds; legacy rows may be null until a guarded rebuild.
45
+ */
46
+ source_local_date?: string | null;
41
47
  schema_version: number;
42
48
  computed_at: Date;
43
49
  createdAt?: Date;
@@ -57,6 +63,8 @@ export interface IMaterializedReportDrilldownScope {
57
63
  scope_field: string;
58
64
  row_count: number;
59
65
  off_app_order_count: number;
66
+ /** Last day whose close updated this scope (migration/audit marker). */
67
+ source_local_date?: string | null;
60
68
  schema_version: number;
61
69
  computed_at: Date;
62
70
  createdAt?: Date;
@@ -5,9 +5,10 @@ import { MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM, MATERIALIZED_DISCOUNT_LEVEL_ENUM
5
5
  * discount rows behind the discounts report's drill-down (owner decision (a):
6
6
  * SPLIT — the report documents hold counters only).
7
7
  *
8
- * ONE document per (tenant, scope context, scope value), scopes CAPPED AT
9
- * `LOCAL_MONTH` (`MATERIALIZED_DISCOUNT_REPORT_SCOPES`) so a month bounds how
10
- * many rows a document accumulates. Each document carries a per-key map
8
+ * ONE PAGE per (tenant, scope context, scope value, source day), scopes CAPPED
9
+ * AT `LOCAL_MONTH` (`MATERIALIZED_DISCOUNT_REPORT_SCOPES`). Day/hour scopes use
10
+ * `page = 'all'`; a period scope uses `page = <source localDate>`, so every
11
+ * document is bounded by one day's rows. Each page carries a per-key map
11
12
  * `discount_entries: { [sale_type_key]: { rows: [...] } }` — the same
12
13
  * `ORDER_STATUS:PLATFORM` key grammar as every materialized report, so platform
13
14
  * / status filters apply to the rows too.
@@ -93,8 +94,9 @@ export interface IMaterializedDiscountKeySection {
93
94
  rows: IMaterializedDiscountEntry[];
94
95
  }
95
96
  /**
96
- * One `materialized_tenant_discount_entries` document — tenant × scope context ×
97
- * scope value, month-capped.
97
+ * One `materialized_tenant_discount_entries` PAGE — tenant × scope context ×
98
+ * scope value × source day. Day/hour pages use `page = 'all'`; period pages use
99
+ * the source `localDate`, so a month is bounded by its days.
98
100
  */
99
101
  export interface IMaterializedTenantDiscountEntries {
100
102
  _id: string;
@@ -102,6 +104,8 @@ export interface IMaterializedTenantDiscountEntries {
102
104
  brand_id: string;
103
105
  scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
104
106
  scope_field: string;
107
+ /** `'all'` for day/hour scopes; source `YYYY-MM-DD` for period scopes. */
108
+ page: string;
105
109
  day_index?: DAY_INDEX_ENUM | null;
106
110
  sale_type_key_filters: MATERIALIZED_REPORT_KEY_FILTER_ENUM[];
107
111
  discount_entries: Record<string, IMaterializedDiscountKeySection> | null;
@@ -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;
@@ -254,6 +254,60 @@ describe('resolveCreditBillDay (delta resolution + carry-forward + settlements)'
254
254
  issued_local_hour: '2026-10-01 20',
255
255
  });
256
256
  });
257
+ it('patches the STORED issue section when the order status changed (status drift)', () => {
258
+ const oldKey = `COMPLETED:POS_WALK-IN`;
259
+ const stored = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-01', {
260
+ [oldKey]: { issued: [issuedEntry()], received: [] },
261
+ });
262
+ // The order is now DELIVERED; the collection candidate's current key is
263
+ // DELIVERED:POS_WALK-IN while the issue entry lives under COMPLETED.
264
+ const resolution = expectNonNull((0, materialized_credit_bills_helpers_1.resolveCreditBillDay)({
265
+ tenantId: TENANT,
266
+ localDate: '2026-10-03',
267
+ issued: [],
268
+ events: [
269
+ makeEventCandidate({
270
+ order_status: constants_1.ORDER_STATUS_ENUM.DELIVERED,
271
+ candidate_cumulative: 1000,
272
+ }),
273
+ ],
274
+ stored: [stored],
275
+ computedAt: NOW,
276
+ }));
277
+ expect(resolution.settled_bills[0].stored_key).toBe(oldKey);
278
+ const patched = expectNonNull((0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(stored, { settled_bills: resolution.settled_bills }, { computedAt: NOW }));
279
+ expect(patched.credit_bills?.[oldKey]?.issued[0]).toMatchObject({
280
+ received_amount: 1000,
281
+ settled_local_date: '2026-10-03',
282
+ });
283
+ expect(patched.credit_bills?.[`DELIVERED:POS_WALK-IN`]).toBeUndefined();
284
+ expect(patched.iteration).toBe(2);
285
+ });
286
+ it('updates the SAME bill cumulative for a PARTIAL receipt (no second receivable)', () => {
287
+ const stored = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-01', {
288
+ [KEY]: { issued: [issuedEntry()], received: [] },
289
+ });
290
+ const resolution = expectNonNull((0, materialized_credit_bills_helpers_1.resolveCreditBillDay)({
291
+ tenantId: TENANT,
292
+ localDate: '2026-10-03',
293
+ issued: [],
294
+ events: [makeEventCandidate({ candidate_cumulative: 400 })],
295
+ stored: [stored],
296
+ computedAt: NOW,
297
+ }));
298
+ expect(resolution.settled_bills).toEqual([]);
299
+ expect(resolution.receipt_bills).toHaveLength(1);
300
+ const patched = expectNonNull((0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(stored, { receipt_bills: resolution.receipt_bills }, { computedAt: NOW }));
301
+ expect(patched.credit_bills?.[KEY]?.issued).toHaveLength(1);
302
+ expect(patched.credit_bills?.[KEY]?.issued[0]).toMatchObject({
303
+ amount: 1000,
304
+ received_amount: 400,
305
+ settled_at: null,
306
+ });
307
+ // Replaying the same receipt is idempotent — no new bill, no new iteration.
308
+ const replay = expectNonNull((0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(patched, { receipt_bills: resolution.receipt_bills }, { computedAt: NOW }));
309
+ expect(replay.iteration).toBe(patched.iteration);
310
+ });
257
311
  it('keeps a stored same-day delta and never re-emits a settled transition (idempotent re-close)', () => {
258
312
  const stored = makeCreditDoc(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, '2026-10-03', {
259
313
  [KEY]: {
@@ -342,6 +396,7 @@ describe('buildMaterializedCreditBillDayReports (month-capped scopes)', () => {
342
396
  },
343
397
  ],
344
398
  settled_bills: [],
399
+ receipt_bills: [],
345
400
  };
346
401
  it('materializes hour/date/week/ISO-week/month documents with the entries on every scope', () => {
347
402
  const docs = expectNonNull((0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillDayReports)({
@@ -381,7 +436,7 @@ describe('buildMaterializedCreditBillDayReports (month-capped scopes)', () => {
381
436
  tenantId: TENANT,
382
437
  brandId: 'brand-1',
383
438
  localDate: '2026-10-01',
384
- resolution: { issued: [], received_events: [], settled_bills: [] },
439
+ resolution: { issued: [], received_events: [], settled_bills: [], receipt_bills: [] },
385
440
  computedAt: NOW,
386
441
  }));
387
442
  expect(docs).toEqual([]);
@@ -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
+ });
@@ -266,6 +266,23 @@ describe('materialized discounts — sub-kind classifier (synthesized coverage)'
266
266
  expect(resolved.perSlot.get(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SLOT_ENUM.SPECIAL)).toBe(580);
267
267
  expect(resolved.unallocated).toBe(0);
268
268
  });
269
+ it('caps several FIXED slots at the headline instead of over-allocating', () => {
270
+ const details = {
271
+ special_discount: 500,
272
+ special_discount_id: 'MANUAL_Rs 500',
273
+ is_special_discount_percentage: false,
274
+ loyalty_discount: 300,
275
+ loyalty_discount_id: '6aa472763689e5f08dd0599f',
276
+ is_loyalty_discount_percentage: false,
277
+ total_discount: 600,
278
+ };
279
+ const resolved = (0, materialized_discount_classification_helpers_1.resolveRowMoney)(details, 600);
280
+ expect(resolved.perSlot.get(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SLOT_ENUM.SPECIAL)).toBe(500);
281
+ expect(resolved.perSlot.get(MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_SLOT_ENUM.LOYALTY)).toBe(100);
282
+ expect(resolved.allocated).toBe(600);
283
+ expect(resolved.unallocated).toBe(0);
284
+ expect(resolved.row_total).toBe(600);
285
+ });
269
286
  it('books money with NO usable slot as unattributed (never dropped)', () => {
270
287
  const details = { total_discount: 8717.5 };
271
288
  const resolved = (0, materialized_discount_classification_helpers_1.resolveRowMoney)(details, 8717.5);