@managesome/eposmatic-toolkit 0.4.28 → 0.4.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +9 -12
  2. package/esm/helpers/materialized-reports/index.js +2 -0
  3. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +178 -40
  4. package/esm/helpers/materialized-reports/materialized-day-input-signature.js +103 -0
  5. package/esm/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  6. package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +299 -227
  7. package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +20 -1
  8. package/esm/helpers/materialized-reports/materialized-discount-source-helpers.js +176 -0
  9. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +64 -0
  10. package/esm/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  11. package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  12. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  13. package/esm/helpers/materialized-reports/scope-helpers.js +27 -0
  14. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +400 -46
  15. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +28 -6
  16. package/esm/schemas/models/materialized_credit_bills.js +8 -0
  17. package/esm/schemas/models/materialized_report_drilldown_rows.js +39 -12
  18. package/esm/schemas/models/materialized_tenant_discount_entries.js +18 -12
  19. package/esm/schemas/models/materialized_tenant_discount_reports.js +9 -0
  20. package/esm/schemas/models/materialized_tenant_discount_sources.js +1 -1
  21. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
  22. package/esm/schemas/models/orders.js +5 -0
  23. package/esm/schemas/models/tenant_active_jobs.js +8 -0
  24. package/esm/schemas/models/tenant_calendar.js +12 -0
  25. package/lib/constants/MATERIALIZED_REPORTS.d.ts +9 -12
  26. package/lib/constants/MATERIALIZED_REPORTS.js +11 -14
  27. package/lib/helpers/materialized-reports/index.d.ts +2 -0
  28. package/lib/helpers/materialized-reports/index.js +2 -0
  29. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +66 -2
  30. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +179 -39
  31. package/lib/helpers/materialized-reports/materialized-day-input-signature.d.ts +66 -0
  32. package/lib/helpers/materialized-reports/materialized-day-input-signature.js +108 -0
  33. package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  34. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +41 -60
  35. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +298 -226
  36. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.d.ts +4 -4
  37. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +19 -0
  38. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.d.ts +17 -0
  39. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +178 -0
  40. package/lib/helpers/materialized-reports/materialized-index-bootstrap.d.ts +7 -0
  41. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +68 -0
  42. package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +3 -1
  43. package/lib/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  44. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.d.ts +2 -2
  45. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  46. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  47. package/lib/helpers/materialized-reports/scope-helpers.d.ts +22 -0
  48. package/lib/helpers/materialized-reports/scope-helpers.js +28 -0
  49. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +49 -3
  50. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +398 -44
  51. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +4 -1
  52. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +28 -6
  53. package/lib/schemas/models/materialized_credit_bills.d.ts +3 -0
  54. package/lib/schemas/models/materialized_credit_bills.js +8 -0
  55. package/lib/schemas/models/materialized_report_drilldown_rows.d.ts +40 -6
  56. package/lib/schemas/models/materialized_report_drilldown_rows.js +39 -12
  57. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +33 -29
  58. package/lib/schemas/models/materialized_tenant_discount_entries.js +18 -12
  59. package/lib/schemas/models/materialized_tenant_discount_reports.d.ts +3 -0
  60. package/lib/schemas/models/materialized_tenant_discount_reports.js +9 -0
  61. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +6 -6
  62. package/lib/schemas/models/materialized_tenant_discount_sources.js +1 -1
  63. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +3 -0
  64. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
  65. package/lib/schemas/models/orders.d.ts +5 -0
  66. package/lib/schemas/models/orders.js +5 -0
  67. package/lib/schemas/models/tenant_active_jobs.d.ts +3 -0
  68. package/lib/schemas/models/tenant_active_jobs.js +8 -0
  69. package/lib/schemas/models/tenant_calendar.d.ts +13 -0
  70. package/lib/schemas/models/tenant_calendar.js +13 -1
  71. package/lib/schemas/types/materialized_credit_bills.d.ts +6 -0
  72. package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +8 -0
  73. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +9 -5
  74. package/lib/schemas/types/materialized_tenant_discount_reports.d.ts +6 -0
  75. package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +9 -0
  76. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +14 -0
  77. package/lib/schemas/types/tenant_active_jobs.d.ts +8 -0
  78. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +56 -1
  79. package/lib/tests/materialized-reports/materialized-day-input-signature.test.d.ts +1 -0
  80. package/lib/tests/materialized-reports/materialized-day-input-signature.test.js +81 -0
  81. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +17 -0
  82. package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +148 -53
  83. package/lib/tests/materialized-reports/materialized-discount-entries-accumulation.test.js +14 -13
  84. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +76 -0
  85. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +11 -0
  86. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +2 -2
  87. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +311 -4
  88. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +89 -0
  89. package/package.json +1 -1
