@managesome/eposmatic-toolkit 0.4.51 → 0.4.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +106 -2
  2. package/esm/constants/enums/delivery.js +13 -0
  3. package/esm/helpers/materialized-reports/index.js +5 -0
  4. package/esm/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +8 -62
  5. package/esm/helpers/materialized-reports/materialized-delivery-classification-helpers.js +95 -73
  6. package/esm/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +118 -146
  7. package/esm/helpers/materialized-reports/materialized-delivery-compile-helpers.js +304 -71
  8. package/esm/helpers/materialized-reports/materialized-delivery-entry-pages.js +307 -0
  9. package/esm/helpers/materialized-reports/materialized-delivery-index-migration.js +103 -0
  10. package/esm/helpers/materialized-reports/materialized-delivery-rows.js +109 -0
  11. package/esm/helpers/materialized-reports/materialized-delivery-wipe-targets.js +32 -0
  12. package/esm/helpers/materialized-reports/materialized-document-size.js +65 -0
  13. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +31 -16
  14. package/esm/helpers/materialized-reports/materialized-integer-contract.js +10 -1
  15. package/esm/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +3 -91
  16. package/esm/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.js +597 -0
  17. package/esm/helpers/materialized-reports/scope-helpers.js +98 -0
  18. package/esm/helpers/materialized-reports/tenant-delivery-formatter.js +70 -20
  19. package/esm/helpers/utils/offer-item-resolution.js +39 -0
  20. package/esm/schemas/models/index.js +12 -10
  21. package/esm/schemas/models/materialized_tenant_delivery_entries.js +33 -12
  22. package/esm/schemas/models/materialized_tenant_delivery_geo_cells.js +83 -0
  23. package/esm/schemas/models/materialized_tenant_delivery_geo_scopes.js +35 -0
  24. package/esm/schemas/models/materialized_tenant_delivery_reports.js +10 -1
  25. package/esm/schemas/types/index.js +14 -12
  26. package/esm/schemas/types/materialized_tenant_delivery_geo_cells.js +1 -0
  27. package/esm/schemas/types/materialized_tenant_delivery_geo_scopes.js +1 -0
  28. package/lib/constants/MATERIALIZED_REPORTS.d.ts +95 -1
  29. package/lib/constants/MATERIALIZED_REPORTS.js +108 -4
  30. package/lib/constants/enums/delivery.d.ts +9 -0
  31. package/lib/constants/enums/delivery.js +14 -1
  32. package/lib/helpers/materialized-reports/index.d.ts +5 -0
  33. package/lib/helpers/materialized-reports/index.js +5 -0
  34. package/lib/helpers/materialized-reports/materialized-delivery-accumulator-helpers.js +8 -62
  35. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.d.ts +36 -9
  36. package/lib/helpers/materialized-reports/materialized-delivery-classification-helpers.js +94 -72
  37. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.d.ts +23 -26
  38. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +121 -150
  39. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.d.ts +44 -5
  40. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +306 -69
  41. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.d.ts +128 -0
  42. package/lib/helpers/materialized-reports/materialized-delivery-entry-pages.js +322 -0
  43. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.d.ts +48 -0
  44. package/lib/helpers/materialized-reports/materialized-delivery-index-migration.js +108 -0
  45. package/lib/helpers/materialized-reports/materialized-delivery-rows.d.ts +15 -0
  46. package/lib/helpers/materialized-reports/materialized-delivery-rows.js +115 -0
  47. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.d.ts +17 -0
  48. package/lib/helpers/materialized-reports/materialized-delivery-wipe-targets.js +35 -0
  49. package/lib/helpers/materialized-reports/materialized-document-size.d.ts +47 -0
  50. package/lib/helpers/materialized-reports/materialized-document-size.js +73 -0
  51. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +28 -13
  52. package/lib/helpers/materialized-reports/materialized-integer-contract.js +10 -1
  53. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +2 -90
  54. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.d.ts +186 -0
  55. package/lib/helpers/materialized-reports/materialized-tenant-delivery-geo-helpers.js +620 -0
  56. package/lib/helpers/materialized-reports/scope-helpers.d.ts +8 -0
  57. package/lib/helpers/materialized-reports/scope-helpers.js +99 -0
  58. package/lib/helpers/materialized-reports/tenant-delivery-formatter.d.ts +41 -0
  59. package/lib/helpers/materialized-reports/tenant-delivery-formatter.js +70 -20
  60. package/lib/helpers/utils/offer-item-resolution.d.ts +28 -0
  61. package/lib/helpers/utils/offer-item-resolution.js +41 -0
  62. package/lib/schemas/models/index.d.ts +12 -10
  63. package/lib/schemas/models/index.js +12 -10
  64. package/lib/schemas/models/materialized_tenant_delivery_entries.d.ts +31 -9
  65. package/lib/schemas/models/materialized_tenant_delivery_entries.js +32 -11
  66. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.d.ts +129 -0
  67. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.js +86 -0
  68. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.d.ts +71 -0
  69. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.js +38 -0
  70. package/lib/schemas/models/materialized_tenant_delivery_reports.d.ts +10 -1
  71. package/lib/schemas/models/materialized_tenant_delivery_reports.js +10 -1
  72. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +15 -15
  73. package/lib/schemas/types/index.d.ts +14 -12
  74. package/lib/schemas/types/index.js +14 -12
  75. package/lib/schemas/types/materialized_tenant_delivery_entries.d.ts +36 -4
  76. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.d.ts +178 -0
  77. package/lib/schemas/types/materialized_tenant_delivery_geo_cells.js +2 -0
  78. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.d.ts +21 -0
  79. package/lib/schemas/types/materialized_tenant_delivery_geo_scopes.js +2 -0
  80. package/lib/schemas/types/materialized_tenant_delivery_reports.d.ts +49 -7
  81. package/lib/tests/materialized-reports/materialized-delivery-accumulation.test.js +56 -19
  82. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.d.ts +1 -0
  83. package/lib/tests/materialized-reports/materialized-delivery-budgets.test.js +91 -0
  84. package/lib/tests/materialized-reports/materialized-delivery-compile.test.js +271 -15
  85. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.d.ts +1 -0
  86. package/lib/tests/materialized-reports/materialized-delivery-final-audit.test.js +128 -0
  87. package/lib/tests/materialized-reports/materialized-delivery-fold.test.js +42 -5
  88. package/lib/tests/materialized-reports/materialized-delivery-formatter.test.js +13 -1
  89. package/lib/tests/materialized-reports/materialized-delivery-geo.test.d.ts +1 -0
  90. package/lib/tests/materialized-reports/materialized-delivery-geo.test.js +446 -0
  91. package/lib/tests/materialized-reports/materialized-delivery-plan.test.js +117 -25
  92. package/lib/tests/materialized-reports/materialized-delivery-practical.test.d.ts +1 -0
  93. package/lib/tests/materialized-reports/materialized-delivery-practical.test.js +344 -0
  94. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +14 -0
  95. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +1 -1
  96. package/lib/tests/offer-item-resolution.test.js +57 -0
  97. package/package.json +4 -2
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The BSON SIZE BUDGET of a materialized report/entry/geo document.
3
+ *
4
+ * ## Why compile-time, and why PER COLLECTION
5
+ *
6
+ * MongoDB rejects a document above 16 MiB. Without a guard, an entry page that folded
7
+ * one delivery row too many would fail at `insert`/`bulkWrite` time - i.e. in the middle
8
+ * of the day-close transaction, after the counters and iterations had been computed,
9
+ * with a server-side "object too large" error that names nothing.
10
+ *
11
+ * The guard moves that failure to the COMPILE, names the collection (and, for an entry
12
+ * page, the day and scope), and uses a PRACTICAL budget per collection rather than one
13
+ * global "almost 16 MiB" target:
14
+ *
15
+ * - `MATERIALIZED_DELIVERY_REPORT_MAX_BSON_BYTES` (15 MiB) - counters only;
16
+ * - `MATERIALIZED_DELIVERY_ENTRY_MAX_BSON_BYTES` (15 MiB) - ONE source day's page
17
+ * (oversized pages split into deterministic `#0`, `#1` sub-pages);
18
+ * - `MATERIALIZED_DELIVERY_GEO_CELL_MAX_BSON_BYTES` (2 MiB) - one H3 cell.
19
+ *
20
+ * `maxBytes` is REQUIRED: a caller must choose the budget that belongs to its document
21
+ * shape, so a new collection cannot silently inherit the wrong one.
22
+ *
23
+ * ## What it measures
24
+ *
25
+ * The exact BSON encoding MongoDB would store (`BSON.calculateObjectSize`), not
26
+ * `JSON.stringify` - a JSON estimate is meaningless for Dates/ObjectIds and misses the
27
+ * type tags that make up a large part of a materialized document.
28
+ */
29
+ /** The measured size of one document, in bytes. */
30
+ export declare function materializedDocumentBsonBytes(document: unknown): number;
31
+ export interface IMaterializedDocumentSizeContext {
32
+ /** Collection the document is destined for (named in the error). */
33
+ collection?: string;
34
+ /** Optional label (`materialized_tenant_delivery_entries:2026-09-10:localMonth:2026-09`). */
35
+ label?: string;
36
+ /** REQUIRED budget, in bytes - one of the named per-collection constants. */
37
+ maxBytes: number;
38
+ }
39
+ /**
40
+ * Throws when ONE document exceeds its budget.
41
+ *
42
+ * The message carries the label/collection, the budget and the actual size, so a writer
43
+ * that produced the document can be found from the error alone.
44
+ */
45
+ export declare function assertMaterializedDocumentSize(document: unknown, context: IMaterializedDocumentSizeContext): void;
46
+ /** Asserts a whole SET of documents (a scope, a plan, a batch) in one call. */
47
+ export declare function assertMaterializedDocumentsSize(documents: readonly unknown[] | null | undefined, context: IMaterializedDocumentSizeContext): void;
@@ -0,0 +1,73 @@
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
+ exports.materializedDocumentBsonBytes = materializedDocumentBsonBytes;
7
+ exports.assertMaterializedDocumentSize = assertMaterializedDocumentSize;
8
+ exports.assertMaterializedDocumentsSize = assertMaterializedDocumentsSize;
9
+ const mongoose_1 = __importDefault(require("mongoose"));
10
+ /**
11
+ * The BSON SIZE BUDGET of a materialized report/entry/geo document.
12
+ *
13
+ * ## Why compile-time, and why PER COLLECTION
14
+ *
15
+ * MongoDB rejects a document above 16 MiB. Without a guard, an entry page that folded
16
+ * one delivery row too many would fail at `insert`/`bulkWrite` time - i.e. in the middle
17
+ * of the day-close transaction, after the counters and iterations had been computed,
18
+ * with a server-side "object too large" error that names nothing.
19
+ *
20
+ * The guard moves that failure to the COMPILE, names the collection (and, for an entry
21
+ * page, the day and scope), and uses a PRACTICAL budget per collection rather than one
22
+ * global "almost 16 MiB" target:
23
+ *
24
+ * - `MATERIALIZED_DELIVERY_REPORT_MAX_BSON_BYTES` (15 MiB) - counters only;
25
+ * - `MATERIALIZED_DELIVERY_ENTRY_MAX_BSON_BYTES` (15 MiB) - ONE source day's page
26
+ * (oversized pages split into deterministic `#0`, `#1` sub-pages);
27
+ * - `MATERIALIZED_DELIVERY_GEO_CELL_MAX_BSON_BYTES` (2 MiB) - one H3 cell.
28
+ *
29
+ * `maxBytes` is REQUIRED: a caller must choose the budget that belongs to its document
30
+ * shape, so a new collection cannot silently inherit the wrong one.
31
+ *
32
+ * ## What it measures
33
+ *
34
+ * The exact BSON encoding MongoDB would store (`BSON.calculateObjectSize`), not
35
+ * `JSON.stringify` - a JSON estimate is meaningless for Dates/ObjectIds and misses the
36
+ * type tags that make up a large part of a materialized document.
37
+ */
38
+ /** The measured size of one document, in bytes. */
39
+ function materializedDocumentBsonBytes(document) {
40
+ if (document == null)
41
+ return 0;
42
+ return mongoose_1.default.mongo.BSON.calculateObjectSize(document);
43
+ }
44
+ /**
45
+ * Throws when ONE document exceeds its budget.
46
+ *
47
+ * The message carries the label/collection, the budget and the actual size, so a writer
48
+ * that produced the document can be found from the error alone.
49
+ */
50
+ function assertMaterializedDocumentSize(document, context) {
51
+ if (context == null || !Number.isFinite(context.maxBytes) || context.maxBytes <= 0) {
52
+ throw new Error('assertMaterializedDocumentSize: an explicit maxBytes budget is required');
53
+ }
54
+ const budget = context.maxBytes;
55
+ const size = materializedDocumentBsonBytes(document);
56
+ if (size <= budget)
57
+ return;
58
+ const scope = context.label ?? context.collection ?? 'materialized document';
59
+ throw new Error(`BSON size budget exceeded in ${scope}: ${size} > ${budget} bytes. ` +
60
+ 'Split or bound the document at the writer (one page per source day, top-N maps) ' +
61
+ 'instead of writing a document MongoDB will reject.');
62
+ }
63
+ /** Asserts a whole SET of documents (a scope, a plan, a batch) in one call. */
64
+ function assertMaterializedDocumentsSize(documents, context) {
65
+ if (documents == null)
66
+ return;
67
+ const scope = context.collection;
68
+ documents.forEach((document, index) => assertMaterializedDocumentSize(document, {
69
+ collection: scope,
70
+ label: context.label ?? (scope != null ? `${scope}[${index}]` : undefined),
71
+ maxBytes: context.maxBytes,
72
+ }));
73
+ }
@@ -2,26 +2,34 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MATERIALIZED_REPORT_INDEX_COLLECTIONS = void 0;
4
4
  exports.ensureMaterializedReportIndexes = ensureMaterializedReportIndexes;
