@managesome/eposmatic-toolkit 0.4.29 → 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 (63) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +9 -12
  2. package/esm/helpers/materialized-reports/index.js +1 -0
  3. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +129 -20
  4. package/esm/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  5. package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +251 -240
  6. package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +2 -1
  7. package/esm/helpers/materialized-reports/materialized-discount-source-helpers.js +176 -0
  8. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +64 -0
  9. package/esm/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  10. package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  11. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  12. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +284 -43
  13. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -4
  14. package/esm/schemas/models/materialized_report_drilldown_rows.js +39 -12
  15. package/esm/schemas/models/materialized_tenant_discount_entries.js +18 -12
  16. package/esm/schemas/models/materialized_tenant_discount_sources.js +1 -1
  17. package/esm/schemas/models/orders.js +5 -0
  18. package/esm/schemas/models/tenant_calendar.js +12 -0
  19. package/lib/constants/MATERIALIZED_REPORTS.d.ts +9 -12
  20. package/lib/constants/MATERIALIZED_REPORTS.js +11 -14
  21. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  22. package/lib/helpers/materialized-reports/index.js +1 -0
  23. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +38 -0
  24. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +129 -19
  25. package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  26. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +23 -61
  27. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +250 -239
  28. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.d.ts +4 -4
  29. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +1 -0
  30. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.d.ts +17 -0
  31. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +178 -0
  32. package/lib/helpers/materialized-reports/materialized-index-bootstrap.d.ts +7 -0
  33. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +68 -0
  34. package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +3 -1
  35. package/lib/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  36. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.d.ts +2 -2
  37. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  38. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  39. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +8 -0
  40. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +283 -42
  41. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -4
  42. package/lib/schemas/models/materialized_report_drilldown_rows.d.ts +40 -6
  43. package/lib/schemas/models/materialized_report_drilldown_rows.js +39 -12
  44. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +33 -29
  45. package/lib/schemas/models/materialized_tenant_discount_entries.js +18 -12
  46. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +6 -6
  47. package/lib/schemas/models/materialized_tenant_discount_sources.js +1 -1
  48. package/lib/schemas/models/orders.d.ts +5 -0
  49. package/lib/schemas/models/orders.js +5 -0
  50. package/lib/schemas/models/tenant_calendar.d.ts +13 -0
  51. package/lib/schemas/models/tenant_calendar.js +13 -1
  52. package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +8 -0
  53. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +9 -5
  54. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +56 -1
  55. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +17 -0
  56. package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +60 -54
  57. package/lib/tests/materialized-reports/materialized-discount-entries-accumulation.test.js +14 -13
  58. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +76 -0
  59. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +11 -0
  60. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +2 -2
  61. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +152 -7
  62. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +89 -0
  63. package/package.json +1 -1
@@ -26,6 +26,7 @@ const DISCOUNT_ACCUMULATED_SCOPES = MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT
26
26
  /** True for the accumulating (period) scopes. */
27
27
  const isAccumulatedScope = (scope) => DISCOUNT_ACCUMULATED_SCOPES.includes(scope);
28
28
  const scopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
29
+ const entryPageKey = (doc) => `${scopeKey(doc)}|${doc.page}`;
29
30
  /** Every stored scope one local day's plan needs (date + 3 periods + 24 hours). */
