@managesome/eposmatic-toolkit 0.4.29 → 0.4.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +9 -12
  2. package/esm/helpers/materialized-reports/index.js +1 -0
  3. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +129 -20
  4. package/esm/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  5. package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +251 -240
  6. package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +2 -1
  7. package/esm/helpers/materialized-reports/materialized-discount-source-helpers.js +176 -0
  8. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +64 -0
  9. package/esm/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  10. package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  11. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  12. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +284 -43
  13. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -4
  14. package/esm/schemas/models/materialized_report_drilldown_rows.js +39 -12
  15. package/esm/schemas/models/materialized_tenant_discount_entries.js +18 -12
  16. package/esm/schemas/models/materialized_tenant_discount_sources.js +1 -1
  17. package/esm/schemas/models/orders.js +5 -0
  18. package/esm/schemas/models/tenant_calendar.js +12 -0
  19. package/lib/constants/MATERIALIZED_REPORTS.d.ts +9 -12
  20. package/lib/constants/MATERIALIZED_REPORTS.js +11 -14
  21. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  22. package/lib/helpers/materialized-reports/index.js +1 -0
  23. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +38 -0
  24. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +129 -19
  25. package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
  26. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +23 -61
  27. package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +250 -239
  28. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.d.ts +4 -4
  29. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +1 -0
  30. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.d.ts +17 -0
  31. package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +178 -0
  32. package/lib/helpers/materialized-reports/materialized-index-bootstrap.d.ts +7 -0
  33. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +68 -0
  34. package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +3 -1
  35. package/lib/helpers/materialized-reports/materialized-integer-contract.js +30 -4
  36. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.d.ts +2 -2
  37. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
  38. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
  39. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +8 -0
  40. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +283 -42
  41. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -4
  42. package/lib/schemas/models/materialized_report_drilldown_rows.d.ts +40 -6
  43. package/lib/schemas/models/materialized_report_drilldown_rows.js +39 -12
  44. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +33 -29
  45. package/lib/schemas/models/materialized_tenant_discount_entries.js +18 -12
  46. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +6 -6
  47. package/lib/schemas/models/materialized_tenant_discount_sources.js +1 -1
  48. package/lib/schemas/models/orders.d.ts +5 -0
  49. package/lib/schemas/models/orders.js +5 -0
  50. package/lib/schemas/models/tenant_calendar.d.ts +13 -0
  51. package/lib/schemas/models/tenant_calendar.js +13 -1
  52. package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +8 -0
  53. package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +9 -5
  54. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +56 -1
  55. package/lib/tests/materialized-reports/materialized-discount-classification.test.js +17 -0
  56. package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +60 -54
  57. package/lib/tests/materialized-reports/materialized-discount-entries-accumulation.test.js +14 -13
  58. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +76 -0
  59. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +11 -0
  60. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +2 -2
  61. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +152 -7
  62. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +89 -0
  63. package/package.json +1 -1
@@ -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
  ];
@@ -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,
@@ -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';
@@ -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);
@@ -1,5 +1,6 @@
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 { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
3
4
  import { IMaterializedCreditBillIssuedEntry, IMaterializedCreditBillKeySection, IMaterializedCreditBillReceivedEntry, IMaterializedTenantCreditBillsReport } from '../../schemas/types/materialized_credit_bills';
4
5
  import { IGetMaterializedReportScopeGroup } from '../types/materialized-reports-apis';
5
6
  /**
@@ -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;
@@ -212,6 +248,8 @@ export interface IUpdateMaterializedCreditBillsReportInput {
212
248
  additions?: IMaterializedTenantCreditBillsReport[];
213
249
  /** Settlement patches: update issue-scope `issued[]` entries exactly once. */
214
250
  settled_bills?: IResolvedCreditBillSettlement[];
251
+ /** Partial-receipt patches: update the SAME issue entry's cumulative amount. */
252
+ receipt_bills?: IResolvedCreditBillReceiptPatch[];
215
253
  }
