@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
@@ -0,0 +1,14 @@
1
+ import { buildMaterializedDrilldownRows, buildMaterializedDrilldownScope, } from '../../materialized-report-drilldown-rows';
2
+ export function buildReportFlatProjectionPlan(input) {
3
+ if (input.entryDocument == null)
4
+ return null;
5
+ const retargeted = {
6
+ ...input.entryDocument,
7
+ scope_context: input.scopeContext,
8
+ scope_field: input.scopeField,
9
+ day_index: input.dayIndex ?? null,
10
+ };
11
+ const flattened = buildMaterializedDrilldownRows(input.reportType, retargeted, input.sourceLocalDate ?? null);
12
+ const scope = buildMaterializedDrilldownScope(input.reportType, retargeted, flattened.rows, input.sourceLocalDate ?? null);
13
+ return { rows: flattened.rows, scope };
14
+ }
@@ -0,0 +1,8 @@
1
+ export * from './scope-refs';
2
+ export * from './entry-pages';
3
+ export * from './iteration-row';
4
+ export * from './flat-projection';
5
+ export * from './budget';
6
+ export * from './run-stats';
7
+ export * from './cap-metadata';
8
+ export * from './top-n';
@@ -0,0 +1,10 @@
1
+ import { buildMaterializedTenantReportIteration } from '../../materialized-tenant-reports-iterations-helpers';
2
+ /**
3
+ * PHASE 2 — generic iteration-row builder.
4
+ *
5
+ * Thin composition over the existing builder so later phases have one place to
6
+ * pass a registry report type. The existing builder remains the source of truth.
7
+ */
8
+ export function buildReportIterationRow(report, options) {
9
+ return buildMaterializedTenantReportIteration(report, options);
10
+ }
@@ -0,0 +1,42 @@
1
+ export const EMPTY_REPORT_RUN_STATS = {
2
+ reportKey: '',
3
+ localDate: '',
4
+ documents: 0,
5
+ entryDocuments: 0,
6
+ entryPages: 0,
7
+ flatRows: 0,
8
+ flatScopes: 0,
9
+ geoCells: 0,
10
+ iterationRows: 0,
11
+ deletes: 0,
12
+ cappedCells: 0,
13
+ cappedOrders: 0,
14
+ skipped: 0,
15
+ warnings: [],
16
+ };
17
+ export function buildReportRunStats(input) {
18
+ return {
19
+ ...EMPTY_REPORT_RUN_STATS,
20
+ ...input,
21
+ warnings: [...(input.warnings ?? [])],
22
+ };
23
+ }
24
+ export function mergeReportRunStats(left, right) {
25
+ const sum = (key) => Number(left[key] ?? 0) + Number(right[key] ?? 0);
26
+ return {
27
+ reportKey: left.reportKey === right.reportKey ? left.reportKey : `${left.reportKey}+${right.reportKey}`,
28
+ localDate: left.localDate === right.localDate ? left.localDate : `${left.localDate}+${right.localDate}`,
29
+ documents: sum('documents'),
30
+ entryDocuments: sum('entryDocuments'),
31
+ entryPages: sum('entryPages'),
32
+ flatRows: sum('flatRows'),
33
+ flatScopes: sum('flatScopes'),
34
+ geoCells: sum('geoCells'),
35
+ iterationRows: sum('iterationRows'),
36
+ deletes: sum('deletes'),
37
+ cappedCells: sum('cappedCells'),
38
+ cappedOrders: sum('cappedOrders'),
39
+ skipped: sum('skipped'),
40
+ warnings: [...left.warnings, ...right.warnings],
41
+ };
42
+ }
@@ -0,0 +1,28 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../../../constants/MATERIALIZED_REPORTS';
2
+ import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields } from '../../scope-helpers';
3
+ export function resolveReportScopeRefsForDay(definition, localDate) {
4
+ const periodFields = getMaterializedPeriodScopeFields(localDate);
5
+ if (periodFields == null)
6
+ return null;
7
+ const refs = [];
8
+ for (const [scopeContext, scopeField] of Object.entries(periodFields)) {
9
+ if (definition.reportScopes.includes(scopeContext)) {
10
+ refs.push({
11
+ scope_context: scopeContext,
12
+ scope_field: scopeField,
13
+ });
14
+ }
15
+ }
16
+ if (definition.reportScopes.includes(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR)) {
17
+ for (let hour = 0; hour < 24; hour += 1) {
18
+ const scopeField = getMaterializedHourScopeField(localDate, hour);
19
+ if (scopeField == null)
20
+ return null;
21
+ refs.push({
22
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
23
+ scope_field: scopeField,
24
+ });
25
+ }
26
+ }
27
+ return refs;
28
+ }
@@ -0,0 +1,24 @@
1
+ /** PHASE 2 — deterministic top-N + reserved overflow token. */
2
+ export const REPORT_OTHER_TOKEN = '__OTHER__';
3
+ /**
4
+ * Selects the top-N keys by `count DESC, key ASC` and folds the rest into the
5
+ * reserved `__OTHER__` token. Generic; report-specific mapping stays report-owned.
6
+ */
7
+ export function selectReportTopN(entries, limit, otherToken = REPORT_OTHER_TOKEN) {
8
+ const counts = new Map();
9
+ for (const entry of entries ?? []) {
10
+ if (entry == null || typeof entry.key !== 'string' || entry.key === '')
11
+ continue;
12
+ counts.set(entry.key, (counts.get(entry.key) ?? 0) + (Number(entry.count) || 0));
13
+ }
14
+ const ranked = [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
15
+ if (ranked.length <= Math.max(1, limit)) {
16
+ return { kept: ranked.map(([key]) => key), dropped: [], other: null };
17
+ }
18
+ const kept = ranked.slice(0, Math.max(1, limit)).map(([key]) => key);
19
+ const dropped = ranked.slice(Math.max(1, limit)).map(([key]) => key);
20
+ return { kept, dropped, other: otherToken };
21
+ }
22
+ export function resolveReportTopNKey(selection, key) {
23
+ return selection.other != null && selection.dropped.includes(key) ? selection.other : key;
24
+ }
@@ -0,0 +1,23 @@
1
+ import { ALL_REPORT_KEYS } from '../../reporting-contract/report-contract';
2
+ import { PRODUCTION_REPORT_DEFINITIONS, REPORT_DEFINITIONS, REPORT_DEFINITION_STATUS, REPORT_REGISTRY_EXEMPTIONS, } from './definition';
3
+ /**
4
+ * PHASE 2 — the metadata registry lookup surface.
5
+ *
6
+ * Pure lookups only; no side effects and no service imports.
7
+ */
8
+ export const REPORT_REGISTRY_KEYS = ALL_REPORT_KEYS;
9
+ export function getReportDefinition(key) {
10
+ return REPORT_DEFINITIONS[String(key)] ?? null;
11
+ }
12
+ export function getReportExemption(key) {
13
+ return REPORT_REGISTRY_EXEMPTIONS[String(key)] ?? null;
14
+ }
15
+ export function isProductionReportKey(key) {
16
+ return getReportDefinition(key)?.status === REPORT_DEFINITION_STATUS.PRODUCTION;
17
+ }
18
+ export function getProductionReportDefinitions() {
19
+ return [...PRODUCTION_REPORT_DEFINITIONS];
20
+ }
21
+ export function getReportDefinitionBySegment(segment) {
22
+ return PRODUCTION_REPORT_DEFINITIONS.find((definition) => definition.segment === segment) ?? null;
23
+ }
@@ -0,0 +1,214 @@
1
+ import { ALL_MATERIALIZED_REPORT_SCOPES, ALL_MATERIALIZED_REPORT_TYPES, } from '../../../constants/MATERIALIZED_REPORTS';
2
+ import { ALL_REPORT_KEYS, REPORT_CAPABILITIES, REPORT_ROUTE_SEGMENTS } from '../../reporting-contract/report-contract';
3
+ import { REPORT_DEFINITIONS, REPORT_DEFINITION_STATUS, REPORT_ENTRY_SPLIT, REPORT_ENTRY_STORAGE, REPORT_PROJECTION, REPORT_REGISTRY_EXEMPTIONS, } from './definition';
4
+ const MATERIALIZED_PREFIX = 'materialized_';
5
+ const isPositiveInteger = (value) => typeof value === 'number' && Number.isInteger(value) && value > 0;
6
+ const isNonEmptyString = (value) => typeof value === 'string' && value.trim() !== '';
7
+ function validateCollection(definition, label, collection, errors, warnings) {
8
+ if (!isNonEmptyString(collection.name)) {
9
+ errors.push(`${definition.key}: ${label} has no collection name`);
10
+ return;
11
+ }
12
+ if (!collection.name.startsWith(MATERIALIZED_PREFIX)) {
13
+ errors.push(`${definition.key}: ${label} collection "${collection.name}" is not a materialized_* collection`);
14
+ }
15
+ if (!isPositiveInteger(collection.schemaVersion)) {
16
+ errors.push(`${definition.key}: ${label} has no positive schema version`);
17
+ }
18
+ if (!isPositiveInteger(collection.budgetBytes)) {
19
+ errors.push(`${definition.key}: ${label} has no positive budget`);
20
+ }
21
+ if (!isNonEmptyString(collection.indexOwner)) {
22
+ errors.push(`${definition.key}: ${label} has no index ownership`);
23
+ }
24
+ if (collection.validatorFile == null && !isNonEmptyString(collection.validatorDebt)) {
25
+ errors.push(`${definition.key}: ${label} has neither a validator file nor a declared validator debt`);
26
+ }
27
+ if (collection.validatorFile == null && isNonEmptyString(collection.validatorDebt)) {
28
+ warnings.push(`${definition.key}: ${label} validator debt: ${collection.validatorDebt}`);
29
+ }
30
+ if (definition.budgets[collection.name] == null || !isPositiveInteger(definition.budgets[collection.name])) {
31
+ errors.push(`${definition.key}: collection "${collection.name}" has no budget declaration in budgets`);
32
+ }
33
+ }
34
+ function validateScopes(definition, label, scopes, errors) {
35
+ if (scopes.length === 0) {
36
+ errors.push(`${definition.key}: ${label} has no scopes`);
37
+ return;
38
+ }
39
+ const seen = new Set();
40
+ for (const scope of scopes) {
41
+ if (!ALL_MATERIALIZED_REPORT_SCOPES.includes(scope)) {
42
+ errors.push(`${definition.key}: ${label} has unknown scope "${String(scope)}"`);
43
+ }
44
+ if (seen.has(String(scope))) {
45
+ errors.push(`${definition.key}: ${label} repeats scope "${String(scope)}"`);
46
+ }
47
+ seen.add(String(scope));
48
+ }
49
+ }
50
+ export function validateReportRegistry(input = {}) {
51
+ const definitions = input.definitions ?? REPORT_DEFINITIONS;
52
+ const exemptions = input.exemptions ?? REPORT_REGISTRY_EXEMPTIONS;
53
+ const keys = input.keys ?? ALL_REPORT_KEYS;
54
+ const errors = [];
55
+ const warnings = [];
56
+ for (const key of keys) {
57
+ const definition = definitions[key];
58
+ const exemption = exemptions[key];
59
+ if (definition == null && exemption == null) {
60
+ errors.push(`${key}: no report definition and no explicit exemption`);
61
+ continue;
62
+ }
63
+ if (definition != null && exemption != null) {
64
+ errors.push(`${key}: both a report definition and an exemption exist`);
65
+ }
66
+ if (definition == null)
67
+ continue;
68
+ if (definition.key !== key) {
69
+ errors.push(`${key}: definition key is "${definition.key}"`);
70
+ }
71
+ if (definition.status !== REPORT_DEFINITION_STATUS.PRODUCTION &&
72
+ definition.status !== REPORT_DEFINITION_STATUS.READ_ONLY) {
73
+ errors.push(`${key}: a concrete definition must be PRODUCTION or READ_ONLY`);
74
+ }
75
+ if (!isNonEmptyString(definition.owner))
76
+ errors.push(`${key}: no owner`);
77
+ if (!ALL_MATERIALIZED_REPORT_TYPES.includes(definition.reportType)) {
78
+ errors.push(`${key}: unknown report type "${String(definition.reportType)}"`);
79
+ }
80
+ if (definition.segment !== REPORT_ROUTE_SEGMENTS[definition.key]) {
81
+ errors.push(`${key}: segment "${definition.segment}" disagrees with REPORT_ROUTE_SEGMENTS`);
82
+ }
83
+ const expectedCapabilities = REPORT_CAPABILITIES[definition.key];
84
+ if (expectedCapabilities == null ||
85
+ expectedCapabilities.live !== definition.capabilities.live ||
86
+ expectedCapabilities.historical !== definition.capabilities.historical ||
87
+ expectedCapabilities.details !== definition.capabilities.details) {
88
+ errors.push(`${key}: capabilities disagree with REPORT_CAPABILITIES`);
89
+ }
90
+ validateCollection(definition, 'report', definition.report, errors, warnings);
91
+ if (definition.entries != null) {
92
+ validateCollection(definition, 'entries', definition.entries, errors, warnings);
93
+ }
94
+ for (const side of definition.sideCollections) {
95
+ validateCollection(definition, 'side', side, errors, warnings);
96
+ }
97
+ const allCollections = [
98
+ definition.report,
99
+ ...(definition.entries == null ? [] : [definition.entries]),
100
+ ...definition.sideCollections,
101
+ ].map((collection) => collection.name);
102
+ for (const collectionName of Object.keys(definition.budgets)) {
103
+ if (!allCollections.includes(collectionName)) {
104
+ warnings.push(`${key}: budget declared for unknown collection "${collectionName}"`);
105
+ }
106
+ }
107
+ validateScopes(definition, 'reportScopes', definition.reportScopes, errors);
108
+ if (definition.entryScopes.length > 0 || definition.entryStorage !== REPORT_ENTRY_STORAGE.NONE) {
109
+ validateScopes(definition, 'entryScopes', definition.entryScopes, errors);
110
+ }
111
+ if (!definition.reportScopes.includes(definition.maxReportScope)) {
112
+ errors.push(`${key}: maxReportScope is not a declared report scope`);
113
+ }
114
+ if (definition.maxEntryScope != null && !definition.entryScopes.includes(definition.maxEntryScope)) {
115
+ errors.push(`${key}: maxEntryScope is not a declared entry scope`);
116
+ }
117
+ for (const scope of definition.entryScopes) {
118
+ if (!definition.reportScopes.includes(scope)) {
119
+ errors.push(`${key}: entry scope "${scope}" is outside reportScopes`);
120
+ }
121
+ }
122
+ if (definition.entryStorage === REPORT_ENTRY_STORAGE.NONE) {
123
+ if (definition.entries != null) {
124
+ errors.push(`${key}: entryStorage NONE must not declare an entry collection`);
125
+ }
126
+ if (definition.entryScopes.length !== 0) {
127
+ errors.push(`${key}: entryStorage NONE must not declare entry scopes`);
128
+ }
129
+ if (definition.entrySplit !== REPORT_ENTRY_SPLIT.NONE) {
130
+ errors.push(`${key}: entryStorage NONE must not split pages`);
131
+ }
132
+ if (definition.maxEntryScope != null) {
133
+ errors.push(`${key}: entryStorage NONE must not declare maxEntryScope`);
134
+ }
135
+ }
136
+ else {
137
+ if (definition.entries == null) {
138
+ errors.push(`${key}: entry storage requires an entry collection`);
139
+ }
140
+ if (definition.entryScopes.length === 0) {
141
+ errors.push(`${key}: entry storage requires entry scopes`);
142
+ }
143
+ if (definition.maxEntryScope == null) {
144
+ errors.push(`${key}: entry storage requires maxEntryScope`);
145
+ }
146
+ }
147
+ if (definition.entrySplit === REPORT_ENTRY_SPLIT.DETERMINISTIC_SUBPAGES &&
148
+ definition.entryStorage !== REPORT_ENTRY_STORAGE.PAGE_PER_SOURCE_DAY) {
149
+ errors.push(`${key}: #N splitting requires page-per-source-day entries`);
150
+ }
151
+ if (definition.projections.includes(REPORT_PROJECTION.FLAT_DRILLDOWN)) {
152
+ const names = definition.sideCollections.map((collection) => collection.name);
153
+ if (!names.includes('materialized_report_drilldown_rows') ||
154
+ !names.includes('materialized_report_drilldown_scopes')) {
155
+ errors.push(`${key}: FLAT_DRILLDOWN requires both flat collections`);
156
+ }
157
+ }
158
+ if (definition.projections.includes(REPORT_PROJECTION.DISCOUNT_SOURCES) &&
159
+ !definition.sideCollections.some((collection) => collection.name === 'materialized_tenant_discount_sources')) {
160
+ errors.push(`${key}: DISCOUNT_SOURCES requires the source collection`);
161
+ }
162
+ if (definition.projections.includes(REPORT_PROJECTION.DELIVERY_GEO)) {
163
+ const names = definition.sideCollections.map((collection) => collection.name);
164
+ if (!names.includes('materialized_tenant_delivery_geo_cells') ||
165
+ !names.includes('materialized_tenant_delivery_geo_scopes')) {
166
+ errors.push(`${key}: DELIVERY_GEO requires cells + cap metadata`);
167
+ }
168
+ }
169
+ if (definition.capabilities.details &&
170
+ (definition.adapters.details == null || !isNonEmptyString(definition.adapters.details))) {
171
+ errors.push(`${key}: capabilities.details is true but no details adapter is declared`);
172
+ }
173
+ if (!definition.capabilities.details && definition.adapters.details != null) {
174
+ errors.push(`${key}: details adapter declared without details capability`);
175
+ }
176
+ if (!isNonEmptyString(definition.adapters.writer))
177
+ errors.push(`${key}: no writer adapter`);
178
+ if (!isNonEmptyString(definition.adapters.live))
179
+ errors.push(`${key}: no live adapter`);
180
+ if (!isNonEmptyString(definition.adapters.historical)) {
181
+ errors.push(`${key}: no historical adapter`);
182
+ }
183
+ if (definition.completeness.details === 'FLAT_PROJECTION' &&
184
+ !definition.projections.includes(REPORT_PROJECTION.FLAT_DRILLDOWN)) {
185
+ errors.push(`${key}: details completeness requires the flat projection`);
186
+ }
187
+ if (definition.filters.length === 0) {
188
+ errors.push(`${key}: no filter definitions`);
189
+ }
190
+ for (const filter of definition.filters) {
191
+ if (!isNonEmptyString(filter.id))
192
+ errors.push(`${key}: filter without an id`);
193
+ if (filter.mode !== 'CLIENT' && filter.mode !== 'SERVER') {
194
+ errors.push(`${key}: filter "${filter.id}" has an invalid mode`);
195
+ }
196
+ if (!['SUMMARY', 'DETAILS', 'BOTH'].includes(filter.appliesTo)) {
197
+ errors.push(`${key}: filter "${filter.id}" has an invalid appliesTo`);
198
+ }
199
+ }
200
+ if (definition.capabilities.details && definition.cursor === 'NONE') {
201
+ warnings.push(`${key}: details capability but cursor NONE`);
202
+ }
203
+ for (const rule of definition.retention) {
204
+ if (!allCollections.includes(rule.collection)) {
205
+ errors.push(`${key}: retention targets an unknown collection "${rule.collection}"`);
206
+ }
207
+ if (!isPositiveInteger(rule.amount)) {
208
+ errors.push(`${key}: retention amount must be a positive integer`);
209
+ }
210
+ }
211
+ }
212
+ return { ok: errors.length === 0, errors, warnings };
213
+ }
214
+ export const REPORT_REGISTRY_VALIDATION = validateReportRegistry();
@@ -132,3 +132,101 @@ export function getMaterializedPeriodDayScopeRange(localDate) {
132
132
  lte: toKey(new Date(Date.UTC(year, 11, 31 + 7))),
133
133
  };
134
134
  }
