@managesome/eposmatic-toolkit 0.4.52 → 0.4.53

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 (107) 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 +5 -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/scope-helpers.js +98 -0
  18. package/esm/helpers/materialized-reports/tenant-delivery-formatter.js +70 -20
  19. package/esm/schemas/models/applied_order_discounts.js +103 -0
  20. package/esm/schemas/models/index.js +12 -10
  21. package/esm/schemas/models/materialized_tenant_delivery_entries.js +33 -12
  22. package/esm/schemas/models/materialized_tenant_delivery_geo_cells.js +83 -0
  23. package/esm/schemas/models/materialized_tenant_delivery_geo_scopes.js +35 -0
  24. package/esm/schemas/models/materialized_tenant_delivery_reports.js +10 -1
  25. package/esm/schemas/types/applied_order_discounts.js +1 -0
  26. package/esm/schemas/types/index.js +14 -12
  27. package/esm/schemas/types/materialized_tenant_delivery_geo_cells.js +1 -0
  28. package/esm/schemas/types/materialized_tenant_delivery_geo_scopes.js +1 -0
  29. package/lib/constants/MATERIALIZED_REPORTS.d.ts +95 -1
  30. package/lib/constants/MATERIALIZED_REPORTS.js +108 -4
  31. package/lib/constants/enums/delivery.d.ts +9 -0
  32. package/lib/constants/enums/delivery.js +14 -1
  33. package/lib/helpers/materialized-reports/index.d.ts +5 -0
  34. package/lib/helpers/materialized-reports/index.js +5 -0
  35. package/lib/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +8 -62
  36. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.d.ts +36 -9
  37. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.js +94 -72
  38. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.d.ts +23 -26
  39. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +121 -150
  40. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.d.ts +44 -5
  41. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +306 -69
  42. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.d.ts +128 -0
  43. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.js +322 -0
  44. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.d.ts +48 -0
  45. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.js +108 -0
  46. package/lib/helpers/materialized-reports/materialized-delivery-rows.d.ts +15 -0
  47. package/lib/helpers/materialized-reports/materialized-delivery-rows.js +115 -0
  48. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.d.ts +17 -0
  49. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.js +35 -0
  50. package/lib/helpers/materialized-reports/materialized-document-size.d.ts +47 -0
  51. package/lib/helpers/materialized-reports/materialized-document-size.js +73 -0
  52. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +28 -13
  53. package/lib/helpers/materialized-reports/materialized-integer-contract.js +10 -1
  54. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +2 -90
  55. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.d.ts +186 -0
  56. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.js +620 -0
  57. package/lib/helpers/materialized-reports/scope-helpers.d.ts +8 -0
  58. package/lib/helpers/materialized-reports/scope-helpers.js +99 -0
  59. package/lib/helpers/materialized-reports/tenant-delivery-formatter.d.ts +41 -0
  60. package/lib/helpers/materialized-reports/tenant-delivery-formatter.js +70 -20
  61. package/lib/helpers/order/payment-collection.d.ts +25 -0
  62. package/lib/helpers/order/payment-collection.js +51 -0
  63. package/lib/schemas/models/applied_order_discounts.d.ts +80 -0
  64. package/lib/schemas/models/applied_order_discounts.js +106 -0
  65. package/lib/schemas/models/index.d.ts +12 -10
  66. package/lib/schemas/models/index.js +12 -10
  67. package/lib/schemas/models/materialized_tenant_delivery_entries.d.ts +31 -9
  68. package/lib/schemas/models/materialized_tenant_delivery_entries.js +32 -11
  69. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.d.ts +129 -0
  70. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.js +86 -0
  71. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.d.ts +71 -0
  72. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.js +38 -0
  73. package/lib/schemas/models/materialized_tenant_delivery_reports.d.ts +10 -1
  74. package/lib/schemas/models/materialized_tenant_delivery_reports.js +10 -1
  75. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +15 -15
  76. package/lib/schemas/types/applied_order_discounts.d.ts +22 -0
  77. package/lib/schemas/types/applied_order_discounts.js +2 -0
  78. package/lib/schemas/types/index.d.ts +14 -12
  79. package/lib/schemas/types/index.js +14 -12
  80. package/lib/schemas/types/materialized_tenant_delivery_entries.d.ts +36 -4
  81. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.d.ts +178 -0
  82. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.js +2 -0
  83. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.d.ts +21 -0
  84. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.js +2 -0
  85. package/lib/schemas/types/materialized_tenant_delivery_reports.d.ts +49 -7
  86. package/lib/tests/materialized-reports/analytics-growth-helpers.test.d.ts +1 -0
  87. package/lib/tests/materialized-reports/analytics-overview-helpers.test.d.ts +1 -0
  88. package/lib/tests/materialized-reports/analytics-performance-helpers.test.d.ts +1 -0
  89. package/lib/tests/materialized-reports/materialized-delivery-accumulation.test.js +56 -19
  90. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.d.ts +1 -0
  91. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.js +91 -0
  92. package/lib/tests/materialized-reports/materialized-delivery-compile.test.js +271 -15
  93. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.d.ts +1 -0
  94. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.js +128 -0
  95. package/lib/tests/materialized-reports/materialized-delivery-fold.test.js +42 -5
  96. package/lib/tests/materialized-reports/materialized-delivery-formatter.test.js +13 -1
  97. package/lib/tests/materialized-reports/materialized-delivery-geo.test.d.ts +1 -0
  98. package/lib/tests/materialized-reports/materialized-delivery-geo.test.js +446 -0
  99. package/lib/tests/materialized-reports/materialized-delivery-plan.test.js +117 -25
  100. package/lib/tests/materialized-reports/materialized-delivery-practical.test.d.ts +1 -0
  101. package/lib/tests/materialized-reports/materialized-delivery-practical.test.js +344 -0
  102. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +14 -0
  103. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +1 -1
  104. package/lib/tests/offer-item-resolution.test.js +1 -4
  105. package/lib/tests/payment-collection-timestamps.test.d.ts +1 -0
  106. package/lib/tests/payment-collection-timestamps.test.js +71 -0
  107. package/package.json +4 -2
