@managesome/eposmatic-toolkit 0.4.52 → 0.4.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +106 -2
  2. package/esm/constants/enums/delivery.js +13 -0
  3. package/esm/helpers/materialized-reports/index.js +6 -0
  4. package/esm/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +8 -62
  5. package/esm/helpers/materialized-reports/materialized-delivery-classification-helpers.js +95 -73
  6. package/esm/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +118 -146
  7. package/esm/helpers/materialized-reports/materialized-delivery-compile-helpers.js +304 -71
  8. package/esm/helpers/materialized-reports/materialized-delivery-entry-pages.js +307 -0
  9. package/esm/helpers/materialized-reports/materialized-delivery-index-migration.js +103 -0
  10. package/esm/helpers/materialized-reports/materialized-delivery-rows.js +109 -0
  11. package/esm/helpers/materialized-reports/materialized-delivery-wipe-targets.js +32 -0
  12. package/esm/helpers/materialized-reports/materialized-document-size.js +65 -0
  13. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +31 -16
  14. package/esm/helpers/materialized-reports/materialized-integer-contract.js +10 -1
  15. package/esm/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +3 -91
  16. package/esm/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.js +597 -0
  17. package/esm/helpers/materialized-reports/report-platform/definition.js +508 -0
  18. package/esm/helpers/materialized-reports/report-platform/index.js +4 -0
  19. package/esm/helpers/materialized-reports/report-platform/lifecycle/budget.js +27 -0
  20. package/esm/helpers/materialized-reports/report-platform/lifecycle/cap-metadata.js +12 -0
  21. package/esm/helpers/materialized-reports/report-platform/lifecycle/entry-pages.js +121 -0
  22. package/esm/helpers/materialized-reports/report-platform/lifecycle/flat-projection.js +14 -0
  23. package/esm/helpers/materialized-reports/report-platform/lifecycle/index.js +8 -0
  24. package/esm/helpers/materialized-reports/report-platform/lifecycle/iteration-row.js +10 -0
  25. package/esm/helpers/materialized-reports/report-platform/lifecycle/run-stats.js +42 -0
  26. package/esm/helpers/materialized-reports/report-platform/lifecycle/scope-refs.js +28 -0
  27. package/esm/helpers/materialized-reports/report-platform/lifecycle/top-n.js +24 -0
  28. package/esm/helpers/materialized-reports/report-platform/registry.js +23 -0
  29. package/esm/helpers/materialized-reports/report-platform/validate-report-registry.js +214 -0
  30. package/esm/helpers/materialized-reports/scope-helpers.js +98 -0
  31. package/esm/helpers/materialized-reports/tenant-delivery-formatter.js +70 -20
  32. package/esm/schemas/models/applied_order_discounts.js +103 -0
  33. package/esm/schemas/models/index.js +12 -10
  34. package/esm/schemas/models/materialized_tenant_delivery_entries.js +33 -12
  35. package/esm/schemas/models/materialized_tenant_delivery_geo_cells.js +83 -0
  36. package/esm/schemas/models/materialized_tenant_delivery_geo_scopes.js +35 -0
  37. package/esm/schemas/models/materialized_tenant_delivery_reports.js +10 -1
  38. package/esm/schemas/types/applied_order_discounts.js +1 -0
  39. package/esm/schemas/types/index.js +14 -12
  40. package/esm/schemas/types/materialized_tenant_delivery_geo_cells.js +1 -0
  41. package/esm/schemas/types/materialized_tenant_delivery_geo_scopes.js +1 -0
  42. package/lib/constants/MATERIALIZED_REPORTS.d.ts +95 -1
  43. package/lib/constants/MATERIALIZED_REPORTS.js +108 -4
  44. package/lib/constants/enums/delivery.d.ts +9 -0
  45. package/lib/constants/enums/delivery.js +14 -1
  46. package/lib/helpers/materialized-reports/index.d.ts +6 -0
  47. package/lib/helpers/materialized-reports/index.js +6 -0
  48. package/lib/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +8 -62
  49. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.d.ts +36 -9
  50. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.js +94 -72
  51. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.d.ts +23 -26
  52. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +121 -150
  53. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.d.ts +44 -5
  54. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +306 -69
  55. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.d.ts +128 -0
  56. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.js +322 -0
  57. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.d.ts +48 -0
  58. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.js +108 -0
  59. package/lib/helpers/materialized-reports/materialized-delivery-rows.d.ts +15 -0
  60. package/lib/helpers/materialized-reports/materialized-delivery-rows.js +115 -0
  61. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.d.ts +17 -0
  62. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.js +35 -0
  63. package/lib/helpers/materialized-reports/materialized-document-size.d.ts +47 -0
  64. package/lib/helpers/materialized-reports/materialized-document-size.js +73 -0
  65. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +28 -13
  66. package/lib/helpers/materialized-reports/materialized-integer-contract.js +10 -1
  67. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +2 -90
  68. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.d.ts +186 -0
  69. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.js +620 -0
  70. package/lib/helpers/materialized-reports/report-platform/definition.d.ts +133 -0
  71. package/lib/helpers/materialized-reports/report-platform/definition.js +511 -0
  72. package/lib/helpers/materialized-reports/report-platform/index.d.ts +4 -0
  73. package/lib/helpers/materialized-reports/report-platform/index.js +20 -0
  74. package/lib/helpers/materialized-reports/report-platform/lifecycle/budget.d.ts +8 -0
  75. package/lib/helpers/materialized-reports/report-platform/lifecycle/budget.js +31 -0
  76. package/lib/helpers/materialized-reports/report-platform/lifecycle/cap-metadata.d.ts +8 -0
  77. package/lib/helpers/materialized-reports/report-platform/lifecycle/cap-metadata.js +16 -0
  78. package/lib/helpers/materialized-reports/report-platform/lifecycle/entry-pages.d.ts +40 -0
  79. package/lib/helpers/materialized-reports/report-platform/lifecycle/entry-pages.js +130 -0
  80. package/lib/helpers/materialized-reports/report-platform/lifecycle/flat-projection.d.ts +22 -0
  81. package/lib/helpers/materialized-reports/report-platform/lifecycle/flat-projection.js +17 -0
  82. package/lib/helpers/materialized-reports/report-platform/lifecycle/index.d.ts +8 -0
  83. package/lib/helpers/materialized-reports/report-platform/lifecycle/index.js +24 -0
  84. package/lib/helpers/materialized-reports/report-platform/lifecycle/iteration-row.d.ts +13 -0
  85. package/lib/helpers/materialized-reports/report-platform/lifecycle/iteration-row.js +13 -0
  86. package/lib/helpers/materialized-reports/report-platform/lifecycle/run-stats.d.ts +20 -0
  87. package/lib/helpers/materialized-reports/report-platform/lifecycle/run-stats.js +47 -0
  88. package/lib/helpers/materialized-reports/report-platform/lifecycle/scope-refs.d.ts +13 -0
  89. package/lib/helpers/materialized-reports/report-platform/lifecycle/scope-refs.js +31 -0
  90. package/lib/helpers/materialized-reports/report-platform/lifecycle/top-n.d.ts +16 -0
  91. package/lib/helpers/materialized-reports/report-platform/lifecycle/top-n.js +29 -0
  92. package/lib/helpers/materialized-reports/report-platform/registry.d.ts +13 -0
  93. package/lib/helpers/materialized-reports/report-platform/registry.js +31 -0
  94. package/lib/helpers/materialized-reports/report-platform/validate-report-registry.d.ts +20 -0
  95. package/lib/helpers/materialized-reports/report-platform/validate-report-registry.js +218 -0
  96. package/lib/helpers/materialized-reports/scope-helpers.d.ts +8 -0
  97. package/lib/helpers/materialized-reports/scope-helpers.js +99 -0
  98. package/lib/helpers/materialized-reports/tenant-delivery-formatter.d.ts +41 -0
  99. package/lib/helpers/materialized-reports/tenant-delivery-formatter.js +70 -20
  100. package/lib/helpers/order/payment-collection.d.ts +25 -0
  101. package/lib/helpers/order/payment-collection.js +51 -0
  102. package/lib/schemas/models/applied_order_discounts.d.ts +80 -0
  103. package/lib/schemas/models/applied_order_discounts.js +106 -0
  104. package/lib/schemas/models/index.d.ts +12 -10
  105. package/lib/schemas/models/index.js +12 -10
  106. package/lib/schemas/models/materialized_tenant_delivery_entries.d.ts +31 -9
  107. package/lib/schemas/models/materialized_tenant_delivery_entries.js +32 -11
  108. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.d.ts +129 -0
  109. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.js +86 -0
  110. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.d.ts +71 -0
  111. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.js +38 -0
  112. package/lib/schemas/models/materialized_tenant_delivery_reports.d.ts +10 -1
  113. package/lib/schemas/models/materialized_tenant_delivery_reports.js +10 -1
  114. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +15 -15
  115. package/lib/schemas/types/applied_order_discounts.d.ts +22 -0
  116. package/lib/schemas/types/applied_order_discounts.js +2 -0
  117. package/lib/schemas/types/index.d.ts +14 -12
  118. package/lib/schemas/types/index.js +14 -12
  119. package/lib/schemas/types/materialized_tenant_delivery_entries.d.ts +36 -4
  120. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.d.ts +178 -0
  121. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.js +2 -0
  122. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.d.ts +21 -0
  123. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.js +2 -0
  124. package/lib/schemas/types/materialized_tenant_delivery_reports.d.ts +49 -7
  125. package/lib/tests/materialized-reports/analytics-growth-helpers.test.d.ts +1 -0
  126. package/lib/tests/materialized-reports/analytics-overview-helpers.test.d.ts +1 -0
  127. package/lib/tests/materialized-reports/analytics-performance-helpers.test.d.ts +1 -0
  128. package/lib/tests/materialized-reports/characterization/delivery.characterization.test.d.ts +1 -0
  129. package/lib/tests/materialized-reports/characterization/delivery.characterization.test.js +229 -0
  130. package/lib/tests/materialized-reports/characterization/discount.characterization.test.d.ts +1 -0
  131. package/lib/tests/materialized-reports/characterization/discount.characterization.test.js +99 -0
  132. package/lib/tests/materialized-reports/characterization/fixtures.d.ts +30 -0
  133. package/lib/tests/materialized-reports/characterization/fixtures.js +402 -0
  134. package/lib/tests/materialized-reports/characterization/golden.d.ts +18 -0
  135. package/lib/tests/materialized-reports/characterization/golden.js +127 -0
  136. package/lib/tests/materialized-reports/characterization/overview.characterization.test.d.ts +1 -0
  137. package/lib/tests/materialized-reports/characterization/overview.characterization.test.js +69 -0
  138. package/lib/tests/materialized-reports/characterization/prep-time.characterization.test.d.ts +1 -0
  139. package/lib/tests/materialized-reports/characterization/prep-time.characterization.test.js +102 -0
  140. package/lib/tests/materialized-reports/materialized-delivery-accumulation.test.js +56 -19
  141. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.d.ts +1 -0
  142. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.js +91 -0
  143. package/lib/tests/materialized-reports/materialized-delivery-compile.test.js +271 -15
  144. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.d.ts +1 -0
  145. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.js +128 -0
  146. package/lib/tests/materialized-reports/materialized-delivery-fold.test.js +42 -5
  147. package/lib/tests/materialized-reports/materialized-delivery-formatter.test.js +13 -1
  148. package/lib/tests/materialized-reports/materialized-delivery-geo.test.d.ts +1 -0
  149. package/lib/tests/materialized-reports/materialized-delivery-geo.test.js +446 -0
  150. package/lib/tests/materialized-reports/materialized-delivery-plan.test.js +117 -25
  151. package/lib/tests/materialized-reports/materialized-delivery-practical.test.d.ts +1 -0
  152. package/lib/tests/materialized-reports/materialized-delivery-practical.test.js +344 -0
  153. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +14 -0
  154. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +1 -1
  155. package/lib/tests/materialized-reports/report-platform/lifecycle-primitives.test.d.ts +1 -0
  156. package/lib/tests/materialized-reports/report-platform/lifecycle-primitives.test.js +177 -0
  157. package/lib/tests/materialized-reports/report-platform/registry-conformance.test.d.ts +1 -0
  158. package/lib/tests/materialized-reports/report-platform/registry-conformance.test.js +214 -0
  159. package/lib/tests/materialized-reports/report-platform/registry-validation.test.d.ts +1 -0
  160. package/lib/tests/materialized-reports/report-platform/registry-validation.test.js +103 -0
  161. package/lib/tests/offer-item-resolution.test.js +1 -4
  162. package/lib/tests/payment-collection-timestamps.test.d.ts +1 -0
  163. package/lib/tests/payment-collection-timestamps.test.js +71 -0
  164. package/package.json +6 -2