135
+ /* ------------------------------------------------------------------------ */
136
+ /* Period sibling-day enumeration */
137
+ /* ------------------------------------------------------------------------ */
138
+ const pad2 = (value) => String(value).padStart(2, '0');
139
+ const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
140
+ const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
141
+ const addMonthDays = (year, month, count, days) => {
142
+ if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12)
143
+ return false;
144
+ for (let offset = 0; offset < count; offset += 1) {
145
+ const date = new Date(Date.UTC(year, month - 1 + offset, 1));
146
+ const monthYear = date.getUTCFullYear();
147
+ const monthNumber = date.getUTCMonth() + 1;
148
+ const last = new Date(Date.UTC(monthYear, monthNumber, 0)).getUTCDate();
149
+ for (let day = 1; day <= last; day += 1) {
150
+ days.add(`${monthYear}-${pad2(monthNumber)}-${pad2(day)}`);
151
+ }
152
+ }
153
+ return true;
154
+ };
155
+ const addPeriodDays = (scope, scopeField, days) => {
156
+ switch (scope) {
157
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
158
+ const parts = parseMaterializedLocalDate(scopeField);
159
+ if (parts == null)
160
+ return false;
161
+ const start = new Date(Date.UTC(parts.year, parts.month - 1, parts.day));
162
+ if (start.getUTCDay() !== 0)
163
+ return false;
164
+ for (let offset = 0; offset < 7; offset += 1)
165
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
166
+ return true;
167
+ }
168
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
169
+ const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
170
+ if (match == null)
171
+ return false;
172
+ const weekYear = Number(match[1]);
173
+ const week = Number(match[2]);
174
+ if (!Number.isInteger(week) || week < 1 || week > 53)
175
+ return false;
176
+ const jan4 = new Date(Date.UTC(weekYear, 0, 4));
177
+ const isoWeekday = jan4.getUTCDay() || 7;
178
+ const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
179
+ const start = addUtcDays(weekOneMonday, (week - 1) * 7);
180
+ for (let offset = 0; offset < 7; offset += 1)
181
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
182
+ return true;
183
+ }
184
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH: {
185
+ const match = /^(\d{4})-(\d{2})$/.exec(scopeField);
186
+ if (match == null)
187
+ return false;
188
+ return addMonthDays(Number(match[1]), Number(match[2]), 1, days);
189
+ }
190
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER: {
191
+ const match = /^(\d{4})-Q([1-4])$/.exec(scopeField);
192
+ if (match == null)
193
+ return false;
194
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 3 + 1, 3, days);
195
+ }
196
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER: {
197
+ const match = /^(\d{4})-S([12])$/.exec(scopeField);
198
+ if (match == null)
199
+ return false;
200
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 6 + 1, 6, days);
201
+ }
202
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR: {
203
+ const match = /^(\d{4})$/.exec(scopeField);
204
+ if (match == null)
205
+ return false;
206
+ return addMonthDays(Number(match[1]), 1, 12, days);
207
+ }
208
+ default:
209
+ return false;
210
+ }
211
+ };
212
+ /**
213
+ * Every `localDate` label whose DAY documents can contribute to the period scopes the
214
+ * given date rolls into. The close-day writer uses it to fetch exactly the sibling DAY
215
+ * documents a period re-fold needs - never a full-period document.
216
+ *
217
+ * Returns `null` (never throws) for a malformed date or scope field.
218
+ */
219
+ export function enumerateMaterializedPeriodDays(localDate, scopes) {
220
+ const periodFields = getMaterializedPeriodScopeFields(localDate);
221
+ if (periodFields == null)
222
+ return null;
223
+ const days = new Set([localDate]);
224
+ for (const scope of scopes) {
225
+ const scopeField = periodFields[scope];
226
+ if (typeof scopeField !== 'string' || scopeField.length === 0)
227
+ return null;
228
+ if (!addPeriodDays(scope, scopeField, days))
229
+ return null;
230
+ }
231
+ return [...days].sort();
232
+ }
@@ -1,7 +1,7 @@
1
+ import { MATERIALIZED_DELIVERY_DISTANCE_BUCKETS, MATERIALIZED_REPORT_SCOPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
1
2
  import { convertPriceFromCents } from '../utils/price-conversion';
2
- import { DELIVERY_UNKNOWN_TOKEN, freshDeliveryCounters, parseMaterializedDeliveryKey, } from './materialized-delivery-classification-helpers';
3
3
  import { mergeMaterializedDeliveryCounters } from './materialized-delivery-accumulator-helpers';
4
- import { MATERIALIZED_DELIVERY_DISTANCE_BUCKETS, MATERIALIZED_REPORT_SCOPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
4
+ import { DELIVERY_UNKNOWN_TOKEN, freshDeliveryCounters, parseMaterializedDeliveryKey, } from './materialized-delivery-classification-helpers';
5
5
  const toDecimal = (cents) => convertPriceFromCents(cents ?? 0);
6
6
  const km = (meters) => Math.round(((meters ?? 0) / 1000) * 100) / 100;
7
7
  const safeAverage = (total, count) => count > 0 ? Math.round((total / count) * 100) / 100 : null;
@@ -11,6 +11,10 @@ function keyPassesFilters(key, filters) {
11
11
  const parsed = parseMaterializedDeliveryKey(key);
12
12
  if (parsed == null)
13
13
  return true; // never hide a key we cannot parse
14
+ const orderStatuses = filters.order_statuses;
15
+ if (orderStatuses != null && orderStatuses.length > 0 && !orderStatuses.includes(parsed.order_status)) {
16
+ return false;
17
+ }
14
18
  const platforms = filters.platforms;
15
19
  if (platforms != null && platforms.length > 0 && !platforms.includes(parsed.platform))
16
20
  return false;
@@ -95,17 +99,21 @@ function buildPageForTenant(tenantIds, docs, filters) {
95
99
  last_delivery_at: row.last_delivery_at == null ? null : new Date(row.last_delivery_at),
96
100
  });
97
101
  }
98
- riders.sort((a, b) => b.deliveries - a.deliveries);
102
+ // Deterministic: deliveries DESC, rider id ASC (a tie must never depend on key order).
103
+ riders.sort((a, b) => b.deliveries - a.deliveries || (a.rider_id < b.rider_id ? -1 : a.rider_id > b.rider_id ? 1 : 0));
104
+ // DEMAND heat: every delivery ORDER (off-app included), bucketed by the JOINED
105
+ // ORDER's local hour. It is deliberately NOT the delivery-record count - the map must
106
+ // show where delivery demand IS, not only where the rider app was used.
99
107
  const hotAreas = [];
100
108
  for (const [city, row] of Object.entries(total.areas ?? {})) {
101
109
  for (const [hour, count] of Object.entries(row.by_hour ?? {})) {
102
110
  const numeric = Number(count) || 0;
103
111
  if (numeric === 0)
104
112
  continue;
105
- hotAreas.push({ city, hour: Number(hour) || 0, deliveries: numeric });
113
+ hotAreas.push({ city, hour: Number(hour) || 0, orders: numeric, deliveries: numeric });
106
114
  }
107
115
  }
108
- hotAreas.sort((a, b) => b.deliveries - a.deliveries);
116
+ hotAreas.sort((a, b) => b.orders - a.orders || (a.city < b.city ? -1 : a.city > b.city ? 1 : 0) || a.hour - b.hour);
109
117
  const totalDistance = Number(distance.sum_meters) || 0;
110
118
  const distanceCount = Number(distance.count) || 0;
111
119
  return {
@@ -124,14 +132,26 @@ function buildPageForTenant(tenantIds, docs, filters) {
124
132
  with_dropoff_proof: Number(adoption.proof_dropoff_count) || 0,
125
133
  },
126
134
  summary: {
135
+ // The POPULATIONS, side by side and never conflated.
136
+ orders: Number(adoption.delivery_order_count) || 0,
137
+ app_orders: Number(adoption.delivered_via_app_count) || 0,
138
+ off_app_orders: Number(adoption.off_app_count) || 0,
139
+ delivery_records: Number(deliveries.count) || 0,
127
140
  deliveries: Number(deliveries.count) || 0,
128
141
  completed: completedForTiming,
129
142
  cancelled: Number(deliveries.cancelled_count) || 0,
130
- in_progress: Number(deliveries.in_progress_count) || 0,
143
+ // "Open" = PENDING + ASSIGNED + IN_PROGRESS (one definition shared with the
144
+ // statement view and the volume chart's Open bucket). The status-specific counters
145
+ // remain available on the counter block.
146
+ in_progress: (Number(deliveries.pending_count) || 0) +
147
+ (Number(deliveries.assigned_count) || 0) +
148
+ (Number(deliveries.in_progress_count) || 0),
131
149
  rider_revenue: toDecimal(money.rider_revenue_amount),
150
+ rider_payout: toDecimal(money.rider_revenue_amount),
132
151
  net_sale: toDecimal(money.net_sale_amount),
133
152
  collected: toDecimal(money.collected_amount),
134
153
  charges_levied: toDecimal(money.delivery_charge_amount),
154
+ delivery_fees: toDecimal(money.delivery_charge_amount),
135
155
  tips: toDecimal(money.tip_amount),
136
156
  discounts: toDecimal(money.discount_amount),
137
157
  refunds: toDecimal(money.refund_amount),
@@ -139,9 +159,9 @@ function buildPageForTenant(tenantIds, docs, filters) {
139
159
  total_distance_km: km(totalDistance),
140
160
  average_distance_km: safeAverage(km(totalDistance), distanceCount),
141
161
  average_rider_revenue: safeAverage(toDecimal(money.rider_revenue_amount), Number(money.rider_revenue_count) || 0),
142
- average_dispatch_lag_minutes: safeAverage(Number(timing?.dispatch_lag_sum_minutes) || 0, Number(timing?.graded_count) || 0),
143
- average_complete_minutes: safeAverage(Number(timing?.complete_sum_minutes) || 0, Number(timing?.graded_count) || 0),
144
- average_total_minutes: safeAverage(Number(timing?.total_sum_minutes) || 0, Number(timing?.graded_count) || 0),
162
+ average_dispatch_lag_minutes: safeAverage(Number(timing?.dispatch_lag_sum_minutes) || 0, Number(timing?.dispatch_lag_count ?? timing?.graded_count) || 0),
163
+ average_complete_minutes: safeAverage(Number(timing?.complete_sum_minutes) || 0, Number(timing?.complete_count ?? completedForTiming) || 0),
164
+ average_total_minutes: safeAverage(Number(timing?.total_sum_minutes) || 0, Number(timing?.total_count ?? completedForTiming) || 0),
145
165
  average_assignment_minutes: safeAverage(Number(timing?.assignment_sum_minutes) || 0, Number(timing?.assignment_count) || 0),
146
166
  average_pickup_wait_minutes: safeAverage(Number(timing?.pickup_wait_sum_minutes) || 0, Number(timing?.pickup_wait_count) || 0),
147
167
  average_transit_minutes: safeAverage(Number(timing?.transit_sum_minutes) || 0, Number(timing?.transit_count) || 0),
@@ -149,6 +169,9 @@ function buildPageForTenant(tenantIds, docs, filters) {
149
169
  average_status_updates: safeAverage(Number(timing?.status_updates_sum) || 0, Number(timing?.status_updates_count) || 0),
150
170
  cancelled_after_pickup: Number(timing?.cancelled_after_pickup_count) || 0,
151
171
  promise_known: Number(timing?.promise_known_count) || 0,
172
+ eta_coverage_percent: completedForTiming > 0
173
+ ? Math.round(((Number(timing?.promise_known_count) || 0) / completedForTiming) * 1000) / 10
174
+ : null,
152
175
  on_time: Number(timing?.on_time_count) || 0,
153
176
  on_time_percent: Number(timing?.promise_known_count) > 0
154
177
  ? Math.round(((Number(timing?.on_time_count) || 0) / Number(timing?.promise_known_count)) * 1000) / 10
@@ -166,18 +189,45 @@ function buildPageForTenant(tenantIds, docs, filters) {
166
189
  rider_revenue: toDecimal(block.money?.rider_revenue_amount),
167
190
  avg_distance_km: safeAverage(km(Number(block.distance.sum_meters) || 0), Number(block.distance.count) || 0),
168
191
  }))
169
- .sort((a, b) => b.deliveries - a.deliveries),
192
+ .sort((a, b) => b.deliveries - a.deliveries || (a.platform < b.platform ? -1 : a.platform > b.platform ? 1 : 0)),
170
193
  by_area: [...byCity.entries()]
171
- .map(([city, block]) => ({
172
- city,
173
- deliveries: Number(block.deliveries?.count) || 0,
174
- completed: Number(block.deliveries?.completed_count) || 0,
175
- net_sale: toDecimal(block.money?.net_sale_amount),
176
- charges_levied: toDecimal(block.money?.delivery_charge_amount),
177
- rider_revenue: toDecimal(block.money?.rider_revenue_amount),
178
- avg_distance_km: safeAverage(km(Number(block.distance.sum_meters) || 0), Number(block.distance.count) || 0),
179
- }))
180
- .sort((a, b) => b.deliveries - a.deliveries),
194
+ .map(([city, block]) => {
195
+ const rows = Object.values(block.areas ?? {});
196
+ const deliveryOrders = rows.reduce((sum, row) => sum + (Number(row?.delivery_orders) || 0), 0);
197
+ const appOrders = rows.reduce((sum, row) => sum + (Number(row?.app_orders) || 0), 0);
198
+ const offAppOrders = rows.reduce((sum, row) => sum + (Number(row?.off_app_orders) || 0), 0);
199
+ const deliveryRecords = rows.reduce((sum, row) => sum + (Number(row?.delivery_records ?? row?.count) || 0), 0);
200
+ const completed = rows.reduce((sum, row) => sum + (Number(row?.completed_count) || 0), 0);
201
+ const cancelled = rows.reduce((sum, row) => sum + (Number(row?.cancelled_count) || 0), 0);
202
+ const riderPayout = rows.reduce((sum, row) => sum + (Number(row?.rider_revenue_amount) || 0), 0);
203
+ const orderNetSale = rows.reduce((sum, row) => sum + (Number(row?.net_sale_amount) || 0), 0);
204
+ const orderFees = rows.reduce((sum, row) => sum + (Number(row?.delivery_charge_amount) || 0), 0);
205
+ const distanceMeters = rows.reduce((sum, row) => sum + (Number(row?.distance_sum_meters) || 0), 0);
206
+ // Fallback for documents written before area rows carried the order side.
207
+ const netSale = deliveryOrders > 0 ? orderNetSale : Number(block.money?.net_sale_amount) || 0;
208
+ const fees = deliveryOrders > 0 ? orderFees : Number(block.money?.delivery_charge_amount) || 0;
209
+ const payout = rows.length > 0 ? riderPayout : Number(block.money?.rider_revenue_amount) || 0;
210
+ return {
211
+ city,
212
+ delivery_orders: deliveryOrders,
213
+ app_orders: appOrders,
214
+ off_app_orders: offAppOrders,
215
+ delivery_records: deliveryRecords,
216
+ app_coverage_percent: deliveryOrders > 0 ? Math.round((appOrders / deliveryOrders) * 1000) / 10 : null,
217
+ deliveries: deliveryRecords,
218
+ completed,
219
+ cancelled,
220
+ net_sale: toDecimal(netSale),
221
+ delivery_fees: toDecimal(fees),
222
+ charges_levied: toDecimal(fees),
223
+ rider_payout: toDecimal(payout),
224
+ rider_revenue: toDecimal(payout),
225
+ avg_distance_km: safeAverage(km(distanceMeters), deliveryRecords),
226
+ };
227
+ })
228
+ .sort((a, b) => b.delivery_orders - a.delivery_orders ||
229
+ b.deliveries - a.deliveries ||
230
+ (a.city < b.city ? -1 : a.city > b.city ? 1 : 0)),
181
231
  by_rider: riders,
182
232
  distance_buckets: MATERIALIZED_DELIVERY_DISTANCE_BUCKETS.map((bucket) => ({
183
233
  label: bucket.key,