@@ -7,6 +7,8 @@ exports.needsMaterializedCreditBillsReportWrite = exports.toMaterializedHourLabe
7
7
  exports.buildCreditBillIssuedCandidatesFromOrder = buildCreditBillIssuedCandidatesFromOrder;
8
8
  exports.buildCreditBillEventCandidatesFromOrder = buildCreditBillEventCandidatesFromOrder;
9
9
  exports.resolveCreditBillDay = resolveCreditBillDay;
10
+ exports.applyCreditResolutionToReportDocuments = applyCreditResolutionToReportDocuments;
11
+ exports.mergeMaterializedCreditBillSections = mergeMaterializedCreditBillSections;
10
12
  exports.buildMaterializedCreditBillDayReports = buildMaterializedCreditBillDayReports;
11
13
  exports.updateMaterializedCreditBillsReport = updateMaterializedCreditBillsReport;
12
14
  exports.getMaterializedCreditBillScopeRefsForDay = getMaterializedCreditBillScopeRefsForDay;
@@ -20,6 +22,7 @@ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
20
22
  const materialized_credit_bills_1 = require("../../schemas/models/materialized_credit_bills");
21
23
  const time_helpers_1 = require("../utils/time-helpers");
22
24
  const key_helpers_1 = require("./key-helpers");
25
+ const materialized_day_input_signature_1 = require("./materialized-day-input-signature");
23
26
  const scope_helpers_1 = require("./scope-helpers");
