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