@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
@@ -10,6 +10,7 @@ exports.needsMaterializedDiscountEntriesWrite = needsMaterializedDiscountEntries
10
10
  exports.buildTenantDiscountCloseDayPlan = buildTenantDiscountCloseDayPlan;
11
11
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
12
12
  const materialized_tenant_reports_iterations_helpers_1 = require("./materialized-tenant-reports-iterations-helpers");
13
+ const materialized_day_input_signature_1 = require("./materialized-day-input-signature");
13
14
  const scope_helpers_1 = require("./scope-helpers");
14
15
  /** Day-scoped documents (replaced wholesale for the compiled day). */
15
16
  const DISCOUNT_DAY_SCOPES = [
@@ -172,7 +173,9 @@ function getMaterializedDiscountPeriodDayScopeFields(localDate) {
172
173
  /**
173
174
  * Watermark guard: does the stored document need a structural write?
174
175
  * `false` (skip) when the incoming `source_watermark` is not newer than the
175
- * stored one and the schema version + key grammar match.
176
+ * stored one, the day-input SIGNATURE is unchanged, and the schema version +
177
+ * key grammar match. The signature catches a deleted / moved order whose
178
+ * removal lowered the incoming watermark.
176
179
  */
177
180
  function needsMaterializedDiscountReportWrite(existing, incoming) {
178
181
  if (existing == null || incoming == null)
@@ -182,6 +185,9 @@ function needsMaterializedDiscountReportWrite(existing, incoming) {
182
185
  if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
183
186
  return true;
184
187
  }
188
+ if ((0, materialized_day_input_signature_1.materializedDayInputSignatureChanged)(existing.source_input_signature, incoming.source_input_signature)) {
189
+ return true;
190
+ }
185
191
  const existingTime = new Date(existing.source_watermark ?? 0).getTime();
186
192
  const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
187
193
  if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
@@ -283,6 +289,9 @@ function updateMaterializedDiscountReport(existing, updates, options = {}) {
283
289
  // step with it — one source of truth, so the map and the rows can never
284
290
  // disagree (and a correction that empties a key drops it from both).
285
291
  discount_counter_rows: finalCounters == null ? null : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
292
+ // A REPLACEMENT carries the freshly compiled day digest; period folds keep
293
+ // the stored value (their payload is a running sum, not one day's input).
294
+ source_input_signature: updates.replacement?.source_input_signature ?? existing.source_input_signature,
286
295
  source_watermark: sourceWatermark,
287
296
  computed_at: computedAt,
288
297
  updatedAt: computedAt,
@@ -484,6 +493,7 @@ function buildTenantDiscountCloseDayPlan(input) {
484
493
  const skippedDocuments = [];
485
494
  const skippedEntryDocuments = [];
486
495
  const createdPeriodDocuments = [];
496
+ let foldedPeriodDayDocuments = 0;
487
497
  const addWrite = (report) => {
488
498
  const persisted = report.iteration == null ? { ...report, iteration: 1 } : report;
489
499
  const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(persisted, {
@@ -594,6 +604,7 @@ function buildTenantDiscountCloseDayPlan(input) {
594
604
  skippedDocuments,
595
605
  skippedEntryDocuments,
596
606
  createdPeriodDocuments,
607
+ foldedPeriodDayDocuments,
597
608
  };
598
609
  }
599
610
  const dayChanged = force || needsMaterializedDiscountReportWrite(storedDateDoc, storedDateDocInCompiled);
@@ -625,7 +636,56 @@ function buildTenantDiscountCloseDayPlan(input) {
625
636
  if (!isAccumulatedScope(compiled.scope_context))
626
637
  return null; // unknown scope
627
638
  if (existing == null) {
628
- if (addWrite(compiled) == null)
639
+ // Missing period counter document: rebuild it from the sibling DAY
640
+ // counters that belong to this exact scope (plus the compiled day), so
641
+ // the period equals the sum of its days again. The closing day's own
642
+ // stored date document is excluded by the input contract.
643
+ const referenceDoc = storedDateDocInCompiled ?? reports[0];
644
+ const siblings = (input.existingPeriodDayDocuments ?? []).filter((doc) => {
645
+ if (doc == null || doc.tenant_id !== tenantId)
646
+ return false;
647
+ if (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
648
+ return false;
649
+ if (typeof doc.scope_field !== 'string' || doc.scope_field === localDate)
650
+ return false;
651
+ if (doc.schema_version !== referenceDoc.schema_version)
652
+ return false;
653
+ if ((doc.sale_type_key_filters ?? []).join(':') !== (referenceDoc.sale_type_key_filters ?? []).join(':')) {
654
+ return false;
655
+ }
656
+ const refs = getMaterializedDiscountScopeRefsForDay(doc.scope_field);
657
+ return (refs != null &&
658
+ refs.some((ref) => ref.scope_context === compiled.scope_context && ref.scope_field === compiled.scope_field));
659
+ });
660
+ let created = compiled;
661
+ if (siblings.length > 0) {
662
+ const counters = JSON.parse(JSON.stringify(compiled.discount_counters ?? {}));
663
+ let watermark = new Date(compiled.source_watermark);
664
+ for (const sibling of siblings) {
665
+ applyCounters(counters, sibling.discount_counters, 1);
666
+ const siblingWatermark = new Date(sibling.source_watermark);
667
+ if (siblingWatermark.getTime() > watermark.getTime())
668
+ watermark = siblingWatermark;
669
+ }
670
+ for (const key of Object.keys(counters)) {
671
+ if (isZeroCounters(counters[key]))
672
+ delete counters[key];
673
+ }
674
+ const finalCounters = Object.keys(counters).length === 0
675
+ ? null
676
+ : counters;
677
+ created = {
678
+ ...compiled,
679
+ discount_counters: finalCounters,
680
+ discount_counter_rows: finalCounters == null
681
+ ? null
682
+ : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
683
+ source_watermark: watermark,
684
+ iteration: 1,
685
+ };
686
+ foldedPeriodDayDocuments += siblings.length;
687
+ }
688
+ if (addWrite(created) == null)
629
689
  return null;
630
690
  createdPeriodDocuments.push({ scope_context: compiled.scope_context, scope_field: compiled.scope_field });
631
691
  continue;
@@ -757,5 +817,6 @@ function buildTenantDiscountCloseDayPlan(input) {
757
817
  skippedDocuments,
758
818
  skippedEntryDocuments,
759
819
  createdPeriodDocuments,
820
+ foldedPeriodDayDocuments,
760
821
  };
761
822
  }
@@ -10,6 +10,7 @@ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
10
10
  const materialized_discount_accumulator_helpers_1 = require("./materialized-discount-accumulator-helpers");
11
11
  const materialized_discount_classification_helpers_1 = require("./materialized-discount-classification-helpers");
12
12
  const key_helpers_1 = require("./key-helpers");
13
+ const materialized_day_input_signature_1 = require("./materialized-day-input-signature");
13
14
  const scope_helpers_1 = require("./scope-helpers");
14
15
  const materialized_credit_bills_helpers_1 = require("./materialized-credit-bills-helpers");
15
16
  /** Adds every numeric field of `source` into `target`, recursively. */
@@ -60,6 +61,16 @@ function compileTenantDiscountReports(input) {
60
61
  if (periodFields == null)
61
62
  return null;
62
63
  const dayIndex = (0, scope_helpers_1.getDayIndexFromLocalDate)(localDate);
64
+ // Day-input digest: the discount counter documents are guarded by a
65
+ // watermark that only advances, so deleting / moving the order with the
66
+ // highest `updatedAt` would otherwise skip the correction and leave its
67
+ // discount behind. The digest covers EVERY order the day compiled (a removed
68
+ // non-discount order changes nothing, but rewriting one document is cheaper
69
+ // than a missed correction). Computed once — the same value is stamped on
70
+ // every scope document of the day.
71
+ const sourceInputSignature = (0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)(orders.filter((order) => order != null &&
72
+ order.is_deleted === false &&
73
+ (order.tenant_id == null || String(order.tenant_id) === tenantId))) ?? undefined;
63
74
  // DERIVED from the report's scope list (as prep / cash / delivery do). This used to be a
64
75
  // second, hand-maintained copy of the same four scopes - so widening the report's scopes
65
76
  // compiled the new ones nowhere and the documents silently never appeared.
@@ -86,6 +97,12 @@ function compileTenantDiscountReports(input) {
86
97
  for (const order of orders) {
87
98
  if (order == null)
88
99
  continue;
100
+ // DELETED orders never contribute (defence in depth: the worker loader
101
+ // already filters `is_deleted: false`, but the compile is also used by the
102
+ // live adapter and by tests — a deleted order must never re-appear through
103
+ // a caller passing a wider query).
104
+ if (order.is_deleted !== false)
105
+ continue;
89
106
  // Only orders of this tenant compile into this tenant's documents.
90
107
  if (order.tenant_id != null && String(order.tenant_id) !== tenantId)
91
108
  continue;
@@ -161,6 +178,7 @@ function compileTenantDiscountReports(input) {
161
178
  top_sources: null,
162
179
  schema_version: 1,
163
180
  source_watermark: docWatermark,
181
+ source_input_signature: sourceInputSignature,
164
182
  computed_at: computedAt,
165
183
  createdAt: computedAt,
166
184
  updatedAt: computedAt,
@@ -55,3 +55,25 @@ export declare function getMaterializedPeriodScopeFields(localDate: string): IMa
55
55
  * hour.
56
56
  */
57
57
  export declare function getMaterializedHourScopeField(localDate: string, hour: number): string | null;
58
+ /** Inclusive `YYYY-MM-DD` range of day documents that can belong to a date's periods. */
59
+ export interface IMaterializedPeriodDayScopeRange {
60
+ gte: string;
61
+ lte: string;
62
+ }
63
+ /**
64
+ * The `scope_field` RANGE a close must scan to find every stored `localDate`
65
+ * document that can share a period with `localDate` — used to REPAIR a missing
66
+ * period document from its sibling days (a period is a running sum; creating it
67
+ * from the closing day alone would make it disagree with the sum of the day
68
+ * documents).
69
+ *
70
+ * This is a deliberately generous SUPERSET: the ISO week / calendar week of a
71
+ * date can start in the previous calendar year (e.g. `2027-01-01` belongs to
72
+ * `2026-W53`), and the calendar week can extend into the next one. Membership
73
+ * is decided afterwards by comparing each candidate's
74
+ * `getMaterializedPeriodScopeFields` / scope refs to the created period; the
75
+ * range only bounds the query (one indexed range scan, no `$in` of 366 keys).
76
+ *
77
+ * Returns `null` (never throws) for a malformed date.
78
+ */
79
+ export declare function getMaterializedPeriodDayScopeRange(localDate: string): IMaterializedPeriodDayScopeRange | null;
@@ -5,6 +5,7 @@ exports.getIsoWeekYear = getIsoWeekYear;
5
5
  exports.getDayIndexFromLocalDate = getDayIndexFromLocalDate;
6
6
  exports.getMaterializedPeriodScopeFields = getMaterializedPeriodScopeFields;
7
7
  exports.getMaterializedHourScopeField = getMaterializedHourScopeField;
8
+ exports.getMaterializedPeriodDayScopeRange = getMaterializedPeriodDayScopeRange;
8
9
  const ENUMS_1 = require("../../constants/ENUMS");
9
10
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
10
11
  const time_helpers_1 = require("../utils/time-helpers");
@@ -112,3 +113,30 @@ function getMaterializedHourScopeField(localDate, hour) {
112
113
  return null;
113
114
  return `${localDate} ${pad(hour)}`;
114
115
  }
116
+ /**
117
+ * The `scope_field` RANGE a close must scan to find every stored `localDate`
118
+ * document that can share a period with `localDate` — used to REPAIR a missing
119
+ * period document from its sibling days (a period is a running sum; creating it
120
+ * from the closing day alone would make it disagree with the sum of the day
121
+ * documents).
122
+ *
123
+ * This is a deliberately generous SUPERSET: the ISO week / calendar week of a
124
+ * date can start in the previous calendar year (e.g. `2027-01-01` belongs to
125
+ * `2026-W53`), and the calendar week can extend into the next one. Membership
126
+ * is decided afterwards by comparing each candidate's
127
+ * `getMaterializedPeriodScopeFields` / scope refs to the created period; the
128
+ * range only bounds the query (one indexed range scan, no `$in` of 366 keys).
129
+ *
130
+ * Returns `null` (never throws) for a malformed date.
131
+ */
132
+ function getMaterializedPeriodDayScopeRange(localDate) {
133
+ const parts = parseMaterializedLocalDate(localDate);
134
+ if (parts == null)
135
+ return null;
136
+ const { year } = parts;
137
+ const toKey = (date) => `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;
138
+ return {
139
+ gte: toKey(new Date(Date.UTC(year, 0, 1 - 7))),
140
+ lte: toKey(new Date(Date.UTC(year, 11, 31 + 7))),
141
+ };
142
+ }
@@ -92,6 +92,27 @@ export interface IBuildTenantSalesOverviewCloseDayPlanInput {
92
92
  * one scope key → `null`.
93
93
  */
94
94
  existingCreditBills?: IMaterializedTenantCreditBillsReport[];
95
+ /**
96
+ * Stored `localDate` documents of the SAME tenant (any day of the year,
97
+ * excluding the closing day), fetched by the job so a MISSING period
98
+ * document can be rebuilt from the days that were already materialized.
99
+ *
100
+ * Why: a period document is a running sum, so creating it from the closing
101
+ * day alone would make `localMonth` disagree with the SUM of the month's
102
+ * `localDate` documents whenever the document is missing (a partial failure
103
+ * between the history and the period write, a manual delete, a backfill).
104
+ * The plan folds the sibling days that BELONG to the created scope, so the
105
+ * period equals the sum of its days again. Days that were never
106
+ * materialized have no document and contribute nothing — the same answer the
107
+ * day-level read gives, so the two scopes stay equivalent.
108
+ */
109
+ existingPeriodDayDocuments?: IMaterializedTenantSalesOverviewReport[];
110
+ /**
111
+ * Stored `localDate` `materialized_tenant_credit_bills` documents of the
112
+ * same tenant, used to rebuild a missing credit PERIOD document from the
113
+ * sibling days (same contract as `existingPeriodDayDocuments`).
114
+ */
115
+ existingPeriodDayCreditDocuments?: IMaterializedTenantCreditBillsReport[];
95
116
  /** Force structural writes even when the watermarks are up to date. */
96
117
  force?: boolean;
97
118
  /** Override for write timestamps (tests, replays). */
@@ -149,6 +170,20 @@ export interface ITenantSalesOverviewCloseDayPlan {
149
170
  * when the day is not the period's first materialized close.
150
171
  */
151
172
  createdPeriodDocuments: IMaterializedReportScopeRef[];
173
+ /**
174
+ * How many stored sibling DAY documents were folded into period documents
175
+ * this close CREATED (see `existingPeriodDayDocuments`). 0 means either no
176
+ * period document was created or the period genuinely had no materialized
177
+ * earlier day; a non-zero value means a missing period document was REPAIRED
178
+ * from the day level instead of being seeded with the closing day alone.
179
+ */
180
+ foldedPeriodDayDocuments: number;
181
+ /**
182
+ * Same repair count for `materialized_tenant_credit_bills` period documents
183
+ * rebuilt from the sibling days (see
184
+ * `existingPeriodDayCreditDocuments`).
185
+ */
186
+ foldedPeriodDayCreditDocuments: number;
152
187
  }
153
188
  /** `(scope_context, scope_field)` pair of a stored / compiled document. */
154
189
  export interface IMaterializedReportScopeRef {
@@ -167,9 +202,12 @@ export declare function getMaterializedTenantSalesOverviewScopeRefsForDay(localD
167
202
  * structural write for the incoming compiled version?
168
203
  *
169
204
  * `false` (skip) when the incoming `source_watermark` is not newer than the
170
- * stored one and the schema version + key-filter grammar match. Watermarks are
171
- * monotonic (`updateMaterializedTenantSalesOverviewReport` never regresses
172
- * them). A missing stored document always needs a write.
205
+ * stored one, the day-input SIGNATURE is unchanged, and the schema version +
206
+ * key-filter grammar match. Watermarks are monotonic
207
+ * (`updateMaterializedTenantSalesOverviewReport` never regresses them); the
208
+ * signature is the SET-shaped signal that detects a deleted / moved order even
209
+ * when the incoming watermark is lower than the stored one. A missing stored
210
+ * document always needs a write.
173
211
  */
174
212
  export declare function needsMaterializedTenantSalesOverviewReportWrite(existing: IMaterializedTenantSalesOverviewReport | null | undefined, incoming: IMaterializedTenantSalesOverviewReport | null | undefined): boolean;
175
213
  /**
@@ -7,6 +7,7 @@ const constants_1 = require("../../constants");
7
7
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
8
8
  const materialized_credit_bills_helpers_1 = require("./materialized-credit-bills-helpers");
9
9
  const materialized_tenant_reports_iterations_helpers_1 = require("./materialized-tenant-reports-iterations-helpers");
10
+ const materialized_day_input_signature_1 = require("./materialized-day-input-signature");
10
11
  const scope_helpers_1 = require("./scope-helpers");
11
12
  const tenant_sales_overview_helpers_1 = require("./tenant-sales-overview-helpers");
12
13
  /** Scopes written wholesale for the compiled day (replacement semantics). */
@@ -55,9 +56,12 @@ function getMaterializedTenantSalesOverviewScopeRefsForDay(localDate) {
55
56
  * structural write for the incoming compiled version?
56
57
  *
57
58
  * `false` (skip) when the incoming `source_watermark` is not newer than the
58
- * stored one and the schema version + key-filter grammar match. Watermarks are
59
- * monotonic (`updateMaterializedTenantSalesOverviewReport` never regresses
60
- * them). A missing stored document always needs a write.
59
+ * stored one, the day-input SIGNATURE is unchanged, and the schema version +
60
+ * key-filter grammar match. Watermarks are monotonic
61
+ * (`updateMaterializedTenantSalesOverviewReport` never regresses them); the
62
+ * signature is the SET-shaped signal that detects a deleted / moved order even
63
+ * when the incoming watermark is lower than the stored one. A missing stored
64
+ * document always needs a write.
61
65
  */
62
66
  function needsMaterializedTenantSalesOverviewReportWrite(existing, incoming) {
63
67
  if (existing == null || incoming == null)
@@ -67,6 +71,11 @@ function needsMaterializedTenantSalesOverviewReportWrite(existing, incoming) {
67
71
  if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
68
72
  return true;
69
73
  }
74
+ // Set-shaped signal FIRST: a delete / move must correct even when the
75
+ // incoming watermark regressed below the stored one.
76
+ if ((0, materialized_day_input_signature_1.materializedDayInputSignatureChanged)(existing.source_input_signature, incoming.source_input_signature)) {
77
+ return true;
78
+ }
70
79
  const existingTime = new Date(existing.source_watermark ?? 0).getTime();
71
80
  const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
72
81
  if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
@@ -125,6 +134,37 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
125
134
  if (String(prior._id) !== String(doc._id))
126
135
  return null;
127
136
  }
137
+ // REPAIR SOURCE: stored sibling DAY documents, used only when a period
138
+ // document has to be CREATED. A period is a running sum, so seeding it with
139
+ // the closing day alone would leave every earlier materialized day out of
140
+ // the period while its `localDate` document still exists (month ≠ Σ days).
141
+ // The closing day itself is excluded: the freshly compiled day replaces it.
142
+ const periodDayDocuments = [];
143
+ const periodDayDocumentsByField = new Map();
144
+ for (const doc of input.existingPeriodDayDocuments ?? []) {
145
+ if (doc == null || doc.tenant_id !== tenantId)
146
+ continue;
147
+ if (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
148
+ continue;
149
+ if (typeof doc.scope_field !== 'string' || doc.scope_field === localDate)
150
+ continue;
151
+ // A day document from another schema version / brand cannot be summed
152
+ // (`sumMaterialized…` would return null and fail the whole close); it is
153
+ // ignored here and re-materialized by its own close.
154
+ if (doc.schema_version !== compiledDateDoc.schema_version)
155
+ continue;
156
+ if ((doc.sale_type_key_filters ?? []).join(':') !== (compiledDateDoc.sale_type_key_filters ?? []).join(':')) {
157
+ continue;
158
+ }
159
+ if (doc.brand_id !== compiledDateDoc.brand_id)
160
+ continue;
161
+ periodDayDocumentsByField.set(doc.scope_field, doc);
162
+ periodDayDocuments.push(doc);
163
+ }
164
+ const dayDocumentBelongsToScope = (doc, scopeContext, scopeField) => {
165
+ const refs = getMaterializedTenantSalesOverviewScopeRefsForDay(doc.scope_field);
166
+ return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
167
+ };
128
168
  // ------------------------------------------------------------------
129
169
  // Resolve THIS day against the stored credit ledger documents — the only
130
170
  // stateful step (receipt deltas, carried anchors, settlements), executed
@@ -225,6 +265,8 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
225
265
  const writes = [];
226
266
  const skippedDocuments = [];
227
267
  const createdPeriodDocuments = [];
268
+ let foldedPeriodDayDocuments = 0;
269
+ let foldedPeriodDayCreditDocuments = 0;
228
270
  const addStructuralWrite = (report) => {
229
271
  const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(report, {
230
272
  reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
@@ -261,9 +303,26 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
261
303
  if (!CLOSE_DAY_ACCUMULATED_SCOPES.includes(compiledDoc.scope_context))
262
304
  return null; // unknown scope — data issue
263
305
  if (existing == null) {
264
- if (dayDeltaEmpty)
265
- continue; // nothing to fold into a (new) period document
266
- if (!addStructuralWrite(compiledDoc))
306
+ // Missing period document: REPAIR it from the stored sibling days that
307
+ // belong to this exact scope, then add the closing day. Without the fold
308
+ // the period would hold only this close's delta while the earlier days'
309
+ // `localDate` documents still exist — `localMonth` would no longer equal
310
+ // the sum of its days.
311
+ const siblings = periodDayDocuments.filter((doc) => dayDocumentBelongsToScope(doc, compiledDoc.scope_context, compiledDoc.scope_field));
312
+ // An order-less close still repairs a missing period when sibling days
313
+ // exist; with no deltas and no siblings there is nothing to create.
314
+ if (dayDeltaEmpty && siblings.length === 0)
315
+ continue;
316
+ let createdReport = compiledDoc;
317
+ if (siblings.length > 0) {
318
+ createdReport = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)([compiledDoc, ...siblings], {
319
+ computedAt,
320
+ });
321
+ if (createdReport == null)
322
+ return null; // inconsistent sibling — data issue
323
+ foldedPeriodDayDocuments += siblings.length;
324
+ }
325
+ if (createdReport == null || !addStructuralWrite(createdReport))
267
326
  return null;
268
327
  createdPeriodDocuments.push({
269
328
  scope_context: compiledDoc.scope_context,
@@ -366,9 +425,38 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
366
425
  localDate,
367
426
  resolution: creditResolution,
368
427
  computedAt,
428
+ sourceInputSignature: compiledDateDoc.source_input_signature ?? null,
369
429
  });
370
430
  if (creditCompiledDocs == null)
371
431
  return null;
432
+ // REPAIR SOURCE for missing credit PERIOD documents — the stored sibling
433
+ // DAY documents (the closing day is replaced by the compiled one). Mirrors
434
+ // the sales-overview fold above; without it a recreated month document would
435
+ // hold only this close's bills while the other days' date documents exist.
436
+ const creditPeriodDayDocuments = [];
437
+ // The credit collection has its OWN schema version / key grammar — compare
438
+ // siblings against a compiled CREDIT document, never the overview envelope.
439
+ const creditReferenceDoc = creditCompiledDocs[0] ?? null;
440
+ for (const doc of input.existingPeriodDayCreditDocuments ?? []) {
441
+ if (creditReferenceDoc == null)
442
+ break;
443
+ if (doc == null || doc.tenant_id !== tenantId)
444
+ continue;
445
+ if (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
446
+ continue;
447
+ if (typeof doc.scope_field !== 'string' || doc.scope_field === localDate)
448
+ continue;
449
+ if (doc.schema_version !== creditReferenceDoc.schema_version)
450
+ continue;
451
+ if (JSON.stringify(doc.sale_type_key_filters ?? []) !== JSON.stringify(creditReferenceDoc.sale_type_key_filters ?? [])) {
452
+ continue;
453
+ }
454
+ creditPeriodDayDocuments.push(doc);
455
+ }
456
+ const creditDayDocumentBelongsToScope = (doc, scopeContext, scopeField) => {
457
+ const refs = (0, materialized_credit_bills_helpers_1.getMaterializedCreditBillScopeRefsForDay)(doc.scope_field);
458
+ return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
459
+ };
372
460
  const creditExistingByScope = new Map();
373
461
  for (const doc of input.existingCreditBills ?? []) {
374
462
  if (doc == null || doc.tenant_id !== tenantId)
@@ -461,7 +549,30 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
461
549
  if (!creditAccumulatedScopes.includes(compiledCreditDoc.scope_context))
462
550
  return null; // unknown scope — data issue
463
551
  if (existing == null) {
464
- if (!addCreditWrite(compiledCreditDoc))
552
+ // Missing period document: rebuild it from the sibling DAY documents
553
+ // that belong to this exact scope (the closing day is the compiled
554
+ // document), so the ledger stays equal to the sum of its days.
555
+ const siblings = creditPeriodDayDocuments.filter((doc) => creditDayDocumentBelongsToScope(doc, compiledCreditDoc.scope_context, compiledCreditDoc.scope_field));
556
+ let created = compiledCreditDoc;
557
+ if (siblings.length > 0) {
558
+ const sections = {};
559
+ (0, materialized_credit_bills_helpers_1.mergeMaterializedCreditBillSections)(sections, compiledCreditDoc.credit_bills);
560
+ let watermark = new Date(compiledCreditDoc.source_watermark);
561
+ for (const sibling of siblings) {
562
+ (0, materialized_credit_bills_helpers_1.mergeMaterializedCreditBillSections)(sections, sibling.credit_bills);
563
+ const siblingWatermark = new Date(sibling.source_watermark);
564
+ if (siblingWatermark.getTime() > watermark.getTime())
565
+ watermark = siblingWatermark;
566
+ }
567
+ created = {
568
+ ...compiledCreditDoc,
569
+ credit_bills: sections,
570
+ source_watermark: watermark,
571
+ iteration: 1,
572
+ };
573
+ foldedPeriodDayCreditDocuments += siblings.length;
574
+ }
575
+ if (!addCreditWrite(created))
465
576
  return null;
466
577
  continue;
467
578
  }
@@ -538,5 +649,7 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
538
649
  creditSkippedDocuments,
539
650
  skippedDocuments,
540
651
  createdPeriodDocuments,
652
+ foldedPeriodDayDocuments,
653
+ foldedPeriodDayCreditDocuments,
541
654
  };
542
655
  }
@@ -226,7 +226,10 @@ export interface IUpdateMaterializedTenantSalesOverviewReportInput {
226
226
  * so replays stay churn-free;
227
227
  * 4. `source_watermark` advances to the max of the existing and the incoming
228
228
  * (`replacement` / `additions`) watermarks — monotonic, never regressed
229
- * (rollbacks / replays keep the previously folded maximum).
229
+ * (rollbacks / replays keep the previously folded maximum);
230
+ * 5. `source_input_signature` follows a `replacement` (the fresh day compile)
231
+ * and is KEPT on period accumulates — a period's payload is a running sum,
232
+ * not one day's input set.
230
233
  *
231
234
  * Returns a new JSON report; the input is not mutated.
232
235
  */
@@ -18,6 +18,7 @@ const constants_1 = require("../../constants");
18
18
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
19
19
  const materialized_tenant_sales_overview_reports_1 = require("../../schemas/models/materialized_tenant_sales_overview_reports");
20
20
  const key_helpers_1 = require("./key-helpers");
21
+ const materialized_day_input_signature_1 = require("./materialized-day-input-signature");
21
22
  const materialized_credit_bills_helpers_1 = require("./materialized-credit-bills-helpers");
22
23
  Object.defineProperty(exports, "isMaterializedCreditBillPayment", { enumerable: true, get: function () { return materialized_credit_bills_helpers_1.isMaterializedCreditBillPayment; } });
23
24
  const scope_helpers_1 = require("./scope-helpers");
@@ -519,13 +520,26 @@ function convertOrdersToMaterializedTenantSalesOverviewReports(localDate, orders
519
520
  // `source_watermark` = max `order.updatedAt` folded in; a day with no
520
521
  // orders folds nothing → epoch. Stable across recompiles, so the
521
522
  // watermark guard skips unchanged (order-less) days instead of churning.
522
- const watermark = tenantOrders.reduce((latest, order) => {
523
+ //
524
+ // `source_input_signature` is the SET-shaped companion: the watermark only
525
+ // advances, so a delete / move that removes the maximum-`updatedAt` order
526
+ // would leave the incoming watermark LOWER than the stored one and the
527
+ // guard would skip the correction. The digest changes with the input set,
528
+ // so the close is still applied. Both are computed from the SAME
529
+ // `tenantOrders` array the compile consumed.
530
+ // Both change-detection signals describe the orders this day ACTUALLY
531
+ // materializes: a deleted order must never keep the day "fresh" (or
532
+ // contribute a watermark the remaining orders cannot reproduce).
533
+ const consideredOrders = tenantOrders.filter((order) => order.is_deleted === false);
534
+ const watermark = consideredOrders.reduce((latest, order) => {
523
535
  const updatedAt = new Date(order.updatedAt ?? now);
524
536
  return updatedAt.getTime() > latest.getTime() ? updatedAt : latest;
525
537
  }, new Date(0));
538
+ const sourceInputSignature = (0, materialized_day_input_signature_1.buildMaterializedDayInputSignature)(consideredOrders) ?? undefined;
526
539
  for (const { doc, metrics } of [...periodDocs, ...hourDocs.values()]) {
527
540
  doc.sale_type_metrics = finalizeMetrics(metrics);
528
541
  doc.source_watermark = watermark;
542
+ doc.source_input_signature = sourceInputSignature;
529
543
  materializedReports.push(doc);
530
544
  }
531
545
  }
@@ -749,7 +763,10 @@ function subtractMaterializedTenantSalesOverviewReports(minuend, subtrahend) {
749
763
  * so replays stay churn-free;
750
764
  * 4. `source_watermark` advances to the max of the existing and the incoming
751
765
  * (`replacement` / `additions`) watermarks — monotonic, never regressed
752
- * (rollbacks / replays keep the previously folded maximum).
766
+ * (rollbacks / replays keep the previously folded maximum);
767
+ * 5. `source_input_signature` follows a `replacement` (the fresh day compile)
768
+ * and is KEPT on period accumulates — a period's payload is a running sum,
769
+ * not one day's input set.
753
770
  *
754
771
  * Returns a new JSON report; the input is not mutated.
755
772
  */
@@ -807,6 +824,11 @@ function updateMaterializedTenantSalesOverviewReport(existing, updates, options
807
824
  // Reconcile artifacts: a fully-subtracted key is pruned so accumulated
808
825
  // period documents keep the same key set as day / hour reads.
809
826
  sale_type_metrics: pruneZeroReportKeys(finalizeMetrics(metrics)),
827
+ // The day-input digest travels with a REPLACEMENT write (the freshly
828
+ // compiled day/hour document) so the next close can compare it. Period
829
+ // accumulates keep the stored value: their payload is a running sum, not
830
+ // one day's input set.
831
+ source_input_signature: updates.replacement?.source_input_signature ?? existing.source_input_signature,
810
832
  // Version metric writes AND ledger-changing received-payment patches (both
811
833
  // append a history row via the caller). No-op patches bump nothing, so
812
834
  // replays stay churn-free.
@@ -109,6 +109,7 @@ export declare const MaterializedTenantCreditBillsReportSchema: Schema<any, impo
109
109
  schema_version: number;
110
110
  source_watermark: NativeDate;
111
111
  computed_at: NativeDate;
112
+ source_input_signature?: string | null | undefined;
112
113
  }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
113
114
  createdAt: NativeDate;
114
115
  updatedAt: NativeDate;
@@ -196,6 +197,7 @@ export declare const MaterializedTenantCreditBillsReportSchema: Schema<any, impo
196
197
  schema_version: number;
197
198
  source_watermark: NativeDate;
198
199
  computed_at: NativeDate;
200
+ source_input_signature?: string | null | undefined;
199
201
  }>> & import("mongoose").FlatRecord<{
200
202
  createdAt: NativeDate;
201
203
  updatedAt: NativeDate;
@@ -283,6 +285,7 @@ export declare const MaterializedTenantCreditBillsReportSchema: Schema<any, impo
283
285
  schema_version: number;
284
286
  source_watermark: NativeDate;
285
287
  computed_at: NativeDate;
288
+ source_input_signature?: string | null | undefined;
286
289
  }> & Required<{
287
290
  _id: import("mongoose").Types.ObjectId;
288
291
  }> & {
@@ -204,6 +204,14 @@ exports.MaterializedTenantCreditBillsReportSchema = new mongoose_1.Schema({
204
204
  type: mongoose_1.Schema.Types.Date,
205
205
  required: true,
206
206
  },
207
+ // Day-input digest (`v1:<count>:<hash>`) — set-shaped change detection
208
+ // for the credit ledger, mirroring the sales-overview reports. A deleted /
209
+ // moved order must remove its bill even when the watermark regresses.
210
+ source_input_signature: {
211
+ type: String,
212
+ required: false,
213
+ default: undefined,
214
+ },
207
215
  computed_at: {
208
216
  type: mongoose_1.Schema.Types.Date,
209
217
  required: true,
@@ -61,6 +61,7 @@ export declare const MaterializedTenantDiscountReportSchema: Schema<any, import(
61
61
  sub_kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SUB_KIND_ENUM;
62
62
  resolved_amount: number;
63
63
  }>;
64
+ source_input_signature?: string | null | undefined;
64
65
  discount_counters?: any;
65
66
  discount_counter_rows?: any;
66
67
  }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
@@ -99,6 +100,7 @@ export declare const MaterializedTenantDiscountReportSchema: Schema<any, import(
99
100
  sub_kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SUB_KIND_ENUM;
100
101
  resolved_amount: number;
101
102
  }>;
103
+ source_input_signature?: string | null | undefined;
102
104
  discount_counters?: any;
103
105
  discount_counter_rows?: any;
104
106
  }>> & import("mongoose").FlatRecord<{
@@ -137,6 +139,7 @@ export declare const MaterializedTenantDiscountReportSchema: Schema<any, import(
137
139
  sub_kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SUB_KIND_ENUM;
138
140
  resolved_amount: number;
139
141
  }>;
142
+ source_input_signature?: string | null | undefined;
140
143
  discount_counters?: any;
141
144
  discount_counter_rows?: any;
142
145
  }> & Required<{
@@ -210,6 +210,15 @@ exports.MaterializedTenantDiscountReportSchema = new mongoose_1.Schema({
210
210
  type: mongoose_1.Schema.Types.Date,
211
211
  required: true,
212
212
  },
213
+ // Day-input digest (`v1:<count>:<hash>`) — set-shaped change detection
214
+ // for the discount counters, mirroring the sales-overview reports. A
215
+ // deleted / moved order must remove its discount even when the watermark
216
+ // regresses.
217
+ source_input_signature: {
218
+ type: String,
219
+ required: false,
220
+ default: undefined,
221
+ },
213
222
  computed_at: {
214
223
  type: mongoose_1.Schema.Types.Date,
215
224
  required: true,