24
27
  /**
25
28
  * The shared credit-bill ledger (`materialized_tenant_credit_bills`) —
@@ -131,11 +134,11 @@ function buildCreditBillIssuedCandidatesFromOrder(order, orderLocalDate, options
131
134
  const paymentId = payment.payment_id ?? payment._id ?? null;
132
135
  if (paymentId == null || paymentId.length === 0)
133
136
  return null; // un-keyable bill — data issue
134
- // Money is integer CENTS: the payment amounts are rounded to the cent at
135
- // this writer boundary, because a materialized ledger document may not
136
- // hold a decimal.
137
- const amount = Math.round(payment.amount_due ?? 0);
138
- const receivedAmount = Math.round(payment.amount_paid ?? 0);
137
+ // Money is integer CENTS. Do NOT round here: a fractional source amount is
138
+ // a data defect and the materialized-write integer gate must fail the close
139
+ // loudly, never silently change the ledger.
140
+ const amount = payment.amount_due ?? 0;
141
+ const receivedAmount = payment.amount_paid ?? 0;
139
142
  const settled = !settledLater && receivedAmount >= amount;
140
143
  candidates.push({
141
144
  order_id: order._id,
@@ -171,7 +174,7 @@ function buildCreditBillEventCandidatesFromOrder(order, eventLocalDate, options)
171
174
  if (paymentId == null || paymentId.length === 0)
172
175
  return null; // un-keyable bill — data issue
173
176
  // Money is integer CENTS (see the issued-bill candidate above).
174
- const receivedAmount = Math.round(payment.amount_paid ?? 0);
177
+ const receivedAmount = payment.amount_paid ?? 0;
175
178
  if (receivedAmount <= 0)
176
179
  continue; // nothing collected yet
177
180
  candidates.push({
@@ -180,7 +183,7 @@ function buildCreditBillEventCandidatesFromOrder(order, eventLocalDate, options)
180
183
  order_status: order.order_status,
181
184
  platform: order.platform,
182
185
  // Money is integer CENTS.
183
- amount: Math.round(payment.amount_due ?? 0),
186
+ amount: payment.amount_due ?? 0,
184
187
  issued_at: issuedAt,
185
188
  issued_local_date: orderLocalDate,
186
189
  issued_local_hour: issuedHourLabel,
@@ -237,12 +240,12 @@ function resolveCreditBillDay(input) {
237
240
  for (const report of input.stored ?? []) {
238
241
  if (report == null || report.tenant_id !== tenantId)
239
242
  continue;
240
- for (const [, section] of sectionsOf(report)) {
243
+ for (const [sectionKey, section] of sectionsOf(report)) {
241
244
  for (const entry of section?.issued ?? []) {
242
- const key = creditBillIdentityKey(entry.order_id, entry.payment_id);
243
- const prior = storedIssuedByKey.get(key);
244
- if (prior == null || (entry.received_amount ?? 0) > (prior.received_amount ?? 0)) {
245
- storedIssuedByKey.set(key, entry);
245
+ const identity = creditBillIdentityKey(entry.order_id, entry.payment_id);
246
+ const prior = storedIssuedByKey.get(identity);
247
+ if (prior == null || (entry.received_amount ?? 0) > (prior.entry.received_amount ?? 0)) {
248
+ storedIssuedByKey.set(identity, { entry, key: sectionKey });
246
249
  }
247
250
  }
248
251
  for (const entry of section?.received ?? []) {
@@ -263,7 +266,7 @@ function resolveCreditBillDay(input) {
263
266
  const key = (0, key_helpers_1.buildMaterializedReportKey)([candidate.order_status, candidate.platform]);
264
267
  if (key == null)
265
268
  return null; // un-keyable sale-type fields — data issue
266
- const stored = storedIssuedByKey.get(creditBillIdentityKey(candidate.order_id, candidate.payment_id));
269
+ const stored = storedIssuedByKey.get(creditBillIdentityKey(candidate.order_id, candidate.payment_id))?.entry;
267
270
  issued.push({
268
271
  key,
269
272
  source_watermark: candidate.source_watermark,
@@ -284,12 +287,14 @@ function resolveCreditBillDay(input) {
284
287
  }
285
288
  const received_events = [];
286
289
  const settled_bills = [];
290
+ const receipt_bills = [];
287
291
  for (const candidate of input.events ?? []) {
288
292
  const key = (0, key_helpers_1.buildMaterializedReportKey)([candidate.order_status, candidate.platform]);
289
293
  if (key == null)
290
294
  return null; // un-keyable sale-type fields — data issue
291
295
  const identity = creditBillIdentityKey(candidate.order_id, candidate.payment_id);
292
- const storedIssued = storedIssuedByKey.get(identity) ?? null;
296
+ const storedIssuedRecord = storedIssuedByKey.get(identity) ?? null;
297
+ const storedIssued = storedIssuedRecord?.entry ?? null;
293
298
  const storedEvent = storedReceivedByKey.get(`${identity}|${candidate.event.event_local_date}`) ?? null;
294
299
  let delta;
295
300
  let cumulativeAfter;
@@ -339,11 +344,15 @@ function resolveCreditBillDay(input) {
339
344
  });
340
345
  // The issue scopes must be patched exactly once per settlement — only
341
346
  // for EARLIER issue days (a same-day settlement rides the issued payload).
342
- if (settled && storedIssued != null && candidate.issued_local_date !== localDate) {
347
+ // The section key comes from the STORED entry, not the current order
348
+ // status/platform: an order may move PLACED -> COMPLETED between issue and
349
+ // collection, and the issue documents remain under the old key.
350
+ if (storedIssued != null && candidate.issued_local_date !== localDate) {
343
351
  const alreadySettled = storedIssued.settled_at != null || storedIssued.settled_local_date != null;
344
- if (!alreadySettled) {
352
+ if (settled && !alreadySettled) {
345
353
  settled_bills.push({
346
354
  key,
355
+ stored_key: storedIssuedRecord?.key ?? null,
347
356
  order_id: candidate.order_id,
348
357
  payment_id: candidate.payment_id,
349
358
  amount,
@@ -355,12 +364,119 @@ function resolveCreditBillDay(input) {
355
364
  issued_local_hour: storedIssued.issued_local_hour ?? candidate.issued_local_hour ?? null,
356
365
  });
357
366
  }
367
+ else if (!settled && (storedIssued.received_amount ?? 0) < cumulativeAfter) {
368
+ // PARTIAL receipt: update the SAME bill's cumulative received_amount so
369
+ // outstanding_now reflects every installment, not only the final one.
370
+ receipt_bills.push({
371
+ key,
372
+ stored_key: storedIssuedRecord?.key ?? null,
373
+ order_id: candidate.order_id,
374
+ payment_id: candidate.payment_id,
375
+ amount,
376
+ received_amount: cumulativeAfter,
377
+ credit_note: candidate.event.credit_note ?? storedIssued.credit_note ?? null,
378
+ issued_local_date: candidate.issued_local_date,
379
+ issued_local_hour: storedIssued.issued_local_hour ?? candidate.issued_local_hour ?? null,
380
+ });
381
+ }
382
+ }
383
+ }
384
+ return { issued, received_events, settled_bills, receipt_bills };
385
+ }
386
+ /**
387
+ * Applies one day's credit resolution to the compiled Overview documents:
388
+ * overwrites each key's received counters from the resolved event deltas and
389
+ * its issued settled counters from the stored anchors. Shared by the close-day
390
+ * plan and the LIVE Overview adapter so both use one rule.
391
+ */
392
+ function applyCreditResolutionToReportDocuments(reports, resolution) {
393
+ const receivedByScopeKey = new Map();
394
+ for (const resolved of resolution.received_events) {
395
+ const delta = resolved.entry.received_delta ?? 0;
396
+ for (const doc of reports) {
397
+ if (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
398
+ doc.scope_field !== resolved.entry.event_local_hour) {
399
+ continue;
400
+ }
401
+ const mapKey = doc.scope_context + '|' + doc.scope_field + '|' + resolved.key;
402
+ const entry = receivedByScopeKey.get(mapKey) ?? { count: 0, amount: 0 };
403
+ entry.count += 1;
404
+ entry.amount += delta;
405
+ receivedByScopeKey.set(mapKey, entry);
406
+ }
407
+ }
408
+ for (const doc of reports) {
409
+ const metrics = doc.sale_type_metrics;
410
+ for (const [key, metric] of Object.entries(metrics ?? {})) {
411
+ const entry = receivedByScopeKey.get(doc.scope_context + '|' + doc.scope_field + '|' + key);
412
+ metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received = entry != null ? { ...entry } : { count: 0, amount: 0 };
413
+ }
414
+ }
415
+ const settledByKey = new Map();
416
+ for (const resolved of resolution.issued) {
417
+ const entry = resolved.entry;
418
+ if (entry.settled_at == null && entry.settled_local_date == null)
419
+ continue;
420
+ const totals = settledByKey.get(resolved.key) ?? { count: 0, amount: 0 };
421
+ totals.count += 1;
422
+ totals.amount += entry.amount ?? 0;
423
+ settledByKey.set(resolved.key, totals);
424
+ }
425
+ for (const doc of reports) {
426
+ const metrics = doc.sale_type_metrics;
427
+ for (const [key, metric] of Object.entries(metrics ?? {})) {
428
+ const entry = settledByKey.get(key);
429
+ metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_count = entry?.count ?? 0;
430
+ metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_amount = entry?.amount ?? 0;
358
431
  }
359
432
  }
360
- return { issued, received_events, settled_bills };
433
+ const collectedAtIssue = {};
434
+ for (const resolved of resolution.issued) {
435
+ const atIssue = resolved.entry.received_at_issue ?? 0;
436
+ if (atIssue <= 0)
437
+ continue;
438
+ const totals = collectedAtIssue[resolved.key] ?? { count: 0, amount: 0 };
439
+ totals.count += 1;
440
+ totals.amount += atIssue;
441
+ collectedAtIssue[resolved.key] = totals;
442
+ }
443
+ return { collected_at_issue: collectedAtIssue };
361
444
  }
