@managesome/eposmatic-toolkit 0.4.51 → 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 (97) 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/helpers/utils/offer-item-resolution.js +39 -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/index.js +14 -12
  26. package/esm/schemas/types/materialized_tenant_delivery_geo_cells.js +1 -0
  27. package/esm/schemas/types/materialized_tenant_delivery_geo_scopes.js +1 -0
  28. package/lib/constants/MATERIALIZED_REPORTS.d.ts +95 -1
  29. package/lib/constants/MATERIALIZED_REPORTS.js +108 -4
  30. package/lib/constants/enums/delivery.d.ts +9 -0
  31. package/lib/constants/enums/delivery.js +14 -1
  32. package/lib/helpers/materialized-reports/index.d.ts +5 -0
  33. package/lib/helpers/materialized-reports/index.js +5 -0
  34. package/lib/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +8 -62
  35. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.d.ts +36 -9
  36. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.js +94 -72
  37. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.d.ts +23 -26
  38. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +121 -150
  39. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.d.ts +44 -5
  40. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +306 -69
  41. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.d.ts +128 -0
  42. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.js +322 -0
  43. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.d.ts +48 -0
  44. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.js +108 -0
  45. package/lib/helpers/materialized-reports/materialized-delivery-rows.d.ts +15 -0
  46. package/lib/helpers/materialized-reports/materialized-delivery-rows.js +115 -0
  47. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.d.ts +17 -0
  48. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.js +35 -0
  49. package/lib/helpers/materialized-reports/materialized-document-size.d.ts +47 -0
  50. package/lib/helpers/materialized-reports/materialized-document-size.js +73 -0
  51. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +28 -13
  52. package/lib/helpers/materialized-reports/materialized-integer-contract.js +10 -1
  53. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +2 -90
  54. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.d.ts +186 -0
  55. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.js +620 -0
  56. package/lib/helpers/materialized-reports/scope-helpers.d.ts +8 -0
  57. package/lib/helpers/materialized-reports/scope-helpers.js +99 -0
  58. package/lib/helpers/materialized-reports/tenant-delivery-formatter.d.ts +41 -0
  59. package/lib/helpers/materialized-reports/tenant-delivery-formatter.js +70 -20
  60. package/lib/helpers/utils/offer-item-resolution.d.ts +28 -0
  61. package/lib/helpers/utils/offer-item-resolution.js +41 -0
  62. package/lib/schemas/models/index.d.ts +12 -10
  63. package/lib/schemas/models/index.js +12 -10
  64. package/lib/schemas/models/materialized_tenant_delivery_entries.d.ts +31 -9
  65. package/lib/schemas/models/materialized_tenant_delivery_entries.js +32 -11
  66. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.d.ts +129 -0
  67. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.js +86 -0
  68. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.d.ts +71 -0
  69. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.js +38 -0
  70. package/lib/schemas/models/materialized_tenant_delivery_reports.d.ts +10 -1
  71. package/lib/schemas/models/materialized_tenant_delivery_reports.js +10 -1
  72. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +15 -15
  73. package/lib/schemas/types/index.d.ts +14 -12
  74. package/lib/schemas/types/index.js +14 -12
  75. package/lib/schemas/types/materialized_tenant_delivery_entries.d.ts +36 -4
  76. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.d.ts +178 -0
  77. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.js +2 -0
  78. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.d.ts +21 -0
  79. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.js +2 -0
  80. package/lib/schemas/types/materialized_tenant_delivery_reports.d.ts +49 -7
  81. package/lib/tests/materialized-reports/materialized-delivery-accumulation.test.js +56 -19
  82. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.d.ts +1 -0
  83. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.js +91 -0
  84. package/lib/tests/materialized-reports/materialized-delivery-compile.test.js +271 -15
  85. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.d.ts +1 -0
  86. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.js +128 -0
  87. package/lib/tests/materialized-reports/materialized-delivery-fold.test.js +42 -5
  88. package/lib/tests/materialized-reports/materialized-delivery-formatter.test.js +13 -1
  89. package/lib/tests/materialized-reports/materialized-delivery-geo.test.d.ts +1 -0
  90. package/lib/tests/materialized-reports/materialized-delivery-geo.test.js +446 -0
  91. package/lib/tests/materialized-reports/materialized-delivery-plan.test.js +117 -25
  92. package/lib/tests/materialized-reports/materialized-delivery-practical.test.d.ts +1 -0
  93. package/lib/tests/materialized-reports/materialized-delivery-practical.test.js +344 -0
  94. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +14 -0
  95. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +1 -1
  96. package/lib/tests/offer-item-resolution.test.js +57 -0
  97. package/package.json +4 -2
@@ -1,13 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deliveryAreaOfOrder = deliveryAreaOfOrder;
3
4
  exports.deliveryKeyOfOrder = deliveryKeyOfOrder;
