@managesome/eposmatic-toolkit 0.4.29 → 0.4.31

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 (66) 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 +83 -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_active_jobs.js +7 -0
  19. package/esm/schemas/models/tenant_calendar.js +12 -0
  20. package/lib/constants/MATERIALIZED_REPORTS.d.ts +9 -12
  21. package/lib/constants/MATERIALIZED_REPORTS.js +11 -14
  22. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  23. package/lib/helpers/materialized-reports/index.js +1 -0
  24. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +38 -0
  25. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +129 -19
  26. package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  27. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +23 -61
  28. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +250 -239
  29. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.d.ts +4 -4
  30. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +1 -0
  31. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.d.ts +17 -0
  32. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +178 -0
  33. package/lib/helpers/materialized-reports/materialized-index-bootstrap.d.ts +7 -0
  34. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +87 -0
  35. package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +3 -1
  36. package/lib/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  37. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.d.ts +2 -2
  38. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  39. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  40. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +8 -0
  41. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +283 -42
  42. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -4
  43. package/lib/schemas/models/materialized_report_drilldown_rows.d.ts +40 -6
  44. package/lib/schemas/models/materialized_report_drilldown_rows.js +39 -12
  45. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +33 -29
  46. package/lib/schemas/models/materialized_tenant_discount_entries.js +18 -12
  47. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +6 -6
  48. package/lib/schemas/models/materialized_tenant_discount_sources.js +1 -1
  49. package/lib/schemas/models/orders.d.ts +5 -0
  50. package/lib/schemas/models/orders.js +5 -0
  51. package/lib/schemas/models/tenant_active_jobs.d.ts +7 -0
  52. package/lib/schemas/models/tenant_active_jobs.js +8 -1
  53. package/lib/schemas/models/tenant_calendar.d.ts +13 -0
  54. package/lib/schemas/models/tenant_calendar.js +13 -1
  55. package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +8 -0
  56. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +9 -5
  57. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +56 -1
  58. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +17 -0
  59. package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +60 -54
  60. package/lib/tests/materialized-reports/materialized-discount-entries-accumulation.test.js +14 -13
  61. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +76 -0
  62. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +11 -0
  63. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +2 -2
  64. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +152 -7
  65. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +89 -0
  66. package/package.json +1 -1
@@ -161,10 +161,41 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
161
161
  periodDayDocumentsByField.set(doc.scope_field, doc);
162
162
  periodDayDocuments.push(doc);
163
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
+ ];
164
188
  const dayDocumentBelongsToScope = (doc, scopeContext, scopeField) => {
165
189
  const refs = getMaterializedTenantSalesOverviewScopeRefsForDay(doc.scope_field);
166
190
  return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
167
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));
168
199
  // ------------------------------------------------------------------
169
200
  // Resolve THIS day against the stored credit ledger documents — the only
170
201
  // stateful step (receipt deltas, carried anchors, settlements), executed
@@ -260,8 +291,20 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
260
291
  // counters). The resolution emits each settlement exactly once.
261
292
  const settledTransitions = creditResolution.settled_bills;