362
445
  const emptySection = () => ({ issued: [], received: [] });
363
446
  const sectionFor = (map, key) => map[key] ?? (map[key] = emptySection());
447
+ /**
448
+ * Folds `source` sections INTO `target` (mutating it), identity-matched:
449
+ * an ISSUED entry is one `(order_id, payment_id)` bill; a RECEIVED entry is one
450
+ * `(order_id, payment_id, event_local_date)` collection event. A source entry
451
+ * REPLACES its target counterpart (fresh wins), so re-applying the same day is
452
+ * idempotent.
453
+ *
454
+ * Exported because the close-day plan uses the SAME merge when it rebuilds a
455
+ * MISSING period document from the stored day documents (a deleted period
456
+ * document must not be recreated from the closing day alone; see
457
+ * `buildTenantSalesOverviewCloseDayPlan`'s period repair).
458
+ */
459
+ function mergeMaterializedCreditBillSections(target, source) {
460
+ for (const [key, section] of Object.entries(source ?? {})) {
461
+ const bucket = target[key] ?? (target[key] = emptySection());
462
+ for (const entry of section?.issued ?? []) {
463
+ const identity = creditBillIdentityKey(entry.order_id, entry.payment_id);
464
+ const index = bucket.issued.findIndex((current) => creditBillIdentityKey(current.order_id, current.payment_id) === identity);
465
+ if (index >= 0)
466
+ bucket.issued[index] = entry;
467
+ else
468
+ bucket.issued.push(entry);
469
+ }
470
+ for (const entry of section?.received ?? []) {
471
+ const identity = `${creditBillIdentityKey(entry.order_id, entry.payment_id)}|${entry.event_local_date}`;
472
+ const index = bucket.received.findIndex((current) => `${creditBillIdentityKey(current.order_id, current.payment_id)}|${current.event_local_date}` === identity);
473
+ if (index >= 0)
474
+ bucket.received[index] = entry;
475
+ else
476
+ bucket.received.push(entry);
477
+ }
478
+ }
479
+ }
364
480
  /**
365
481
  * Materializes ONE day's credit documents from its resolution — the
366
482
  * month-capped scope set (`MATERIALIZED_CREDIT_BILLS_SCOPES`): one document per
@@ -371,6 +487,7 @@ function buildMaterializedCreditBillDayReports(input) {
371
487
  if (input == null)
372
488
  return null;
373
489
  const { tenantId, brandId, localDate, resolution, computedAt } = input;
490
+ const sourceInputSignature = input.sourceInputSignature ?? undefined;
374
491
  const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
375
492
  if (periodFields == null)
376
493
  return null;
@@ -440,6 +557,7 @@ function buildMaterializedCreditBillDayReports(input) {
440
557
  iteration: 1,
441
558
  schema_version: materialized_credit_bills_1.MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION,
442
559
  source_watermark: sourceWatermark,
560
+ source_input_signature: sourceInputSignature,
443
561
  computed_at: computedAt,
444
562
  createdAt: computedAt,
445
563
  updatedAt: computedAt,
@@ -540,33 +658,21 @@ function updateMaterializedCreditBillsReport(existing, updates, options = {}) {
540
658
  }
541
659
  }
542
660
  for (const delta of updates.additions ?? []) {
543
- for (const [key, section] of Object.entries(toMutableSections(delta.credit_bills))) {
544
- const target = sections[key] ?? (sections[key] = emptySection());
545
- for (const entry of section.issued) {
546
- const identity = creditBillIdentityKey(entry.order_id, entry.payment_id);
547
- const index = target.issued.findIndex((current) => creditBillIdentityKey(current.order_id, current.payment_id) === identity);
548
- if (index >= 0)
549
- target.issued[index] = entry;
550
- else
551
- target.issued.push(entry);
552
- }
553
- for (const entry of section.received) {
554
- const identity = `${creditBillIdentityKey(entry.order_id, entry.payment_id)}|${entry.event_local_date}`;
555
- const index = target.received.findIndex((current) => `${creditBillIdentityKey(current.order_id, current.payment_id)}|${current.event_local_date}` === identity);
556
- if (index >= 0)
557
- target.received[index] = entry;
558
- else
559
- target.received.push(entry);
560
- }
561
- }
661
+ mergeMaterializedCreditBillSections(sections, toMutableSections(delta.credit_bills));
562
662
  }
563
663
  for (const delta of updates.additions ?? []) {
564
664
  sourceWatermark = maxDate(sourceWatermark, delta.source_watermark) ?? sourceWatermark;
565
665
  }
566
666
  }
667
+ /** Find the issue section by the stored key (status drift), then fall back to the current key. */
668
+ const findIssueTarget = (key, storedKey) => {
669
+ if (storedKey != null && sections[storedKey] != null)
670
+ return sections[storedKey];
671
+ return sections[key] ?? null;
672
+ };
567
673
  let ledgerPatched = false;
