@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
@@ -12,6 +12,7 @@ exports.addDelivery = addDelivery;
12
12
  exports.finalizeDeliveryAccumulator = finalizeDeliveryAccumulator;
13
13
  const delivery_1 = require("../../constants/enums/delivery");
14
14
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
15
+ const materialized_delivery_rows_1 = require("./materialized-delivery-rows");
15
16
  /**
16
17
  * M4 delivery - key grammar, the order join, and the accumulators.
17
18
  *
@@ -28,7 +29,7 @@ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
28
29
  * ## The join
29
30
  *
30
31
  * A delivery document carries neither the platform nor the city, so the key
31
- * `<PLATFORM>:<CITY>` and every order-derived money figure come from joining by
32
+ * `<ORDER_STATUS>:<PLATFORM>:<CITY>` and every order-derived money figure come from joining by
32
33
  * `order_id`. An order with no platform/city details falls into an explicit UNKNOWN
33
34
  * bucket rather than being dropped silently - a missing dimension must still show up in
34
35
  * the totals.
@@ -44,9 +45,13 @@ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
44
45
  /** The key token used when a dimension is missing, so nothing is silently dropped. */
45
46
  exports.DELIVERY_UNKNOWN_TOKEN = 'UNKNOWN';
46
47
  exports.MATERIALIZED_DELIVERY_KEY_SEPARATOR = ':';