5
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
5
6
  const materialized_credit_bills_1 = require("../../schemas/models/materialized_credit_bills");
7
+ const materialized_report_drilldown_rows_1 = require("../../schemas/models/materialized_report_drilldown_rows");
8
+ const materialized_tenant_delivery_entries_1 = require("../../schemas/models/materialized_tenant_delivery_entries");
9
+ const materialized_tenant_delivery_geo_cells_1 = require("../../schemas/models/materialized_tenant_delivery_geo_cells");
10
+ const materialized_tenant_delivery_geo_scopes_1 = require("../../schemas/models/materialized_tenant_delivery_geo_scopes");
11
+ const materialized_tenant_delivery_reports_1 = require("../../schemas/models/materialized_tenant_delivery_reports");
6
12
  const materialized_tenant_discount_entries_1 = require("../../schemas/models/materialized_tenant_discount_entries");
7
13
  const materialized_tenant_discount_reports_1 = require("../../schemas/models/materialized_tenant_discount_reports");
8
14
  const materialized_tenant_discount_sources_1 = require("../../schemas/models/materialized_tenant_discount_sources");
9
- const materialized_tenant_reports_iterations_1 = require("../../schemas/models/materialized_tenant_reports_iterations");
10
15
  const materialized_tenant_prep_time_entries_1 = require("../../schemas/models/materialized_tenant_prep_time_entries");