5
+ exports.buildDeliveryCityResolver = buildDeliveryCityResolver;
6
+ exports.pruneDocumentDeliveryRiders = pruneDocumentDeliveryRiders;
7
+ exports.pruneDocumentDeliveryAreas = pruneDocumentDeliveryAreas;
4
8
  exports.compileTenantDeliveryReports = compileTenantDeliveryReports;
5
9
  const ENUMS_1 = require("../../constants/ENUMS");
6
10
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
7
11
  const delivery_1 = require("../../constants/enums/delivery");
8
12
  const materialized_tenant_delivery_entries_1 = require("../../schemas/models/materialized_tenant_delivery_entries");
9
13
  const materialized_tenant_delivery_reports_1 = require("../../schemas/models/materialized_tenant_delivery_reports");
14
+ const materialized_delivery_accumulator_helpers_1 = require("./materialized-delivery-accumulator-helpers");
10
15
  const materialized_delivery_classification_helpers_1 = require("./materialized-delivery-classification-helpers");
16
+ const materialized_delivery_entry_pages_1 = require("./materialized-delivery-entry-pages");
17
+ const materialized_delivery_rows_1 = require("./materialized-delivery-rows");
18
+ const materialized_document_size_1 = require("./materialized-document-size");
19
+ const scope_helpers_1 = require("./scope-helpers");
11
20
  const watermarkOf = (row, fallback) => {
12
21
  const raw = row?.updatedAt ?? row?.createdAt;
13
22
  const time = raw == null ? NaN : new Date(raw).getTime();
@@ -20,31 +29,189 @@ const minutesBetween = (from, to) => {
20
29
  return null;
21
30
  return Math.round((b - a) / 60000);
22
31
  };
23
- const hourLabelOf = (row) => {
24
- const hour = row?.localHour;
25
- if (typeof hour === 'number' && Number.isFinite(hour)) {
26
- const day = String(row?.localDate ?? '');
27
- if (day === '')
28
- return null;
29
- return day + ' ' + String(hour).padStart(2, '0');
30
- }
31
- const raw = row?.createdAt;
32
- if (raw == null)
32
+ /**
33
+ * `YYYY-MM-DD HH:MM` (minute known) or `YYYY-MM-DD HH` (hour only) of the JOINED
34
+ * ORDER's tenant-local time.
35
+ *
36
+ * This is the ONLY local-time source of the report. The delivery write path carries no
37
+ * `localHour`/`localMinute`, and deriving one from the delivery's `createdAt` on the
38
+ * server would report UTC as if it were tenant-local. Minutes are preserved because
39
+ * half-hour tenant offsets (e.g. +05:30) cannot be reconstructed from an hour alone.
40
+ *
41
+ * When `localMinute` is absent, the label stays HOUR-ONLY. This is deliberate: emitting
42
+ * a synthetic `:00` would make the UI derive an offset from a minute that does not exist
43
+ * (e.g. 23:00 - 20:50 = 2h10m instead of the tenant's whole-hour offset). The UI's
44
+ * hour-only branch derives the offset from the whole hour and is correct for that row.
45
+ * A missing local hour leaves the field null - unmeasured, never hour 0.
46
+ */
47
+ const orderHourLabel = (order) => {
48
+ if (order == null)
33
49
  return null;
34
- const date = new Date(raw);
35
- if (Number.isNaN(date.getTime()))
50
+ const hour = Number(order.localHour);
51
+ const day = String(order.localDate ?? '');
52
+ if (!Number.isFinite(hour) || day === '')
53
+ return null;
54
+ const whole = Math.floor(hour);
55
+ if (whole < 0 || whole > 23)
36
56
  return null;
37
- return date.toISOString().slice(0, 13).replace('T', ' ');
57
+ const hourLabel = String(whole).padStart(2, '0');
58
+ if (order.localMinute == null)
59
+ return day + ' ' + hourLabel;
60
+ const minuteRaw = Number(order.localMinute);
61
+ if (!Number.isFinite(minuteRaw) || minuteRaw < 0 || minuteRaw > 59) {
62
+ return day + ' ' + hourLabel;
63
+ }
64
+ return day + ' ' + hourLabel + ':' + String(Math.floor(minuteRaw)).padStart(2, '0');
38
65
  };
39
- /** The key of an ORDER - platform and city, both from the order itself. */
66
+ /** The normalized AREA of an order - the city component of its key (`city`, then `state`). */
67
+ function deliveryAreaOfOrder(order) {
68
+ const value = order?.delivery_details?.city ?? order?.delivery_details?.state ?? null;
69
+ return value == null ? null : String(value);
70
+ }
71
+ /** The key of an ORDER - status, platform and city, all from the order itself. */
40
72
  function deliveryKeyOfOrder(order) {
41
- return (0, materialized_delivery_classification_helpers_1.buildMaterializedDeliveryKey)(order?.platform, order?.delivery_details?.city ?? order?.delivery_details?.state ?? null);
73
+ return (0, materialized_delivery_classification_helpers_1.buildMaterializedDeliveryKey)(order?.order_status, order?.platform, deliveryAreaOfOrder(order));
74
+ }
75
+ /**
76
+ * Builds the resolver that bounds the CITY dimension to top-N + `__OTHER__`.
77
+ *
78
+ * The CITY is part of the key grammar (`ORDER_STATUS:PLATFORM:CITY`), so an unbounded city set is an
79
+ * unbounded DOCUMENT, not merely a long leaderboard. The top-N cities (by delivery
80
+ * orders, `count DESC, city ASC`) keep their own keys; every other city is resolved to
81
+ * the reserved `__OTHER__` component, which merges them per platform. The area rows and
82
+ * the by-area read then see a bounded `__OTHER__` area, and the totals still reconcile
83
+ * because the merge happens before the adoption sets are finalized.
84
+ */
85
+ function buildDeliveryCityResolver(orders, limit = MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_AREA_LIMIT) {
86
+ const counts = new Map();
87
+ for (const order of orders ?? []) {
88
+ const area = deliveryAreaOfOrder(order);
89
+ if (area == null)
90
+ continue;
91
+ counts.set(area, (counts.get(area) ?? 0) + 1);
92
+ }
93
+ const ranked = [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
94
+ const kept = new Set(ranked.slice(0, Math.max(0, limit)).map(([area]) => area));
95
+ return (area) => {
96
+ if (area == null)
97
+ return null;
98
+ return kept.has(area) ? area : MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_OTHER_TOKEN;
99
+ };
100
+ }
101
+ /**
102
+ * Bounds the RIDER leaderboard at the DOCUMENT level: top-N riders by record count
103
+ * (`count DESC, rider id ASC`), and every other rider's rows - in WHICHEVER key they
104
+ * appear - are folded into that key's `__OTHER__` row.
105
+ *
106
+ * Pruning per key would bound each key but not the document; a rider working several
107
+ * cities would be kept several times. This runs after the accumulators are finalized and
108
+ * before the counter rows are assembled, so the stored document is genuinely top-N.
109
+ */
110
+ function pruneDocumentDeliveryRiders(countersByKey, limit = MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_RIDER_LIMIT) {
111
+ const countersValues = countersByKey instanceof Map ? [...countersByKey.values()] : Object.values(countersByKey ?? {});
112
+ const totals = new Map();
113
+ for (const counters of countersValues) {
114
+ for (const [riderId, row] of Object.entries(counters.riders ?? {})) {
115
+ totals.set(riderId, (totals.get(riderId) ?? 0) + (Number(row?.count) || 0));
116
+ }
117
+ }
118
+ if (totals.size <= limit)
119
+ return;
120
+ const ranked = [...totals.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
121
+ const kept = new Set(ranked.slice(0, Math.max(0, limit)).map(([riderId]) => riderId));
122
+ for (const counters of countersValues) {
123
+ const riders = counters.riders;
124
+ if (riders == null)
125
+ continue;
126
+ const dropped = Object.entries(riders).filter(([riderId]) => !kept.has(riderId));
127
+ if (dropped.length === 0)
128
+ continue;
129
+ const other = riders[MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_OTHER_TOKEN] ?? (0, materialized_delivery_rows_1.emptyMaterializedDeliveryRiderRow)();
130
+ for (const [riderId, row] of dropped) {
131
+ (0, materialized_delivery_rows_1.mergeMaterializedDeliveryRiderRow)(other, row);
132
+ delete riders[riderId];
133
+ }
134
+ // Deterministic display label: the overflow row must not inherit the first
135
+ // merged rider's name (day-doc order differs between live fold and close fold).
136
+ other.rider_name = 'Other riders';
137
+ riders[MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_OTHER_TOKEN] = other;
138
+ counters.riders = riders;
139
+ }
42
140
  }
43
141
  /**
44
- * Compiles one business day into the DATE report document plus the DATE entries document.
142
+ * Bounds the CITY dimension of a FOLDED period document.
143
+ *
144
+ * Each DAY document already resolves cities to top-N + `__OTHER__`, but a month has
145
+ * 28-31 such resolvers: the union can exceed the top-N even though every day is bounded.
146
+ * Re-rank the folded city totals and merge every dropped city's key into the matching
147
+ * `ORDER_STATUS:PLATFORM:__OTHER__` key. The area rows are remapped with the key, so the
148
+ * by-area read and the totals stay consistent.
149
+ */
150
+ function pruneDocumentDeliveryAreas(countersByKey, limit = MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_AREA_LIMIT) {
151
+ if (countersByKey == null)
152
+ return {};
153
+ const cityOrders = new Map();
154
+ for (const counters of Object.values(countersByKey)) {
155
+ for (const [city, row] of Object.entries(counters.areas ?? {})) {
156
+ cityOrders.set(city, (cityOrders.get(city) ?? 0) + (Number(row?.delivery_orders) || 0));
157
+ }
158
+ }
159
+ if (cityOrders.size <= limit)
160
+ return countersByKey;
161
+ const ranked = [...cityOrders.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
162
+ const kept = new Set(ranked.slice(0, Math.max(1, limit)).map(([city]) => city));
163
+ // The overflow bucket and the explicit unknown area must always exist.
164
+ kept.add(MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_OTHER_TOKEN);
165
+ kept.add(materialized_delivery_classification_helpers_1.DELIVERY_UNKNOWN_TOKEN);
166
+ const result = {};
167
+ const targetKeyOf = (city, key) => {
168
+ if (kept.has(city))
169
+ return key;
170
+ const parsed = (0, materialized_delivery_classification_helpers_1.parseMaterializedDeliveryKey)(key);
171
+ if (parsed == null)
172
+ return key;
173
+ return (parsed.order_status +
174
+ materialized_delivery_classification_helpers_1.MATERIALIZED_DELIVERY_KEY_SEPARATOR +
175
+ parsed.platform +
176
+ materialized_delivery_classification_helpers_1.MATERIALIZED_DELIVERY_KEY_SEPARATOR +
177
+ MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_OTHER_TOKEN);
178
+ };
179
+ for (const [key, counters] of Object.entries(countersByKey)) {
180
+ const parsed = (0, materialized_delivery_classification_helpers_1.parseMaterializedDeliveryKey)(key);
181
+ const city = parsed?.city ?? materialized_delivery_classification_helpers_1.DELIVERY_UNKNOWN_TOKEN;
182
+ const targetKey = targetKeyOf(city, key);
183
+ if (result[targetKey] == null)
184
+ result[targetKey] = (0, materialized_delivery_classification_helpers_1.freshDeliveryCounters)();
185
+ if (targetKey === key) {
186
+ (0, materialized_delivery_accumulator_helpers_1.mergeMaterializedDeliveryCounters)(result[targetKey], counters);
187
+ continue;
188
+ }
189
+ // A dropped city's AREA row must also move to __OTHER__, or by_area would still
190
+ // expose the dropped city through the key that was supposed to be gone.
191
+ const remapped = {
192
+ ...counters,
193
+ areas: {},
194
+ };
195
+ const otherArea = (0, materialized_delivery_rows_1.emptyMaterializedDeliveryAreaRow)();
196
+ for (const row of Object.values(counters.areas ?? {})) {
197
+ (0, materialized_delivery_rows_1.mergeMaterializedDeliveryAreaRow)(otherArea, row);
198
+ }
199
+ remapped.areas = { [MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_OTHER_TOKEN]: otherArea };
200
+ (0, materialized_delivery_accumulator_helpers_1.mergeMaterializedDeliveryCounters)(result[targetKey], remapped);
201
+ }
202
+ return result;
203
+ }
204
+ /**
205
+ * Compiles one business day into:
206
+ *
207
+ * - the `localDate` COUNTER report document (the close-day plan re-folds the period
208
+ * counters from the sibling day documents);
209
+ * - ONE ENTRY PAGE per entry scope (date/ week / ISO week / month). The day page uses
210
+ * `page='all'`; each period page is partitioned by the source date, so a document is
211
+ * bounded by ONE day's rows. There is no quarter/semester/year entry document.
45
212
  *
46
213
  * Returns null when the day has NEITHER a delivery order NOR a delivery - an emptied day
47
- * writes nothing, and the close-day planner deletes what is left over.
214
+ * writes nothing, and the close-day planner deletes the pages it used to own.
48
215
  */
49
216
  function compileTenantDeliveryReports(input) {
50
217
  if (input == null)
@@ -59,13 +226,33 @@ function compileTenantDeliveryReports(input) {
59
226
  return null;
60
227
  }
61
228
  const computedAt = input.computedAt ?? new Date();
62
- const orders = (Array.isArray(input.orders) ? input.orders : []).filter((row) => String(row?.tenant_id ?? tenantId) === tenantId && (0, materialized_delivery_classification_helpers_1.isDeliveryOrder)(row));
63
- const deliveries = (Array.isArray(input.deliveries) ? input.deliveries : []).filter((row) => String(row?.tenant_id ?? tenantId) === tenantId);
64
- if (orders.length === 0 && deliveries.length === 0)
65
- return null;
229
+ const orders = (Array.isArray(input.orders) ? input.orders : []).filter((row) => String(row?.tenant_id ?? tenantId) === tenantId &&
230
+ (0, materialized_delivery_classification_helpers_1.isDeliveryOrder)(row) &&
231
+ String(row?.localDate ?? localDate) === localDate);
66
232
  const ordersById = new Map();
67
233
  for (const order of orders)
68
234
  ordersById.set(String(order._id), order);
235
+ /**
236
+ * SOURCE DAY: the JOINED ORDER's localDate. A delivery whose order is staged for
237
+ * this day is always included, even if the delivery document itself was created
238
+ * after midnight. A delivery with no staged order is included only when its own
239
+ * `localDate` is this day; that is the explicit unattributable fallback.
240
+ */
241
+ const deliveries = (Array.isArray(input.deliveries) ? input.deliveries : []).filter((row) => {
242
+ if (String(row?.tenant_id ?? tenantId) !== tenantId)
243
+ return false;
244
+ const orderId = row?.order_id == null ? '' : String(row.order_id);
245
+ const order = orderId === '' ? null : ordersById.get(orderId);
246
+ if (order != null)
247
+ return String(order.localDate ?? localDate) === localDate;
248
+ return String(row?.localDate ?? '') === localDate;
249
+ });
250
+ if (orders.length === 0 && deliveries.length === 0)
251
+ return null;
252
+ // Bound the CITY dimension (it is part of the key grammar) BEFORE accumulating, so
253
+ // both stages and the area rows agree on the top-N + `__OTHER__` resolution.
254
+ const resolveArea = buildDeliveryCityResolver(orders);
255
+ const keyOfOrder = (order) => (0, materialized_delivery_classification_helpers_1.buildMaterializedDeliveryKey)(order?.order_status, order?.platform, resolveArea(deliveryAreaOfOrder(order)));
69
256
  const accumulators = new Map();
70
257
  const accumulatorFor = (key) => {
71
258
  const existing = accumulators.get(key);
@@ -79,7 +266,10 @@ function compileTenantDeliveryReports(input) {
79
266
  // The ORDERS stage first: adoption is a property of the order population, and a
80
267
  // delivery that arrives for an unseen order must not invent one.
81
268
  for (const order of orders) {
82
- (0, materialized_delivery_classification_helpers_1.addDeliveryOrder)(accumulatorFor(deliveryKeyOfOrder(order)), order);
269
+ // The RESOLVED key is passed explicitly: recomputing it inside addDeliveryOrder
270
+ // would use the raw city and put the area row under a city the key folded away.
271
+ const key = keyOfOrder(order);
272
+ (0, materialized_delivery_classification_helpers_1.addDeliveryOrder)(accumulatorFor(key), order, key);
83
273
  watermarks.push(watermarkOf(order, computedAt));
84
274
  }
85
275
  const rowsByKey = new Map();
@@ -88,21 +278,28 @@ function compileTenantDeliveryReports(input) {
88
278
  const order = orderId == null ? null : (ordersById.get(orderId) ?? null);
89
279
  // A delivery whose order was NOT staged keys on its own (absent) dimensions, so it
90
280
  // lands in UNKNOWN rather than being dropped or attributed to a neighbouring city.
91
- const key = order == null ? (0, materialized_delivery_classification_helpers_1.buildMaterializedDeliveryKey)(null, null) : deliveryKeyOfOrder(order);
281
+ const key = order == null ? (0, materialized_delivery_classification_helpers_1.buildMaterializedDeliveryKey)(null, null, null) : keyOfOrder(order);
92
282
  (0, materialized_delivery_classification_helpers_1.addDelivery)(accumulatorFor(key), delivery, order, key);
93
283
  watermarks.push(watermarkOf(delivery, computedAt));
94
284
  const details = order?.delivery_details ?? {};
95
- const row = buildEntryRow(delivery, order, details);
285
+ const row = buildEntryRow(delivery, order, details, localDate);
96
286
  const bucket = rowsByKey.get(key);
97
287
  if (bucket == null)
98
288
  rowsByKey.set(key, [row]);
99
289
  else
100
290
  bucket.push(row);
101
291
  }
292
+ const finalized = new Map();
293
+ for (const [key, accumulator] of accumulators) {
294
+ finalized.set(key, (0, materialized_delivery_classification_helpers_1.finalizeDeliveryAccumulator)(accumulator));
295
+ }
296
+ // The rider leaderboard is bounded at the DOCUMENT level, after the adoption figures
297
+ // are derived (they depend on the per-key order sets, not on the rider map).
298
+ pruneDocumentDeliveryRiders(finalized);
102
299
  const deliveryCounters = {};
103
300
  const deliveryCounterRows = [];
104
- for (const key of [...accumulators.keys()].sort()) {
105
- const counters = (0, materialized_delivery_classification_helpers_1.finalizeDeliveryAccumulator)(accumulators.get(key));
301
+ for (const key of [...finalized.keys()].sort()) {
302
+ const counters = finalized.get(key);
106
303
  deliveryCounters[key] = counters;
107
304
  deliveryCounterRows.push({ key, counters });
108
305
  }
@@ -120,47 +317,81 @@ function compileTenantDeliveryReports(input) {
120
317
  offAppCount += Number(counters?.adoption?.off_app_count) || 0;
121
318
  }
122
319
  const watermark = watermarks.reduce((latest, current) => (current.getTime() > latest.getTime() ? current : latest), computedAt);
123
- return {
124
- reports: [
125
- {
126
- _id: undefined,
127
- tenant_id: tenantId,
128
- brand_id: brandId,
129
- scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
130
- scope_field: localDate,
131
- day_index: dayIndexOf(localDate),
132
- sale_type_key_filters: [...MATERIALIZED_REPORTS_1.DELIVERY_KEY_FILTERS],
133
- delivery_counters: deliveryCounters,
134
- delivery_counter_rows: deliveryCounterRows,
135
- schema_version: materialized_tenant_delivery_reports_1.MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION,
136
- source_watermark: watermark,
137
- computed_at: computedAt,
138
- createdAt: computedAt,
139
- updatedAt: computedAt,
140
- },
141
- ],
142
- entries: [
143
- {
144
- _id: undefined,
145
- tenant_id: tenantId,
146
- brand_id: brandId,
147
- scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
148
- scope_field: localDate,
149
- day_index: dayIndexOf(localDate),
150
- sale_type_key_filters: [...MATERIALIZED_REPORTS_1.DELIVERY_KEY_FILTERS],
151
- delivery_entries: Object.keys(sections).length === 0 ? null : sections,
152
- off_app_order_count: offAppCount,
153
- schema_version: materialized_tenant_delivery_entries_1.MATERIALIZED_TENANT_DELIVERY_ENTRIES_SCHEMA_VERSION,
154
- source_watermark: watermark,
155
- computed_at: computedAt,
156
- createdAt: computedAt,
157
- updatedAt: computedAt,
158
- },
159
- ],
160
- };
320
+ const reports = [
321
+ {
322
+ _id: undefined,
323
+ tenant_id: tenantId,
324
+ brand_id: brandId,
325
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
326
+ scope_field: localDate,
327
+ day_index: dayIndexOf(localDate),
328
+ sale_type_key_filters: [...MATERIALIZED_REPORTS_1.DELIVERY_KEY_FILTERS],
329
+ delivery_counters: deliveryCounters,
330
+ delivery_counter_rows: deliveryCounterRows,
331
+ schema_version: materialized_tenant_delivery_reports_1.MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION,
332
+ source_watermark: watermark,
333
+ computed_at: computedAt,
334
+ createdAt: computedAt,
335
+ updatedAt: computedAt,
336
+ },
337
+ ];
338
+ // ---- ENTRY PAGES (one page per source day, max scope LOCAL_MONTH) ----
339
+ // Every entry scope carries the SAME day rows; the difference is the scope value and
340
+ // the page identity. A quarter/semester/year entry document does not exist.
341
+ const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
342
+ if (periodFields == null)
343
+ return null;
344
+ const entrySections = Object.keys(sections).length === 0 ? null : sections;
345
+ const entries = [];
346
+ for (const scope of MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_ENTRY_SCOPES) {
347
+ const scopeField = periodFields[scope];
348
+ const page = (0, materialized_delivery_entry_pages_1.deliveryEntryPageOf)(scope, localDate);
349
+ if (typeof scopeField !== 'string' || scopeField === '' || page == null)
350
+ return null;
351
+ const pageDoc = {
352
+ _id: undefined,
353
+ tenant_id: tenantId,
354
+ brand_id: brandId,
355
+ scope_context: scope,
356
+ scope_field: scopeField,
357
+ page,
358
+ day_index: scope === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ? dayIndexOf(localDate) : null,
359
+ sale_type_key_filters: [...MATERIALIZED_REPORTS_1.DELIVERY_KEY_FILTERS],
360
+ delivery_entries: entrySections,
361
+ off_app_order_count: offAppCount,
362
+ schema_version: materialized_tenant_delivery_entries_1.MATERIALIZED_TENANT_DELIVERY_ENTRIES_SCHEMA_VERSION,
363
+ source_watermark: watermark,
364
+ computed_at: computedAt,
365
+ createdAt: computedAt,
366
+ updatedAt: computedAt,
367
+ };
368
+ entries.push(...(0, materialized_delivery_entry_pages_1.splitMaterializedDeliveryEntryPage)(pageDoc));
369
+ }
370
+ // BSON BUDGETS: fail at COMPILE time, naming the collection + day + scope, rather
371
+ // than at insert time inside the close transaction.
372
+ (0, materialized_document_size_1.assertMaterializedDocumentSize)(reports[0], {
373
+ label: `materialized_tenant_delivery_reports:${tenantId}:${localDate}:localDate:${localDate}`,
374
+ maxBytes: MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_REPORT_MAX_BSON_BYTES,
375
+ });
376
+ for (const page of entries) {
377
+ (0, materialized_document_size_1.assertMaterializedDocumentSize)(page, {
378
+ label: 'materialized_tenant_delivery_entries:' +
379
+ tenantId +
380
+ ':' +
381
+ localDate +
382
+ ':' +
383
+ String(page.scope_context) +
384
+ ':' +
385
+ page.scope_field +
386
+ ':page=' +
387
+ page.page,
388
+ maxBytes: MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_ENTRY_MAX_BSON_BYTES,
389
+ });
390
+ }
391
+ return { reports, entries };
161
392
  }
162
393
  /** Builds one statement row from a delivery plus its joined order. */
163
- function buildEntryRow(delivery, order, details) {
394
+ function buildEntryRow(delivery, order, details, localDate) {
164
395
  const createdAt = new Date(delivery?.createdAt ?? Date.now());
165
396
  const orderCreatedAt = order?.createdAt == null ? null : new Date(order.createdAt);
166
397
  const deliveredAt = delivery?.delivered_at == null ? null : new Date(delivery.delivered_at);
@@ -187,13 +418,19 @@ function buildEntryRow(delivery, order, details) {
187
418
  has_dropoff_proof: delivery?.dropoff_food_image_url != null,
188
419
  polyline_point_count: Array.isArray(delivery?.polyline) ? delivery.polyline.length : 0,
189
420
  platform: order?.platform == null ? materialized_delivery_classification_helpers_1.DELIVERY_UNKNOWN_TOKEN : String(order.platform),
190
- city: details?.city == null ? null : String(details.city),
421
+ order_status: order?.order_status == null ? materialized_delivery_classification_helpers_1.DELIVERY_UNKNOWN_TOKEN : String(order.order_status),
422
+ // The key resolves city, then state. The row must use the same fallback or a
423
+ // state-only order would sit under one area in the counters and another in the UI.
424
+ city: details?.city != null ? String(details.city) : details?.state != null ? String(details.state) : null,
191
425
  state: details?.state == null ? null : String(details.state),
192
- street: details?.street == null ? null : String(details.street),
426
+ source_local_date: String(order?.localDate ?? delivery?.localDate ?? localDate),
427
+ source_day_unattributed: order == null,
193
428
  // Money is integer CENTS.
194
429
  net_sale_amount: Math.round(Number(order?.net_sale_amount ?? order?.amount_earned) || 0),
195
430
  collected_amount: Math.round(Number(order?.amount_collected) || 0),
196
- delivery_charge: Math.round(Number(details?.delivery_cost) || 0),
431
+ delivery_charge: Math.round(Number(details?.delivery_cost ??
432
+ details?.delivery_charge ??
433
+ details?.delivery_charge_amount) || 0),
197
434
  order_created_at: orderCreatedAt ?? createdAt,
198
435
  assigned_at: delivery?.assigned_at == null ? null : new Date(delivery.assigned_at),
199
436
  picked_up_at: delivery?.picked_up_at == null ? null : new Date(delivery.picked_up_at),
@@ -207,7 +444,7 @@ function buildEntryRow(delivery, order, details) {
207
444
  status_updated_count: delivery?.status_updated_count == null ? null : Number(delivery.status_updated_count) || 0,
208
445
  created_at: createdAt,
209
446
  created_at_mins: delivery?.createdAt_mins == null ? null : Number(delivery.createdAt_mins) || 0,
210
- local_hour: hourLabelOf(delivery),
447
+ local_hour: orderHourLabel(order),
211
448
  };
212
449
  }
213
450
  /** Weekday denormalization for a date document. */
@@ -0,0 +1,128 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { IMaterializedTenantDeliveryEntries } from '../../schemas/types/materialized_tenant_delivery_entries';
3
+ /**
4
+ * Delivery ENTRY PAGES — the page identity of `materialized_tenant_delivery_entries`.
5
+ *
6
+ * ## One page per source day
7
+ *
8
+ * The entry collection follows the Discounts split exactly: the report document is
9
+ * counters only, and an entry document is ONE PAGE bounded by ONE source day.
10
+ *
11
+ * | scope | page |
12
+ * | --- | --- |
13
+ * | `localDate` | `'all'` (the scope is already one day) |
14
+ * | `localWeek` | `<source localDate>` |
15
+ * | `localWeekOfYear` | `<source localDate>` |
16
+ * | `localMonth` | `<source localDate>` |
17
+ *
18
+ * There is NO quarter / semester / year entry scope: a whole month of statement rows
19
+ * in one document is exactly the unbounded shape this replaces. A month is covered by
20
+ * its 28-31 pages.
21
+ *
22
+ * An oversized page is split into deterministic `#0`, `#1` sub-pages. The unsuffixed
23
+ * identity is used while the page fits; every sub-page still belongs to the same source
24
+ * day and is unioned by the flat/details and close readers.
25
+ *
26
+ * ## Broad selections
27
+ *
28
+ * A details reader resolves its exact selected DAYS into either the single day group
29
+ * (one day) or the set of MONTH groups that contain them. The pages of those months are
30
+ * scanned, and the rows are filtered to the exact days using each row's
31
+ * `source_local_date` - so a custom multi-month range is exact, not month-rounded.
32
+ */
33
+ /** True when a scope context carries entry pages (day + the three period scopes). */
34
+ export declare function isMaterializedDeliveryEntryScope(scope: unknown): boolean;
35
+ /**
36
+ * The `page` value a compiled entry document of `scopeContext` must carry for the
37
+ * closing day `localDate`, or null for a scope that carries no entry pages.
38
+ */
39
+ export declare function deliveryEntryPageOf(scopeContext: unknown, localDate: string): string | null;
40
+ /** The unsuffixed source-day page (`all` / `YYYY-MM-DD`). */
41
+ export declare function deliveryEntryPageBase(page: unknown): string;
42
+ /** True when a stored page belongs to the source day. */
43
+ export declare function isDeliveryEntryPageForSourceDay(scopeContext: unknown, page: unknown, localDate: string): boolean;
44
+ /** The deterministic page identity of one chunk. */
45
+ export declare function materializedDeliveryEntrySubPage(basePage: string, index: number): string;
46
+ /**
47
+ * Splits ONE source-day entry page when it exceeds the 15 MiB budget.
48
+ *
49
+ * Rows are walked in their deterministic key/row order and packed until the next row
50
+ * would cross the budget; the resulting chunks are `page#0`, `page#1`, ... . A page
51
+ * that fits keeps its original identity (no suffix), so existing pages are untouched
52
+ * until they actually grow. The pages are disjoint: every row appears exactly once.
53
+ */
54
+ export declare function splitMaterializedDeliveryEntryPage(doc: IMaterializedTenantDeliveryEntries, maxBytes?: number): IMaterializedTenantDeliveryEntries[];
55
+ /**
56
+ * Unions all pages of ONE source day (the base page or its #N sub-pages) into a single
57
+ * logical document. Used by the flat-projection writer and by any in-process details
58
+ * read; rows are disjoint by construction, and the delivery_id/entry_key dedupe makes a
59
+ * duplicate page harmless instead of doubling a row.
60
+ */
61
+ export declare function mergeMaterializedDeliveryEntryPages(pages: readonly IMaterializedTenantDeliveryEntries[] | null | undefined, identity?: {
62
+ scope_context: IMaterializedTenantDeliveryEntries['scope_context'];
63
+ scope_field: string;
64
+ page: string;
65
+ } | null): IMaterializedTenantDeliveryEntries | null;
66
+ /** One entry-page identity: the scope, its value, and the source-day page. */
67
+ export interface IMaterializedDeliveryEntryPageRef {
68
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
69
+ scope_field: string;
70
+ page: string;
71
+ }
72
+ /**
73
+ * The BASE page refs belonging to ONE source day. The close reader expands each ref to
74
+ * the base plus any deterministic `#N` sub-pages; no other day's page is ever fetched.
75
+ *
76
+ * Returns null for a malformed date.
77
+ */
78
+ export declare function buildMaterializedDeliveryEntryPageRefs(localDate: string): IMaterializedDeliveryEntryPageRef[] | null;
79
+ /** Stable identity string of one entry page (tests / diagnostics). */
80
+ export declare function materializedDeliveryEntryPageKey(ref: {
81
+ scope_context: unknown;
82
+ scope_field: unknown;
83
+ page: unknown;
84
+ }): string;
85
+ /** The distinct `YYYY-MM` scope values of a day set, ascending. */
86
+ export declare function deliveryMonthScopeFieldsOfDays(days: readonly string[]): string[];
87
+ /** A decoded scope group, structurally identical to the read API's group shape. */
88
+ export interface IDeliveryScopeGroup {
89
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
90
+ scope_field: string[];
91
+ }
92
+ /**
93
+ * Resolves the EXACT selected days into the scope groups a DELIVERY DETAILS read uses.
94
+ *
95
+ * - one day -> the `localDate` page (`page='all'`) - the direct path;
96
+ * - many days -> the `localMonth` groups that contain them. The reader scans every page
97
+ * of those months and filters rows to the exact days, so a quarter / semester / year
98
+ * / custom multi-month range is served from monthly pages instead of being refused.
99
+ */
100
+ export declare function buildMaterializedDeliveryDetailsScopeGroups(days: readonly string[]): IDeliveryScopeGroup[] | null;
101
+ /** A resolved geo read: scope groups plus the granularity the UI must state. */
102
+ export interface IDeliveryGeoReadPlan {
103
+ groups: IDeliveryScopeGroup[];
104
+ /** Which stored cells were chosen. */
105
+ granularity: 'DAY' | 'MONTH';
106
+ /** True only when the cells cover exactly the selected days. */
107
+ exact_days: boolean;
108
+ /** Oldest day that can still have retained DAY cells. */
109
+ day_cutoff: string;
110
+ }
111
+ /**
112
+ * THE canonical GEO resolver, shared by LIVE and HISTORICAL.
113
+ *
114
+ * - all selected days are inside the DAY-cell retention window -> exact DAY cells;
115
+ * - otherwise -> whole-MONTH cells for every month the selection touches.
116
+ *
117
+ * It never mixes DAY cells for some days with MONTH cells for others. The caller must
118
+ * expose `granularity` / `exact_days` so the UI can say when the map is month-granular.
119
+ */
120
+ export declare function resolveMaterializedDeliveryGeoRead(days: readonly string[], options?: {
121
+ now?: Date | string | null;
122
+ retentionDays?: number | null;
123
+ }): IDeliveryGeoReadPlan | null;
124
+ /**
125
+ * Scope groups for the GEO read. Kept as the public group-only helper; prefer
126
+ * `resolveMaterializedDeliveryGeoRead` when the response must carry granularity.
127
+ */
128
+ export declare function buildMaterializedDeliveryGeoScopeGroups(days: readonly string[]): IDeliveryScopeGroup[] | null;