262
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} `)));
263
307
  const dayChanged = force || needsMaterializedTenantSalesOverviewReportWrite(storedDateDoc, compiledDateDoc);
264
- const dayDeltaEmpty = !hasMaterializedMetrics(compiledDateDoc);
265
308
  const writes = [];
266
309
  const skippedDocuments = [];
267
310
  const createdPeriodDocuments = [];
@@ -308,11 +351,40 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
308
351
  // the period would hold only this close's delta while the earlier days'
309
352
  // `localDate` documents still exist — `localMonth` would no longer equal
310
353
  // the sum of its days.
311
- const siblings = periodDayDocuments.filter((doc) => dayDocumentBelongsToScope(doc, compiledDoc.scope_context, compiledDoc.scope_field));
312
- // An order-less close still repairs a missing period when sibling days
313
- // exist; with no deltas and no siblings there is nothing to create.
314
- if (dayDeltaEmpty && siblings.length === 0)
315
- continue;
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".
316
388
  let createdReport = compiledDoc;
317
389
  if (siblings.length > 0) {
318
390
  createdReport = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)([compiledDoc, ...siblings], {
@@ -334,11 +406,67 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
334
406
  skippedDocuments.push(existing);
335
407
  continue;
336
408
  }
337
- if (dayDeltaEmpty && storedDateDoc == null) {
338
- 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;
339
467
  continue;
340
468
  }
341
- 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 });
342
470
  if (updated == null || !addStructuralWrite(updated))
343
471
  return null;
344
472
  }
@@ -366,10 +494,12 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
366
494
  // pre-patch state with ALL deltas applied in a single update.
367
495
  const settledDeltasByDoc = new Map();
368
496
  for (const transition of settledTransitions) {
369
- 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;
370
500
  const issuePeriodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(transition.issued_local_date);
371
501
  if (issuePeriodFields == null)
372
- return null; // malformed issue date — data issue
502
+ return null;
373
503
  const issueScopeValues = new Set([transition.issued_local_date, ...Object.values(issuePeriodFields)]);
374
504
  for (const [scopeKey, doc] of postWriteByScope) {
375
505
  const scopeOnIssueDay = issueScopeValues.has(doc.scope_field) ||
@@ -457,6 +587,29 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
457
587
  const refs = (0, materialized_credit_bills_helpers_1.getMaterializedCreditBillScopeRefsForDay)(doc.scope_field);
458
588
  return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
459
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
+ };
460
613
  const creditExistingByScope = new Map();
461
614
  for (const doc of input.existingCreditBills ?? []) {
462
615
  if (doc == null || doc.tenant_id !== tenantId)
@@ -474,6 +627,7 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
474
627
  const creditSkippedDocuments = [];
475
628
  const creditStaleHourDocuments = [];
476
629
  const creditSettlementPatches = [];
630
+ const creditReceiptPatches = [];
477
631
  const addCreditWrite = (report) => {
478
632
  const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(report, {
479
633
  reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_CREDIT_BILLS,
@@ -488,28 +642,45 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
488
642
  const creditStoredDateDoc = creditExistingByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
489
643
  if (creditCompiledDocs.length === 0) {
490
644
  // Orders deleted / moved left the day with NO credit activity: subtract
491
- // the stored day from the period docs and drop the day/hour documents.
492
- if (creditStoredDateDoc != null) {
493
- for (const doc of creditExistingByScope.values()) {
494
- if (!creditAccumulatedScopes.includes(doc.scope_context))
495
- continue;
496
- 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 });
497
660
  if (updated == null)
498
661
  return null;
499
662
  if ((updated.iteration ?? 1) === (doc.iteration ?? 1))
500
- continue; // day not in this doc — no-op
663
+ continue;
501
664
  if (!addCreditWrite(updated))
502
665
  return null;
666
+ continue;
503
667
  }
504
- for (const doc of creditExistingByScope.values()) {
505
- const onDay = doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
506
- ? doc.scope_field === localDate
507
- : doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
508
- typeof doc.scope_field === 'string' &&
509
- doc.scope_field.startsWith(`${localDate} `);
510
- if (onDay)
511
- creditStaleHourDocuments.push(doc);
512
- }
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);
513
684
  }
514
685
  }
515
686
  else {
@@ -580,8 +751,55 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
580
751
  creditSkippedDocuments.push(existing);
581
752
  continue;
582
753
  }
583
- const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { subtract: creditStoredDateDoc != null ? [creditStoredDateDoc] : [], additions: [compiledCreditDoc] }, { computedAt });
584
- 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))
585
803
  return null;
586
804
  }
587
805
  if (creditDayChanged) {
@@ -594,10 +812,11 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
594
812
  }
595
813
  }
596
814
  }
597
- // Settlements patch the ISSUE scopes exactly once — computed against the
598
- // POST-write credit documents (persist after `creditWrites`), batched per
599
- // document so several settlements apply in one versioned update.
600
- 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) {
601
820
  const creditPostWriteByScope = new Map();
602
821
  for (const doc of creditExistingByScope.values())
603
822
  creditPostWriteByScope.set(materializedScopeKey(doc), doc);
@@ -606,24 +825,39 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
606
825
  for (const stale of creditStaleHourDocuments)
607
826
  creditPostWriteByScope.delete(materializedScopeKey(stale));
608
827
  const settlementsByScope = new Map();
609
- for (const settlement of creditResolution.settled_bills) {
610
- 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);
611
831
  if (refs == null)
612
- return null; // malformed issue date — data issue
832
+ return false; // malformed issue date — data issue
613
833
  for (const ref of refs) {
614
834
  const scopeKey = `${ref.scope_context}|${ref.scope_field}`;
615
835
  if (!creditPostWriteByScope.has(scopeKey))
616
836
  continue;
617
- const entries = settlementsByScope.get(scopeKey) ?? [];
618
- entries.push(settlement);
619
- 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;
620
851
  }
621
852
  }
622
- for (const [scopeKey, settlements] of settlementsByScope) {
853
+ const patchScopeKeys = new Set([...settlementsByScope.keys(), ...receiptsByScope.keys()]);
854
+ for (const scopeKey of patchScopeKeys) {
623
855
  const doc = creditPostWriteByScope.get(scopeKey);
624
856
  if (doc == null)
625
857
  continue;
626
- 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 });
627
861
  if (patched == null)
628
862
  return null;
629
863
  if ((patched.iteration ?? 1) === (doc.iteration ?? 1))
@@ -635,7 +869,13 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
635
869
  });
636
870
  if (iteration == null)
637
871
  return null;
638
- 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 });
639
879
  }
640
880
  }
641
881
  }
@@ -646,6 +886,7 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
646
886
  creditWrites,
647
887
  creditStaleHourDocuments,
648
888
  creditSettlementPatches,
889
+ creditReceiptPatches,
649
890
  creditSkippedDocuments,
650
891
  skippedDocuments,
651
892
  createdPeriodDocuments,
@@ -51,16 +51,16 @@ function isPaymentIncludedInMaterializedSalesOverview(payment) {
51
51
  function getMaterializedPaymentGross(payment) {
52
52
  const reportedType = normalizeMaterializedPaymentType(payment.payment_type);
53
53
  const isUnpaid = reportedType === constants_1.PAYMENT_TYPE_ENUM.UNPAID;
54
- // Money is integer CENTS: the result is rounded to the cent at this
55
- // boundary, because it feeds a materialized document.
54
+ // Money is integer CENTS. Do NOT round: a fractional source amount must fail
55
+ // the materialized-write integer gate, not be silently changed here.
56
56
  if ((payment.amount_refunded ?? 0) === 0) {
57
57
  let gross = isUnpaid ? (payment.amount_due ?? 0) : Math.min(payment.amount_paid ?? 0, payment.amount_due ?? 0);
58
58
  if (payment.card_details != null) {
59
59
  gross -= payment.card_details.card_charges ?? 0;
60
60
  }
61
- return Math.round(gross);
61
+ return gross;
62
62
  }
63
- return -Math.round(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
63
+ return -(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
64
64
  }
65
65
  const createEmptyOrderMetric = () => ({
66
66
  count: 0,
@@ -42,7 +42,7 @@ export declare const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES: {
42
42
  readonly _id: {
43
43
  readonly _id: 1;
44
44
  };
45
- readonly identity: {
45
+ readonly tenant_id__report_type__scope_context__scope_field__order_id__cursor_id: {
46
46
  readonly tenant_id: 1;
47
47
  readonly report_type: 1;
48
48
  readonly scope_context: 1;
@@ -50,7 +50,7 @@ export declare const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES: {
50
50
  readonly order_id: 1;
51
51
  readonly cursor_id: 1;
52
52
  };
53
- readonly read_asc: {
53
+ readonly tenant_id__report_type__scope_context__scope_field__time__order_id__cursor_id: {
54
54
  readonly tenant_id: 1;
55
55
  readonly report_type: 1;
56
56
  readonly scope_context: 1;
@@ -59,7 +59,7 @@ export declare const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES: {
59
59
  readonly order_id: 1;
60
60
  readonly cursor_id: 1;
61
61
  };
62
- readonly read_desc: {
62
+ readonly tenant_id__report_type__scope_context__scope_field__time__cursor_id: {
63
63
  readonly tenant_id: 1;
64
64
  readonly report_type: 1;
65
65
  readonly scope_context: 1;
@@ -67,6 +67,13 @@ export declare const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES: {
67
67
  readonly time: -1;
68
68
  readonly cursor_id: -1;
69
69
  };
70
+ readonly tenant_id__report_type__scope_context__scope_field__source_local_date: {
71
+ readonly tenant_id: 1;
72
+ readonly report_type: 1;
73
+ readonly scope_context: 1;
74
+ readonly scope_field: 1;
75
+ readonly source_local_date: 1;
76
+ };
70
77
  };
71
78
  export declare const MATERIALIZED_REPORT_DRILLDOWN_ROWS_INDEX_OPTIONS: ({
72
79
  key: {
@@ -102,19 +109,36 @@ export declare const MATERIALIZED_REPORT_DRILLDOWN_ROWS_INDEX_OPTIONS: ({
102
109
  };
103
110
  name: string;
104
111
  unique?: undefined;
112
+ } | {
113
+ key: {
114
+ readonly tenant_id: 1;
115
+ readonly report_type: 1;
116
+ readonly scope_context: 1;
117
+ readonly scope_field: 1;
118
+ readonly source_local_date: 1;
119
+ };
120
+ name: string;
121
+ unique?: undefined;
105
122
  })[];
106
123
  export declare const MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_INDEXES: {
107
124
  readonly _id: {
108
125
  readonly _id: 1;
109
126
  };
110
- readonly identity: {
127
+ readonly tenant_id__report_type__scope_context__scope_field: {
111
128
  readonly tenant_id: 1;
112
129
  readonly report_type: 1;
113
130
  readonly scope_context: 1;
114
131
  readonly scope_field: 1;
115
132
  };
133
+ readonly tenant_id__report_type__scope_context__scope_field__source_local_date: {
134
+ readonly tenant_id: 1;
135
+ readonly report_type: 1;
136
+ readonly scope_context: 1;
137
+ readonly scope_field: 1;
138
+ readonly source_local_date: 1;
139
+ };
116
140
  };
117
- export declare const MATERIALIZED_REPORT_DRILLDOWN_SCOPES_INDEX_OPTIONS: {
141
+ export declare const MATERIALIZED_REPORT_DRILLDOWN_SCOPES_INDEX_OPTIONS: ({
118
142
  key: {
119
143
  readonly tenant_id: 1;
120
144
  readonly report_type: 1;
@@ -123,7 +147,17 @@ export declare const MATERIALIZED_REPORT_DRILLDOWN_SCOPES_INDEX_OPTIONS: {
123
147
  };
124
148
  name: string;
125
149
  unique: boolean;
126
- }[];
150
+ } | {
151
+ key: {
152
+ readonly tenant_id: 1;
153
+ readonly report_type: 1;
154
+ readonly scope_context: 1;
155
+ readonly scope_field: 1;
156
+ readonly source_local_date: 1;
157
+ };
158
+ name: string;
159
+ unique?: undefined;
160
+ })[];
127
161
  /** The report-type values the flat reader accepts. */
128
162
  export declare const ALL_DRILLDOWN_REPORT_TYPE_VALUES: import("../types/materialized_report_drilldown_rows").TDrilldownReportType[];
129
163
  /** Kept explicit so the JSON/demo upload can validate a file's report type. */