216
254
  /**
217
255
  * Applies one write to a stored credit document — NEVER throws (`null` on
@@ -7,6 +7,7 @@ exports.needsMaterializedCreditBillsReportWrite = exports.toMaterializedHourLabe
7
7
  exports.buildCreditBillIssuedCandidatesFromOrder = buildCreditBillIssuedCandidatesFromOrder;
8
8
  exports.buildCreditBillEventCandidatesFromOrder = buildCreditBillEventCandidatesFromOrder;
9
9
  exports.resolveCreditBillDay = resolveCreditBillDay;
10
+ exports.applyCreditResolutionToReportDocuments = applyCreditResolutionToReportDocuments;
10
11
  exports.mergeMaterializedCreditBillSections = mergeMaterializedCreditBillSections;
11
12
  exports.buildMaterializedCreditBillDayReports = buildMaterializedCreditBillDayReports;
12
13
  exports.updateMaterializedCreditBillsReport = updateMaterializedCreditBillsReport;
@@ -133,11 +134,11 @@ function buildCreditBillIssuedCandidatesFromOrder(order, orderLocalDate, options
133
134
  const paymentId = payment.payment_id ?? payment._id ?? null;
134
135
  if (paymentId == null || paymentId.length === 0)
135
136
  return null; // un-keyable bill — data issue
136
- // Money is integer CENTS: the payment amounts are rounded to the cent at
137
- // this writer boundary, because a materialized ledger document may not
138
- // hold a decimal.
139
- const amount = Math.round(payment.amount_due ?? 0);
140
- 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;
141
142
  const settled = !settledLater && receivedAmount >= amount;
142
143
  candidates.push({
143
144
  order_id: order._id,
@@ -173,7 +174,7 @@ function buildCreditBillEventCandidatesFromOrder(order, eventLocalDate, options)
173
174
  if (paymentId == null || paymentId.length === 0)
174
175
  return null; // un-keyable bill — data issue
175
176
  // Money is integer CENTS (see the issued-bill candidate above).
176
- const receivedAmount = Math.round(payment.amount_paid ?? 0);
177
+ const receivedAmount = payment.amount_paid ?? 0;
177
178
  if (receivedAmount <= 0)
178
179
  continue; // nothing collected yet
179
180
  candidates.push({
@@ -182,7 +183,7 @@ function buildCreditBillEventCandidatesFromOrder(order, eventLocalDate, options)
182
183
  order_status: order.order_status,
183
184
  platform: order.platform,
184
185
  // Money is integer CENTS.
185
- amount: Math.round(payment.amount_due ?? 0),
186
+ amount: payment.amount_due ?? 0,
186
187
  issued_at: issuedAt,
187
188
  issued_local_date: orderLocalDate,
188
189
  issued_local_hour: issuedHourLabel,
@@ -239,12 +240,12 @@ function resolveCreditBillDay(input) {
239
240
  for (const report of input.stored ?? []) {
240
241
  if (report == null || report.tenant_id !== tenantId)
241
242
  continue;
242
- for (const [, section] of sectionsOf(report)) {
243
+ for (const [sectionKey, section] of sectionsOf(report)) {
243
244
  for (const entry of section?.issued ?? []) {
244
- const key = creditBillIdentityKey(entry.order_id, entry.payment_id);
245
- const prior = storedIssuedByKey.get(key);
246
- if (prior == null || (entry.received_amount ?? 0) > (prior.received_amount ?? 0)) {
247
- 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 });
248
249
  }
249
250
  }
250
251
  for (const entry of section?.received ?? []) {
@@ -265,7 +266,7 @@ function resolveCreditBillDay(input) {
265
266
  const key = (0, key_helpers_1.buildMaterializedReportKey)([candidate.order_status, candidate.platform]);
266
267
  if (key == null)
267
268
  return null; // un-keyable sale-type fields — data issue
268
- const stored = storedIssuedByKey.get(creditBillIdentityKey(candidate.order_id, candidate.payment_id));
269
+ const stored = storedIssuedByKey.get(creditBillIdentityKey(candidate.order_id, candidate.payment_id))?.entry;
269
270
  issued.push({
270
271
  key,
271
272
  source_watermark: candidate.source_watermark,
@@ -286,12 +287,14 @@ function resolveCreditBillDay(input) {
286
287
  }
287
288
  const received_events = [];
288
289
  const settled_bills = [];
290
+ const receipt_bills = [];
289
291
  for (const candidate of input.events ?? []) {
290
292
  const key = (0, key_helpers_1.buildMaterializedReportKey)([candidate.order_status, candidate.platform]);
291
293
  if (key == null)
292
294
  return null; // un-keyable sale-type fields — data issue
293
295
  const identity = creditBillIdentityKey(candidate.order_id, candidate.payment_id);
294
- const storedIssued = storedIssuedByKey.get(identity) ?? null;
296
+ const storedIssuedRecord = storedIssuedByKey.get(identity) ?? null;
297
+ const storedIssued = storedIssuedRecord?.entry ?? null;
295
298
  const storedEvent = storedReceivedByKey.get(`${identity}|${candidate.event.event_local_date}`) ?? null;
296
299
  let delta;
297
300
  let cumulativeAfter;
@@ -341,11 +344,15 @@ function resolveCreditBillDay(input) {
341
344
  });
342
345
  // The issue scopes must be patched exactly once per settlement — only
343
346
  // for EARLIER issue days (a same-day settlement rides the issued payload).
344
- 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) {
345
351
  const alreadySettled = storedIssued.settled_at != null || storedIssued.settled_local_date != null;
346
- if (!alreadySettled) {
352
+ if (settled && !alreadySettled) {
347
353
  settled_bills.push({
348
354
  key,
355
+ stored_key: storedIssuedRecord?.key ?? null,
349
356
  order_id: candidate.order_id,
350
357
  payment_id: candidate.payment_id,
351
358
  amount,
@@ -357,9 +364,83 @@ function resolveCreditBillDay(input) {
357
364
  issued_local_hour: storedIssued.issued_local_hour ?? candidate.issued_local_hour ?? null,
358
365
  });
359
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
+ }
360
382
  }
361
383
  }
362
- return { issued, received_events, settled_bills };
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;
431
+ }
432
+ }
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 };
363
444
  }
364
445
  const emptySection = () => ({ issued: [], received: [] });
365
446
  const sectionFor = (map, key) => map[key] ?? (map[key] = emptySection());
@@ -583,9 +664,15 @@ function updateMaterializedCreditBillsReport(existing, updates, options = {}) {
583
664
  sourceWatermark = maxDate(sourceWatermark, delta.source_watermark) ?? sourceWatermark;
584
665
  }
585
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
+ };
586
673
  let ledgerPatched = false;
587
674
  for (const settlement of updates.settled_bills ?? []) {
588
- const target = sections[settlement.key];
675
+ const target = findIssueTarget(settlement.key, settlement.stored_key);
589
676
  if (target == null)
590
677
  continue;
591
678
  const index = target.issued.findIndex((entry) => creditBillIdentityKey(entry.order_id, entry.payment_id) ===
@@ -604,12 +691,35 @@ function updateMaterializedCreditBillsReport(existing, updates, options = {}) {
604
691
  };
605
692
  ledgerPatched = true;
606
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
+ }
607
714
  const pruned = pruneSections(sections);
608
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();
609
719
  return {
610
720
  ...existing,
611
721
  credit_bills: pruned,
612
- iteration: (existing.iteration ?? 1) + (changed || ledgerPatched ? 1 : 0),
722
+ iteration: (existing.iteration ?? 1) + (changed || ledgerPatched || envelopeChanged ? 1 : 0),
613
723
  // A REPLACEMENT carries the freshly compiled day digest; period folds keep
614
724
  // the stored value (their payload is a running ledger, not one day's input).
615
725
  source_input_signature: updates.replacement?.source_input_signature ?? existing.source_input_signature,
@@ -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
  }
@@ -17,15 +17,14 @@ import { IMaterializedTenantReportIterationInput } from '../../schemas/types/mat
17
17
  * subtracts the stored DATE document (the day's previous delta) before adding
18
18
  * the fresh compile. Each write carries its
19
19
  * `materialized_tenant_reports_iterations` history row — persist both.
20
- * - **`entryWrites`** — the day's `materialized_tenant_discount_entries`
21
- * documents. Rows are NOT accumulated across days (a row belongs to exactly
22
- * one day), so each scope document is REPLACED by the day's rows; a scope with
23
- * no rows is dropped from the day (and its stored document, if any, becomes
24
- * stale).
25
- * - **`staleDocuments`** / **`staleEntryDocuments`** — stored day-scoped
20
+ * - **`entryWrites`** — the closing day's `materialized_tenant_discount_entries`
21
+ * PAGES. Day/hour pages are `page='all'`; each period scope contributes one
22
+ * page for the source `localDate`. A page is REPLACED wholesale; a page with no
23
+ * rows is deleted. Other days' pages are never in the input and never touched.
24
+ * - **`staleDocuments`** / **`staleEntryDocuments`** — stored day-owned
26
25
  * documents whose activity disappeared (orders deleted / moved) — delete by
27
- * `_id`. Only DAY-scoped documents (date + hour) go stale; period documents
28
- * are corrected by subtraction instead.
26
+ * `_id`. Period COUNTERS are corrected by subtraction; period ENTRY pages are
27
+ * deleted/replaced page-by-page.
29
28
  * - **`skippedDocuments`** / **`skippedEntryDocuments`** — already up to date
30
29
  * (see `needsMaterializedDiscountReportWrite`).
31
30
  *
@@ -65,34 +64,12 @@ export interface IBuildTenantDiscountCloseDayPlanInput {
65
64
  */