568
674
  for (const settlement of updates.settled_bills ?? []) {
569
- const target = sections[settlement.key];
675
+ const target = findIssueTarget(settlement.key, settlement.stored_key);
570
676
  if (target == null)
571
677
  continue;
572
678
  const index = target.issued.findIndex((entry) => creditBillIdentityKey(entry.order_id, entry.payment_id) ===
@@ -585,12 +691,38 @@ function updateMaterializedCreditBillsReport(existing, updates, options = {}) {
585
691
  };
586
692
  ledgerPatched = true;
587
693
  }
694
+ // Partial receipts update the SAME issue entry's cumulative amount. They are
695
+ // not new bills and never create a second receivable.
696
+ for (const receipt of updates.receipt_bills ?? []) {
697
+ const target = findIssueTarget(receipt.key, receipt.stored_key);
698
+ if (target == null)
699
+ continue;
700
+ const index = target.issued.findIndex((entry) => creditBillIdentityKey(entry.order_id, entry.payment_id) ===
701
+ creditBillIdentityKey(receipt.order_id, receipt.payment_id));
702
+ if (index < 0)
703
+ continue;
704
+ const entry = target.issued[index];
705
+ if ((entry.received_amount ?? 0) >= receipt.received_amount)
706
+ continue; // idempotent
707
+ target.issued[index] = {
708
+ ...entry,
709
+ received_amount: receipt.received_amount,
710
+ credit_note: receipt.credit_note ?? entry.credit_note ?? null,
711
+ };
712
+ ledgerPatched = true;
713
+ }
588
714
  const pruned = pruneSections(sections);
589
715
  const changed = serializeSections(pruned) !== serializeSections(toMutableSections(existing.credit_bills));
716
+ const envelopeChanged = (updates.replacement != null &&
717
+ (updates.replacement.source_input_signature ?? null) !== (existing.source_input_signature ?? null)) ||
718
+ new Date(sourceWatermark).getTime() > new Date(existing.source_watermark).getTime();
590
719
  return {
591
720
  ...existing,
592
721
  credit_bills: pruned,
593
- iteration: (existing.iteration ?? 1) + (changed || ledgerPatched ? 1 : 0),
722
+ iteration: (existing.iteration ?? 1) + (changed || ledgerPatched || envelopeChanged ? 1 : 0),
723
+ // A REPLACEMENT carries the freshly compiled day digest; period folds keep
724
+ // the stored value (their payload is a running ledger, not one day's input).
725
+ source_input_signature: updates.replacement?.source_input_signature ?? existing.source_input_signature,
594
726
  source_watermark: sourceWatermark,
595
727
  computed_at: computedAt,
596
728
  updatedAt: computedAt,
@@ -616,7 +748,12 @@ const creditPeriodRefs = (localDate) => {
616
748
  },
617
749
  ];
618
750
  };
