@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
@@ -4,7 +4,7 @@ import { buildMaterializedCreditBillDayReports, getMaterializedCreditBillScopeRe
4
4
  import { buildMaterializedTenantReportIteration } from './materialized-tenant-reports-iterations-helpers';
5
5
  import { materializedDayInputSignatureChanged } from './materialized-day-input-signature';
6
6
  import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields } from './scope-helpers';
7
- import { normalizeMaterializedSaleTypeMetrics, sumMaterializedTenantSalesOverviewReports, updateMaterializedTenantSalesOverviewReport, } from './tenant-sales-overview-helpers';
7
+ import { normalizeMaterializedSaleTypeMetrics, subtractMaterializedTenantSalesOverviewReports, sumMaterializedTenantSalesOverviewReports, updateMaterializedTenantSalesOverviewReport, } from './tenant-sales-overview-helpers';
8
8
  /** Scopes written wholesale for the compiled day (replacement semantics). */
9
9
  const CLOSE_DAY_DAY_SCOPES = [
10
10
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
@@ -156,10 +156,41 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
156
156
  periodDayDocumentsByField.set(doc.scope_field, doc);
157
157
  periodDayDocuments.push(doc);
158
158
  }
159
+ // Month siblings for the upper levels (quarter/semester/year). A month is
160
+ // NEVER derived from weeks: Sunday-based weeks cross month boundaries.
161
+ const periodMonthDocuments = [];
162
+ for (const doc of input.existingPeriodMonthDocuments ?? []) {
163
+ if (doc == null || doc.tenant_id !== tenantId)
164
+ continue;
165
+ if (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)
166
+ continue;
167
+ if (typeof doc.scope_field !== 'string')
168
+ continue;
169
+ if (doc.schema_version !== compiledDateDoc.schema_version)
170
+ continue;
171
+ if ((doc.sale_type_key_filters ?? []).join(':') !== (compiledDateDoc.sale_type_key_filters ?? []).join(':')) {
172
+ continue;
173
+ }
174
+ if (doc.brand_id !== compiledDateDoc.brand_id)
175
+ continue;
176
+ periodMonthDocuments.push(doc);
177
+ }
178
+ const upperPeriodScopes = [
179
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
180
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
181
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
182
+ ];
159
183
  const dayDocumentBelongsToScope = (doc, scopeContext, scopeField) => {
160
184
  const refs = getMaterializedTenantSalesOverviewScopeRefsForDay(doc.scope_field);
161
185
  return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
162
186
  };
187
+ /** The sibling documents the hierarchy says to fold into a missing period. */
188
+ const periodSiblingsFor = (scopeContext, scopeField) => upperPeriodScopes.includes(scopeContext)
189
+ ? periodMonthDocuments.filter((doc) => {
190
+ const fields = getMaterializedPeriodScopeFields(`${doc.scope_field}-01`);
191
+ return fields != null && fields[scopeContext] === scopeField;
192
+ })
193
+ : periodDayDocuments.filter((doc) => dayDocumentBelongsToScope(doc, scopeContext, scopeField));
163
194
  // ------------------------------------------------------------------
164
195
  // Resolve THIS day against the stored credit ledger documents — the only
165
196
  // stateful step (receipt deltas, carried anchors, settlements), executed
@@ -255,8 +286,20 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
255
286
  // counters). The resolution emits each settlement exactly once.
256
287
  const settledTransitions = creditResolution.settled_bills;
257
288
  const storedDateDoc = existingByScope.get(materializedScopeKey(compiledDateDoc)) ?? null;