11
16
  const materialized_tenant_prep_time_reports_1 = require("../../schemas/models/materialized_tenant_prep_time_reports");
17
+ const materialized_tenant_reports_iterations_1 = require("../../schemas/models/materialized_tenant_reports_iterations");
12
18
  const materialized_tenant_sales_overview_reports_1 = require("../../schemas/models/materialized_tenant_sales_overview_reports");
13
- const materialized_report_drilldown_rows_1 = require("../../schemas/models/materialized_report_drilldown_rows");
14
- const tenant_calendar_1 = require("../../schemas/models/tenant_calendar");
15
19
  const tenant_active_jobs_1 = require("../../schemas/models/tenant_active_jobs");
20
+ const tenant_calendar_1 = require("../../schemas/models/tenant_calendar");
16
21
  /**
17
- * BOOTSTRAP the indexes the materialized reads/writes assume.
22
+ * MANUAL index helper for the materialized reads/writes.
23
+ *
24
+ * The services run with `autoIndex: false`, and the model schemas deliberately do not
25
+ * declare these compound indexes. This module is available for an explicit maintenance
26
+ * run / tests, but it is NOT called automatically after `mongoose.connect` by
27
+ * items/workers/operations. Indexes are an OWNER DEPLOY STEP, applied with the migration
28
+ * scripts before the first close/read. Do not describe this as a runtime bootstrap.
18
29
  *
19
- * The services run with `autoIndex: false`, and the model schemas deliberately
20
- * do not declare these compound indexes. Until now the only creator was a
21
- * manual simulation script; a fresh deployment therefore failed every
22
- * `.hint()` read and could create duplicate scope/year documents. This helper
23
- * is called after `mongoose.connect` by items/workers/operations and fails the
24
- * startup if an expected unique index is missing afterwards.
30
+ * For the Delivery page model, use
31
+ * `simulations/migrate-delivery-report-indexes.ts --apply` (it also drops the legacy
32
+ * entry index and creates the deliveries source and geo-scope indexes).
25
33
  *
26
34
  * It creates indexes with `createIndexes` (never drops unrelated indexes).
27
35
  */
