@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
@@ -3,6 +3,7 @@ import { PAYMENT_STATUS_ENUM, PAYMENT_TYPE_ENUM, REPORT_SALE_TYPE_ENUM } from '.
3
3
  import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX, SALES_OVERVIEW_KEY_FILTERS, } from '../../constants/MATERIALIZED_REPORTS';
4
4
  import { MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME, MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_SCHEMA_VERSION, MaterializedTenantSalesOverviewReportSchema, } from '../../schemas/models/materialized_tenant_sales_overview_reports';
5
5
  import { buildMaterializedReportKey } from './key-helpers';
6
+ import { buildMaterializedDayInputSignature, } from './materialized-day-input-signature';
6
7
  import { buildCreditBillEventCandidatesFromOrder, buildCreditBillIssuedCandidatesFromOrder, isMaterializedCreditBillPayment, resolveOrderLocalHour, resolveReceivedLocalHour, } from './materialized-credit-bills-helpers';
7
8
  import { getDayIndexFromLocalDate, getMaterializedHourScopeField, getMaterializedPeriodScopeFields, parseMaterializedLocalDate, } from './scope-helpers';
8
9
  /* ------------------------------------------------------------------------ */
@@ -34,16 +35,16 @@ export function isPaymentIncludedInMaterializedSalesOverview(payment) {
34
35
  export function getMaterializedPaymentGross(payment) {
35
36
  const reportedType = normalizeMaterializedPaymentType(payment.payment_type);
36
37
  const isUnpaid = reportedType === PAYMENT_TYPE_ENUM.UNPAID;
37
- // Money is integer CENTS: the result is rounded to the cent at this
38
- // boundary, because it feeds a materialized document.
38
+ // Money is integer CENTS. Do NOT round: a fractional source amount must fail
39
+ // the materialized-write integer gate, not be silently changed here.
39
40
  if ((payment.amount_refunded ?? 0) === 0) {
40
41
  let gross = isUnpaid ? (payment.amount_due ?? 0) : Math.min(payment.amount_paid ?? 0, payment.amount_due ?? 0);
41
42
  if (payment.card_details != null) {
42
43
  gross -= payment.card_details.card_charges ?? 0;
43
44
  }
44
- return Math.round(gross);
45
+ return gross;
45
46
  }
46
- return -Math.round(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
47
+ return -(isUnpaid ? (payment.amount_due ?? 0) : (payment.amount_refunded ?? 0));
47
48
  }
48
49
  // `isMaterializedCreditBillPayment` moved to `./materialized-credit-bills-helpers`
49
50
  // (imported above) — re-exported here for API stability.
@@ -506,13 +507,26 @@ export function convertOrdersToMaterializedTenantSalesOverviewReports(localDate,
506
507
  // `source_watermark` = max `order.updatedAt` folded in; a day with no
507
508
  // orders folds nothing → epoch. Stable across recompiles, so the
508
509
  // watermark guard skips unchanged (order-less) days instead of churning.
509
- const watermark = tenantOrders.reduce((latest, order) => {
510
+ //
511
+ // `source_input_signature` is the SET-shaped companion: the watermark only
512
+ // advances, so a delete / move that removes the maximum-`updatedAt` order
513
+ // would leave the incoming watermark LOWER than the stored one and the
514
+ // guard would skip the correction. The digest changes with the input set,
515
+ // so the close is still applied. Both are computed from the SAME
516
+ // `tenantOrders` array the compile consumed.
517
+ // Both change-detection signals describe the orders this day ACTUALLY
518
+ // materializes: a deleted order must never keep the day "fresh" (or
519
+ // contribute a watermark the remaining orders cannot reproduce).
520
+ const consideredOrders = tenantOrders.filter((order) => order.is_deleted === false);
521
+ const watermark = consideredOrders.reduce((latest, order) => {
510
522
  const updatedAt = new Date(order.updatedAt ?? now);
511
523
  return updatedAt.getTime() > latest.getTime() ? updatedAt : latest;
512
524
  }, new Date(0));
525
+ const sourceInputSignature = buildMaterializedDayInputSignature(consideredOrders) ?? undefined;
513
526
  for (const { doc, metrics } of [...periodDocs, ...hourDocs.values()]) {
514
527
  doc.sale_type_metrics = finalizeMetrics(metrics);
515
528
  doc.source_watermark = watermark;
529
+ doc.source_input_signature = sourceInputSignature;
516
530
  materializedReports.push(doc);
517
531
  }
518
532
  }
@@ -736,7 +750,10 @@ export function subtractMaterializedTenantSalesOverviewReports(minuend, subtrahe
736
750
  * so replays stay churn-free;
737
751
  * 4. `source_watermark` advances to the max of the existing and the incoming
738
752
  * (`replacement` / `additions`) watermarks — monotonic, never regressed
739
- * (rollbacks / replays keep the previously folded maximum).
753
+ * (rollbacks / replays keep the previously folded maximum);
754
+ * 5. `source_input_signature` follows a `replacement` (the fresh day compile)
755
+ * and is KEPT on period accumulates — a period's payload is a running sum,
756
+ * not one day's input set.
740
757
  *
741
758
  * Returns a new JSON report; the input is not mutated.
742
759
  */
@@ -794,6 +811,11 @@ export function updateMaterializedTenantSalesOverviewReport(existing, updates, o
794
811
  // Reconcile artifacts: a fully-subtracted key is pruned so accumulated
795
812
  // period documents keep the same key set as day / hour reads.
796
813
  sale_type_metrics: pruneZeroReportKeys(finalizeMetrics(metrics)),
814
+ // The day-input digest travels with a REPLACEMENT write (the freshly
815
+ // compiled day/hour document) so the next close can compare it. Period
816
+ // accumulates keep the stored value: their payload is a running sum, not
817
+ // one day's input set.
818
+ source_input_signature: updates.replacement?.source_input_signature ?? existing.source_input_signature,
797
819
  // Version metric writes AND ledger-changing received-payment patches (both
798
820
  // append a history row via the caller). No-op patches bump nothing, so
799
821
  // replays stay churn-free.
@@ -201,6 +201,14 @@ export const MaterializedTenantCreditBillsReportSchema = new Schema({
201
201
  type: Schema.Types.Date,
202
202
  required: true,
203
203
  },
204
+ // Day-input digest (`v1:<count>:<hash>`) — set-shaped change detection
205
+ // for the credit ledger, mirroring the sales-overview reports. A deleted /
206
+ // moved order must remove its bill even when the watermark regresses.
207
+ source_input_signature: {
208
+ type: String,
209
+ required: false,
210
+ default: undefined,
211
+ },
204
212
  computed_at: {
205
213
  type: Schema.Types.Date,
206
214
  required: true,
@@ -40,6 +40,9 @@ export const MaterializedReportDrilldownRowSchema = new Schema({
40
40
  // The original row is polymorphic across reports; the report_type
41
41
  // discriminator says which shape it is.
42
42
  data: { type: Schema.Types.Mixed, required: true },
43
+ // Null only on legacy rows written before the incremental flat projection.
44
+ // The writer rebuilds a touched scope once and stamps every rebuilt row.
45
+ source_local_date: { type: String, default: null },
43
46
  schema_version: {
44
47
  type: Number,
45
48
  required: true,
@@ -66,6 +69,8 @@ export const MaterializedReportDrilldownScopeSchema = new Schema({
66
69
  scope_field: { type: String, required: true, immutable: true },
67
70
  row_count: { type: Number, required: true, min: 0, default: 0 },
68
71
  off_app_order_count: { type: Number, required: true, min: 0, default: 0 },
72
+ /** Last day whose close updated this scope (not an identity). */
73
+ source_local_date: { type: String, default: null },
69
74
  schema_version: {
70
75
  type: Number,
71
76
  required: true,
@@ -84,7 +89,7 @@ export const MaterializedReportDrilldownScopeSchema = new Schema({
84
89
  */
85
90
  export const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES = {
86
91
  _id: { _id: 1 },
87
- identity: {
92
+ tenant_id__report_type__scope_context__scope_field__order_id__cursor_id: {
88
93
  tenant_id: 1,
89
94
  report_type: 1,
90
95
  scope_context: 1,
@@ -92,7 +97,7 @@ export const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES = {
92
97
  order_id: 1,
93
98
  cursor_id: 1,
94
99
  },
95
- read_asc: {
100
+ tenant_id__report_type__scope_context__scope_field__time__order_id__cursor_id: {
96
101
  tenant_id: 1,
97
102
  report_type: 1,
98
103
  scope_context: 1,
@@ -101,7 +106,7 @@ export const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES = {
101
106
  order_id: 1,
102
107
  cursor_id: 1,
103
108
  },
104
- read_desc: {
109
+ tenant_id__report_type__scope_context__scope_field__time__cursor_id: {
105
110
  tenant_id: 1,
106
111
  report_type: 1,
107
112
  scope_context: 1,
@@ -109,37 +114,59 @@ export const MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES = {
109
114
  time: -1,
110
115
  cursor_id: -1,
111
116
  },
117
+ tenant_id__report_type__scope_context__scope_field__source_local_date: {
118
+ tenant_id: 1,
119
+ report_type: 1,
120
+ scope_context: 1,
121
+ scope_field: 1,
122
+ source_local_date: 1,
123
+ },
112
124
  };
113
125
  export const MATERIALIZED_REPORT_DRILLDOWN_ROWS_INDEX_OPTIONS = [
114
126
  {
115
- key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.identity,
116
- name: 'tenant_id__report_type__scope__order_id__cursor_id',
127
+ key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field__order_id__cursor_id,
128
+ name: 'tenant_id__report_type__scope_context__scope_field__order_id__cursor_id',
117
129
  unique: true,
118
130
  },
119
131
  {
120
- key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.read_asc,
121
- name: 'tenant_id__report_type__scope__time_desc__order_id__cursor_id',
132
+ key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field__time__order_id__cursor_id,
133
+ name: 'tenant_id__report_type__scope_context__scope_field__time__order_id__cursor_id',
134
+ },
135
+ {
136
+ key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field__time__cursor_id,
137
+ name: 'tenant_id__report_type__scope_context__scope_field__time__cursor_id',
122
138
  },
123
139
  {
124
- key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.read_desc,
125
- name: 'tenant_id__report_type__scope__time_desc__cursor_id_desc',
140
+ key: MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field__source_local_date,
141
+ name: 'tenant_id__report_type__scope_context__scope_field__source_local_date',
126
142
  },
127
143
  ];
128
144
  export const MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_INDEXES = {
129
145
  _id: { _id: 1 },
130
- identity: {
146
+ tenant_id__report_type__scope_context__scope_field: {
131
147
  tenant_id: 1,
132
148
  report_type: 1,
133
149
  scope_context: 1,
134
150
  scope_field: 1,
135
151
  },
152
+ tenant_id__report_type__scope_context__scope_field__source_local_date: {
153
+ tenant_id: 1,
154
+ report_type: 1,
155
+ scope_context: 1,
156
+ scope_field: 1,
157
+ source_local_date: 1,
158
+ },
136
159
  };
137
160
  export const MATERIALIZED_REPORT_DRILLDOWN_SCOPES_INDEX_OPTIONS = [
138
161
  {
139
- key: MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_INDEXES.identity,
140
- name: 'tenant_id__report_type__scope',
162
+ key: MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field,
163
+ name: 'tenant_id__report_type__scope_context__scope_field',
141
164
  unique: true,
142
165
  },
166
+ {
167
+ key: MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_INDEXES.tenant_id__report_type__scope_context__scope_field__source_local_date,
168
+ name: 'tenant_id__report_type__scope_context__scope_field__source_local_date',
169
+ },
143
170
  ];
144
171
  /** The report-type values the flat reader accepts. */
145
172
  export const ALL_DRILLDOWN_REPORT_TYPE_VALUES = ALL_DRILLDOWN_REPORT_TYPES;
@@ -7,10 +7,12 @@ import { ALL_MATERIALIZED_DISCOUNT_ENTRY_KINDS, ALL_MATERIALIZED_DISCOUNT_LEVELS
7
7
  * SPLIT). See `schemas/types/materialized_tenant_discount_entries.ts` and
8
8
  * `docs/report-discounts-concept.md`.
9
9
  *
10
- * Scopes are capped at `LOCAL_MONTH` so a document can never grow unboundedly.
11
- * Rows are slim (ids + discount facts); each carries `entry_key`, its stable
12
- * identity INSIDE an order, so the `(time, order_id, entry_key)` cursor can
13
- * never collide. Amounts are CENTS; reads pin `schema_version`.
10
+ * Documents are PAGE-PARTITIONED by source day: day/hour scopes use
11
+ * `page='all'`; a period scope uses `page=<source localDate>`, so each document
12
+ * is bounded by one day's rows. Rows are slim (ids + discount facts); each
13
+ * carries `entry_key`, its stable identity INSIDE an order, so the
14
+ * `(time, order_id, entry_key)` cursor can never collide. Amounts are CENTS;
15
+ * reads pin `schema_version`.
14
16
  */
15
17
  /**
16
18
  * Version of the discount ENTRY rules of this collection. Bump when row
@@ -85,6 +87,11 @@ export const MaterializedTenantDiscountEntriesSchema = new Schema({
85
87
  type: String,
86
88
  required: true,
87
89
  },
90
+ page: {
91
+ type: String,
92
+ required: true,
93
+ immutable: true,
94
+ },
88
95
  day_index: {
89
96
  type: String,
90
97
  default: null,
@@ -145,24 +152,23 @@ export const MaterializedTenantDiscountEntriesSchema = new Schema({
145
152
  export { DiscountEntrySchema };
146
153
  export const MATERIALIZED_TENANT_DISCOUNT_ENTRIES_COLLECTION_NAME = 'materialized_tenant_discount_entries';
147
154
  /**
148
- * Indexes for `materialized_tenant_discount_entries` — the same single
149
- * UNIQUE compound identity index as every materialized report collection. The
150
- * `{ tenant_id, scope_context, scope_field }` prefix also serves the
151
- * drill-down's month-document resolution.
155
+ * Indexes for `materialized_tenant_discount_entries` — ONE unique index per
156
+ * page. The `{ tenant_id, scope_context, scope_field, page }` prefix serves
157
+ * both page replacement and the operations multi-page aggregation.
152
158
  */
153
159
  export const MATERIALIZED_TENANT_DISCOUNT_ENTRIES_COLLECTION_INDEXES = {
154
160
  _id: { _id: 1 },
155
- tenant_id__scope_context__scope_field__day_index: {
161
+ tenant_id__scope_context__scope_field__page: {
156
162
  tenant_id: 1,
157
163
  scope_context: 1,
158
164
  scope_field: 1,
159
- day_index: 1,
165
+ page: 1,
160
166
  },
161
167
  };
162
168
  export const MATERIALIZED_TENANT_DISCOUNT_ENTRIES_INDEX_OPTIONS = [
163
169
  {
164
- key: { tenant_id: 1, scope_context: 1, scope_field: 1, day_index: 1 },
165
- name: 'tenant_id__scope_context__scope_field__day_index',
170
+ key: { tenant_id: 1, scope_context: 1, scope_field: 1, page: 1 },
171
+ name: 'tenant_id__scope_context__scope_field__page',
166
172
  unique: true,
167
173
  },
168
174
  ];
@@ -207,6 +207,15 @@ export const MaterializedTenantDiscountReportSchema = new Schema({
207
207
  type: Schema.Types.Date,
208
208
  required: true,
209
209
  },
210
+ // Day-input digest (`v1:<count>:<hash>`) — set-shaped change detection
211
+ // for the discount counters, mirroring the sales-overview reports. A
212
+ // deleted / moved order must remove its discount even when the watermark
213
+ // regresses.
214
+ source_input_signature: {
215
+ type: String,
216
+ required: false,
217
+ default: undefined,
218
+ },
210
219
  computed_at: {
211
220
  type: Schema.Types.Date,
212
221
  required: true,
@@ -164,6 +164,6 @@ export const MATERIALIZED_TENANT_DISCOUNT_SOURCES_INDEX_OPTIONS = [
164
164
  },
165
165
  {
166
166
  key: MATERIALIZED_TENANT_DISCOUNT_SOURCES_COLLECTION_INDEXES.tenant_id__scope_context__scope_field__discount_amount,
167
- name: 'tenant_id__scope_context__scope_field__discount_amount_desc',
167
+ name: 'tenant_id__scope_context__scope_field__discount_amount',
168
168
  },
169
169
  ];
@@ -264,6 +264,15 @@ export const MaterializedTenantSalesOverviewReportSchema = new Schema({
264
264
  type: Schema.Types.Date,
265
265
  required: true,
266
266
  },
267
+ // Day-input digest (`v1:<count>:<hash>`) — the SET-shaped half of change
268
+ // detection. A delete / move can lower the incoming watermark; the digest
269
+ // changes instead, so the close still performs the corrective writes.
270
+ // Optional: documents written before it existed are rewritten once.
271
+ source_input_signature: {
272
+ type: String,
273
+ required: false,
274
+ default: undefined,
275
+ },
267
276
  computed_at: {
268
277
  type: Schema.Types.Date,
269
278
  required: true,
@@ -1035,6 +1035,11 @@ export const ORDERS_COLLECTION_INDEXES = {
1035
1035
  localDate: 1,
1036
1036
  createdAt: -1,
1037
1037
  }, // partial index (partialFilterExpression: { localDate: { $exists: true } }) — per-tenant local-date order lookups filtered by is_deleted, newest first
1038
+ tenant_id__is_deleted__order_settled_at: {
1039
+ tenant_id: 1,
1040
+ is_deleted: 1,
1041
+ order_settled_at: -1,
1042
+ }, // deployed settlement-window index — prior-day credit bills collected in a day's window
1038
1043
  tenant_id__is_deleted__consumer_phone__createdAt: {
1039
1044
  tenant_id: 1,
1040
1045
  is_deleted: 1,
@@ -27,6 +27,14 @@ export const TenantActiveJobSchema = new Schema({
27
27
  enum: ALL_TENANT_ACTIVE_JOBS_NAMES,
28
28
  default: null,
29
29
  },
30
+ // Fencing token of the current owner — fresh per acquisition. Updates,
31
+ // completion and failure filter on it so a stale owner cannot touch the
32
+ // job after a takeover. `null` when the job is free.
33
+ lease_id: {
34
+ type: String,
35
+ required: false,
36
+ default: null,
37
+ },
30
38
  failed_jobs: {
31
39
  type: [String],
32
40
  enum: ALL_TENANT_ACTIVE_JOBS_NAMES,
@@ -87,3 +87,15 @@ export const TENANT_CALENDAR_COLLECTION_INDEXES = {
87
87
  _id: { _id: 1 }, // Unique Index
88
88
  tenant_id__localYear: { tenant_id: 1, localYear: -1 }, // unique per (tenant_id, localYear)
89
89
  };
90
+ /**
91
+ * Index OPTIONS the bootstrapper must create. `tenant_calendar` has no report
92
+ * history, but it DOES need the unique (tenant_id, localYear) invariant: a
93
+ * concurrent/retried upsert must never create a second year document.
94
+ */
95
+ export const TENANT_CALENDAR_INDEX_OPTIONS = [
96
+ {
97
+ key: { tenant_id: 1, localYear: -1 },
98
+ name: 'tenant_id__localYear',
99
+ unique: true,
100
+ },
101
+ ];
@@ -93,24 +93,21 @@ export declare const ALL_MATERIALIZED_REPORT_KEY_FILTERS: MATERIALIZED_REPORT_KE
93
93
  /** Ordered key filters of the tenant sales overview report (`PLACED:POS_WALK-IN`). */
94
94
  export declare const SALES_OVERVIEW_KEY_FILTERS: MATERIALIZED_REPORT_KEY_FILTER_ENUM[];
95
95
  /**
96
- * Scopes materialized by `materialized_tenant_discount_reports` — the same
97
- * month-capped set as the credit ledger, for the same reason: the itemized
98
- * discount rows live in the SIBLING entries collection
99
- * (`materialized_tenant_discount_entries`), capped at `LOCAL_MONTH` so a
100
- * document can never grow unboundedly.
96
+ * Scopes materialized by `materialized_tenant_discount_reports`.
101
97
  *
102
- * DELIBERATELY MONTH-CAPPED: quarter / semester / year are NOT materialized.
103
- * The entry documents accumulate every day's rows for their scope, so a
104
- * quarter-scoped entry document grows without a natural bound and can reach the
105
- * 16 MB document ceiling at high volume (the credit-ledger reason). The
106
- * counter documents would be safe to widen, but the scope list is shared by
107
- * BOTH collections and the entries are the binding constraint. A selection that
108
- * decodes to a wider scope is refused by the historical route
98
+ * Period ENTRY documents are now day-partitioned (`page = source localDate`), so
99
+ * the old 16 MB constraint no longer binds. The scope set intentionally stays
100
+ * at `LOCAL_MONTH` for this change: widening the report surface is a report
101
+ * calculation/API change, not part of the page redesign. The page rule itself is
102
+ * generic and already supports quarter/semester/year if they are enabled.
103
+ * A selection that decodes to a wider scope is refused by the historical route
109
104
  * (`allowedScopeContexts`), never silently narrowed to a month.
110
105
  *
111
106
  * The report documents themselves are COUNTERS ONLY (see
112
107
  * `schemas/types/materialized_tenant_discount_reports.ts`).
113
108
  */
109
+ /** Entry-document page key for the day/hour scopes (they are already day-bounded). */
110
+ export declare const MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL = "all";
114
111
  export declare const MATERIALIZED_DISCOUNT_REPORT_SCOPES: MATERIALIZED_REPORT_SCOPE_ENUM[];
115
112
  /** Ordered key filters of the discounts report (`COMPLETED:POS_WALK-IN`). */
116
113
  export declare const DISCOUNTS_KEY_FILTERS: MATERIALIZED_REPORT_KEY_FILTER_ENUM[];
@@ -10,8 +10,8 @@
10
10
  * explicitly-enabled step.
11
11
  */
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.MATERIALIZED_PREP_TIME_TARGET_ENUM = exports.MATERIALIZED_PREP_TIME_ON_TIME_MAX_DELTA = exports.MATERIALIZED_PREP_TIME_TOP_BUCKET = exports.MATERIALIZED_PREP_TIME_MAX_MINUTES = exports.ALL_MATERIALIZED_PREP_TIME_BUCKET_LABELS = exports.MATERIALIZED_PREP_TIME_BUCKETS = exports.ALL_MATERIALIZED_PREP_TIME_ANCHORS = exports.MATERIALIZED_PREP_TIME_ANCHOR_ENUM = exports.PREP_TIME_KEY_FILTERS = exports.MATERIALIZED_PREP_TIME_REPORT_SCOPES = exports.MATERIALIZED_DELIVERY_AREA_LIMIT = exports.MATERIALIZED_DELIVERY_RIDER_LIMIT = exports.MATERIALIZED_DELIVERY_DISTANCE_BUCKETS = exports.DELIVERY_KEY_FILTERS = exports.MATERIALIZED_DELIVERY_REPORT_SCOPES = exports.MATERIALIZED_CASH_SOURCE_LIMIT = exports.CASH_KEY_FILTERS = exports.MATERIALIZED_CASH_REPORT_SCOPES = exports.ALL_MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPES = exports.MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM = exports.MATERIALIZED_CREDIT_SETTLEMENT_PAYMENT_TYPE = exports.MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX = exports.MATERIALIZED_DISCOUNT_SOURCE_KEY = exports.ALL_MATERIALIZED_DISCOUNT_RATE_KINDS = exports.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SOURCE_CLASSES = exports.MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM = exports.MATERIALIZED_DISCOUNT_PRICE_OVERRIDE_PREFIX = exports.MATERIALIZED_DISCOUNT_MANUAL_PREFIX = exports.MATERIALIZED_DISCOUNT_SPECIAL_DISCOUNT_ID = exports.MATERIALIZED_DISCOUNT_SOURCE_LIMIT = exports.ALL_MATERIALIZED_DISCOUNT_LEVELS = exports.MATERIALIZED_DISCOUNT_LEVEL_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_ENTRY_KINDS = exports.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SUB_KINDS = exports.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SLOTS = exports.MATERIALIZED_DISCOUNT_SLOT_ENUM = exports.DISCOUNTS_KEY_FILTERS = exports.MATERIALIZED_DISCOUNT_REPORT_SCOPES = exports.SALES_OVERVIEW_KEY_FILTERS = exports.ALL_MATERIALIZED_REPORT_KEY_FILTERS = exports.MATERIALIZED_REPORT_KEY_FILTER_ENUM = exports.MATERIALIZED_CREDIT_BILLS_SCOPES = exports.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX = exports.ALL_MATERIALIZED_REPORT_WINDOW_KINDS = exports.MATERIALIZED_REPORT_WINDOW_KIND_ENUM = exports.ALL_MATERIALIZED_REPORT_SCOPES = exports.MATERIALIZED_REPORT_SCOPE_ENUM = void 0;
14
- exports.ALL_PAYMENTS_COMPARISON_METRICS = exports.PAYMENTS_COMPARISON_METRIC_ENUM = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_REPORTS_SCHEMA_VERSION = exports.PAYMENTS_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_PAYMENTS_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_REPORTS_COLLECTION_NAME = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_REPORTS_SCHEMA_VERSION = exports.HOURLY_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_HOURLY_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_REPORTS_COLLECTION_NAME = exports.ALL_SALES_COMPARISON_METRICS = exports.SALES_COMPARISON_METRIC_ENUM = exports.ALL_SALES_COMPARISON_BASELINES = exports.SALES_COMPARISON_BASELINE_ENUM = exports.MATERIALIZED_TENANT_SALES_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_SALES_COMPARISON_REPORTS_SCHEMA_VERSION = exports.SALES_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_SALES_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_SALES_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_SALES_COMPARISON_REPORTS_COLLECTION_NAME = exports.ALL_MATERIALIZED_REPORT_TYPES = exports.MATERIALIZED_REPORT_TYPE_ENUM = exports.ALL_MATERIALIZED_PREP_TIME_TARGETS = void 0;
13
+ exports.MATERIALIZED_PREP_TIME_ON_TIME_MAX_DELTA = exports.MATERIALIZED_PREP_TIME_TOP_BUCKET = exports.MATERIALIZED_PREP_TIME_MAX_MINUTES = exports.ALL_MATERIALIZED_PREP_TIME_BUCKET_LABELS = exports.MATERIALIZED_PREP_TIME_BUCKETS = exports.ALL_MATERIALIZED_PREP_TIME_ANCHORS = exports.MATERIALIZED_PREP_TIME_ANCHOR_ENUM = exports.PREP_TIME_KEY_FILTERS = exports.MATERIALIZED_PREP_TIME_REPORT_SCOPES = exports.MATERIALIZED_DELIVERY_AREA_LIMIT = exports.MATERIALIZED_DELIVERY_RIDER_LIMIT = exports.MATERIALIZED_DELIVERY_DISTANCE_BUCKETS = exports.DELIVERY_KEY_FILTERS = exports.MATERIALIZED_DELIVERY_REPORT_SCOPES = exports.MATERIALIZED_CASH_SOURCE_LIMIT = exports.CASH_KEY_FILTERS = exports.MATERIALIZED_CASH_REPORT_SCOPES = exports.ALL_MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPES = exports.MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM = exports.MATERIALIZED_CREDIT_SETTLEMENT_PAYMENT_TYPE = exports.MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX = exports.MATERIALIZED_DISCOUNT_SOURCE_KEY = exports.ALL_MATERIALIZED_DISCOUNT_RATE_KINDS = exports.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SOURCE_CLASSES = exports.MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM = exports.MATERIALIZED_DISCOUNT_PRICE_OVERRIDE_PREFIX = exports.MATERIALIZED_DISCOUNT_MANUAL_PREFIX = exports.MATERIALIZED_DISCOUNT_SPECIAL_DISCOUNT_ID = exports.MATERIALIZED_DISCOUNT_SOURCE_LIMIT = exports.ALL_MATERIALIZED_DISCOUNT_LEVELS = exports.MATERIALIZED_DISCOUNT_LEVEL_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_ENTRY_KINDS = exports.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SUB_KINDS = exports.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SLOTS = exports.MATERIALIZED_DISCOUNT_SLOT_ENUM = exports.DISCOUNTS_KEY_FILTERS = exports.MATERIALIZED_DISCOUNT_REPORT_SCOPES = exports.MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL = exports.SALES_OVERVIEW_KEY_FILTERS = exports.ALL_MATERIALIZED_REPORT_KEY_FILTERS = exports.MATERIALIZED_REPORT_KEY_FILTER_ENUM = exports.MATERIALIZED_CREDIT_BILLS_SCOPES = exports.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX = exports.ALL_MATERIALIZED_REPORT_WINDOW_KINDS = exports.MATERIALIZED_REPORT_WINDOW_KIND_ENUM = exports.ALL_MATERIALIZED_REPORT_SCOPES = exports.MATERIALIZED_REPORT_SCOPE_ENUM = void 0;
14
+ exports.ALL_PAYMENTS_COMPARISON_METRICS = exports.PAYMENTS_COMPARISON_METRIC_ENUM = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_REPORTS_SCHEMA_VERSION = exports.PAYMENTS_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_PAYMENTS_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_REPORTS_COLLECTION_NAME = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_REPORTS_SCHEMA_VERSION = exports.HOURLY_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_HOURLY_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_REPORTS_COLLECTION_NAME = exports.ALL_SALES_COMPARISON_METRICS = exports.SALES_COMPARISON_METRIC_ENUM = exports.ALL_SALES_COMPARISON_BASELINES = exports.SALES_COMPARISON_BASELINE_ENUM = exports.MATERIALIZED_TENANT_SALES_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_SALES_COMPARISON_REPORTS_SCHEMA_VERSION = exports.SALES_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_SALES_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_SALES_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_SALES_COMPARISON_REPORTS_COLLECTION_NAME = exports.ALL_MATERIALIZED_REPORT_TYPES = exports.MATERIALIZED_REPORT_TYPE_ENUM = exports.ALL_MATERIALIZED_PREP_TIME_TARGETS = exports.MATERIALIZED_PREP_TIME_TARGET_ENUM = void 0;
15
15
  /**
16
16
  * Time-scope of a materialized report document. Every document covers exactly
17
17
  * one tenant × one scope context × one scope value (`scope_field`), and the
@@ -125,24 +125,21 @@ exports.SALES_OVERVIEW_KEY_FILTERS = [
125
125
  /* Discounts report (M1) */
126
126
  /* ======================================================================== */
127
127
  /**
128
- * Scopes materialized by `materialized_tenant_discount_reports` — the same
129
- * month-capped set as the credit ledger, for the same reason: the itemized
130
- * discount rows live in the SIBLING entries collection
131
- * (`materialized_tenant_discount_entries`), capped at `LOCAL_MONTH` so a
132
- * document can never grow unboundedly.
128
+ * Scopes materialized by `materialized_tenant_discount_reports`.
133
129
  *
134
- * DELIBERATELY MONTH-CAPPED: quarter / semester / year are NOT materialized.
135
- * The entry documents accumulate every day's rows for their scope, so a
136
- * quarter-scoped entry document grows without a natural bound and can reach the
137
- * 16 MB document ceiling at high volume (the credit-ledger reason). The
138
- * counter documents would be safe to widen, but the scope list is shared by
139
- * BOTH collections and the entries are the binding constraint. A selection that
140
- * decodes to a wider scope is refused by the historical route
130
+ * Period ENTRY documents are now day-partitioned (`page = source localDate`), so
131
+ * the old 16 MB constraint no longer binds. The scope set intentionally stays
132
+ * at `LOCAL_MONTH` for this change: widening the report surface is a report
133
+ * calculation/API change, not part of the page redesign. The page rule itself is
134
+ * generic and already supports quarter/semester/year if they are enabled.
135
+ * A selection that decodes to a wider scope is refused by the historical route
141
136
  * (`allowedScopeContexts`), never silently narrowed to a month.
142
137
  *
143
138
  * The report documents themselves are COUNTERS ONLY (see
144
139
  * `schemas/types/materialized_tenant_discount_reports.ts`).
145
140
  */
141
+ /** Entry-document page key for the day/hour scopes (they are already day-bounded). */
142
+ exports.MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL = 'all';
146
143
  exports.MATERIALIZED_DISCOUNT_REPORT_SCOPES = [
147
144
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
148
145
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
@@ -1,5 +1,6 @@
1
1
  export * from './key-helpers';
2
2
  export * from './materialized-credit-bills-helpers';
3
+ export * from './materialized-index-bootstrap';
3
4
  export * from './materialized-integer-contract';
4
5
  export * from './materialized-discount-accumulator-helpers';
5
6
  export * from './materialized-discount-classification-helpers';
@@ -18,6 +19,7 @@ export * from './materialized-delivery-accumulator-helpers';
18
19
  export * from './materialized-delivery-compile-helpers';
19
20
  export * from './materialized-delivery-classification-helpers';
20
21
  export * from './materialized-delivery-close-day-helpers';
22
+ export * from './materialized-day-input-signature';
21
23
  export * from './materialized-cash-classification-helpers';
22
24
  export * from './materialized-cash-close-day-helpers';
23
25
  export * from './materialized-cash-compile-helpers';
@@ -16,6 +16,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./key-helpers"), exports);
18
18
  __exportStar(require("./materialized-credit-bills-helpers"), exports);
19
+ __exportStar(require("./materialized-index-bootstrap"), exports);
19
20
  __exportStar(require("./materialized-integer-contract"), exports);
20
21
  __exportStar(require("./materialized-discount-accumulator-helpers"), exports);
21
22
  __exportStar(require("./materialized-discount-classification-helpers"), exports);
@@ -34,6 +35,7 @@ __exportStar(require("./materialized-delivery-accumulator-helpers"), exports);
34
35
  __exportStar(require("./materialized-delivery-compile-helpers"), exports);
35
36
  __exportStar(require("./materialized-delivery-classification-helpers"), exports);
36
37
  __exportStar(require("./materialized-delivery-close-day-helpers"), exports);
38
+ __exportStar(require("./materialized-day-input-signature"), exports);
37
39
  __exportStar(require("./materialized-cash-classification-helpers"), exports);
38
40
  __exportStar(require("./materialized-cash-close-day-helpers"), exports);
39
41
  __exportStar(require("./materialized-cash-compile-helpers"), exports);
@@ -1,6 +1,7 @@
1
1
  import { MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM, MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
2
  import { IOrder, IOrderPayment } from '../../schemas';
3
- import { IMaterializedCreditBillIssuedEntry, IMaterializedCreditBillReceivedEntry, IMaterializedTenantCreditBillsReport } from '../../schemas/types/materialized_credit_bills';
3
+ import { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
4
+ import { IMaterializedCreditBillIssuedEntry, IMaterializedCreditBillKeySection, IMaterializedCreditBillReceivedEntry, IMaterializedTenantCreditBillsReport } from '../../schemas/types/materialized_credit_bills';
4
5
  import { IGetMaterializedReportScopeGroup } from '../types/materialized-reports-apis';
5
6
  /**
6
7
  * The shared credit-bill ledger (`materialized_tenant_credit_bills`) —
@@ -117,7 +118,10 @@ export interface IResolvedCreditBillEvent {
117
118
  }
118
119
  /** A bill that fully settled on the compiled day — the close must patch its issue scopes. */
119
120
  export interface IResolvedCreditBillSettlement {
121
+ /** Current sale-type key (used by the report-counter patch). */
120
122
  key: string;
123
+ /** The section key the stored issue entry actually lives under (status drift safe). */
124
+ stored_key?: string | null;
121
125
  order_id: string;
122
126
  payment_id: string;
123
127
  amount: number;
@@ -130,6 +134,21 @@ export interface IResolvedCreditBillSettlement {
130
134
  /** Punch-hour label of the issue day (null when unknown) — patch target ref. */
131
135
  issued_local_hour: string | null;
132
136
  }
137
+ /**
138
+ * A PARTIAL receipt on an EARLIER issue day. The same bill identity is patched
139
+ * with the new cumulative `received_amount` — never a second receivable.
140
+ */
141
+ export interface IResolvedCreditBillReceiptPatch {
142
+ key: string;
143
+ stored_key?: string | null;
144
+ order_id: string;
145
+ payment_id: string;
146
+ amount: number;
147
+ received_amount: number;
148
+ credit_note: string | null;
149
+ issued_local_date: string;
150
+ issued_local_hour: string | null;
151
+ }
133
152
  export interface ICreditBillDayResolution {
134
153
  issued: IResolvedCreditBillIssued[];
135
154
  received_events: IResolvedCreditBillEvent[];
@@ -139,6 +158,11 @@ export interface ICreditBillDayResolution {
139
158
  * issued payload itself).
140
159
  */
141
160
  settled_bills: IResolvedCreditBillSettlement[];
161
+ /**
162
+ * Partial receipts on an earlier issue day: update the SAME issued entry's
163
+ * cumulative received_amount (and therefore outstanding_now), not a new bill.
164
+ */
165
+ receipt_bills: IResolvedCreditBillReceiptPatch[];
142
166
  }
143
167
  export interface IResolveCreditBillDayInput {
144
168
  tenantId: string;
@@ -167,6 +191,18 @@ export interface IResolveCreditBillDayInput {
167
191
  * entry is not settled yet.
168
192
  */
169
193
  export declare function resolveCreditBillDay(input: IResolveCreditBillDayInput | null | undefined): ICreditBillDayResolution | null;
194
+ /**
195
+ * Applies one day's credit resolution to the compiled Overview documents:
196
+ * overwrites each key's received counters from the resolved event deltas and
197
+ * its issued settled counters from the stored anchors. Shared by the close-day
198
+ * plan and the LIVE Overview adapter so both use one rule.
199
+ */
200
+ export declare function applyCreditResolutionToReportDocuments(reports: IMaterializedTenantSalesOverviewReport[], resolution: ICreditBillDayResolution): {
201
+ collected_at_issue: Record<string, {
202
+ count: number;
203
+ amount: number;
204
+ }>;
205
+ };
170
206
  export interface IBuildMaterializedCreditBillDayReportsInput {
171
207
  tenantId: string;
172
208
  brandId: string;
@@ -174,7 +210,28 @@ export interface IBuildMaterializedCreditBillDayReportsInput {
174
210
  localDate: string;
175
211
  resolution: ICreditBillDayResolution;
176
212
  computedAt: Date;
213
+ /**
214
+ * Day-input digest (`buildMaterializedDayInputSignature`) of the orders the
215
+ * resolution was compiled from — the SET-shaped half of change detection
216
+ * (a delete / move must correct the ledger even when the watermark
217
+ * regresses). Optional so existing callers keep working; a document without
218
+ * one is re-materialized by the guard on its next close.
219
+ */
220
+ sourceInputSignature?: string | null;
177
221
  }
222
+ /**
223
+ * Folds `source` sections INTO `target` (mutating it), identity-matched:
224
+ * an ISSUED entry is one `(order_id, payment_id)` bill; a RECEIVED entry is one
225
+ * `(order_id, payment_id, event_local_date)` collection event. A source entry
226
+ * REPLACES its target counterpart (fresh wins), so re-applying the same day is
227
+ * idempotent.
228
+ *
229
+ * Exported because the close-day plan uses the SAME merge when it rebuilds a
230
+ * MISSING period document from the stored day documents (a deleted period
231
+ * document must not be recreated from the closing day alone; see
232
+ * `buildTenantSalesOverviewCloseDayPlan`'s period repair).
233
+ */
234
+ export declare function mergeMaterializedCreditBillSections(target: Record<string, IMaterializedCreditBillKeySection>, source: Record<string, IMaterializedCreditBillKeySection> | null | undefined): void;
178
235
  /**
179
236
  * Materializes ONE day's credit documents from its resolution — the
180
237
  * month-capped scope set (`MATERIALIZED_CREDIT_BILLS_SCOPES`): one document per
@@ -191,6 +248,8 @@ export interface IUpdateMaterializedCreditBillsReportInput {
191
248
  additions?: IMaterializedTenantCreditBillsReport[];
192
249
  /** Settlement patches: update issue-scope `issued[]` entries exactly once. */
193
250
  settled_bills?: IResolvedCreditBillSettlement[];
251
+ /** Partial-receipt patches: update the SAME issue entry's cumulative amount. */
252
+ receipt_bills?: IResolvedCreditBillReceiptPatch[];
194
253
  }
195
254
  /**
196
255
  * Applies one write to a stored credit document — NEVER throws (`null` on
@@ -208,7 +267,12 @@ export interface IMaterializedCreditBillScopeRef {
208
267
  scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
209
268
  scope_field: string;
210
269
  }
211
- /** `Writes the watermarks / schema / key-filter grammar allow a write?` (mirrors the sales-report guard). */
270
+ /**
271
+ * `Writes the watermarks / day-input signature / schema / key-filter grammar
272
+ * allow a write?` (mirrors the sales-report guard). The signature is checked
273
+ * FIRST so a deleted / moved order still corrects the ledger when the incoming
274
+ * watermark regressed.
275
+ */
212
276
  export declare const needsMaterializedCreditBillsReportWrite: (existing: IMaterializedTenantCreditBillsReport | null | undefined, incoming: IMaterializedTenantCreditBillsReport) => boolean;
213
277
  /**
214
278
  * The day-close fetch plan: every scope document one compiled day may touch —