@@ -17,6 +17,7 @@ const order = (id, over = {}) => ({
17
17
  _id: id,
18
18
  tenant_id: TENANT,
19
19
  platform: 'POS_WALK-IN',
20
+ order_status: 'COMPLETED',
20
21
  order_number: 100,
21
22
  createdAt: new Date('2026-09-14T10:00:00.000Z'),
22
23
  net_sale_amount: 5000,
@@ -54,7 +55,50 @@ const compile = (over = {}) => (0, materialized_delivery_compile_helpers_1.compi
54
55
  computedAt: new Date('2026-09-14T23:00:00.000Z'),
55
56
  ...over,
56
57
  });
58
+ /** The DAY entry page (`page='all'`) - the row set every other entry page retargets. */
59
+ const dayEntry = (compiled) => compiled.entries.find((entry) => String(entry.scope_context) === 'localDate');
57
60
  describe('M4 day compile', () => {
61
+ it('uses the same delivery-charge and city/state fallbacks as the counter', () => {
62
+ const compiled = (0, materialized_delivery_compile_helpers_1.compileTenantDeliveryReports)({
63
+ tenantId: 't',
64
+ brandId: 'b',
65
+ localDate: '2026-09-14',
66
+ orders: [
67
+ {
68
+ _id: 'o-fallback',
69
+ tenant_id: 't',
70
+ platform: 'POS_DELIVERY',
71
+ order_status: 'COMPLETED',
72
+ createdAt: new Date('2026-09-14T10:00:00.000Z'),
73
+ localDate: '2026-09-14',
74
+ localHour: 10,
75
+ localMinute: 30,
76
+ net_sale_amount: 1000,
77
+ amount_collected: 1000,
78
+ delivery_details: { state: 'Ankara', delivery_charge: 250 },
79
+ },
80
+ ],
81
+ deliveries: [
82
+ {
83
+ _id: 'd-fallback',
84
+ tenant_id: 't',
85
+ order_id: 'o-fallback',
86
+ rider_id: 'r1',
87
+ status: 'COMPLETED',
88
+ createdAt: new Date('2026-09-14T10:05:00.000Z'),
89
+ updatedAt: new Date('2026-09-14T10:30:00.000Z'),
90
+ delivered_at: new Date('2026-09-14T10:28:00.000Z'),
91
+ localDate: '2026-09-14',
92
+ },
93
+ ],
94
+ computedAt: new Date('2026-09-14T23:00:00.000Z'),
95
+ });
96
+ const row = Object.values(compiled.entries[0].delivery_entries ?? {}).flatMap((section) => section.rows)[0];
97
+ expect(row.city).toBe('Ankara');
98
+ expect(row.delivery_charge).toBe(250);
99
+ expect(row.local_hour).toBe('2026-09-14 10:30');
100
+ expect(Object.values(compiled.reports[0].delivery_counters)[0].money.delivery_charge_amount).toBe(250);
101
+ });
58
102
  it('returns null only when there is NEITHER an order NOR a delivery', () => {
59
103
  expect(compile()).toBeNull();
60
104
  expect(compile({ orders: [order('o')] })).not.toBeNull();
@@ -62,51 +106,100 @@ describe('M4 day compile', () => {
62
106
  expect((0, materialized_delivery_compile_helpers_1.compileTenantDeliveryReports)(null)).toBeNull();
63
107
  expect(compile({ tenantId: '' })).toBeNull();
64
108
  });
109
+ it('emits ONE page per entry scope, with the page rules of the discounts split', () => {
110
+ const compiled = compile({
111
+ orders: [order('o1')],
112
+ deliveries: [delivery({ order_id: 'o1' })],
113
+ });
114
+ const byScope = new Map(compiled.entries.map((entry) => [String(entry.scope_context), entry]));
115
+ expect([...byScope.keys()].sort()).toEqual(['localDate', 'localMonth', 'localWeek', 'localWeekOfYear']);
116
+ expect(byScope.get('localDate').page).toBe('all');
117
+ expect(byScope.get('localDate').scope_field).toBe(DAY);
118
+ expect(byScope.get('localWeek').page).toBe(DAY);
119
+ expect(byScope.get('localWeekOfYear').page).toBe(DAY);
120
+ expect(byScope.get('localMonth').page).toBe(DAY);
121
+ expect(byScope.get('localMonth').scope_field).toBe('2026-09');
122
+ // No quarter / semester / year entry document exists at ANY time.
123
+ for (const forbidden of ['localQuarter', 'localSemester', 'localYear']) {
124
+ expect(byScope.has(forbidden)).toBe(false);
125
+ }
126
+ });
127
+ it('a MONTH of closes produces one month page per source day', () => {
128
+ const monthPages = [];
129
+ for (let day = 1; day <= 30; day += 1) {
130
+ const localDate = `2026-09-${String(day).padStart(2, '0')}`;
131
+ const compiled = (0, materialized_delivery_compile_helpers_1.compileTenantDeliveryReports)({
132
+ tenantId: TENANT,
133
+ brandId: BRAND,
134
+ localDate,
135
+ orders: [order(`o-${day}`, { localDate })],
136
+ deliveries: [],
137
+ computedAt: new Date(`${localDate}T23:00:00.000Z`),
138
+ });
139
+ monthPages.push(compiled.entries.find((entry) => String(entry.scope_context) === 'localMonth'));
140
+ }
141
+ expect(monthPages).toHaveLength(30);
142
+ expect(new Set(monthPages.map((page) => page.page)).size).toBe(30);
143
+ expect(new Set(monthPages.map((page) => page.scope_field))).toEqual(new Set(['2026-09']));
144
+ // never one document holding the month's rows
145
+ expect(monthPages.every((page) => page.page !== '2026-09')).toBe(true);
146
+ });
147
+ it('puts the SAME day rows on every page - a page is never a folded period', () => {
148
+ const compiled = compile({
149
+ orders: [order('o1')],
150
+ deliveries: [delivery({ _id: 'd1', order_id: 'o1' })],
151
+ });
152
+ for (const entry of compiled.entries) {
153
+ const rows = Object.values(entry.delivery_entries ?? {}).flatMap((section) => section.rows);
154
+ expect(rows.map((row) => row.delivery_id)).toEqual(['d1']);
155
+ expect(entry.off_app_order_count).toBe(0);
156
+ }
157
+ });
65
158
  it('reports an adoption-POOR day: orders, no deliveries', () => {
66
159
  const compiled = compile({ orders: [order('o1'), order('o2')] });
67
- const counters = compiled.reports[0].delivery_counters['POS_WALK-IN:Istanbul'];
160
+ const counters = compiled.reports[0].delivery_counters['COMPLETED:POS_WALK-IN:Istanbul'];
68
161
  expect(counters.adoption.delivery_order_count).toBe(2);
69
162
  expect(counters.adoption.delivered_via_app_count).toBe(0);
70
163
  // the app has won NOTHING yet - the pool is the whole day.
71
164
  expect(counters.adoption.off_app_count).toBe(2);
72
165
  expect(counters.deliveries.count).toBe(0);
73
166
  // and the entries document carries the count, because off-app orders are not rows.
74
- expect(compiled.entries[0].off_app_order_count).toBe(2);
75
- expect(compiled.entries[0].delivery_entries).toBeNull();
167
+ expect(dayEntry(compiled).off_app_order_count).toBe(2);
168
+ expect(dayEntry(compiled).delivery_entries).toBeNull();
76
169
  });
77
170
  it('reports an adoption-RICH day', () => {
78
171
  const compiled = compile({
79
172
  orders: [order('o1'), order('o2')],
80
173
  deliveries: [delivery({ _id: 'd1', order_id: 'o1' }), delivery({ _id: 'd2', order_id: 'o2' })],
81
174
  });
82
- const counters = compiled.reports[0].delivery_counters['POS_WALK-IN:Istanbul'];
175
+ const counters = compiled.reports[0].delivery_counters['COMPLETED:POS_WALK-IN:Istanbul'];
83
176
  expect(counters.adoption.delivery_order_count).toBe(2);
84
177
  expect(counters.adoption.delivered_via_app_count).toBe(2);
85
178
  expect(counters.adoption.off_app_count).toBe(0);
86
- expect(compiled.entries[0].off_app_order_count).toBe(0);
179
+ expect(dayEntry(compiled).off_app_order_count).toBe(0);
87
180
  });
88
181
  it('keys a delivery on its ORDER, not on the delivery', () => {
89
182
  const compiled = compile({
90
183
  orders: [order('o1', { platform: 'DELIVEROO', delivery_details: { city: 'Ankara', delivery_cost: 500 } })],
91
184
  deliveries: [delivery({ order_id: 'o1' })],
92
185
  });
93
- expect(Object.keys(compiled.reports[0].delivery_counters)).toEqual(['DELIVEROO:Ankara']);
186
+ expect(Object.keys(compiled.reports[0].delivery_counters)).toEqual(['COMPLETED:DELIVEROO:Ankara']);
94
187
  });
95
188
  it('puts a delivery with an unstaged order in UNKNOWN rather than dropping it', () => {
96
189
  const compiled = compile({ deliveries: [delivery({ order_id: 'not-staged' })] });
97
190
  const keys = Object.keys(compiled.reports[0].delivery_counters);
98
- expect(keys).toEqual(['UNKNOWN:UNKNOWN']);
191
+ expect(keys).toEqual(['UNKNOWN:UNKNOWN:UNKNOWN']);
99
192
  // it is a real row a rider performed, so it counts as a delivery...
100
- expect(compiled.reports[0].delivery_counters['UNKNOWN:UNKNOWN'].deliveries.count).toBe(1);
193
+ expect(compiled.reports[0].delivery_counters['UNKNOWN:UNKNOWN:UNKNOWN'].deliveries.count).toBe(1);
101
194
  // ...but it cannot claim adoption for an order we never staged.
102
- expect(compiled.reports[0].delivery_counters['UNKNOWN:UNKNOWN'].adoption.delivery_order_count).toBe(0);
195
+ expect(compiled.reports[0].delivery_counters['UNKNOWN:UNKNOWN:UNKNOWN'].adoption.delivery_order_count).toBe(0);
103
196
  });
104
197
  it('builds statement rows with the joined order fields', () => {
105
198
  const compiled = compile({
106
199
  orders: [order('o1')],
107
200
  deliveries: [delivery({ order_id: 'o1' })],
108
201
  });
109
- const rows = Object.values(compiled.entries[0].delivery_entries).flatMap((section) => section.rows);
202
+ const rows = Object.values(dayEntry(compiled).delivery_entries).flatMap((section) => section.rows);
110
203
  expect(rows).toHaveLength(1);
111
204
  const row = rows[0];
112
205
  expect(row.order_id).toBe('o1');
@@ -125,7 +218,7 @@ describe('M4 day compile', () => {
125
218
  order('o1', {
126
219
  tip_amount: 500,
127
220
  total_discount_applied: 200,
128
- amount_refunded: 100,
221
+ payments: [{ amount_refunded: 60 }, { amount_refunded: 40 }],
129
222
  gst_amount: 300,
130
223
  tax_amount: 100,
131
224
  delivery_details: {
@@ -146,7 +239,7 @@ describe('M4 day compile', () => {
146
239
  }),
147
240
  ],
148
241
  });
149
- const counters = compiled.reports[0].delivery_counters['POS_WALK-IN:Istanbul'];
242
+ const counters = compiled.reports[0].delivery_counters['COMPLETED:POS_WALK-IN:Istanbul'];
150
243
  expect(counters.money.tip_amount).toBe(500);
151
244
  expect(counters.money.discount_amount).toBe(200);
152
245
  expect(counters.money.refund_amount).toBe(100);
@@ -186,7 +279,7 @@ describe('M4 day compile', () => {
186
279
  }),
187
280
  ],
188
281
  });
189
- const timing = compiled.reports[0].delivery_counters['POS_WALK-IN:Istanbul'].timing;
282
+ const timing = compiled.reports[0].delivery_counters['COMPLETED:POS_WALK-IN:Istanbul'].timing;
190
283
  expect(timing.promise_known_count).toBe(1);
191
284
  expect(timing.on_time_count).toBe(1);
192
285
  expect(timing.late_count).toBe(0);
@@ -207,7 +300,7 @@ describe('M4 day compile', () => {
207
300
  const compiled = compile({
208
301
  deliveries: [delivery({ rider_earnings: snapshot(status) })],
209
302
  });
210
- return Object.values(compiled.entries[0].delivery_entries).flatMap((section) => section.rows)[0];
303
+ return Object.values(dayEntry(compiled).delivery_entries).flatMap((section) => section.rows)[0];
211
304
  };
212
305
  expect(rowFor(delivery_1.RIDER_EARNINGS_STATUS_ENUM.PENDING).rider_revenue).toBeNull();
213
306
  expect(rowFor(delivery_1.RIDER_EARNINGS_STATUS_ENUM.FINAL).rider_revenue).toBe(900);
@@ -233,10 +326,173 @@ describe('M4 day compile', () => {
233
326
  });
234
327
  expect(Object.values(final.reports[0].delivery_counters)[0].money.rider_revenue_amount).toBe(900);
235
328
  });
329
+ it('counts ONLY orders that carry delivery_details (DINE / walk-in are excluded)', () => {
330
+ const dineIn = order('dine-1', {
331
+ platform: 'POS_DINE-IN',
332
+ delivery_details: null,
333
+ dinein_details: { floor_id: 'f1', table_id: 't1', table_name: 'T1', num_of_guests: 2 },
334
+ });
335
+ const walkIn = order('walk-1', { platform: 'POS_WALK-IN', delivery_details: null });
336
+ const deliveryOrder = order('delivery-1');
337
+ const compiled = compile({ orders: [dineIn, walkIn, deliveryOrder], deliveries: [] });
338
+ const counters = compiled.reports[0].delivery_counters['COMPLETED:POS_WALK-IN:Istanbul'];
339
+ expect(counters.adoption.delivery_order_count).toBe(1);
340
+ expect(counters.adoption.off_app_count).toBe(1);
341
+ expect(counters.money.net_sale_amount).toBe(5000);
342
+ expect(dayEntry(compiled).off_app_order_count).toBe(1);
343
+ });
344
+ it('keeps the three populations distinct under REASSIGNMENT', () => {
345
+ // o1 was reassigned (two attempts), o2 was delivered once, o3 never reached the app.
346
+ const compiled = compile({
347
+ orders: [order('o1'), order('o2'), order('o3')],
348
+ deliveries: [
349
+ delivery({ _id: 'd1', order_id: 'o1', rider_id: 'rider-1' }),
350
+ delivery({ _id: 'd2', order_id: 'o1', rider_id: 'rider-2', status: 'CANCELLED' }),
351
+ delivery({ _id: 'd3', order_id: 'o2', rider_id: 'rider-1' }),
352
+ ],
353
+ });
354
+ const counters = compiled.reports[0].delivery_counters['COMPLETED:POS_WALK-IN:Istanbul'];
355
+ expect(counters.adoption.delivery_order_count).toBe(3); // unique ORDERS
356
+ expect(counters.adoption.delivered_via_app_count).toBe(2); // unique app orders
357
+ expect(counters.adoption.off_app_count).toBe(1); // o3, never off-app by reassignment
358
+ expect(counters.deliveries.count).toBe(3); // ATTEMPTS, one order contributed two
359
+ expect(counters.deliveries.cancelled_count).toBe(1);
360
+ // and the area row carries the same split.
361
+ expect(counters.areas['Istanbul'].delivery_orders).toBe(3);
362
+ expect(counters.areas['Istanbul'].app_orders).toBe(2);
363
+ expect(counters.areas['Istanbul'].off_app_orders).toBe(1);
364
+ expect(counters.areas['Istanbul'].delivery_records).toBe(3);
365
+ // adoption can never exceed 100 %.
366
+ expect(counters.adoption.delivered_via_app_count).toBeLessThanOrEqual(counters.adoption.delivery_order_count);
367
+ });
368
+ it('caps the RIDER leaderboard at the document level, deterministically', () => {
369
+ const orders = [];
370
+ const deliveries = [];
371
+ for (let index = 1; index <= 51; index += 1) {
372
+ const id = `cap-order-${index}`;
373
+ orders.push(order(id));
374
+ deliveries.push(delivery({
375
+ _id: `cap-delivery-${index}`,
376
+ order_id: id,
377
+ rider_id: `rider-${String(index).padStart(2, '0')}`,
378
+ }));
379
+ }
380
+ const compiled = compile({ orders, deliveries });
381
+ const counters = Object.values(compiled.reports[0].delivery_counters)[0];
382
+ const riderIds = Object.keys(counters.riders);
383
+ expect(riderIds).toHaveLength(51); // top 50 + __OTHER__
384
+ expect(riderIds).toContain('__OTHER__');
385
+ // ties break on rider id ASC, so the LAST rider is the one folded away.
386
+ expect(riderIds).toContain('rider-50');
387
+ expect(riderIds).not.toContain('rider-51');
388
+ expect(counters.riders['__OTHER__'].count).toBe(1);
389
+ expect(counters.deliveries.count).toBe(51);
390
+ });
391
+ it('folds cities beyond the top 50 into __OTHER__, keeping the totals exact', () => {
392
+ const orders = [];
393
+ for (let index = 1; index <= 51; index += 1) {
394
+ orders.push(order(`city-order-${index}`, {
395
+ delivery_details: {
396
+ city: `City-${String(index).padStart(2, '0')}`,
397
+ state: 'State',
398
+ delivery_cost: 300,
399
+ },
400
+ }));
401
+ }
402
+ const compiled = compile({ orders });
403
+ const counters = compiled.reports[0].delivery_counters;
404
+ const keys = Object.keys(counters);
405
+ expect(keys).toHaveLength(51); // top 50 cities + one __OTHER__ key
406
+ expect(keys).toContain('COMPLETED:POS_WALK-IN:__OTHER__');
407
+ expect(counters['COMPLETED:POS_WALK-IN:__OTHER__'].areas['__OTHER__'].delivery_orders).toBe(1);
408
+ const totalOrders = Object.values(counters).reduce((sum, block) => sum + block.adoption.delivery_order_count, 0);
409
+ expect(totalOrders).toBe(51);
410
+ expect(dayEntry(compiled).off_app_order_count).toBe(51);
411
+ });
412
+ it('includes OFF-APP order money in delivery sales, but no app-side payout', () => {
413
+ const compiled = compile({
414
+ orders: [order('o1'), order('o2')],
415
+ // only o1 reached the app; o2 is off-app and must still be a delivery sale.
416
+ deliveries: [delivery({ _id: 'd1', order_id: 'o1' })],
417
+ });
418
+ const counters = compiled.reports[0].delivery_counters['COMPLETED:POS_WALK-IN:Istanbul'];
419
+ // 2 x 5000 cents - the sale exists whether or not the rider app saw it.
420
+ expect(counters.money.net_sale_amount).toBe(10000);
421
+ expect(counters.money.delivery_charge_amount).toBe(600);
422
+ // rider payout comes ONLY from the one app record.
423
+ expect(counters.money.rider_revenue_amount).toBe(700);
424
+ // the off-app order is not a row.
425
+ expect(dayEntry(compiled).off_app_order_count).toBe(1);
426
+ expect(Object.values(dayEntry(compiled).delivery_entries).flatMap((section) => section.rows)).toHaveLength(1);
427
+ });
428
+ it('grades on-time / late ONLY against an explicit ETA', () => {
429
+ const explicit = compile({
430
+ orders: [
431
+ order('o1', {
432
+ delivery_details: {
433
+ city: 'Istanbul',
434
+ state: 'Istanbul',
435
+ delivery_cost: 300,
436
+ estimated_delivery_time: new Date('2026-09-14T10:30:00.000Z'),
437
+ },
438
+ }),
439
+ ],
440
+ deliveries: [delivery({ _id: 'd1', order_id: 'o1', delivered_at: new Date('2026-09-14T10:32:00.000Z') })],
441
+ });
442
+ const timing = Object.values(explicit.reports[0].delivery_counters)[0].timing;
443
+ expect(timing.promise_known_count).toBe(1);
444
+ expect(timing.late_count).toBe(1);
445
+ expect(timing.on_time_count).toBe(0);
446
+ expect(timing.late_minutes_sum).toBe(2);
447
+ // NO ETA anywhere: the delivery is completed but UNGRADED - not counted as on time.
448
+ const asap = compile({
449
+ orders: [order('o1')],
450
+ deliveries: [delivery({ _id: 'd1', order_id: 'o1' })],
451
+ });
452
+ const asapTiming = Object.values(asap.reports[0].delivery_counters)[0].timing;
453
+ expect(asapTiming.promise_known_count).toBe(0);
454
+ expect(asapTiming.on_time_count).toBe(0);
455
+ expect(asapTiming.late_count).toBe(0);
456
+ });
457
+ it('takes the LOCAL HOUR from the joined order, never from the delivery clock', () => {
458
+ const compiled = compile({
459
+ // 02:00 tenant-local, while the delivery document was written at 18:05 UTC.
460
+ orders: [order('o1', { localHour: 2 })],
461
+ deliveries: [
462
+ delivery({
463
+ _id: 'd1',
464
+ order_id: 'o1',
465
+ createdAt: new Date('2026-09-14T18:05:00.000Z'),
466
+ }),
467
+ ],
468
+ });
469
+ const row = Object.values(dayEntry(compiled).delivery_entries)
470
+ .flatMap((section) => section.rows)
471
+ .find((entry) => entry.delivery_id === 'd1');
472
+ // No localMinute on the order: keep the HOUR-ONLY stamp (never a false :00),
473
+ // so the UI's hour-only offset branch stays correct.
474
+ expect(row.local_hour).toBe(DAY + ' 02');
475
+ expect(Object.values(compiled.reports[0].delivery_counters)[0].areas['Istanbul'].by_hour['02']).toBe(1);
476
+ expect(Object.values(compiled.reports[0].delivery_counters)[0].areas['Istanbul'].by_hour['18']).toBeUndefined();
477
+ // A delivery whose order was not staged has NO local hour - not a server-time guess.
478
+ const orphan = compile({ deliveries: [delivery({ _id: 'd2', order_id: 'missing' })] });
479
+ const orphanRow = Object.values(dayEntry(orphan).delivery_entries).flatMap((section) => section.rows)[0];
480
+ expect(orphanRow.local_hour).toBeNull();
481
+ });
482
+ it('counts an orphan delivery as an app RECORD in the UNKNOWN area', () => {
483
+ const compiled = compile({ deliveries: [delivery({ _id: 'd1', order_id: 'missing' })] });
484
+ const counters = compiled.reports[0].delivery_counters['UNKNOWN:UNKNOWN:UNKNOWN'];
485
+ expect(counters.deliveries.count).toBe(1);
486
+ // it cannot be an APP ORDER: adoption is order-based and its order is not staged.
487
+ expect(counters.adoption.delivery_order_count).toBe(0);
488
+ expect(counters.adoption.delivered_via_app_count).toBe(0);
489
+ expect(counters.areas['UNKNOWN'].delivery_records).toBe(1);
490
+ expect(counters.money.net_sale_amount).toBe(0);
491
+ });
236
492
  it('never lets a FOREIGN tenant into the documents', () => {
237
493
  const compiled = compile({
238
494
  orders: [order('o1'), order('o2', { tenant_id: 'someone-else' })],
239
495
  });
240
- expect(compiled.reports[0].delivery_counters['POS_WALK-IN:Istanbul'].adoption.delivery_order_count).toBe(1);
496
+ expect(compiled.reports[0].delivery_counters['COMPLETED:POS_WALK-IN:Istanbul'].adoption.delivery_order_count).toBe(1);
241
497
  });
242
498
  });
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const fs_1 = __importDefault(require("fs"));
7
+ const path_1 = __importDefault(require("path"));
8
+ const delivery_1 = require("../../constants/enums/delivery");
9
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
10
+ const materialized_tenant_delivery_entries_1 = require("../../schemas/models/materialized_tenant_delivery_entries");
11
+ const materialized_tenant_delivery_geo_cells_1 = require("../../schemas/models/materialized_tenant_delivery_geo_cells");
12
+ const materialized_tenant_delivery_reports_1 = require("../../schemas/models/materialized_tenant_delivery_reports");
13
+ const materialized_tenant_reports_iterations_1 = require("../../schemas/models/materialized_tenant_reports_iterations");
14
+ const materialized_report_drilldown_rows_1 = require("../../schemas/models/materialized_report_drilldown_rows");
15
+ const materialized_reports_1 = require("../../helpers/materialized-reports");
16
+ const materialized_delivery_wipe_targets_1 = require("../../helpers/materialized-reports/materialized-delivery-wipe-targets");
17
+ const ROOT = path_1.default.resolve(__dirname, '..', '..', '..');
18
+ const cell = () => (0, materialized_reports_1.compileTenantDeliveryGeoCells)({
19
+ tenantId: 't',
20
+ brandId: 'b',
21
+ localDate: '2026-09-14',
22
+ orders: [
23
+ {
24
+ _id: 'o1',
25
+ tenant_id: 't',
26
+ platform: 'POS_DELIVERY',
27
+ order_status: 'COMPLETED',
28
+ createdAt: new Date('2026-09-14T10:00:00.000Z'),
29
+ localDate: '2026-09-14',
30
+ localHour: 10,
31
+ localMinute: 0,
32
+ net_sale_amount: 1000,
33
+ amount_collected: 1000,
34
+ delivery_details: { city: 'Istanbul', state: 'Istanbul', delivery_cost: 100, lat: 41, lng: 29 },
35
+ },
36
+ ],
37
+ })[0];
38
+ describe('Delivery final-audit invariants', () => {
39
+ it('defines ONE open-status set for statement / volume / summary', () => {
40
+ expect(delivery_1.DELIVERY_OPEN_STATUSES).toEqual([
41
+ delivery_1.DELIVERY_STATUS_ENUM.PENDING,
42
+ delivery_1.DELIVERY_STATUS_ENUM.ASSIGNED,
43
+ delivery_1.DELIVERY_STATUS_ENUM.IN_PROGRESS,
44
+ ]);
45
+ });
46
+ it('disables the map for __OTHER__ with an honest reason and no cells', () => {
47
+ const compiled = cell();
48
+ const response = (0, materialized_reports_1.buildDeliveryGeoResponse)({
49
+ cells: [compiled],
50
+ totalOrders: 10,
51
+ totalAppOrders: 8,
52
+ minOrders: 1,
53
+ mapDisabled: true,
54
+ mapDisabledReason: 'OTHER_AREAS',
55
+ });
56
+ expect(response.cells).toHaveLength(0);
57
+ expect(response.total_orders).toBe(10);
58
+ expect(response.total_app_orders).toBe(8);
59
+ expect(response.map_disabled).toBe(true);
60
+ expect(response.map_disabled_reason).toBe('OTHER_AREAS');
61
+ });
62
+ it('normal geo responses explicitly mark the map available', () => {
63
+ const compiled = cell();
64
+ const response = (0, materialized_reports_1.buildDeliveryGeoResponse)({
65
+ cells: [compiled],
66
+ totalOrders: 1,
67
+ totalAppOrders: 1,
68
+ minOrders: 1,
69
+ });
70
+ expect(response.map_disabled).toBe(false);
71
+ expect(response.map_disabled_reason).toBeNull();
72
+ expect(response.cells.length).toBeGreaterThan(0);
73
+ });
74
+ it('wipes BOTH Delivery report-type iteration rows, tenant-scoped', () => {
75
+ const all = (0, materialized_delivery_wipe_targets_1.buildDeliveryMaterializationWipeTargets)();
76
+ const allIterations = all.find((target) => target.name === materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME);
77
+ expect(allIterations.filter.report_type).toEqual({
78
+ $in: [
79
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DELIVERY_REPORTS,
80
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DELIVERY_ENTRIES,
81
+ ],
82
+ });
83
+ expect(allIterations.filter['snapshot.tenant_id']).toBeUndefined();
84
+ const tenant = (0, materialized_delivery_wipe_targets_1.buildDeliveryMaterializationWipeTargets)('tenant-1');
85
+ expect(tenant.map((target) => target.name)).toEqual(expect.arrayContaining([
86
+ materialized_tenant_delivery_reports_1.MATERIALIZED_TENANT_DELIVERY_REPORTS_COLLECTION_NAME,
87
+ materialized_tenant_delivery_entries_1.MATERIALIZED_TENANT_DELIVERY_ENTRIES_COLLECTION_NAME,
88
+ materialized_tenant_delivery_geo_cells_1.MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_COLLECTION_NAME,
89
+ MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_COLLECTION_NAME,
90
+ materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_NAME,
91
+ materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_NAME,
92
+ materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME,
93
+ ]));
94
+ const tenantIterations = tenant.find((target) => target.name === materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME);
95
+ expect(tenantIterations.filter['snapshot.tenant_id']).toBe('tenant-1');
96
+ for (const target of tenant) {
97
+ if (target.name === materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME)
98
+ continue;
99
+ expect(target.filter.tenant_id).toBe('tenant-1');
100
+ }
101
+ // The wipe never targets a source collection.
102
+ expect(tenant.map((target) => target.name)).not.toContain('orders');
103
+ expect(tenant.map((target) => target.name)).not.toContain('deliveries');
104
+ });
105
+ it('the wipe script uses the shared target builder', () => {
106
+ const source = fs_1.default.readFileSync(path_1.default.join(ROOT, 'scripts', 'wipe-delivery-materialization.ts'), 'utf8');
107
+ expect(source).toContain('buildDeliveryMaterializationWipeTargets');
108
+ expect(source).not.toContain('TENANT_DELIVERY_ENTRIES },\n },');
109
+ });
110
+ it('migration / practical-scale scripts are present and unignored', () => {
111
+ for (const file of [
112
+ 'simulations/migrate-delivery-report-indexes.ts',
113
+ 'simulations/measure-delivery-practical-scale.ts',
114
+ 'scripts/wipe-delivery-materialization.ts',
115
+ ]) {
116
+ expect(fs_1.default.existsSync(path_1.default.join(ROOT, file))).toBe(true);
117
+ }
118
+ const gitignore = fs_1.default.readFileSync(path_1.default.join(ROOT, '.gitignore'), 'utf8');
119
+ expect(gitignore).toContain('!simulations/migrate-delivery-report-indexes.ts');
120
+ expect(gitignore).toContain('!simulations/measure-delivery-practical-scale.ts');
121
+ expect(materialized_reports_1.DELIVERY_MATERIALIZED_COLLECTIONS).toEqual(expect.arrayContaining([
122
+ materialized_tenant_delivery_reports_1.MATERIALIZED_TENANT_DELIVERY_REPORTS_COLLECTION_NAME,
123
+ materialized_tenant_delivery_entries_1.MATERIALIZED_TENANT_DELIVERY_ENTRIES_COLLECTION_NAME,
124
+ materialized_tenant_delivery_geo_cells_1.MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_COLLECTION_NAME,
125
+ MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_COLLECTION_NAME,
126
+ ]));
127
+ });
128
+ });
@@ -3,6 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const delivery_1 = require("../../constants/enums/delivery");
4
4
  const materialized_delivery_classification_helpers_1 = require("../../helpers/materialized-reports/materialized-delivery-classification-helpers");
5
5
  const materialized_delivery_accumulator_helpers_1 = require("../../helpers/materialized-reports/materialized-delivery-accumulator-helpers");
6
+ const materialized_delivery_compile_helpers_1 = require("../../helpers/materialized-reports/materialized-delivery-compile-helpers");
7
+ const materialized_delivery_classification_helpers_2 = require("../../helpers/materialized-reports/materialized-delivery-classification-helpers");
8
+ const materialized_delivery_rows_1 = require("../../helpers/materialized-reports/materialized-delivery-rows");
6
9
  /**
7
10
  * M4 period fold.
8
11
  *
@@ -12,12 +15,24 @@ const materialized_delivery_accumulator_helpers_1 = require("../../helpers/mater
12
15
  * reports a rider as having started later than they did, which is invisible unless a test
13
16
  * deliberately spans two days with the SAME rider.
14
17
  */
15
- const day = (rows) => {
18
+ const day = (rows, orders = []) => {
16
19
  const acc = (0, materialized_delivery_classification_helpers_1.freshDeliveryAccumulator)();
20
+ for (const order of orders)
21
+ (0, materialized_delivery_classification_helpers_1.addDeliveryOrder)(acc, order, 'COMPLETED:POS:Istanbul');
17
22
  for (const row of rows)
18
- (0, materialized_delivery_classification_helpers_1.addDelivery)(acc, row, null, 'POS:Istanbul');
23
+ (0, materialized_delivery_classification_helpers_1.addDelivery)(acc, row, null, 'COMPLETED:POS:Istanbul');
19
24
  return (0, materialized_delivery_classification_helpers_1.finalizeDeliveryAccumulator)(acc);
20
25
  };
26
+ const order = (id, localHour) => ({
27
+ _id: id,
28
+ order_status: 'COMPLETED',
29
+ createdAt: new Date('2026-09-14T10:00:00.000Z'),
30
+ net_sale_amount: 5000,
31
+ amount_collected: 5000,
32
+ localHour,
33
+ delivery_details: { city: 'Istanbul', delivery_cost: 300 },
34
+ localDate: '2026-09-14',
35
+ });
21
36
  const delivery = (over = {}) => ({
22
37
  _id: 'd',
23
38
  order_id: 'o',
@@ -64,11 +79,13 @@ describe('M4 period fold', () => {
64
79
  const second = new Date(backwards.riders['rider-1'].first_delivery_at).toISOString();
65
80
  expect(second).toBe(first);
66
81
  });
67
- it('sums the hour heat map and the distance histogram', () => {
68
- const monday = day([delivery({ _id: 'm', localHour: 10, distance_in_meters_from_store: 1500 })]);
69
- const tuesday = day([delivery({ _id: 't', localHour: 10, distance_in_meters_from_store: 26000 })]);
82
+ it('sums the ORDER-hour demand heat and the distance histogram', () => {
83
+ const monday = day([delivery({ _id: 'm', distance_in_meters_from_store: 1500 })], [order('o-m', 10)]);
84
+ const tuesday = day([delivery({ _id: 't', distance_in_meters_from_store: 26000 })], [order('o-t', 10)]);
70
85
  const folded = (0, materialized_delivery_accumulator_helpers_1.mergeMaterializedDeliveryCounters)(monday, tuesday);
71
86
  expect(folded.areas['Istanbul'].by_hour['10']).toBe(2);
87
+ expect(folded.areas['Istanbul'].delivery_orders).toBe(2);
88
+ expect(folded.areas['Istanbul'].delivery_records).toBe(2);
72
89
  expect(folded.distance.under_2km).toBe(1);
73
90
  expect(folded.distance.over_25km).toBe(1);
74
91
  expect(folded.distance.sum_meters).toBe(27500);
@@ -108,3 +125,23 @@ describe('M4 period fold', () => {
108
125
  expect(() => (0, materialized_delivery_accumulator_helpers_1.mergeMaterializedDeliveryCounters)(day([delivery()]), broken)).not.toThrow();
109
126
  });
110
127
  });
128
+ describe('period area bound', () => {
129
+ it('folds cities beyond the top-N into ORDER_STATUS:PLATFORM:__OTHER__', () => {
130
+ const block = (orders, city) => {
131
+ const counters = (0, materialized_delivery_classification_helpers_2.freshDeliveryCounters)();
132
+ counters.adoption.delivery_order_count = orders;
133
+ const area = (0, materialized_delivery_rows_1.emptyMaterializedDeliveryAreaRow)();
134
+ area.delivery_orders = orders;
135
+ counters.areas = { [city]: area };
136
+ return counters;
137
+ };
138
+ const pruned = (0, materialized_delivery_compile_helpers_1.pruneDocumentDeliveryAreas)({
139
+ 'COMPLETED:POS:A': block(3, 'A'),
140
+ 'COMPLETED:POS:B': block(2, 'B'),
141
+ 'COMPLETED:POS:C': block(1, 'C'),
142
+ }, 2);
143
+ expect(Object.keys(pruned).sort()).toEqual(['COMPLETED:POS:A', 'COMPLETED:POS:B', 'COMPLETED:POS:__OTHER__']);
144
+ expect(pruned['COMPLETED:POS:__OTHER__'].areas['__OTHER__'].delivery_orders).toBe(1);
145
+ expect(pruned['COMPLETED:POS:__OTHER__'].adoption.delivery_order_count).toBe(1);
146
+ });
147
+ });
@@ -25,6 +25,7 @@ const order = (over = {}) => ({
25
25
  net_sale_amount: 5000,
26
26
  amount_collected: 5000,
27
27
  delivery_details: { city: over.city ?? 'Istanbul', delivery_cost: 300 },
28
+ localHour: over.localHour ?? 10,
28
29
  localDate: DAY,
29
30
  ...over,
30
31
  });
@@ -40,7 +41,6 @@ const delivery = (orderId, over = {}) => ({
40
41
  delivered_at: over.delivered_at === undefined ? new Date(DAY + 'T10:32:00.000Z') : over.delivered_at,
41
42
  distance_in_meters_from_store: over.distance ?? 3000,
42
43
  rider_earnings: { amount: over.revenue === undefined ? 700 : over.revenue, status: delivery_1.RIDER_EARNINGS_STATUS_ENUM.FINAL },
43
- localHour: 10,
44
44
  localDate: DAY,
45
45
  ...over,
46
46
  });
@@ -76,6 +76,18 @@ describe('M4 formatter', () => {
76
76
  expect(page.adoption.delivery_orders).toBe(0);
77
77
  expect(page.adoption.adoption_percent).toBeNull();
78
78
  });
79
+ it('reports OPEN as pending + assigned + in-progress (one definition)', () => {
80
+ const first = order();
81
+ const second = order();
82
+ const third = order();
83
+ const page = format([first, second, third], [
84
+ delivery(first._id, { status: 'PENDING' }),
85
+ delivery(second._id, { status: 'ASSIGNED' }),
86
+ delivery(third._id, { status: 'IN_PROGRESS' }),
87
+ ])[0][0];
88
+ expect(page.summary.in_progress).toBe(3);
89
+ expect(page.summary.deliveries).toBe(3);
90
+ });
79
91
  it('reports full adoption and the money join', () => {
80
92
  const o = order();
81
93
  const page = format([o], [delivery(String(o._id))])[0][0];