289
+ // A missing date document is a NEW day when no day-scoped document (date or
290
+ // hour) exists at all; otherwise it is a LOST document on a previously
291
+ // materialized day and needs the sibling rebuild. Without this distinction a
292
+ // first close after an earlier day of the same period would look like an
293
+ // unprovable repair.
294
+ const dayWasMaterialized = [...existingByScope.values()].some((doc) => (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
295
+ (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
296
+ typeof doc.scope_field === 'string' &&
297
+ doc.scope_field.startsWith(`${localDate} `))) ||
298
+ (input.existingCreditBills ?? []).some((doc) => (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
299
+ (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
300
+ typeof doc.scope_field === 'string' &&
301
+ doc.scope_field.startsWith(`${localDate} `)));
258
302
  const dayChanged = force || needsMaterializedTenantSalesOverviewReportWrite(storedDateDoc, compiledDateDoc);
259
- const dayDeltaEmpty = !hasMaterializedMetrics(compiledDateDoc);
260
303
  const writes = [];
261
304
  const skippedDocuments = [];
262
305
  const createdPeriodDocuments = [];
@@ -303,11 +346,40 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
303
346
  // the period would hold only this close's delta while the earlier days'
304
347
  // `localDate` documents still exist — `localMonth` would no longer equal
305
348
  // the sum of its days.
306
- const siblings = periodDayDocuments.filter((doc) => dayDocumentBelongsToScope(doc, compiledDoc.scope_context, compiledDoc.scope_field));
307
- // An order-less close still repairs a missing period when sibling days
308
- // exist; with no deltas and no siblings there is nothing to create.
309
- if (dayDeltaEmpty && siblings.length === 0)
310
- continue;
349
+ let siblings = periodSiblingsFor(compiledDoc.scope_context, String(compiledDoc.scope_field));
350
+ if (upperPeriodScopes.includes(compiledDoc.scope_context)) {
351
+ const currentMonth = localDate.slice(0, 7);
352
+ if (storedDateDoc == null && dayWasMaterialized)
353
+ return null; // month docs may still contain the lost day
354
+ if (storedDateDoc != null) {
355
+ // A stored date document proves the current month should exist. If
356
+ // the month sibling set is empty/incomplete, creating the upper
357
+ // period from the closing day alone would silently undercount it.
358
+ if (!siblings.some((doc) => doc.scope_field === currentMonth))
359
+ return null;
360
+ const corrected = [];
361
+ for (const month of siblings) {
362
+ if (month.scope_field !== currentMonth) {
363
+ corrected.push(month);
364
+ continue;
365
+ }
366
+ const dayDelta = {
367
+ ...storedDateDoc,
368
+ scope_context: month.scope_context,
369
+ scope_field: month.scope_field,
370
+ day_index: null,
371
+ };
372
+ const withoutDay = subtractMaterializedTenantSalesOverviewReports(month, dayDelta);
373
+ if (withoutDay == null)
374
+ return null;
375
+ corrected.push(withoutDay);
376
+ }
377
+ siblings = corrected;
378
+ }
379
+ }
380
+ // Even an order-less close writes its period marker: the Overview
381
+ // completeness probe needs a zero document for a legitimately empty
382
+ // period instead of reporting the period as "not materialized".
311
383
  let createdReport = compiledDoc;
312
384
  if (siblings.length > 0) {
313
385
  createdReport = sumMaterializedTenantSalesOverviewReports([compiledDoc, ...siblings], {
@@ -329,11 +401,67 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
329
401
  skippedDocuments.push(existing);
330
402
  continue;
331
403
  }
332
- if (dayDeltaEmpty && storedDateDoc == null) {
333
- skippedDocuments.push(existing); // first close of an order-less day — nothing to fold
404
+ // MISSING DATE DOCUMENT: the stored day delta is unknown. Do NOT add the
405
+ // fresh day to a running sum that may already contain it. Rebuild the
406
+ // period from the stored sibling DAY documents + the fresh day. If the
407
+ // period has data but no sibling evidence at all, the repair is unprovable;
408
+ // fail loudly instead of guessing.
409
+ if (storedDateDoc == null) {
410
+ if (dayWasMaterialized && upperPeriodScopes.includes(compiledDoc.scope_context)) {
411
+ // The month documents may still contain the lost day; a quarter cannot
412
+ // be repaired by adding the fresh day. Fail loudly.
413
+ return null;
414
+ }
415
+ let siblings = periodSiblingsFor(compiledDoc.scope_context, String(compiledDoc.scope_field));
416
+ if (upperPeriodScopes.includes(compiledDoc.scope_context) && siblings.length === 0) {
417
+ // The month document may be the one that was lost. The stored localDate
418
+ // documents are still valid evidence for this upper period; use them
419
+ // instead of falling back to an unprovable additive write.
420
+ siblings = periodDayDocuments.filter((doc) => dayDocumentBelongsToScope(doc, compiledDoc.scope_context, String(compiledDoc.scope_field)));
421
+ }
422
+ if (!dayWasMaterialized) {
423
+ // No day-scoped document survives, so the stored day delta is unknown.
424
+ // The period is additive ONLY if it currently equals the sibling days
425
+ // exactly (the day contributed nothing / this is its first close).
426
+ // Otherwise the missing day is still INSIDE the period and adding the
427
+ // fresh delta would double it — fail loudly instead of guessing.
428
+ if (siblings.length === 0) {
429
+ // The period exists but the old day delta is unprovable. Adding the
430
+ // fresh day could double it; fail loudly instead.
431
+ return null;
432
+ }
433
+ const siblingSum = sumMaterializedTenantSalesOverviewReports(siblings, { computedAt });
434
+ if (siblingSum == null ||
435
+ JSON.stringify(existing.sale_type_metrics ?? {}) !== JSON.stringify(siblingSum.sale_type_metrics ?? {})) {
436
+ return null;
437
+ }
438
+ const updated = updateMaterializedTenantSalesOverviewReport(existing, { additions: [compiledDoc] }, { computedAt });
439
+ if (updated == null)
440
+ return null;
441
+ if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
442
+ skippedDocuments.push(existing);
443
+ continue;
444
+ }
445
+ if (!addStructuralWrite(updated))
446
+ return null;
447
+ continue;
448
+ }
449
+ if (siblings.length === 0 && hasMaterializedMetrics(existing)) {
450
+ // Unprovable repair: a non-empty period with no sibling day evidence.
451
+ // The worker turns a null plan into a permanent, logged close failure.
452
+ return null;
453
+ }
454
+ const rebuilt = siblings.length > 0
455
+ ? sumMaterializedTenantSalesOverviewReports([compiledDoc, ...siblings], { computedAt })
456
+ : compiledDoc;
457
+ if (rebuilt == null)
458
+ return null;
459
+ const updated = updateMaterializedTenantSalesOverviewReport(existing, { replacement: rebuilt }, { computedAt });
460
+ if (updated == null || !addStructuralWrite(updated))
461
+ return null;
334
462
  continue;
335
463
  }
336
- const updated = updateMaterializedTenantSalesOverviewReport(existing, { subtract: storedDateDoc != null ? [storedDateDoc] : [], additions: [compiledDoc] }, { computedAt });
464
+ const updated = updateMaterializedTenantSalesOverviewReport(existing, { subtract: [storedDateDoc], additions: [compiledDoc] }, { computedAt });
337
465
  if (updated == null || !addStructuralWrite(updated))
338
466
  return null;
339
467
  }
@@ -361,10 +489,12 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
361
489
  // pre-patch state with ALL deltas applied in a single update.
362
490
  const settledDeltasByDoc = new Map();
363
491
  for (const transition of settledTransitions) {
364
- const billKey = transition.key;
492
+ // Patch the section the ISSUE document actually holds — the order status
493
+ // may have changed between the issue day and the collection day.
494
+ const billKey = transition.stored_key ?? transition.key;
365
495
  const issuePeriodFields = getMaterializedPeriodScopeFields(transition.issued_local_date);
366
496
  if (issuePeriodFields == null)
367
- return null; // malformed issue date — data issue
497
+ return null;
368
498
  const issueScopeValues = new Set([transition.issued_local_date, ...Object.values(issuePeriodFields)]);
369
499
  for (const [scopeKey, doc] of postWriteByScope) {
370
500
  const scopeOnIssueDay = issueScopeValues.has(doc.scope_field) ||
@@ -452,6 +582,29 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
452
582
  const refs = getMaterializedCreditBillScopeRefsForDay(doc.scope_field);
453
583
  return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
454
584
  };
585
+ const hasCreditBillEntries = (doc) => Object.values(doc.credit_bills ?? {}).some((section) => (section?.issued ?? []).length > 0 || (section?.received ?? []).length > 0);
586
+ const buildCreditPeriodReplacement = (existing, compiled, siblings) => {
587
+ const sections = {};
588
+ let watermark = new Date(existing.source_watermark);
589
+ if (compiled != null) {
590
+ mergeMaterializedCreditBillSections(sections, compiled.credit_bills);
591
+ const compiledWatermark = new Date(compiled.source_watermark);
592
+ if (compiledWatermark.getTime() > watermark.getTime())
593
+ watermark = compiledWatermark;
594
+ }
595
+ for (const sibling of siblings) {
596
+ mergeMaterializedCreditBillSections(sections, sibling.credit_bills);
597
+ const siblingWatermark = new Date(sibling.source_watermark);
598
+ if (siblingWatermark.getTime() > watermark.getTime())
599
+ watermark = siblingWatermark;
600
+ }
601
+ return {
602
+ ...existing,
603
+ credit_bills: sections,
604
+ source_watermark: watermark,
605
+ source_input_signature: existing.source_input_signature,
606
+ };
607
+ };
455
608
  const creditExistingByScope = new Map();
456
609
  for (const doc of input.existingCreditBills ?? []) {
457
610
  if (doc == null || doc.tenant_id !== tenantId)
@@ -469,6 +622,7 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
469
622
  const creditSkippedDocuments = [];
470
623
  const creditStaleHourDocuments = [];
471
624
  const creditSettlementPatches = [];
625
+ const creditReceiptPatches = [];
472
626
  const addCreditWrite = (report) => {
473
627
  const iteration = buildMaterializedTenantReportIteration(report, {
474
628
  reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_CREDIT_BILLS,
@@ -483,28 +637,45 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
483
637
  const creditStoredDateDoc = creditExistingByScope.get(`${MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
484
638
  if (creditCompiledDocs.length === 0) {
485
639
  // Orders deleted / moved left the day with NO credit activity: subtract
486
- // the stored day from the period docs and drop the day/hour documents.
487
- if (creditStoredDateDoc != null) {
488
- for (const doc of creditExistingByScope.values()) {
489
- if (!creditAccumulatedScopes.includes(doc.scope_context))
490
- continue;
491
- const updated = updateMaterializedCreditBillsReport(doc, { subtract: [creditStoredDateDoc] }, { computedAt });
640
+ // the stored day from the period docs (or rebuild them from siblings when
641
+ // the date document itself is missing) and drop the day/hour documents.
642
+ for (const doc of creditExistingByScope.values()) {
643
+ if (!creditAccumulatedScopes.includes(doc.scope_context))
644
+ continue;
645
+ if (creditStoredDateDoc == null && !dayWasMaterialized)
646
+ continue; // new order-less day — no stored delta
647
+ if (creditStoredDateDoc == null) {
648
+ const siblings = creditPeriodDayDocuments.filter((sibling) => creditDayDocumentBelongsToScope(sibling, doc.scope_context, doc.scope_field));
649
+ if (siblings.length === 0 && hasCreditBillEntries(doc))
650
+ return null; // unprovable repair
651
+ const replacement = buildCreditPeriodReplacement(doc, null, siblings);
652
+ if (replacement == null)
653
+ return null;
654
+ const updated = updateMaterializedCreditBillsReport(doc, { replacement }, { computedAt });
492
655
  if (updated == null)
493
656
  return null;
494
657
  if ((updated.iteration ?? 1) === (doc.iteration ?? 1))
495
- continue; // day not in this doc — no-op
658
+ continue;
496
659
  if (!addCreditWrite(updated))
497
660
  return null;
661
+ continue;
498
662
  }
499
- for (const doc of creditExistingByScope.values()) {
500
- const onDay = doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
501
- ? doc.scope_field === localDate
502
- : doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
503
- typeof doc.scope_field === 'string' &&
504
- doc.scope_field.startsWith(`${localDate} `);
505
- if (onDay)
506
- creditStaleHourDocuments.push(doc);
507
- }
663
+ const updated = updateMaterializedCreditBillsReport(doc, { subtract: [creditStoredDateDoc] }, { computedAt });
664
+ if (updated == null)
665
+ return null;
666
+ if ((updated.iteration ?? 1) === (doc.iteration ?? 1))
667
+ continue; // day not in this doc — no-op
668
+ if (!addCreditWrite(updated))
669
+ return null;
670
+ }
671
+ for (const doc of creditExistingByScope.values()) {
672
+ const onDay = doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
673
+ ? doc.scope_field === localDate
674
+ : doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
675
+ typeof doc.scope_field === 'string' &&
676
+ doc.scope_field.startsWith(`${localDate} `);
677
+ if (onDay)
678
+ creditStaleHourDocuments.push(doc);
508
679
  }
509
680
  }
510
681
  else {
@@ -575,8 +746,55 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
575
746
  creditSkippedDocuments.push(existing);
576
747
  continue;
577
748
  }
578
- const updated = updateMaterializedCreditBillsReport(existing, { subtract: creditStoredDateDoc != null ? [creditStoredDateDoc] : [], additions: [compiledCreditDoc] }, { computedAt });
579
- if (updated == null || !addCreditWrite(updated))
749
+ if (creditStoredDateDoc == null) {
750
+ const siblings = creditPeriodDayDocuments.filter((sibling) => creditDayDocumentBelongsToScope(sibling, compiledCreditDoc.scope_context, compiledCreditDoc.scope_field));
751
+ if (!dayWasMaterialized) {
752
+ if (siblings.length === 0) {
753
+ if (hasCreditBillEntries(existing))
754
+ return null;
755
+ }
756
+ else {
757
+ const siblingOnly = buildCreditPeriodReplacement(existing, null, siblings);
758
+ if (siblingOnly == null ||
759
+ JSON.stringify(siblingOnly.credit_bills ?? {}) !== JSON.stringify(existing.credit_bills ?? {})) {
760
+ return null;
761
+ }
762
+ }
763
+ const updated = updateMaterializedCreditBillsReport(existing, { additions: [compiledCreditDoc] }, { computedAt });
764
+ if (updated == null)
765
+ return null;
766
+ if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
767
+ creditSkippedDocuments.push(existing);
768
+ continue;
769
+ }
770
+ if (!addCreditWrite(updated))
771
+ return null;
772
+ continue;
773
+ }
774
+ if (siblings.length === 0 && hasCreditBillEntries(existing))
775
+ return null; // unprovable repair
776
+ const replacement = buildCreditPeriodReplacement(existing, compiledCreditDoc, siblings);
777
+ if (replacement == null)
778
+ return null;
779
+ const updated = updateMaterializedCreditBillsReport(existing, { replacement }, { computedAt });
780
+ if (updated == null)
781
+ return null;
782
+ if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
783
+ creditSkippedDocuments.push(existing);
784
+ continue;
785
+ }
786
+ if (!addCreditWrite(updated))
787
+ return null;
788
+ continue;
789
+ }
790
+ const updated = updateMaterializedCreditBillsReport(existing, { subtract: [creditStoredDateDoc], additions: [compiledCreditDoc] }, { computedAt });
791
+ if (updated == null)
792
+ return null;
793
+ if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
794
+ creditSkippedDocuments.push(existing);
795
+ continue;
796
+ }
797
+ if (!addCreditWrite(updated))
580
798
  return null;
581
799
  }
582
800
  if (creditDayChanged) {
@@ -589,10 +807,11 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
589
807
  }
590
808
  }
591
809
  }
592
- // Settlements patch the ISSUE scopes exactly once — computed against the
593
- // POST-write credit documents (persist after `creditWrites`), batched per
594
- // document so several settlements apply in one versioned update.
595
- if (creditResolution.settled_bills.length > 0) {
810
+ // Settlements AND partial receipts patch the ISSUE scopes exactly once —
811
+ // computed against the POST-write credit documents (persist after
812
+ // `creditWrites`), batched per document so several patches apply in one
813
+ // versioned update.
814
+ if (creditResolution.settled_bills.length > 0 || creditResolution.receipt_bills.length > 0) {
596
815
  const creditPostWriteByScope = new Map();
597
816
  for (const doc of creditExistingByScope.values())
598
817
  creditPostWriteByScope.set(materializedScopeKey(doc), doc);
@@ -601,24 +820,39 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
601
820
  for (const stale of creditStaleHourDocuments)
602
821
  creditPostWriteByScope.delete(materializedScopeKey(stale));
603
822
  const settlementsByScope = new Map();
604
- for (const settlement of creditResolution.settled_bills) {
605
- const refs = getMaterializedCreditBillScopeRefsForIssue(settlement.issued_local_date, settlement.issued_local_hour);
823
+ const receiptsByScope = new Map();
824
+ const addScopePatch = (map, patch, issuedLocalDate, issuedLocalHour) => {
825
+ const refs = getMaterializedCreditBillScopeRefsForIssue(issuedLocalDate, issuedLocalHour);
606
826
  if (refs == null)
607
- return null; // malformed issue date — data issue
827
+ return false; // malformed issue date — data issue
608
828
  for (const ref of refs) {
609
829
  const scopeKey = `${ref.scope_context}|${ref.scope_field}`;
610
830
  if (!creditPostWriteByScope.has(scopeKey))
611
831
  continue;
612
- const entries = settlementsByScope.get(scopeKey) ?? [];
613
- entries.push(settlement);
614
- settlementsByScope.set(scopeKey, entries);
832
+ const entries = map.get(scopeKey) ?? [];
833
+ entries.push(patch);
834
+ map.set(scopeKey, entries);
835
+ }
836
+ return true;
837
+ };
838
+ for (const settlement of creditResolution.settled_bills) {
839
+ if (!addScopePatch(settlementsByScope, settlement, settlement.issued_local_date, settlement.issued_local_hour)) {
840
+ return null;
841
+ }
842
+ }
843
+ for (const receipt of creditResolution.receipt_bills) {
844
+ if (!addScopePatch(receiptsByScope, receipt, receipt.issued_local_date, receipt.issued_local_hour)) {
845
+ return null;
615
846
  }
616
847
  }
617
- for (const [scopeKey, settlements] of settlementsByScope) {
848
+ const patchScopeKeys = new Set([...settlementsByScope.keys(), ...receiptsByScope.keys()]);
849
+ for (const scopeKey of patchScopeKeys) {
618
850
  const doc = creditPostWriteByScope.get(scopeKey);
619
851
  if (doc == null)
620
852
  continue;
621
- const patched = updateMaterializedCreditBillsReport(doc, { settled_bills: settlements }, { computedAt });
853
+ const settlements = settlementsByScope.get(scopeKey) ?? [];
854
+ const receipts = receiptsByScope.get(scopeKey) ?? [];
855
+ const patched = updateMaterializedCreditBillsReport(doc, { settled_bills: settlements, receipt_bills: receipts }, { computedAt });
622
856
  if (patched == null)
623
857
  return null;
624
858
  if ((patched.iteration ?? 1) === (doc.iteration ?? 1))
@@ -630,7 +864,13 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
630
864
  });
631
865
  if (iteration == null)
632
866
  return null;
633
- creditSettlementPatches.push({ report: patched, iteration });
867
+ // A document carrying a settlement goes in the settlement list (the
868
+ // report counters are handled separately); a partial-only patch goes in
869
+ // the receipt list.
870
+ if (settlements.length > 0)
871
+ creditSettlementPatches.push({ report: patched, iteration });
872
+ else
873
+ creditReceiptPatches.push({ report: patched, iteration });
634
874
  }
635
875
  }
636
876
  }
@@ -641,6 +881,7 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
641
881
  creditWrites,
642
882
  creditStaleHourDocuments,
643
883
  creditSettlementPatches,
884
+ creditReceiptPatches,
644
885
  creditSkippedDocuments,
645
886
  skippedDocuments,
646
887
  createdPeriodDocuments,
@@ -35,16 +35,16 @@ export function isPaymentIncludedInMaterializedSalesOverview(payment) {
35
35
  export function getMaterializedPaymentGross(payment) {
36
36
  const reportedType = normalizeMaterializedPaymentType(payment.payment_type);
37
37
  const isUnpaid = reportedType === PAYMENT_TYPE_ENUM.UNPAID;
38
- // Money is integer CENTS: the result is rounded to the cent at this
39
- // boundary, because it feeds a materialized document.
38
+ // Money is integer CENTS. Do NOT round: a fractional source amount must fail
39
+ // the materialized-write integer gate, not be silently changed here.
40
40
  if ((payment.amount_refunded ?? 0) === 0) {
41
41
  let gross = isUnpaid ? (payment.amount_due ?? 0) : Math.min(payment.amount_paid ?? 0, payment.amount_due ?? 0);
42
42
  if (payment.card_details != null) {
43
43
  gross -= payment.card_details.card_charges ?? 0;
44
44
  }
45
- return Math.round(gross);
45
+ return gross;
46
46
  }
47
- return -Math.round(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
47
+ return -(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
48
48
  }
49
49
  // `isMaterializedCreditBillPayment` moved to `./materialized-credit-bills-helpers`
50
50
  // (imported above) — re-exported here for API stability.
@@ -40,6 +40,9 @@ export const MaterializedReportDrilldownRowSchema = new Schema({
40
40
  // The original row is polymorphic across reports; the report_type
41
41
  // discriminator says which shape it is.
42
42
  data: { type: Schema.Types.Mixed, required: true },
43
+ // Null only on legacy rows written before the incremental flat projection.
44
+ // The writer rebuilds a touched scope once and stamps every rebuilt row.
45
+ source_local_date: { type: String, default: null },
43
46
  schema_version: {
44
47
  type: Number,
45
48
  required: true,
@@ -66,6 +69,8 @@ export const MaterializedReportDrilldownScopeSchema = new Schema({
66
69
  scope_field: { type: String, required: true, immutable: true },
67
70
  row_count: { type: Number, required: true, min: 0, default: 0 },
68
71
  off_app_order_count: { type: Number, required: true, min: 0, default: 0 },
72
+ /** Last day whose close updated this scope (not an identity). */
73
+ source_local_date: { type: String, default: null },
69
74
  schema_version: {
70
75
  type: Number,
71
76
  required: true,
@@ -84,7 +89,7 @@ export const MaterializedReportDrilldownScopeSchema = new Schema({
84
89
  */
85
90
  export const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES = {
86
91
  _id: { _id: 1 },
87
- identity: {
92
+ tenant_id__report_type__scope_context__scope_field__order_id__cursor_id: {
88
93
  tenant_id: 1,
89
94
  report_type: 1,
90
95
  scope_context: 1,
@@ -92,7 +97,7 @@ export const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES = {
92
97
  order_id: 1,
93
98
  cursor_id: 1,
94
99
  },
95
- read_asc: {
100
+ tenant_id__report_type__scope_context__scope_field__time__order_id__cursor_id: {
96
101
  tenant_id: 1,
97
102
  report_type: 1,
98
103
  scope_context: 1,
@@ -101,7 +106,7 @@ export const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES = {
101
106
  order_id: 1,
102
107
  cursor_id: 1,
103
108
  },
104
- read_desc: {
109
+ tenant_id__report_type__scope_context__scope_field__time__cursor_id: {
105
110
  tenant_id: 1,
106
111
  report_type: 1,
107
112
  scope_context: 1,
@@ -109,37 +114,59 @@ export const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES = {
109
114
  time: -1,
110
115
  cursor_id: -1,
111
116
  },
117
+ tenant_id__report_type__scope_context__scope_field__source_local_date: {
118
+ tenant_id: 1,
119
+ report_type: 1,
120
+ scope_context: 1,
121
+ scope_field: 1,
122
+ source_local_date: 1,
123
+ },
112
124
  };
113
125
  export const MATERIALIZED_REPORT_DRILLDOWN_ROWS_INDEX_OPTIONS = [
114
126
  {
115
- key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.identity,
116
- name: 'tenant_id__report_type__scope__order_id__cursor_id',
127
+ key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field__order_id__cursor_id,
128
+ name: 'tenant_id__report_type__scope_context__scope_field__order_id__cursor_id',
117
129
  unique: true,
118
130
  },
119
131
  {
120
- key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.read_asc,
121
- name: 'tenant_id__report_type__scope__time_desc__order_id__cursor_id',
132
+ key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field__time__order_id__cursor_id,
133
+ name: 'tenant_id__report_type__scope_context__scope_field__time__order_id__cursor_id',
134
+ },
135
+ {
136
+ key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field__time__cursor_id,
137
+ name: 'tenant_id__report_type__scope_context__scope_field__time__cursor_id',
122
138
  },
123
139
  {
124
- key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.read_desc,
125
- name: 'tenant_id__report_type__scope__time_desc__cursor_id_desc',
140
+ key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field__source_local_date,
141
+ name: 'tenant_id__report_type__scope_context__scope_field__source_local_date',
126
142
  },
127
143
  ];
128
144
  export const MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_INDEXES = {
129
145
  _id: { _id: 1 },
130
- identity: {
146
+ tenant_id__report_type__scope_context__scope_field: {
131
147
  tenant_id: 1,
132
148
  report_type: 1,
133
149
  scope_context: 1,
134
150
  scope_field: 1,
135
151
  },
152
+ tenant_id__report_type__scope_context__scope_field__source_local_date: {
153
+ tenant_id: 1,
154
+ report_type: 1,
155
+ scope_context: 1,
156
+ scope_field: 1,
157
+ source_local_date: 1,
158
+ },
136
159
  };
137
160
  export const MATERIALIZED_REPORT_DRILLDOWN_SCOPES_INDEX_OPTIONS = [
138
161
  {
139
- key: MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_INDEXES.identity,
140
- name: 'tenant_id__report_type__scope',
162
+ key: MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field,
163
+ name: 'tenant_id__report_type__scope_context__scope_field',
141
164
  unique: true,
142
165
  },
166
+ {
167
+ key: MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field__source_local_date,
168
+ name: 'tenant_id__report_type__scope_context__scope_field__source_local_date',
169
+ },
143
170
  ];
144
171
  /** The report-type values the flat reader accepts. */
145
172
  export const ALL_DRILLDOWN_REPORT_TYPE_VALUES = ALL_DRILLDOWN_REPORT_TYPES;
@@ -7,10 +7,12 @@ import { ALL_MATERIALIZED_DISCOUNT_ENTRY_KINDS, ALL_MATERIALIZED_DISCOUNT_LEVELS
7
7
  * SPLIT). See `schemas/types/materialized_tenant_discount_entries.ts` and
8
8
  * `docs/report-discounts-concept.md`.
9
9
  *
10
- * Scopes are capped at `LOCAL_MONTH` so a document can never grow unboundedly.
11
- * Rows are slim (ids + discount facts); each carries `entry_key`, its stable
12
- * identity INSIDE an order, so the `(time, order_id, entry_key)` cursor can
13
- * never collide. Amounts are CENTS; reads pin `schema_version`.
10
+ * Documents are PAGE-PARTITIONED by source day: day/hour scopes use
11
+ * `page='all'`; a period scope uses `page=<source localDate>`, so each document
12
+ * is bounded by one day's rows. Rows are slim (ids + discount facts); each
13
+ * carries `entry_key`, its stable identity INSIDE an order, so the
14
+ * `(time, order_id, entry_key)` cursor can never collide. Amounts are CENTS;
15
+ * reads pin `schema_version`.
14
16
  */
15
17
  /**
16
18
  * Version of the discount ENTRY rules of this collection. Bump when row
@@ -85,6 +87,11 @@ export const MaterializedTenantDiscountEntriesSchema = new Schema({
85
87
  type: String,
86
88
  required: true,
87
89
  },
90
+ page: {
91
+ type: String,
92
+ required: true,
93
+ immutable: true,
94
+ },
88
95
  day_index: {
89
96
  type: String,
90
97
  default: null,
@@ -145,24 +152,23 @@ export const MaterializedTenantDiscountEntriesSchema = new Schema({
145
152
  export { DiscountEntrySchema };
146
153
  export const MATERIALIZED_TENANT_DISCOUNT_ENTRIES_COLLECTION_NAME = 'materialized_tenant_discount_entries';
147
154
  /**
148
- * Indexes for `materialized_tenant_discount_entries` — the same single
149
- * UNIQUE compound identity index as every materialized report collection. The
150
- * `{ tenant_id, scope_context, scope_field }` prefix also serves the
151
- * drill-down's month-document resolution.
155
+ * Indexes for `materialized_tenant_discount_entries` — ONE unique index per
156
+ * page. The `{ tenant_id, scope_context, scope_field, page }` prefix serves
157
+ * both page replacement and the operations multi-page aggregation.
152
158
  */
153
159
  export const MATERIALIZED_TENANT_DISCOUNT_ENTRIES_COLLECTION_INDEXES = {
154
160
  _id: { _id: 1 },
155
- tenant_id__scope_context__scope_field__day_index: {
161
+ tenant_id__scope_context__scope_field__page: {
156
162
  tenant_id: 1,
157
163
  scope_context: 1,
158
164
  scope_field: 1,
159
- day_index: 1,
165
+ page: 1,
160
166
  },
161
167
  };
162
168
  export const MATERIALIZED_TENANT_DISCOUNT_ENTRIES_INDEX_OPTIONS = [
163
169
  {
164
- key: { tenant_id: 1, scope_context: 1, scope_field: 1, day_index: 1 },
165
- name: 'tenant_id__scope_context__scope_field__day_index',
170
+ key: { tenant_id: 1, scope_context: 1, scope_field: 1, page: 1 },
171
+ name: 'tenant_id__scope_context__scope_field__page',
166
172
  unique: true,
167
173
  },
168
174
  ];