@managesome/eposmatic-toolkit 0.4.52 → 0.4.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +106 -2
  2. package/esm/constants/enums/delivery.js +13 -0
  3. package/esm/helpers/materialized-reports/index.js +5 -0
  4. package/esm/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +8 -62
  5. package/esm/helpers/materialized-reports/materialized-delivery-classification-helpers.js +95 -73
  6. package/esm/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +118 -146
  7. package/esm/helpers/materialized-reports/materialized-delivery-compile-helpers.js +304 -71
  8. package/esm/helpers/materialized-reports/materialized-delivery-entry-pages.js +307 -0
  9. package/esm/helpers/materialized-reports/materialized-delivery-index-migration.js +103 -0
  10. package/esm/helpers/materialized-reports/materialized-delivery-rows.js +109 -0
  11. package/esm/helpers/materialized-reports/materialized-delivery-wipe-targets.js +32 -0
  12. package/esm/helpers/materialized-reports/materialized-document-size.js +65 -0
  13. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +31 -16
  14. package/esm/helpers/materialized-reports/materialized-integer-contract.js +10 -1
  15. package/esm/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +3 -91
  16. package/esm/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.js +597 -0
  17. package/esm/helpers/materialized-reports/scope-helpers.js +98 -0
  18. package/esm/helpers/materialized-reports/tenant-delivery-formatter.js +70 -20
  19. package/esm/schemas/models/applied_order_discounts.js +103 -0
  20. package/esm/schemas/models/index.js +12 -10
  21. package/esm/schemas/models/materialized_tenant_delivery_entries.js +33 -12
  22. package/esm/schemas/models/materialized_tenant_delivery_geo_cells.js +83 -0
  23. package/esm/schemas/models/materialized_tenant_delivery_geo_scopes.js +35 -0
  24. package/esm/schemas/models/materialized_tenant_delivery_reports.js +10 -1
  25. package/esm/schemas/types/applied_order_discounts.js +1 -0
  26. package/esm/schemas/types/index.js +14 -12
  27. package/esm/schemas/types/materialized_tenant_delivery_geo_cells.js +1 -0
  28. package/esm/schemas/types/materialized_tenant_delivery_geo_scopes.js +1 -0
  29. package/lib/constants/MATERIALIZED_REPORTS.d.ts +95 -1
  30. package/lib/constants/MATERIALIZED_REPORTS.js +108 -4
  31. package/lib/constants/enums/delivery.d.ts +9 -0
  32. package/lib/constants/enums/delivery.js +14 -1
  33. package/lib/helpers/materialized-reports/index.d.ts +5 -0
  34. package/lib/helpers/materialized-reports/index.js +5 -0
  35. package/lib/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +8 -62
  36. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.d.ts +36 -9
  37. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.js +94 -72
  38. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.d.ts +23 -26
  39. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +121 -150
  40. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.d.ts +44 -5
  41. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +306 -69
  42. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.d.ts +128 -0
  43. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.js +322 -0
  44. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.d.ts +48 -0
  45. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.js +108 -0
  46. package/lib/helpers/materialized-reports/materialized-delivery-rows.d.ts +15 -0
  47. package/lib/helpers/materialized-reports/materialized-delivery-rows.js +115 -0
  48. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.d.ts +17 -0
  49. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.js +35 -0
  50. package/lib/helpers/materialized-reports/materialized-document-size.d.ts +47 -0
  51. package/lib/helpers/materialized-reports/materialized-document-size.js +73 -0
  52. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +28 -13
  53. package/lib/helpers/materialized-reports/materialized-integer-contract.js +10 -1
  54. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +2 -90
  55. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.d.ts +186 -0
  56. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.js +620 -0
  57. package/lib/helpers/materialized-reports/scope-helpers.d.ts +8 -0
  58. package/lib/helpers/materialized-reports/scope-helpers.js +99 -0
  59. package/lib/helpers/materialized-reports/tenant-delivery-formatter.d.ts +41 -0
  60. package/lib/helpers/materialized-reports/tenant-delivery-formatter.js +70 -20
  61. package/lib/helpers/order/payment-collection.d.ts +25 -0
  62. package/lib/helpers/order/payment-collection.js +51 -0
  63. package/lib/schemas/models/applied_order_discounts.d.ts +80 -0
  64. package/lib/schemas/models/applied_order_discounts.js +106 -0
  65. package/lib/schemas/models/index.d.ts +12 -10
  66. package/lib/schemas/models/index.js +12 -10
  67. package/lib/schemas/models/materialized_tenant_delivery_entries.d.ts +31 -9
  68. package/lib/schemas/models/materialized_tenant_delivery_entries.js +32 -11
  69. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.d.ts +129 -0
  70. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.js +86 -0
  71. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.d.ts +71 -0
  72. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.js +38 -0
  73. package/lib/schemas/models/materialized_tenant_delivery_reports.d.ts +10 -1
  74. package/lib/schemas/models/materialized_tenant_delivery_reports.js +10 -1
  75. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +15 -15
  76. package/lib/schemas/types/applied_order_discounts.d.ts +22 -0
  77. package/lib/schemas/types/applied_order_discounts.js +2 -0
  78. package/lib/schemas/types/index.d.ts +14 -12
  79. package/lib/schemas/types/index.js +14 -12
  80. package/lib/schemas/types/materialized_tenant_delivery_entries.d.ts +36 -4
  81. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.d.ts +178 -0
  82. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.js +2 -0
  83. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.d.ts +21 -0
  84. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.js +2 -0
  85. package/lib/schemas/types/materialized_tenant_delivery_reports.d.ts +49 -7
  86. package/lib/tests/materialized-reports/analytics-growth-helpers.test.d.ts +1 -0
  87. package/lib/tests/materialized-reports/analytics-overview-helpers.test.d.ts +1 -0
  88. package/lib/tests/materialized-reports/analytics-performance-helpers.test.d.ts +1 -0
  89. package/lib/tests/materialized-reports/materialized-delivery-accumulation.test.js +56 -19
  90. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.d.ts +1 -0
  91. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.js +91 -0
  92. package/lib/tests/materialized-reports/materialized-delivery-compile.test.js +271 -15
  93. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.d.ts +1 -0
  94. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.js +128 -0
  95. package/lib/tests/materialized-reports/materialized-delivery-fold.test.js +42 -5
  96. package/lib/tests/materialized-reports/materialized-delivery-formatter.test.js +13 -1
  97. package/lib/tests/materialized-reports/materialized-delivery-geo.test.d.ts +1 -0
  98. package/lib/tests/materialized-reports/materialized-delivery-geo.test.js +446 -0
  99. package/lib/tests/materialized-reports/materialized-delivery-plan.test.js +117 -25
  100. package/lib/tests/materialized-reports/materialized-delivery-practical.test.d.ts +1 -0
  101. package/lib/tests/materialized-reports/materialized-delivery-practical.test.js +344 -0
  102. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +14 -0
  103. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +1 -1
  104. package/lib/tests/offer-item-resolution.test.js +1 -4
  105. package/lib/tests/payment-collection-timestamps.test.d.ts +1 -0
  106. package/lib/tests/payment-collection-timestamps.test.js +71 -0
  107. package/package.json +4 -2