@@ -34,6 +42,10 @@ const INDEXES = {
34
42
  [materialized_tenant_prep_time_reports_1.MATERIALIZED_TENANT_PREP_TIME_REPORTS_COLLECTION_NAME]: materialized_tenant_prep_time_reports_1.MATERIALIZED_TENANT_PREP_TIME_REPORTS_INDEX_OPTIONS,
35
43
  [materialized_tenant_prep_time_entries_1.MATERIALIZED_TENANT_PREP_TIME_ENTRIES_COLLECTION_NAME]: materialized_tenant_prep_time_entries_1.MATERIALIZED_TENANT_PREP_TIME_ENTRIES_INDEX_OPTIONS,
36
44
  [materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME]: materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_INDEX_OPTIONS,
45
+ [materialized_tenant_delivery_geo_cells_1.MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_COLLECTION_NAME]: materialized_tenant_delivery_geo_cells_1.MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_INDEX_OPTIONS,
46
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_COLLECTION_NAME]: materialized_tenant_delivery_geo_scopes_1.MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_INDEX_OPTIONS,
47
+ [materialized_tenant_delivery_entries_1.MATERIALIZED_TENANT_DELIVERY_ENTRIES_COLLECTION_NAME]: materialized_tenant_delivery_entries_1.MATERIALIZED_TENANT_DELIVERY_ENTRIES_INDEX_OPTIONS,
48
+ [materialized_tenant_delivery_reports_1.MATERIALIZED_TENANT_DELIVERY_REPORTS_COLLECTION_NAME]: materialized_tenant_delivery_reports_1.MATERIALIZED_TENANT_DELIVERY_REPORTS_INDEX_OPTIONS,
37
49
  [materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_NAME]: materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_ROWS_INDEX_OPTIONS,
38
50
  [materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_NAME]: materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_SCOPES_INDEX_OPTIONS,
39
51
  [tenant_calendar_1.TENANT_CALENDAR_COLLECTION_NAME]: tenant_calendar_1.TENANT_CALENDAR_INDEX_OPTIONS,
@@ -52,9 +64,12 @@ async function ensureMaterializedReportIndexes(connection, options = {}) {
52
64
  }
53
65
  const collection = db.collection(collectionName);
54
66
  const indexes = definitions.filter((definition) => definition.name !== '_id_');