66
65
  existing?: IMaterializedTenantDiscountReport[];
67
66
  /**
68
- * Stored ENTRY documents, in plain JSON (`.lean()`).
69
- *
70
- * Required content - **both** of these, and the plan's repairs depend on it:
71
- *
72
- * 1. the day's own scope refs (its `localDate` + `localHour` entry documents and
73
- * the PERIOD entry documents it rolls into);
74
- * 2. **the period's DAY-scoped entry documents** - every `localDate` entry document
75
- * whose period refs (`getMaterializedDiscountScopeRefsForDay`) include one of
76
- * those period scopes.
77
- *
78
- * (2) is not an optimisation. Period rows are DERIVED from day rows, so a period
79
- * document that was never persisted - a partial failure between the counter writes
80
- * and the entry writes, which are persisted separately - can only be rebuilt from
81
- * the day documents still on hand. Without them it is rebuilt from the closing day
82
- * alone and every sibling day silently disappears from the period drill-down.
83
- *
84
- * **Under-fetching is silent.** A caller passing only (1) still gets correct
85
- * emptied-day, correction and shrink behaviour; only the missing-document repair
86
- * degrades. That is why (2) is part of the contract rather than a hint.
67
+ * Stored ENTRY pages owned by THIS close, in plain JSON (`.lean()`):
68
+ * the closing day's date/hour pages (`page = 'all'`) and the closing day's
69
+ * period pages (`page = localDate`). No other page is fetched or touched.
70
+ * A stored entry without a page is inconsistent input and fails the plan.
87
71
  */