619
- /** `Writes the watermarks / schema / key-filter grammar allow a write?` (mirrors the sales-report guard). */
751
+ /**
752
+ * `Writes the watermarks / day-input signature / schema / key-filter grammar
753
+ * allow a write?` (mirrors the sales-report guard). The signature is checked
754
+ * FIRST so a deleted / moved order still corrects the ledger when the incoming
755
+ * watermark regressed.
756
+ */
620
757
  const needsMaterializedCreditBillsReportWrite = (existing, incoming) => {
621
758
  if (existing == null)
622
759
  return true;
@@ -625,6 +762,9 @@ const needsMaterializedCreditBillsReportWrite = (existing, incoming) => {
625
762
  if (JSON.stringify(existing.sale_type_key_filters ?? []) !== JSON.stringify(incoming.sale_type_key_filters ?? [])) {
626
763
  return true;
627
764
  }
765
+ if ((0, materialized_day_input_signature_1.materializedDayInputSignatureChanged)(existing.source_input_signature, incoming.source_input_signature)) {
766
+ return true;
767
+ }
628
768
  return new Date(incoming.source_watermark).getTime() > new Date(existing.source_watermark).getTime();
629
769
  };
630
770
  exports.needsMaterializedCreditBillsReportWrite = needsMaterializedCreditBillsReportWrite;
@@ -0,0 +1,66 @@
1
+ import { IOrder } from '../../schemas/types/orders';
2
+ /**
3
+ * Day-input SIGNATURE — the change-detection token of a materialized day.
4
+ *
5
+ * ## Why a watermark alone is not enough
6
+ *
7
+ * Every report document stores `source_watermark` = the MAX `orders.updatedAt`
8
+ * folded into it, and the close-day plans skip a document when the incoming
9
+ * watermark is not NEWER than the stored one. That is sound for an UPDATE of an
10
+ * order (its `updatedAt` advances), but it is blind to the order set SHRINKING:
11
+ *
12
+ * - delete the order that carried the maximum `updatedAt`, then re-close the
13
+ * day → the incoming max is LOWER than the stored watermark, the guard
14
+ * reports "nothing new", and the deleted order stays in every report
15
+ * (date/hour/period/credit/discount) forever;
16
+ * - move that order to another `localDate` → same regression on the old day,
17
+ * so the old day keeps a sale it no longer owns.
18
+ *
19
+ * The fix is a SECOND, set-shaped signal: a deterministic digest of the exact
20
+ * order identities (and their versions) the day was compiled from. A delete or
21
+ * a move changes the digest even when the watermark regresses, so the guard can
22
+ * trigger the corrective writes. A re-close of the SAME input reproduces the
23
+ * same digest, so the no-churn skip is preserved.
24
+ *
25
+ * ## Shape
26
+ *
27
+ * `v1:<count>:<hash>` where
28
+ * - `count` is the number of orders in the input (cheap first check);
29
+ * - `hash` is two independent 32-bit FNV-1a passes over the sorted
30
+ * `id|updatedAt` lines, emitted as 16 hex chars (a ~64-bit digest).
31
+ *
32
+ * The leading `v1:` version tag makes the value a non-numeric string, which
33
+ * keeps it outside the integer-only storage contract's numeric-string rule; a
34
+ * future algorithm change must bump the tag so old documents are re-materialized
35
+ * exactly once instead of being silently compared with a different digest.
36
+ *
37
+ * The digest is NOT a security primitive — it detects accidental divergence,
38
+ * and a full re-close always repairs the document regardless.
39
+ */
40
+ /** Version tag of the digest algorithm; bump when the line format changes. */
41
+ export declare const MATERIALIZED_DAY_INPUT_SIGNATURE_VERSION = "v1";
42
+ /**
43
+ * Builds the day-input signature for the orders a materializer compiled.
44
+ *
45
+ * The caller passes the SAME array the compile used (and the same tenant
46
+ * filter); the digest is order-independent (lines are sorted) and idempotent
47
+ * (identical input → identical value). An empty input yields the stable
48
+ * `v1:0:<hash of ''>` value, which is deliberately DIFFERENT from "no stored
49
+ * signature" (`undefined`) — a legacy document with no signature is therefore
50
+ * rewritten once, and an order-less day keeps skipping on later re-closes.
51
+ *
52
+ * Returns `null` (never throws) when the input is not an array.
53
+ */
54
+ export declare function buildMaterializedDayInputSignature(orders: readonly IOrder[] | null | undefined): string | null;
55
+ /**
56
+ * Does a stored / incoming signature pair require a write?
57
+ *
58
+ * - BOTH missing → `false`: neither side describes an input set (legacy
59
+ * fixtures / documents), so the watermark guard decides — exactly the
60
+ * pre-signature behaviour;
61
+ * - exactly ONE missing → `true`: a legacy stored document meets a compiled
62
+ * day (or the reverse), so the corrective write happens once;
63
+ * - different values → `true` (the input SET changed, e.g. a delete or move);
64
+ * - identical → `false` (the watermark guard then decides).
65
+ */
66
+ export declare const materializedDayInputSignatureChanged: (stored: string | null | undefined, incoming: string | null | undefined) => boolean;
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.materializedDayInputSignatureChanged = exports.MATERIALIZED_DAY_INPUT_SIGNATURE_VERSION = void 0;
4
+ exports.buildMaterializedDayInputSignature = buildMaterializedDayInputSignature;
5
+ /**
6
+ * Day-input SIGNATURE — the change-detection token of a materialized day.
7
+ *
8
+ * ## Why a watermark alone is not enough
9
+ *
10
+ * Every report document stores `source_watermark` = the MAX `orders.updatedAt`
11
+ * folded into it, and the close-day plans skip a document when the incoming
12
+ * watermark is not NEWER than the stored one. That is sound for an UPDATE of an
13
+ * order (its `updatedAt` advances), but it is blind to the order set SHRINKING:
14
+ *
15
+ * - delete the order that carried the maximum `updatedAt`, then re-close the
16
+ * day → the incoming max is LOWER than the stored watermark, the guard
17
+ * reports "nothing new", and the deleted order stays in every report
18
+ * (date/hour/period/credit/discount) forever;
19
+ * - move that order to another `localDate` → same regression on the old day,
20
+ * so the old day keeps a sale it no longer owns.
21
+ *
22
+ * The fix is a SECOND, set-shaped signal: a deterministic digest of the exact
23
+ * order identities (and their versions) the day was compiled from. A delete or
24
+ * a move changes the digest even when the watermark regresses, so the guard can
25
+ * trigger the corrective writes. A re-close of the SAME input reproduces the
26
+ * same digest, so the no-churn skip is preserved.
27
+ *
28
+ * ## Shape
29
+ *
30
+ * `v1:<count>:<hash>` where
31
+ * - `count` is the number of orders in the input (cheap first check);
32
+ * - `hash` is two independent 32-bit FNV-1a passes over the sorted
33
+ * `id|updatedAt` lines, emitted as 16 hex chars (a ~64-bit digest).
34
+ *
35
+ * The leading `v1:` version tag makes the value a non-numeric string, which
36
+ * keeps it outside the integer-only storage contract's numeric-string rule; a
37
+ * future algorithm change must bump the tag so old documents are re-materialized
38
+ * exactly once instead of being silently compared with a different digest.
39
+ *
40
+ * The digest is NOT a security primitive — it detects accidental divergence,
41
+ * and a full re-close always repairs the document regardless.
42
+ */
43
+ /** Version tag of the digest algorithm; bump when the line format changes. */
44
+ exports.MATERIALIZED_DAY_INPUT_SIGNATURE_VERSION = 'v1';
45
+ /** One stable line per order: identity + the version that produced its numbers. */
46
+ const signatureLine = (order) => {
47
+ const id = order._id == null ? '' : String(order._id);
48
+ const updatedAt = order.updatedAt == null ? '' : new Date(order.updatedAt).toISOString();
49
+ return `${id}|${updatedAt}`;
50
+ };
51
+ /** Two independent FNV-1a 32-bit passes over `value`, as 16 hex chars. */
52
+ const hashSignatureLines = (value) => {
53
+ let first = 0x811c9dc5;
54
+ let second = 0x01000193 ^ 0x9e3779b9;
55
+ for (let index = 0; index < value.length; index += 1) {
56
+ const code = value.charCodeAt(index);
57
+ first ^= code;
58
+ first = Math.imul(first, 0x01000193) >>> 0;
59
+ second = Math.imul(second ^ code, 0x85ebca6b) >>> 0;
60
+ second = (second ^ (second >>> 13)) >>> 0;
61
+ }
62
+ return `${first.toString(16).padStart(8, '0')}${second.toString(16).padStart(8, '0')}`;
63
+ };
64
+ /**
65
+ * Builds the day-input signature for the orders a materializer compiled.
66
+ *
67
+ * The caller passes the SAME array the compile used (and the same tenant
68
+ * filter); the digest is order-independent (lines are sorted) and idempotent
69
+ * (identical input → identical value). An empty input yields the stable
70
+ * `v1:0:<hash of ''>` value, which is deliberately DIFFERENT from "no stored
71
+ * signature" (`undefined`) — a legacy document with no signature is therefore
72
+ * rewritten once, and an order-less day keeps skipping on later re-closes.
73
+ *
74
+ * Returns `null` (never throws) when the input is not an array.
75
+ */
76
+ function buildMaterializedDayInputSignature(orders) {
77
+ if (!Array.isArray(orders))
78
+ return null;
79
+ const lines = [];
80
+ for (const order of orders) {
81
+ if (order == null)
82
+ continue;
83
+ lines.push(signatureLine(order));
84
+ }
85
+ lines.sort();
86
+ return `${exports.MATERIALIZED_DAY_INPUT_SIGNATURE_VERSION}:${lines.length}:${hashSignatureLines(lines.join('\n'))}`;
87
+ }
88
+ /**
89
+ * Does a stored / incoming signature pair require a write?
90
+ *
91
+ * - BOTH missing → `false`: neither side describes an input set (legacy
92
+ * fixtures / documents), so the watermark guard decides — exactly the
93
+ * pre-signature behaviour;
94
+ * - exactly ONE missing → `true`: a legacy stored document meets a compiled
95
+ * day (or the reverse), so the corrective write happens once;
96
+ * - different values → `true` (the input SET changed, e.g. a delete or move);
97
+ * - identical → `false` (the watermark guard then decides).
98
+ */
99
+ const materializedDayInputSignatureChanged = (stored, incoming) => {
100
+ const storedMissing = typeof stored !== 'string';
101
+ const incomingMissing = typeof incoming !== 'string';
102
+ if (storedMissing && incomingMissing)
103
+ return false;
104
+ if (storedMissing || incomingMissing)
105
+ return true;
106
+ return stored !== incoming;
107
+ };
108
+ exports.materializedDayInputSignatureChanged = materializedDayInputSignatureChanged;
@@ -146,13 +146,20 @@ function resolveRowMoney(details, rowTotal) {
146
146
  return { perSlot, row_total: total, allocated: resolved, unallocated: Math.max(0, total - resolved) };
147
147
  }
148
148
  // Several active slots (allocated offers): every slot is a FIXED amount when
149
- // more than one is active in practice, so assign each its own value and let
150
- // the remainder be unattributed rather than guessing a split.
149
+ // more than one is active in practice. Allocate in slot order against the
150
+ // headline, EXACTLY like a single fixed slot: a slot can never contribute
151
+ // more than the remaining discount. This prevents 500 + 300 against a 600
152
+ // headline from emitting 800 of entry money while the report total is 600.
151
153
  let allocated = 0;
152
154
  for (const reading of readings) {
153
155
  if (reading.is_percentage)
154
156
  continue; // a % mixed with other slots is unsplittable
155
- const value = Math.max(0, reading.rate);
157
+ const remaining = Math.max(0, total - allocated);
158
+ if (remaining <= 0)
159
+ break;
160
+ const value = Math.min(Math.max(0, reading.rate), remaining);
161
+ if (value <= 0)
162
+ continue;
156
163
  perSlot.set(reading.slot, value);
157
164
  allocated += value;
158
165
  }