@@ -0,0 +1,446 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const h3_js_1 = require("h3-js");
4
+ const delivery_1 = require("../../constants/enums/delivery");
5
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
6
+ const materialized_tenant_delivery_geo_helpers_1 = require("../../helpers/materialized-reports/materialized-tenant-delivery-geo-helpers");
7
+ const materialized_delivery_entry_pages_1 = require("../../helpers/materialized-reports/materialized-delivery-entry-pages");
8
+ const materialized_document_size_1 = require("../../helpers/materialized-reports/materialized-document-size");
9
+ /**
10
+ * Delivery DEMAND HEAT MAP (H3).
11
+ *
12
+ * The hard requirements pinned here:
13
+ * - a cell is derived from the JOINED ORDER's destination, never from the rider trace;
14
+ * - invalid / missing / (0, 0) coordinates are NOT plotted, but are not lost either -
15
+ * they land in a geometry-less `__UNKNOWN__` aggregate;
16
+ * - `orders` (all delivery orders) and `delivery_records` (attempts) are different
17
+ * populations, and a reassignment never inflates `app_orders`;
18
+ * - the cell cap and the 3-order suppression threshold are real.
19
+ */
20
+ const TENANT = 'tenant-geo';
21
+ const BRAND = 'brand-geo';
22
+ const DAY = '2026-09-14';
23
+ const ISTANBUL = { lat: 41.0082, lng: 28.9784 };
24
+ const ANKARA = { lat: 39.9334, lng: 32.8597 };
25
+ let seq = 0;
26
+ const order = (over = {}) => {
27
+ const { lat, lng, city, delivery_details, ...rest } = over;
28
+ const details = delivery_details === null
29
+ ? null
30
+ : {
31
+ city: city ?? 'Istanbul',
32
+ state: city ?? 'Istanbul',
33
+ delivery_cost: 300,
34
+ lat: lat === undefined ? ISTANBUL.lat : lat,
35
+ lng: lng === undefined ? ISTANBUL.lng : lng,
36
+ ...(delivery_details ?? {}),
37
+ };
38
+ return {
39
+ _id: 'o-' + (seq += 1),
40
+ tenant_id: TENANT,
41
+ platform: 'POS_DELIVERY',
42
+ localDate: DAY,
43
+ localHour: 12,
44
+ net_sale_amount: 5000,
45
+ amount_collected: 5000,
46
+ ...rest,
47
+ delivery_details: details,
48
+ };
49
+ };
50
+ const delivery = (orderId, over = {}) => ({
51
+ _id: 'd-' + (seq += 1),
52
+ tenant_id: TENANT,
53
+ order_id: orderId,
54
+ rider_id: 'rider-1',
55
+ status: 'COMPLETED',
56
+ createdAt: new Date(DAY + 'T10:00:00.000Z'),
57
+ updatedAt: new Date(DAY + 'T10:30:00.000Z'),
58
+ delivered_at: new Date(DAY + 'T10:28:00.000Z'),
59
+ distance_in_meters_from_store: 3000,
60
+ rider_earnings: { amount: 700, status: delivery_1.RIDER_EARNINGS_STATUS_ENUM.FINAL },
61
+ ...over,
62
+ });
63
+ const compile = (orders, deliveries = [], over = {}) => (0, materialized_tenant_delivery_geo_helpers_1.compileTenantDeliveryGeoCells)({
64
+ tenantId: TENANT,
65
+ brandId: BRAND,
66
+ localDate: DAY,
67
+ orders,
68
+ deliveries,
69
+ computedAt: new Date(DAY + 'T23:00:00.000Z'),
70
+ ...over,
71
+ });
72
+ const cellOf = (lat, lng) => (0, materialized_tenant_delivery_geo_helpers_1.deliveryGeoCellOf)(lat, lng);
73
+ describe('delivery geo cells', () => {
74
+ it('aggregates orders into H3 cells at resolution 8', () => {
75
+ const first = order();
76
+ const second = order();
77
+ const cells = compile([first, second], [
78
+ delivery(String(first._id), { rider_id: 'rider-1' }),
79
+ // The same order reassigned: two attempts, ONE app order.
80
+ delivery(String(first._id), { rider_id: 'rider-2' }),
81
+ delivery(String(second._id), { rider_id: 'rider-1', status: 'CANCELLED' }),
82
+ ]);
83
+ const cell = cells.find((entry) => entry.h3_cell === cellOf(ISTANBUL.lat, ISTANBUL.lng));
84
+ expect(cell).toBeDefined();
85
+ expect(cell.resolution).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_RESOLUTION);
86
+ expect(cell.orders).toBe(2);
87
+ expect(cell.app_orders).toBe(2);
88
+ expect(cell.delivery_records).toBe(3);
89
+ expect(cell.completed).toBe(2);
90
+ expect(cell.cancelled).toBe(1);
91
+ expect(cell.net_sale_amount).toBe(10000);
92
+ expect(cell.delivery_charge_amount).toBe(600);
93
+ // d1 + d3 are FINAL; d2 is FINAL too -> 3 x 700.
94
+ expect(cell.rider_revenue_amount).toBe(2100);
95
+ expect(cell.city).toBe('Istanbul');
96
+ expect(cell.scope_context).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
97
+ expect(cell.scope_field).toBe(DAY);
98
+ // the DERIVED centroid, in [lng, lat] order.
99
+ expect(cell.location.type).toBe('Point');
100
+ const [lng, lat] = cell.location.coordinates;
101
+ expect(Math.abs(lat - ISTANBUL.lat)).toBeLessThan(0.05);
102
+ expect(Math.abs(lng - ISTANBUL.lng)).toBeLessThan(0.05);
103
+ });
104
+ it('separates two cities into two cells and picks the dominant city', () => {
105
+ const cells = compile([
106
+ order({ lat: ISTANBUL.lat, lng: ISTANBUL.lng, delivery_details: { city: 'Istanbul' } }),
107
+ order({ lat: ANKARA.lat, lng: ANKARA.lng, delivery_details: { city: 'Ankara' } }),
108
+ ]);
109
+ expect(cells).toHaveLength(2);
110
+ expect(cells.map((cell) => cell.city).sort()).toEqual(['Ankara', 'Istanbul']);
111
+ });
112
+ it('never plots invalid or (0, 0) coordinates - they go to a geometry-less unknown', () => {
113
+ expect((0, materialized_tenant_delivery_geo_helpers_1.isValidDeliveryCoordinate)(0, 0)).toBe(false);
114
+ expect((0, materialized_tenant_delivery_geo_helpers_1.isValidDeliveryCoordinate)(Number.NaN, 28)).toBe(false);
115
+ expect((0, materialized_tenant_delivery_geo_helpers_1.isValidDeliveryCoordinate)(120, 10)).toBe(false);
116
+ expect((0, materialized_tenant_delivery_geo_helpers_1.isValidDeliveryCoordinate)(41, undefined)).toBe(false);
117
+ expect((0, materialized_tenant_delivery_geo_helpers_1.isValidDeliveryCoordinate)(41.0082, 28.9784)).toBe(true);
118
+ const cells = compile([
119
+ order({ lat: 0, lng: 0 }),
120
+ order({ lat: null, lng: null }),
121
+ order({ lat: 91, lng: 10 }),
122
+ order(),
123
+ ]);
124
+ const unknown = cells.find((cell) => cell.h3_cell === MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_UNKNOWN_CELL);
125
+ expect(unknown.orders).toBe(3);
126
+ expect(unknown.resolution).toBe(0);
127
+ expect(unknown.location).toBeUndefined();
128
+ // the city label is still known from the order; only the GEOMETRY is unknown.
129
+ expect(unknown.city).toBe('Istanbul');
130
+ expect(cells.filter((cell) => cell.location != null)).toHaveLength(1);
131
+ });
132
+ it('caps a scope at the requested cell count, busiest first', () => {
133
+ // Six separate places, each with a different order count.
134
+ const places = [
135
+ { lat: 41.01, lng: 28.97 },
136
+ { lat: 39.93, lng: 32.86 },
137
+ { lat: 40.18, lng: 29.06 },
138
+ { lat: 40.74, lng: 29.92 },
139
+ { lat: 41.04, lng: 29.0 },
140
+ { lat: 38.42, lng: 27.14 },
141
+ ];
142
+ const orders = places.flatMap((place, index) => Array.from({ length: 3 + index }, () => order({ lat: place.lat, lng: place.lng })));
143
+ const cells = compile(orders, [], { maxCells: 3 });
144
+ expect(cells).toHaveLength(3);
145
+ // busiest cell first: the last place has 8 orders, then 7, then 6.
146
+ expect(cells[0].orders).toBe(8);
147
+ expect(cells[1].orders).toBe(7);
148
+ expect(cells[2].orders).toBe(6);
149
+ // the cap helper is deterministic on ties (orders DESC, h3 ASC).
150
+ const tied = (0, materialized_tenant_delivery_geo_helpers_1.capDeliveryGeoCells)([
151
+ { ...cells[0], h3_cell: 'b', orders: 1 },
152
+ { ...cells[0], h3_cell: 'a', orders: 1 },
153
+ ], 2);
154
+ expect(tied.map((cell) => cell.h3_cell)).toEqual(['a', 'b']);
155
+ });
156
+ it('suppresses cells below the 3-order threshold and reports the hidden counts', () => {
157
+ const cells = compile([
158
+ order(),
159
+ order(),
160
+ order(),
161
+ // a lone order in a second cell must not be exposed.
162
+ order({ lat: ANKARA.lat, lng: ANKARA.lng, delivery_details: { city: 'Ankara' } }),
163
+ ]);
164
+ const response = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({
165
+ cells,
166
+ totalOrders: 4,
167
+ totalAppOrders: 0,
168
+ });
169
+ expect(response.cells).toHaveLength(1);
170
+ expect(response.cells[0].orders).toBe(3);
171
+ expect(response.suppressed_cell_count).toBe(1);
172
+ expect(response.suppressed_order_count).toBe(1);
173
+ expect(response.total_orders).toBe(4);
174
+ expect(response.total_app_orders).toBe(0);
175
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_MIN_ORDERS).toBe(3);
176
+ });
177
+ it('applies a viewport without changing the totals', () => {
178
+ const cells = compile([
179
+ order(),
180
+ order(),
181
+ order(),
182
+ order({ lat: ANKARA.lat, lng: ANKARA.lng, delivery_details: { city: 'Ankara' } }),
183
+ order({ lat: ANKARA.lat, lng: ANKARA.lng, delivery_details: { city: 'Ankara' } }),
184
+ order({ lat: ANKARA.lat, lng: ANKARA.lng, delivery_details: { city: 'Ankara' } }),
185
+ ]);
186
+ const istanbulCentroid = (0, materialized_tenant_delivery_geo_helpers_1.deliveryGeoCellCentroid)(cellOf(ISTANBUL.lat, ISTANBUL.lng));
187
+ const [lng, lat] = istanbulCentroid;
188
+ const viewport = {
189
+ north: lat + 0.5,
190
+ south: lat - 0.5,
191
+ east: lng + 0.5,
192
+ west: lng - 0.5,
193
+ };
194
+ const windowed = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({
195
+ cells,
196
+ totalOrders: 6,
197
+ totalAppOrders: 0,
198
+ viewport,
199
+ });
200
+ expect(windowed.cells).toHaveLength(1);
201
+ expect(windowed.cells[0].city).toBe('Istanbul');
202
+ expect(windowed.total_orders).toBe(6);
203
+ const all = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({ cells, totalOrders: 6, totalAppOrders: 0, viewport: null });
204
+ expect(all.cells).toHaveLength(2);
205
+ });
206
+ it('returns no raw coordinates - only the derived centroid and counts', () => {
207
+ const cell = compile([order(), order(), order()])[0];
208
+ const response = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({ cells: [cell], totalOrders: 3, totalAppOrders: 0 });
209
+ const payload = response.cells[0];
210
+ expect(payload.centroid).toEqual((0, materialized_tenant_delivery_geo_helpers_1.deliveryGeoCellCentroid)(cell.h3_cell));
211
+ expect(JSON.stringify(payload)).not.toContain('polyline');
212
+ expect(JSON.stringify(payload)).not.toContain('street');
213
+ for (const key of ['lat', 'lng', 'latitude', 'longitude']) {
214
+ expect(Object.keys(payload)).not.toContain(key);
215
+ }
216
+ });
217
+ it('enforces the named per-collection BSON budgets', () => {
218
+ const huge = { rows: Array.from({ length: 20 }, () => ({ blob: 'x'.repeat(200) })) };
219
+ expect(() => (0, materialized_document_size_1.assertMaterializedDocumentsSize)([huge], {
220
+ collection: 'materialized_tenant_delivery_entries',
221
+ maxBytes: 1024,
222
+ })).toThrow(/BSON size budget exceeded in materialized_tenant_delivery_entries\[0\]/);
223
+ // the DELIVERY budgets use the owner-approved 15 MiB / 2 MiB values
224
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_REPORT_MAX_BSON_BYTES).toBe(15 * 1024 * 1024);
225
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_ENTRY_MAX_BSON_BYTES).toBe(15 * 1024 * 1024);
226
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_CELL_MAX_BSON_BYTES).toBe(2 * 1024 * 1024);
227
+ // a budget is REQUIRED - no silent global default
228
+ expect(() => (0, materialized_document_size_1.assertMaterializedDocumentsSize)([huge], { collection: 'test' })).toThrow(/explicit maxBytes budget is required/);
229
+ });
230
+ });
231
+ describe('delivery geo read plan / cap / granularity', () => {
232
+ const geoCell = (h3Cell, orders, over = {}) => ({
233
+ tenant_id: TENANT,
234
+ brand_id: BRAND,
235
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
236
+ scope_field: DAY,
237
+ city: 'Istanbul',
238
+ h3_cell: h3Cell,
239
+ resolution: h3Cell === MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_UNKNOWN_CELL ? 0 : MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_RESOLUTION,
240
+ orders,
241
+ app_orders: orders,
242
+ delivery_records: orders,
243
+ completed: orders,
244
+ cancelled: 0,
245
+ net_sale_amount: orders * 100,
246
+ delivery_charge_amount: 0,
247
+ rider_revenue_amount: 0,
248
+ by_key: {
249
+ 'COMPLETED:POS_DELIVERY': {
250
+ orders,
251
+ app_orders: orders,
252
+ delivery_records: orders,
253
+ completed: orders,
254
+ cancelled: 0,
255
+ net_sale_amount: orders * 100,
256
+ delivery_charge_amount: 0,
257
+ rider_revenue_amount: 0,
258
+ },
259
+ },
260
+ schema_version: 1,
261
+ computed_at: new Date(DAY + 'T23:00:00.000Z'),
262
+ ...over,
263
+ });
264
+ it('resolves exact DAY cells while every selected day is retained', () => {
265
+ const plan = (0, materialized_delivery_entry_pages_1.resolveMaterializedDeliveryGeoRead)(['2026-09-14', '2026-09-15'], { now: '2026-10-27T12:00:00.000Z' });
266
+ expect(plan.granularity).toBe('DAY');
267
+ expect(plan.exact_days).toBe(true);
268
+ expect(plan.groups).toEqual([
269
+ { scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, scope_field: ['2026-09-14', '2026-09-15'] },
270
+ ]);
271
+ });
272
+ it('resolves MONTH cells (and says so) when any selected day is older than retention', () => {
273
+ const plan = (0, materialized_delivery_entry_pages_1.resolveMaterializedDeliveryGeoRead)(['2025-01-10', '2025-01-11'], { now: '2026-10-27T12:00:00.000Z' });
274
+ expect(plan.granularity).toBe('MONTH');
275
+ expect(plan.exact_days).toBe(false);
276
+ expect(plan.groups).toEqual([
277
+ { scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, scope_field: ['2025-01'] },
278
+ ]);
279
+ // A single old day must not silently read pruned DAY cells.
280
+ expect((0, materialized_delivery_entry_pages_1.resolveMaterializedDeliveryGeoRead)(['2025-01-10'], { now: '2026-10-27T12:00:00.000Z' }).granularity).toBe('MONTH');
281
+ });
282
+ it('caps the filtered historical union at 2,000 and reports the dropped counts', () => {
283
+ const cells = [];
284
+ const seen = new Set();
285
+ for (let i = 0; cells.length < 2001; i += 1) {
286
+ const h3 = (0, h3_js_1.latLngToCell)(38 + (i % 100) * 0.02, 28 + Math.floor(i / 100) * 0.02, 8);
287
+ if (seen.has(h3))
288
+ continue;
289
+ seen.add(h3);
290
+ cells.push(geoCell(h3, 4));
291
+ }
292
+ const response = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({
293
+ cells,
294
+ totalOrders: 8004,
295
+ totalAppOrders: 8004,
296
+ maxCells: 2000,
297
+ });
298
+ expect(response.cells).toHaveLength(2000);
299
+ expect(response.capped_cell_count).toBe(1);
300
+ expect(response.capped_order_count).toBe(4);
301
+ expect(response.capped_counts_exact).toBe(true);
302
+ expect(response.granularity).toBe('DAY');
303
+ expect(response.exact_days).toBe(true);
304
+ });
305
+ it('merges multi-tenant H3 collisions before capping', () => {
306
+ const h3 = (0, h3_js_1.latLngToCell)(41, 29, 8);
307
+ const merged = (0, materialized_tenant_delivery_geo_helpers_1.mergeDeliveryGeoCellsByH3)([geoCell(h3, 2), geoCell(h3, 3, { city: 'Ankara' })]);
308
+ expect(merged).toHaveLength(1);
309
+ expect(merged[0].orders).toBe(5);
310
+ expect(merged[0].city).toBeNull();
311
+ });
312
+ it('reports unknown-geometry orders instead of silently dropping them', () => {
313
+ const response = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({
314
+ cells: [geoCell(MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_UNKNOWN_CELL, 5, { resolution: 0 })],
315
+ totalOrders: 5,
316
+ totalAppOrders: 0,
317
+ });
318
+ expect(response.cells).toHaveLength(0);
319
+ expect(response.unknown_order_count).toBe(5);
320
+ });
321
+ });
322
+ /**
323
+ * The CITY dimension of a cell.
324
+ *
325
+ * A cell is an H3 index, so it can hold orders from more than one city - including
326
+ * orders whose city is missing entirely. The cell's `city` field is only a DISPLAY
327
+ * label (the dominant city); filtering must use the by_key map, which carries the city
328
+ * as part of its key, so the selected city's counters are summed out of the cell
329
+ * exactly. The totals, the plotted cells and the unknown count must reconcile: no
330
+ * selected order may vanish between the summary and the map.
331
+ */
332
+ describe('delivery geo city dimension', () => {
333
+ const cityLess = (over = {}) => order({
334
+ order_status: 'COMPLETED',
335
+ ...over,
336
+ delivery_details: { city: null, state: null, ...(over.delivery_details ?? {}) },
337
+ });
338
+ const istanbul = (over = {}) => order({
339
+ order_status: 'COMPLETED',
340
+ ...over,
341
+ delivery_details: { city: 'Istanbul', state: 'Istanbul', ...(over.delivery_details ?? {}) },
342
+ });
343
+ it('keys the by_key map by ORDER_STATUS:PLATFORM:CITY', () => {
344
+ const cells = compile([istanbul(), cityLess()]);
345
+ expect(cells).toHaveLength(1);
346
+ expect(Object.keys(cells[0].by_key ?? {}).sort()).toEqual([
347
+ 'COMPLETED:POS_DELIVERY:Istanbul',
348
+ 'COMPLETED:POS_DELIVERY:UNKNOWN',
349
+ ]);
350
+ });
351
+ it('filters a MIXED-CITY cell exactly - the selected city, not the dominant one', () => {
352
+ // Three city-less orders and three Istanbul orders share ONE H3 cell.
353
+ const orders = [...Array.from({ length: 3 }, () => cityLess()), ...Array.from({ length: 3 }, () => istanbul())];
354
+ const cells = compile(orders);
355
+ expect(cells).toHaveLength(1);
356
+ expect(cells[0].orders).toBe(6);
357
+ // The LABEL is the dominant city - but it is a label, never the filter.
358
+ expect(cells[0].city).toBe('Istanbul');
359
+ const unknown = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({
360
+ cells,
361
+ totalOrders: 3,
362
+ totalAppOrders: 0,
363
+ filters: { cities: ['UNKNOWN'] },
364
+ });
365
+ expect(unknown.cells).toHaveLength(1);
366
+ // ONLY the city-less orders - the Istanbul orders in the same cell are not counted.
367
+ expect(unknown.cells[0].orders).toBe(3);
368
+ // The label must not name a city that was filtered out.
369
+ expect(unknown.cells[0].city).toBeNull();
370
+ const named = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({
371
+ cells,
372
+ totalOrders: 3,
373
+ totalAppOrders: 0,
374
+ filters: { cities: ['Istanbul'] },
375
+ });
376
+ expect(named.cells).toHaveLength(1);
377
+ expect(named.cells[0].orders).toBe(3);
378
+ expect(named.cells[0].city).toBe('Istanbul');
379
+ });
380
+ it('reconciles the totals, the plotted cells and the unknown count', () => {
381
+ const orders = [...Array.from({ length: 3 }, () => cityLess()), ...Array.from({ length: 3 }, () => istanbul())];
382
+ const cells = compile(orders);
383
+ const response = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({
384
+ cells,
385
+ totalOrders: 3,
386
+ totalAppOrders: 0,
387
+ filters: { cities: ['UNKNOWN'] },
388
+ });
389
+ const plotted = response.cells.reduce((sum, cell) => sum + cell.orders, 0);
390
+ expect(plotted + response.unknown_order_count + response.suppressed_order_count).toBe(response.total_orders);
391
+ // The selected population is fully accounted for - nothing is silently dropped.
392
+ expect(response.cells).toHaveLength(1);
393
+ });
394
+ it('keeps a named city selectable inside the geometry-less aggregate', () => {
395
+ // An order with NO coordinates but a known city lands in the __UNKNOWN__ cell.
396
+ const cells = compile([istanbul({ lat: null, lng: null })]);
397
+ const unknownCell = cells.find((cell) => cell.h3_cell === MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_UNKNOWN_CELL);
398
+ expect(unknownCell).toBeDefined();
399
+ expect(unknownCell.orders).toBe(1);
400
+ const response = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({
401
+ cells,
402
+ totalOrders: 1,
403
+ totalAppOrders: 0,
404
+ filters: { cities: ['Istanbul'] },
405
+ });
406
+ // It cannot be plotted, but it must not be lost either.
407
+ expect(response.cells).toHaveLength(0);
408
+ expect(response.unknown_order_count).toBe(1);
409
+ });
410
+ it('combines a city filter with a platform filter on the same cell', () => {
411
+ const orders = [
412
+ ...Array.from({ length: 3 }, () => cityLess({ platform: 'POS_DELIVERY' })),
413
+ ...Array.from({ length: 3 }, () => cityLess({ platform: 'WEB_DELIVERY' })),
414
+ ];
415
+ const cells = compile(orders);
416
+ const response = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({
417
+ cells,
418
+ totalOrders: 3,
419
+ totalAppOrders: 0,
420
+ filters: { cities: ['UNKNOWN'], platforms: ['WEB_DELIVERY'] },
421
+ });
422
+ expect(response.cells).toHaveLength(1);
423
+ expect(response.cells[0].orders).toBe(3);
424
+ });
425
+ it('folds a TAIL city into __OTHER__ exactly like the report counters do', () => {
426
+ // More cities than the top-N area limit, so the last one is folded. The geo cells
427
+ // must use the SAME city dimension as the report counters, or the map and the
428
+ // summary would resolve a tail city differently.
429
+ const cities = Array.from({ length: 60 }, (_, index) => `City${String(index).padStart(2, '0')}`);
430
+ const orders = cities.map((city) => istanbul({ delivery_details: { city, state: city } }));
431
+ const cells = compile(orders);
432
+ const keys = cells.flatMap((cell) => Object.keys(cell.by_key ?? {}));
433
+ const folded = keys.filter((key) => key.endsWith(':__OTHER__'));
434
+ const named = keys.filter((key) => key.endsWith(':City00'));
435
+ expect(folded.length).toBeGreaterThan(0);
436
+ expect(named.length).toBeGreaterThan(0);
437
+ // The folded city is NOT addressable by its own name any more - in either mode.
438
+ const byTailName = (0, materialized_tenant_delivery_geo_helpers_1.buildDeliveryGeoResponse)({
439
+ cells,
440
+ totalOrders: 0,
441
+ totalAppOrders: 0,
442
+ filters: { cities: ['City59'] },
443
+ });
444
+ expect(byTailName.cells).toHaveLength(0);
445
+ });
446
+ });
@@ -21,6 +21,7 @@ const order = (over = {}) => ({
21
21
  _id: 'o-' + (seq += 1),
22
22
  tenant_id: TENANT,
23
23
  platform: 'POS_WALK-IN',
24
+ order_status: 'COMPLETED',
24
25
  order_number: 100,
25
26
  createdAt: new Date((over.localDate ?? DAY_ONE) + 'T10:00:00.000Z'),
26
27
  net_sale_amount: 5000,
@@ -100,7 +101,6 @@ describe('M4 close-day plan', () => {
100
101
  computedAt: new Date('2026-09-14T23:00:00.000Z'),
101
102
  });
102
103
  const storedReports = first.writes.map((w) => w.report);
103
- const storedEntries = first.entryWrites.map((w) => w.report);
104
104
  const monthBefore = storedReports.find((r) => String(r.scope_context) === 'localMonth');
105
105
  const dayTwo = linkedDayTwo('2026-09-15T23:00:00.000Z');
106
106
  const second = (0, materialized_delivery_close_day_helpers_1.buildTenantDeliveryCloseDayPlan)({
@@ -108,7 +108,9 @@ describe('M4 close-day plan', () => {
108
108
  reports: dayTwo.reports,
109
109
  entries: dayTwo.entries,
110
110
  existing: storedReports,
111
- existingEntries: storedEntries,
111
+ // The caller fetches ONLY the closing day's pages; day one's pages are not in
112
+ // scope for day two and must never be passed here.
113
+ existingEntries: [],
112
114
  reason: 'NEW_DAY',
113
115
  computedAt: new Date('2026-09-15T23:00:00.000Z'),
114
116
  });
@@ -116,8 +118,9 @@ describe('M4 close-day plan', () => {
116
118
  // If the fold had inherited the stored watermark this would be undefined.
117
119
  expect(monthAfter).toBeDefined();
118
120
  expect(monthAfter.report.source_watermark.getTime()).toBeGreaterThan(new Date(monthBefore.source_watermark).getTime());
119
- const key = 'POS_WALK-IN:Istanbul';
121
+ const key = 'COMPLETED:POS_WALK-IN:Istanbul';
120
122
  expect(monthAfter.report.delivery_counters[key].deliveries.count).toBe(2);
123
+ expect(monthAfter.report.schema_version).toBe(2);
121
124
  });
122
125
  it('EMPTYING a day removes it and its contribution from every period', () => {
123
126
  const dayOne = linkedDay('2026-09-14T23:00:00.000Z');
@@ -144,8 +147,12 @@ describe('M4 close-day plan', () => {
144
147
  const staleScopes = plan.staleDocuments.map((d) => String(d.scope_context));
145
148
  expect(staleScopes).toContain('localMonth');
146
149
  expect(staleScopes).toContain('localWeek');
150
+ // Every ENTRY PAGE of the emptied day is deleted; no other page is in scope.
151
+ expect(plan.staleEntryDocuments).toHaveLength(4);
152
+ expect(new Set(plan.staleEntryDocuments.map((d) => String(d.scope_context)))).toEqual(new Set(['localDate', 'localWeek', 'localWeekOfYear', 'localMonth']));
153
+ expect(plan.entryWrites).toHaveLength(0);
147
154
  });
148
- it('SUMS off-app orders into the period, since they are not rows', () => {
155
+ it('carries the day off-app count on EVERY page, without folding rows', () => {
149
156
  const dayOne = compileDay(DAY_ONE, [order(), order()], [], '2026-09-14T23:00:00.000Z');
150
157
  const first = (0, materialized_delivery_close_day_helpers_1.buildTenantDeliveryCloseDayPlan)({
151
158
  tenantId: TENANT,
@@ -156,12 +163,36 @@ describe('M4 close-day plan', () => {
156
163
  reason: 'NEW_DAY',
157
164
  computedAt: new Date('2026-09-14T23:00:00.000Z'),
158
165
  });
159
- const month = first.entryWrites.find((w) => String(w.report.scope_context) === 'localMonth');
160
- expect(month.report.off_app_order_count).toBe(2);
161
- // ...and with no deliveries at all there are no row sections, only the count.
162
- expect(month.report.delivery_entries).toBeNull();
166
+ // One page per entry scope, all owned by the same source day.
167
+ expect(first.entryWrites).toHaveLength(4);
168
+ for (const write of first.entryWrites) {
169
+ expect(write.report.page).toBe(String(write.report.scope_context) === 'localDate' ? 'all' : DAY_ONE);
170
+ expect(write.report.off_app_order_count).toBe(2);
171
+ // no rows: the day has only off-app orders.
172
+ expect(write.report.delivery_entries).toBeNull();
173
+ }
174
+ });
175
+ it('writes ONE page per entry scope for the closing day and never a quarter/year document', () => {
176
+ const dayOne = linkedDay('2026-09-14T23:00:00.000Z');
177
+ const first = (0, materialized_delivery_close_day_helpers_1.buildTenantDeliveryCloseDayPlan)({
178
+ tenantId: TENANT,
179
+ reports: dayOne.reports,
180
+ entries: dayOne.entries,
181
+ existing: [],
182
+ existingEntries: [],
183
+ reason: 'NEW_DAY',
184
+ computedAt: new Date('2026-09-14T23:00:00.000Z'),
185
+ });
186
+ const scopes = first.entryWrites.map((w) => String(w.report.scope_context)).sort();
187
+ expect(scopes).toEqual(['localDate', 'localMonth', 'localWeek', 'localWeekOfYear']);
188
+ for (const write of first.entryWrites) {
189
+ expect(['localQuarter', 'localSemester', 'localYear']).not.toContain(String(write.report.scope_context));
190
+ }
191
+ const monthPage = first.entryWrites.find((w) => String(w.report.scope_context) === 'localMonth');
192
+ expect(monthPage.report.page).toBe(DAY_ONE);
193
+ expect(Object.values(monthPage.report.delivery_entries).flatMap((section) => section.rows)).toHaveLength(1);
163
194
  });
164
- it('deduplicates statement rows across the fold', () => {
195
+ it('a reclose replaces ONLY the closing day pages it fetched', () => {
165
196
  const dayOne = linkedDay('2026-09-14T23:00:00.000Z');
166
197
  const first = (0, materialized_delivery_close_day_helpers_1.buildTenantDeliveryCloseDayPlan)({
167
198
  tenantId: TENANT,
@@ -172,23 +203,39 @@ describe('M4 close-day plan', () => {
172
203
  reason: 'NEW_DAY',
173
204
  computedAt: new Date('2026-09-14T23:00:00.000Z'),
174
205
  });
175
- const month = first.entryWrites.find((w) => String(w.report.scope_context) === 'localMonth');
176
- const rows = Object.values(month.report.delivery_entries).flatMap((s) => s.rows);
177
- expect(rows).toHaveLength(1);
178
- // Folding the SAME day document twice must not duplicate the row.
179
- const again = (0, materialized_delivery_close_day_helpers_1.foldMaterializedDeliveryPeriodRows)({
180
- periodScope: 'localMonth',
181
- periodScopeField: '2026-09',
182
- // the ENTRIES document, not the counters document.
183
- dayDocuments: [
184
- first.entryWrites.find((w) => String(w.report.scope_context) === 'localDate').report,
185
- first.entryWrites.find((w) => String(w.report.scope_context) === 'localDate').report,
186
- ],
206
+ const dayOnePages = first.entryWrites.map((w) => w.report);
207
+ // Re-close the SAME day: the fetched pages are its own, and every page is replaced.
208
+ const reclose = (0, materialized_delivery_close_day_helpers_1.buildTenantDeliveryCloseDayPlan)({
209
+ tenantId: TENANT,
210
+ reports: dayOne.reports,
211
+ entries: dayOne.entries,
212
+ existing: first.writes.map((w) => w.report),
213
+ existingEntries: dayOnePages,
214
+ reason: 'RECLOSE',
215
+ force: true,
216
+ computedAt: new Date('2026-09-14T23:30:00.000Z'),
217
+ });
218
+ expect(reclose.entryWrites).toHaveLength(4);
219
+ expect(reclose.staleEntryDocuments).toHaveLength(0);
220
+ // the `_id` is REUSED, so the page identity survives the reclose.
221
+ for (const write of reclose.entryWrites) {
222
+ const previous = dayOnePages.find((page) => page.scope_context === write.report.scope_context && page.scope_field === write.report.scope_field);
223
+ expect(write.report._id).toBe(previous._id);
224
+ expect(write.report.iteration).toBe(Number(previous.iteration) + 1);
225
+ }
226
+ // Closing the NEXT day does not include day one's pages, so they are untouched.
227
+ const dayTwo = linkedDayTwo('2026-09-15T23:00:00.000Z');
228
+ const next = (0, materialized_delivery_close_day_helpers_1.buildTenantDeliveryCloseDayPlan)({
229
+ tenantId: TENANT,
230
+ reports: dayTwo.reports,
231
+ entries: dayTwo.entries,
232
+ existing: first.writes.map((w) => w.report),
233
+ existingEntries: [],
234
+ reason: 'NEW_DAY',
235
+ computedAt: new Date('2026-09-15T23:00:00.000Z'),
187
236
  });
188
- expect(Object.values(again.sections).flatMap((s) => s.rows)).toHaveLength(1);
189
- // and the off-app count would double - which is WHY it is summed from distinct
190
- // documents by the caller, not from a repeated day.
191
- expect(again.offApp).toBe(0);
237
+ expect(next.staleEntryDocuments).toHaveLength(0);
238
+ expect(next.entryWrites.every((w) => String(w.report.scope_context) === 'localDate' ? w.report.page === 'all' : w.report.page === DAY_TWO)).toBe(true);
192
239
  });
193
240
  it('returns null on malformed input', () => {
194
241
  expect((0, materialized_delivery_close_day_helpers_1.buildTenantDeliveryCloseDayPlan)(null)).toBeNull();
@@ -197,3 +244,48 @@ describe('M4 close-day plan', () => {
197
244
  expect((0, materialized_delivery_close_day_helpers_1.buildTenantDeliveryCloseDayPlan)({ tenantId: TENANT, reports: [], entries: [], reason: 'x' })).toBeNull();
198
245
  });
199
246
  });
247
+ describe('entry page identity', () => {
248
+ it('rejects duplicate page identity instead of writing twice', () => {
249
+ const compiled = linkedDay('2026-09-14T23:00:00.000Z');
250
+ const plan = (0, materialized_delivery_close_day_helpers_1.buildTenantDeliveryCloseDayPlan)({
251
+ tenantId: TENANT,
252
+ reports: compiled.reports,
253
+ entries: [...compiled.entries, { ...compiled.entries[0], _id: undefined }],
254
+ localDate: DAY_ONE,
255
+ existing: [],
256
+ existingEntries: [],
257
+ reason: 'RECLOSE',
258
+ computedAt: new Date('2026-09-14T23:00:00.000Z'),
259
+ });
260
+ expect(plan).toBeNull();
261
+ });
262
+ });
263
+ describe('entry source-day sub-pages', () => {
264
+ it('accepts deterministic source-day sub-pages as one logical day', () => {
265
+ const compiled = linkedDay('2026-09-14T23:00:00.000Z');
266
+ const dayPage = compiled.entries.find((entry) => entry.scope_context === 'localDate');
267
+ const sections = Object.entries(dayPage.delivery_entries ?? {});
268
+ const firstRows = sections.map(([key, value]) => ({
269
+ key,
270
+ rows: value.rows.slice(0, 1),
271
+ }));
272
+ const first = {
273
+ ...dayPage,
274
+ page: 'all#0',
275
+ delivery_entries: Object.fromEntries(firstRows.map(({ key, rows }) => [key, { rows }])),
276
+ };
277
+ const second = { ...dayPage, page: 'all#1', delivery_entries: {} };
278
+ const entries = [...compiled.entries.filter((entry) => entry.scope_context !== 'localDate'), first, second];
279
+ const plan = (0, materialized_delivery_close_day_helpers_1.buildTenantDeliveryCloseDayPlan)({
280
+ tenantId: TENANT,
281
+ reports: compiled.reports,
282
+ entries,
283
+ localDate: DAY_ONE,
284
+ existing: [],
285
+ existingEntries: [],
286
+ reason: 'RECLOSE',
287
+ computedAt: new Date('2026-09-14T23:00:00.000Z'),
288
+ });
289
+ expect(plan.entryWrites.filter((write) => write.report.scope_context === 'localDate')).toHaveLength(2);
290
+ });
291
+ });