@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
@@ -7,6 +7,7 @@ const constants_1 = require("../../constants");
7
7
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
8
8
  const materialized_credit_bills_helpers_1 = require("./materialized-credit-bills-helpers");
9
9
  const materialized_tenant_reports_iterations_helpers_1 = require("./materialized-tenant-reports-iterations-helpers");
10
+ const materialized_day_input_signature_1 = require("./materialized-day-input-signature");
10
11
  const scope_helpers_1 = require("./scope-helpers");
11
12
  const tenant_sales_overview_helpers_1 = require("./tenant-sales-overview-helpers");
12
13
  /** Scopes written wholesale for the compiled day (replacement semantics). */
@@ -55,9 +56,12 @@ function getMaterializedTenantSalesOverviewScopeRefsForDay(localDate) {
55
56
  * structural write for the incoming compiled version?
56
57
  *
57
58
  * `false` (skip) when the incoming `source_watermark` is not newer than the
58
- * stored one and the schema version + key-filter grammar match. Watermarks are
59
- * monotonic (`updateMaterializedTenantSalesOverviewReport` never regresses
60
- * them). A missing stored document always needs a write.
59
+ * stored one, the day-input SIGNATURE is unchanged, and the schema version +
60
+ * key-filter grammar match. Watermarks are monotonic
61
+ * (`updateMaterializedTenantSalesOverviewReport` never regresses them); the
62
+ * signature is the SET-shaped signal that detects a deleted / moved order even
63
+ * when the incoming watermark is lower than the stored one. A missing stored
64
+ * document always needs a write.
61
65
  */
62
66
  function needsMaterializedTenantSalesOverviewReportWrite(existing, incoming) {
63
67
  if (existing == null || incoming == null)
@@ -67,6 +71,11 @@ function needsMaterializedTenantSalesOverviewReportWrite(existing, incoming) {
67
71
  if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
68
72
  return true;
69
73
  }
74
+ // Set-shaped signal FIRST: a delete / move must correct even when the
75
+ // incoming watermark regressed below the stored one.
76
+ if ((0, materialized_day_input_signature_1.materializedDayInputSignatureChanged)(existing.source_input_signature, incoming.source_input_signature)) {
77
+ return true;
78
+ }
70
79
  const existingTime = new Date(existing.source_watermark ?? 0).getTime();
71
80
  const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
72
81
  if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
@@ -125,6 +134,68 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
125
134
  if (String(prior._id) !== String(doc._id))
126
135
  return null;
127
136
  }
137
+ // REPAIR SOURCE: stored sibling DAY documents, used only when a period
138
+ // document has to be CREATED. A period is a running sum, so seeding it with
139
+ // the closing day alone would leave every earlier materialized day out of
140
+ // the period while its `localDate` document still exists (month ≠ Σ days).
141
+ // The closing day itself is excluded: the freshly compiled day replaces it.
142
+ const periodDayDocuments = [];
143
+ const periodDayDocumentsByField = new Map();
144
+ for (const doc of input.existingPeriodDayDocuments ?? []) {
145
+ if (doc == null || doc.tenant_id !== tenantId)
146
+ continue;
147
+ if (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
148
+ continue;
149
+ if (typeof doc.scope_field !== 'string' || doc.scope_field === localDate)
150
+ continue;
151
+ // A day document from another schema version / brand cannot be summed
152
+ // (`sumMaterialized…` would return null and fail the whole close); it is
153
+ // ignored here and re-materialized by its own close.
154
+ if (doc.schema_version !== compiledDateDoc.schema_version)
155
+ continue;
156
+ if ((doc.sale_type_key_filters ?? []).join(':') !== (compiledDateDoc.sale_type_key_filters ?? []).join(':')) {
157
+ continue;
158
+ }
159
+ if (doc.brand_id !== compiledDateDoc.brand_id)
160
+ continue;
161
+ periodDayDocumentsByField.set(doc.scope_field, doc);
162
+ periodDayDocuments.push(doc);
163
+ }
164
+ // Month siblings for the upper levels (quarter/semester/year). A month is
165
+ // NEVER derived from weeks: Sunday-based weeks cross month boundaries.
166
+ const periodMonthDocuments = [];
167
+ for (const doc of input.existingPeriodMonthDocuments ?? []) {
168
+ if (doc == null || doc.tenant_id !== tenantId)
169
+ continue;
170
+ if (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)
171
+ continue;
172
+ if (typeof doc.scope_field !== 'string')
173
+ continue;
174
+ if (doc.schema_version !== compiledDateDoc.schema_version)
175
+ continue;
176
+ if ((doc.sale_type_key_filters ?? []).join(':') !== (compiledDateDoc.sale_type_key_filters ?? []).join(':')) {
177
+ continue;
178
+ }
179
+ if (doc.brand_id !== compiledDateDoc.brand_id)
180
+ continue;
181
+ periodMonthDocuments.push(doc);
182
+ }
183
+ const upperPeriodScopes = [
184
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
185
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
186
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
187
+ ];
188
+ const dayDocumentBelongsToScope = (doc, scopeContext, scopeField) => {
189
+ const refs = getMaterializedTenantSalesOverviewScopeRefsForDay(doc.scope_field);
190
+ return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
191
+ };
192
+ /** The sibling documents the hierarchy says to fold into a missing period. */
193
+ const periodSiblingsFor = (scopeContext, scopeField) => upperPeriodScopes.includes(scopeContext)
194
+ ? periodMonthDocuments.filter((doc) => {
195
+ const fields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(`${doc.scope_field}-01`);
196
+ return fields != null && fields[scopeContext] === scopeField;
197
+ })
198
+ : periodDayDocuments.filter((doc) => dayDocumentBelongsToScope(doc, scopeContext, scopeField));
128
199
  // ------------------------------------------------------------------
129
200
  // Resolve THIS day against the stored credit ledger documents — the only
130
201
  // stateful step (receipt deltas, carried anchors, settlements), executed
@@ -220,11 +291,25 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
220
291
  // counters). The resolution emits each settlement exactly once.
221
292
  const settledTransitions = creditResolution.settled_bills;
222
293
  const storedDateDoc = existingByScope.get(materializedScopeKey(compiledDateDoc)) ?? null;
294
+ // A missing date document is a NEW day when no day-scoped document (date or
295
+ // hour) exists at all; otherwise it is a LOST document on a previously
296
+ // materialized day and needs the sibling rebuild. Without this distinction a
297
+ // first close after an earlier day of the same period would look like an
298
+ // unprovable repair.
299
+ const dayWasMaterialized = [...existingByScope.values()].some((doc) => (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
300
+ (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
301
+ typeof doc.scope_field === 'string' &&
302
+ doc.scope_field.startsWith(`${localDate} `))) ||
303
+ (input.existingCreditBills ?? []).some((doc) => (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
304
+ (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
305
+ typeof doc.scope_field === 'string' &&
306
+ doc.scope_field.startsWith(`${localDate} `)));
223
307
  const dayChanged = force || needsMaterializedTenantSalesOverviewReportWrite(storedDateDoc, compiledDateDoc);
224
- const dayDeltaEmpty = !hasMaterializedMetrics(compiledDateDoc);
225
308
  const writes = [];
226
309
  const skippedDocuments = [];
227
310
  const createdPeriodDocuments = [];
311
+ let foldedPeriodDayDocuments = 0;
312
+ let foldedPeriodDayCreditDocuments = 0;
228
313
  const addStructuralWrite = (report) => {
229
314
  const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(report, {
230
315
  reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
@@ -261,9 +346,55 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
261
346
  if (!CLOSE_DAY_ACCUMULATED_SCOPES.includes(compiledDoc.scope_context))
262
347
  return null; // unknown scope — data issue
263
348
  if (existing == null) {
264
- if (dayDeltaEmpty)
265
- continue; // nothing to fold into a (new) period document
266
- if (!addStructuralWrite(compiledDoc))
349
+ // Missing period document: REPAIR it from the stored sibling days that
350
+ // belong to this exact scope, then add the closing day. Without the fold
351
+ // the period would hold only this close's delta while the earlier days'
352
+ // `localDate` documents still exist — `localMonth` would no longer equal
353
+ // the sum of its days.
354
+ let siblings = periodSiblingsFor(compiledDoc.scope_context, String(compiledDoc.scope_field));
355
+ if (upperPeriodScopes.includes(compiledDoc.scope_context)) {
356
+ const currentMonth = localDate.slice(0, 7);
357
+ if (storedDateDoc == null && dayWasMaterialized)
358
+ return null; // month docs may still contain the lost day
359
+ if (storedDateDoc != null) {
360
+ // A stored date document proves the current month should exist. If
361
+ // the month sibling set is empty/incomplete, creating the upper
362
+ // period from the closing day alone would silently undercount it.
363
+ if (!siblings.some((doc) => doc.scope_field === currentMonth))
364
+ return null;
365
+ const corrected = [];
366
+ for (const month of siblings) {
367
+ if (month.scope_field !== currentMonth) {
368
+ corrected.push(month);
369
+ continue;
370
+ }
371
+ const dayDelta = {
372
+ ...storedDateDoc,
373
+ scope_context: month.scope_context,
374
+ scope_field: month.scope_field,
375
+ day_index: null,
376
+ };
377
+ const withoutDay = (0, tenant_sales_overview_helpers_1.subtractMaterializedTenantSalesOverviewReports)(month, dayDelta);
378
+ if (withoutDay == null)
379
+ return null;
380
+ corrected.push(withoutDay);
381
+ }
382
+ siblings = corrected;
383
+ }
384
+ }
385
+ // Even an order-less close writes its period marker: the Overview
386
+ // completeness probe needs a zero document for a legitimately empty
387
+ // period instead of reporting the period as "not materialized".
388
+ let createdReport = compiledDoc;
389
+ if (siblings.length > 0) {
390
+ createdReport = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)([compiledDoc, ...siblings], {
391
+ computedAt,
392
+ });
393
+ if (createdReport == null)
394
+ return null; // inconsistent sibling — data issue
395
+ foldedPeriodDayDocuments += siblings.length;
396
+ }
397
+ if (createdReport == null || !addStructuralWrite(createdReport))
267
398
  return null;
268
399
  createdPeriodDocuments.push({
269
400
  scope_context: compiledDoc.scope_context,
@@ -275,11 +406,67 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
275
406
  skippedDocuments.push(existing);
276
407
  continue;
277
408
  }
278
- if (dayDeltaEmpty && storedDateDoc == null) {
279
- skippedDocuments.push(existing); // first close of an order-less day — nothing to fold
409
+ // MISSING DATE DOCUMENT: the stored day delta is unknown. Do NOT add the
410
+ // fresh day to a running sum that may already contain it. Rebuild the
411
+ // period from the stored sibling DAY documents + the fresh day. If the
412
+ // period has data but no sibling evidence at all, the repair is unprovable;
413
+ // fail loudly instead of guessing.
414
+ if (storedDateDoc == null) {
415
+ if (dayWasMaterialized && upperPeriodScopes.includes(compiledDoc.scope_context)) {
416
+ // The month documents may still contain the lost day; a quarter cannot
417
+ // be repaired by adding the fresh day. Fail loudly.
418
+ return null;
419
+ }
420
+ let siblings = periodSiblingsFor(compiledDoc.scope_context, String(compiledDoc.scope_field));
421
+ if (upperPeriodScopes.includes(compiledDoc.scope_context) && siblings.length === 0) {
422
+ // The month document may be the one that was lost. The stored localDate
423
+ // documents are still valid evidence for this upper period; use them
424
+ // instead of falling back to an unprovable additive write.
425
+ siblings = periodDayDocuments.filter((doc) => dayDocumentBelongsToScope(doc, compiledDoc.scope_context, String(compiledDoc.scope_field)));
426
+ }
427
+ if (!dayWasMaterialized) {
428
+ // No day-scoped document survives, so the stored day delta is unknown.
429
+ // The period is additive ONLY if it currently equals the sibling days
430
+ // exactly (the day contributed nothing / this is its first close).
431
+ // Otherwise the missing day is still INSIDE the period and adding the
432
+ // fresh delta would double it — fail loudly instead of guessing.
433
+ if (siblings.length === 0) {
434
+ // The period exists but the old day delta is unprovable. Adding the
435
+ // fresh day could double it; fail loudly instead.
436
+ return null;
437
+ }
438
+ const siblingSum = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)(siblings, { computedAt });
439
+ if (siblingSum == null ||
440
+ JSON.stringify(existing.sale_type_metrics ?? {}) !== JSON.stringify(siblingSum.sale_type_metrics ?? {})) {
441
+ return null;
442
+ }
443
+ const updated = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(existing, { additions: [compiledDoc] }, { computedAt });
444
+ if (updated == null)
445
+ return null;
446
+ if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
447
+ skippedDocuments.push(existing);
448
+ continue;
449
+ }
450
+ if (!addStructuralWrite(updated))
451
+ return null;
452
+ continue;
453
+ }
454
+ if (siblings.length === 0 && hasMaterializedMetrics(existing)) {
455
+ // Unprovable repair: a non-empty period with no sibling day evidence.
456
+ // The worker turns a null plan into a permanent, logged close failure.
457
+ return null;
458
+ }
459
+ const rebuilt = siblings.length > 0
460
+ ? (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)([compiledDoc, ...siblings], { computedAt })
461
+ : compiledDoc;
462
+ if (rebuilt == null)
463
+ return null;
464
+ const updated = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(existing, { replacement: rebuilt }, { computedAt });
465
+ if (updated == null || !addStructuralWrite(updated))
466
+ return null;
280
467
  continue;
281
468
  }
282
- const updated = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(existing, { subtract: storedDateDoc != null ? [storedDateDoc] : [], additions: [compiledDoc] }, { computedAt });
469
+ const updated = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(existing, { subtract: [storedDateDoc], additions: [compiledDoc] }, { computedAt });
283
470
  if (updated == null || !addStructuralWrite(updated))
284
471
  return null;
285
472
  }
@@ -307,10 +494,12 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
307
494
  // pre-patch state with ALL deltas applied in a single update.
308
495
  const settledDeltasByDoc = new Map();
309
496
  for (const transition of settledTransitions) {
310
- const billKey = transition.key;
497
+ // Patch the section the ISSUE document actually holds — the order status
498
+ // may have changed between the issue day and the collection day.
499
+ const billKey = transition.stored_key ?? transition.key;
311
500
  const issuePeriodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(transition.issued_local_date);
312
501
  if (issuePeriodFields == null)
313
- return null; // malformed issue date — data issue
502
+ return null;
314
503
  const issueScopeValues = new Set([transition.issued_local_date, ...Object.values(issuePeriodFields)]);
315
504
  for (const [scopeKey, doc] of postWriteByScope) {
316
505
  const scopeOnIssueDay = issueScopeValues.has(doc.scope_field) ||
@@ -366,9 +555,61 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
366
555
  localDate,
367
556
  resolution: creditResolution,
368
557
  computedAt,
558
+ sourceInputSignature: compiledDateDoc.source_input_signature ?? null,
369
559
  });
370
560
  if (creditCompiledDocs == null)
371
561
  return null;
562
+ // REPAIR SOURCE for missing credit PERIOD documents — the stored sibling
563
+ // DAY documents (the closing day is replaced by the compiled one). Mirrors
564
+ // the sales-overview fold above; without it a recreated month document would
565
+ // hold only this close's bills while the other days' date documents exist.
566
+ const creditPeriodDayDocuments = [];
567
+ // The credit collection has its OWN schema version / key grammar — compare
568
+ // siblings against a compiled CREDIT document, never the overview envelope.
569
+ const creditReferenceDoc = creditCompiledDocs[0] ?? null;
570
+ for (const doc of input.existingPeriodDayCreditDocuments ?? []) {
571
+ if (creditReferenceDoc == null)
572
+ break;
573
+ if (doc == null || doc.tenant_id !== tenantId)
574
+ continue;
575
+ if (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
576
+ continue;
577
+ if (typeof doc.scope_field !== 'string' || doc.scope_field === localDate)
578
+ continue;
579
+ if (doc.schema_version !== creditReferenceDoc.schema_version)
580
+ continue;
581
+ if (JSON.stringify(doc.sale_type_key_filters ?? []) !== JSON.stringify(creditReferenceDoc.sale_type_key_filters ?? [])) {
582
+ continue;
583
+ }
584
+ creditPeriodDayDocuments.push(doc);
585
+ }
586
+ const creditDayDocumentBelongsToScope = (doc, scopeContext, scopeField) => {
587
+ const refs = (0, materialized_credit_bills_helpers_1.getMaterializedCreditBillScopeRefsForDay)(doc.scope_field);
588
+ return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
589
+ };
590
+ const hasCreditBillEntries = (doc) => Object.values(doc.credit_bills ?? {}).some((section) => (section?.issued ?? []).length > 0 || (section?.received ?? []).length > 0);
591
+ const buildCreditPeriodReplacement = (existing, compiled, siblings) => {
592
+ const sections = {};
593
+ let watermark = new Date(existing.source_watermark);
594
+ if (compiled != null) {
595
+ (0, materialized_credit_bills_helpers_1.mergeMaterializedCreditBillSections)(sections, compiled.credit_bills);
596
+ const compiledWatermark = new Date(compiled.source_watermark);
597
+ if (compiledWatermark.getTime() > watermark.getTime())
598
+ watermark = compiledWatermark;
599
+ }
600
+ for (const sibling of siblings) {
601
+ (0, materialized_credit_bills_helpers_1.mergeMaterializedCreditBillSections)(sections, sibling.credit_bills);
602
+ const siblingWatermark = new Date(sibling.source_watermark);
603
+ if (siblingWatermark.getTime() > watermark.getTime())
604
+ watermark = siblingWatermark;
605
+ }
606
+ return {
607
+ ...existing,
608
+ credit_bills: sections,
609
+ source_watermark: watermark,
610
+ source_input_signature: existing.source_input_signature,
611
+ };
612
+ };
372
613
  const creditExistingByScope = new Map();
373
614
  for (const doc of input.existingCreditBills ?? []) {
374
615
  if (doc == null || doc.tenant_id !== tenantId)
@@ -386,6 +627,7 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
386
627
  const creditSkippedDocuments = [];
387
628
  const creditStaleHourDocuments = [];
388
629
  const creditSettlementPatches = [];
630
+ const creditReceiptPatches = [];
389
631
  const addCreditWrite = (report) => {
390
632
  const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(report, {
391
633
  reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_CREDIT_BILLS,
@@ -400,28 +642,45 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
400
642
  const creditStoredDateDoc = creditExistingByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
401
643
  if (creditCompiledDocs.length === 0) {
402
644
  // Orders deleted / moved left the day with NO credit activity: subtract
403
- // the stored day from the period docs and drop the day/hour documents.
404
- if (creditStoredDateDoc != null) {
405
- for (const doc of creditExistingByScope.values()) {
406
- if (!creditAccumulatedScopes.includes(doc.scope_context))
407
- continue;
408
- const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(doc, { subtract: [creditStoredDateDoc] }, { computedAt });
645
+ // the stored day from the period docs (or rebuild them from siblings when
646
+ // the date document itself is missing) and drop the day/hour documents.
647
+ for (const doc of creditExistingByScope.values()) {
648
+ if (!creditAccumulatedScopes.includes(doc.scope_context))
649
+ continue;
650
+ if (creditStoredDateDoc == null && !dayWasMaterialized)
651
+ continue; // new order-less day — no stored delta
652
+ if (creditStoredDateDoc == null) {
653
+ const siblings = creditPeriodDayDocuments.filter((sibling) => creditDayDocumentBelongsToScope(sibling, doc.scope_context, doc.scope_field));
654
+ if (siblings.length === 0 && hasCreditBillEntries(doc))
655
+ return null; // unprovable repair
656
+ const replacement = buildCreditPeriodReplacement(doc, null, siblings);
657
+ if (replacement == null)
658
+ return null;
659
+ const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(doc, { replacement }, { computedAt });
409
660
  if (updated == null)
410
661
  return null;
411
662
  if ((updated.iteration ?? 1) === (doc.iteration ?? 1))
412
- continue; // day not in this doc — no-op
663
+ continue;
413
664
  if (!addCreditWrite(updated))
414
665
  return null;
666
+ continue;
415
667
  }
416
- for (const doc of creditExistingByScope.values()) {
417
- const onDay = doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
418
- ? doc.scope_field === localDate
419
- : doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
420
- typeof doc.scope_field === 'string' &&
421
- doc.scope_field.startsWith(`${localDate} `);
422
- if (onDay)
423
- creditStaleHourDocuments.push(doc);
424
- }
668
+ const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(doc, { subtract: [creditStoredDateDoc] }, { computedAt });
669
+ if (updated == null)
670
+ return null;
671
+ if ((updated.iteration ?? 1) === (doc.iteration ?? 1))
672
+ continue; // day not in this doc — no-op
673
+ if (!addCreditWrite(updated))
674
+ return null;
675
+ }
676
+ for (const doc of creditExistingByScope.values()) {
677
+ const onDay = doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
678
+ ? doc.scope_field === localDate
679
+ : doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
680
+ typeof doc.scope_field === 'string' &&
681
+ doc.scope_field.startsWith(`${localDate} `);
682
+ if (onDay)
683
+ creditStaleHourDocuments.push(doc);
425
684
  }
426
685
  }
427
686
  else {
@@ -461,7 +720,30 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
461
720
  if (!creditAccumulatedScopes.includes(compiledCreditDoc.scope_context))
462
721
  return null; // unknown scope — data issue
463
722
  if (existing == null) {
464
- if (!addCreditWrite(compiledCreditDoc))
723
+ // Missing period document: rebuild it from the sibling DAY documents
724
+ // that belong to this exact scope (the closing day is the compiled
725
+ // document), so the ledger stays equal to the sum of its days.
726
+ const siblings = creditPeriodDayDocuments.filter((doc) => creditDayDocumentBelongsToScope(doc, compiledCreditDoc.scope_context, compiledCreditDoc.scope_field));
727
+ let created = compiledCreditDoc;
728
+ if (siblings.length > 0) {
729
+ const sections = {};
730
+ (0, materialized_credit_bills_helpers_1.mergeMaterializedCreditBillSections)(sections, compiledCreditDoc.credit_bills);
731
+ let watermark = new Date(compiledCreditDoc.source_watermark);
732
+ for (const sibling of siblings) {
733
+ (0, materialized_credit_bills_helpers_1.mergeMaterializedCreditBillSections)(sections, sibling.credit_bills);
734
+ const siblingWatermark = new Date(sibling.source_watermark);
735
+ if (siblingWatermark.getTime() > watermark.getTime())
736
+ watermark = siblingWatermark;
737
+ }
738
+ created = {
739
+ ...compiledCreditDoc,
740
+ credit_bills: sections,
741
+ source_watermark: watermark,
742
+ iteration: 1,
743
+ };
744
+ foldedPeriodDayCreditDocuments += siblings.length;
745
+ }
746
+ if (!addCreditWrite(created))
465
747
  return null;
466
748
  continue;
467
749
  }
@@ -469,8 +751,55 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
469
751
  creditSkippedDocuments.push(existing);
470
752
  continue;
471
753
  }
472
- const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { subtract: creditStoredDateDoc != null ? [creditStoredDateDoc] : [], additions: [compiledCreditDoc] }, { computedAt });
473
- if (updated == null || !addCreditWrite(updated))
754
+ if (creditStoredDateDoc == null) {
755
+ const siblings = creditPeriodDayDocuments.filter((sibling) => creditDayDocumentBelongsToScope(sibling, compiledCreditDoc.scope_context, compiledCreditDoc.scope_field));
756
+ if (!dayWasMaterialized) {
757
+ if (siblings.length === 0) {
758
+ if (hasCreditBillEntries(existing))
759
+ return null;
760
+ }
761
+ else {
762
+ const siblingOnly = buildCreditPeriodReplacement(existing, null, siblings);
763
+ if (siblingOnly == null ||
764
+ JSON.stringify(siblingOnly.credit_bills ?? {}) !== JSON.stringify(existing.credit_bills ?? {})) {
765
+ return null;
766
+ }
767
+ }
768
+ const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { additions: [compiledCreditDoc] }, { computedAt });
769
+ if (updated == null)
770
+ return null;
771
+ if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
772
+ creditSkippedDocuments.push(existing);
773
+ continue;
774
+ }
775
+ if (!addCreditWrite(updated))
776
+ return null;
777
+ continue;
778
+ }
779
+ if (siblings.length === 0 && hasCreditBillEntries(existing))
780
+ return null; // unprovable repair
781
+ const replacement = buildCreditPeriodReplacement(existing, compiledCreditDoc, siblings);
782
+ if (replacement == null)
783
+ return null;
784
+ const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { replacement }, { computedAt });
785
+ if (updated == null)
786
+ return null;
787
+ if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
788
+ creditSkippedDocuments.push(existing);
789
+ continue;
790
+ }
791
+ if (!addCreditWrite(updated))
792
+ return null;
793
+ continue;
794
+ }
795
+ const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { subtract: [creditStoredDateDoc], additions: [compiledCreditDoc] }, { computedAt });
796
+ if (updated == null)
797
+ return null;
798
+ if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
799
+ creditSkippedDocuments.push(existing);
800
+ continue;
801
+ }
802
+ if (!addCreditWrite(updated))
474
803
  return null;
475
804
  }
476
805
  if (creditDayChanged) {
@@ -483,10 +812,11 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
483
812
  }
484
813
  }
485
814
  }
486
- // Settlements patch the ISSUE scopes exactly once — computed against the
487
- // POST-write credit documents (persist after `creditWrites`), batched per
488
- // document so several settlements apply in one versioned update.
489
- if (creditResolution.settled_bills.length > 0) {
815
+ // Settlements AND partial receipts patch the ISSUE scopes exactly once —
816
+ // computed against the POST-write credit documents (persist after
817
+ // `creditWrites`), batched per document so several patches apply in one
818
+ // versioned update.
819
+ if (creditResolution.settled_bills.length > 0 || creditResolution.receipt_bills.length > 0) {
490
820
  const creditPostWriteByScope = new Map();
491
821
  for (const doc of creditExistingByScope.values())
492
822
  creditPostWriteByScope.set(materializedScopeKey(doc), doc);
@@ -495,24 +825,39 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
495
825
  for (const stale of creditStaleHourDocuments)
496
826
  creditPostWriteByScope.delete(materializedScopeKey(stale));
497
827
  const settlementsByScope = new Map();
498
- for (const settlement of creditResolution.settled_bills) {
499
- const refs = (0, materialized_credit_bills_helpers_1.getMaterializedCreditBillScopeRefsForIssue)(settlement.issued_local_date, settlement.issued_local_hour);
828
+ const receiptsByScope = new Map();
829
+ const addScopePatch = (map, patch, issuedLocalDate, issuedLocalHour) => {
830
+ const refs = (0, materialized_credit_bills_helpers_1.getMaterializedCreditBillScopeRefsForIssue)(issuedLocalDate, issuedLocalHour);
500
831
  if (refs == null)
501
- return null; // malformed issue date — data issue
832
+ return false; // malformed issue date — data issue
502
833
  for (const ref of refs) {
503
834
  const scopeKey = `${ref.scope_context}|${ref.scope_field}`;
504
835
  if (!creditPostWriteByScope.has(scopeKey))
505
836
  continue;
506
- const entries = settlementsByScope.get(scopeKey) ?? [];
507
- entries.push(settlement);
508
- settlementsByScope.set(scopeKey, entries);
837
+ const entries = map.get(scopeKey) ?? [];
838
+ entries.push(patch);
839
+ map.set(scopeKey, entries);
840
+ }
841
+ return true;
842
+ };
843
+ for (const settlement of creditResolution.settled_bills) {
844
+ if (!addScopePatch(settlementsByScope, settlement, settlement.issued_local_date, settlement.issued_local_hour)) {
845
+ return null;
846
+ }
847
+ }
848
+ for (const receipt of creditResolution.receipt_bills) {
849
+ if (!addScopePatch(receiptsByScope, receipt, receipt.issued_local_date, receipt.issued_local_hour)) {
850
+ return null;
509
851
  }
510
852
  }
511
- for (const [scopeKey, settlements] of settlementsByScope) {
853
+ const patchScopeKeys = new Set([...settlementsByScope.keys(), ...receiptsByScope.keys()]);
854
+ for (const scopeKey of patchScopeKeys) {
512
855
  const doc = creditPostWriteByScope.get(scopeKey);
513
856
  if (doc == null)
514
857
  continue;
515
- const patched = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(doc, { settled_bills: settlements }, { computedAt });
858
+ const settlements = settlementsByScope.get(scopeKey) ?? [];
859
+ const receipts = receiptsByScope.get(scopeKey) ?? [];
860
+ const patched = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(doc, { settled_bills: settlements, receipt_bills: receipts }, { computedAt });
516
861
  if (patched == null)
517
862
  return null;
518
863
  if ((patched.iteration ?? 1) === (doc.iteration ?? 1))
@@ -524,7 +869,13 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
524
869
  });
525
870
  if (iteration == null)
526
871
  return null;
527
- creditSettlementPatches.push({ report: patched, iteration });
872
+ // A document carrying a settlement goes in the settlement list (the
873
+ // report counters are handled separately); a partial-only patch goes in
874
+ // the receipt list.
875
+ if (settlements.length > 0)
876
+ creditSettlementPatches.push({ report: patched, iteration });
877
+ else
878
+ creditReceiptPatches.push({ report: patched, iteration });
528
879
  }
529
880
  }
530
881
  }
@@ -535,8 +886,11 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
535
886
  creditWrites,
536
887
  creditStaleHourDocuments,
537
888
  creditSettlementPatches,
889
+ creditReceiptPatches,
538
890
  creditSkippedDocuments,
539
891
  skippedDocuments,
540
892
  createdPeriodDocuments,
893
+ foldedPeriodDayDocuments,
894
+ foldedPeriodDayCreditDocuments,
541
895
  };
542
896
  }
@@ -226,7 +226,10 @@ export interface IUpdateMaterializedTenantSalesOverviewReportInput {
226
226
  * so replays stay churn-free;
227
227
  * 4. `source_watermark` advances to the max of the existing and the incoming
228
228
  * (`replacement` / `additions`) watermarks — monotonic, never regressed
229
- * (rollbacks / replays keep the previously folded maximum).
229
+ * (rollbacks / replays keep the previously folded maximum);
230
+ * 5. `source_input_signature` follows a `replacement` (the fresh day compile)
231
+ * and is KEPT on period accumulates — a period's payload is a running sum,
232
+ * not one day's input set.
230
233
  *
231
234
  * Returns a new JSON report; the input is not mutated.
232
235
  */