@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,620 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isValidDeliveryCoordinate = isValidDeliveryCoordinate;
4
+ exports.deliveryGeoCellOf = deliveryGeoCellOf;
5
+ exports.deliveryGeoCellCentroid = deliveryGeoCellCentroid;
6
+ exports.mergeDeliveryGeoCounters = mergeDeliveryGeoCounters;
7
+ exports.deliveryGeoKeyPart = deliveryGeoKeyPart;
8
+ exports.deliveryGeoKeyOfOrder = deliveryGeoKeyOfOrder;
9
+ exports.deliveryGeoKeyOfParts = deliveryGeoKeyOfParts;
10
+ exports.mergeDeliveryGeoByKey = mergeDeliveryGeoByKey;
11
+ exports.boundDeliveryGeoByKey = boundDeliveryGeoByKey;
12
+ exports.deliveryOrderCharge = deliveryOrderCharge;
13
+ exports.deliveryRecordPayout = deliveryRecordPayout;
14
+ exports.compileTenantDeliveryGeoCellsWithStats = compileTenantDeliveryGeoCellsWithStats;
15
+ exports.compileTenantDeliveryGeoCells = compileTenantDeliveryGeoCells;
16
+ exports.compileDeliveryGeoCounters = compileDeliveryGeoCounters;
17
+ exports.dominantCity = dominantCity;
18
+ exports.capDeliveryGeoCells = capDeliveryGeoCells;
19
+ exports.deliveryGeoCellWithinViewport = deliveryGeoCellWithinViewport;
20
+ exports.isDeliveryGeoCellSuppressed = isDeliveryGeoCellSuppressed;
21
+ exports.filterDeliveryGeoCell = filterDeliveryGeoCell;
22
+ exports.mergeDeliveryGeoCellsByH3 = mergeDeliveryGeoCellsByH3;
23
+ exports.buildDeliveryGeoResponse = buildDeliveryGeoResponse;
24
+ const h3_js_1 = require("h3-js");
25
+ const delivery_1 = require("../../constants/enums/delivery");
26
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
27
+ const price_conversion_1 = require("../utils/price-conversion");
28
+ const materialized_delivery_classification_helpers_1 = require("./materialized-delivery-classification-helpers");
29
+ const materialized_delivery_compile_helpers_1 = require("./materialized-delivery-compile-helpers");
30
+ /**
31
+ * Delivery DEMAND HEAT MAP - the H3 cell compiler (M4.1).
32
+ *
33
+ * ## The cell is derived from the JOINED ORDER's destination
34
+ *
35
+ * The order carries the only customer coordinate the platform has
36
+ * (`delivery_details.lat/lng`). A delivery document carries the RIDER's trace, which is
37
+ * not the demand location and is deliberately not used here.
38
+ *
39
+ * ## Privacy
40
+ *
41
+ * A cell document stores an H3 cell index and its DERIVED CENTROID - never a customer
42
+ * coordinate, never an address, never a polyline. The centroid is a property of the cell
43
+ * (identical for every order inside it), so it reveals nothing about an individual drop.
44
+ *
45
+ * ## Invalid coordinates
46
+ *
47
+ * Missing, non-finite, out-of-range or `(0, 0)` coordinates cannot be plotted. They are
48
+ * NOT dropped: they land in the reserved `__UNKNOWN__` aggregate, which has NO geometry,
49
+ * so the map can still say "N orders could not be located" without inventing a place.
50
+ *
51
+ * ## Two populations, again
52
+ *
53
+ * `orders` is EVERY delivery order in the cell (off-app included) - the demand unit.
54
+ * `delivery_records` counts delivery documents/attempts; `app_orders` counts unique
55
+ * orders with at least one document. A cell with 10 orders and 0 records is a real,
56
+ * useful map point: it is demand the rider app never saw.
57
+ */
58
+ /** True when a coordinate pair can be turned into a cell. `(0, 0)` is explicitly invalid. */
59
+ function isValidDeliveryCoordinate(lat, lng) {
60
+ const latitude = Number(lat);
61
+ const longitude = Number(lng);
62
+ if (!Number.isFinite(latitude) || !Number.isFinite(longitude))
63
+ return false;
64
+ // (0, 0) is the classic "never filled in" default of the ordering apps; treating it
65
+ // as a real place would put phantom demand in the Gulf of Guinea.
66
+ if (latitude === 0 && longitude === 0)
67
+ return false;
68
+ return latitude >= -90 && latitude <= 90 && longitude >= -180 && longitude <= 180;
69
+ }
70
+ /** The H3 cell of a coordinate pair, or null when the pair is invalid. */
71
+ function deliveryGeoCellOf(lat, lng, resolution = MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_RESOLUTION) {
72
+ if (!isValidDeliveryCoordinate(lat, lng))
73
+ return null;
74
+ return (0, h3_js_1.latLngToCell)(Number(lat), Number(lng), resolution);
75
+ }
76
+ /** `[lng, lat]` centroid of an H3 cell (GeoJSON order). */
77
+ function deliveryGeoCellCentroid(cell) {
78
+ if (typeof cell !== 'string' || cell === '' || cell === MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_UNKNOWN_CELL) {
79
+ return null;
80
+ }
81
+ try {
82
+ const [lat, lng] = (0, h3_js_1.cellToLatLng)(cell);
83
+ if (!Number.isFinite(lat) || !Number.isFinite(lng))
84
+ return null;
85
+ return [lng, lat];
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
91
+ /** The GeoJSON location of a cell, omitted when the cell has no resolvable centroid. */
92
+ function locationOf(cell) {
93
+ const centroid = deliveryGeoCellCentroid(cell);
94
+ if (centroid == null)
95
+ return {};
96
+ return { location: { type: 'Point', coordinates: centroid } };
97
+ }
98
+ const cents = (value) => {
99
+ const number = typeof value === 'number' ? value : Number(value);
100
+ return Number.isFinite(number) ? Math.round(number) : 0;
101
+ };
102
+ const emptyCounters = () => ({
103
+ orders: 0,
104
+ app_orders: 0,
105
+ delivery_records: 0,
106
+ completed: 0,
107
+ cancelled: 0,
108
+ net_sale_amount: 0,
109
+ delivery_charge_amount: 0,
110
+ rider_revenue_amount: 0,
111
+ });
112
+ const num = (value) => Number(value) || 0;
113
+ /** Merges a cell's counters (used by the day compiler, the month fold and the cap). */
114
+ function mergeDeliveryGeoCounters(target, source) {
115
+ if (target == null || source == null)
116
+ return target;
117
+ target.orders += num(source.orders);
118
+ target.app_orders += num(source.app_orders);
119
+ target.delivery_records += num(source.delivery_records);
120
+ target.completed += num(source.completed);
121
+ target.cancelled += num(source.cancelled);
122
+ target.net_sale_amount += num(source.net_sale_amount);
123
+ target.delivery_charge_amount += num(source.delivery_charge_amount);
124
+ target.rider_revenue_amount += num(source.rider_revenue_amount);
125
+ return target;
126
+ }
127
+ const UNKNOWN_GEO_KEY_PART = 'UNKNOWN';
128
+ /** A bounded key part; unknown / blank values get the UNKNOWN token. */
129
+ function deliveryGeoKeyPart(value) {
130
+ if (value == null)
131
+ return UNKNOWN_GEO_KEY_PART;
132
+ const text = String(value).trim();
133
+ return text === '' ? UNKNOWN_GEO_KEY_PART : text;
134
+ }
135
+ /**
136
+ * The by_key identity of a joined order: ORDER_STATUS:PLATFORM:CITY.
137
+ *
138
+ * The city part is the RESOLVED city - the SAME top-N + `__OTHER__` resolution the report
139
+ * counters use - so the geo cells and the report counters share ONE city dimension. A city
140
+ * filter therefore means exactly the same thing in the map and in the summary, and a cell
141
+ * that holds orders from two cities can be split by city instead of being attributed to
142
+ * its dominant city.
143
+ */
144
+ function deliveryGeoKeyOfOrder(order, city) {
145
+ return (deliveryGeoKeyPart(order?.order_status) + ':' + deliveryGeoKeyPart(order?.platform) + ':' + deliveryGeoKeyPart(city));
146
+ }
147
+ /** The by_key identity of a filter triple; null values mean the UNKNOWN token. */
148
+ function deliveryGeoKeyOfParts(orderStatus, platform, city) {
149
+ return deliveryGeoKeyPart(orderStatus) + ':' + deliveryGeoKeyPart(platform) + ':' + deliveryGeoKeyPart(city);
150
+ }
151
+ const emptyKeyCounters = () => ({
152
+ ...emptyCounters(),
153
+ });
154
+ /** Merges a by_key map; keys are ORDER_STATUS:PLATFORM. */
155
+ function mergeDeliveryGeoByKey(target, source) {
156
+ if (target == null || source == null)
157
+ return target;
158
+ for (const [key, counters] of Object.entries(source)) {
159
+ const current = target[key] ?? emptyKeyCounters();
160
+ mergeDeliveryGeoCounters(current, counters);
161
+ target[key] = current;
162
+ }
163
+ return target;
164
+ }
165
+ /**
166
+ * Caps the by_key map at MATERIALIZED_DELIVERY_GEO_MAX_KEYS. The overflow folds into
167
+ * UNKNOWN:UNKNOWN:UNKNOWN; the cell's top-level counters are unchanged, so sum(by_key)
168
+ * still equals the cell total.
169
+ */
170
+ function boundDeliveryGeoByKey(byKey, maxKeys = MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_MAX_KEYS) {
171
+ const entries = Object.entries(byKey ?? {});
172
+ const limit = Number.isFinite(maxKeys) ? Math.max(1, Math.floor(maxKeys)) : MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_MAX_KEYS;
173
+ if (entries.length <= limit)
174
+ return byKey;
175
+ entries.sort((a, b) => num(b[1]?.orders) + num(b[1]?.delivery_records) - (num(a[1]?.orders) + num(a[1]?.delivery_records)) ||
176
+ (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
177
+ const bounded = {};
178
+ for (const [key, counters] of entries.slice(0, limit - 1))
179
+ bounded[key] = counters;
180
+ const overflowKey = deliveryGeoKeyOfParts(null, null);
181
+ const overflow = bounded[overflowKey] ?? emptyKeyCounters();
182
+ for (const [, counters] of entries.slice(limit - 1)) {
183
+ mergeDeliveryGeoCounters(overflow, counters);
184
+ }
185
+ bounded[overflowKey] = overflow;
186
+ return bounded;
187
+ }
188
+ /** The delivery fee of a delivery order (the declared field, with tolerated fallbacks). */
189
+ function deliveryOrderCharge(order) {
190
+ const details = order?.delivery_details ?? {};
191
+ return cents(details.delivery_cost ?? details.delivery_charge ?? details.delivery_charge_amount);
192
+ }
193
+ /** Finalized rider payout of a delivery document, or 0 when the snapshot is not FINAL. */
194
+ function deliveryRecordPayout(delivery) {
195
+ const earnings = delivery?.rider_earnings;
196
+ if (earnings?.status !== delivery_1.RIDER_EARNINGS_STATUS_ENUM.FINAL)
197
+ return 0;
198
+ return cents(earnings.amount);
199
+ }
200
+ /**
201
+ * Compiles a day and also returns the cap metadata consumed by the scope document.
202
+ * The raw cells are capped exactly once, with the same deterministic ranking as the
203
+ * persisted day scope.
204
+ */
205
+ function compileTenantDeliveryGeoCellsWithStats(input) {
206
+ const maxCells = input?.maxCells ?? MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_MAX_CELLS;
207
+ const raw = compileDeliveryGeoCounters({ ...input, maxCells: Number.MAX_SAFE_INTEGER });
208
+ const cells = capDeliveryGeoCells(raw, maxCells);
209
+ const kept = new Set(cells.map((cell) => String(cell.h3_cell)));
210
+ const dropped = raw.filter((cell) => !kept.has(String(cell.h3_cell)));
211
+ return {
212
+ cells: cells.map((cell) => ({
213
+ ...cell,
214
+ tenant_id: input.tenantId,
215
+ brand_id: input.brandId,
216
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
217
+ scope_field: input.localDate,
218
+ schema_version: MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_SCHEMA_VERSION,
219
+ computed_at: input.computedAt ?? new Date(),
220
+ })),
221
+ cappedCellCount: dropped.length,
222
+ cappedOrderCount: dropped.reduce((sum, cell) => sum + num(cell.orders), 0),
223
+ };
224
+ }
225
+ function compileTenantDeliveryGeoCells(input) {
226
+ return compileTenantDeliveryGeoCellsWithStats(input).cells;
227
+ }
228
+ /**
229
+ * The pure aggregation step: cell index -> counters (no envelope fields).
230
+ *
231
+ * Exported so tests and the month fold can use the exact same arithmetic as the writer.
232
+ */
233
+ function compileDeliveryGeoCounters(input) {
234
+ if (input == null)
235
+ return [];
236
+ const { tenantId } = input;
237
+ if (typeof tenantId !== 'string' || tenantId === '')
238
+ return [];
239
+ const resolution = input.resolution ?? MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_RESOLUTION;
240
+ const maxCells = input.maxCells ?? MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_MAX_CELLS;
241
+ const computedAt = input.computedAt ?? new Date();
242
+ // The heat map is DEMAND from delivery orders. Pickup/dine-in orders are not
243
+ // part of this population and must never enter cells, the unknown aggregate or
244
+ // the cell cap.
245
+ const orders = (Array.isArray(input.orders) ? input.orders : []).filter((order) => order != null && String(order.tenant_id ?? tenantId) === tenantId && (0, materialized_delivery_classification_helpers_1.isDeliveryOrder)(order));
246
+ const deliveries = (Array.isArray(input.deliveries) ? input.deliveries : []).filter((delivery) => delivery != null && String(delivery.tenant_id ?? tenantId) === tenantId);
247
+ const ordersById = new Map();
248
+ for (const order of orders)
249
+ ordersById.set(String(order._id), order);
250
+ const recordsByOrder = new Map();
251
+ const orphans = [];
252
+ for (const delivery of deliveries) {
253
+ const orderId = delivery?.order_id == null ? null : String(delivery.order_id);
254
+ if (orderId == null || !ordersById.has(orderId)) {
255
+ orphans.push(delivery);
256
+ continue;
257
+ }
258
+ const bucket = recordsByOrder.get(orderId);
259
+ if (bucket == null)
260
+ recordsByOrder.set(orderId, [delivery]);
261
+ else
262
+ bucket.push(delivery);
263
+ }
264
+ const accumulators = new Map();
265
+ const accumulatorFor = (cell) => {
266
+ const existing = accumulators.get(cell);
267
+ if (existing != null)
268
+ return existing;
269
+ const created = {
270
+ counters: emptyCounters(),
271
+ byKey: new Map(),
272
+ cities: new Map(),
273
+ };
274
+ accumulators.set(cell, created);
275
+ return created;
276
+ };
277
+ const keyCountersFor = (accumulator, key) => {
278
+ const existing = accumulator.byKey.get(key);
279
+ if (existing != null)
280
+ return existing;
281
+ const created = emptyKeyCounters();
282
+ accumulator.byKey.set(key, created);
283
+ return created;
284
+ };
285
+ const absorbRecord = (accumulator, delivery, keyCounters) => {
286
+ for (const counters of [accumulator.counters, keyCounters]) {
287
+ counters.delivery_records += 1;
288
+ if (String(delivery?.status ?? '') === delivery_1.DELIVERY_STATUS_ENUM.COMPLETED)
289
+ counters.completed += 1;
290
+ else if (String(delivery?.status ?? '') === delivery_1.DELIVERY_STATUS_ENUM.CANCELLED)
291
+ counters.cancelled += 1;
292
+ counters.rider_revenue_amount += deliveryRecordPayout(delivery);
293
+ }
294
+ };
295
+ /**
296
+ * The RESOLVED city - the SAME top-N + `__OTHER__` resolution the report counters use.
297
+ * The geo cells and the report counters must share one city dimension, otherwise a city
298
+ * filter would select different populations in the map and in the summary.
299
+ */
300
+ const resolveArea = (0, materialized_delivery_compile_helpers_1.buildDeliveryCityResolver)(orders);
301
+ for (const order of orders) {
302
+ const details = order.delivery_details ?? {};
303
+ const cell = deliveryGeoCellOf(details.lat, details.lng, resolution) ?? MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_UNKNOWN_CELL;
304
+ const accumulator = accumulatorFor(cell);
305
+ const city = resolveArea((0, materialized_delivery_compile_helpers_1.deliveryAreaOfOrder)(order));
306
+ const key = deliveryGeoKeyOfOrder(order, city);
307
+ const keyCounters = keyCountersFor(accumulator, key);
308
+ const counters = accumulator.counters;
309
+ counters.orders += 1;
310
+ keyCounters.orders += 1;
311
+ const netSale = cents(order.net_sale_amount ?? order.amount_earned);
312
+ const charge = deliveryOrderCharge(order);
313
+ counters.net_sale_amount += netSale;
314
+ counters.delivery_charge_amount += charge;
315
+ keyCounters.net_sale_amount += netSale;
316
+ keyCounters.delivery_charge_amount += charge;
317
+ if (city != null && city !== '')
318
+ accumulator.cities.set(city, (accumulator.cities.get(city) ?? 0) + 1);
319
+ const records = recordsByOrder.get(String(order._id)) ?? [];
320
+ if (records.length > 0) {
321
+ counters.app_orders += 1;
322
+ keyCounters.app_orders += 1;
323
+ }
324
+ for (const record of records)
325
+ absorbRecord(accumulator, record, keyCounters);
326
+ }
327
+ // A delivery document whose order was not staged still counts as an APP RECORD; its
328
+ // area and order money are unknown, so it can only be attributed to the unknown cell
329
+ // AND the bounded UNKNOWN:UNKNOWN:UNKNOWN filter key.
330
+ for (const orphan of orphans) {
331
+ const accumulator = accumulatorFor(MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_UNKNOWN_CELL);
332
+ absorbRecord(accumulator, orphan, keyCountersFor(accumulator, deliveryGeoKeyOfParts(null, null, null)));
333
+ }
334
+ const built = [];
335
+ for (const [cell, accumulator] of accumulators) {
336
+ const unknown = cell === MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_UNKNOWN_CELL;
337
+ const city = dominantCity(accumulator.cities);
338
+ built.push({
339
+ tenant_id: tenantId,
340
+ brand_id: String(input.brandId ?? ''),
341
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
342
+ scope_field: String(input.localDate ?? ''),
343
+ city,
344
+ h3_cell: cell,
345
+ resolution: unknown ? 0 : resolution,
346
+ ...(unknown ? {} : locationOf(cell)),
347
+ ...accumulator.counters,
348
+ by_key: boundDeliveryGeoByKey(Object.fromEntries(accumulator.byKey)),
349
+ schema_version: MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_SCHEMA_VERSION,
350
+ computed_at: computedAt,
351
+ });
352
+ }
353
+ return capDeliveryGeoCells(built, maxCells);
354
+ }
355
+ /** Deterministic dominant city: most orders, then city ASC. */
356
+ function dominantCity(counts) {
357
+ let best = null;
358
+ let bestCount = -1;
359
+ for (const [city, count] of counts) {
360
+ if (count > bestCount || (count === bestCount && best != null && city < best)) {
361
+ best = city;
362
+ bestCount = count;
363
+ }
364
+ }
365
+ return best;
366
+ }
367
+ /**
368
+ * Caps a scope's cells at `maxCells`, ranked `orders DESC, h3_cell ASC`.
369
+ *
370
+ * The tail is DROPPED, not folded: the heat response reports scope totals from the
371
+ * report counters, so a capped map can never overstate them. Keeping a synthetic
372
+ * `__OTHER__` geometry would put a meaningless point on the map.
373
+ */
374
+ function capDeliveryGeoCells(cells, maxCells = MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_MAX_CELLS) {
375
+ if (!Array.isArray(cells))
376
+ return [];
377
+ const limit = Number.isFinite(maxCells) ? Math.max(0, Math.floor(maxCells)) : MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_MAX_CELLS;
378
+ const ranked = [...cells].sort((a, b) => num(b?.orders) - num(a?.orders) ||
379
+ (String(a?.h3_cell) < String(b?.h3_cell) ? -1 : String(a?.h3_cell) > String(b?.h3_cell) ? 1 : 0));
380
+ return ranked.slice(0, limit);
381
+ }
382
+ /** True when the cell's centroid falls inside the viewport (antimeridian-safe). */
383
+ function deliveryGeoCellWithinViewport(cell, viewport) {
384
+ if (viewport == null)
385
+ return true;
386
+ const coordinates = cell?.location?.coordinates;
387
+ if (!Array.isArray(coordinates) || coordinates.length !== 2) {
388
+ // A cell without geometry (the unknown aggregate) cannot be inside a box; a
389
+ // viewport read is a map read, and the map cannot place it.
390
+ return false;
391
+ }
392
+ const [lng, lat] = coordinates;
393
+ if (!(lat >= viewport.south && lat <= viewport.north))
394
+ return false;
395
+ // A west > east box crosses the antimeridian.
396
+ if (viewport.west <= viewport.east)
397
+ return lng >= viewport.west && lng <= viewport.east;
398
+ return lng >= viewport.west || lng <= viewport.east;
399
+ }
400
+ /** True when the cell must be hidden: fewer orders than the privacy threshold. */
401
+ function isDeliveryGeoCellSuppressed(cell, minOrders = MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_MIN_ORDERS) {
402
+ return num(cell?.orders) < minOrders;
403
+ }
404
+ const GEO_FILTER_UNSET = '__GEO_FILTER_UNSET__';
405
+ /**
406
+ * True when a by_key entry matches the selected status/platform/city filters.
407
+ *
408
+ * The key is ORDER_STATUS:PLATFORM:CITY. The CITY is the LAST part, because a city name
409
+ * may itself contain a colon - the same convention the report key parser uses.
410
+ */
411
+ function deliveryGeoKeyMatches(key, filters) {
412
+ const parts = String(key ?? '').split(':');
413
+ const status = parts[0] ?? '';
414
+ const platform = parts.length > 1 ? parts[1] : GEO_FILTER_UNSET;
415
+ const city = parts.length > 2 ? parts.slice(2).join(':') : GEO_FILTER_UNSET;
416
+ const statuses = filters.order_statuses;
417
+ const platforms = filters.platforms;
418
+ const cities = filters.cities;
419
+ if (statuses != null && statuses.length > 0) {
420
+ const selected = new Set(statuses.map((value) => deliveryGeoKeyPart(value)));
421
+ if (!selected.has(status))
422
+ return false;
423
+ }
424
+ if (platforms != null && platforms.length > 0) {
425
+ const selected = new Set(platforms.map((value) => deliveryGeoKeyPart(value)));
426
+ if (!selected.has(platform))
427
+ return false;
428
+ }
429
+ if (cities != null && cities.length > 0) {
430
+ const selected = new Set(cities.map((value) => deliveryGeoKeyPart(value)));
431
+ if (!selected.has(city))
432
+ return false;
433
+ }
434
+ return true;
435
+ }
436
+ /**
437
+ * Applies the city / platform / order-status filters to ONE cell by summing its by_key
438
+ * map. Returns null when the cell has no matching key.
439
+ *
440
+ * EVERY filter is applied per key, so the cell's counters are the EXACT counters of the
441
+ * selected population - never the cell total of a cell that merely had a matching
442
+ * dominant city. Cells without by_key (pre-v4) are unavailable for a filtered read
443
+ * rather than silently treated as zero.
444
+ */
445
+ function filterDeliveryGeoCell(cell, filters) {
446
+ if (cell == null)
447
+ return null;
448
+ const statuses = filters?.order_statuses;
449
+ const platforms = filters?.platforms;
450
+ const cities = filters?.cities;
451
+ const statusActive = statuses != null && statuses.length > 0;
452
+ const platformActive = platforms != null && platforms.length > 0;
453
+ const cityActive = cities != null && cities.length > 0;
454
+ if (!statusActive && !platformActive && !cityActive)
455
+ return cell;
456
+ if (cell.by_key == null)
457
+ return null;
458
+ const counters = emptyCounters();
459
+ let matched = false;
460
+ for (const [key, value] of Object.entries(cell.by_key)) {
461
+ if (!deliveryGeoKeyMatches(key, filters))
462
+ continue;
463
+ matched = true;
464
+ mergeDeliveryGeoCounters(counters, value);
465
+ }
466
+ if (!matched)
467
+ return null;
468
+ const next = { ...cell, ...counters, by_key: null };
469
+ if (cityActive) {
470
+ // The LABEL must never name a city that was filtered out. One selected city keeps its
471
+ // name; several selected cities make the cell ambiguous, so the label is dropped.
472
+ const selected = [...new Set(cities.map((value) => deliveryGeoKeyPart(value)))];
473
+ const only = selected.length === 1 ? selected[0] : null;
474
+ next.city = only == null || only === UNKNOWN_GEO_KEY_PART ? null : only;
475
+ }
476
+ return next;
477
+ }
478
+ /**
479
+ * Merges cells that share an H3 index. This is what makes a brand-level response a
480
+ * MAP rather than a pile of tenant rows: two tenants can produce the same cell, and the
481
+ * response has no tenant dimension, so the counters must be summed before the map cap.
482
+ * The city label is kept only when every merged tenant agrees; otherwise it is null.
483
+ */
484
+ function mergeDeliveryGeoCellsByH3(cells) {
485
+ const merged = new Map();
486
+ for (const cell of cells ?? []) {
487
+ if (cell == null)
488
+ continue;
489
+ const h3 = String(cell.h3_cell ?? '');
490
+ if (h3 === '' || h3 === MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_UNKNOWN_CELL)
491
+ continue;
492
+ const existing = merged.get(h3);
493
+ if (existing == null) {
494
+ merged.set(h3, {
495
+ ...cell,
496
+ ...(cell.by_key == null ? {} : { by_key: { ...cell.by_key } }),
497
+ });
498
+ continue;
499
+ }
500
+ mergeDeliveryGeoCounters(existing, cell);
501
+ if (cell.by_key != null) {
502
+ existing.by_key ?? (existing.by_key = {});
503
+ mergeDeliveryGeoByKey(existing.by_key, cell.by_key);
504
+ }
505
+ if (existing.city !== cell.city)
506
+ existing.city = null;
507
+ }
508
+ return [...merged.values()];
509
+ }
510
+ /**
511
+ * Turns stored cells into the `POST /reports/delivery/geo` payload.
512
+ *
513
+ * Order of operations matters:
514
+ * 1. apply city/platform/order-status filters to each cell;
515
+ * 2. merge duplicate H3 cells (brand-level tenants can collide);
516
+ * 3. count geometry-less unknown orders (they are never plotted);
517
+ * 4. apply the 2,000-cell read cap to the FILTERED union and count what it dropped;
518
+ * 5. apply the viewport and the privacy suppression floor.
519
+ *
520
+ * The cap is applied here rather than before filtering, so both LIVE and HISTORICAL cap
521
+ * the same population. Write-time cap counts (if any) are added to the read-time drops.
522
+ */
523
+ function buildDeliveryGeoResponse(input) {
524
+ const mapDisabled = input.mapDisabled === true;
525
+ if (mapDisabled) {
526
+ // OPTION A (audit H3): `__OTHER__` is a folded key, not a geography. Totals and
527
+ // tables remain valid, but the map must be disabled explicitly - never an empty
528
+ // map that looks like "no demand".
529
+ return {
530
+ cells: [],
531
+ suppressed_cell_count: 0,
532
+ suppressed_order_count: 0,
533
+ capped_cell_count: num(input.cappedCellCount),
534
+ capped_order_count: num(input.cappedOrderCount),
535
+ capped_counts_exact: input.cappedCountsExact !== false,
536
+ total_orders: num(input.totalOrders),
537
+ total_app_orders: num(input.totalAppOrders),
538
+ granularity: input.granularity ?? 'DAY',
539
+ exact_days: input.exactDays !== false,
540
+ unknown_order_count: 0,
541
+ map_disabled: true,
542
+ map_disabled_reason: input.mapDisabledReason ?? 'OTHER_AREAS',
543
+ };
544
+ }
545
+ const minOrders = input.minOrders ?? MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_MIN_ORDERS;
546
+ let suppressedCellCount = 0;
547
+ let suppressedOrderCount = 0;
548
+ let unknownOrderCount = input.unknownOrderCount == null ? 0 : num(input.unknownOrderCount);
549
+ const visible = [];
550
+ const filtered = [];
551
+ for (const rawCell of input.cells ?? []) {
552
+ const cell = filterDeliveryGeoCell(rawCell, input.filters ?? null);
553
+ if (cell == null)
554
+ continue;
555
+ // A cell with no centroid is the unknown aggregate: it is real demand but it cannot
556
+ // be placed on a map. Count it explicitly; never put it in the cell payload.
557
+ const centroid = deliveryGeoCellCentroid(String(cell.h3_cell));
558
+ if (centroid == null) {
559
+ unknownOrderCount += num(cell.orders);
560
+ continue;
561
+ }
562
+ filtered.push(cell);
563
+ }
564
+ // Brand-level cells from different tenants can share an H3 index. The payload has no
565
+ // tenant dimension, so sum them before the cap.
566
+ const merged = mergeDeliveryGeoCellsByH3(filtered);
567
+ let cappedCells = merged;
568
+ let readCappedCellCount = 0;
569
+ let readCappedOrderCount = 0;
570
+ const maxCells = input.maxCells == null ? null : Number(input.maxCells);
571
+ if (maxCells != null && Number.isFinite(maxCells)) {
572
+ cappedCells = capDeliveryGeoCells(merged, maxCells);
573
+ const kept = new Set(cappedCells.map((cell) => String(cell.h3_cell)));
574
+ const dropped = merged.filter((cell) => !kept.has(String(cell.h3_cell)));
575
+ readCappedCellCount = dropped.length;
576
+ readCappedOrderCount = dropped.reduce((sum, cell) => sum + num(cell.orders), 0);
577
+ }
578
+ for (const cell of cappedCells) {
579
+ if (!deliveryGeoCellWithinViewport(cell, input.viewport))
580
+ continue;
581
+ if (isDeliveryGeoCellSuppressed(cell, minOrders)) {
582
+ suppressedCellCount += 1;
583
+ suppressedOrderCount += num(cell?.orders);
584
+ continue;
585
+ }
586
+ const centroid = deliveryGeoCellCentroid(String(cell.h3_cell));
587
+ if (centroid == null)
588
+ continue;
589
+ visible.push({
590
+ h3_cell: String(cell.h3_cell),
591
+ centroid,
592
+ resolution: num(cell.resolution),
593
+ city: cell.city ?? null,
594
+ orders: num(cell.orders),
595
+ app_orders: num(cell.app_orders),
596
+ delivery_records: num(cell.delivery_records),
597
+ completed: num(cell.completed),
598
+ cancelled: num(cell.cancelled),
599
+ net_sale: (0, price_conversion_1.convertPriceFromCents)(num(cell.net_sale_amount)),
600
+ delivery_charge: (0, price_conversion_1.convertPriceFromCents)(num(cell.delivery_charge_amount)),
601
+ rider_revenue: (0, price_conversion_1.convertPriceFromCents)(num(cell.rider_revenue_amount)),
602
+ });
603
+ }
604
+ visible.sort((a, b) => b.orders - a.orders || (a.h3_cell < b.h3_cell ? -1 : a.h3_cell > b.h3_cell ? 1 : 0));
605
+ return {
606
+ cells: visible,
607
+ suppressed_cell_count: suppressedCellCount,
608
+ suppressed_order_count: suppressedOrderCount,
609
+ capped_cell_count: num(input.cappedCellCount) + readCappedCellCount,
610
+ capped_order_count: num(input.cappedOrderCount) + readCappedOrderCount,
611
+ capped_counts_exact: input.cappedCountsExact !== false,
612
+ total_orders: num(input.totalOrders),
613
+ total_app_orders: num(input.totalAppOrders),
614
+ granularity: input.granularity ?? 'DAY',
615
+ exact_days: input.exactDays !== false,
616
+ unknown_order_count: unknownOrderCount,
617
+ map_disabled: false,
618
+ map_disabled_reason: null,
619
+ };
620
+ }