@@ -0,0 +1,322 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isMaterializedDeliveryEntryScope = isMaterializedDeliveryEntryScope;
4
+ exports.deliveryEntryPageOf = deliveryEntryPageOf;
5
+ exports.deliveryEntryPageBase = deliveryEntryPageBase;
6
+ exports.isDeliveryEntryPageForSourceDay = isDeliveryEntryPageForSourceDay;
7
+ exports.materializedDeliveryEntrySubPage = materializedDeliveryEntrySubPage;
8
+ exports.splitMaterializedDeliveryEntryPage = splitMaterializedDeliveryEntryPage;
9
+ exports.mergeMaterializedDeliveryEntryPages = mergeMaterializedDeliveryEntryPages;
10
+ exports.buildMaterializedDeliveryEntryPageRefs = buildMaterializedDeliveryEntryPageRefs;
11
+ exports.materializedDeliveryEntryPageKey = materializedDeliveryEntryPageKey;
12
+ exports.deliveryMonthScopeFieldsOfDays = deliveryMonthScopeFieldsOfDays;
13
+ exports.buildMaterializedDeliveryDetailsScopeGroups = buildMaterializedDeliveryDetailsScopeGroups;
14
+ exports.resolveMaterializedDeliveryGeoRead = resolveMaterializedDeliveryGeoRead;
15
+ exports.buildMaterializedDeliveryGeoScopeGroups = buildMaterializedDeliveryGeoScopeGroups;
16
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
17
+ const materialized_document_size_1 = require("./materialized-document-size");
18
+ const scope_helpers_1 = require("./scope-helpers");
19
+ /**
20
+ * Delivery ENTRY PAGES — the page identity of `materialized_tenant_delivery_entries`.
21
+ *
22
+ * ## One page per source day
23
+ *
24
+ * The entry collection follows the Discounts split exactly: the report document is
25
+ * counters only, and an entry document is ONE PAGE bounded by ONE source day.
26
+ *
27
+ * | scope | page |
28
+ * | --- | --- |
29
+ * | `localDate` | `'all'` (the scope is already one day) |
30
+ * | `localWeek` | `<source localDate>` |
31
+ * | `localWeekOfYear` | `<source localDate>` |
32
+ * | `localMonth` | `<source localDate>` |
33
+ *
34
+ * There is NO quarter / semester / year entry scope: a whole month of statement rows
35
+ * in one document is exactly the unbounded shape this replaces. A month is covered by
36
+ * its 28-31 pages.
37
+ *
38
+ * An oversized page is split into deterministic `#0`, `#1` sub-pages. The unsuffixed
39
+ * identity is used while the page fits; every sub-page still belongs to the same source
40
+ * day and is unioned by the flat/details and close readers.
41
+ *
42
+ * ## Broad selections
43
+ *
44
+ * A details reader resolves its exact selected DAYS into either the single day group
45
+ * (one day) or the set of MONTH groups that contain them. The pages of those months are
46
+ * scanned, and the rows are filtered to the exact days using each row's
47
+ * `source_local_date` - so a custom multi-month range is exact, not month-rounded.
48
+ */
49
+ /** True when a scope context carries entry pages (day + the three period scopes). */
50
+ function isMaterializedDeliveryEntryScope(scope) {
51
+ return MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_ENTRY_SCOPES.includes(String(scope));
52
+ }
53
+ /**
54
+ * The `page` value a compiled entry document of `scopeContext` must carry for the
55
+ * closing day `localDate`, or null for a scope that carries no entry pages.
56
+ */
57
+ function deliveryEntryPageOf(scopeContext, localDate) {
58
+ const scope = String(scopeContext);
59
+ if (!isMaterializedDeliveryEntryScope(scope))
60
+ return null;
61
+ if (scope === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE) {
62
+ return MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_ENTRY_PAGE_ALL;
63
+ }
64
+ if (typeof localDate !== 'string' || localDate === '')
65
+ return null;
66
+ return localDate;
67
+ }
68
+ const SUB_PAGE_PATTERN = /^(.*)#(\d+)$/;
69
+ /** The unsuffixed source-day page (`all` / `YYYY-MM-DD`). */
70
+ function deliveryEntryPageBase(page) {
71
+ const text = String(page ?? '');
72
+ const match = SUB_PAGE_PATTERN.exec(text);
73
+ return match == null ? text : match[1];
74
+ }
75
+ /** True when a stored page belongs to the source day. */
76
+ function isDeliveryEntryPageForSourceDay(scopeContext, page, localDate) {
77
+ const base = deliveryEntryPageOf(scopeContext, localDate);
78
+ if (base == null)
79
+ return false;
80
+ return deliveryEntryPageBase(page) === base;
81
+ }
82
+ /** The deterministic page identity of one chunk. */
83
+ function materializedDeliveryEntrySubPage(basePage, index) {
84
+ return `${basePage}#${Math.max(0, Math.floor(index))}`;
85
+ }
86
+ /**
87
+ * Splits ONE source-day entry page when it exceeds the 15 MiB budget.
88
+ *
89
+ * Rows are walked in their deterministic key/row order and packed until the next row
90
+ * would cross the budget; the resulting chunks are `page#0`, `page#1`, ... . A page
91
+ * that fits keeps its original identity (no suffix), so existing pages are untouched
92
+ * until they actually grow. The pages are disjoint: every row appears exactly once.
93
+ */
94
+ function splitMaterializedDeliveryEntryPage(doc, maxBytes = MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_ENTRY_MAX_BSON_BYTES) {
95
+ if (doc == null)
96
+ return [];
97
+ if ((0, materialized_document_size_1.materializedDocumentBsonBytes)(doc) <= maxBytes)
98
+ return [doc];
99
+ const sections = doc.delivery_entries ?? null;
100
+ if (sections == null)
101
+ return [doc];
102
+ const basePage = deliveryEntryPageBase(doc.page);
103
+ const baseDoc = { ...doc, page: basePage, delivery_entries: {} };
104
+ const envelopeBytes = (0, materialized_document_size_1.materializedDocumentBsonBytes)(baseDoc);
105
+ const chunks = [];
106
+ let current = {};
107
+ let currentBytes = envelopeBytes;
108
+ let currentRows = 0;
109
+ const flush = () => {
110
+ if (currentRows > 0)
111
+ chunks.push(current);
112
+ current = {};
113
+ currentBytes = envelopeBytes;
114
+ currentRows = 0;
115
+ };
116
+ for (const key of Object.keys(sections)) {
117
+ for (const row of sections[key]?.rows ?? []) {
118
+ const rowBytes = (0, materialized_document_size_1.materializedDocumentBsonBytes)(row) + key.length + 24;
119
+ if (currentRows > 0 && currentBytes + rowBytes > maxBytes - 512)
120
+ flush();
121
+ if (current[key] == null)
122
+ current[key] = { rows: [] };
123
+ current[key].rows.push(row);
124
+ currentBytes += rowBytes;
125
+ currentRows += 1;
126
+ if (currentBytes > maxBytes) {
127
+ throw new Error(`Delivery entry page ${String(doc.scope_context)}:${String(doc.scope_field)}:` +
128
+ `${basePage} cannot split below the budget (one row is too large)`);
129
+ }
130
+ }
131
+ }
132
+ flush();
133
+ if (chunks.length <= 1) {
134
+ const allRows = [];
135
+ for (const key of Object.keys(sections)) {
136
+ for (const row of sections[key]?.rows ?? [])
137
+ allRows.push({ key, row });
138
+ }
139
+ if (allRows.length < 2) {
140
+ throw new Error(`Delivery entry page ${String(doc.scope_context)}:${String(doc.scope_field)}:` +
141
+ `${basePage} is over budget and has no splittable row`);
142
+ }
143
+ const mid = Math.ceil(allRows.length / 2);
144
+ const toChunk = (rows) => {
145
+ const chunk = {};
146
+ for (const { key, row } of rows) {
147
+ if (chunk[key] == null)
148
+ chunk[key] = { rows: [] };
149
+ chunk[key].rows.push(row);
150
+ }
151
+ return chunk;
152
+ };
153
+ chunks.push(toChunk(allRows.slice(0, mid)), toChunk(allRows.slice(mid)));
154
+ }
155
+ return chunks.map((chunk, index) => {
156
+ const page = {
157
+ ...doc,
158
+ page: materializedDeliveryEntrySubPage(basePage, index),
159
+ delivery_entries: chunk,
160
+ };
161
+ if ((0, materialized_document_size_1.materializedDocumentBsonBytes)(page) > maxBytes) {
162
+ throw new Error(`Delivery entry sub-page ${String(doc.scope_context)}:${String(doc.scope_field)}:` +
163
+ `${page.page} exceeds the entry-page budget`);
164
+ }
165
+ return page;
166
+ });
167
+ }
168
+ /**
169
+ * Unions all pages of ONE source day (the base page or its #N sub-pages) into a single
170
+ * logical document. Used by the flat-projection writer and by any in-process details
171
+ * read; rows are disjoint by construction, and the delivery_id/entry_key dedupe makes a
172
+ * duplicate page harmless instead of doubling a row.
173
+ */
174
+ function mergeMaterializedDeliveryEntryPages(pages, identity) {
175
+ const list = (pages ?? []).filter((page) => page != null);
176
+ if (list.length === 0)
177
+ return null;
178
+ const sections = {};
179
+ const seen = new Set();
180
+ let offApp = 0;
181
+ for (const page of list) {
182
+ offApp = Math.max(offApp, Math.max(0, Number(page.off_app_order_count) || 0));
183
+ for (const [key, section] of Object.entries(page.delivery_entries ?? {})) {
184
+ for (const row of section?.rows ?? []) {
185
+ const rowIdentity = String(row.delivery_id ?? row.entry_key ?? '');
186
+ if (rowIdentity !== '') {
187
+ if (seen.has(rowIdentity))
188
+ continue;
189
+ seen.add(rowIdentity);
190
+ }
191
+ if (sections[key] == null)
192
+ sections[key] = { rows: [] };
193
+ sections[key].rows.push(row);
194
+ }
195
+ }
196
+ }
197
+ const first = list[0];
198
+ return {
199
+ ...first,
200
+ ...(identity ?? {}),
201
+ delivery_entries: sections,
202
+ off_app_order_count: offApp,
203
+ };
204
+ }
205
+ /**
206
+ * The BASE page refs belonging to ONE source day. The close reader expands each ref to
207
+ * the base plus any deterministic `#N` sub-pages; no other day's page is ever fetched.
208
+ *
209
+ * Returns null for a malformed date.
210
+ */
211
+ function buildMaterializedDeliveryEntryPageRefs(localDate) {
212
+ const fields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
213
+ if (fields == null)
214
+ return null;
215
+ const refs = [];
216
+ for (const scope of MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_ENTRY_SCOPES) {
217
+ const scopeField = fields[String(scope)];
218
+ const page = deliveryEntryPageOf(scope, localDate);
219
+ if (typeof scopeField !== 'string' || scopeField === '' || page == null)
220
+ return null;
221
+ refs.push({ scope_context: scope, scope_field: scopeField, page });
222
+ }
223
+ return refs;
224
+ }
225
+ /** Stable identity string of one entry page (tests / diagnostics). */
226
+ function materializedDeliveryEntryPageKey(ref) {
227
+ return `${String(ref?.scope_context)}|${String(ref?.scope_field)}|${String(ref?.page)}`;
228
+ }
229
+ /** The distinct `YYYY-MM` scope values of a day set, ascending. */
230
+ function deliveryMonthScopeFieldsOfDays(days) {
231
+ const months = new Set();
232
+ for (const day of days ?? []) {
233
+ const match = /^(\d{4})-(\d{2})-\d{2}$/.exec(String(day));
234
+ if (match == null)
235
+ continue;
236
+ months.add(`${match[1]}-${match[2]}`);
237
+ }
238
+ return [...months].sort();
239
+ }
240
+ /**
241
+ * Resolves the EXACT selected days into the scope groups a DELIVERY DETAILS read uses.
242
+ *
243
+ * - one day -> the `localDate` page (`page='all'`) - the direct path;
244
+ * - many days -> the `localMonth` groups that contain them. The reader scans every page
245
+ * of those months and filters rows to the exact days, so a quarter / semester / year
246
+ * / custom multi-month range is served from monthly pages instead of being refused.
247
+ */
248
+ function buildMaterializedDeliveryDetailsScopeGroups(days) {
249
+ const unique = [...new Set((days ?? []).map((day) => String(day)))].sort();
250
+ if (unique.length === 0)
251
+ return null;
252
+ if (unique.length === 1) {
253
+ return [{ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, scope_field: [unique[0]] }];
254
+ }
255
+ const months = deliveryMonthScopeFieldsOfDays(unique);
256
+ if (months.length === 0)
257
+ return null;
258
+ return [{ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, scope_field: months }];
259
+ }
260
+ const DAY_KEY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
261
+ /** UTC day key — the report's local dates are already tenant-local keys. */
262
+ const utcDayKey = (date) => date.toISOString().slice(0, 10);
263
+ const dayKeyOffset = (day, offsetDays) => {
264
+ const match = DAY_KEY_PATTERN.exec(day);
265
+ if (match == null)
266
+ return null;
267
+ const date = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])));
268
+ if (Number.isNaN(date.getTime()))
269
+ return null;
270
+ date.setUTCDate(date.getUTCDate() + offsetDays);
271
+ return utcDayKey(date);
272
+ };
273
+ /**
274
+ * THE canonical GEO resolver, shared by LIVE and HISTORICAL.
275
+ *
276
+ * - all selected days are inside the DAY-cell retention window -> exact DAY cells;
277
+ * - otherwise -> whole-MONTH cells for every month the selection touches.
278
+ *
279
+ * It never mixes DAY cells for some days with MONTH cells for others. The caller must
280
+ * expose `granularity` / `exact_days` so the UI can say when the map is month-granular.
281
+ */
282
+ function resolveMaterializedDeliveryGeoRead(days, options) {
283
+ const unique = [...new Set((days ?? []).map((day) => String(day)))].sort();
284
+ if (unique.length === 0)
285
+ return null;
286
+ if (unique.some((day) => DAY_KEY_PATTERN.exec(day) == null))
287
+ return null;
288
+ const now = options?.now == null ? new Date() : new Date(options.now);
289
+ if (Number.isNaN(now.getTime()))
290
+ return null;
291
+ const retentionDays = Number.isFinite(Number(options?.retentionDays))
292
+ ? Math.max(0, Math.floor(Number(options?.retentionDays)))
293
+ : MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_GEO_DAY_RETENTION_DAYS;
294
+ const cutoff = dayKeyOffset(utcDayKey(now), -retentionDays);
295
+ if (cutoff == null)
296
+ return null;
297
+ const allWithinRetention = unique.every((day) => day >= cutoff);
298
+ if (allWithinRetention) {
299
+ return {
300
+ groups: [{ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, scope_field: unique }],
301
+ granularity: 'DAY',
302
+ exact_days: true,
303
+ day_cutoff: cutoff,
304
+ };
305
+ }
306
+ const months = deliveryMonthScopeFieldsOfDays(unique);
307
+ if (months.length === 0)
308
+ return null;
309
+ return {
310
+ groups: [{ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, scope_field: months }],
311
+ granularity: 'MONTH',
312
+ exact_days: false,
313
+ day_cutoff: cutoff,
314
+ };
315
+ }
316
+ /**
317
+ * Scope groups for the GEO read. Kept as the public group-only helper; prefer
318
+ * `resolveMaterializedDeliveryGeoRead` when the response must carry granularity.
319
+ */
320
+ function buildMaterializedDeliveryGeoScopeGroups(days) {
321
+ return resolveMaterializedDeliveryGeoRead(days)?.groups ?? null;
322
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Delivery report index migration (pure helper; no automatic execution).
3
+ *
4
+ * Drops the legacy entry identity index and creates the page identity index. Also
5
+ * exposes the owner-approved SOURCE index definition for `deliveries`.
6
+ *
7
+ * The deployable CLI is `simulations/migrate-delivery-report-indexes.ts`; it passes a
8
+ * live Db and `apply`. Tests pass an in-memory Db.
9
+ */
10
+ export declare const DELIVERY_ENTRY_LEGACY_INDEX_NAME = "tenant_id__scope_context__scope_field__day_index";
11
+ export declare const DELIVERY_ENTRY_PAGE_INDEX_NAME = "tenant_id__scope_context__scope_field__page";
12
+ export declare const DELIVERIES_SOURCE_INDEX_NAME = "tenant_id__localDate__updatedAt";
13
+ export declare const DELIVERY_GEO_SCOPE_INDEX_NAME = "tenant_id__scope_context__scope_field";
14
+ export declare const DELIVERY_ENTRY_PAGE_INDEX_KEY: {
15
+ readonly tenant_id: 1;
16
+ readonly scope_context: 1;
17
+ readonly scope_field: 1;
18
+ readonly page: 1;
19
+ };
20
+ /** Approved source index: staging and cross-day reads by order-local day. */
21
+ export declare const DELIVERIES_SOURCE_INDEX_KEY: {
22
+ readonly tenant_id: 1;
23
+ readonly localDate: 1;
24
+ readonly updatedAt: -1;
25
+ };
26
+ /** One cap-metadata document per tenant + geo scope + scope field. */
27
+ export declare const DELIVERY_GEO_SCOPE_INDEX_KEY: {
28
+ readonly tenant_id: 1;
29
+ readonly scope_context: 1;
30
+ readonly scope_field: 1;
31
+ };
32
+ /** Collections the migration/index bootstrap may touch. */
33
+ export declare const DELIVERY_MATERIALIZED_COLLECTIONS: readonly ["materialized_tenant_delivery_reports", "materialized_tenant_delivery_entries", "materialized_tenant_delivery_geo_cells", "materialized_tenant_delivery_geo_scopes"];
34
+ export interface IDeliveryIndexMigrationPlan {
35
+ legacyEntryIndex: string | null;
36
+ createEntryPageIndex: boolean;
37
+ createSourceIndex: boolean;
38
+ createGeoScopeIndex: boolean;
39
+ }
40
+ /** Inspect the indexes without mutating anything. */
41
+ export declare function planDeliveryReportIndexMigration(db: any): Promise<IDeliveryIndexMigrationPlan>;
42
+ /**
43
+ * Apply the migration. Caller must have a backup and must NOT run this during a close.
44
+ * Idempotent: a missing legacy index is a no-op; createIndex is idempotent by name/key.
45
+ */
46
+ export declare function migrateDeliveryReportIndexes(db: any, options: {
47
+ apply: boolean;
48
+ }): Promise<IDeliveryIndexMigrationPlan>;
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DELIVERY_MATERIALIZED_COLLECTIONS = exports.DELIVERY_GEO_SCOPE_INDEX_KEY = exports.DELIVERIES_SOURCE_INDEX_KEY = exports.DELIVERY_ENTRY_PAGE_INDEX_KEY = exports.DELIVERY_GEO_SCOPE_INDEX_NAME = exports.DELIVERIES_SOURCE_INDEX_NAME = exports.DELIVERY_ENTRY_PAGE_INDEX_NAME = exports.DELIVERY_ENTRY_LEGACY_INDEX_NAME = void 0;
4
+ exports.planDeliveryReportIndexMigration = planDeliveryReportIndexMigration;
5
+ exports.migrateDeliveryReportIndexes = migrateDeliveryReportIndexes;
6
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
7
+ const materialized_tenant_delivery_entries_1 = require("../../schemas/models/materialized_tenant_delivery_entries");
8
+ const materialized_tenant_delivery_geo_cells_1 = require("../../schemas/models/materialized_tenant_delivery_geo_cells");
9
+ const materialized_tenant_delivery_reports_1 = require("../../schemas/models/materialized_tenant_delivery_reports");
10
+ /**
11
+ * Delivery report index migration (pure helper; no automatic execution).
12
+ *
13
+ * Drops the legacy entry identity index and creates the page identity index. Also
14
+ * exposes the owner-approved SOURCE index definition for `deliveries`.
15
+ *
16
+ * The deployable CLI is `simulations/migrate-delivery-report-indexes.ts`; it passes a
17
+ * live Db and `apply`. Tests pass an in-memory Db.
18
+ */
19
+ exports.DELIVERY_ENTRY_LEGACY_INDEX_NAME = 'tenant_id__scope_context__scope_field__day_index';
20
+ exports.DELIVERY_ENTRY_PAGE_INDEX_NAME = 'tenant_id__scope_context__scope_field__page';
21
+ exports.DELIVERIES_SOURCE_INDEX_NAME = 'tenant_id__localDate__updatedAt';
22
+ exports.DELIVERY_GEO_SCOPE_INDEX_NAME = 'tenant_id__scope_context__scope_field';
23
+ exports.DELIVERY_ENTRY_PAGE_INDEX_KEY = {
24
+ tenant_id: 1,
25
+ scope_context: 1,
26
+ scope_field: 1,
27
+ page: 1,
28
+ };
29
+ /** Approved source index: staging and cross-day reads by order-local day. */
30
+ exports.DELIVERIES_SOURCE_INDEX_KEY = {
31
+ tenant_id: 1,
32
+ localDate: 1,
33
+ updatedAt: -1,
34
+ };
35
+ /** One cap-metadata document per tenant + geo scope + scope field. */
36
+ exports.DELIVERY_GEO_SCOPE_INDEX_KEY = {
37
+ tenant_id: 1,
38
+ scope_context: 1,
39
+ scope_field: 1,
40
+ };
41
+ /** Collections the migration/index bootstrap may touch. */
42
+ exports.DELIVERY_MATERIALIZED_COLLECTIONS = [
43
+ materialized_tenant_delivery_reports_1.MATERIALIZED_TENANT_DELIVERY_REPORTS_COLLECTION_NAME,
44
+ materialized_tenant_delivery_entries_1.MATERIALIZED_TENANT_DELIVERY_ENTRIES_COLLECTION_NAME,
45
+ materialized_tenant_delivery_geo_cells_1.MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_COLLECTION_NAME,
46
+ MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_COLLECTION_NAME,
47
+ ];
48
+ /** Create a collection if it does not exist; tolerate NamespaceExists (code 48). */
49
+ async function ensureCollection(db, name) {
50
+ try {
51
+ await db.createCollection(name);
52
+ }
53
+ catch (error) {
54
+ if (Number(error?.code) !== 48)
55
+ throw error;
56
+ }
57
+ }
58
+ /** Inspect the indexes without mutating anything. */
59
+ async function planDeliveryReportIndexMigration(db) {
60
+ const existing = await db
61
+ .collection(materialized_tenant_delivery_entries_1.MATERIALIZED_TENANT_DELIVERY_ENTRIES_COLLECTION_NAME)
62
+ .listIndexes()
63
+ .toArray()
64
+ .catch(() => []);
65
+ const legacy = existing.find((index) => index.name === exports.DELIVERY_ENTRY_LEGACY_INDEX_NAME ||
66
+ (index.unique === true &&
67
+ index.key?.tenant_id === 1 &&
68
+ index.key?.scope_context === 1 &&
69
+ index.key?.scope_field === 1 &&
70
+ index.key?.day_index === 1 &&
71
+ index.key?.page == null));
72
+ return {
73
+ legacyEntryIndex: legacy?.name ?? null,
74
+ createEntryPageIndex: true,
75
+ createSourceIndex: true,
76
+ createGeoScopeIndex: true,
77
+ };
78
+ }
79
+ /**
80
+ * Apply the migration. Caller must have a backup and must NOT run this during a close.
81
+ * Idempotent: a missing legacy index is a no-op; createIndex is idempotent by name/key.
82
+ */
83
+ async function migrateDeliveryReportIndexes(db, options) {
84
+ const plan = await planDeliveryReportIndexMigration(db);
85
+ if (!options.apply)
86
+ return plan;
87
+ for (const collectionName of exports.DELIVERY_MATERIALIZED_COLLECTIONS) {
88
+ await ensureCollection(db, collectionName);
89
+ }
90
+ const entries = db.collection(materialized_tenant_delivery_entries_1.MATERIALIZED_TENANT_DELIVERY_ENTRIES_COLLECTION_NAME);
91
+ if (plan.legacyEntryIndex != null) {
92
+ await entries.dropIndex(plan.legacyEntryIndex);
93
+ }
94
+ await entries.createIndex(exports.DELIVERY_ENTRY_PAGE_INDEX_KEY, {
95
+ name: exports.DELIVERY_ENTRY_PAGE_INDEX_NAME,
96
+ unique: true,
97
+ });
98
+ await db.collection('deliveries').createIndex(exports.DELIVERIES_SOURCE_INDEX_KEY, {
99
+ name: exports.DELIVERIES_SOURCE_INDEX_NAME,
100
+ });
101
+ await db
102
+ .collection(MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_COLLECTION_NAME)
103
+ .createIndex(exports.DELIVERY_GEO_SCOPE_INDEX_KEY, {
104
+ name: exports.DELIVERY_GEO_SCOPE_INDEX_NAME,
105
+ unique: true,
106
+ });
107
+ return plan;
108
+ }
@@ -0,0 +1,15 @@
1
+ import { IMaterializedDeliveryAreaRow, IMaterializedDeliveryRiderRow } from '../../schemas/types/materialized_tenant_delivery_reports';
2
+ /** A zeroed rider row. */
3
+ export declare function emptyMaterializedDeliveryRiderRow(riderName?: string | null): IMaterializedDeliveryRiderRow;
4
+ /** A zeroed area row. */
5
+ export declare function emptyMaterializedDeliveryAreaRow(): IMaterializedDeliveryAreaRow;
6
+ /** Merges one rider row into another, MIN/MAX on the tenure bounds. */
7
+ export declare function mergeMaterializedDeliveryRiderRow(target: IMaterializedDeliveryRiderRow, source: IMaterializedDeliveryRiderRow): void;
8
+ /**
9
+ * Merges one AREA row into another.
10
+ *
11
+ * Both populations are additive within an area: order-side figures count every delivery
12
+ * order (off-app included) and app-side figures count delivery records. `by_hour` is the
13
+ * order-demand histogram, so it sums too.
14
+ */
15
+ export declare function mergeMaterializedDeliveryAreaRow(target: IMaterializedDeliveryAreaRow, source: IMaterializedDeliveryAreaRow): void;
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.emptyMaterializedDeliveryRiderRow = emptyMaterializedDeliveryRiderRow;
4
+ exports.emptyMaterializedDeliveryAreaRow = emptyMaterializedDeliveryAreaRow;
5
+ exports.mergeMaterializedDeliveryRiderRow = mergeMaterializedDeliveryRiderRow;
6
+ exports.mergeMaterializedDeliveryAreaRow = mergeMaterializedDeliveryAreaRow;
7
+ /**
8
+ * Row helpers for the two BOUNDED leaderboards of a delivery report document.
9
+ *
10
+ * ## Bounded, and honest about it
11
+ *
12
+ * `riders` and `areas` are keyed maps whose key space is unbounded in principle (rider
13
+ * churn, city sprawl). Each is capped, and the tail is NOT dropped: it is folded into a
14
+ * single `__OTHER__` row, so the leaderboard still reconciles against the document
15
+ * totals.
16
+ *
17
+ * ## Deterministic order
18
+ *
19
+ * The top-N is ranked `count DESC, key ASC`. Without the key tie-break two closes of the
20
+ * same day could keep different rows (and different `__OTHER__` sums), which would make
21
+ * `iteration` churn on an unchanged day.
22
+ *
23
+ * ## MIN/MAX tenure bounds
24
+ *
25
+ * A rider row carries `first_delivery_at` / `last_delivery_at`. When two rows are merged
26
+ * (a period fold, or the `__OTHER__` fold) the bounds must stay a MINIMUM and a MAXIMUM -
27
+ * summing them, or keeping the newest value, would report a rider's tenure as starting
28
+ * after it did.
29
+ */
30
+ const num = (value) => Number(value) || 0;
31
+ const earlierOf = (current, candidate) => {
32
+ const time = candidate == null ? NaN : new Date(candidate).getTime();
33
+ if (Number.isNaN(time))
34
+ return current;
35
+ if (current == null || time < new Date(current).getTime())
36
+ return new Date(time);
37
+ return current;
38
+ };
39
+ const laterOf = (current, candidate) => {
40
+ const time = candidate == null ? NaN : new Date(candidate).getTime();
41
+ if (Number.isNaN(time))
42
+ return current;
43
+ if (current == null || time > new Date(current).getTime())
44
+ return new Date(time);
45
+ return current;
46
+ };
47
+ /** A zeroed rider row. */
48
+ function emptyMaterializedDeliveryRiderRow(riderName = null) {
49
+ return {
50
+ rider_name: riderName,
51
+ count: 0,
52
+ completed_count: 0,
53
+ cancelled_count: 0,
54
+ in_progress_count: 0,
55
+ rider_revenue_amount: 0,
56
+ distance_sum_meters: 0,
57
+ first_delivery_at: null,
58
+ last_delivery_at: null,
59
+ };
60
+ }
61
+ /** A zeroed area row. */
62
+ function emptyMaterializedDeliveryAreaRow() {
63
+ return {
64
+ delivery_orders: 0,
65
+ app_orders: 0,
66
+ off_app_orders: 0,
67
+ delivery_records: 0,
68
+ completed_count: 0,
69
+ cancelled_count: 0,
70
+ net_sale_amount: 0,
71
+ delivery_charge_amount: 0,
72
+ rider_revenue_amount: 0,
73
+ distance_sum_meters: 0,
74
+ by_hour: {},
75
+ };
76
+ }
77
+ /** Merges one rider row into another, MIN/MAX on the tenure bounds. */
78
+ function mergeMaterializedDeliveryRiderRow(target, source) {
79
+ target.count += num(source?.count);
80
+ target.completed_count += num(source?.completed_count);
81
+ target.cancelled_count += num(source?.cancelled_count);
82
+ target.in_progress_count += num(source?.in_progress_count);
83
+ target.rider_revenue_amount += num(source?.rider_revenue_amount);
84
+ target.distance_sum_meters += num(source?.distance_sum_meters);
85
+ target.rider_name ?? (target.rider_name = source?.rider_name ?? null);
86
+ // MIN / MAX - never a sum, and never just the newest document value.
87
+ target.first_delivery_at = earlierOf(target.first_delivery_at, source?.first_delivery_at);
88
+ target.last_delivery_at = laterOf(target.last_delivery_at, source?.last_delivery_at);
89
+ }
90
+ /**
91
+ * Merges one AREA row into another.
92
+ *
93
+ * Both populations are additive within an area: order-side figures count every delivery
94
+ * order (off-app included) and app-side figures count delivery records. `by_hour` is the
95
+ * order-demand histogram, so it sums too.
96
+ */
97
+ function mergeMaterializedDeliveryAreaRow(target, source) {
98
+ target.delivery_orders += num(source?.delivery_orders);
99
+ target.app_orders += num(source?.app_orders);
100
+ target.off_app_orders += num(source?.off_app_orders);
101
+ // Historical tolerance: documents written before the area row split stored the
102
+ // delivery-record count as `count`. Reading both keeps a period fold exact across the
103
+ // schema boundary instead of silently dropping the old days' records.
104
+ target.delivery_records += num(source?.delivery_records ?? source?.count);
105
+ target.completed_count += num(source?.completed_count);
106
+ target.cancelled_count += num(source?.cancelled_count);
107
+ target.net_sale_amount += num(source?.net_sale_amount);
108
+ target.delivery_charge_amount += num(source?.delivery_charge_amount);
109
+ target.rider_revenue_amount += num(source?.rider_revenue_amount);
110
+ target.distance_sum_meters += num(source?.distance_sum_meters);
111
+ target.by_hour ?? (target.by_hour = {});
112
+ for (const [hour, value] of Object.entries(source?.by_hour ?? {})) {
113
+ target.by_hour[hour] = num(target.by_hour[hour]) + num(value);
114
+ }
115
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Every collection/filter a Delivery materialization wipe must clear.
3
+ *
4
+ * The wipe is PRE-LAUNCH: v1/v2 documents are not upgraded. It must remove BOTH
5
+ * Delivery report-type iteration rows and scope them to the selected tenant when
6
+ * `--tenant` is supplied. The iteration row has no tenant_id of its own; the
7
+ * snapshot carries the document's tenant_id, so the filter is
8
+ * `snapshot.tenant_id`.
9
+ *
10
+ * Pure data (no mongoose / no DB access) so the filter list is unit-testable
11
+ * without a database.
12
+ */
13
+ export interface IDeliveryMaterializationWipeTarget {
14
+ name: string;
15
+ filter: Record<string, unknown>;
16
+ }
17
+ export declare function buildDeliveryMaterializationWipeTargets(tenantId?: string | null): IDeliveryMaterializationWipeTarget[];
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildDeliveryMaterializationWipeTargets = buildDeliveryMaterializationWipeTargets;
4
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
5
+ const materialized_report_drilldown_rows_1 = require("../../schemas/models/materialized_report_drilldown_rows");
6
+ const materialized_tenant_delivery_entries_1 = require("../../schemas/models/materialized_tenant_delivery_entries");
7
+ const materialized_tenant_delivery_geo_cells_1 = require("../../schemas/models/materialized_tenant_delivery_geo_cells");
8
+ const materialized_tenant_delivery_reports_1 = require("../../schemas/models/materialized_tenant_delivery_reports");
9
+ const materialized_tenant_reports_iterations_1 = require("../../schemas/models/materialized_tenant_reports_iterations");
10
+ function buildDeliveryMaterializationWipeTargets(tenantId) {
11
+ const selectedTenant = typeof tenantId === 'string' && tenantId.trim() !== '' ? tenantId.trim() : null;
12
+ const tenantFilter = selectedTenant == null ? {} : { tenant_id: selectedTenant };
13
+ const flatFilter = {
14
+ report_type: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DELIVERY_ENTRIES,
15
+ ...tenantFilter,
16
+ };
17
+ const iterationFilter = {
18
+ report_type: {
19
+ $in: [
20
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DELIVERY_REPORTS,
21
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DELIVERY_ENTRIES,
22
+ ],
23
+ },
24
+ ...(selectedTenant == null ? {} : { 'snapshot.tenant_id': selectedTenant }),
25
+ };
26
+ return [
27
+ { name: materialized_tenant_delivery_reports_1.MATERIALIZED_TENANT_DELIVERY_REPORTS_COLLECTION_NAME, filter: tenantFilter },
28
+ { name: materialized_tenant_delivery_entries_1.MATERIALIZED_TENANT_DELIVERY_ENTRIES_COLLECTION_NAME, filter: tenantFilter },
29
+ { name: materialized_tenant_delivery_geo_cells_1.MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_COLLECTION_NAME, filter: tenantFilter },
30
+ { name: MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_COLLECTION_NAME, filter: tenantFilter },
31
+ { name: materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_NAME, filter: flatFilter },
32
+ { name: materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_NAME, filter: flatFilter },
33
+ { name: materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME, filter: iterationFilter },
34
+ ];
35
+ }