@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
@@ -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 = [
@@ -25,6 +26,7 @@ const DISCOUNT_ACCUMULATED_SCOPES = MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT
25
26
  /** True for the accumulating (period) scopes. */
26
27
  const isAccumulatedScope = (scope) => DISCOUNT_ACCUMULATED_SCOPES.includes(scope);
27
28
  const scopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
29
+ const entryPageKey = (doc) => `${scopeKey(doc)}|${doc.page}`;
28
30
  /** Every stored scope one local day's plan needs (date + 3 periods + 24 hours). */
29
31
  function getMaterializedDiscountScopeRefsForDay(localDate) {
30
32
  const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
@@ -45,15 +47,12 @@ function getMaterializedDiscountScopeRefsForDay(localDate) {
45
47
  return refs;
46
48
  }
47
49
  /* ------------------------------------------------------------------------ */
48
- /* Period sibling-day enumeration (the close-day fetch contract) */
50
+ /* Period sibling-day enumeration for COUNTER repair only */
49
51
  /* ------------------------------------------------------------------------ */
50
52
  const pad2 = (value) => String(value).padStart(2, '0');
51
- /** `'YYYY-MM-DD'` of a UTC calendar date. */
52
53
  const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
53
- /** Adds whole days to a UTC calendar date. */
54
54
  const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
55
55
  const daysInUtcMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
56
- /** Adds every day of `count` whole months starting at (year, month). */
57
56
  const addMonthDays = (year, month, count, days) => {
58
57
  for (let offset = 0; offset < count; offset += 1) {
59
58
  const date = new Date(Date.UTC(year, month - 1 + offset, 1));
@@ -66,17 +65,9 @@ const addMonthDays = (year, month, count, days) => {
66
65
  }
67
66
  return true;
68
67
  };
69
- /**
70
- * Adds the day labels covered by ONE stored period scope value to `days`.
71
- *
72
- * Returns `false` (never throws) for a malformed / non-canonical scope value —
73
- * a caller must not silently treat an unparseable period as "no sibling days",
74
- * because that would make the `existingEntriesComplete` acknowledgement lie.
75
- */
76
68
  const addPeriodDays = (scope, scopeField, days) => {
77
69
  switch (scope) {
78
70
  case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
79
- // Sunday-based week start (the `localWeek` bucket identity).
80
71
  const parts = (0, scope_helpers_1.parseMaterializedLocalDate)(scopeField);
81
72
  if (parts == null)
82
73
  return false;
@@ -88,7 +79,6 @@ const addPeriodDays = (scope, scopeField, days) => {
88
79
  return true;
89
80
  }
90
81
  case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
91
- // ISO week: the week-year may differ from the calendar year at boundaries.
92
82
  const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
93
83
  if (match == null)
94
84
  return false;
@@ -96,7 +86,6 @@ const addPeriodDays = (scope, scopeField, days) => {
96
86
  const week = Number(match[2]);
97
87
  if (!Number.isInteger(week) || week < 1 || week > 53)
98
88
  return false;
99
- // ISO week 1 always contains Jan 4; its Monday is the week-1 Monday.
100
89
  const jan4 = new Date(Date.UTC(weekYear, 0, 4));
101
90
  const isoWeekday = jan4.getUTCDay() || 7;
102
91
  const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
@@ -138,22 +127,9 @@ const addPeriodDays = (scope, scopeField, days) => {
138
127
  }
139
128
  };
140
129
  /**
141
- * Every `localDate` day label whose day-scoped ENTRY documents can belong to the
142
- * periods the closing day rolls into (`week`, ISO week, month — whatever
143
- * `MATERIALIZED_DISCOUNT_REPORT_SCOPES` accumulates).
144
- *
145
- * This is the **sibling-day fetch contract** in code: a close caller must fetch
146
- * every `localDate` entry document whose `scope_field` is in this set, in
147
- * addition to the day's own scope refs. Period entry documents are DERIVED from
148
- * day rows, so a period document that was never persisted can only be rebuilt
149
- * from the sibling days — without them the plan rebuilds the period from the
150
- * closing day alone and every other day silently disappears from the period
151
- * drill-down (see `buildTenantDiscountCloseDayPlan`).
152
- *
153
- * The returned set always contains `localDate` itself and is sorted. Returns
154
- * `null` (never throws) for a malformed date or an unparseable period value —
155
- * a `null` means the caller must fail loudly rather than pass an incomplete
156
- * `existingEntries` set with `existingEntriesComplete: true`.
130
+ * Every `localDate` label whose day-scoped COUNTER documents can belong to the
131
+ * periods the closing day rolls into. Used ONLY to repair a missing period
132
+ * counter; entry pages are keyed by the closed day and never use this set.
157
133
  */
158
134
  function getMaterializedDiscountPeriodDayScopeFields(localDate) {
159
135
  const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
@@ -172,7 +148,9 @@ function getMaterializedDiscountPeriodDayScopeFields(localDate) {
172
148
  /**
173
149
  * Watermark guard: does the stored document need a structural write?
174
150
  * `false` (skip) when the incoming `source_watermark` is not newer than the
175
- * stored one and the schema version + key grammar match.
151
+ * stored one, the day-input SIGNATURE is unchanged, and the schema version +
152
+ * key grammar match. The signature catches a deleted / moved order whose
153
+ * removal lowered the incoming watermark.
176
154
  */
177
155
  function needsMaterializedDiscountReportWrite(existing, incoming) {
178
156
  if (existing == null || incoming == null)
@@ -182,6 +160,9 @@ function needsMaterializedDiscountReportWrite(existing, incoming) {
182
160
  if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
183
161
  return true;
184
162
  }
163
+ if ((0, materialized_day_input_signature_1.materializedDayInputSignatureChanged)(existing.source_input_signature, incoming.source_input_signature)) {
164
+ return true;
165
+ }
185
166
  const existingTime = new Date(existing.source_watermark ?? 0).getTime();
186
167
  const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
187
168
  if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
@@ -220,6 +201,36 @@ function isZeroCounters(counters) {
220
201
  }
221
202
  return true;
222
203
  }
204
+ /** Sums a compiled period counter with sibling DAY counters (repair path). */
205
+ function buildDiscountCounterReplacement(existing, compiled, siblings) {
206
+ const counters = JSON.parse(JSON.stringify(compiled?.discount_counters ?? {}));
207
+ let watermark = new Date(compiled?.source_watermark ?? existing.source_watermark);
208
+ for (const sibling of siblings) {
209
+ if (sibling.schema_version !== existing.schema_version)
210
+ return null;
211
+ if ((sibling.sale_type_key_filters ?? []).join(':') !== (existing.sale_type_key_filters ?? []).join(':')) {
212
+ return null;
213
+ }
214
+ applyCounters(counters, sibling.discount_counters, 1);
215
+ const siblingWatermark = new Date(sibling.source_watermark);
216
+ if (siblingWatermark.getTime() > watermark.getTime())
217
+ watermark = siblingWatermark;
218
+ }
219
+ for (const key of Object.keys(counters)) {
220
+ if (isZeroCounters(counters[key]))
221
+ delete counters[key];
222
+ }
223
+ const finalCounters = Object.keys(counters).length === 0 ? null : counters;
224
+ return {
225
+ ...existing,
226
+ discount_counters: finalCounters,
227
+ discount_counter_rows: finalCounters == null ? null : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
228
+ source_watermark: watermark,
229
+ computed_at: existing.computed_at,
230
+ updatedAt: existing.updatedAt,
231
+ };
232
+ }
233
+ const countDiscountEntryRows = (sections) => Object.values(sections ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
223
234
  /**
224
235
  * Applies a counter update to a stored document: optionally REPLACE the counter
225
236
  * map wholesale, else subtract the given deltas and add the compiled ones. Keys
@@ -283,6 +294,9 @@ function updateMaterializedDiscountReport(existing, updates, options = {}) {
283
294
  // step with it — one source of truth, so the map and the rows can never
284
295
  // disagree (and a correction that empties a key drops it from both).
285
296
  discount_counter_rows: finalCounters == null ? null : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
297
+ // A REPLACEMENT carries the freshly compiled day digest; period folds keep
298
+ // the stored value (their payload is a running sum, not one day's input).
299
+ source_input_signature: updates.replacement?.source_input_signature ?? existing.source_input_signature,
286
300
  source_watermark: sourceWatermark,
287
301
  computed_at: computedAt,
288
302
  updatedAt: computedAt,
@@ -342,23 +356,18 @@ const subtractMaterializedDiscountEntrySections = (stored, removed) => {
342
356
  };
343
357
  exports.subtractMaterializedDiscountEntrySections = subtractMaterializedDiscountEntrySections;
344
358
  /**
345
- * Updates a stored ENTRY document.
359
+ * Updates ONE stored ENTRY PAGE by replacing it with the compiled page. Rows
360
+ * never merge across pages; a source day is the whole truth for its page.
346
361
  *
347
- * - DAY scopes (`localHour` / `localDate`) are REPLACED wholesale: the day's rows
348
- * are the whole truth for that scope.
349
- * - PERIOD scopes (`localWeek` / `localWeekOfYear` / `localMonth`) MERGE, because
350
- * the compile produces only ONE day of rows: replacing would leave the period
351
- * showing just its final day.
352
- *
353
- * Returns null when the documents disagree on schema/scope (a data issue the
354
- * caller must surface).
362
+ * Returns null when the documents disagree on schema/scope/page.
355
363
  */
356
364
  function updateMaterializedDiscountEntries(existing, compiled, options = {}) {
357
365
  if (existing == null || compiled == null)
358
366
  return null;
359
367
  if (existing.schema_version !== compiled.schema_version ||
360
368
  existing.scope_context !== compiled.scope_context ||
361
- existing.scope_field !== compiled.scope_field) {
369
+ existing.scope_field !== compiled.scope_field ||
370
+ existing.page !== compiled.page) {
362
371
  return null;
363
372
  }
364
373
  const computedAt = options.computedAt ?? new Date();
@@ -366,9 +375,8 @@ function updateMaterializedDiscountEntries(existing, compiled, options = {}) {
366
375
  const compiledTime = new Date(compiled.source_watermark ?? 0).getTime();
367
376
  return {
368
377
  ...existing,
369
- discount_entries: options.mergePeriodRows === true
370
- ? (0, exports.mergeMaterializedDiscountEntrySections)(existing.discount_entries, compiled.discount_entries)
371
- : compiled.discount_entries,
378
+ page: compiled.page,
379
+ discount_entries: compiled.discount_entries,
372
380
  source_watermark: compiledTime > existingTime ? compiled.source_watermark : existing.source_watermark,
373
381
  computed_at: computedAt,
374
382
  updatedAt: computedAt,
@@ -381,6 +389,8 @@ function needsMaterializedDiscountEntriesWrite(existing, incoming) {
381
389
  return true;
382
390
  if (existing.schema_version !== incoming.schema_version)
383
391
  return true;
392
+ if (existing.page !== incoming.page)
393
+ return true;
384
394
  if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
385
395
  return true;
386
396
  }
@@ -437,41 +447,46 @@ function buildTenantDiscountCloseDayPlan(input) {
437
447
  if (String(prior._id) !== String(doc._id))
438
448
  return null; // two rows for one scope
439
449
  }
440
- const existingEntriesByScope = new Map();
441
- /**
442
- * Rebuilds a PERIOD entry document's rows from the DAY entry documents still on hand.
443
- *
444
- * Discount period entries ACCUMULATE each day's rows, so a period document that was never
445
- * persisted - a partial failure between the counter writes and the entry writes - would
446
- * otherwise be rebuilt from the CLOSING DAY ALONE, silently dropping every sibling day's
447
- * rows from the period drill-down even though those days' documents are right there. The
448
- * counters already repair this case explicitly; without this, the entries did not.
449
- *
450
- * Only called when the period document is MISSING, so the normal path keeps its
451
- * accumulate-forward behaviour and pays nothing for this.
452
- */
453
- const refoldPeriodEntrySections = (scopeContext, scopeField) => {
454
- let folded = {};
455
- for (const doc of existingEntriesByScope.values()) {
456
- if (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
457
- continue;
458
- const refs = getMaterializedDiscountScopeRefsForDay(String(doc.scope_field));
459
- if (refs == null)
460
- continue;
461
- const belongs = refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
462
- if (!belongs)
463
- continue;
464
- folded = (0, exports.mergeMaterializedDiscountEntrySections)(folded, doc.discount_entries);
465
- }
466
- return folded;
450
+ const existingEntriesByPage = new Map();
451
+ const upperPeriodScopes = [
452
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
453
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
454
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
455
+ ];
456
+ const counterSiblingsForScope = (scopeContext, scopeField, referenceDoc) => {
457
+ const upper = upperPeriodScopes.includes(scopeContext);
458
+ const source = upper
459
+ ? (input.existingPeriodMonthDocuments ?? []).filter((doc) => doc?.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)
460
+ : (input.existingPeriodDayDocuments ?? []);
461
+ return source.filter((doc) => {
462
+ if (doc == null || doc.tenant_id !== tenantId)
463
+ return false;
464
+ if (!upper &&
465
+ (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ||
466
+ typeof doc.scope_field !== 'string' ||
467
+ doc.scope_field === localDate)) {
468
+ return false;
469
+ }
470
+ if (typeof doc.scope_field !== 'string')
471
+ return false;
472
+ if (doc.schema_version !== referenceDoc.schema_version)
473
+ return false;
474
+ if ((doc.sale_type_key_filters ?? []).join(':') !== (referenceDoc.sale_type_key_filters ?? []).join(':')) {
475
+ return false;
476
+ }
477
+ const refs = getMaterializedDiscountScopeRefsForDay(doc.scope_field);
478
+ return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
479
+ });
467
480
  };
468
481
  for (const doc of input.existingEntries ?? []) {
469
482
  if (doc == null || doc.tenant_id !== tenantId)
470
483
  continue;
471
- const key = scopeKey(doc);
472
- const prior = existingEntriesByScope.get(key);
484
+ if (typeof doc.page !== 'string' || doc.page.length === 0)
485
+ return null; // no legacy guess
486
+ const key = entryPageKey(doc);
487
+ const prior = existingEntriesByPage.get(key);
473
488
  if (prior == null) {
474
- existingEntriesByScope.set(key, doc);
489
+ existingEntriesByPage.set(key, doc);
475
490
  continue;
476
491
  }
477
492
  if (String(prior._id) !== String(doc._id))
@@ -484,6 +499,7 @@ function buildTenantDiscountCloseDayPlan(input) {
484
499
  const skippedDocuments = [];
485
500
  const skippedEntryDocuments = [];
486
501
  const createdPeriodDocuments = [];
502
+ let foldedPeriodDayDocuments = 0;
487
503
  const addWrite = (report) => {
488
504
  const persisted = report.iteration == null ? { ...report, iteration: 1 } : report;
489
505
  const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(persisted, {
@@ -510,34 +526,57 @@ function buildTenantDiscountCloseDayPlan(input) {
510
526
  };
511
527
  const storedDateDoc = existingByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
512
528
  const storedDateDocInCompiled = compiledByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
513
- // The rows this day CURRENTLY contributes, read from its own day-scoped entry documents.
514
- // A period entry document MERGES day rows in, and a merge can only ADD or OVERWRITE - it
515
- // cannot remove. So any close that replaces this day must subtract these rows from every
516
- // period document first, or rows the correction removed linger there as phantoms while the
517
- // DAY document correctly shrinks. Two callers need this: the emptied-day path (subtract
518
- // everything) and the normal path (subtract, then merge the fresh rows back).
519
- const storedDayEntrySections = {};
520
- const isThisDayEntryDoc = (doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
521
- ? doc.scope_field === localDate
522
- : doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
529
+ // A missing date document on a day with NO day-scoped counter/entry page is
530
+ // a FIRST close (additive). A surviving day page means the date counter was
531
+ // lost on an already-materialized day; period counters still repair by
532
+ // subtraction from the stored date counter.
533
+ const dayWasMaterialized = [...existingByScope.values()].some((doc) => (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
534
+ (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
523
535
  typeof doc.scope_field === 'string' &&
524
- doc.scope_field.startsWith(`${localDate} `);
525
- for (const doc of existingEntriesByScope.values()) {
526
- if (!isThisDayEntryDoc(doc))
527
- continue;
528
- for (const [key, section] of Object.entries(doc.discount_entries ?? {})) {
529
- storedDayEntrySections[key] = {
530
- rows: [...(storedDayEntrySections[key]?.rows ?? []), ...(section?.rows ?? [])],
531
- };
532
- }
533
- }
536
+ doc.scope_field.startsWith(`${localDate} `))) ||
537
+ [...existingEntriesByPage.values()].some((doc) => doc.page === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL &&
538
+ ((doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
539
+ (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
540
+ typeof doc.scope_field === 'string' &&
541
+ doc.scope_field.startsWith(`${localDate} `))));
542
+ const isThisDayEntryPage = (doc) => doc.page === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL &&
543
+ (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
544
+ ? doc.scope_field === localDate
545
+ : doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
546
+ typeof doc.scope_field === 'string' &&
547
+ doc.scope_field.startsWith(`${localDate} `));
534
548
  if (reports.length === 0) {
535
- // The day has NO discounts anymore (orders deleted / moved): subtract the
536
- // stored day from every period document and drop the day's documents.
537
- if (storedDateDoc != null) {
538
- for (const doc of existingByScope.values()) {
539
- if (!isAccumulatedScope(doc.scope_context))
540
- continue;
549
+ // The day has NO discounts anymore (orders deleted / moved). When the date
550
+ // document exists, subtract it; when it is MISSING, rebuild every period
551
+ // from the sibling DAY documents. Never silently leave a stale delta.
552
+ if (storedDateDoc == null && !dayWasMaterialized) {
553
+ const siblings = (input.existingPeriodDayDocuments ?? []).filter((sibling) => sibling?.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && sibling.scope_field !== localDate);
554
+ const hasNonZeroPeriodCounter = [...existingByScope.values()].some((doc) => isAccumulatedScope(doc.scope_context) &&
555
+ !isZeroCounters(doc.discount_counters));
556
+ // A new empty day after earlier days is harmless (zero delta), but a
557
+ // lost date with no day evidence and no sibling proof must not be
558
+ // surfaced as "empty": the old delta may still sit in the periods.
559
+ if (hasNonZeroPeriodCounter && siblings.length === 0)
560
+ return null;
561
+ if (siblings.length === 0) {
562
+ return {
563
+ writes,
564
+ entryWrites,
565
+ staleDocuments,
566
+ staleEntryDocuments,
567
+ skippedDocuments,
568
+ skippedEntryDocuments,
569
+ createdPeriodDocuments,
570
+ foldedPeriodDayDocuments,
571
+ };
572
+ }
573
+ // Fall through: rebuild period counters from the sibling days (the
574
+ // current day contributes nothing), which removes any stale lost delta.
575
+ }
576
+ for (const doc of existingByScope.values()) {
577
+ if (!isAccumulatedScope(doc.scope_context))
578
+ continue;
579
+ if (storedDateDoc != null) {
541
580
  const updated = updateMaterializedDiscountReport(doc, { subtract: [storedDateDoc] }, { computedAt });
542
581
  if (updated == null)
543
582
  return null;
@@ -545,47 +584,43 @@ function buildTenantDiscountCloseDayPlan(input) {
545
584
  continue;
546
585
  if (addWrite(updated) == null)
547
586
  return null;
587
+ continue;
548
588
  }
549
- for (const doc of existingByScope.values()) {
550
- if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
551
- staleDocuments.push(doc);
552
- }
553
- // ENTRY documents. A PERIOD entry document ACCUMULATES every day's rows
554
- // (`updateMaterializedDiscountEntries` merges them in), so DELETING it discards
555
- // every OTHER day it holds - those rows exist nowhere else. The emptied day must
556
- // be SUBTRACTED from each period document, and only the day's OWN documents
557
- // dropped. Deleting the period document would also leave the period drill-down
558
- // empty until some later close recreated it, holding that one day.
559
- for (const doc of existingEntriesByScope.values()) {
560
- if (isThisDayEntryDoc(doc))
561
- staleEntryDocuments.push(doc);
562
- }
563
- for (const doc of existingEntriesByScope.values()) {
564
- // Another day's document is not this close's business - never touch it.
565
- if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
566
- continue;
567
- const remaining = (0, exports.subtractMaterializedDiscountEntrySections)(doc.discount_entries, storedDayEntrySections);
568
- const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
569
- const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
570
- // Nothing of this day was in that period: leave it untouched.
571
- if (rowsAfter === rowsBefore)
572
- continue;
573
- // No rows left anywhere in the period: the document itself goes.
574
- if (rowsAfter === 0) {
575
- staleEntryDocuments.push(doc);
576
- continue;
577
- }
578
- if (addEntryWrite({
579
- ...doc,
580
- discount_entries: remaining,
581
- computed_at: computedAt,
582
- updatedAt: computedAt,
583
- iteration: (doc.iteration ?? 1) + 1,
584
- }) == null) {
585
- return null;
589
+ const referenceDoc = storedDateDocInCompiled ?? reports[0] ?? doc;
590
+ const siblings = (input.existingPeriodDayDocuments ?? []).filter((sibling) => {
591
+ if (sibling == null || sibling.tenant_id !== tenantId)
592
+ return false;
593
+ if (sibling.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
594
+ return false;
595
+ if (typeof sibling.scope_field !== 'string' || sibling.scope_field === localDate)
596
+ return false;
597
+ if (sibling.schema_version !== referenceDoc.schema_version)
598
+ return false;
599
+ if ((sibling.sale_type_key_filters ?? []).join(':') !== (referenceDoc.sale_type_key_filters ?? []).join(':')) {
600
+ return false;
586
601
  }
602
+ const refs = getMaterializedDiscountScopeRefsForDay(sibling.scope_field);
603
+ return (refs != null &&
604
+ refs.some((ref) => ref.scope_context === doc.scope_context && ref.scope_field === doc.scope_field));
605
+ });
606
+ if (siblings.length === 0 && !isZeroCounters(doc.discount_counters)) {
607
+ return null; // unprovable repair: non-empty period with no sibling evidence
587
608
  }
609
+ const replacement = buildDiscountCounterReplacement(doc, null, siblings);
610
+ if (replacement == null)
611
+ return null;
612
+ const updated = updateMaterializedDiscountReport(doc, { replacement }, { computedAt });
613
+ if (updated == null || addWrite(updated) == null)
614
+ return null;
615
+ }
616
+ for (const doc of existingByScope.values()) {
617
+ if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
618
+ staleDocuments.push(doc);
588
619
  }
620
+ // Every entry page fetched by this close belongs to the closing day; an
621
+ // emptied day deletes exactly those pages.
622
+ for (const doc of existingEntriesByPage.values())
623
+ staleEntryDocuments.push(doc);
589
624
  return {
590
625
  writes,
591
626
  entryWrites,
@@ -594,6 +629,7 @@ function buildTenantDiscountCloseDayPlan(input) {
594
629
  skippedDocuments,
595
630
  skippedEntryDocuments,
596
631
  createdPeriodDocuments,
632
+ foldedPeriodDayDocuments,
597
633
  };
598
634
  }
599
635
  const dayChanged = force || needsMaterializedDiscountReportWrite(storedDateDoc, storedDateDocInCompiled);
@@ -625,12 +661,109 @@ function buildTenantDiscountCloseDayPlan(input) {
625
661
  if (!isAccumulatedScope(compiled.scope_context))
626
662
  return null; // unknown scope
627
663
  if (existing == null) {
628
- if (addWrite(compiled) == null)
664
+ // Missing period counter document: rebuild it from the sibling DAY
665
+ // counters that belong to this exact scope (plus the compiled day), so
666
+ // the period equals the sum of its days again. The closing day's own
667
+ // stored date document is excluded by the input contract.
668
+ const referenceDoc = storedDateDocInCompiled ?? reports[0];
669
+ let siblings = counterSiblingsForScope(compiled.scope_context, String(compiled.scope_field), referenceDoc);
670
+ if (upperPeriodScopes.includes(compiled.scope_context)) {
671
+ const currentMonth = localDate.slice(0, 7);
672
+ if (storedDateDoc == null && dayWasMaterialized)
673
+ return null;
674
+ if (storedDateDoc != null) {
675
+ if (!siblings.some((doc) => doc.scope_field === currentMonth))
676
+ return null;
677
+ const corrected = [];
678
+ for (const month of siblings) {
679
+ if (month.scope_field !== currentMonth) {
680
+ corrected.push(month);
681
+ continue;
682
+ }
683
+ const withoutDay = updateMaterializedDiscountReport(month, { subtract: [storedDateDoc] }, { computedAt });
684
+ if (withoutDay == null)
685
+ return null;
686
+ corrected.push(withoutDay);
687
+ }
688
+ siblings = corrected;
689
+ }
690
+ }
691
+ let created = compiled;
692
+ if (siblings.length > 0) {
693
+ const counters = JSON.parse(JSON.stringify(compiled.discount_counters ?? {}));
694
+ let watermark = new Date(compiled.source_watermark);
695
+ for (const sibling of siblings) {
696
+ applyCounters(counters, sibling.discount_counters, 1);
697
+ const siblingWatermark = new Date(sibling.source_watermark);
698
+ if (siblingWatermark.getTime() > watermark.getTime())
699
+ watermark = siblingWatermark;
700
+ }
701
+ for (const key of Object.keys(counters)) {
702
+ if (isZeroCounters(counters[key]))
703
+ delete counters[key];
704
+ }
705
+ const finalCounters = Object.keys(counters).length === 0
706
+ ? null
707
+ : counters;
708
+ created = {
709
+ ...compiled,
710
+ discount_counters: finalCounters,
711
+ discount_counter_rows: finalCounters == null
712
+ ? null
713
+ : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
714
+ source_watermark: watermark,
715
+ iteration: 1,
716
+ };
717
+ foldedPeriodDayDocuments += siblings.length;
718
+ }
719
+ if (addWrite(created) == null)
629
720
  return null;
630
721
  createdPeriodDocuments.push({ scope_context: compiled.scope_context, scope_field: compiled.scope_field });
631
722
  continue;
632
723
  }
633
- const updated = updateMaterializedDiscountReport(existing, { subtract: storedDateDoc != null ? [storedDateDoc] : [], additions: [compiled] }, { computedAt });
724
+ if (storedDateDoc == null && dayWasMaterialized && upperPeriodScopes.includes(compiled.scope_context)) {
725
+ return null; // month docs may still contain the lost day
726
+ }
727
+ if (storedDateDoc == null && !dayWasMaterialized) {
728
+ const siblings = counterSiblingsForScope(compiled.scope_context, String(compiled.scope_field), compiled);
729
+ if (siblings.length === 0) {
730
+ if (!isZeroCounters(existing.discount_counters)) {
731
+ return null;
732
+ }
733
+ }
734
+ else {
735
+ const siblingOnly = buildDiscountCounterReplacement(existing, null, siblings);
736
+ if (siblingOnly == null ||
737
+ JSON.stringify(siblingOnly.discount_counters ?? {}) !== JSON.stringify(existing.discount_counters ?? {})) {
738
+ return null;
739
+ }
740
+ }
741
+ const updated = updateMaterializedDiscountReport(existing, { additions: [compiled] }, { computedAt });
742
+ if (updated == null)
743
+ return null;
744
+ if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
745
+ skippedDocuments.push(existing);
746
+ continue;
747
+ }
748
+ if (addWrite(updated) == null)
749
+ return null;
750
+ continue;
751
+ }
752
+ if (storedDateDoc == null) {
753
+ const siblings = counterSiblingsForScope(compiled.scope_context, String(compiled.scope_field), compiled);
754
+ if (siblings.length === 0 &&
755
+ !isZeroCounters(existing.discount_counters)) {
756
+ return null; // unprovable repair: non-empty period with no sibling evidence
757
+ }
758
+ const replacement = buildDiscountCounterReplacement(existing, compiled, siblings);
759
+ if (replacement == null)
760
+ return null;
761
+ const updated = updateMaterializedDiscountReport(existing, { replacement }, { computedAt });
762
+ if (updated == null || addWrite(updated) == null)
763
+ return null;
764
+ continue;
765
+ }
766
+ const updated = updateMaterializedDiscountReport(existing, { subtract: [storedDateDoc], additions: [compiled] }, { computedAt });
634
767
  if (updated == null || addWrite(updated) == null)
635
768
  return null;
636
769
  }
@@ -644,110 +777,48 @@ function buildTenantDiscountCloseDayPlan(input) {
644
777
  }
645
778
  }
646
779
  }
647
- // ---- entry documents ------------------------------------------------------
648
- // DAY scopes are replaced wholesale (the day is the whole truth); PERIOD scopes
649
- // MERGE the day's rows in - see updateMaterializedDiscountEntries. ----------
650
- const compiledEntriesByScope = new Map();
780
+ // ---- entry pages ---------------------------------------------------------
781
+ // Each period scope is partitioned by the source day; day/hour pages are the
782
+ // single 'all' page. A close replaces ONLY the closing day's pages and deletes
783
+ // that page if the day no longer has rows.
784
+ const compiledEntriesByPage = new Map();
651
785
  for (const doc of entries) {
652
786
  if (doc == null || doc.tenant_id !== tenantId)
653
787
  return null;
654
- const key = scopeKey(doc);
655
- if (compiledEntriesByScope.has(key))
788
+ if (typeof doc.page !== 'string' || doc.page.length === 0)
789
+ return null;
790
+ const expectedPage = DISCOUNT_DAY_SCOPES.includes(doc.scope_context)
791
+ ? MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL
792
+ : localDate;
793
+ if (doc.page !== expectedPage)
794
+ return null;
795
+ const key = entryPageKey(doc);
796
+ if (compiledEntriesByPage.has(key))
656
797
  return null; // duplicate — data issue
657
- compiledEntriesByScope.set(key, doc);
798
+ compiledEntriesByPage.set(key, doc);
658
799
  }
659
- for (const compiled of compiledEntriesByScope.values()) {
660
- const existing = existingEntriesByScope.get(scopeKey(compiled)) ?? null;
800
+ for (const compiled of compiledEntriesByPage.values()) {
801
+ const key = entryPageKey(compiled);
802
+ const existing = existingEntriesByPage.get(key) ?? null;
661
803
  if (!dayChanged && existing != null && !needsMaterializedDiscountEntriesWrite(existing, compiled)) {
662
804
  skippedEntryDocuments.push(existing);
663
805
  continue;
664
806
  }
665
807
  if (existing == null) {
666
- const missingIsPeriod = !DISCOUNT_DAY_SCOPES.includes(compiled.scope_context);
667
- if (!missingIsPeriod) {
668
- if (addEntryWrite(compiled) == null)
669
- return null;
670
- continue;
671
- }
672
- // A missing period entry document is a partial write only when the period
673
- // COUNTER document exists. Refuse to rebuild from an unverified fetch.
674
- const periodCounterExists = existingByScope.has(scopeKey(compiled));
675
- if (periodCounterExists && input.existingEntriesComplete !== true) {
676
- return null;
677
- }
678
- // Never persisted: rebuild from the sibling days, minus this day's stored rows (a
679
- // correction may have REMOVED rows), then merge this day's fresh rows on top.
680
- const folded = (0, exports.subtractMaterializedDiscountEntrySections)(refoldPeriodEntrySections(compiled.scope_context, String(compiled.scope_field)), storedDayEntrySections);
681
- const rebuilt = (0, exports.mergeMaterializedDiscountEntrySections)(folded, compiled.discount_entries);
682
- if (addEntryWrite({ ...compiled, discount_entries: rebuilt }) == null)
808
+ if (addEntryWrite(compiled) == null)
683
809
  return null;
684
810
  continue;
685
811
  }
686
- // A PERIOD document accumulates every day of the period; a DAY document is
687
- // the day itself. Replacing a period wholesale left it holding only the
688
- // final closed day (measured).
689
- const isPeriodEntry = !DISCOUNT_DAY_SCOPES.includes(compiled.scope_context);
690
- // PERIOD documents: remove this day's STORED rows FIRST, then merge the fresh ones.
691
- // Merging alone cannot remove, so a correction that dropped a row left it behind in
692
- // the period while the day document shrank - a phantom row in the period drill-down.
693
- // DAY documents are replaced wholesale and need no subtraction.
694
- const updated = updateMaterializedDiscountEntries(isPeriodEntry
695
- ? {
696
- ...existing,
697
- discount_entries: (0, exports.subtractMaterializedDiscountEntrySections)(existing.discount_entries, storedDayEntrySections),
698
- }
699
- : existing, compiled, { computedAt, mergePeriodRows: isPeriodEntry });
812
+ const updated = updateMaterializedDiscountEntries(existing, compiled, { computedAt });
700
813
  if (updated == null || addEntryWrite(updated) == null)
701
814
  return null;
702
815
  }
703
- // Stored entry documents for this day's scopes that the compile no longer has.
704
- for (const doc of existingEntriesByScope.values()) {
705
- if (compiledEntriesByScope.has(scopeKey(doc)))
816
+ // Only the closing day's pages were fetched, so anything not recompiled is a
817
+ // page this day no longer owns: delete it. Other days' pages are untouched.
818
+ for (const doc of existingEntriesByPage.values()) {
819
+ if (compiledEntriesByPage.has(entryPageKey(doc)))
706
820
  continue;
707
- const isDayScoped = doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
708
- ? doc.scope_field === localDate
709
- : doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
710
- typeof doc.scope_field === 'string' &&
711
- doc.scope_field.startsWith(`${localDate} `);
712
- if (isDayScoped) {
713
- staleEntryDocuments.push(doc);
714
- continue;
715
- }
716
- // A DAY-scoped document belonging to ANOTHER day is simply not this close's
717
- // business. Without this guard it fell through to the period branch below, where
718
- // the compile had (correctly) not emitted it, so it was marked STALE and DELETED -
719
- // meaning every close wiped every OTHER day's entry rows. Measured in the demo data
720
- // before the fix: counters covered 19 discount days while only ONE day of entry rows
721
- // survived, so the drill-down was empty for 18 days that the summary said had
722
- // discounts. The period branch must only ever see PERIOD scopes.
723
- if (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ||
724
- doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
725
- continue;
726
- }
727
- // The compiled day has no rows in this period scope. That does NOT mean the
728
- // period is empty: a period entry document accumulates EVERY day's rows, so
729
- // deleting it would wipe the sibling days that exist nowhere else. Subtract
730
- // the rows this day currently contributes (read from its day-scoped entry
731
- // documents) and drop the document only when nothing remains.
732
- const remaining = (0, exports.subtractMaterializedDiscountEntrySections)(doc.discount_entries, storedDayEntrySections);
733
- const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
734
- const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
735
- // Nothing of this day was in that period: leave it untouched.
736
- if (rowsAfter === rowsBefore)
737
- continue;
738
- if (rowsAfter === 0) {
739
- staleEntryDocuments.push(doc);
740
- continue;
741
- }
742
- if (addEntryWrite({
743
- ...doc,
744
- discount_entries: remaining,
745
- computed_at: computedAt,
746
- updatedAt: computedAt,
747
- iteration: (doc.iteration ?? 1) + 1,
748
- }) == null) {
749
- return null;
750
- }
821
+ staleEntryDocuments.push(doc);
751
822
  }
752
823
  return {
753
824
  writes,
@@ -757,5 +828,6 @@ function buildTenantDiscountCloseDayPlan(input) {
757
828
  skippedDocuments,
758
829
  skippedEntryDocuments,
759
830
  createdPeriodDocuments,
831
+ foldedPeriodDayDocuments,
760
832
  };
761
833
  }