@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
@@ -1,5 +1,6 @@
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
+ import { materializedDayInputSignatureChanged } from './materialized-day-input-signature';
3
4
  import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields, parseMaterializedLocalDate, } from './scope-helpers';
4
5
  /** Day-scoped documents (replaced wholesale for the compiled day). */
5
6
  const DISCOUNT_DAY_SCOPES = [
@@ -15,6 +16,7 @@ const DISCOUNT_ACCUMULATED_SCOPES = MATERIALIZED_DISCOUNT_REPORT_SCOPES.filter((
15
16
  /** True for the accumulating (period) scopes. */
16
17
  const isAccumulatedScope = (scope) => DISCOUNT_ACCUMULATED_SCOPES.includes(scope);
17
18
  const scopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
19
+ const entryPageKey = (doc) => `${scopeKey(doc)}|${doc.page}`;
18
20
  /** Every stored scope one local day's plan needs (date + 3 periods + 24 hours). */
19
21
  export function getMaterializedDiscountScopeRefsForDay(localDate) {
20
22
  const periodFields = getMaterializedPeriodScopeFields(localDate);
@@ -35,15 +37,12 @@ export function getMaterializedDiscountScopeRefsForDay(localDate) {
35
37
  return refs;
36
38
  }
37
39
  /* ------------------------------------------------------------------------ */
38
- /* Period sibling-day enumeration (the close-day fetch contract) */
40
+ /* Period sibling-day enumeration for COUNTER repair only */
39
41
  /* ------------------------------------------------------------------------ */
40
42
  const pad2 = (value) => String(value).padStart(2, '0');
41
- /** `'YYYY-MM-DD'` of a UTC calendar date. */
42
43
  const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
43
- /** Adds whole days to a UTC calendar date. */
44
44
  const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
45
45
  const daysInUtcMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
46
- /** Adds every day of `count` whole months starting at (year, month). */
47
46
  const addMonthDays = (year, month, count, days) => {
48
47
  for (let offset = 0; offset < count; offset += 1) {
49
48
  const date = new Date(Date.UTC(year, month - 1 + offset, 1));
@@ -56,17 +55,9 @@ const addMonthDays = (year, month, count, days) => {
56
55
  }
57
56
  return true;
58
57
  };
59
- /**
60
- * Adds the day labels covered by ONE stored period scope value to `days`.
61
- *
62
- * Returns `false` (never throws) for a malformed / non-canonical scope value —
63
- * a caller must not silently treat an unparseable period as "no sibling days",
64
- * because that would make the `existingEntriesComplete` acknowledgement lie.
65
- */
66
58
  const addPeriodDays = (scope, scopeField, days) => {
67
59
  switch (scope) {
68
60
  case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
69
- // Sunday-based week start (the `localWeek` bucket identity).
70
61
  const parts = parseMaterializedLocalDate(scopeField);
71
62
  if (parts == null)
72
63
  return false;
@@ -78,7 +69,6 @@ const addPeriodDays = (scope, scopeField, days) => {
78
69
  return true;
79
70
  }
80
71
  case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
81
- // ISO week: the week-year may differ from the calendar year at boundaries.
82
72
  const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
83
73
  if (match == null)
84
74
  return false;
@@ -86,7 +76,6 @@ const addPeriodDays = (scope, scopeField, days) => {
86
76
  const week = Number(match[2]);
87
77
  if (!Number.isInteger(week) || week < 1 || week > 53)
88
78
  return false;
89
- // ISO week 1 always contains Jan 4; its Monday is the week-1 Monday.
90
79
  const jan4 = new Date(Date.UTC(weekYear, 0, 4));
91
80
  const isoWeekday = jan4.getUTCDay() || 7;
92
81
  const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
@@ -128,22 +117,9 @@ const addPeriodDays = (scope, scopeField, days) => {
128
117
  }
129
118
  };
130
119
  /**
131
- * Every `localDate` day label whose day-scoped ENTRY documents can belong to the
132
- * periods the closing day rolls into (`week`, ISO week, month — whatever
133
- * `MATERIALIZED_DISCOUNT_REPORT_SCOPES` accumulates).
134
- *
135
- * This is the **sibling-day fetch contract** in code: a close caller must fetch
136
- * every `localDate` entry document whose `scope_field` is in this set, in
137
- * addition to the day's own scope refs. Period entry documents are DERIVED from
138
- * day rows, so a period document that was never persisted can only be rebuilt
139
- * from the sibling days — without them the plan rebuilds the period from the
140
- * closing day alone and every other day silently disappears from the period
141
- * drill-down (see `buildTenantDiscountCloseDayPlan`).
142
- *
143
- * The returned set always contains `localDate` itself and is sorted. Returns
144
- * `null` (never throws) for a malformed date or an unparseable period value —
145
- * a `null` means the caller must fail loudly rather than pass an incomplete
146
- * `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.
147
123
  */
148
124
  export function getMaterializedDiscountPeriodDayScopeFields(localDate) {
149
125
  const periodFields = getMaterializedPeriodScopeFields(localDate);
@@ -162,7 +138,9 @@ export function getMaterializedDiscountPeriodDayScopeFields(localDate) {
162
138
  /**
163
139
  * Watermark guard: does the stored document need a structural write?
164
140
  * `false` (skip) when the incoming `source_watermark` is not newer than the
165
- * stored one and the schema version + key grammar match.
141
+ * stored one, the day-input SIGNATURE is unchanged, and the schema version +
142
+ * key grammar match. The signature catches a deleted / moved order whose
143
+ * removal lowered the incoming watermark.
166
144
  */
167
145
  export function needsMaterializedDiscountReportWrite(existing, incoming) {
168
146
  if (existing == null || incoming == null)
@@ -172,6 +150,9 @@ export function needsMaterializedDiscountReportWrite(existing, incoming) {
172
150
  if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
173
151
  return true;
174
152
  }
153
+ if (materializedDayInputSignatureChanged(existing.source_input_signature, incoming.source_input_signature)) {
154
+ return true;
155
+ }
175
156
  const existingTime = new Date(existing.source_watermark ?? 0).getTime();
176
157
  const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
177
158
  if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
@@ -210,6 +191,36 @@ function isZeroCounters(counters) {
210
191
  }
211
192
  return true;
212
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);
213
224
  /**
214
225
  * Applies a counter update to a stored document: optionally REPLACE the counter
215
226
  * map wholesale, else subtract the given deltas and add the compiled ones. Keys
@@ -273,6 +284,9 @@ export function updateMaterializedDiscountReport(existing, updates, options = {}
273
284
  // step with it — one source of truth, so the map and the rows can never
274
285
  // disagree (and a correction that empties a key drops it from both).
275
286
  discount_counter_rows: finalCounters == null ? null : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
287
+ // A REPLACEMENT carries the freshly compiled day digest; period folds keep
288
+ // the stored value (their payload is a running sum, not one day's input).
289
+ source_input_signature: updates.replacement?.source_input_signature ?? existing.source_input_signature,
276
290
  source_watermark: sourceWatermark,
277
291
  computed_at: computedAt,
278
292
  updatedAt: computedAt,
@@ -330,23 +344,18 @@ export const subtractMaterializedDiscountEntrySections = (stored, removed) => {
330
344
  return out;
331
345
  };
332
346
  /**
333
- * Updates a stored ENTRY document.
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.
334
349
  *
335
- * - DAY scopes (`localHour` / `localDate`) are REPLACED wholesale: the day's rows
336
- * are the whole truth for that scope.
337
- * - PERIOD scopes (`localWeek` / `localWeekOfYear` / `localMonth`) MERGE, because
338
- * the compile produces only ONE day of rows: replacing would leave the period
339
- * showing just its final day.
340
- *
341
- * Returns null when the documents disagree on schema/scope (a data issue the
342
- * caller must surface).
350
+ * Returns null when the documents disagree on schema/scope/page.
343
351
  */
344
352
  export function updateMaterializedDiscountEntries(existing, compiled, options = {}) {
345
353
  if (existing == null || compiled == null)
346
354
  return null;
347
355
  if (existing.schema_version !== compiled.schema_version ||
348
356
  existing.scope_context !== compiled.scope_context ||
349
- existing.scope_field !== compiled.scope_field) {
357
+ existing.scope_field !== compiled.scope_field ||
358
+ existing.page !== compiled.page) {
350
359
  return null;
351
360
  }
352
361
  const computedAt = options.computedAt ?? new Date();
@@ -354,9 +363,8 @@ export function updateMaterializedDiscountEntries(existing, compiled, options =
354
363
  const compiledTime = new Date(compiled.source_watermark ?? 0).getTime();
355
364
  return {
356
365
  ...existing,
357
- discount_entries: options.mergePeriodRows === true
358
- ? mergeMaterializedDiscountEntrySections(existing.discount_entries, compiled.discount_entries)
359
- : compiled.discount_entries,
366
+ page: compiled.page,
367
+ discount_entries: compiled.discount_entries,
360
368
  source_watermark: compiledTime > existingTime ? compiled.source_watermark : existing.source_watermark,
361
369
  computed_at: computedAt,
362
370
  updatedAt: computedAt,
@@ -369,6 +377,8 @@ export function needsMaterializedDiscountEntriesWrite(existing, incoming) {
369
377
  return true;
370
378
  if (existing.schema_version !== incoming.schema_version)
371
379
  return true;
380
+ if (existing.page !== incoming.page)
381
+ return true;
372
382
  if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
373
383
  return true;
374
384
  }
@@ -425,41 +435,46 @@ export function buildTenantDiscountCloseDayPlan(input) {
425
435
  if (String(prior._id) !== String(doc._id))
426
436
  return null; // two rows for one scope
427
437
  }
428
- const existingEntriesByScope = new Map();
429
- /**
430
- * Rebuilds a PERIOD entry document's rows from the DAY entry documents still on hand.
431
- *
432
- * Discount period entries ACCUMULATE each day's rows, so a period document that was never
433
- * persisted - a partial failure between the counter writes and the entry writes - would
434
- * otherwise be rebuilt from the CLOSING DAY ALONE, silently dropping every sibling day's
435
- * rows from the period drill-down even though those days' documents are right there. The
436
- * counters already repair this case explicitly; without this, the entries did not.
437
- *
438
- * Only called when the period document is MISSING, so the normal path keeps its
439
- * accumulate-forward behaviour and pays nothing for this.
440
- */
441
- const refoldPeriodEntrySections = (scopeContext, scopeField) => {
442
- let folded = {};
443
- for (const doc of existingEntriesByScope.values()) {
444
- if (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
445
- continue;
446
- const refs = getMaterializedDiscountScopeRefsForDay(String(doc.scope_field));
447
- if (refs == null)
448
- continue;
449
- const belongs = refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
450
- if (!belongs)
451
- continue;
452
- folded = mergeMaterializedDiscountEntrySections(folded, doc.discount_entries);
453
- }
454
- 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
+ });
455
468
  };
456
469
  for (const doc of input.existingEntries ?? []) {
457
470
  if (doc == null || doc.tenant_id !== tenantId)
458
471
  continue;
459
- const key = scopeKey(doc);
460
- 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);
461
476
  if (prior == null) {
462
- existingEntriesByScope.set(key, doc);
477
+ existingEntriesByPage.set(key, doc);
463
478
  continue;
464
479
  }
465
480
  if (String(prior._id) !== String(doc._id))
@@ -472,6 +487,7 @@ export function buildTenantDiscountCloseDayPlan(input) {
472
487
  const skippedDocuments = [];
473
488
  const skippedEntryDocuments = [];
474
489
  const createdPeriodDocuments = [];
490
+ let foldedPeriodDayDocuments = 0;
475
491
  const addWrite = (report) => {
476
492
  const persisted = report.iteration == null ? { ...report, iteration: 1 } : report;
477
493
  const iteration = buildMaterializedTenantReportIteration(persisted, {
@@ -498,34 +514,57 @@ export function buildTenantDiscountCloseDayPlan(input) {
498
514
  };
499
515
  const storedDateDoc = existingByScope.get(`${MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
500
516
  const storedDateDocInCompiled = compiledByScope.get(`${MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
501
- // The rows this day CURRENTLY contributes, read from its own day-scoped entry documents.
502
- // A period entry document MERGES day rows in, and a merge can only ADD or OVERWRITE - it
503
- // cannot remove. So any close that replaces this day must subtract these rows from every
504
- // period document first, or rows the correction removed linger there as phantoms while the
505
- // DAY document correctly shrinks. Two callers need this: the emptied-day path (subtract
506
- // everything) and the normal path (subtract, then merge the fresh rows back).
507
- const storedDayEntrySections = {};
508
- const isThisDayEntryDoc = (doc) => doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
509
- ? doc.scope_field === localDate
510
- : 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 &&
511
523
  typeof doc.scope_field === 'string' &&
512
- doc.scope_field.startsWith(`${localDate} `);
513
- for (const doc of existingEntriesByScope.values()) {
514
- if (!isThisDayEntryDoc(doc))
515
- continue;
516
- for (const [key, section] of Object.entries(doc.discount_entries ?? {})) {
517
- storedDayEntrySections[key] = {
518
- rows: [...(storedDayEntrySections[key]?.rows ?? []), ...(section?.rows ?? [])],
519
- };
520
- }
521
- }
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} `));
522
536
  if (reports.length === 0) {
523
- // The day has NO discounts anymore (orders deleted / moved): subtract the
524
- // stored day from every period document and drop the day's documents.
525
- if (storedDateDoc != null) {
526
- for (const doc of existingByScope.values()) {
527
- if (!isAccumulatedScope(doc.scope_context))
528
- 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) {
529
568
  const updated = updateMaterializedDiscountReport(doc, { subtract: [storedDateDoc] }, { computedAt });
530
569
  if (updated == null)
531
570
  return null;
@@ -533,47 +572,43 @@ export function buildTenantDiscountCloseDayPlan(input) {
533
572
  continue;
534
573
  if (addWrite(updated) == null)
535
574
  return null;
575
+ continue;
536
576
  }
537
- for (const doc of existingByScope.values()) {
538
- if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
539
- staleDocuments.push(doc);
540
- }
541
- // ENTRY documents. A PERIOD entry document ACCUMULATES every day's rows
542
- // (`updateMaterializedDiscountEntries` merges them in), so DELETING it discards
543
- // every OTHER day it holds - those rows exist nowhere else. The emptied day must
544
- // be SUBTRACTED from each period document, and only the day's OWN documents
545
- // dropped. Deleting the period document would also leave the period drill-down
546
- // empty until some later close recreated it, holding that one day.
547
- for (const doc of existingEntriesByScope.values()) {
548
- if (isThisDayEntryDoc(doc))
549
- staleEntryDocuments.push(doc);
550
- }
551
- for (const doc of existingEntriesByScope.values()) {
552
- // Another day's document is not this close's business - never touch it.
553
- if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
554
- continue;
555
- const remaining = subtractMaterializedDiscountEntrySections(doc.discount_entries, storedDayEntrySections);
556
- const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
557
- const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
558
- // Nothing of this day was in that period: leave it untouched.
559
- if (rowsAfter === rowsBefore)
560
- continue;
561
- // No rows left anywhere in the period: the document itself goes.
562
- if (rowsAfter === 0) {
563
- staleEntryDocuments.push(doc);
564
- continue;
565
- }
566
- if (addEntryWrite({
567
- ...doc,
568
- discount_entries: remaining,
569
- computed_at: computedAt,
570
- updatedAt: computedAt,
571
- iteration: (doc.iteration ?? 1) + 1,
572
- }) == null) {
573
- 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;
574
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
575
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);
576
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);
577
612
  return {
578
613
  writes,
579
614
  entryWrites,
@@ -582,6 +617,7 @@ export function buildTenantDiscountCloseDayPlan(input) {
582
617
  skippedDocuments,
583
618
  skippedEntryDocuments,
584
619
  createdPeriodDocuments,
620
+ foldedPeriodDayDocuments,
585
621
  };
586
622
  }
587
623
  const dayChanged = force || needsMaterializedDiscountReportWrite(storedDateDoc, storedDateDocInCompiled);
@@ -613,12 +649,109 @@ export function buildTenantDiscountCloseDayPlan(input) {
613
649
  if (!isAccumulatedScope(compiled.scope_context))
614
650
  return null; // unknown scope
615
651
  if (existing == null) {
616
- if (addWrite(compiled) == null)
652
+ // Missing period counter document: rebuild it from the sibling DAY
653
+ // counters that belong to this exact scope (plus the compiled day), so
654
+ // the period equals the sum of its days again. The closing day's own
655
+ // stored date document is excluded by the input contract.
656
+ const referenceDoc = storedDateDocInCompiled ?? reports[0];
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;
677
+ }
678
+ }
679
+ let created = compiled;
680
+ if (siblings.length > 0) {
681
+ const counters = JSON.parse(JSON.stringify(compiled.discount_counters ?? {}));
682
+ let watermark = new Date(compiled.source_watermark);
683
+ for (const sibling of siblings) {
684
+ applyCounters(counters, sibling.discount_counters, 1);
685
+ const siblingWatermark = new Date(sibling.source_watermark);
686
+ if (siblingWatermark.getTime() > watermark.getTime())
687
+ watermark = siblingWatermark;
688
+ }
689
+ for (const key of Object.keys(counters)) {
690
+ if (isZeroCounters(counters[key]))
691
+ delete counters[key];
692
+ }
693
+ const finalCounters = Object.keys(counters).length === 0
694
+ ? null
695
+ : counters;
696
+ created = {
697
+ ...compiled,
698
+ discount_counters: finalCounters,
699
+ discount_counter_rows: finalCounters == null
700
+ ? null
701
+ : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
702
+ source_watermark: watermark,
703
+ iteration: 1,
704
+ };
705
+ foldedPeriodDayDocuments += siblings.length;
706
+ }
707
+ if (addWrite(created) == null)
617
708
  return null;
618
709
  createdPeriodDocuments.push({ scope_context: compiled.scope_context, scope_field: compiled.scope_field });
619
710
  continue;
620
711
  }
621
- 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 });
622
755
  if (updated == null || addWrite(updated) == null)
623
756
  return null;
624
757
  }
@@ -632,110 +765,48 @@ export function buildTenantDiscountCloseDayPlan(input) {
632
765
  }
633
766
  }
634
767
  }
635
- // ---- entry documents ------------------------------------------------------
636
- // DAY scopes are replaced wholesale (the day is the whole truth); PERIOD scopes
637
- // MERGE the day's rows in - see updateMaterializedDiscountEntries. ----------
638
- 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();
639
773
  for (const doc of entries) {
640
774
  if (doc == null || doc.tenant_id !== tenantId)
641
775
  return null;
642
- const key = scopeKey(doc);
643
- 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))
644
785
  return null; // duplicate — data issue
645
- compiledEntriesByScope.set(key, doc);
786
+ compiledEntriesByPage.set(key, doc);
646
787
  }
647
- for (const compiled of compiledEntriesByScope.values()) {
648
- 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;
649
791
  if (!dayChanged && existing != null && !needsMaterializedDiscountEntriesWrite(existing, compiled)) {
650
792
  skippedEntryDocuments.push(existing);
651
793
  continue;
652
794
  }
653
795
  if (existing == null) {
654
- const missingIsPeriod = !DISCOUNT_DAY_SCOPES.includes(compiled.scope_context);
655
- if (!missingIsPeriod) {
656
- if (addEntryWrite(compiled) == null)
657
- return null;
658
- continue;
659
- }
660
- // A missing period entry document is a partial write only when the period
661
- // COUNTER document exists. Refuse to rebuild from an unverified fetch.
662
- const periodCounterExists = existingByScope.has(scopeKey(compiled));
663
- if (periodCounterExists && input.existingEntriesComplete !== true) {
664
- return null;
665
- }
666
- // Never persisted: rebuild from the sibling days, minus this day's stored rows (a
667
- // correction may have REMOVED rows), then merge this day's fresh rows on top.
668
- const folded = subtractMaterializedDiscountEntrySections(refoldPeriodEntrySections(compiled.scope_context, String(compiled.scope_field)), storedDayEntrySections);
669
- const rebuilt = mergeMaterializedDiscountEntrySections(folded, compiled.discount_entries);
670
- if (addEntryWrite({ ...compiled, discount_entries: rebuilt }) == null)
796
+ if (addEntryWrite(compiled) == null)
671
797
  return null;
672
798
  continue;
673
799
  }
674
- // A PERIOD document accumulates every day of the period; a DAY document is
675
- // the day itself. Replacing a period wholesale left it holding only the
676
- // final closed day (measured).
677
- const isPeriodEntry = !DISCOUNT_DAY_SCOPES.includes(compiled.scope_context);
678
- // PERIOD documents: remove this day's STORED rows FIRST, then merge the fresh ones.
679
- // Merging alone cannot remove, so a correction that dropped a row left it behind in
680
- // the period while the day document shrank - a phantom row in the period drill-down.
681
- // DAY documents are replaced wholesale and need no subtraction.
682
- const updated = updateMaterializedDiscountEntries(isPeriodEntry
683
- ? {
684
- ...existing,
685
- discount_entries: subtractMaterializedDiscountEntrySections(existing.discount_entries, storedDayEntrySections),
686
- }
687
- : existing, compiled, { computedAt, mergePeriodRows: isPeriodEntry });
800
+ const updated = updateMaterializedDiscountEntries(existing, compiled, { computedAt });
688
801
  if (updated == null || addEntryWrite(updated) == null)
689
802
  return null;
690
803
  }
691
- // Stored entry documents for this day's scopes that the compile no longer has.
692
- for (const doc of existingEntriesByScope.values()) {
693
- 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)))
694
808
  continue;
695
- const isDayScoped = doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
696
- ? doc.scope_field === localDate
697
- : doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
698
- typeof doc.scope_field === 'string' &&
699
- doc.scope_field.startsWith(`${localDate} `);
700
- if (isDayScoped) {
701
- staleEntryDocuments.push(doc);
702
- continue;
703
- }
704
- // A DAY-scoped document belonging to ANOTHER day is simply not this close's
705
- // business. Without this guard it fell through to the period branch below, where
706
- // the compile had (correctly) not emitted it, so it was marked STALE and DELETED -
707
- // meaning every close wiped every OTHER day's entry rows. Measured in the demo data
708
- // before the fix: counters covered 19 discount days while only ONE day of entry rows
709
- // survived, so the drill-down was empty for 18 days that the summary said had
710
- // discounts. The period branch must only ever see PERIOD scopes.
711
- if (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ||
712
- doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
713
- continue;
714
- }
715
- // The compiled day has no rows in this period scope. That does NOT mean the
716
- // period is empty: a period entry document accumulates EVERY day's rows, so
717
- // deleting it would wipe the sibling days that exist nowhere else. Subtract
718
- // the rows this day currently contributes (read from its day-scoped entry
719
- // documents) and drop the document only when nothing remains.
720
- const remaining = subtractMaterializedDiscountEntrySections(doc.discount_entries, storedDayEntrySections);
721
- const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
722
- const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
723
- // Nothing of this day was in that period: leave it untouched.
724
- if (rowsAfter === rowsBefore)
725
- continue;
726
- if (rowsAfter === 0) {
727
- staleEntryDocuments.push(doc);
728
- continue;
729
- }
730
- if (addEntryWrite({
731
- ...doc,
732
- discount_entries: remaining,
733
- computed_at: computedAt,
734
- updatedAt: computedAt,
735
- iteration: (doc.iteration ?? 1) + 1,
736
- }) == null) {
737
- return null;
738
- }
809
+ staleEntryDocuments.push(doc);
739
810
  }
740
811
  return {
741
812
  writes,
@@ -745,5 +816,6 @@ export function buildTenantDiscountCloseDayPlan(input) {
745
816
  skippedDocuments,
746
817
  skippedEntryDocuments,
747
818
  createdPeriodDocuments,
819
+ foldedPeriodDayDocuments,
748
820
  };
749
821
  }