@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
@@ -1,4 +1,4 @@
1
- import { MATERIALIZED_DISCOUNT_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
1
+ import { MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL, MATERIALIZED_DISCOUNT_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
2
2
  import { buildMaterializedTenantReportIteration } from './materialized-tenant-reports-iterations-helpers';
3
3
  import { materializedDayInputSignatureChanged } from './materialized-day-input-signature';
4
4
  import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields, parseMaterializedLocalDate, } from './scope-helpers';
@@ -16,6 +16,7 @@ const DISCOUNT_ACCUMULATED_SCOPES = MATERIALIZED_DISCOUNT_REPORT_SCOPES.filter((
16
16
  /** True for the accumulating (period) scopes. */
17
17
  const isAccumulatedScope = (scope) => DISCOUNT_ACCUMULATED_SCOPES.includes(scope);
18
18
  const scopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
19
+ const entryPageKey = (doc) => `${scopeKey(doc)}|${doc.page}`;
19
20
  /** Every stored scope one local day's plan needs (date + 3 periods + 24 hours). */
20
21
  export function getMaterializedDiscountScopeRefsForDay(localDate) {
21
22
  const periodFields = getMaterializedPeriodScopeFields(localDate);
@@ -36,15 +37,12 @@ export function getMaterializedDiscountScopeRefsForDay(localDate) {
36
37
  return refs;
37
38
  }
38
39
  /* ------------------------------------------------------------------------ */
39
- /* Period sibling-day enumeration (the close-day fetch contract) */
40
+ /* Period sibling-day enumeration for COUNTER repair only */
40
41
  /* ------------------------------------------------------------------------ */
41
42
  const pad2 = (value) => String(value).padStart(2, '0');
42
- /** `'YYYY-MM-DD'` of a UTC calendar date. */
43
43
  const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
44
- /** Adds whole days to a UTC calendar date. */
45
44
  const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
46
45
  const daysInUtcMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
47
- /** Adds every day of `count` whole months starting at (year, month). */
48
46
  const addMonthDays = (year, month, count, days) => {
49
47
  for (let offset = 0; offset < count; offset += 1) {
50
48
  const date = new Date(Date.UTC(year, month - 1 + offset, 1));
@@ -57,17 +55,9 @@ const addMonthDays = (year, month, count, days) => {
57
55
  }
58
56
  return true;
59
57
  };
60
- /**
61
- * Adds the day labels covered by ONE stored period scope value to `days`.
62
- *
63
- * Returns `false` (never throws) for a malformed / non-canonical scope value —
64
- * a caller must not silently treat an unparseable period as "no sibling days",
65
- * because that would make the `existingEntriesComplete` acknowledgement lie.
66
- */
67
58
  const addPeriodDays = (scope, scopeField, days) => {
68
59
  switch (scope) {
69
60
  case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
70
- // Sunday-based week start (the `localWeek` bucket identity).
71
61
  const parts = parseMaterializedLocalDate(scopeField);
72
62
  if (parts == null)
73
63
  return false;
@@ -79,7 +69,6 @@ const addPeriodDays = (scope, scopeField, days) => {
79
69
  return true;
80
70
  }
81
71
  case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
82
- // ISO week: the week-year may differ from the calendar year at boundaries.
83
72
  const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
84
73
  if (match == null)
85
74
  return false;
@@ -87,7 +76,6 @@ const addPeriodDays = (scope, scopeField, days) => {
87
76
  const week = Number(match[2]);
88
77
  if (!Number.isInteger(week) || week < 1 || week > 53)
89
78
  return false;
90
- // ISO week 1 always contains Jan 4; its Monday is the week-1 Monday.
91
79
  const jan4 = new Date(Date.UTC(weekYear, 0, 4));
92
80
  const isoWeekday = jan4.getUTCDay() || 7;
93
81
  const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
@@ -129,22 +117,9 @@ const addPeriodDays = (scope, scopeField, days) => {
129
117
  }
130
118
  };
131
119
  /**
132
- * Every `localDate` day label whose day-scoped ENTRY documents can belong to the
133
- * periods the closing day rolls into (`week`, ISO week, month — whatever
134
- * `MATERIALIZED_DISCOUNT_REPORT_SCOPES` accumulates).
135
- *
136
- * This is the **sibling-day fetch contract** in code: a close caller must fetch
137
- * every `localDate` entry document whose `scope_field` is in this set, in
138
- * addition to the day's own scope refs. Period entry documents are DERIVED from
139
- * day rows, so a period document that was never persisted can only be rebuilt
140
- * from the sibling days — without them the plan rebuilds the period from the
141
- * closing day alone and every other day silently disappears from the period
142
- * drill-down (see `buildTenantDiscountCloseDayPlan`).
143
- *
144
- * The returned set always contains `localDate` itself and is sorted. Returns
145
- * `null` (never throws) for a malformed date or an unparseable period value —
146
- * a `null` means the caller must fail loudly rather than pass an incomplete
147
- * `existingEntries` set with `existingEntriesComplete: true`.
120
+ * Every `localDate` label whose day-scoped COUNTER documents can belong to the
121
+ * periods the closing day rolls into. Used ONLY to repair a missing period
122
+ * counter; entry pages are keyed by the closed day and never use this set.
148
123
  */
149
124
  export function getMaterializedDiscountPeriodDayScopeFields(localDate) {
150
125
  const periodFields = getMaterializedPeriodScopeFields(localDate);
@@ -216,6 +191,36 @@ function isZeroCounters(counters) {
216
191
  }
217
192
  return true;
218
193
  }
194
+ /** Sums a compiled period counter with sibling DAY counters (repair path). */
195
+ function buildDiscountCounterReplacement(existing, compiled, siblings) {
196
+ const counters = JSON.parse(JSON.stringify(compiled?.discount_counters ?? {}));
197
+ let watermark = new Date(compiled?.source_watermark ?? existing.source_watermark);
198
+ for (const sibling of siblings) {
199
+ if (sibling.schema_version !== existing.schema_version)
200
+ return null;
201
+ if ((sibling.sale_type_key_filters ?? []).join(':') !== (existing.sale_type_key_filters ?? []).join(':')) {
202
+ return null;
203
+ }
204
+ applyCounters(counters, sibling.discount_counters, 1);
205
+ const siblingWatermark = new Date(sibling.source_watermark);
206
+ if (siblingWatermark.getTime() > watermark.getTime())
207
+ watermark = siblingWatermark;
208
+ }
209
+ for (const key of Object.keys(counters)) {
210
+ if (isZeroCounters(counters[key]))
211
+ delete counters[key];
212
+ }
213
+ const finalCounters = Object.keys(counters).length === 0 ? null : counters;
214
+ return {
215
+ ...existing,
216
+ discount_counters: finalCounters,
217
+ discount_counter_rows: finalCounters == null ? null : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
218
+ source_watermark: watermark,
219
+ computed_at: existing.computed_at,
220
+ updatedAt: existing.updatedAt,
221
+ };
222
+ }
223
+ const countDiscountEntryRows = (sections) => Object.values(sections ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
219
224
  /**
220
225
  * Applies a counter update to a stored document: optionally REPLACE the counter
221
226
  * map wholesale, else subtract the given deltas and add the compiled ones. Keys
@@ -339,23 +344,18 @@ export const subtractMaterializedDiscountEntrySections = (stored, removed) => {
339
344
  return out;
340
345
  };
341
346
  /**
342
- * Updates a stored ENTRY document.
343
- *
344
- * - DAY scopes (`localHour` / `localDate`) are REPLACED wholesale: the day's rows
345
- * are the whole truth for that scope.
346
- * - PERIOD scopes (`localWeek` / `localWeekOfYear` / `localMonth`) MERGE, because
347
- * the compile produces only ONE day of rows: replacing would leave the period
348
- * showing just its final day.
347
+ * Updates ONE stored ENTRY PAGE by replacing it with the compiled page. Rows
348
+ * never merge across pages; a source day is the whole truth for its page.
349
349
  *
350
- * Returns null when the documents disagree on schema/scope (a data issue the
351
- * caller must surface).
350
+ * Returns null when the documents disagree on schema/scope/page.
352
351
  */
353
352
  export function updateMaterializedDiscountEntries(existing, compiled, options = {}) {
354
353
  if (existing == null || compiled == null)
355
354
  return null;
356
355
  if (existing.schema_version !== compiled.schema_version ||
357
356
  existing.scope_context !== compiled.scope_context ||
358
- existing.scope_field !== compiled.scope_field) {
357
+ existing.scope_field !== compiled.scope_field ||
358
+ existing.page !== compiled.page) {
359
359
  return null;
360
360
  }
361
361
  const computedAt = options.computedAt ?? new Date();
@@ -363,9 +363,8 @@ export function updateMaterializedDiscountEntries(existing, compiled, options =
363
363
  const compiledTime = new Date(compiled.source_watermark ?? 0).getTime();
364
364
  return {
365
365
  ...existing,
366
- discount_entries: options.mergePeriodRows === true
367
- ? mergeMaterializedDiscountEntrySections(existing.discount_entries, compiled.discount_entries)
368
- : compiled.discount_entries,
366
+ page: compiled.page,
367
+ discount_entries: compiled.discount_entries,
369
368
  source_watermark: compiledTime > existingTime ? compiled.source_watermark : existing.source_watermark,
370
369
  computed_at: computedAt,
371
370
  updatedAt: computedAt,
@@ -378,6 +377,8 @@ export function needsMaterializedDiscountEntriesWrite(existing, incoming) {
378
377
  return true;
379
378
  if (existing.schema_version !== incoming.schema_version)
380
379
  return true;
380
+ if (existing.page !== incoming.page)
381
+ return true;
381
382
  if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
382
383
  return true;
383
384
  }
@@ -434,41 +435,46 @@ export function buildTenantDiscountCloseDayPlan(input) {
434
435
  if (String(prior._id) !== String(doc._id))
435
436
  return null; // two rows for one scope
436
437
  }
437
- const existingEntriesByScope = new Map();
438
- /**
439
- * Rebuilds a PERIOD entry document's rows from the DAY entry documents still on hand.
440
- *
441
- * Discount period entries ACCUMULATE each day's rows, so a period document that was never
442
- * persisted - a partial failure between the counter writes and the entry writes - would
443
- * otherwise be rebuilt from the CLOSING DAY ALONE, silently dropping every sibling day's
444
- * rows from the period drill-down even though those days' documents are right there. The
445
- * counters already repair this case explicitly; without this, the entries did not.
446
- *
447
- * Only called when the period document is MISSING, so the normal path keeps its
448
- * accumulate-forward behaviour and pays nothing for this.
449
- */
450
- const refoldPeriodEntrySections = (scopeContext, scopeField) => {
451
- let folded = {};
452
- for (const doc of existingEntriesByScope.values()) {
453
- if (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
454
- continue;
455
- const refs = getMaterializedDiscountScopeRefsForDay(String(doc.scope_field));
456
- if (refs == null)
457
- continue;
458
- const belongs = refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
459
- if (!belongs)
460
- continue;
461
- folded = mergeMaterializedDiscountEntrySections(folded, doc.discount_entries);
462
- }
463
- return folded;
438
+ const existingEntriesByPage = new Map();
439
+ const upperPeriodScopes = [
440
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
441
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
442
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
443
+ ];
444
+ const counterSiblingsForScope = (scopeContext, scopeField, referenceDoc) => {
445
+ const upper = upperPeriodScopes.includes(scopeContext);
446
+ const source = upper
447
+ ? (input.existingPeriodMonthDocuments ?? []).filter((doc) => doc?.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)
448
+ : (input.existingPeriodDayDocuments ?? []);
449
+ return source.filter((doc) => {
450
+ if (doc == null || doc.tenant_id !== tenantId)
451
+ return false;
452
+ if (!upper &&
453
+ (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ||
454
+ typeof doc.scope_field !== 'string' ||
455
+ doc.scope_field === localDate)) {
456
+ return false;
457
+ }
458
+ if (typeof doc.scope_field !== 'string')
459
+ return false;
460
+ if (doc.schema_version !== referenceDoc.schema_version)
461
+ return false;
462
+ if ((doc.sale_type_key_filters ?? []).join(':') !== (referenceDoc.sale_type_key_filters ?? []).join(':')) {
463
+ return false;
464
+ }
465
+ const refs = getMaterializedDiscountScopeRefsForDay(doc.scope_field);
466
+ return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
467
+ });
464
468
  };
465
469
  for (const doc of input.existingEntries ?? []) {
466
470
  if (doc == null || doc.tenant_id !== tenantId)
467
471
  continue;
468
- const key = scopeKey(doc);
469
- const prior = existingEntriesByScope.get(key);
472
+ if (typeof doc.page !== 'string' || doc.page.length === 0)
473
+ return null; // no legacy guess
474
+ const key = entryPageKey(doc);
475
+ const prior = existingEntriesByPage.get(key);
470
476
  if (prior == null) {
471
- existingEntriesByScope.set(key, doc);
477
+ existingEntriesByPage.set(key, doc);
472
478
  continue;
473
479
  }
474
480
  if (String(prior._id) !== String(doc._id))
@@ -508,34 +514,57 @@ export function buildTenantDiscountCloseDayPlan(input) {
508
514
  };
509
515
  const storedDateDoc = existingByScope.get(`${MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
510
516
  const storedDateDocInCompiled = compiledByScope.get(`${MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
511
- // The rows this day CURRENTLY contributes, read from its own day-scoped entry documents.
512
- // A period entry document MERGES day rows in, and a merge can only ADD or OVERWRITE - it
513
- // cannot remove. So any close that replaces this day must subtract these rows from every
514
- // period document first, or rows the correction removed linger there as phantoms while the
515
- // DAY document correctly shrinks. Two callers need this: the emptied-day path (subtract
516
- // everything) and the normal path (subtract, then merge the fresh rows back).
517
- const storedDayEntrySections = {};
518
- const isThisDayEntryDoc = (doc) => doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
519
- ? doc.scope_field === localDate
520
- : doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
517
+ // A missing date document on a day with NO day-scoped counter/entry page is
518
+ // a FIRST close (additive). A surviving day page means the date counter was
519
+ // lost on an already-materialized day; period counters still repair by
520
+ // subtraction from the stored date counter.
521
+ const dayWasMaterialized = [...existingByScope.values()].some((doc) => (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
522
+ (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
521
523
  typeof doc.scope_field === 'string' &&
522
- doc.scope_field.startsWith(`${localDate} `);
523
- for (const doc of existingEntriesByScope.values()) {
524
- if (!isThisDayEntryDoc(doc))
525
- continue;
526
- for (const [key, section] of Object.entries(doc.discount_entries ?? {})) {
527
- storedDayEntrySections[key] = {
528
- rows: [...(storedDayEntrySections[key]?.rows ?? []), ...(section?.rows ?? [])],
529
- };
530
- }
531
- }
524
+ doc.scope_field.startsWith(`${localDate} `))) ||
525
+ [...existingEntriesByPage.values()].some((doc) => doc.page === MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL &&
526
+ ((doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
527
+ (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
528
+ typeof doc.scope_field === 'string' &&
529
+ doc.scope_field.startsWith(`${localDate} `))));
530
+ const isThisDayEntryPage = (doc) => doc.page === MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL &&
531
+ (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
532
+ ? doc.scope_field === localDate
533
+ : doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
534
+ typeof doc.scope_field === 'string' &&
535
+ doc.scope_field.startsWith(`${localDate} `));
532
536
  if (reports.length === 0) {
533
- // The day has NO discounts anymore (orders deleted / moved): subtract the
534
- // stored day from every period document and drop the day's documents.
535
- if (storedDateDoc != null) {
536
- for (const doc of existingByScope.values()) {
537
- if (!isAccumulatedScope(doc.scope_context))
538
- continue;
537
+ // The day has NO discounts anymore (orders deleted / moved). When the date
538
+ // document exists, subtract it; when it is MISSING, rebuild every period
539
+ // from the sibling DAY documents. Never silently leave a stale delta.
540
+ if (storedDateDoc == null && !dayWasMaterialized) {
541
+ const siblings = (input.existingPeriodDayDocuments ?? []).filter((sibling) => sibling?.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && sibling.scope_field !== localDate);
542
+ const hasNonZeroPeriodCounter = [...existingByScope.values()].some((doc) => isAccumulatedScope(doc.scope_context) &&
543
+ !isZeroCounters(doc.discount_counters));
544
+ // A new empty day after earlier days is harmless (zero delta), but a
545
+ // lost date with no day evidence and no sibling proof must not be
546
+ // surfaced as "empty": the old delta may still sit in the periods.
547
+ if (hasNonZeroPeriodCounter && siblings.length === 0)
548
+ return null;
549
+ if (siblings.length === 0) {
550
+ return {
551
+ writes,
552
+ entryWrites,
553
+ staleDocuments,
554
+ staleEntryDocuments,
555
+ skippedDocuments,
556
+ skippedEntryDocuments,
557
+ createdPeriodDocuments,
558
+ foldedPeriodDayDocuments,
559
+ };
560
+ }
561
+ // Fall through: rebuild period counters from the sibling days (the
562
+ // current day contributes nothing), which removes any stale lost delta.
563
+ }
564
+ for (const doc of existingByScope.values()) {
565
+ if (!isAccumulatedScope(doc.scope_context))
566
+ continue;
567
+ if (storedDateDoc != null) {
539
568
  const updated = updateMaterializedDiscountReport(doc, { subtract: [storedDateDoc] }, { computedAt });
540
569
  if (updated == null)
541
570
  return null;
@@ -543,47 +572,43 @@ export function buildTenantDiscountCloseDayPlan(input) {
543
572
  continue;
544
573
  if (addWrite(updated) == null)
545
574
  return null;
575
+ continue;
546
576
  }
547
- for (const doc of existingByScope.values()) {
548
- if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
549
- staleDocuments.push(doc);
550
- }
551
- // ENTRY documents. A PERIOD entry document ACCUMULATES every day's rows
552
- // (`updateMaterializedDiscountEntries` merges them in), so DELETING it discards
553
- // every OTHER day it holds - those rows exist nowhere else. The emptied day must
554
- // be SUBTRACTED from each period document, and only the day's OWN documents
555
- // dropped. Deleting the period document would also leave the period drill-down
556
- // empty until some later close recreated it, holding that one day.
557
- for (const doc of existingEntriesByScope.values()) {
558
- if (isThisDayEntryDoc(doc))
559
- staleEntryDocuments.push(doc);
560
- }
561
- for (const doc of existingEntriesByScope.values()) {
562
- // Another day's document is not this close's business - never touch it.
563
- if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
564
- continue;
565
- const remaining = subtractMaterializedDiscountEntrySections(doc.discount_entries, storedDayEntrySections);
566
- const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
567
- const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
568
- // Nothing of this day was in that period: leave it untouched.
569
- if (rowsAfter === rowsBefore)
570
- continue;
571
- // No rows left anywhere in the period: the document itself goes.
572
- if (rowsAfter === 0) {
573
- staleEntryDocuments.push(doc);
574
- continue;
575
- }
576
- if (addEntryWrite({
577
- ...doc,
578
- discount_entries: remaining,
579
- computed_at: computedAt,
580
- updatedAt: computedAt,
581
- iteration: (doc.iteration ?? 1) + 1,
582
- }) == null) {
583
- return null;
577
+ const referenceDoc = storedDateDocInCompiled ?? reports[0] ?? doc;
578
+ const siblings = (input.existingPeriodDayDocuments ?? []).filter((sibling) => {
579
+ if (sibling == null || sibling.tenant_id !== tenantId)
580
+ return false;
581
+ if (sibling.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
582
+ return false;
583
+ if (typeof sibling.scope_field !== 'string' || sibling.scope_field === localDate)
584
+ return false;
585
+ if (sibling.schema_version !== referenceDoc.schema_version)
586
+ return false;
587
+ if ((sibling.sale_type_key_filters ?? []).join(':') !== (referenceDoc.sale_type_key_filters ?? []).join(':')) {
588
+ return false;
584
589
  }
590
+ const refs = getMaterializedDiscountScopeRefsForDay(sibling.scope_field);
591
+ return (refs != null &&
592
+ refs.some((ref) => ref.scope_context === doc.scope_context && ref.scope_field === doc.scope_field));
593
+ });
594
+ if (siblings.length === 0 && !isZeroCounters(doc.discount_counters)) {
595
+ return null; // unprovable repair: non-empty period with no sibling evidence
585
596
  }
597
+ const replacement = buildDiscountCounterReplacement(doc, null, siblings);
598
+ if (replacement == null)
599
+ return null;
600
+ const updated = updateMaterializedDiscountReport(doc, { replacement }, { computedAt });
601
+ if (updated == null || addWrite(updated) == null)
602
+ return null;
603
+ }
604
+ for (const doc of existingByScope.values()) {
605
+ if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
606
+ staleDocuments.push(doc);
586
607
  }
608
+ // Every entry page fetched by this close belongs to the closing day; an
609
+ // emptied day deletes exactly those pages.
610
+ for (const doc of existingEntriesByPage.values())
611
+ staleEntryDocuments.push(doc);
587
612
  return {
588
613
  writes,
589
614
  entryWrites,
@@ -629,22 +654,28 @@ export function buildTenantDiscountCloseDayPlan(input) {
629
654
  // the period equals the sum of its days again. The closing day's own
630
655
  // stored date document is excluded by the input contract.
631
656
  const referenceDoc = storedDateDocInCompiled ?? reports[0];
632
- const siblings = (input.existingPeriodDayDocuments ?? []).filter((doc) => {
633
- if (doc == null || doc.tenant_id !== tenantId)
634
- return false;
635
- if (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
636
- return false;
637
- if (typeof doc.scope_field !== 'string' || doc.scope_field === localDate)
638
- return false;
639
- if (doc.schema_version !== referenceDoc.schema_version)
640
- return false;
641
- if ((doc.sale_type_key_filters ?? []).join(':') !== (referenceDoc.sale_type_key_filters ?? []).join(':')) {
642
- return false;
657
+ let siblings = counterSiblingsForScope(compiled.scope_context, String(compiled.scope_field), referenceDoc);
658
+ if (upperPeriodScopes.includes(compiled.scope_context)) {
659
+ const currentMonth = localDate.slice(0, 7);
660
+ if (storedDateDoc == null && dayWasMaterialized)
661
+ return null;
662
+ if (storedDateDoc != null) {
663
+ if (!siblings.some((doc) => doc.scope_field === currentMonth))
664
+ return null;
665
+ const corrected = [];
666
+ for (const month of siblings) {
667
+ if (month.scope_field !== currentMonth) {
668
+ corrected.push(month);
669
+ continue;
670
+ }
671
+ const withoutDay = updateMaterializedDiscountReport(month, { subtract: [storedDateDoc] }, { computedAt });
672
+ if (withoutDay == null)
673
+ return null;
674
+ corrected.push(withoutDay);
675
+ }
676
+ siblings = corrected;
643
677
  }
644
- const refs = getMaterializedDiscountScopeRefsForDay(doc.scope_field);
645
- return (refs != null &&
646
- refs.some((ref) => ref.scope_context === compiled.scope_context && ref.scope_field === compiled.scope_field));
647
- });
678
+ }
648
679
  let created = compiled;
649
680
  if (siblings.length > 0) {
650
681
  const counters = JSON.parse(JSON.stringify(compiled.discount_counters ?? {}));
@@ -678,7 +709,49 @@ export function buildTenantDiscountCloseDayPlan(input) {
678
709
  createdPeriodDocuments.push({ scope_context: compiled.scope_context, scope_field: compiled.scope_field });
679
710
  continue;
680
711
  }
681
- const updated = updateMaterializedDiscountReport(existing, { subtract: storedDateDoc != null ? [storedDateDoc] : [], additions: [compiled] }, { computedAt });
712
+ if (storedDateDoc == null && dayWasMaterialized && upperPeriodScopes.includes(compiled.scope_context)) {
713
+ return null; // month docs may still contain the lost day
714
+ }
715
+ if (storedDateDoc == null && !dayWasMaterialized) {
716
+ const siblings = counterSiblingsForScope(compiled.scope_context, String(compiled.scope_field), compiled);
717
+ if (siblings.length === 0) {
718
+ if (!isZeroCounters(existing.discount_counters)) {
719
+ return null;
720
+ }
721
+ }
722
+ else {
723
+ const siblingOnly = buildDiscountCounterReplacement(existing, null, siblings);
724
+ if (siblingOnly == null ||
725
+ JSON.stringify(siblingOnly.discount_counters ?? {}) !== JSON.stringify(existing.discount_counters ?? {})) {
726
+ return null;
727
+ }
728
+ }
729
+ const updated = updateMaterializedDiscountReport(existing, { additions: [compiled] }, { computedAt });
730
+ if (updated == null)
731
+ return null;
732
+ if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
733
+ skippedDocuments.push(existing);
734
+ continue;
735
+ }
736
+ if (addWrite(updated) == null)
737
+ return null;
738
+ continue;
739
+ }
740
+ if (storedDateDoc == null) {
741
+ const siblings = counterSiblingsForScope(compiled.scope_context, String(compiled.scope_field), compiled);
742
+ if (siblings.length === 0 &&
743
+ !isZeroCounters(existing.discount_counters)) {
744
+ return null; // unprovable repair: non-empty period with no sibling evidence
745
+ }
746
+ const replacement = buildDiscountCounterReplacement(existing, compiled, siblings);
747
+ if (replacement == null)
748
+ return null;
749
+ const updated = updateMaterializedDiscountReport(existing, { replacement }, { computedAt });
750
+ if (updated == null || addWrite(updated) == null)
751
+ return null;
752
+ continue;
753
+ }
754
+ const updated = updateMaterializedDiscountReport(existing, { subtract: [storedDateDoc], additions: [compiled] }, { computedAt });
682
755
  if (updated == null || addWrite(updated) == null)
683
756
  return null;
684
757
  }
@@ -692,110 +765,48 @@ export function buildTenantDiscountCloseDayPlan(input) {
692
765
  }
693
766
  }
694
767
  }
695
- // ---- entry documents ------------------------------------------------------
696
- // DAY scopes are replaced wholesale (the day is the whole truth); PERIOD scopes
697
- // MERGE the day's rows in - see updateMaterializedDiscountEntries. ----------
698
- const compiledEntriesByScope = new Map();
768
+ // ---- entry pages ---------------------------------------------------------
769
+ // Each period scope is partitioned by the source day; day/hour pages are the
770
+ // single 'all' page. A close replaces ONLY the closing day's pages and deletes
771
+ // that page if the day no longer has rows.
772
+ const compiledEntriesByPage = new Map();
699
773
  for (const doc of entries) {
700
774
  if (doc == null || doc.tenant_id !== tenantId)
701
775
  return null;
702
- const key = scopeKey(doc);
703
- if (compiledEntriesByScope.has(key))
776
+ if (typeof doc.page !== 'string' || doc.page.length === 0)
777
+ return null;
778
+ const expectedPage = DISCOUNT_DAY_SCOPES.includes(doc.scope_context)
779
+ ? MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL
780
+ : localDate;
781
+ if (doc.page !== expectedPage)
782
+ return null;
783
+ const key = entryPageKey(doc);
784
+ if (compiledEntriesByPage.has(key))
704
785
  return null; // duplicate — data issue
705
- compiledEntriesByScope.set(key, doc);
786
+ compiledEntriesByPage.set(key, doc);
706
787
  }
707
- for (const compiled of compiledEntriesByScope.values()) {
708
- const existing = existingEntriesByScope.get(scopeKey(compiled)) ?? null;
788
+ for (const compiled of compiledEntriesByPage.values()) {
789
+ const key = entryPageKey(compiled);
790
+ const existing = existingEntriesByPage.get(key) ?? null;
709
791
  if (!dayChanged && existing != null && !needsMaterializedDiscountEntriesWrite(existing, compiled)) {
710
792
  skippedEntryDocuments.push(existing);
711
793
  continue;
712
794
  }
713
795
  if (existing == null) {
714
- const missingIsPeriod = !DISCOUNT_DAY_SCOPES.includes(compiled.scope_context);
715
- if (!missingIsPeriod) {
716
- if (addEntryWrite(compiled) == null)
717
- return null;
718
- continue;
719
- }
720
- // A missing period entry document is a partial write only when the period
721
- // COUNTER document exists. Refuse to rebuild from an unverified fetch.
722
- const periodCounterExists = existingByScope.has(scopeKey(compiled));
723
- if (periodCounterExists && input.existingEntriesComplete !== true) {
724
- return null;
725
- }
726
- // Never persisted: rebuild from the sibling days, minus this day's stored rows (a
727
- // correction may have REMOVED rows), then merge this day's fresh rows on top.
728
- const folded = subtractMaterializedDiscountEntrySections(refoldPeriodEntrySections(compiled.scope_context, String(compiled.scope_field)), storedDayEntrySections);
729
- const rebuilt = mergeMaterializedDiscountEntrySections(folded, compiled.discount_entries);
730
- if (addEntryWrite({ ...compiled, discount_entries: rebuilt }) == null)
796
+ if (addEntryWrite(compiled) == null)
731
797
  return null;
732
798
  continue;
733
799
  }
734
- // A PERIOD document accumulates every day of the period; a DAY document is
735
- // the day itself. Replacing a period wholesale left it holding only the
736
- // final closed day (measured).
737
- const isPeriodEntry = !DISCOUNT_DAY_SCOPES.includes(compiled.scope_context);
738
- // PERIOD documents: remove this day's STORED rows FIRST, then merge the fresh ones.
739
- // Merging alone cannot remove, so a correction that dropped a row left it behind in
740
- // the period while the day document shrank - a phantom row in the period drill-down.
741
- // DAY documents are replaced wholesale and need no subtraction.
742
- const updated = updateMaterializedDiscountEntries(isPeriodEntry
743
- ? {
744
- ...existing,
745
- discount_entries: subtractMaterializedDiscountEntrySections(existing.discount_entries, storedDayEntrySections),
746
- }
747
- : existing, compiled, { computedAt, mergePeriodRows: isPeriodEntry });
800
+ const updated = updateMaterializedDiscountEntries(existing, compiled, { computedAt });
748
801
  if (updated == null || addEntryWrite(updated) == null)
749
802
  return null;
750
803
  }
751
- // Stored entry documents for this day's scopes that the compile no longer has.
752
- for (const doc of existingEntriesByScope.values()) {
753
- if (compiledEntriesByScope.has(scopeKey(doc)))
804
+ // Only the closing day's pages were fetched, so anything not recompiled is a
805
+ // page this day no longer owns: delete it. Other days' pages are untouched.
806
+ for (const doc of existingEntriesByPage.values()) {
807
+ if (compiledEntriesByPage.has(entryPageKey(doc)))
754
808
  continue;
755
- const isDayScoped = doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
756
- ? doc.scope_field === localDate
757
- : doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
758
- typeof doc.scope_field === 'string' &&
759
- doc.scope_field.startsWith(`${localDate} `);
760
- if (isDayScoped) {
761
- staleEntryDocuments.push(doc);
762
- continue;
763
- }
764
- // A DAY-scoped document belonging to ANOTHER day is simply not this close's
765
- // business. Without this guard it fell through to the period branch below, where
766
- // the compile had (correctly) not emitted it, so it was marked STALE and DELETED -
767
- // meaning every close wiped every OTHER day's entry rows. Measured in the demo data
768
- // before the fix: counters covered 19 discount days while only ONE day of entry rows
769
- // survived, so the drill-down was empty for 18 days that the summary said had
770
- // discounts. The period branch must only ever see PERIOD scopes.
771
- if (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ||
772
- doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
773
- continue;
774
- }
775
- // The compiled day has no rows in this period scope. That does NOT mean the
776
- // period is empty: a period entry document accumulates EVERY day's rows, so
777
- // deleting it would wipe the sibling days that exist nowhere else. Subtract
778
- // the rows this day currently contributes (read from its day-scoped entry
779
- // documents) and drop the document only when nothing remains.
780
- const remaining = subtractMaterializedDiscountEntrySections(doc.discount_entries, storedDayEntrySections);
781
- const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
782
- const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
783
- // Nothing of this day was in that period: leave it untouched.
784
- if (rowsAfter === rowsBefore)
785
- continue;
786
- if (rowsAfter === 0) {
787
- staleEntryDocuments.push(doc);
788
- continue;
789
- }
790
- if (addEntryWrite({
791
- ...doc,
792
- discount_entries: remaining,
793
- computed_at: computedAt,
794
- updatedAt: computedAt,
795
- iteration: (doc.iteration ?? 1) + 1,
796
- }) == null) {
797
- return null;
798
- }
809
+ staleEntryDocuments.push(doc);
799
810
  }
800
811
  return {
801
812
  writes,