@managesome/eposmatic-toolkit 0.4.52 → 0.4.54

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 (164) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +106 -2
  2. package/esm/constants/enums/delivery.js +13 -0
  3. package/esm/helpers/materialized-reports/index.js +6 -0
  4. package/esm/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +8 -62
  5. package/esm/helpers/materialized-reports/materialized-delivery-classification-helpers.js +95 -73
  6. package/esm/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +118 -146
  7. package/esm/helpers/materialized-reports/materialized-delivery-compile-helpers.js +304 -71
  8. package/esm/helpers/materialized-reports/materialized-delivery-entry-pages.js +307 -0
  9. package/esm/helpers/materialized-reports/materialized-delivery-index-migration.js +103 -0
  10. package/esm/helpers/materialized-reports/materialized-delivery-rows.js +109 -0
  11. package/esm/helpers/materialized-reports/materialized-delivery-wipe-targets.js +32 -0
  12. package/esm/helpers/materialized-reports/materialized-document-size.js +65 -0
  13. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +31 -16
  14. package/esm/helpers/materialized-reports/materialized-integer-contract.js +10 -1
  15. package/esm/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +3 -91
  16. package/esm/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.js +597 -0
  17. package/esm/helpers/materialized-reports/report-platform/definition.js +508 -0
  18. package/esm/helpers/materialized-reports/report-platform/index.js +4 -0
  19. package/esm/helpers/materialized-reports/report-platform/lifecycle/budget.js +27 -0
  20. package/esm/helpers/materialized-reports/report-platform/lifecycle/cap-metadata.js +12 -0
  21. package/esm/helpers/materialized-reports/report-platform/lifecycle/entry-pages.js +121 -0
  22. package/esm/helpers/materialized-reports/report-platform/lifecycle/flat-projection.js +14 -0
  23. package/esm/helpers/materialized-reports/report-platform/lifecycle/index.js +8 -0
  24. package/esm/helpers/materialized-reports/report-platform/lifecycle/iteration-row.js +10 -0
  25. package/esm/helpers/materialized-reports/report-platform/lifecycle/run-stats.js +42 -0
  26. package/esm/helpers/materialized-reports/report-platform/lifecycle/scope-refs.js +28 -0
  27. package/esm/helpers/materialized-reports/report-platform/lifecycle/top-n.js +24 -0
  28. package/esm/helpers/materialized-reports/report-platform/registry.js +23 -0
  29. package/esm/helpers/materialized-reports/report-platform/validate-report-registry.js +214 -0
  30. package/esm/helpers/materialized-reports/scope-helpers.js +98 -0
  31. package/esm/helpers/materialized-reports/tenant-delivery-formatter.js +70 -20
  32. package/esm/schemas/models/applied_order_discounts.js +103 -0
  33. package/esm/schemas/models/index.js +12 -10
  34. package/esm/schemas/models/materialized_tenant_delivery_entries.js +33 -12
  35. package/esm/schemas/models/materialized_tenant_delivery_geo_cells.js +83 -0
  36. package/esm/schemas/models/materialized_tenant_delivery_geo_scopes.js +35 -0
  37. package/esm/schemas/models/materialized_tenant_delivery_reports.js +10 -1
  38. package/esm/schemas/types/applied_order_discounts.js +1 -0
  39. package/esm/schemas/types/index.js +14 -12
  40. package/esm/schemas/types/materialized_tenant_delivery_geo_cells.js +1 -0
  41. package/esm/schemas/types/materialized_tenant_delivery_geo_scopes.js +1 -0
  42. package/lib/constants/MATERIALIZED_REPORTS.d.ts +95 -1
  43. package/lib/constants/MATERIALIZED_REPORTS.js +108 -4
  44. package/lib/constants/enums/delivery.d.ts +9 -0
  45. package/lib/constants/enums/delivery.js +14 -1
  46. package/lib/helpers/materialized-reports/index.d.ts +6 -0
  47. package/lib/helpers/materialized-reports/index.js +6 -0
  48. package/lib/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +8 -62
  49. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.d.ts +36 -9
  50. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.js +94 -72
  51. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.d.ts +23 -26
  52. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +121 -150
  53. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.d.ts +44 -5
  54. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +306 -69
  55. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.d.ts +128 -0
  56. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.js +322 -0
  57. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.d.ts +48 -0
  58. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.js +108 -0
  59. package/lib/helpers/materialized-reports/materialized-delivery-rows.d.ts +15 -0
  60. package/lib/helpers/materialized-reports/materialized-delivery-rows.js +115 -0
  61. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.d.ts +17 -0
  62. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.js +35 -0
  63. package/lib/helpers/materialized-reports/materialized-document-size.d.ts +47 -0
  64. package/lib/helpers/materialized-reports/materialized-document-size.js +73 -0
  65. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +28 -13
  66. package/lib/helpers/materialized-reports/materialized-integer-contract.js +10 -1
  67. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +2 -90
  68. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.d.ts +186 -0
  69. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.js +620 -0
  70. package/lib/helpers/materialized-reports/report-platform/definition.d.ts +133 -0
  71. package/lib/helpers/materialized-reports/report-platform/definition.js +511 -0
  72. package/lib/helpers/materialized-reports/report-platform/index.d.ts +4 -0
  73. package/lib/helpers/materialized-reports/report-platform/index.js +20 -0
  74. package/lib/helpers/materialized-reports/report-platform/lifecycle/budget.d.ts +8 -0
  75. package/lib/helpers/materialized-reports/report-platform/lifecycle/budget.js +31 -0
  76. package/lib/helpers/materialized-reports/report-platform/lifecycle/cap-metadata.d.ts +8 -0
  77. package/lib/helpers/materialized-reports/report-platform/lifecycle/cap-metadata.js +16 -0
  78. package/lib/helpers/materialized-reports/report-platform/lifecycle/entry-pages.d.ts +40 -0
  79. package/lib/helpers/materialized-reports/report-platform/lifecycle/entry-pages.js +130 -0
  80. package/lib/helpers/materialized-reports/report-platform/lifecycle/flat-projection.d.ts +22 -0
  81. package/lib/helpers/materialized-reports/report-platform/lifecycle/flat-projection.js +17 -0
  82. package/lib/helpers/materialized-reports/report-platform/lifecycle/index.d.ts +8 -0
  83. package/lib/helpers/materialized-reports/report-platform/lifecycle/index.js +24 -0
  84. package/lib/helpers/materialized-reports/report-platform/lifecycle/iteration-row.d.ts +13 -0
  85. package/lib/helpers/materialized-reports/report-platform/lifecycle/iteration-row.js +13 -0
  86. package/lib/helpers/materialized-reports/report-platform/lifecycle/run-stats.d.ts +20 -0
  87. package/lib/helpers/materialized-reports/report-platform/lifecycle/run-stats.js +47 -0
  88. package/lib/helpers/materialized-reports/report-platform/lifecycle/scope-refs.d.ts +13 -0
  89. package/lib/helpers/materialized-reports/report-platform/lifecycle/scope-refs.js +31 -0
  90. package/lib/helpers/materialized-reports/report-platform/lifecycle/top-n.d.ts +16 -0
  91. package/lib/helpers/materialized-reports/report-platform/lifecycle/top-n.js +29 -0
  92. package/lib/helpers/materialized-reports/report-platform/registry.d.ts +13 -0
  93. package/lib/helpers/materialized-reports/report-platform/registry.js +31 -0
  94. package/lib/helpers/materialized-reports/report-platform/validate-report-registry.d.ts +20 -0
  95. package/lib/helpers/materialized-reports/report-platform/validate-report-registry.js +218 -0
  96. package/lib/helpers/materialized-reports/scope-helpers.d.ts +8 -0
  97. package/lib/helpers/materialized-reports/scope-helpers.js +99 -0
  98. package/lib/helpers/materialized-reports/tenant-delivery-formatter.d.ts +41 -0
  99. package/lib/helpers/materialized-reports/tenant-delivery-formatter.js +70 -20
  100. package/lib/helpers/order/payment-collection.d.ts +25 -0
  101. package/lib/helpers/order/payment-collection.js +51 -0
  102. package/lib/schemas/models/applied_order_discounts.d.ts +80 -0
  103. package/lib/schemas/models/applied_order_discounts.js +106 -0
  104. package/lib/schemas/models/index.d.ts +12 -10
  105. package/lib/schemas/models/index.js +12 -10
  106. package/lib/schemas/models/materialized_tenant_delivery_entries.d.ts +31 -9
  107. package/lib/schemas/models/materialized_tenant_delivery_entries.js +32 -11
  108. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.d.ts +129 -0
  109. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.js +86 -0
  110. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.d.ts +71 -0
  111. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.js +38 -0
  112. package/lib/schemas/models/materialized_tenant_delivery_reports.d.ts +10 -1
  113. package/lib/schemas/models/materialized_tenant_delivery_reports.js +10 -1
  114. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +15 -15
  115. package/lib/schemas/types/applied_order_discounts.d.ts +22 -0
  116. package/lib/schemas/types/applied_order_discounts.js +2 -0
  117. package/lib/schemas/types/index.d.ts +14 -12
  118. package/lib/schemas/types/index.js +14 -12
  119. package/lib/schemas/types/materialized_tenant_delivery_entries.d.ts +36 -4
  120. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.d.ts +178 -0
  121. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.js +2 -0
  122. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.d.ts +21 -0
  123. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.js +2 -0
  124. package/lib/schemas/types/materialized_tenant_delivery_reports.d.ts +49 -7
  125. package/lib/tests/materialized-reports/analytics-growth-helpers.test.d.ts +1 -0
  126. package/lib/tests/materialized-reports/analytics-overview-helpers.test.d.ts +1 -0
  127. package/lib/tests/materialized-reports/analytics-performance-helpers.test.d.ts +1 -0
  128. package/lib/tests/materialized-reports/characterization/delivery.characterization.test.d.ts +1 -0
  129. package/lib/tests/materialized-reports/characterization/delivery.characterization.test.js +229 -0
  130. package/lib/tests/materialized-reports/characterization/discount.characterization.test.d.ts +1 -0
  131. package/lib/tests/materialized-reports/characterization/discount.characterization.test.js +99 -0
  132. package/lib/tests/materialized-reports/characterization/fixtures.d.ts +30 -0
  133. package/lib/tests/materialized-reports/characterization/fixtures.js +402 -0
  134. package/lib/tests/materialized-reports/characterization/golden.d.ts +18 -0
  135. package/lib/tests/materialized-reports/characterization/golden.js +127 -0
  136. package/lib/tests/materialized-reports/characterization/overview.characterization.test.d.ts +1 -0
  137. package/lib/tests/materialized-reports/characterization/overview.characterization.test.js +69 -0
  138. package/lib/tests/materialized-reports/characterization/prep-time.characterization.test.d.ts +1 -0
  139. package/lib/tests/materialized-reports/characterization/prep-time.characterization.test.js +102 -0
  140. package/lib/tests/materialized-reports/materialized-delivery-accumulation.test.js +56 -19
  141. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.d.ts +1 -0
  142. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.js +91 -0
  143. package/lib/tests/materialized-reports/materialized-delivery-compile.test.js +271 -15
  144. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.d.ts +1 -0
  145. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.js +128 -0
  146. package/lib/tests/materialized-reports/materialized-delivery-fold.test.js +42 -5
  147. package/lib/tests/materialized-reports/materialized-delivery-formatter.test.js +13 -1
  148. package/lib/tests/materialized-reports/materialized-delivery-geo.test.d.ts +1 -0
  149. package/lib/tests/materialized-reports/materialized-delivery-geo.test.js +446 -0
  150. package/lib/tests/materialized-reports/materialized-delivery-plan.test.js +117 -25
  151. package/lib/tests/materialized-reports/materialized-delivery-practical.test.d.ts +1 -0
  152. package/lib/tests/materialized-reports/materialized-delivery-practical.test.js +344 -0
  153. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +14 -0
  154. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +1 -1
  155. package/lib/tests/materialized-reports/report-platform/lifecycle-primitives.test.d.ts +1 -0
  156. package/lib/tests/materialized-reports/report-platform/lifecycle-primitives.test.js +177 -0
  157. package/lib/tests/materialized-reports/report-platform/registry-conformance.test.d.ts +1 -0
  158. package/lib/tests/materialized-reports/report-platform/registry-conformance.test.js +214 -0
  159. package/lib/tests/materialized-reports/report-platform/registry-validation.test.d.ts +1 -0
  160. package/lib/tests/materialized-reports/report-platform/registry-validation.test.js +103 -0
  161. package/lib/tests/offer-item-resolution.test.js +1 -4
  162. package/lib/tests/payment-collection-timestamps.test.d.ts +1 -0
  163. package/lib/tests/payment-collection-timestamps.test.js +71 -0
  164. package/package.json +6 -2