55
- // One-time migration for the old discount-entry identity index. A page
56
- // design cannot coexist with a unique index that omits `page`.
57
- if (collectionName === materialized_tenant_discount_entries_1.MATERIALIZED_TENANT_DISCOUNT_ENTRIES_COLLECTION_NAME) {
67
+ // One-time migration for a per-SCOPE entry identity index. A PAGE design cannot
68
+ // coexist with a unique index that omits `page` (all period pages share
69
+ // `day_index: null`, so the legacy index would reject the second page of a month).
70
+ // Discounts and Delivery entries have the same migration.
71
+ if (collectionName === materialized_tenant_discount_entries_1.MATERIALIZED_TENANT_DISCOUNT_ENTRIES_COLLECTION_NAME ||
72
+ collectionName === materialized_tenant_delivery_entries_1.MATERIALIZED_TENANT_DELIVERY_ENTRIES_COLLECTION_NAME) {
58
73
  const existing = await collection
59
74
  .listIndexes()
60
75
  .toArray()
@@ -49,6 +49,15 @@ const IDENTIFIER_FIELD = /^(scope_field|day_index|key|_id|.*_id)$/;
49
49
  * numeric-looking string when it sits in a field that is not one of these.
50
50
  */
51
51
  const TEXT_FIELD = /(name|label|title|reason|note|description|reference|reference_number|code|currency|platform|status|type|source_key|order_number)$/i;
52
+ /**
53
+ * GEOMETRY leaves are the one exception to the integer-only contract.
54
+ *
55
+ * `location.coordinates` is a GeoJSON `[lng, lat]` pair - a POSITION, not a stored
56
+ * measurement. Rounding it to an integer would move a heat cell's centroid by up to a
57
+ * degree, and the 2dsphere index needs the real value. Every OTHER numeric leaf of a
58
+ * materialized document (counts, cents, minutes, basis points) stays integer-only.
59
+ */
60
+ const GEOMETRY_COORDINATE_PATH = /(^|\.)coordinates\[\d+\]$/;
52
61
  /**
53
62
  * BSON values: only IDENTITY types are ignored. A numeric BSON value
54
63
  * (Decimal128 / Long / Double / Int32) is storage of a number and must obey the
@@ -111,7 +120,7 @@ function findNonIntegerNumericLeaves(document) {
111
120
  violations.push({ path, value: node, reason: 'non-finite' });
112
121
  return;
113
122
  }
114
- if (!Number.isInteger(node)) {
123
+ if (!Number.isInteger(node) && !GEOMETRY_COORDINATE_PATH.test(path)) {
115
124
  violations.push({ path, value: node, reason: 'decimal' });
116
125
  }
117
126
  return;
@@ -175,94 +175,6 @@ exports.MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES = MATERIALIZED_REPORTS_1.MATER
175
175
  /* ------------------------------------------------------------------------ */
176
176
  /* Period sibling-day enumeration */
177
177
  /* ------------------------------------------------------------------------ */
178
- const pad2 = (value) => String(value).padStart(2, '0');
179
- const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
180
- const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
181
- const addMonthDays = (year, month, count, days) => {
182
- if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12)
183
- return false;
184
- for (let offset = 0; offset < count; offset += 1) {
185
- const date = new Date(Date.UTC(year, month - 1 + offset, 1));
186
- const monthYear = date.getUTCFullYear();
187
- const monthNumber = date.getUTCMonth() + 1;
188
- const last = new Date(Date.UTC(monthYear, monthNumber, 0)).getUTCDate();
189
- for (let day = 1; day <= last; day += 1) {
190
- days.add(`${monthYear}-${pad2(monthNumber)}-${pad2(day)}`);
191
- }
192
- }
193
- return true;
194
- };
195
- const addPeriodDays = (scope, scopeField, days) => {
196
- switch (scope) {
197
- case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
198
- const parts = (0, scope_helpers_1.parseMaterializedLocalDate)(scopeField);
199
- if (parts == null)
200
- return false;
201
- const start = new Date(Date.UTC(parts.year, parts.month - 1, parts.day));
202
- if (start.getUTCDay() !== 0)
203
- return false;
204
- for (let offset = 0; offset < 7; offset += 1)
205
- days.add(toLocalDateKey(addUtcDays(start, offset)));
206
- return true;
207
- }
208
- case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
209
- const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
210
- if (match == null)
211
- return false;
212
- const weekYear = Number(match[1]);
213
- const week = Number(match[2]);
214
- if (!Number.isInteger(week) || week < 1 || week > 53)
215
- return false;
216
- const jan4 = new Date(Date.UTC(weekYear, 0, 4));
217
- const isoWeekday = jan4.getUTCDay() || 7;
218
- const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
219
- const start = addUtcDays(weekOneMonday, (week - 1) * 7);
220
- for (let offset = 0; offset < 7; offset += 1)
221
- days.add(toLocalDateKey(addUtcDays(start, offset)));
222
- return true;
223
- }
224
- case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH: {
225
- const match = /^(\d{4})-(\d{2})$/.exec(scopeField);
226
- if (match == null)
227
- return false;
228
- return addMonthDays(Number(match[1]), Number(match[2]), 1, days);
229
- }
230
- case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER: {
231
- const match = /^(\d{4})-Q([1-4])$/.exec(scopeField);
232
- if (match == null)
233
- return false;
234
- return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 3 + 1, 3, days);
235
- }
236
- case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER: {
237
- const match = /^(\d{4})-S([12])$/.exec(scopeField);
238
- if (match == null)
239
- return false;
240
- return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 6 + 1, 6, days);
241
- }
242
- case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR: {
243
- const match = /^(\d{4})$/.exec(scopeField);
244
- if (match == null)
245
- return false;
246
- return addMonthDays(Number(match[1]), 1, 12, days);
247
- }
248
- default:
249
- return false;
250
- }
251
- };
252
- const enumeratePeriodDays = (localDate, scopes) => {
253
- const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
254
- if (periodFields == null)
255
- return null;
256
- const days = new Set([localDate]);
257
- for (const scope of scopes) {
258
- const scopeField = periodFields[scope];
259
- if (typeof scopeField !== 'string' || scopeField.length === 0)
260
- return null;
261
- if (!addPeriodDays(scope, scopeField, days))
262
- return null;
263
- }
264
- return [...days].sort();
265
- };
266
178
  /**
267
179
  * Every `localDate` label whose DAY entry document can contribute to a
268
180
  * month-capped period (week / ISO week / month). The worker uses this to fetch
@@ -270,7 +182,7 @@ const enumeratePeriodDays = (localDate, scopes) => {
270
182
  * entry document and never a year-wide scan.
271
183
  */