88
72
  existingEntries?: IMaterializedTenantDiscountEntries[];
89
- /**
90
- * Set only when `existingEntries` contains every stored DAY-scoped entry
91
- * document in the touched periods. A period entry document that is missing
92
- * while its counter document exists can only be repaired from that complete
93
- * set; without this acknowledgement the plan refuses to guess.
94
- */
95
- existingEntriesComplete?: boolean;
96
73
  /**
97
74
  * Stored `localDate` COUNTER documents of the same tenant (the sibling days
98
75
  * inside the touched periods, excluding the closing day), used ONLY to
@@ -105,6 +82,8 @@ export interface IBuildTenantDiscountCloseDayPlanInput {
105
82
  * belong to the created scope.
106
83
  */
107
84
  existingPeriodDayDocuments?: IMaterializedTenantDiscountReport[];
85
+ /** Stored `localMonth` counters for quarter/semester/year repair (never weeks). */
86
+ existingPeriodMonthDocuments?: IMaterializedTenantDiscountReport[];
108
87
  /** Why this close is applied — stored as every history row's `reason`. */
109
88
  reason: string;
110
89
  /** Force structural writes even when the watermarks are up to date. */
@@ -115,7 +94,10 @@ export interface IBuildTenantDiscountCloseDayPlanInput {
115
94
  export interface ITenantDiscountCloseDayPlan {
116
95
  /** Counter writes (report + history row) — persist in any order. */
117
96
  writes: IMaterializedDiscountCloseDayWrite<IMaterializedTenantDiscountReport>[];
118
- /** Entry writes (rows + history row) — persist after the counter writes. */
97
+ /**
98
+ * Entry PAGE writes (rows + full-page history row) — persist after counters.
99
+ * A period scope contributes ONE page per source day.
100
+ */
119
101
  entryWrites: IMaterializedDiscountCloseDayWrite<IMaterializedTenantDiscountEntries>[];
120
102
  /** Stored DAY-scoped counter docs no longer backed by activity — delete by `_id`. */
121
103
  staleDocuments: IMaterializedTenantDiscountReport[];
@@ -136,22 +118,9 @@ export interface ITenantDiscountCloseDayPlan {
136
118
  /** Every stored scope one local day's plan needs (date + 3 periods + 24 hours). */
137
119
  export declare function getMaterializedDiscountScopeRefsForDay(localDate: string): IMaterializedDiscountScopeRef[] | null;
138
120
  /**
139
- * Every `localDate` day label whose day-scoped ENTRY documents can belong to the
140
- * periods the closing day rolls into (`week`, ISO week, month — whatever
141
- * `MATERIALIZED_DISCOUNT_REPORT_SCOPES` accumulates).
142
- *
143
- * This is the **sibling-day fetch contract** in code: a close caller must fetch
144
- * every `localDate` entry document whose `scope_field` is in this set, in
145
- * addition to the day's own scope refs. Period entry documents are DERIVED from
146
- * day rows, so a period document that was never persisted can only be rebuilt
147
- * from the sibling days — without them the plan rebuilds the period from the
148
- * closing day alone and every other day silently disappears from the period
149
- * drill-down (see `buildTenantDiscountCloseDayPlan`).
150
- *
151
- * The returned set always contains `localDate` itself and is sorted. Returns
152
- * `null` (never throws) for a malformed date or an unparseable period value —
153
- * a `null` means the caller must fail loudly rather than pass an incomplete
154
- * `existingEntries` set with `existingEntriesComplete: true`.
121
+ * Every `localDate` label whose day-scoped COUNTER documents can belong to the
122
+ * periods the closing day rolls into. Used ONLY to repair a missing period
123
+ * counter; entry pages are keyed by the closed day and never use this set.
155
124
  */
156
125
  export declare function getMaterializedDiscountPeriodDayScopeFields(localDate: string): string[] | null;
157
126
  /**
@@ -201,20 +170,13 @@ export declare const mergeMaterializedDiscountEntrySections: (stored: Record<str
201
170
  */
202
171
  export declare const subtractMaterializedDiscountEntrySections: (stored: Record<string, IMaterializedDiscountKeySection> | null | undefined, removed: Record<string, IMaterializedDiscountKeySection> | null | undefined) => Record<string, IMaterializedDiscountKeySection>;
203
172
  /**
204
- * Updates a stored ENTRY document.
205
- *
206
- * - DAY scopes (`localHour` / `localDate`) are REPLACED wholesale: the day's rows
207
- * are the whole truth for that scope.
208
- * - PERIOD scopes (`localWeek` / `localWeekOfYear` / `localMonth`) MERGE, because
209
- * the compile produces only ONE day of rows: replacing would leave the period
210
- * showing just its final day.
173
+ * Updates ONE stored ENTRY PAGE by replacing it with the compiled page. Rows
174
+ * never merge across pages; a source day is the whole truth for its page.
211
175
  *
212
- * Returns null when the documents disagree on schema/scope (a data issue the
213
- * caller must surface).
176
+ * Returns null when the documents disagree on schema/scope/page.
214
177
  */
215
178
  export declare function updateMaterializedDiscountEntries(existing: IMaterializedTenantDiscountEntries | null | undefined, compiled: IMaterializedTenantDiscountEntries | null | undefined, options?: {
216
179
  computedAt?: Date;
217
- mergePeriodRows?: boolean;
218
180
  }): IMaterializedTenantDiscountEntries | null;
219
181
  /** True when a stored entry document equals the compiled one's rows + watermark. */
220
182
  export declare function needsMaterializedDiscountEntriesWrite(existing: IMaterializedTenantDiscountEntries | null | undefined, incoming: IMaterializedTenantDiscountEntries | null | undefined): boolean;