@managesome/eposmatic-toolkit 0.4.28 → 0.4.29

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 (45) hide show
  1. package/esm/helpers/materialized-reports/index.js +1 -0
  2. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +49 -20
  3. package/esm/helpers/materialized-reports/materialized-day-input-signature.js +103 -0
  4. package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +63 -2
  5. package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +18 -0
  6. package/esm/helpers/materialized-reports/scope-helpers.js +27 -0
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +122 -9
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +24 -2
  9. package/esm/schemas/models/materialized_credit_bills.js +8 -0
  10. package/esm/schemas/models/materialized_tenant_discount_reports.js +9 -0
  11. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
  12. package/esm/schemas/models/tenant_active_jobs.js +8 -0
  13. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  14. package/lib/helpers/materialized-reports/index.js +1 -0
  15. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +28 -2
  16. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +50 -20
  17. package/lib/helpers/materialized-reports/materialized-day-input-signature.d.ts +66 -0
  18. package/lib/helpers/materialized-reports/materialized-day-input-signature.js +108 -0
  19. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +20 -1
  20. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +63 -2
  21. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +18 -0
  22. package/lib/helpers/materialized-reports/scope-helpers.d.ts +22 -0
  23. package/lib/helpers/materialized-reports/scope-helpers.js +28 -0
  24. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +41 -3
  25. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +120 -7
  26. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +4 -1
  27. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +24 -2
  28. package/lib/schemas/models/materialized_credit_bills.d.ts +3 -0
  29. package/lib/schemas/models/materialized_credit_bills.js +8 -0
  30. package/lib/schemas/models/materialized_tenant_discount_reports.d.ts +3 -0
  31. package/lib/schemas/models/materialized_tenant_discount_reports.js +9 -0
  32. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +3 -0
  33. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
  34. package/lib/schemas/models/tenant_active_jobs.d.ts +3 -0
  35. package/lib/schemas/models/tenant_active_jobs.js +8 -0
  36. package/lib/schemas/types/materialized_credit_bills.d.ts +6 -0
  37. package/lib/schemas/types/materialized_tenant_discount_reports.d.ts +6 -0
  38. package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +9 -0
  39. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +14 -0
  40. package/lib/schemas/types/tenant_active_jobs.d.ts +8 -0
  41. package/lib/tests/materialized-reports/materialized-day-input-signature.test.d.ts +1 -0
  42. package/lib/tests/materialized-reports/materialized-day-input-signature.test.js +81 -0
  43. package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +89 -0
  44. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +162 -0
  45. package/package.json +1 -1
@@ -18,6 +18,7 @@ export * from './materialized-delivery-accumulator-helpers';
18
18
  export * from './materialized-delivery-compile-helpers';
19
19
  export * from './materialized-delivery-classification-helpers';
20
20
  export * from './materialized-delivery-close-day-helpers';
21
+ export * from './materialized-day-input-signature';
21
22
  export * from './materialized-cash-classification-helpers';
22
23
  export * from './materialized-cash-close-day-helpers';
23
24
  export * from './materialized-cash-compile-helpers';