@@ -0,0 +1,178 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ /**
3
+ * Types for `materialized_tenant_delivery_geo_cells` (delivery demand heat map).
4
+ *
5
+ * ## Why this is a SEPARATE collection
6
+ *
7
+ * The heat map is the only part of the delivery report whose cardinality depends on
8
+ * GEOGRAPHY rather than on a fixed dimension set. Embedding it in the report document
9
+ * would put an unbounded array of cells next to the counters and eventually breach the
10
+ * 16 MiB document limit. So the report document stays counters-only and the cells live
11
+ * here, one document per cell.
12
+ *
13
+ * ## One document per `tenant_id + scope_context + scope_field + h3_cell`
14
+ *
15
+ * `scope_context` is ONLY `localDate` or `localMonth`. Each document is a cell's
16
+ * aggregate for one day or one month - never a raw order, never a raw customer point.
17
+ *
18
+ * ## No raw coordinates, ever
19
+ *
20
+ * The only geometry stored is the cell's DERIVED CENTROID (the H3 cell centre), which
21
+ * is a property of the cell and identical for every order inside it. The unknown bucket
22
+ * (`__UNKNOWN__`) deliberately has NO `location` at all, so an unattributable order can
23
+ * never be plotted.
24
+ *
25
+ * ## Money and counts are integer CENTS / counts
26
+ *
27
+ * `net_sale_amount` / `delivery_charge_amount` / `rider_revenue_amount` are integer
28
+ * cents; every other numeric field is an integer count, per the toolkit's
29
+ * integer-only storage contract.
30
+ */
31
+ export interface IDeliveryGeoPoint {
32
+ type: 'Point';
33
+ /** `[lng, lat]` - GeoJSON order, required by the 2dsphere index. */
34
+ coordinates: [number, number];
35
+ }
36
+ /** The counters of ONE heat cell. All integers; money in CENTS. */
37
+ export interface IMaterializedDeliveryGeoCounters {
38
+ /** Delivery ORDERS in the cell (the adoption denominator / demand unit). */
39
+ orders: number;
40
+ /** Unique orders in the cell that produced at least one delivery document. */
41
+ app_orders: number;
42
+ /** Delivery documents / attempts in the cell (>= `app_orders` on reassignment). */
43
+ delivery_records: number;
44
+ completed: number;
45
+ cancelled: number;
46
+ net_sale_amount: number;
47
+ delivery_charge_amount: number;
48
+ rider_revenue_amount: number;
49
+ }
50
+ /** Counters for one `ORDER_STATUS:PLATFORM:CITY` dimension inside a cell. */
51
+ export type IMaterializedDeliveryGeoKeyCounters = IMaterializedDeliveryGeoCounters;
52
+ /**
53
+ * Bounded per-cell filter map. Key = `ORDER_STATUS:PLATFORM:CITY` - the SAME grammar as
54
+ * the report counters, with the RESOLVED city (top-N + `__OTHER__`, `UNKNOWN` when the
55
+ * order carries no city).
56
+ *
57
+ * Because the city is part of the key, a cell that holds orders from several cities can
58
+ * be filtered by city EXACTLY: the selected city's counters are summed out of the map
59
+ * instead of the cell being attributed to its dominant city.
60
+ *
61
+ * Sum(by_key) equals the cell's top-level counters (including the UNKNOWN token for
62
+ * orphan records). The map is capped (see MATERIALIZED_DELIVERY_GEO_MAX_KEYS).
63
+ */
64
+ export type TMaterializedDeliveryGeoByKey = Record<string, IMaterializedDeliveryGeoKeyCounters>;
65
+ /** One `materialized_tenant_delivery_geo_cells` document. */
66
+ export interface IMaterializedTenantDeliveryGeoCell extends IMaterializedDeliveryGeoCounters {
67
+ _id?: string;
68
+ tenant_id: string;
69
+ brand_id: string;
70
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
71
+ scope_field: string;
72
+ /**
73
+ * Dominant city of the cell's orders (max orders; ties resolved by city ASC), or
74
+ * `null` when the joined orders carry no city. The city is derived, never a key -
75
+ * filtering uses the by_key map, never this label.
76
+ */
77
+ city: string | null;
78
+ /** H3 cell index at `resolution`, or the sentinel `__UNKNOWN__`. */
79
+ h3_cell: string;
80
+ /** H3 resolution; `0` for the unknown bucket (which has no cell). */
81
+ resolution: number;
82
+ /**
83
+ * GeoJSON centroid of the cell. ABSENT for the unknown bucket - a document without
84
+ * `location` is simply not indexed by the 2dsphere index.
85
+ */
86
+ location?: IDeliveryGeoPoint;
87
+ /** Bounded ORDER_STATUS:PLATFORM:CITY map; sum equals the top-level counters. */
88
+ by_key?: TMaterializedDeliveryGeoByKey | null;
89
+ schema_version: number;
90
+ computed_at: Date;
91
+ createdAt?: Date;
92
+ updatedAt?: Date;
93
+ }
94
+ /**
95
+ * The heat-endpoint cell shape: aggregates ONLY.
96
+ *
97
+ * It intentionally omits `tenant_id` / `brand_id` / scope fields - the response is for
98
+ * one selection and one view, and repeating the selection on every cell would balloon
99
+ * the payload without telling the map anything.
100
+ *
101
+ * Only MAPPABLE cells appear: the response never carries a raw point and never carries a
102
+ * cell without a centroid. The difference between `total_orders` and the sum of the
103
+ * returned cells is capped / suppressed / unmappable demand - the totals are explicit so
104
+ * that gap is never mistaken for zero.
105
+ */
106
+ export interface IDeliveryGeoCellResponse {
107
+ h3_cell: string;
108
+ /**
109
+ * `[lng, lat]` derived cell centroid. ALWAYS present: a cell without geometry (the
110
+ * unknown aggregate) is not part of the map payload - the map cannot place it, and
111
+ * exposing it with a null centroid would break the frozen client contract.
112
+ */
113
+ centroid: [number, number];
114
+ resolution: number;
115
+ city: string | null;
116
+ orders: number;
117
+ app_orders: number;
118
+ delivery_records: number;
119
+ completed: number;
120
+ cancelled: number;
121
+ net_sale: number;
122
+ delivery_charge: number;
123
+ rider_revenue: number;
124
+ }
125
+ /**
126
+ * Why the heat map is intentionally disabled for a selection.
127
+ *
128
+ * `OTHER_AREAS`: `__OTHER__` is a KEY-FOLD bucket (cities beyond the report's top-50). It
129
+ * has no geography of its own, so the map cannot isolate it. Totals and tables are still
130
+ * valid; the UI must show the explanation instead of an empty map.
131
+ */
132
+ export type TDeliveryGeoMapDisabledReason = 'OTHER_AREAS';
133
+ /** `POST /reports/delivery/geo` response. */
134
+ export interface IDeliveryGeoResponse {
135
+ cells: IDeliveryGeoCellResponse[];
136
+ /** Cells hidden because `orders < MATERIALIZED_DELIVERY_GEO_MIN_ORDERS`. */
137
+ suppressed_cell_count: number;
138
+ /** Orders inside those hidden cells. */
139
+ suppressed_order_count: number;
140
+ /** Cells dropped because the scope exceeded `MATERIALIZED_DELIVERY_GEO_MAX_CELLS`. */
141
+ capped_cell_count: number;
142
+ /** Orders inside those capped cells. */
143
+ capped_order_count: number;
144
+ /**
145
+ * True when the cap counts describe the same population as the filters. Platform/
146
+ * order-status filters cannot be applied to a write-time cap, so they mark this false
147
+ * rather than silently returning 0.
148
+ */
149
+ capped_counts_exact: boolean;
150
+ /** Delivery ORDERS in the whole selected scope (from the report counters). */
151
+ total_orders: number;
152
+ /** Unique app orders in the whole selected scope. */
153
+ total_app_orders: number;
154
+ /**
155
+ * Granularity actually read for the cells.
156
+ *
157
+ * `DAY` - exact cells for the selected days (all days within day-cell retention);
158
+ * `MONTH` - whole-month cells because at least one selected day is older than the
159
+ * day-cell retention window. The UI must label a `MONTH` map as month-granular.
160
+ */
161
+ granularity: 'DAY' | 'MONTH';
162
+ /** True only when the cells cover exactly the selected days. */
163
+ exact_days: boolean;
164
+ /**
165
+ * Orders in the selected scope whose geometry could not be resolved. They are in the
166
+ * counters/totals but cannot be placed on a map; the UI must report them instead of
167
+ * silently showing a cell/total gap.
168
+ */
169
+ unknown_order_count: number;
170
+ /**
171
+ * True when the selection cannot be geographically isolated. When true, `cells` is
172
+ * ALWAYS empty and the UI must render the reason instead of a map; totals and tables
173
+ * remain valid. This is how a non-zero total with no cells is explained honestly.
174
+ */
175
+ map_disabled?: boolean;
176
+ /** Reason for `map_disabled`; null/absent when the map is available. */
177
+ map_disabled_reason?: TDeliveryGeoMapDisabledReason | null;
178
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,21 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ /**
3
+ * Small cap metadata document for ONE geo scope.
4
+ *
5
+ * The cell cap drops cells before persistence, so the dropped counts cannot be
6
+ * reconstructed at read time. This collection stores ONLY the counts, one document per
7
+ * tenant + scope + field; it never stores itemized cells or geometry.
8
+ */
9
+ export interface IMaterializedTenantDeliveryGeoScope {
10
+ _id?: string;
11
+ tenant_id: string;
12
+ brand_id: string;
13
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
14
+ scope_field: string;
15
+ capped_cell_count: number;
16
+ capped_order_count: number;
17
+ schema_version: number;
18
+ computed_at: Date;
19
+ createdAt?: Date;
20
+ updatedAt?: Date;
21
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -11,7 +11,7 @@ import { MATERIALIZED_REPORT_KEY_FILTER_ENUM, MATERIALIZED_REPORT_SCOPE_ENUM } f
11
11
  * (`delivery_order_count` vs `delivered_via_app_count`) before it states any metric, and
12
12
  * `off_app_count` is published as the pool the app can win rather than as an error.
13
13
  *
14
- * KEY GRAMMAR is `<PLATFORM>:<CITY>`, both JOINED FROM THE ORDER: a delivery document
14
+ * KEY GRAMMAR is `<ORDER_STATUS>:<PLATFORM>:<CITY>`, all JOINED FROM THE ORDER: a delivery document
15
15
  * carries neither, so the report joins by `order_id` and keys on the order dimensions.
16
16
  * Rider is deliberately NOT a key dimension - rider ids are high-cardinality, so rider
17
17
  * analysis is a bounded `riders` map inside the document.
@@ -24,7 +24,7 @@ import { MATERIALIZED_REPORT_KEY_FILTER_ENUM, MATERIALIZED_REPORT_SCOPE_ENUM } f
24
24
  export interface IMaterializedDeliveryAdoption {
25
25
  /** Delivery ORDERS in scope - the denominator, from the orders stage. */
26
26
  delivery_order_count: number;
27
- /** Deliveries present in the `deliveries` collection - the numerator. */
27
+ /** UNIQUE delivery ORDERS with at least one delivery document - the numerator. */
28
28
  delivered_via_app_count: number;
29
29
  /** delivery orders with NO delivery document. NOT an error: the pool to win. */
30
30
  off_app_count: number;
@@ -55,7 +55,13 @@ export interface IMaterializedDeliveryMoney {
55
55
  tip_amount: number;
56
56
  /** Order-level discounts, in cents. */
57
57
  discount_amount: number;
58
- /** Refunded order money, in cents. */
58
+ /**
59
+ * Refunded order money, in cents - Σ `order.payments[].amount_refunded`.
60
+ *
61
+ * `IOrder` does NOT declare an order-level `amount_refunded`; refund money exists only
62
+ * on its payment rows. Reading an undeclared order field would silently report every
63
+ * refund as zero, so the accumulator sums the declared source.
64
+ */
59
65
  refund_amount: number;
60
66
  /** Tax on the delivery order, in cents. */
61
67
  tax_amount: number;
@@ -83,14 +89,44 @@ export interface IMaterializedDeliveryRiderRow {
83
89
  first_delivery_at: Date | null;
84
90
  last_delivery_at: Date | null;
85
91
  }
86
- /** One area row, carrying the hot-area hour histogram. */
92
+ /**
93
+ * One area row.
94
+ *
95
+ * AREA ROWS DISTINGUISH THE TWO POPULATIONS, because they are not the same population:
96
+ *
97
+ * - `delivery_orders` / `net_sale_amount` / `delivery_charge_amount` come from the
98
+ * ORDER side, so an OFF-APP delivery order is present (it is a real delivery sale the
99
+ * operator recognizes even when no rider-app document exists);
100
+ * - `delivery_records` / `completed_count` / `cancelled_count` / `rider_revenue_amount`
101
+ * come from the APP side (delivery documents/attempts).
102
+ *
103
+ * `app_orders` is the unique-order intersection, never the record count - one order may
104
+ * have several attempts after a reassignment and must still count once.
105
+ *
106
+ * `by_hour` is the DEMAND heat map: DELIVERY ORDERS bucketed by the JOINED ORDER's
107
+ * tenant-local `localHour` (`"00"`..`"23"`), NOT by any delivery-side hour. The delivery
108
+ * write path has no `localHour`, and deriving one from a server clock would silently
109
+ * shift the map in every non-UTC tenant.
110
+ */
87
111
  export interface IMaterializedDeliveryAreaRow {
88
- count: number;
112
+ /** All delivery ORDERS in this area - the adoption denominator and the demand unit. */
113
+ delivery_orders: number;
114
+ /** Unique orders in this area with at least one delivery document. */
115
+ app_orders: number;
116
+ /** Delivery orders in this area with NO delivery document. */
117
+ off_app_orders: number;
118
+ /** Delivery documents / attempts in this area (>= `app_orders` on reassignment). */
119
+ delivery_records: number;
89
120
  completed_count: number;
90
121
  cancelled_count: number;
122
+ /** CENTS, order side (includes off-app orders). */
123
+ net_sale_amount: number;
124
+ /** CENTS, order side (includes off-app orders). */
125
+ delivery_charge_amount: number;
126
+ /** CENTS, app side - finalized rider payout only. */
91
127
  rider_revenue_amount: number;
92
128
  distance_sum_meters: number;
93
- /** Keys are `"00"`..`"23"` - the hour dimension, as a heat map. */
129
+ /** Keys are `"00"`..`"23"` - delivery ORDERS by the order's local hour. */
94
130
  by_hour: Record<string, number>;
95
131
  }
96
132
  /**
@@ -98,8 +134,14 @@ export interface IMaterializedDeliveryAreaRow {
98
134
  * the capture has NO timing evidence, and reporting 0 would claim instant delivery.
99
135
  */
100
136
  export interface IMaterializedDeliveryTiming {
101
- /** Deliveries that contributed at least one timing figure. */
137
+ /** Deliveries that contributed at least one timing figure (compatibility total). */
102
138
  graded_count: number;
139
+ /** Deliveries with both an order creation instant and a delivery creation instant. */
140
+ dispatch_lag_count: number;
141
+ /** Completed deliveries whose completion instant is known (exact OR proxy). */
142
+ complete_count: number;
143
+ /** Completed deliveries with both an order creation instant and a completion. */
144
+ total_count: number;
103
145
  /** `delivery.createdAt - order.createdAt` - precise even without the capture. */
104
146
  dispatch_lag_sum_minutes: number;
105
147
  /** `delivered_at - delivery.createdAt`, EXACT once the capture has run. */
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const MATERIALIZED_REPORTS_1 = require("../../../constants/MATERIALIZED_REPORTS");
4
+ const materialized_reports_1 = require("../../../helpers/materialized-reports");
5
+ const golden_1 = require("./golden");
6
+ const fixtures_1 = require("./fixtures");
7
+ /**
8
+ * DELIVERY characterization — counters, page entries, geo cells/scopes,
9
+ * suppression/cap metadata, `#N` splitting and the formatter.
10
+ *
11
+ * Current behaviour captured deliberately:
12
+ * - entry pages use `page='all'` for the day scope and the source date for
13
+ * periods; only Delivery has the deterministic `#N` splitter;
14
+ * - ONLY Delivery has BSON budgets (report 15 MiB / page 15 MiB / cell 2 MiB);
15
+ * - off-app orders are counted but never rows; orphan deliveries are records;
16
+ * - the geo `__UNKNOWN__` aggregate is stored but never returned as a cell.
17
+ */
18
+ describe('characterization: Delivery', () => {
19
+ const fixtures = (0, fixtures_1.buildCharacterizationFixtures)();
20
+ const compiled = (0, materialized_reports_1.compileTenantDeliveryReports)({
21
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
22
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
23
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
24
+ orders: fixtures.dayOrders,
25
+ deliveries: fixtures.deliveries,
26
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
27
+ });
28
+ it('compiles counters and one entry page per entry scope', () => {
29
+ expect(compiled).not.toBeNull();
30
+ (0, golden_1.expectGolden)('delivery.compile.day', compiled);
31
+ const dayEntry = compiled.entries.find((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && entry.scope_field === fixtures_1.CHARACTERIZATION_DAY);
32
+ expect(dayEntry.page).toBe('all');
33
+ expect(compiled.entries
34
+ .filter((entry) => entry.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
35
+ .every((entry) => entry.page === fixtures_1.CHARACTERIZATION_DAY)).toBe(true);
36
+ expect(compiled.entries).toHaveLength(4); // date + week + ISO week + month
37
+ });
38
+ it('captures the off-app / orphan / adoption populations', () => {
39
+ const dayReport = compiled.reports.find((report) => report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
40
+ report.scope_field === fixtures_1.CHARACTERIZATION_DAY);
41
+ const counters = Object.values(dayReport.delivery_counters ?? {});
42
+ const adoptionOrders = counters.reduce((sum, counter) => sum + Number(counter?.adoption?.delivery_order_count ?? 0), 0);
43
+ const offApp = counters.reduce((sum, counter) => sum + Number(counter?.adoption?.off_app_count ?? 0), 0);
44
+ expect(adoptionOrders).toBe(4);
45
+ expect(offApp).toBe(1);
46
+ });
47
+ it('builds the flat drill-down projection tagged by source day', () => {
48
+ const rows = [];
49
+ const scopes = [];
50
+ for (const entry of compiled.entries) {
51
+ const sourceLocalDate = String(entry.page) === 'all' ? String(entry.scope_field) : String(entry.page);
52
+ const flattened = (0, materialized_reports_1.buildMaterializedDrilldownRows)(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DELIVERY_ENTRIES, entry, sourceLocalDate);
53
+ rows.push(...flattened.rows);
54
+ const scope = (0, materialized_reports_1.buildMaterializedDrilldownScope)(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DELIVERY_ENTRIES, entry, flattened.rows, sourceLocalDate);
55
+ if (scope != null)
56
+ scopes.push(scope);
57
+ }
58
+ (0, golden_1.expectGolden)('delivery.flat', { rows, scopes });
59
+ expect(rows.length).toBeGreaterThan(0);
60
+ expect(rows.every((row) => row.source_local_date === fixtures_1.CHARACTERIZATION_DAY)).toBe(true);
61
+ });
62
+ it('compiles H3 cells with the current suppression / cap / unknown metadata', () => {
63
+ const result = (0, materialized_reports_1.compileTenantDeliveryGeoCellsWithStats)({
64
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
65
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
66
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
67
+ orders: fixtures.dayOrders,
68
+ deliveries: fixtures.deliveries,
69
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
70
+ maxCells: 1,
71
+ });
72
+ (0, golden_1.expectGolden)('delivery.geo.day', result);
73
+ expect(result.cells.length).toBeLessThanOrEqual(1);
74
+ expect(result.cappedCellCount).toBeGreaterThanOrEqual(0);
75
+ const response = (0, materialized_reports_1.buildDeliveryGeoResponse)({
76
+ cells: result.cells,
77
+ totalOrders: 4,
78
+ totalAppOrders: 3,
79
+ cappedCellCount: result.cappedCellCount,
80
+ cappedOrderCount: result.cappedOrderCount,
81
+ maxCells: 1,
82
+ });
83
+ (0, golden_1.expectGolden)('delivery.geo.response', response);
84
+ // The geometry-less aggregate is never a plotted cell.
85
+ expect(response.cells.every((cell) => cell.h3_cell !== '__UNKNOWN__')).toBe(true);
86
+ });
87
+ it('disables the map for the folded __OTHER__ area', () => {
88
+ const disabled = (0, materialized_reports_1.buildDeliveryGeoResponse)({
89
+ cells: [],
90
+ totalOrders: 4,
91
+ totalAppOrders: 3,
92
+ mapDisabled: true,
93
+ mapDisabledReason: 'OTHER_AREAS',
94
+ });
95
+ (0, golden_1.expectGolden)('delivery.geo.map-disabled', disabled);
96
+ expect(disabled.map_disabled).toBe(true);
97
+ expect(disabled.cells).toEqual([]);
98
+ });
99
+ it('formats the day and month documents, with and without filters', () => {
100
+ const dayReport = compiled.reports.find((report) => report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
101
+ report.scope_field === fixtures_1.CHARACTERIZATION_DAY);
102
+ (0, golden_1.expectGolden)('delivery.formatted.day', (0, materialized_reports_1.getFormattedTenantDeliveryReporting)([dayReport]));
103
+ (0, golden_1.expectGolden)('delivery.formatted.day-filtered', (0, materialized_reports_1.getFormattedTenantDeliveryReporting)([dayReport], {
104
+ platforms: ['POS_DELIVERY', 'APP_DELIVERY'],
105
+ order_statuses: ['COMPLETED'],
106
+ cities: ['Istanbul', 'Ankara'],
107
+ }));
108
+ (0, golden_1.expectGolden)('delivery.formatted.day-rider-filtered', (0, materialized_reports_1.getFormattedTenantDeliveryReporting)([dayReport], { rider_ids: ['rider-1'] }));
109
+ const monthReport = compiled.reports.find((report) => report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
110
+ (0, golden_1.expectGolden)('delivery.formatted.month', (0, materialized_reports_1.getFormattedTenantDeliveryReporting)([monthReport]));
111
+ });
112
+ it('splits an oversized page deterministically and keeps page identities exact', () => {
113
+ const dayEntry = compiled.entries.find((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
114
+ // Force the split path with a deliberately small budget. The row order and
115
+ // the resulting #N names are the current contract.
116
+ const split = (0, materialized_reports_1.splitMaterializedDeliveryEntryPage)(dayEntry, 3000);
117
+ (0, golden_1.expectGolden)('delivery.split.reduced-budget', split);
118
+ expect(split.length).toBeGreaterThan(1);
119
+ expect(split.every((page) => page.page.includes('#'))).toBe(true);
120
+ expect(split.every((page) => page.page === dayEntry.page || page.page.startsWith(`${dayEntry.page}#`))).toBe(true);
121
+ // A page that fits keeps its unsuffixed identity.
122
+ const fitting = (0, materialized_reports_1.splitMaterializedDeliveryEntryPage)(dayEntry, MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_ENTRY_MAX_BSON_BYTES);
123
+ expect(fitting).toHaveLength(1);
124
+ expect(fitting[0].page).toBe(dayEntry.page);
125
+ });
126
+ it('bounds the city and rider dimensions to top-N + __OTHER__', () => {
127
+ const otherOrders = [];
128
+ const otherDeliveries = [];
129
+ for (let index = 0; index < 51; index += 1) {
130
+ const city = `City-${String(index).padStart(2, '0')}`;
131
+ const orderId = `other-order-${index}`;
132
+ otherOrders.push({
133
+ _id: orderId,
134
+ tenant_id: fixtures_1.CHARACTERIZATION_TENANT_ID,
135
+ platform: 'POS_DELIVERY',
136
+ order_status: 'COMPLETED',
137
+ order_number: 500 + index,
138
+ price: 1000,
139
+ amount_earned: 1000,
140
+ amount_collected: 1000,
141
+ total_discount_applied: 0,
142
+ tip_amount: 0,
143
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
144
+ localHour: 12,
145
+ is_deleted: false,
146
+ createdAt: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T11:00:00.000Z`),
147
+ updatedAt: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T12:00:00.000Z`),
148
+ order_settled_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T12:00:00.000Z`),
149
+ categories: [],
150
+ payments: [],
151
+ delivery_details: {
152
+ city,
153
+ state: city,
154
+ delivery_cost: 100,
155
+ distance_in_meters_from_store: 1000,
156
+ lat: 41 + index / 1000,
157
+ lng: 29 + index / 1000,
158
+ },
159
+ });
160
+ otherDeliveries.push({
161
+ _id: `other-delivery-${index}`,
162
+ tenant_id: fixtures_1.CHARACTERIZATION_TENANT_ID,
163
+ order_id: orderId,
164
+ rider_id: `rider-${String(index).padStart(2, '0')}`,
165
+ rider_name: `Rider ${index}`,
166
+ status: 'COMPLETED',
167
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
168
+ distance_in_meters_from_store: 1000,
169
+ tracking_enabled: false,
170
+ assigned_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:00:00.000Z`),
171
+ picked_up_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:10:00.000Z`),
172
+ expected_delivery_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:40:00.000Z`),
173
+ delivered_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:20:00.000Z`),
174
+ cancelled_at: null,
175
+ status_updated_count: 2,
176
+ delivery_minutes: 20,
177
+ rider_earnings: {
178
+ amount: 100,
179
+ status: 'FINAL',
180
+ rule_type: 'DISTANCE_ONE_WAY',
181
+ per_meter: 5000,
182
+ distance_step: 1000,
183
+ distance_meters: 1000,
184
+ delivery_charge: 100,
185
+ calculated_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:20:00.000Z`),
186
+ version: 1,
187
+ },
188
+ createdAt: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:00:00.000Z`),
189
+ updatedAt: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:20:00.000Z`),
190
+ });
191
+ }
192
+ const other = (0, materialized_reports_1.compileTenantDeliveryReports)({
193
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
194
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
195
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
196
+ orders: otherOrders,
197
+ deliveries: otherDeliveries,
198
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
199
+ });
200
+ const report = other.reports.find((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
201
+ const keys = Object.keys(report.delivery_counters ?? {}).sort();
202
+ const formatted = (0, materialized_reports_1.getFormattedTenantDeliveryReporting)([report])[0][0];
203
+ (0, golden_1.expectGolden)('delivery.__other__.summary', {
204
+ key_count: keys.length,
205
+ has_other_city: keys.some((key) => key.endsWith(':__OTHER__')),
206
+ area_keys: formatted.by_area.map((row) => row.city),
207
+ rider_keys: formatted.by_rider.map((row) => row.rider_id),
208
+ summary: {
209
+ orders: formatted.summary.orders,
210
+ delivery_records: formatted.summary.delivery_records,
211
+ rider_revenue: formatted.summary.rider_revenue,
212
+ },
213
+ });
214
+ expect(keys.some((key) => key.endsWith(':__OTHER__'))).toBe(true);
215
+ expect(formatted.by_area.some((row) => row.city === '__OTHER__')).toBe(true);
216
+ expect(formatted.by_rider.some((row) => row.rider_id === '__OTHER__')).toBe(true);
217
+ });
218
+ it('returns null for a day with no delivery orders and no deliveries', () => {
219
+ const empty = (0, materialized_reports_1.compileTenantDeliveryReports)({
220
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
221
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
222
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
223
+ orders: [],
224
+ deliveries: [],
225
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
226
+ });
227
+ expect(empty).toBeNull();
228
+ });
229
+ });
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const MATERIALIZED_REPORTS_1 = require("../../../constants/MATERIALIZED_REPORTS");
4
+ const materialized_reports_1 = require("../../../helpers/materialized-reports");
5
+ const golden_1 = require("./golden");
6
+ const fixtures_1 = require("./fixtures");
7
+ /**
8
+ * DISCOUNTS characterization — compile, page identity, source projection,
9
+ * flat projection and formatter.
10
+ *
11
+ * Current behaviour captured deliberately:
12
+ * - entry pages use `page='all'` for day/hour and the SOURCE DATE for periods;
13
+ * - there is NO `#N` splitter and NO BSON budget guard on Discounts;
14
+ * - the derived source projection is written from the post-plan entries.
15
+ */
16
+ describe('characterization: Discounts', () => {
17
+ const fixtures = (0, fixtures_1.buildCharacterizationFixtures)();
18
+ const compiled = (0, materialized_reports_1.compileTenantDiscountReports)({
19
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
20
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
21
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
22
+ orders: fixtures.dayOrders,
23
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
24
+ });
25
+ it('compiles counters + entry pages with the current page identity', () => {
26
+ expect(compiled).not.toBeNull();
27
+ (0, golden_1.expectGolden)('discount.compile.day', compiled);
28
+ const dayEntries = compiled.entries.filter((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && entry.scope_field === fixtures_1.CHARACTERIZATION_DAY);
29
+ expect(dayEntries).toHaveLength(1);
30
+ expect(dayEntries[0].page).toBe('all');
31
+ const monthEntries = compiled.entries.filter((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
32
+ expect(monthEntries).toHaveLength(1);
33
+ expect(monthEntries[0].page).toBe(fixtures_1.CHARACTERIZATION_DAY);
34
+ // Current behaviour: the Discounts writer has no #N sub-page path.
35
+ expect(compiled.entries.every((entry) => !entry.page.includes('#'))).toBe(true);
36
+ });
37
+ it('builds the source projection from the post-plan day entries', () => {
38
+ const dayEntry = compiled.entries.find((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && entry.scope_field === fixtures_1.CHARACTERIZATION_DAY);
39
+ const sources = (0, materialized_reports_1.buildDiscountSourcesForScope)({
40
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
41
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
42
+ scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
43
+ scopeField: fixtures_1.CHARACTERIZATION_DAY,
44
+ sections: dayEntry.discount_entries,
45
+ sourceWatermark: dayEntry.source_watermark,
46
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
47
+ });
48
+ expect(sources).not.toBeNull();
49
+ (0, golden_1.expectGolden)('discount.sources.day', sources);
50
+ expect(sources.every((source) => source.scope_field === fixtures_1.CHARACTERIZATION_DAY)).toBe(true);
51
+ });
52
+ it('builds the flat drill-down projection for every stored scope', () => {
53
+ const rows = [];
54
+ const scopes = [];
55
+ for (const entry of compiled.entries) {
56
+ const flattened = (0, materialized_reports_1.buildMaterializedDrilldownRows)(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DISCOUNT_ENTRIES, entry, fixtures_1.CHARACTERIZATION_DAY);
57
+ rows.push(...flattened.rows);
58
+ const scope = (0, materialized_reports_1.buildMaterializedDrilldownScope)(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DISCOUNT_ENTRIES, entry, flattened.rows, fixtures_1.CHARACTERIZATION_DAY);
59
+ if (scope != null)
60
+ scopes.push(scope);
61
+ }
62
+ (0, golden_1.expectGolden)('discount.flat', { rows, scopes });
63
+ expect(rows.length).toBeGreaterThan(0);
64
+ });
65
+ it('formats the raw day documents and the aggregated read record', () => {
66
+ const dayDoc = compiled.reports.find((report) => report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
67
+ report.scope_field === fixtures_1.CHARACTERIZATION_DAY);
68
+ (0, golden_1.expectGolden)('discount.formatted.raw-day', (0, materialized_reports_1.getFormattedTenantDiscountsReporting)([dayDoc]));
69
+ (0, golden_1.expectGolden)('discount.formatted.raw-day-filtered', (0, materialized_reports_1.getFormattedTenantDiscountsReporting)([dayDoc], {
70
+ platforms: ['POS_DINE-IN', 'POS_TAKE-AWAY'],
71
+ order_statuses: ['COMPLETED'],
72
+ }));
73
+ const aggregated = {
74
+ tenant_id: dayDoc.tenant_id,
75
+ brand_id: dayDoc.brand_id,
76
+ max_iteration: dayDoc.iteration ?? 1,
77
+ max_updated_at: dayDoc.updatedAt ?? null,
78
+ matched_documents: 1,
79
+ sale_type_key_filters: dayDoc.sale_type_key_filters,
80
+ discount_counters: dayDoc.discount_counters ?? {},
81
+ first_scope_field: dayDoc.scope_field,
82
+ last_scope_field: dayDoc.scope_field,
83
+ };
84
+ (0, golden_1.expectGolden)('discount.formatted.aggregated', (0, materialized_reports_1.getFormattedTenantDiscountsAggregatedReporting)([aggregated]));
85
+ });
86
+ it('compiles an empty day to empty arrays without inventing pages', () => {
87
+ const empty = (0, materialized_reports_1.compileTenantDiscountReports)({
88
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
89
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
90
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
91
+ orders: [],
92
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
93
+ });
94
+ (0, golden_1.expectGolden)('discount.compile.empty-day', empty);
95
+ expect(empty.entries).toEqual([]);
96
+ // Current behaviour: an empty day emits NO counter documents either.
97
+ expect(empty.reports).toEqual([]);
98
+ });
99
+ });