47
- /** Builds `<PLATFORM>:<CITY>`, substituting UNKNOWN for missing dimensions. */
48
- function buildMaterializedDeliveryKey(platform, city) {
49
- return normalizeDimension(platform) + exports.MATERIALIZED_DELIVERY_KEY_SEPARATOR + normalizeDimension(city);
48
+ /** Builds `<ORDER_STATUS>:<PLATFORM>:<CITY>`, substituting UNKNOWN for missing dimensions. */
49
+ function buildMaterializedDeliveryKey(orderStatus, platform, city) {
50
+ return (normalizeDimension(orderStatus) +
51
+ exports.MATERIALIZED_DELIVERY_KEY_SEPARATOR +
52
+ normalizeDimension(platform) +
53
+ exports.MATERIALIZED_DELIVERY_KEY_SEPARATOR +
54
+ normalizeDimension(city));
50
55
  }
51
56
  function normalizeDimension(value) {
52
57
  if (value == null)
@@ -63,32 +68,15 @@ function parseMaterializedDeliveryKey(key) {
63
68
  if (key == null)
64
69
  return null;
65
70
  const parts = String(key).split(exports.MATERIALIZED_DELIVERY_KEY_SEPARATOR);
66
- if (parts.length !== 2)
71
+ if (parts.length !== 3)
67
72
  return null;
68
- const [platform, city] = parts;
69
- if (platform === '' || city === '')
73
+ const [order_status, platform, city] = parts;
74
+ if (order_status === '' || platform === '' || city === '')
70
75
  return null;
71
- return { platform, city };
76
+ return { order_status, platform, city };
72
77
  }
73
- const emptyRiderRow = (name) => ({
74
- rider_name: name,
75
- count: 0,
76
- completed_count: 0,
77
- cancelled_count: 0,
78
- in_progress_count: 0,
79
- rider_revenue_amount: 0,
80
- distance_sum_meters: 0,
81
- first_delivery_at: null,
82
- last_delivery_at: null,
83
- });
84
- const emptyAreaRow = () => ({
85
- count: 0,
86
- completed_count: 0,
87
- cancelled_count: 0,
88
- rider_revenue_amount: 0,
89
- distance_sum_meters: 0,
90
- by_hour: {},
91
- });
78
+ const emptyRiderRow = materialized_delivery_rows_1.emptyMaterializedDeliveryRiderRow;
79
+ const emptyAreaRow = materialized_delivery_rows_1.emptyMaterializedDeliveryAreaRow;
92
80
  /** A zeroed counter block. */
93
81
  function freshDeliveryCounters() {
94
82
  const distance = { sum_meters: 0, count: 0 };
@@ -129,6 +117,9 @@ function freshDeliveryCounters() {
129
117
  areas: {},
130
118
  timing: {
131
119
  graded_count: 0,
120
+ dispatch_lag_count: 0,
121
+ complete_count: 0,
122
+ total_count: 0,
132
123
  dispatch_lag_sum_minutes: 0,
133
124
  complete_sum_minutes: 0,
134
125
  total_sum_minutes: 0,
@@ -213,7 +204,7 @@ function isDeliveryOrder(order) {
213
204
  * Order-side money is counted HERE rather than on the delivery, because a cancelled
214
205
  * delivery must not lose the order figures the operator recognises.
215
206
  */
216
- function addDeliveryOrder(acc, order) {
207
+ function addDeliveryOrder(acc, order, key = buildMaterializedDeliveryKey(order?.order_status, order?.platform, order?.delivery_details?.city ?? order?.delivery_details?.state ?? null)) {
217
208
  if (acc == null || order == null)
218
209
  return;
219
210
  const orderId = order._id == null ? null : String(order._id);
@@ -227,12 +218,20 @@ function addDeliveryOrder(acc, order) {
227
218
  const details = order.delivery_details ?? {};
228
219
  // Money is integer CENTS: each source amount is rounded to the cent at this
229
220
  // writer boundary, because a materialized document may not hold a decimal.
230
- counters.money.net_sale_amount += cents(order.net_sale_amount ?? order.amount_earned);
231
- counters.money.collected_amount += cents(order.amount_collected);
232
- counters.money.tip_amount += cents(order.tip_amount);
233
- counters.money.discount_amount += cents(order.total_discount_applied);
234
- counters.money.refund_amount += cents(order.amount_refunded);
235
- counters.money.tax_amount += cents(order.gst_amount) + cents(order.tax_amount);
221
+ const netSale = cents(order.net_sale_amount ?? order.amount_earned);
222
+ const collected = cents(order.amount_collected);
223
+ const tip = cents(order.tip_amount);
224
+ const discount = cents(order.total_discount_applied);
225
+ // REFUNDS: `IOrder` declares no order-level `amount_refunded`; the money exists only
226
+ // on the payment rows, so it is summed from that declared source.
227
+ const refund = (order.payments ?? []).reduce((total, payment) => total + cents(payment?.amount_refunded), 0);
228
+ const tax = cents(order.gst_amount) + cents(order.tax_amount);
229
+ counters.money.net_sale_amount += netSale;
230
+ counters.money.collected_amount += collected;
231
+ counters.money.tip_amount += tip;
232
+ counters.money.discount_amount += discount;
233
+ counters.money.refund_amount += refund;
234
+ counters.money.tax_amount += tax;
236
235
  // `delivery_cost` is the field IOrderDeliveryDetails ACTUALLY declares; the other two
237
236
  // names are tolerated fallbacks. Reading the wrong one silently reported every charge
238
237
  // as ZERO while the statement row (which used the right field) showed the real value -
@@ -243,6 +242,16 @@ function addDeliveryOrder(acc, order) {
243
242
  counters.money.delivery_charge_amount += charge;
244
243
  counters.money.delivery_charge_count += 1;
245
244
  }
245
+ // ---- the ORDER side of the area row ----
246
+ // Off-app orders are the whole point: they belong in the area's demand (and its money)
247
+ // even though no delivery document will ever describe them.
248
+ const area = areaRowFor(counters, key);
249
+ area.delivery_orders += 1;
250
+ area.net_sale_amount += netSale;
251
+ area.delivery_charge_amount += charge;
252
+ const hour = orderHourKey(order);
253
+ if (hour != null)
254
+ area.by_hour[hour] = (area.by_hour[hour] ?? 0) + 1;
246
255
  acc.watermark = laterOf(acc.watermark, order.updatedAt ?? order.createdAt);
247
256
  }
248
257
  /**
@@ -253,7 +262,7 @@ function addDeliveryOrder(acc, order) {
253
262
  * attributed, so it lands in the UNKNOWN bucket.
254
263
  */
255
264
  function addDelivery(acc, delivery, order, key) {
256
- var _a, _b;
265
+ var _a;
257
266
  if (acc == null || delivery == null)
258
267
  return;
259
268
  const counters = acc.counters;
@@ -317,12 +326,12 @@ function addDelivery(acc, delivery, order, key) {
317
326
  row.first_delivery_at = earlierOf(row.first_delivery_at, delivery.createdAt);
318
327
  row.last_delivery_at = laterOf(row.last_delivery_at, delivery.createdAt);
319
328
  }
320
- // ---- the bounded area heat map (city from the JOIN) ----
321
- const parsed = parseMaterializedDeliveryKey(key);
322
- const city = parsed == null ? exports.DELIVERY_UNKNOWN_TOKEN : parsed.city;
323
- counters.areas ?? (counters.areas = {});
324
- const area = ((_b = counters.areas)[city] ?? (_b[city] = emptyAreaRow()));
325
- area.count += 1;
329
+ // ---- the APP side of the area row (city from the JOIN) ----
330
+ // The row already exists when the area's orders were consumed; a delivery whose order
331
+ // was not staged creates the UNKNOWN row, so its record is still counted (its money
332
+ // and area attribution simply cannot be known).
333
+ const area = areaRowFor(counters, key);
334
+ area.delivery_records += 1;
326
335
  if (status === delivery_1.DELIVERY_STATUS_ENUM.COMPLETED)
327
336
  area.completed_count += 1;
328
337
  else if (status === delivery_1.DELIVERY_STATUS_ENUM.CANCELLED)
@@ -330,9 +339,7 @@ function addDelivery(acc, delivery, order, key) {
330
339
  if (isFinalPayout)
331
340
  area.rider_revenue_amount += revenue;
332
341
  area.distance_sum_meters += meters;
333
- const hour = hourKeyOf(delivery);
334
- if (hour != null)
335
- area.by_hour[hour] = (area.by_hour[hour] ?? 0) + 1;
342
+ // NO hour here: demand is bucketed by the ORDER's local hour (see addDeliveryOrder).
336
343
  // ---- timing ----
337
344
  const timing = (counters.timing ?? (counters.timing = freshDeliveryCounters().timing));
338
345
  let graded = false;
@@ -340,6 +347,7 @@ function addDelivery(acc, delivery, order, key) {
340
347
  const dispatchLag = minutesBetween(orderCreatedAt, delivery.createdAt);
341
348
  if (dispatchLag != null) {
342
349
  timing.dispatch_lag_sum_minutes += dispatchLag;
350
+ timing.dispatch_lag_count += 1;
343
351
  graded = true;
344
352
  }
345
353
  if (status === delivery_1.DELIVERY_STATUS_ENUM.COMPLETED) {
@@ -351,13 +359,16 @@ function addDelivery(acc, delivery, order, key) {
351
359
  const complete = minutesBetween(delivery.createdAt, completedAt);
352
360
  if (complete != null) {
353
361
  timing.complete_sum_minutes += complete;
362
+ timing.complete_count += 1;
354
363
  graded = true;
355
364
  if (exact)
356
365
  timing.exact_completion_count += 1;
357
366
  }
358
367
  const total = minutesBetween(orderCreatedAt, completedAt);
359
- if (total != null)
368
+ if (total != null) {
360
369
  timing.total_sum_minutes += total;
370
+ timing.total_count += 1;
371
+ }
361
372
  // Explicit ETA only. ASAP orders need tenant settings the compile does not
362
373
  // receive, so they stay UNMEASURED rather than being given an invented promise.
363
374
  const expectedRaw = delivery.expected_delivery_at ?? order?.delivery_details?.estimated_delivery_time;
@@ -409,46 +420,57 @@ function addDelivery(acc, delivery, order, key) {
409
420
  }
410
421
  acc.watermark = laterOf(acc.watermark, delivery.updatedAt ?? delivery.createdAt);
411
422
  }
412
- /** `HH` of a delivery, from the local hour when present. */
413
- function hourKeyOf(delivery) {
414
- const explicit = delivery.localHour;
415
- if (typeof explicit === 'number' && Number.isFinite(explicit)) {
416
- return String(Math.max(0, Math.min(23, Math.floor(explicit)))).padStart(2, '0');
417
- }
418
- const raw = delivery.createdAt;
419
- if (raw == null)
423
+ /**
424
+ * `HH` of an ORDER's tenant-local hour.
425
+ *
426
+ * The ONLY hour source allowed in this report: the delivery write path carries no
427
+ * `localHour`, and deriving one from `createdAt` on the server would report UTC (or the
428
+ * server's zone) as if it were tenant-local - silently shifting the demand heat map in
429
+ * every non-UTC tenant.
430
+ *
431
+ * Returns null when the hour is absent or out of range: an unmeasured hour is not hour 0.
432
+ */
433
+ function orderHourKey(order) {
434
+ const hour = Number(order?.localHour);
435
+ if (!Number.isFinite(hour))
420
436
  return null;
421
- const date = new Date(raw);
422
- if (Number.isNaN(date.getTime()))
437
+ const whole = Math.floor(hour);
438
+ if (whole < 0 || whole > 23)
423
439
  return null;
424
- return String(date.getHours()).padStart(2, '0');
440
+ return String(whole).padStart(2, '0');
441
+ }
442
+ /** The area row of this accumulator, created on first use (key -> city). */
443
+ function areaRowFor(counters, key) {
444
+ var _a;
445
+ const parsed = parseMaterializedDeliveryKey(key);
446
+ const city = parsed == null ? exports.DELIVERY_UNKNOWN_TOKEN : parsed.city;
447
+ counters.areas ?? (counters.areas = {});
448
+ return ((_a = counters.areas)[city] ?? (_a[city] = emptyAreaRow()));
425
449
  }
426
450
  /**
427
- * Computes the DERIVED adoption figures and prunes the bounded maps.
451
+ * Computes the DERIVED adoption figures of one key.
428
452
  *
429
453
  * Call ONCE per key, after both stages have been consumed. `off_app_count` is a set
430
454
  * difference, so an order reassigned to a second rider is NOT counted as off-app even
431
455
  * though there are more deliveries than orders.
456
+ *
457
+ * The per-key ORDER SETS are also what fill the area row's order-side adoption counters:
458
+ * a key maps to exactly one RESOLVED area, so `delivery_order_count` /
459
+ * `delivered_via_app_count` of the key ARE that area's figures for this document.
460
+ *
461
+ * The bounded maps are NOT pruned here: the rider cap applies to the whole DOCUMENT
462
+ * (`pruneDocumentDeliveryRiders`) and the city cap is applied when the key is resolved
463
+ * (`buildDeliveryCityResolver`).
432
464
  */
433
465
  function finalizeDeliveryAccumulator(acc) {
434
466
  const counters = acc.counters;
435
467
  const deliveredOrders = [...acc.deliveredOrderIds].filter((id) => acc.deliveryOrderIds.has(id)).length;
436
468
  counters.adoption.delivered_via_app_count = deliveredOrders;
437
469
  counters.adoption.off_app_count = Math.max(0, acc.deliveryOrderIds.size - deliveredOrders);
438
- counters.riders = pruneMap(counters.riders, MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_RIDER_LIMIT, (row) => Number(row.count) || 0);
439
- counters.areas = pruneMap(counters.areas, MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_AREA_LIMIT, (row) => Number(row.count) || 0);
470
+ for (const row of Object.values(counters.areas ?? {})) {
471
+ row.delivery_orders = acc.deliveryOrderIds.size;
472
+ row.app_orders = deliveredOrders;
473
+ row.off_app_orders = counters.adoption.off_app_count;
474
+ }
440
475
  return counters;
441
476
  }
442
- /** Keeps the N busiest entries, so a document stays bounded. */
443
- function pruneMap(source, limit, weightOf) {
444
- if (source == null)
445
- return null;
446
- const entries = Object.entries(source);
447
- if (entries.length <= limit)
448
- return source;
449
- entries.sort((a, b) => weightOf(b[1]) - weightOf(a[1]));
450
- const kept = {};
451
- for (const [key, value] of entries.slice(0, limit))
452
- kept[key] = value;
453
- return kept;
454
- }
@@ -1,5 +1,5 @@
1
1
  import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
- import { IMaterializedDeliveryEntry, IMaterializedTenantDeliveryEntries } from '../../schemas/types/materialized_tenant_delivery_entries';
2
+ import { IMaterializedTenantDeliveryEntries } from '../../schemas/types/materialized_tenant_delivery_entries';
3
3
  import { IMaterializedDeliveryCounters, IMaterializedTenantDeliveryReport } from '../../schemas/types/materialized_tenant_delivery_reports';
4
4
  /**
5
5
  * M4 close-day helpers.
@@ -16,24 +16,24 @@ import { IMaterializedDeliveryCounters, IMaterializedTenantDeliveryReport } from
16
16
  * A folded document that inherited the STORED document watermark would look unchanged to
17
17
  * the write guard and be skipped forever, freezing the period at its first closed day.
18
18
  * That bug shipped once in the prep time report; it is designed out here from the start.
19
+ *
20
+ * ## ENTRY pages are NOT folded
21
+ *
22
+ * `materialized_tenant_delivery_entries` is page-partitioned by source day (the discounts
23
+ * split). The plan never reads, merges or folds another day's page: the caller fetches
24
+ * exactly the closing day's pages, each is replaced by its page identity, and a fetched
25
+ * page the day no longer owns is deleted. There is no quarter/semester/year entry scope.
19
26
  */
20
- /** Period scopes this report materializes (everything but the day scope). */
27
+ /** Period COUNTER scopes this report materializes (everything but the day scope). */
21
28
  export declare const MATERIALIZED_DELIVERY_PERIOD_SCOPES: MATERIALIZED_REPORT_SCOPE_ENUM[];
22
- /** True when the scope is the plain day scope. */
23
- export declare const isMaterializedDeliveryDayScope: (scopeContext: string) => boolean;
24
29
  /**
25
- * Merges TWO period entry sections, keyed on `entry_key`.
26
- *
27
- * Rows are deduplicated by identity: a source delivery belongs to exactly one day, so the
28
- * same `entry_key` twice means the fold saw it twice.
30
+ * Every `localDate` label whose DAY counter document can contribute to a REPORT period
31
+ * the closing day rolls into - week through YEAR. The worker uses it to fetch exactly
32
+ * the sibling DAY counters the period re-fold needs.
29
33
  */
30
- export declare function mergeMaterializedDeliveryEntrySections(target: Record<string, {
31
- rows: IMaterializedDeliveryEntry[];
32
- }> | null, source: Record<string, {
33
- rows: IMaterializedDeliveryEntry[];
34
- }> | null): Record<string, {
35
- rows: IMaterializedDeliveryEntry[];
36
- }>;
34
+ export declare function getMaterializedDeliveryReportPeriodDayScopeFields(localDate: string): string[] | null;
35
+ /** True when the scope is the plain day scope. */
36
+ export declare const isMaterializedDeliveryDayScope: (scopeContext: string) => boolean;
37
37
  /** True when the stored document already carries this exact content. */
38
38
  export declare function needsMaterializedDeliveryReportWrite(existing: IMaterializedTenantDeliveryReport | null | undefined, next: IMaterializedTenantDeliveryReport): boolean;
39
39
  /** True when the stored entry document already carries these exact rows. */
@@ -44,17 +44,6 @@ export declare function foldMaterializedDeliveryPeriodCounters(input: {
44
44
  periodScopeField: string;
45
45
  dayDocuments: IMaterializedTenantDeliveryReport[];
46
46
  }): Record<string, IMaterializedDeliveryCounters>;
47
- /** Folds the statement rows of every day document belonging to one period scope. */
48
- export declare function foldMaterializedDeliveryPeriodRows(input: {
49
- periodScope: string;
50
- periodScopeField: string;
51
- dayDocuments: IMaterializedTenantDeliveryEntries[];
52
- }): {
53
- sections: Record<string, {
54
- rows: IMaterializedDeliveryEntry[];
55
- }>;
56
- offApp: number;
57
- };
58
47
  /** One plan write: the document plus its iteration history row. */
59
48
  export interface IMaterializedDeliveryCloseDayWrite<T> {
60
49
  report: T;
@@ -86,6 +75,14 @@ export interface IBuildTenantDeliveryCloseDayPlanInput {
86
75
  existingEntries?: IMaterializedTenantDeliveryEntries[];
87
76
  reason: string;
88
77
  computedAt?: Date;
78
+ /**
79
+ * Rewrite every touched document even when the watermark says nothing changed.
80
+ *
81
+ * Delivery counters are NOT purely append-only: a delivery record's STATUS changes
82
+ * (and a removed record changes the day without advancing the max watermark). A
83
+ * value-idempotent forced rewrite is the safe default, exactly like Prep Time.
84
+ */
85
+ force?: boolean;
89
86
  }
90
87
  /**
91
88
  * Builds the close-day plan for ONE tenant-day.