@@ -4,6 +4,7 @@ import { ALL_MATERIALIZED_REPORT_SCOPES, MATERIALIZED_REPORT_CREDIT_BILL_EVENT_T
4
4
  import { MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION } from '../../schemas/models/materialized_credit_bills';
5
5
  import { getLocalDocumentFields, getLocalFieldsFromLocalDate } from '../utils/time-helpers';
6
6
  import { buildMaterializedReportKey } from './key-helpers';
7
+ import { materializedDayInputSignatureChanged } from './materialized-day-input-signature';
7
8
  import { getDayIndexFromLocalDate, getMaterializedHourScopeField, getMaterializedPeriodScopeFields, } from './scope-helpers';
8
9
  /**
9
10
  * The shared credit-bill ledger (`materialized_tenant_credit_bills`) —
@@ -341,6 +342,39 @@ export function resolveCreditBillDay(input) {
341
342
  }
342
343
  const emptySection = () => ({ issued: [], received: [] });
343
344
  const sectionFor = (map, key) => map[key] ?? (map[key] = emptySection());
345
+ /**
346
+ * Folds `source` sections INTO `target` (mutating it), identity-matched:
347
+ * an ISSUED entry is one `(order_id, payment_id)` bill; a RECEIVED entry is one
348
+ * `(order_id, payment_id, event_local_date)` collection event. A source entry
349
+ * REPLACES its target counterpart (fresh wins), so re-applying the same day is
350
+ * idempotent.
351
+ *
352
+ * Exported because the close-day plan uses the SAME merge when it rebuilds a
353
+ * MISSING period document from the stored day documents (a deleted period
354
+ * document must not be recreated from the closing day alone; see
355
+ * `buildTenantSalesOverviewCloseDayPlan`'s period repair).
356
+ */
357
+ export function mergeMaterializedCreditBillSections(target, source) {
358
+ for (const [key, section] of Object.entries(source ?? {})) {
359
+ const bucket = target[key] ?? (target[key] = emptySection());
360
+ for (const entry of section?.issued ?? []) {
361
+ const identity = creditBillIdentityKey(entry.order_id, entry.payment_id);
362
+ const index = bucket.issued.findIndex((current) => creditBillIdentityKey(current.order_id, current.payment_id) === identity);
363
+ if (index >= 0)
364
+ bucket.issued[index] = entry;
365
+ else
366
+ bucket.issued.push(entry);
367
+ }
368
+ for (const entry of section?.received ?? []) {
369
+ const identity = `${creditBillIdentityKey(entry.order_id, entry.payment_id)}|${entry.event_local_date}`;
370
+ const index = bucket.received.findIndex((current) => `${creditBillIdentityKey(current.order_id, current.payment_id)}|${current.event_local_date}` === identity);
371
+ if (index >= 0)
372
+ bucket.received[index] = entry;
373
+ else
374
+ bucket.received.push(entry);
375
+ }
376
+ }
377
+ }
344
378
  /**
345
379
  * Materializes ONE day's credit documents from its resolution — the
346
380
  * month-capped scope set (`MATERIALIZED_CREDIT_BILLS_SCOPES`): one document per
@@ -351,6 +385,7 @@ export function buildMaterializedCreditBillDayReports(input) {
351
385
  if (input == null)
352
386
  return null;
353
387
  const { tenantId, brandId, localDate, resolution, computedAt } = input;
388
+ const sourceInputSignature = input.sourceInputSignature ?? undefined;
354
389
  const periodFields = getMaterializedPeriodScopeFields(localDate);
355
390
  if (periodFields == null)
356
391
  return null;
@@ -420,6 +455,7 @@ export function buildMaterializedCreditBillDayReports(input) {
420
455
  iteration: 1,
421
456
  schema_version: MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION,
422
457
  source_watermark: sourceWatermark,
458
+ source_input_signature: sourceInputSignature,
423
459
  computed_at: computedAt,
424
460
  createdAt: computedAt,
425
461
  updatedAt: computedAt,
@@ -520,25 +556,7 @@ export function updateMaterializedCreditBillsReport(existing, updates, options =
520
556
  }
521
557
  }
522
558
  for (const delta of updates.additions ?? []) {
523
- for (const [key, section] of Object.entries(toMutableSections(delta.credit_bills))) {
524
- const target = sections[key] ?? (sections[key] = emptySection());
525
- for (const entry of section.issued) {
526
- const identity = creditBillIdentityKey(entry.order_id, entry.payment_id);
527
- const index = target.issued.findIndex((current) => creditBillIdentityKey(current.order_id, current.payment_id) === identity);
528
- if (index >= 0)
529
- target.issued[index] = entry;
530
- else
531
- target.issued.push(entry);
532
- }
533
- for (const entry of section.received) {
534
- const identity = `${creditBillIdentityKey(entry.order_id, entry.payment_id)}|${entry.event_local_date}`;
535
- const index = target.received.findIndex((current) => `${creditBillIdentityKey(current.order_id, current.payment_id)}|${current.event_local_date}` === identity);
536
- if (index >= 0)
537
- target.received[index] = entry;
538
- else
539
- target.received.push(entry);
540
- }
541
- }
559
+ mergeMaterializedCreditBillSections(sections, toMutableSections(delta.credit_bills));
542
560
  }
543
561
  for (const delta of updates.additions ?? []) {
544
562
  sourceWatermark = maxDate(sourceWatermark, delta.source_watermark) ?? sourceWatermark;
@@ -571,6 +589,9 @@ export function updateMaterializedCreditBillsReport(existing, updates, options =
571
589
  ...existing,
572
590
  credit_bills: pruned,
573
591
  iteration: (existing.iteration ?? 1) + (changed || ledgerPatched ? 1 : 0),
592
+ // A REPLACEMENT carries the freshly compiled day digest; period folds keep
593
+ // the stored value (their payload is a running ledger, not one day's input).
594
+ source_input_signature: updates.replacement?.source_input_signature ?? existing.source_input_signature,
574
595
  source_watermark: sourceWatermark,
575
596
  computed_at: computedAt,
576
597
  updatedAt: computedAt,
@@ -596,7 +617,12 @@ const creditPeriodRefs = (localDate) => {
596
617
  },
597
618
  ];
598
619
  };
599
- /** `Writes the watermarks / schema / key-filter grammar allow a write?` (mirrors the sales-report guard). */
620
+ /**
621
+ * `Writes the watermarks / day-input signature / schema / key-filter grammar
622
+ * allow a write?` (mirrors the sales-report guard). The signature is checked
623
+ * FIRST so a deleted / moved order still corrects the ledger when the incoming
624
+ * watermark regressed.
625
+ */
600
626
  export const needsMaterializedCreditBillsReportWrite = (existing, incoming) => {
601
627
  if (existing == null)
602
628
  return true;
@@ -605,6 +631,9 @@ export const needsMaterializedCreditBillsReportWrite = (existing, incoming) => {
605
631
  if (JSON.stringify(existing.sale_type_key_filters ?? []) !== JSON.stringify(incoming.sale_type_key_filters ?? [])) {
606
632
  return true;
607
633
  }
634
+ if (materializedDayInputSignatureChanged(existing.source_input_signature, incoming.source_input_signature)) {
635
+ return true;
636
+ }
608
637
  return new Date(incoming.source_watermark).getTime() > new Date(existing.source_watermark).getTime();
609
638
  };
610
639
  /**
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Day-input SIGNATURE — the change-detection token of a materialized day.
3
+ *
4
+ * ## Why a watermark alone is not enough
5
+ *
6
+ * Every report document stores `source_watermark` = the MAX `orders.updatedAt`
7
+ * folded into it, and the close-day plans skip a document when the incoming
8
+ * watermark is not NEWER than the stored one. That is sound for an UPDATE of an
9
+ * order (its `updatedAt` advances), but it is blind to the order set SHRINKING:
10
+ *
11
+ * - delete the order that carried the maximum `updatedAt`, then re-close the
12
+ * day → the incoming max is LOWER than the stored watermark, the guard
13
+ * reports "nothing new", and the deleted order stays in every report
14
+ * (date/hour/period/credit/discount) forever;
15
+ * - move that order to another `localDate` → same regression on the old day,
16
+ * so the old day keeps a sale it no longer owns.
17
+ *
18
+ * The fix is a SECOND, set-shaped signal: a deterministic digest of the exact
19
+ * order identities (and their versions) the day was compiled from. A delete or
20
+ * a move changes the digest even when the watermark regresses, so the guard can
21
+ * trigger the corrective writes. A re-close of the SAME input reproduces the
22
+ * same digest, so the no-churn skip is preserved.
23
+ *
24
+ * ## Shape
25
+ *
26
+ * `v1:<count>:<hash>` where
27
+ * - `count` is the number of orders in the input (cheap first check);
28
+ * - `hash` is two independent 32-bit FNV-1a passes over the sorted
29
+ * `id|updatedAt` lines, emitted as 16 hex chars (a ~64-bit digest).
30
+ *
31
+ * The leading `v1:` version tag makes the value a non-numeric string, which
32
+ * keeps it outside the integer-only storage contract's numeric-string rule; a
33
+ * future algorithm change must bump the tag so old documents are re-materialized
34
+ * exactly once instead of being silently compared with a different digest.
35
+ *
36
+ * The digest is NOT a security primitive — it detects accidental divergence,
37
+ * and a full re-close always repairs the document regardless.
38
+ */
39
+ /** Version tag of the digest algorithm; bump when the line format changes. */
40
+ export const MATERIALIZED_DAY_INPUT_SIGNATURE_VERSION = 'v1';
41
+ /** One stable line per order: identity + the version that produced its numbers. */
42
+ const signatureLine = (order) => {
43
+ const id = order._id == null ? '' : String(order._id);
44
+ const updatedAt = order.updatedAt == null ? '' : new Date(order.updatedAt).toISOString();
45
+ return `${id}|${updatedAt}`;
46
+ };
47
+ /** Two independent FNV-1a 32-bit passes over `value`, as 16 hex chars. */
48
+ const hashSignatureLines = (value) => {
49
+ let first = 0x811c9dc5;
50
+ let second = 0x01000193 ^ 0x9e3779b9;
51
+ for (let index = 0; index < value.length; index += 1) {
52
+ const code = value.charCodeAt(index);
53
+ first ^= code;
54
+ first = Math.imul(first, 0x01000193) >>> 0;
55
+ second = Math.imul(second ^ code, 0x85ebca6b) >>> 0;
56
+ second = (second ^ (second >>> 13)) >>> 0;
57
+ }
58
+ return `${first.toString(16).padStart(8, '0')}${second.toString(16).padStart(8, '0')}`;
59
+ };
60
+ /**
61
+ * Builds the day-input signature for the orders a materializer compiled.
62
+ *
63
+ * The caller passes the SAME array the compile used (and the same tenant
64
+ * filter); the digest is order-independent (lines are sorted) and idempotent
65
+ * (identical input → identical value). An empty input yields the stable
66
+ * `v1:0:<hash of ''>` value, which is deliberately DIFFERENT from "no stored
67
+ * signature" (`undefined`) — a legacy document with no signature is therefore
68
+ * rewritten once, and an order-less day keeps skipping on later re-closes.
69
+ *
70
+ * Returns `null` (never throws) when the input is not an array.
71
+ */
72
+ export function buildMaterializedDayInputSignature(orders) {
73
+ if (!Array.isArray(orders))
74
+ return null;
75
+ const lines = [];
76
+ for (const order of orders) {
77
+ if (order == null)
78
+ continue;
79
+ lines.push(signatureLine(order));
80
+ }
81
+ lines.sort();
82
+ return `${MATERIALIZED_DAY_INPUT_SIGNATURE_VERSION}:${lines.length}:${hashSignatureLines(lines.join('\n'))}`;
83
+ }
84
+ /**
85
+ * Does a stored / incoming signature pair require a write?
86
+ *
87
+ * - BOTH missing → `false`: neither side describes an input set (legacy
88
+ * fixtures / documents), so the watermark guard decides — exactly the
89
+ * pre-signature behaviour;
90
+ * - exactly ONE missing → `true`: a legacy stored document meets a compiled
91
+ * day (or the reverse), so the corrective write happens once;
92
+ * - different values → `true` (the input SET changed, e.g. a delete or move);
93
+ * - identical → `false` (the watermark guard then decides).
94
+ */
95
+ export const materializedDayInputSignatureChanged = (stored, incoming) => {
96
+ const storedMissing = typeof stored !== 'string';
97
+ const incomingMissing = typeof incoming !== 'string';
98
+ if (storedMissing && incomingMissing)
99
+ return false;
100
+ if (storedMissing || incomingMissing)
101
+ return true;
102
+ return stored !== incoming;
103
+ };
@@ -1,5 +1,6 @@
1
1
  import { MATERIALIZED_DISCOUNT_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
2
2
  import { buildMaterializedTenantReportIteration } from './materialized-tenant-reports-iterations-helpers';
3
+ import { materializedDayInputSignatureChanged } from './materialized-day-input-signature';
3
4
  import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields, parseMaterializedLocalDate, } from './scope-helpers';
4
5
  /** Day-scoped documents (replaced wholesale for the compiled day). */
5
6
  const DISCOUNT_DAY_SCOPES = [
@@ -162,7 +163,9 @@ export function getMaterializedDiscountPeriodDayScopeFields(localDate) {
162
163
  /**
163
164
  * Watermark guard: does the stored document need a structural write?
164
165
  * `false` (skip) when the incoming `source_watermark` is not newer than the
165
- * stored one and the schema version + key grammar match.
166
+ * stored one, the day-input SIGNATURE is unchanged, and the schema version +
167
+ * key grammar match. The signature catches a deleted / moved order whose
168
+ * removal lowered the incoming watermark.
166
169
  */
167
170
  export function needsMaterializedDiscountReportWrite(existing, incoming) {
168
171
  if (existing == null || incoming == null)
@@ -172,6 +175,9 @@ export function needsMaterializedDiscountReportWrite(existing, incoming) {
172
175
  if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
173
176
  return true;
174
177
  }
178
+ if (materializedDayInputSignatureChanged(existing.source_input_signature, incoming.source_input_signature)) {
179
+ return true;
180
+ }
175
181
  const existingTime = new Date(existing.source_watermark ?? 0).getTime();
176
182
  const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
177
183
  if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
@@ -273,6 +279,9 @@ export function updateMaterializedDiscountReport(existing, updates, options = {}
273
279
  // step with it — one source of truth, so the map and the rows can never
274
280
  // disagree (and a correction that empties a key drops it from both).
275
281
  discount_counter_rows: finalCounters == null ? null : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
282
+ // A REPLACEMENT carries the freshly compiled day digest; period folds keep
283
+ // the stored value (their payload is a running sum, not one day's input).
284
+ source_input_signature: updates.replacement?.source_input_signature ?? existing.source_input_signature,
276
285
  source_watermark: sourceWatermark,
277
286
  computed_at: computedAt,
278
287
  updatedAt: computedAt,
@@ -472,6 +481,7 @@ export function buildTenantDiscountCloseDayPlan(input) {
472
481
  const skippedDocuments = [];
473
482
  const skippedEntryDocuments = [];
474
483
  const createdPeriodDocuments = [];
484
+ let foldedPeriodDayDocuments = 0;
475
485
  const addWrite = (report) => {
476
486
  const persisted = report.iteration == null ? { ...report, iteration: 1 } : report;
477
487
  const iteration = buildMaterializedTenantReportIteration(persisted, {
@@ -582,6 +592,7 @@ export function buildTenantDiscountCloseDayPlan(input) {
582
592
  skippedDocuments,
583
593
  skippedEntryDocuments,
584
594
  createdPeriodDocuments,
595
+ foldedPeriodDayDocuments,
585
596
  };
586
597
  }
587
598
  const dayChanged = force || needsMaterializedDiscountReportWrite(storedDateDoc, storedDateDocInCompiled);
@@ -613,7 +624,56 @@ export function buildTenantDiscountCloseDayPlan(input) {
613
624
  if (!isAccumulatedScope(compiled.scope_context))
614
625
  return null; // unknown scope
615
626
  if (existing == null) {
616
- if (addWrite(compiled) == null)
627
+ // Missing period counter document: rebuild it from the sibling DAY
628
+ // counters that belong to this exact scope (plus the compiled day), so
629
+ // the period equals the sum of its days again. The closing day's own
630
+ // stored date document is excluded by the input contract.
631
+ const referenceDoc = storedDateDocInCompiled ?? reports[0];
632
+ const siblings = (input.existingPeriodDayDocuments ?? []).filter((doc) => {
633
+ if (doc == null || doc.tenant_id !== tenantId)
634
+ return false;
635
+ if (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
636
+ return false;
637
+ if (typeof doc.scope_field !== 'string' || doc.scope_field === localDate)
638
+ return false;
639
+ if (doc.schema_version !== referenceDoc.schema_version)
640
+ return false;
641
+ if ((doc.sale_type_key_filters ?? []).join(':') !== (referenceDoc.sale_type_key_filters ?? []).join(':')) {
642
+ return false;
643
+ }
644
+ const refs = getMaterializedDiscountScopeRefsForDay(doc.scope_field);
645
+ return (refs != null &&
646
+ refs.some((ref) => ref.scope_context === compiled.scope_context && ref.scope_field === compiled.scope_field));
647
+ });
648
+ let created = compiled;
649
+ if (siblings.length > 0) {
650
+ const counters = JSON.parse(JSON.stringify(compiled.discount_counters ?? {}));
651
+ let watermark = new Date(compiled.source_watermark);
652
+ for (const sibling of siblings) {
653
+ applyCounters(counters, sibling.discount_counters, 1);
654
+ const siblingWatermark = new Date(sibling.source_watermark);
655
+ if (siblingWatermark.getTime() > watermark.getTime())
656
+ watermark = siblingWatermark;
657
+ }
658
+ for (const key of Object.keys(counters)) {
659
+ if (isZeroCounters(counters[key]))
660
+ delete counters[key];
661
+ }
662
+ const finalCounters = Object.keys(counters).length === 0
663
+ ? null
664
+ : counters;
665
+ created = {
666
+ ...compiled,
667
+ discount_counters: finalCounters,
668
+ discount_counter_rows: finalCounters == null
669
+ ? null
670
+ : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
671
+ source_watermark: watermark,
672
+ iteration: 1,
673
+ };
674
+ foldedPeriodDayDocuments += siblings.length;
675
+ }
676
+ if (addWrite(created) == null)
617
677
  return null;
618
678
  createdPeriodDocuments.push({ scope_context: compiled.scope_context, scope_field: compiled.scope_field });
619
679
  continue;
@@ -745,5 +805,6 @@ export function buildTenantDiscountCloseDayPlan(input) {
745
805
  skippedDocuments,
746
806
  skippedEntryDocuments,
747
807
  createdPeriodDocuments,
808
+ foldedPeriodDayDocuments,
748
809
  };
749
810
  }
@@ -3,6 +3,7 @@ import { MATERIALIZED_DISCOUNT_REPORT_SCOPES, MATERIALIZED_REPORT_KEY_FILTER_ENU
3
3
  import { accumulateOrderDiscounts, toDiscountHourLabel, } from './materialized-discount-accumulator-helpers';
4
4
  import { createEmptyDiscountOrderCounters } from './materialized-discount-classification-helpers';
5
5
  import { buildMaterializedReportKey } from './key-helpers';
6
+ import { buildMaterializedDayInputSignature } from './materialized-day-input-signature';
6
7
  import { getDayIndexFromLocalDate, getMaterializedHourScopeField, getMaterializedPeriodScopeFields, } from './scope-helpers';
7
8
  import { resolveOrderLocalHour } from './materialized-credit-bills-helpers';
8
9
  /** Adds every numeric field of `source` into `target`, recursively. */
@@ -53,6 +54,16 @@ export function compileTenantDiscountReports(input) {
53
54
  if (periodFields == null)
54
55
  return null;
55
56
  const dayIndex = getDayIndexFromLocalDate(localDate);
57
+ // Day-input digest: the discount counter documents are guarded by a
58
+ // watermark that only advances, so deleting / moving the order with the
59
+ // highest `updatedAt` would otherwise skip the correction and leave its
60
+ // discount behind. The digest covers EVERY order the day compiled (a removed
61
+ // non-discount order changes nothing, but rewriting one document is cheaper
62
+ // than a missed correction). Computed once — the same value is stamped on
63
+ // every scope document of the day.
64
+ const sourceInputSignature = buildMaterializedDayInputSignature(orders.filter((order) => order != null &&
65
+ order.is_deleted === false &&
66
+ (order.tenant_id == null || String(order.tenant_id) === tenantId))) ?? undefined;
56
67
  // DERIVED from the report's scope list (as prep / cash / delivery do). This used to be a
57
68
  // second, hand-maintained copy of the same four scopes - so widening the report's scopes
58
69
  // compiled the new ones nowhere and the documents silently never appeared.
@@ -79,6 +90,12 @@ export function compileTenantDiscountReports(input) {
79
90
  for (const order of orders) {
80
91
  if (order == null)
81
92
  continue;
93
+ // DELETED orders never contribute (defence in depth: the worker loader
94
+ // already filters `is_deleted: false`, but the compile is also used by the
95
+ // live adapter and by tests — a deleted order must never re-appear through
96
+ // a caller passing a wider query).
97
+ if (order.is_deleted !== false)
98
+ continue;
82
99
  // Only orders of this tenant compile into this tenant's documents.
83
100
  if (order.tenant_id != null && String(order.tenant_id) !== tenantId)
84
101
  continue;
@@ -154,6 +171,7 @@ export function compileTenantDiscountReports(input) {
154
171
  top_sources: null,
155
172
  schema_version: 1,
156
173
  source_watermark: docWatermark,
174
+ source_input_signature: sourceInputSignature,
157
175
  computed_at: computedAt,
158
176
  createdAt: computedAt,
159
177
  updatedAt: computedAt,
@@ -105,3 +105,30 @@ export function getMaterializedHourScopeField(localDate, hour) {
105
105
  return null;
106
106
  return `${localDate} ${pad(hour)}`;
107
107
  }
108
+ /**
109
+ * The `scope_field` RANGE a close must scan to find every stored `localDate`
110
+ * document that can share a period with `localDate` — used to REPAIR a missing
111
+ * period document from its sibling days (a period is a running sum; creating it
112
+ * from the closing day alone would make it disagree with the sum of the day
113
+ * documents).
114
+ *
115
+ * This is a deliberately generous SUPERSET: the ISO week / calendar week of a
116
+ * date can start in the previous calendar year (e.g. `2027-01-01` belongs to
117
+ * `2026-W53`), and the calendar week can extend into the next one. Membership
118
+ * is decided afterwards by comparing each candidate's
119
+ * `getMaterializedPeriodScopeFields` / scope refs to the created period; the
120
+ * range only bounds the query (one indexed range scan, no `$in` of 366 keys).
121
+ *
122
+ * Returns `null` (never throws) for a malformed date.
123
+ */
124
+ export function getMaterializedPeriodDayScopeRange(localDate) {
125
+ const parts = parseMaterializedLocalDate(localDate);
126
+ if (parts == null)
127
+ return null;
128
+ const { year } = parts;
129
+ const toKey = (date) => `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;
130
+ return {
131
+ gte: toKey(new Date(Date.UTC(year, 0, 1 - 7))),
132
+ lte: toKey(new Date(Date.UTC(year, 11, 31 + 7))),
133
+ };
134
+ }
@@ -1,9 +1,10 @@
1
1
  import { REPORT_SALE_TYPE_ENUM } from '../../constants';
2
2
  import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
3
- import { buildMaterializedCreditBillDayReports, getMaterializedCreditBillScopeRefsForIssue, needsMaterializedCreditBillsReportWrite, resolveCreditBillDay, updateMaterializedCreditBillsReport, } from './materialized-credit-bills-helpers';
3
+ import { buildMaterializedCreditBillDayReports, getMaterializedCreditBillScopeRefsForDay, getMaterializedCreditBillScopeRefsForIssue, mergeMaterializedCreditBillSections, needsMaterializedCreditBillsReportWrite, resolveCreditBillDay, updateMaterializedCreditBillsReport, } from './materialized-credit-bills-helpers';
4
4
  import { buildMaterializedTenantReportIteration } from './materialized-tenant-reports-iterations-helpers';
5
+ import { materializedDayInputSignatureChanged } from './materialized-day-input-signature';
5
6
  import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields } from './scope-helpers';
6
- import { normalizeMaterializedSaleTypeMetrics, updateMaterializedTenantSalesOverviewReport, } from './tenant-sales-overview-helpers';
7
+ import { normalizeMaterializedSaleTypeMetrics, sumMaterializedTenantSalesOverviewReports, updateMaterializedTenantSalesOverviewReport, } from './tenant-sales-overview-helpers';
7
8
  /** Scopes written wholesale for the compiled day (replacement semantics). */
8
9
  const CLOSE_DAY_DAY_SCOPES = [
9
10
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
@@ -50,9 +51,12 @@ export function getMaterializedTenantSalesOverviewScopeRefsForDay(localDate) {
50
51
  * structural write for the incoming compiled version?
51
52
  *
52
53
  * `false` (skip) when the incoming `source_watermark` is not newer than the
53
- * stored one and the schema version + key-filter grammar match. Watermarks are
54
- * monotonic (`updateMaterializedTenantSalesOverviewReport` never regresses
55
- * them). A missing stored document always needs a write.
54
+ * stored one, the day-input SIGNATURE is unchanged, and the schema version +
55
+ * key-filter grammar match. Watermarks are monotonic
56
+ * (`updateMaterializedTenantSalesOverviewReport` never regresses them); the
57
+ * signature is the SET-shaped signal that detects a deleted / moved order even
58
+ * when the incoming watermark is lower than the stored one. A missing stored
59
+ * document always needs a write.
56
60
  */
57
61
  export function needsMaterializedTenantSalesOverviewReportWrite(existing, incoming) {
58
62
  if (existing == null || incoming == null)
@@ -62,6 +66,11 @@ export function needsMaterializedTenantSalesOverviewReportWrite(existing, incomi
62
66
  if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
63
67
  return true;
64
68
  }
69
+ // Set-shaped signal FIRST: a delete / move must correct even when the
70
+ // incoming watermark regressed below the stored one.
71
+ if (materializedDayInputSignatureChanged(existing.source_input_signature, incoming.source_input_signature)) {
72
+ return true;
73
+ }
65
74
  const existingTime = new Date(existing.source_watermark ?? 0).getTime();
66
75
  const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
67
76
  if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
@@ -120,6 +129,37 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
120
129
  if (String(prior._id) !== String(doc._id))
121
130
  return null;
122
131
  }
132
+ // REPAIR SOURCE: stored sibling DAY documents, used only when a period
133
+ // document has to be CREATED. A period is a running sum, so seeding it with
134
+ // the closing day alone would leave every earlier materialized day out of
135
+ // the period while its `localDate` document still exists (month ≠ Σ days).
136
+ // The closing day itself is excluded: the freshly compiled day replaces it.
137
+ const periodDayDocuments = [];
138
+ const periodDayDocumentsByField = new Map();
139
+ for (const doc of input.existingPeriodDayDocuments ?? []) {
140
+ if (doc == null || doc.tenant_id !== tenantId)
141
+ continue;
142
+ if (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
143
+ continue;
144
+ if (typeof doc.scope_field !== 'string' || doc.scope_field === localDate)
145
+ continue;
146
+ // A day document from another schema version / brand cannot be summed
147
+ // (`sumMaterialized…` would return null and fail the whole close); it is
148
+ // ignored here and re-materialized by its own close.
149
+ if (doc.schema_version !== compiledDateDoc.schema_version)
150
+ continue;
151
+ if ((doc.sale_type_key_filters ?? []).join(':') !== (compiledDateDoc.sale_type_key_filters ?? []).join(':')) {
152
+ continue;
153
+ }
154
+ if (doc.brand_id !== compiledDateDoc.brand_id)
155
+ continue;
156
+ periodDayDocumentsByField.set(doc.scope_field, doc);
157
+ periodDayDocuments.push(doc);
158
+ }
159
+ const dayDocumentBelongsToScope = (doc, scopeContext, scopeField) => {
160
+ const refs = getMaterializedTenantSalesOverviewScopeRefsForDay(doc.scope_field);
161
+ return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
162
+ };
123
163
  // ------------------------------------------------------------------
124
164
  // Resolve THIS day against the stored credit ledger documents — the only
125
165
  // stateful step (receipt deltas, carried anchors, settlements), executed
@@ -220,6 +260,8 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
220
260
  const writes = [];
221
261
  const skippedDocuments = [];
222
262
  const createdPeriodDocuments = [];
263
+ let foldedPeriodDayDocuments = 0;
264
+ let foldedPeriodDayCreditDocuments = 0;
223
265
  const addStructuralWrite = (report) => {
224
266
  const iteration = buildMaterializedTenantReportIteration(report, {
225
267
  reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
@@ -256,9 +298,26 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
256
298
  if (!CLOSE_DAY_ACCUMULATED_SCOPES.includes(compiledDoc.scope_context))
257
299
  return null; // unknown scope — data issue
258
300
  if (existing == null) {
259
- if (dayDeltaEmpty)
260
- continue; // nothing to fold into a (new) period document
261
- if (!addStructuralWrite(compiledDoc))
301
+ // Missing period document: REPAIR it from the stored sibling days that
302
+ // belong to this exact scope, then add the closing day. Without the fold
303
+ // the period would hold only this close's delta while the earlier days'
304
+ // `localDate` documents still exist — `localMonth` would no longer equal
305
+ // 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;
311
+ let createdReport = compiledDoc;
312
+ if (siblings.length > 0) {
313
+ createdReport = sumMaterializedTenantSalesOverviewReports([compiledDoc, ...siblings], {
314
+ computedAt,
315
+ });
316
+ if (createdReport == null)
317
+ return null; // inconsistent sibling — data issue
318
+ foldedPeriodDayDocuments += siblings.length;
319
+ }
320
+ if (createdReport == null || !addStructuralWrite(createdReport))
262
321
  return null;
263
322
  createdPeriodDocuments.push({
264
323
  scope_context: compiledDoc.scope_context,
@@ -361,9 +420,38 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
361
420
  localDate,
362
421
  resolution: creditResolution,
363
422
  computedAt,
423
+ sourceInputSignature: compiledDateDoc.source_input_signature ?? null,
364
424
  });
365
425
  if (creditCompiledDocs == null)
366
426
  return null;
427
+ // REPAIR SOURCE for missing credit PERIOD documents — the stored sibling
428
+ // DAY documents (the closing day is replaced by the compiled one). Mirrors
429
+ // the sales-overview fold above; without it a recreated month document would
430
+ // hold only this close's bills while the other days' date documents exist.
431
+ const creditPeriodDayDocuments = [];
432
+ // The credit collection has its OWN schema version / key grammar — compare
433
+ // siblings against a compiled CREDIT document, never the overview envelope.
434
+ const creditReferenceDoc = creditCompiledDocs[0] ?? null;
435
+ for (const doc of input.existingPeriodDayCreditDocuments ?? []) {
436
+ if (creditReferenceDoc == null)
437
+ break;
438
+ if (doc == null || doc.tenant_id !== tenantId)
439
+ continue;
440
+ if (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
441
+ continue;
442
+ if (typeof doc.scope_field !== 'string' || doc.scope_field === localDate)
443
+ continue;
444
+ if (doc.schema_version !== creditReferenceDoc.schema_version)
445
+ continue;
446
+ if (JSON.stringify(doc.sale_type_key_filters ?? []) !== JSON.stringify(creditReferenceDoc.sale_type_key_filters ?? [])) {
447
+ continue;
448
+ }
449
+ creditPeriodDayDocuments.push(doc);
450
+ }
451
+ const creditDayDocumentBelongsToScope = (doc, scopeContext, scopeField) => {
452
+ const refs = getMaterializedCreditBillScopeRefsForDay(doc.scope_field);
453
+ return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
454
+ };
367
455
  const creditExistingByScope = new Map();
368
456
  for (const doc of input.existingCreditBills ?? []) {
369
457
  if (doc == null || doc.tenant_id !== tenantId)
@@ -456,7 +544,30 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
456
544
  if (!creditAccumulatedScopes.includes(compiledCreditDoc.scope_context))
457
545
  return null; // unknown scope — data issue
458
546
  if (existing == null) {
459
- if (!addCreditWrite(compiledCreditDoc))
547
+ // Missing period document: rebuild it from the sibling DAY documents
548
+ // that belong to this exact scope (the closing day is the compiled
549
+ // document), so the ledger stays equal to the sum of its days.
550
+ const siblings = creditPeriodDayDocuments.filter((doc) => creditDayDocumentBelongsToScope(doc, compiledCreditDoc.scope_context, compiledCreditDoc.scope_field));
551
+ let created = compiledCreditDoc;
552
+ if (siblings.length > 0) {
553
+ const sections = {};
554
+ mergeMaterializedCreditBillSections(sections, compiledCreditDoc.credit_bills);
555
+ let watermark = new Date(compiledCreditDoc.source_watermark);
556
+ for (const sibling of siblings) {
557
+ mergeMaterializedCreditBillSections(sections, sibling.credit_bills);
558
+ const siblingWatermark = new Date(sibling.source_watermark);
559
+ if (siblingWatermark.getTime() > watermark.getTime())
560
+ watermark = siblingWatermark;
561
+ }
562
+ created = {
563
+ ...compiledCreditDoc,
564
+ credit_bills: sections,
565
+ source_watermark: watermark,
566
+ iteration: 1,
567
+ };
568
+ foldedPeriodDayCreditDocuments += siblings.length;
569
+ }
570
+ if (!addCreditWrite(created))
460
571
  return null;
461
572
  continue;
462
573
  }
@@ -533,5 +644,7 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
533
644
  creditSkippedDocuments,
534
645
  skippedDocuments,
535
646
  createdPeriodDocuments,
647
+ foldedPeriodDayDocuments,
648
+ foldedPeriodDayCreditDocuments,
536
649
  };
537
650
  }