272
184
  function getMaterializedPrepTimePeriodDayScopeFields(localDate) {
273
- return enumeratePeriodDays(localDate, exports.MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES);
185
+ return (0, scope_helpers_1.enumerateMaterializedPeriodDays)(localDate, exports.MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES);
274
186
  }
275
187
  /**
276
188
  * Every `localDate` label whose DAY counter document can contribute to ANY
@@ -279,7 +191,7 @@ function getMaterializedPrepTimePeriodDayScopeFields(localDate) {
279
191
  * month-capped.
280
192
  */
281
193
  function getMaterializedPrepTimeReportPeriodDayScopeFields(localDate) {
282
- return enumeratePeriodDays(localDate, exports.MATERIALIZED_PREP_TIME_PERIOD_SCOPES);
194
+ return (0, scope_helpers_1.enumerateMaterializedPeriodDays)(localDate, exports.MATERIALIZED_PREP_TIME_PERIOD_SCOPES);
283
195
  }
284
196
  /** True when a stored prep counter document equals the incoming one (skip write). */
285
197
  function needsMaterializedPrepTimeReportWrite(existing, incoming) {
@@ -0,0 +1,186 @@
1
+ import { IDeliveryGeoResponse, IMaterializedDeliveryGeoCounters, IMaterializedTenantDeliveryGeoCell, TDeliveryGeoMapDisabledReason, TMaterializedDeliveryGeoByKey } from '../../schemas/types/materialized_tenant_delivery_geo_cells';
2
+ import { IDeliveryOrderSource, TDeliverySource } from './materialized-delivery-classification-helpers';
3
+ /**
4
+ * Delivery DEMAND HEAT MAP - the H3 cell compiler (M4.1).
5
+ *
6
+ * ## The cell is derived from the JOINED ORDER's destination
7
+ *
8
+ * The order carries the only customer coordinate the platform has
9
+ * (`delivery_details.lat/lng`). A delivery document carries the RIDER's trace, which is
10
+ * not the demand location and is deliberately not used here.
11
+ *
12
+ * ## Privacy
13
+ *
14
+ * A cell document stores an H3 cell index and its DERIVED CENTROID - never a customer
15
+ * coordinate, never an address, never a polyline. The centroid is a property of the cell
16
+ * (identical for every order inside it), so it reveals nothing about an individual drop.
17
+ *
18
+ * ## Invalid coordinates
19
+ *
20
+ * Missing, non-finite, out-of-range or `(0, 0)` coordinates cannot be plotted. They are
21
+ * NOT dropped: they land in the reserved `__UNKNOWN__` aggregate, which has NO geometry,
22
+ * so the map can still say "N orders could not be located" without inventing a place.
23
+ *
24
+ * ## Two populations, again
25
+ *
26
+ * `orders` is EVERY delivery order in the cell (off-app included) - the demand unit.
27
+ * `delivery_records` counts delivery documents/attempts; `app_orders` counts unique
28
+ * orders with at least one document. A cell with 10 orders and 0 records is a real,
29
+ * useful map point: it is demand the rider app never saw.
30
+ */
31
+ /** True when a coordinate pair can be turned into a cell. `(0, 0)` is explicitly invalid. */
32
+ export declare function isValidDeliveryCoordinate(lat: unknown, lng: unknown): boolean;
33
+ /** The H3 cell of a coordinate pair, or null when the pair is invalid. */
34
+ export declare function deliveryGeoCellOf(lat: unknown, lng: unknown, resolution?: number): string | null;
35
+ /** `[lng, lat]` centroid of an H3 cell (GeoJSON order). */
36
+ export declare function deliveryGeoCellCentroid(cell: string): [number, number] | null;
37
+ /** Merges a cell's counters (used by the day compiler, the month fold and the cap). */
38
+ export declare function mergeDeliveryGeoCounters(target: IMaterializedDeliveryGeoCounters, source: Partial<IMaterializedDeliveryGeoCounters> | null | undefined): IMaterializedDeliveryGeoCounters;
39
+ /** A bounded key part; unknown / blank values get the UNKNOWN token. */
40
+ export declare function deliveryGeoKeyPart(value: unknown): string;
41
+ /**
42
+ * The by_key identity of a joined order: ORDER_STATUS:PLATFORM:CITY.
43
+ *
44
+ * The city part is the RESOLVED city - the SAME top-N + `__OTHER__` resolution the report
45
+ * counters use - so the geo cells and the report counters share ONE city dimension. A city
46
+ * filter therefore means exactly the same thing in the map and in the summary, and a cell
47
+ * that holds orders from two cities can be split by city instead of being attributed to
48
+ * its dominant city.
49
+ */
50
+ export declare function deliveryGeoKeyOfOrder(order: IDeliveryOrderSource, city?: string | null): string;
51
+ /** The by_key identity of a filter triple; null values mean the UNKNOWN token. */
52
+ export declare function deliveryGeoKeyOfParts(orderStatus: unknown, platform: unknown, city?: unknown): string;
53
+ /** Merges a by_key map; keys are ORDER_STATUS:PLATFORM. */
54
+ export declare function mergeDeliveryGeoByKey(target: TMaterializedDeliveryGeoByKey, source: TMaterializedDeliveryGeoByKey | null | undefined): TMaterializedDeliveryGeoByKey;
55
+ /**
56
+ * Caps the by_key map at MATERIALIZED_DELIVERY_GEO_MAX_KEYS. The overflow folds into
57
+ * UNKNOWN:UNKNOWN:UNKNOWN; the cell's top-level counters are unchanged, so sum(by_key)
58
+ * still equals the cell total.
59
+ */
60
+ export declare function boundDeliveryGeoByKey(byKey: TMaterializedDeliveryGeoByKey, maxKeys?: number): TMaterializedDeliveryGeoByKey;
61
+ /** The delivery fee of a delivery order (the declared field, with tolerated fallbacks). */
62
+ export declare function deliveryOrderCharge(order: IDeliveryOrderSource): number;
63
+ /** Finalized rider payout of a delivery document, or 0 when the snapshot is not FINAL. */
64
+ export declare function deliveryRecordPayout(delivery: TDeliverySource): number;
65
+ export interface IDeliveryGeoDayCompileInput {
66
+ tenantId: string;
67
+ brandId: string;
68
+ localDate: string;
69
+ /** Delivery ORDERS of the day - the demand population. */
70
+ orders?: IDeliveryOrderSource[];
71
+ /** Delivery DOCUMENTS of the day - the app-side population. */
72
+ deliveries?: TDeliverySource[];
73
+ computedAt?: Date;
74
+ /** H3 resolution override (tests). */
75
+ resolution?: number;
76
+ /** Cell cap override (tests). */
77
+ maxCells?: number;
78
+ }
79
+ /**
80
+ * Compiles ONE business day into `materialized_tenant_delivery_geo_cells` documents
81
+ * (the `localDate` scope only - the month scope is re-folded from these by the writer).
82
+ *
83
+ * Returns an empty array for a day with no delivery order and no delivery: the close-day
84
+ * writer then deletes the day's stored cells.
85
+ */
86
+ export interface IDeliveryGeoCompileResult {
87
+ cells: IMaterializedTenantDeliveryGeoCell[];
88
+ cappedCellCount: number;
89
+ cappedOrderCount: number;
90
+ }
91
+ /**
92
+ * Compiles a day and also returns the cap metadata consumed by the scope document.
93
+ * The raw cells are capped exactly once, with the same deterministic ranking as the
94
+ * persisted day scope.
95
+ */
96
+ export declare function compileTenantDeliveryGeoCellsWithStats(input: IDeliveryGeoDayCompileInput): IDeliveryGeoCompileResult;
97
+ export declare function compileTenantDeliveryGeoCells(input: IDeliveryGeoDayCompileInput): IMaterializedTenantDeliveryGeoCell[];
98
+ /**
99
+ * The pure aggregation step: cell index -> counters (no envelope fields).
100
+ *
101
+ * Exported so tests and the month fold can use the exact same arithmetic as the writer.
102
+ */
103
+ export declare function compileDeliveryGeoCounters(input: IDeliveryGeoDayCompileInput): IMaterializedTenantDeliveryGeoCell[];
104
+ /** Deterministic dominant city: most orders, then city ASC. */
105
+ export declare function dominantCity(counts: Map<string, number>): string | null;
106
+ /**
107
+ * Caps a scope's cells at `maxCells`, ranked `orders DESC, h3_cell ASC`.
108
+ *
109
+ * The tail is DROPPED, not folded: the heat response reports scope totals from the
110
+ * report counters, so a capped map can never overstate them. Keeping a synthetic
111
+ * `__OTHER__` geometry would put a meaningless point on the map.
112
+ */
113
+ export declare function capDeliveryGeoCells(cells: IMaterializedTenantDeliveryGeoCell[], maxCells?: number): IMaterializedTenantDeliveryGeoCell[];
114
+ /** A map viewport in decimal degrees. */
115
+ export interface IDeliveryGeoViewport {
116
+ north: number;
117
+ south: number;
118
+ east: number;
119
+ west: number;
120
+ }
121
+ /** True when the cell's centroid falls inside the viewport (antimeridian-safe). */
122
+ export declare function deliveryGeoCellWithinViewport(cell: Pick<IMaterializedTenantDeliveryGeoCell, 'location'>, viewport: IDeliveryGeoViewport | null | undefined): boolean;
123
+ /** True when the cell must be hidden: fewer orders than the privacy threshold. */
124
+ export declare function isDeliveryGeoCellSuppressed(cell: Pick<IMaterializedTenantDeliveryGeoCell, 'orders'>, minOrders?: number): boolean;
125
+ export interface IDeliveryGeoFilters {
126
+ platforms?: string[] | null;
127
+ cities?: string[] | null;
128
+ order_statuses?: string[] | null;
129
+ }
130
+ /**
131
+ * Applies the city / platform / order-status filters to ONE cell by summing its by_key
132
+ * map. Returns null when the cell has no matching key.
133
+ *
134
+ * EVERY filter is applied per key, so the cell's counters are the EXACT counters of the
135
+ * selected population - never the cell total of a cell that merely had a matching
136
+ * dominant city. Cells without by_key (pre-v4) are unavailable for a filtered read
137
+ * rather than silently treated as zero.
138
+ */
139
+ export declare function filterDeliveryGeoCell(cell: IMaterializedTenantDeliveryGeoCell, filters?: IDeliveryGeoFilters | null): IMaterializedTenantDeliveryGeoCell | null;
140
+ /**
141
+ * Merges cells that share an H3 index. This is what makes a brand-level response a
142
+ * MAP rather than a pile of tenant rows: two tenants can produce the same cell, and the
143
+ * response has no tenant dimension, so the counters must be summed before the map cap.
144
+ * The city label is kept only when every merged tenant agrees; otherwise it is null.
145
+ */
146
+ export declare function mergeDeliveryGeoCellsByH3(cells: readonly IMaterializedTenantDeliveryGeoCell[] | null | undefined): IMaterializedTenantDeliveryGeoCell[];
147
+ export interface IBuildDeliveryGeoResponseInput {
148
+ cells: IMaterializedTenantDeliveryGeoCell[];
149
+ totalOrders: number;
150
+ totalAppOrders: number;
151
+ viewport?: IDeliveryGeoViewport | null;
152
+ minOrders?: number;
153
+ filters?: IDeliveryGeoFilters | null;
154
+ /** Cells dropped by the scope cap before this response was built. */
155
+ cappedCellCount?: number;
156
+ /** Orders inside those capped cells. */
157
+ cappedOrderCount?: number;
158
+ /** False when a filter cannot be applied to the write-time cap metadata. */
159
+ cappedCountsExact?: boolean;
160
+ /** Read-time cap. Historical and LIVE must both use the same value. */
161
+ maxCells?: number | null;
162
+ /** Actual cell granularity; defaults to DAY. */
163
+ granularity?: 'DAY' | 'MONTH';
164
+ /** False when the cells cover whole months instead of the exact selected days. */
165
+ exactDays?: boolean;
166
+ /** Optional precomputed unknown-geometry order count. */
167
+ unknownOrderCount?: number | null;
168
+ /** Disable the map because the selection cannot be geographically isolated. */
169
+ mapDisabled?: boolean;
170
+ /** Why the map is disabled. Defaults to `OTHER_AREAS` when disabled. */
171
+ mapDisabledReason?: TDeliveryGeoMapDisabledReason | null;
172
+ }
173
+ /**
174
+ * Turns stored cells into the `POST /reports/delivery/geo` payload.
175
+ *
176
+ * Order of operations matters:
177
+ * 1. apply city/platform/order-status filters to each cell;
178
+ * 2. merge duplicate H3 cells (brand-level tenants can collide);
179
+ * 3. count geometry-less unknown orders (they are never plotted);
180
+ * 4. apply the 2,000-cell read cap to the FILTERED union and count what it dropped;
181
+ * 5. apply the viewport and the privacy suppression floor.
182
+ *
183
+ * The cap is applied here rather than before filtering, so both LIVE and HISTORICAL cap
184
+ * the same population. Write-time cap counts (if any) are added to the read-time drops.
185
+ */
186
+ export declare function buildDeliveryGeoResponse(input: IBuildDeliveryGeoResponseInput): IDeliveryGeoResponse;