30
31
  function getMaterializedDiscountScopeRefsForDay(localDate) {
31
32
  const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
@@ -46,15 +47,12 @@ function getMaterializedDiscountScopeRefsForDay(localDate) {
46
47
  return refs;
47
48
  }
48
49
  /* ------------------------------------------------------------------------ */
49
- /* Period sibling-day enumeration (the close-day fetch contract) */
50
+ /* Period sibling-day enumeration for COUNTER repair only */
50
51
  /* ------------------------------------------------------------------------ */
51
52
  const pad2 = (value) => String(value).padStart(2, '0');
52
- /** `'YYYY-MM-DD'` of a UTC calendar date. */
53
53
  const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
54
- /** Adds whole days to a UTC calendar date. */
55
54
  const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
56
55
  const daysInUtcMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
57
- /** Adds every day of `count` whole months starting at (year, month). */
58
56
  const addMonthDays = (year, month, count, days) => {
59
57
  for (let offset = 0; offset < count; offset += 1) {
60
58
  const date = new Date(Date.UTC(year, month - 1 + offset, 1));
@@ -67,17 +65,9 @@ const addMonthDays = (year, month, count, days) => {
67
65
  }
68
66
  return true;
69
67
  };
70
- /**
71
- * Adds the day labels covered by ONE stored period scope value to `days`.
72
- *
73
- * Returns `false` (never throws) for a malformed / non-canonical scope value —
74
- * a caller must not silently treat an unparseable period as "no sibling days",
75
- * because that would make the `existingEntriesComplete` acknowledgement lie.
76
- */
77
68
  const addPeriodDays = (scope, scopeField, days) => {
78
69
  switch (scope) {
79
70
  case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
80
- // Sunday-based week start (the `localWeek` bucket identity).
81
71
  const parts = (0, scope_helpers_1.parseMaterializedLocalDate)(scopeField);
82
72
  if (parts == null)
83
73
  return false;
@@ -89,7 +79,6 @@ const addPeriodDays = (scope, scopeField, days) => {
89
79
  return true;
90
80
  }
91
81
  case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
92
- // ISO week: the week-year may differ from the calendar year at boundaries.
93
82
  const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
94
83
  if (match == null)
95
84
  return false;
@@ -97,7 +86,6 @@ const addPeriodDays = (scope, scopeField, days) => {
97
86
  const week = Number(match[2]);
98
87
  if (!Number.isInteger(week) || week < 1 || week > 53)
99
88
  return false;
100
- // ISO week 1 always contains Jan 4; its Monday is the week-1 Monday.
101
89
  const jan4 = new Date(Date.UTC(weekYear, 0, 4));
102
90
  const isoWeekday = jan4.getUTCDay() || 7;
103
91
  const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
@@ -139,22 +127,9 @@ const addPeriodDays = (scope, scopeField, days) => {
139
127
  }
140
128
  };
141
129
  /**
142
- * Every `localDate` day label whose day-scoped ENTRY documents can belong to the
143
- * periods the closing day rolls into (`week`, ISO week, month — whatever
144
- * `MATERIALIZED_DISCOUNT_REPORT_SCOPES` accumulates).
145
- *
146
- * This is the **sibling-day fetch contract** in code: a close caller must fetch
147
- * every `localDate` entry document whose `scope_field` is in this set, in
148
- * addition to the day's own scope refs. Period entry documents are DERIVED from
149
- * day rows, so a period document that was never persisted can only be rebuilt
150
- * from the sibling days — without them the plan rebuilds the period from the
151
- * closing day alone and every other day silently disappears from the period
152
- * drill-down (see `buildTenantDiscountCloseDayPlan`).
153
- *
154
- * The returned set always contains `localDate` itself and is sorted. Returns
155
- * `null` (never throws) for a malformed date or an unparseable period value —
156
- * a `null` means the caller must fail loudly rather than pass an incomplete
157
- * `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.
158
133
  */
159
134
  function getMaterializedDiscountPeriodDayScopeFields(localDate) {
160
135
  const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
@@ -226,6 +201,36 @@ function isZeroCounters(counters) {
226
201
  }
227
202
  return true;
228
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);
229
234
  /**
230
235
  * Applies a counter update to a stored document: optionally REPLACE the counter
231
236
  * map wholesale, else subtract the given deltas and add the compiled ones. Keys
@@ -351,23 +356,18 @@ const subtractMaterializedDiscountEntrySections = (stored, removed) => {
351
356
  };
352
357
  exports.subtractMaterializedDiscountEntrySections = subtractMaterializedDiscountEntrySections;
353
358
  /**
354
- * Updates a stored ENTRY document.
355
- *
356
- * - DAY scopes (`localHour` / `localDate`) are REPLACED wholesale: the day's rows
357
- * are the whole truth for that scope.
358
- * - PERIOD scopes (`localWeek` / `localWeekOfYear` / `localMonth`) MERGE, because
359
- * the compile produces only ONE day of rows: replacing would leave the period
360
- * showing just its final day.
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.
361
361
  *
362
- * Returns null when the documents disagree on schema/scope (a data issue the
363
- * caller must surface).
362
+ * Returns null when the documents disagree on schema/scope/page.
364
363
  */
365
364
  function updateMaterializedDiscountEntries(existing, compiled, options = {}) {
366
365
  if (existing == null || compiled == null)
367
366
  return null;
368
367
  if (existing.schema_version !== compiled.schema_version ||
369
368
  existing.scope_context !== compiled.scope_context ||
370
- existing.scope_field !== compiled.scope_field) {
369
+ existing.scope_field !== compiled.scope_field ||
370
+ existing.page !== compiled.page) {
371
371
  return null;
372
372
  }
373
373
  const computedAt = options.computedAt ?? new Date();
@@ -375,9 +375,8 @@ function updateMaterializedDiscountEntries(existing, compiled, options = {}) {
375
375
  const compiledTime = new Date(compiled.source_watermark ?? 0).getTime();
376
376
  return {
377
377
  ...existing,
378
- discount_entries: options.mergePeriodRows === true
379
- ? (0, exports.mergeMaterializedDiscountEntrySections)(existing.discount_entries, compiled.discount_entries)
380
- : compiled.discount_entries,
378
+ page: compiled.page,
379
+ discount_entries: compiled.discount_entries,
381
380
  source_watermark: compiledTime > existingTime ? compiled.source_watermark : existing.source_watermark,
382
381
  computed_at: computedAt,
383
382
  updatedAt: computedAt,
@@ -390,6 +389,8 @@ function needsMaterializedDiscountEntriesWrite(existing, incoming) {
390
389
  return true;
391
390
  if (existing.schema_version !== incoming.schema_version)
392
391
  return true;
392
+ if (existing.page !== incoming.page)
393
+ return true;
393
394
  if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
394
395
  return true;
395
396
  }
@@ -446,41 +447,46 @@ function buildTenantDiscountCloseDayPlan(input) {
446
447
  if (String(prior._id) !== String(doc._id))
447
448
  return null; // two rows for one scope
448
449
  }
449
- const existingEntriesByScope = new Map();
450
- /**
451
- * Rebuilds a PERIOD entry document's rows from the DAY entry documents still on hand.
452
- *
453
- * Discount period entries ACCUMULATE each day's rows, so a period document that was never
454
- * persisted - a partial failure between the counter writes and the entry writes - would
455
- * otherwise be rebuilt from the CLOSING DAY ALONE, silently dropping every sibling day's
456
- * rows from the period drill-down even though those days' documents are right there. The
457
- * counters already repair this case explicitly; without this, the entries did not.
458
- *
459
- * Only called when the period document is MISSING, so the normal path keeps its
460
- * accumulate-forward behaviour and pays nothing for this.
461
- */
462
- const refoldPeriodEntrySections = (scopeContext, scopeField) => {
463
- let folded = {};
464
- for (const doc of existingEntriesByScope.values()) {
465
- if (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
466
- continue;
467
- const refs = getMaterializedDiscountScopeRefsForDay(String(doc.scope_field));
468
- if (refs == null)
469
- continue;
470
- const belongs = refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
471
- if (!belongs)
472
- continue;
473
- folded = (0, exports.mergeMaterializedDiscountEntrySections)(folded, doc.discount_entries);
474
- }
475
- 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
+ });
476
480
  };
477
481
  for (const doc of input.existingEntries ?? []) {
478
482
  if (doc == null || doc.tenant_id !== tenantId)
479
483
  continue;
480
- const key = scopeKey(doc);
481
- 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);
482
488
  if (prior == null) {
483
- existingEntriesByScope.set(key, doc);
489
+ existingEntriesByPage.set(key, doc);
484
490
  continue;
485
491
  }
486
492
  if (String(prior._id) !== String(doc._id))
@@ -520,34 +526,57 @@ function buildTenantDiscountCloseDayPlan(input) {
520
526
  };
521
527
  const storedDateDoc = existingByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
522
528
  const storedDateDocInCompiled = compiledByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
523
- // The rows this day CURRENTLY contributes, read from its own day-scoped entry documents.
524
- // A period entry document MERGES day rows in, and a merge can only ADD or OVERWRITE - it
525
- // cannot remove. So any close that replaces this day must subtract these rows from every
526
- // period document first, or rows the correction removed linger there as phantoms while the
527
- // DAY document correctly shrinks. Two callers need this: the emptied-day path (subtract
528
- // everything) and the normal path (subtract, then merge the fresh rows back).
529
- const storedDayEntrySections = {};
530
- const isThisDayEntryDoc = (doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
531
- ? doc.scope_field === localDate
532
- : 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 &&
533
535
  typeof doc.scope_field === 'string' &&
534
- doc.scope_field.startsWith(`${localDate} `);
535
- for (const doc of existingEntriesByScope.values()) {
536
- if (!isThisDayEntryDoc(doc))
537
- continue;
538
- for (const [key, section] of Object.entries(doc.discount_entries ?? {})) {
539
- storedDayEntrySections[key] = {
540
- rows: [...(storedDayEntrySections[key]?.rows ?? []), ...(section?.rows ?? [])],
541
- };
542
- }
543
- }
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} `));
544
548
  if (reports.length === 0) {
545
- // The day has NO discounts anymore (orders deleted / moved): subtract the
546
- // stored day from every period document and drop the day's documents.
547
- if (storedDateDoc != null) {
548
- for (const doc of existingByScope.values()) {
549
- if (!isAccumulatedScope(doc.scope_context))
550
- 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) {
551
580
  const updated = updateMaterializedDiscountReport(doc, { subtract: [storedDateDoc] }, { computedAt });
552
581
  if (updated == null)
553
582
  return null;
@@ -555,47 +584,43 @@ function buildTenantDiscountCloseDayPlan(input) {
555
584
  continue;
556
585
  if (addWrite(updated) == null)
557
586
  return null;
587
+ continue;
558
588
  }
559
- for (const doc of existingByScope.values()) {
560
- if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
561
- staleDocuments.push(doc);
562
- }
563
- // ENTRY documents. A PERIOD entry document ACCUMULATES every day's rows
564
- // (`updateMaterializedDiscountEntries` merges them in), so DELETING it discards
565
- // every OTHER day it holds - those rows exist nowhere else. The emptied day must
566
- // be SUBTRACTED from each period document, and only the day's OWN documents
567
- // dropped. Deleting the period document would also leave the period drill-down
568
- // empty until some later close recreated it, holding that one day.
569
- for (const doc of existingEntriesByScope.values()) {
570
- if (isThisDayEntryDoc(doc))
571
- staleEntryDocuments.push(doc);
572
- }
573
- for (const doc of existingEntriesByScope.values()) {
574
- // Another day's document is not this close's business - never touch it.
575
- if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
576
- continue;
577
- const remaining = (0, exports.subtractMaterializedDiscountEntrySections)(doc.discount_entries, storedDayEntrySections);
578
- const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
579
- const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
580
- // Nothing of this day was in that period: leave it untouched.
581
- if (rowsAfter === rowsBefore)
582
- continue;
583
- // No rows left anywhere in the period: the document itself goes.
584
- if (rowsAfter === 0) {
585
- staleEntryDocuments.push(doc);
586
- continue;
587
- }
588
- if (addEntryWrite({
589
- ...doc,
590
- discount_entries: remaining,
591
- computed_at: computedAt,
592
- updatedAt: computedAt,
593
- iteration: (doc.iteration ?? 1) + 1,
594
- }) == null) {
595
- 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;
596
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
597
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);
598
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);
599
624
  return {
600
625
  writes,
601
626
  entryWrites,
@@ -641,22 +666,28 @@ function buildTenantDiscountCloseDayPlan(input) {
641
666
  // the period equals the sum of its days again. The closing day's own
642
667
  // stored date document is excluded by the input contract.
643
668
  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;
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;
655
689
  }
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
- });
690
+ }
660
691
  let created = compiled;
661
692
  if (siblings.length > 0) {
662
693
  const counters = JSON.parse(JSON.stringify(compiled.discount_counters ?? {}));
@@ -690,7 +721,49 @@ function buildTenantDiscountCloseDayPlan(input) {
690
721
  createdPeriodDocuments.push({ scope_context: compiled.scope_context, scope_field: compiled.scope_field });
691
722
  continue;
692
723
  }
693
- 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 });
694
767
  if (updated == null || addWrite(updated) == null)
695
768
  return null;
696
769
  }
@@ -704,110 +777,48 @@ function buildTenantDiscountCloseDayPlan(input) {
704
777
  }
705
778
  }
706
779
  }
707
- // ---- entry documents ------------------------------------------------------
708
- // DAY scopes are replaced wholesale (the day is the whole truth); PERIOD scopes
709
- // MERGE the day's rows in - see updateMaterializedDiscountEntries. ----------
710
- 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();
711
785
  for (const doc of entries) {
712
786
  if (doc == null || doc.tenant_id !== tenantId)
713
787
  return null;
714
- const key = scopeKey(doc);
715
- 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))
716
797
  return null; // duplicate — data issue
717
- compiledEntriesByScope.set(key, doc);
798
+ compiledEntriesByPage.set(key, doc);
718
799
  }
719
- for (const compiled of compiledEntriesByScope.values()) {
720
- 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;
721
803
  if (!dayChanged && existing != null && !needsMaterializedDiscountEntriesWrite(existing, compiled)) {
722
804
  skippedEntryDocuments.push(existing);
723
805
  continue;
724
806
  }
725
807
  if (existing == null) {
726
- const missingIsPeriod = !DISCOUNT_DAY_SCOPES.includes(compiled.scope_context);
727
- if (!missingIsPeriod) {
728
- if (addEntryWrite(compiled) == null)
729
- return null;
730
- continue;
731
- }
732
- // A missing period entry document is a partial write only when the period
733
- // COUNTER document exists. Refuse to rebuild from an unverified fetch.
734
- const periodCounterExists = existingByScope.has(scopeKey(compiled));
735
- if (periodCounterExists && input.existingEntriesComplete !== true) {
736
- return null;
737
- }
738
- // Never persisted: rebuild from the sibling days, minus this day's stored rows (a
739
- // correction may have REMOVED rows), then merge this day's fresh rows on top.
740
- const folded = (0, exports.subtractMaterializedDiscountEntrySections)(refoldPeriodEntrySections(compiled.scope_context, String(compiled.scope_field)), storedDayEntrySections);
741
- const rebuilt = (0, exports.mergeMaterializedDiscountEntrySections)(folded, compiled.discount_entries);
742
- if (addEntryWrite({ ...compiled, discount_entries: rebuilt }) == null)
808
+ if (addEntryWrite(compiled) == null)
743
809
  return null;
744
810
  continue;
745
811
  }
746
- // A PERIOD document accumulates every day of the period; a DAY document is
747
- // the day itself. Replacing a period wholesale left it holding only the
748
- // final closed day (measured).
749
- const isPeriodEntry = !DISCOUNT_DAY_SCOPES.includes(compiled.scope_context);
750
- // PERIOD documents: remove this day's STORED rows FIRST, then merge the fresh ones.
751
- // Merging alone cannot remove, so a correction that dropped a row left it behind in
752
- // the period while the day document shrank - a phantom row in the period drill-down.
753
- // DAY documents are replaced wholesale and need no subtraction.
754
- const updated = updateMaterializedDiscountEntries(isPeriodEntry
755
- ? {
756
- ...existing,
757
- discount_entries: (0, exports.subtractMaterializedDiscountEntrySections)(existing.discount_entries, storedDayEntrySections),
758
- }
759
- : existing, compiled, { computedAt, mergePeriodRows: isPeriodEntry });
812
+ const updated = updateMaterializedDiscountEntries(existing, compiled, { computedAt });
760
813
  if (updated == null || addEntryWrite(updated) == null)
761
814
  return null;
762
815
  }
763
- // Stored entry documents for this day's scopes that the compile no longer has.
764
- for (const doc of existingEntriesByScope.values()) {
765
- 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)))
766
820
  continue;
767
- const isDayScoped = doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
768
- ? doc.scope_field === localDate
769
- : doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
770
- typeof doc.scope_field === 'string' &&
771
- doc.scope_field.startsWith(`${localDate} `);
772
- if (isDayScoped) {
773
- staleEntryDocuments.push(doc);
774
- continue;
775
- }
776
- // A DAY-scoped document belonging to ANOTHER day is simply not this close's
777
- // business. Without this guard it fell through to the period branch below, where
778
- // the compile had (correctly) not emitted it, so it was marked STALE and DELETED -
779
- // meaning every close wiped every OTHER day's entry rows. Measured in the demo data
780
- // before the fix: counters covered 19 discount days while only ONE day of entry rows
781
- // survived, so the drill-down was empty for 18 days that the summary said had
782
- // discounts. The period branch must only ever see PERIOD scopes.
783
- if (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ||
784
- doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
785
- continue;
786
- }
787
- // The compiled day has no rows in this period scope. That does NOT mean the
788
- // period is empty: a period entry document accumulates EVERY day's rows, so
789
- // deleting it would wipe the sibling days that exist nowhere else. Subtract
790
- // the rows this day currently contributes (read from its day-scoped entry
791
- // documents) and drop the document only when nothing remains.
792
- const remaining = (0, exports.subtractMaterializedDiscountEntrySections)(doc.discount_entries, storedDayEntrySections);
793
- const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
794
- const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
795
- // Nothing of this day was in that period: leave it untouched.
796
- if (rowsAfter === rowsBefore)
797
- continue;
798
- if (rowsAfter === 0) {
799
- staleEntryDocuments.push(doc);
800
- continue;
801
- }
802
- if (addEntryWrite({
803
- ...doc,
804
- discount_entries: remaining,
805
- computed_at: computedAt,
806
- updatedAt: computedAt,
807
- iteration: (doc.iteration ?? 1) + 1,
808
- }) == null) {
809
- return null;
810
- }
821
+ staleEntryDocuments.push(doc);
811
822
  }
812
823
  return {
813
824
  writes,