@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,218 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REPORT_REGISTRY_VALIDATION = void 0;
4
+ exports.validateReportRegistry = validateReportRegistry;
5
+ const MATERIALIZED_REPORTS_1 = require("../../../constants/MATERIALIZED_REPORTS");
6
+ const report_contract_1 = require("../../reporting-contract/report-contract");
7
+ const definition_1 = require("./definition");
8
+ const MATERIALIZED_PREFIX = 'materialized_';
9
+ const isPositiveInteger = (value) => typeof value === 'number' && Number.isInteger(value) && value > 0;
10
+ const isNonEmptyString = (value) => typeof value === 'string' && value.trim() !== '';
11
+ function validateCollection(definition, label, collection, errors, warnings) {
12
+ if (!isNonEmptyString(collection.name)) {
13
+ errors.push(`${definition.key}: ${label} has no collection name`);
14
+ return;
15
+ }
16
+ if (!collection.name.startsWith(MATERIALIZED_PREFIX)) {
17
+ errors.push(`${definition.key}: ${label} collection "${collection.name}" is not a materialized_* collection`);
18
+ }
19
+ if (!isPositiveInteger(collection.schemaVersion)) {
20
+ errors.push(`${definition.key}: ${label} has no positive schema version`);
21
+ }
22
+ if (!isPositiveInteger(collection.budgetBytes)) {
23
+ errors.push(`${definition.key}: ${label} has no positive budget`);
24
+ }
25
+ if (!isNonEmptyString(collection.indexOwner)) {
26
+ errors.push(`${definition.key}: ${label} has no index ownership`);
27
+ }
28
+ if (collection.validatorFile == null && !isNonEmptyString(collection.validatorDebt)) {
29
+ errors.push(`${definition.key}: ${label} has neither a validator file nor a declared validator debt`);
30
+ }
31
+ if (collection.validatorFile == null && isNonEmptyString(collection.validatorDebt)) {
32
+ warnings.push(`${definition.key}: ${label} validator debt: ${collection.validatorDebt}`);
33
+ }
34
+ if (definition.budgets[collection.name] == null || !isPositiveInteger(definition.budgets[collection.name])) {
35
+ errors.push(`${definition.key}: collection "${collection.name}" has no budget declaration in budgets`);
36
+ }
37
+ }
38
+ function validateScopes(definition, label, scopes, errors) {
39
+ if (scopes.length === 0) {
40
+ errors.push(`${definition.key}: ${label} has no scopes`);
41
+ return;
42
+ }
43
+ const seen = new Set();
44
+ for (const scope of scopes) {
45
+ if (!MATERIALIZED_REPORTS_1.ALL_MATERIALIZED_REPORT_SCOPES.includes(scope)) {
46
+ errors.push(`${definition.key}: ${label} has unknown scope "${String(scope)}"`);
47
+ }
48
+ if (seen.has(String(scope))) {
49
+ errors.push(`${definition.key}: ${label} repeats scope "${String(scope)}"`);
50
+ }
51
+ seen.add(String(scope));
52
+ }
53
+ }
54
+ function validateReportRegistry(input = {}) {
55
+ const definitions = input.definitions ?? definition_1.REPORT_DEFINITIONS;
56
+ const exemptions = input.exemptions ?? definition_1.REPORT_REGISTRY_EXEMPTIONS;
57
+ const keys = input.keys ?? report_contract_1.ALL_REPORT_KEYS;
58
+ const errors = [];
59
+ const warnings = [];
60
+ for (const key of keys) {
61
+ const definition = definitions[key];
62
+ const exemption = exemptions[key];
63
+ if (definition == null && exemption == null) {
64
+ errors.push(`${key}: no report definition and no explicit exemption`);
65
+ continue;
66
+ }
67
+ if (definition != null && exemption != null) {
68
+ errors.push(`${key}: both a report definition and an exemption exist`);
69
+ }
70
+ if (definition == null)
71
+ continue;
72
+ if (definition.key !== key) {
73
+ errors.push(`${key}: definition key is "${definition.key}"`);
74
+ }
75
+ if (definition.status !== definition_1.REPORT_DEFINITION_STATUS.PRODUCTION &&
76
+ definition.status !== definition_1.REPORT_DEFINITION_STATUS.READ_ONLY) {
77
+ errors.push(`${key}: a concrete definition must be PRODUCTION or READ_ONLY`);
78
+ }
79
+ if (!isNonEmptyString(definition.owner))
80
+ errors.push(`${key}: no owner`);
81
+ if (!MATERIALIZED_REPORTS_1.ALL_MATERIALIZED_REPORT_TYPES.includes(definition.reportType)) {
82
+ errors.push(`${key}: unknown report type "${String(definition.reportType)}"`);
83
+ }
84
+ if (definition.segment !== report_contract_1.REPORT_ROUTE_SEGMENTS[definition.key]) {
85
+ errors.push(`${key}: segment "${definition.segment}" disagrees with REPORT_ROUTE_SEGMENTS`);
86
+ }
87
+ const expectedCapabilities = report_contract_1.REPORT_CAPABILITIES[definition.key];
88
+ if (expectedCapabilities == null ||
89
+ expectedCapabilities.live !== definition.capabilities.live ||
90
+ expectedCapabilities.historical !== definition.capabilities.historical ||
91
+ expectedCapabilities.details !== definition.capabilities.details) {
92
+ errors.push(`${key}: capabilities disagree with REPORT_CAPABILITIES`);
93
+ }
94
+ validateCollection(definition, 'report', definition.report, errors, warnings);
95
+ if (definition.entries != null) {
96
+ validateCollection(definition, 'entries', definition.entries, errors, warnings);
97
+ }
98
+ for (const side of definition.sideCollections) {
99
+ validateCollection(definition, 'side', side, errors, warnings);
100
+ }
101
+ const allCollections = [
102
+ definition.report,
103
+ ...(definition.entries == null ? [] : [definition.entries]),
104
+ ...definition.sideCollections,
105
+ ].map((collection) => collection.name);
106
+ for (const collectionName of Object.keys(definition.budgets)) {
107
+ if (!allCollections.includes(collectionName)) {
108
+ warnings.push(`${key}: budget declared for unknown collection "${collectionName}"`);
109
+ }
110
+ }
111
+ validateScopes(definition, 'reportScopes', definition.reportScopes, errors);
112
+ if (definition.entryScopes.length > 0 || definition.entryStorage !== definition_1.REPORT_ENTRY_STORAGE.NONE) {
113
+ validateScopes(definition, 'entryScopes', definition.entryScopes, errors);
114
+ }
115
+ if (!definition.reportScopes.includes(definition.maxReportScope)) {
116
+ errors.push(`${key}: maxReportScope is not a declared report scope`);
117
+ }
118
+ if (definition.maxEntryScope != null && !definition.entryScopes.includes(definition.maxEntryScope)) {
119
+ errors.push(`${key}: maxEntryScope is not a declared entry scope`);
120
+ }
121
+ for (const scope of definition.entryScopes) {
122
+ if (!definition.reportScopes.includes(scope)) {
123
+ errors.push(`${key}: entry scope "${scope}" is outside reportScopes`);
124
+ }
125
+ }
126
+ if (definition.entryStorage === definition_1.REPORT_ENTRY_STORAGE.NONE) {
127
+ if (definition.entries != null) {
128
+ errors.push(`${key}: entryStorage NONE must not declare an entry collection`);
129
+ }
130
+ if (definition.entryScopes.length !== 0) {
131
+ errors.push(`${key}: entryStorage NONE must not declare entry scopes`);
132
+ }
133
+ if (definition.entrySplit !== definition_1.REPORT_ENTRY_SPLIT.NONE) {
134
+ errors.push(`${key}: entryStorage NONE must not split pages`);
135
+ }
136
+ if (definition.maxEntryScope != null) {
137
+ errors.push(`${key}: entryStorage NONE must not declare maxEntryScope`);
138
+ }
139
+ }
140
+ else {
141
+ if (definition.entries == null) {
142
+ errors.push(`${key}: entry storage requires an entry collection`);
143
+ }
144
+ if (definition.entryScopes.length === 0) {
145
+ errors.push(`${key}: entry storage requires entry scopes`);
146
+ }
147
+ if (definition.maxEntryScope == null) {
148
+ errors.push(`${key}: entry storage requires maxEntryScope`);
149
+ }
150
+ }
151
+ if (definition.entrySplit === definition_1.REPORT_ENTRY_SPLIT.DETERMINISTIC_SUBPAGES &&
152
+ definition.entryStorage !== definition_1.REPORT_ENTRY_STORAGE.PAGE_PER_SOURCE_DAY) {
153
+ errors.push(`${key}: #N splitting requires page-per-source-day entries`);
154
+ }
155
+ if (definition.projections.includes(definition_1.REPORT_PROJECTION.FLAT_DRILLDOWN)) {
156
+ const names = definition.sideCollections.map((collection) => collection.name);
157
+ if (!names.includes('materialized_report_drilldown_rows') ||
158
+ !names.includes('materialized_report_drilldown_scopes')) {
159
+ errors.push(`${key}: FLAT_DRILLDOWN requires both flat collections`);
160
+ }
161
+ }
162
+ if (definition.projections.includes(definition_1.REPORT_PROJECTION.DISCOUNT_SOURCES) &&
163
+ !definition.sideCollections.some((collection) => collection.name === 'materialized_tenant_discount_sources')) {
164
+ errors.push(`${key}: DISCOUNT_SOURCES requires the source collection`);
165
+ }
166
+ if (definition.projections.includes(definition_1.REPORT_PROJECTION.DELIVERY_GEO)) {
167
+ const names = definition.sideCollections.map((collection) => collection.name);
168
+ if (!names.includes('materialized_tenant_delivery_geo_cells') ||
169
+ !names.includes('materialized_tenant_delivery_geo_scopes')) {
170
+ errors.push(`${key}: DELIVERY_GEO requires cells + cap metadata`);
171
+ }
172
+ }
173
+ if (definition.capabilities.details &&
174
+ (definition.adapters.details == null || !isNonEmptyString(definition.adapters.details))) {
175
+ errors.push(`${key}: capabilities.details is true but no details adapter is declared`);
176
+ }
177
+ if (!definition.capabilities.details && definition.adapters.details != null) {
178
+ errors.push(`${key}: details adapter declared without details capability`);
179
+ }
180
+ if (!isNonEmptyString(definition.adapters.writer))
181
+ errors.push(`${key}: no writer adapter`);
182
+ if (!isNonEmptyString(definition.adapters.live))
183
+ errors.push(`${key}: no live adapter`);
184
+ if (!isNonEmptyString(definition.adapters.historical)) {
185
+ errors.push(`${key}: no historical adapter`);
186
+ }
187
+ if (definition.completeness.details === 'FLAT_PROJECTION' &&
188
+ !definition.projections.includes(definition_1.REPORT_PROJECTION.FLAT_DRILLDOWN)) {
189
+ errors.push(`${key}: details completeness requires the flat projection`);
190
+ }
191
+ if (definition.filters.length === 0) {
192
+ errors.push(`${key}: no filter definitions`);
193
+ }
194
+ for (const filter of definition.filters) {
195
+ if (!isNonEmptyString(filter.id))
196
+ errors.push(`${key}: filter without an id`);
197
+ if (filter.mode !== 'CLIENT' && filter.mode !== 'SERVER') {
198
+ errors.push(`${key}: filter "${filter.id}" has an invalid mode`);
199
+ }
200
+ if (!['SUMMARY', 'DETAILS', 'BOTH'].includes(filter.appliesTo)) {
201
+ errors.push(`${key}: filter "${filter.id}" has an invalid appliesTo`);
202
+ }
203
+ }
204
+ if (definition.capabilities.details && definition.cursor === 'NONE') {
205
+ warnings.push(`${key}: details capability but cursor NONE`);
206
+ }
207
+ for (const rule of definition.retention) {
208
+ if (!allCollections.includes(rule.collection)) {
209
+ errors.push(`${key}: retention targets an unknown collection "${rule.collection}"`);
210
+ }
211
+ if (!isPositiveInteger(rule.amount)) {
212
+ errors.push(`${key}: retention amount must be a positive integer`);
213
+ }
214
+ }
215
+ }
216
+ return { ok: errors.length === 0, errors, warnings };
217
+ }
218
+ exports.REPORT_REGISTRY_VALIDATION = validateReportRegistry();
@@ -77,3 +77,11 @@ export interface IMaterializedPeriodDayScopeRange {
77
77
  * Returns `null` (never throws) for a malformed date.
78
78
  */
79
79
  export declare function getMaterializedPeriodDayScopeRange(localDate: string): IMaterializedPeriodDayScopeRange | null;
80
+ /**
81
+ * Every `localDate` label whose DAY documents can contribute to the period scopes the
82
+ * given date rolls into. The close-day writer uses it to fetch exactly the sibling DAY
83
+ * documents a period re-fold needs - never a full-period document.
84
+ *
85
+ * Returns `null` (never throws) for a malformed date or scope field.
86
+ */
87
+ export declare function enumerateMaterializedPeriodDays(localDate: string, scopes: readonly MATERIALIZED_REPORT_SCOPE_ENUM[]): string[] | null;
@@ -6,6 +6,7 @@ exports.getDayIndexFromLocalDate = getDayIndexFromLocalDate;
6
6
  exports.getMaterializedPeriodScopeFields = getMaterializedPeriodScopeFields;
7
7
  exports.getMaterializedHourScopeField = getMaterializedHourScopeField;
8
8
  exports.getMaterializedPeriodDayScopeRange = getMaterializedPeriodDayScopeRange;
9
+ exports.enumerateMaterializedPeriodDays = enumerateMaterializedPeriodDays;
9
10
  const ENUMS_1 = require("../../constants/ENUMS");
10
11
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
11
12
  const time_helpers_1 = require("../utils/time-helpers");
@@ -140,3 +141,101 @@ function getMaterializedPeriodDayScopeRange(localDate) {
140
141
  lte: toKey(new Date(Date.UTC(year, 11, 31 + 7))),
141
142
  };
142
143
  }
144
+ /* ------------------------------------------------------------------------ */
145
+ /* Period sibling-day enumeration */
146
+ /* ------------------------------------------------------------------------ */
147
+ const pad2 = (value) => String(value).padStart(2, '0');
148
+ const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
149
+ const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
150
+ const addMonthDays = (year, month, count, days) => {
151
+ if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12)
152
+ return false;
153
+ for (let offset = 0; offset < count; offset += 1) {
154
+ const date = new Date(Date.UTC(year, month - 1 + offset, 1));
155
+ const monthYear = date.getUTCFullYear();
156
+ const monthNumber = date.getUTCMonth() + 1;
157
+ const last = new Date(Date.UTC(monthYear, monthNumber, 0)).getUTCDate();
158
+ for (let day = 1; day <= last; day += 1) {
159
+ days.add(`${monthYear}-${pad2(monthNumber)}-${pad2(day)}`);
160
+ }
161
+ }
162
+ return true;
163
+ };
164
+ const addPeriodDays = (scope, scopeField, days) => {
165
+ switch (scope) {
166
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
167
+ const parts = parseMaterializedLocalDate(scopeField);
168
+ if (parts == null)
169
+ return false;
170
+ const start = new Date(Date.UTC(parts.year, parts.month - 1, parts.day));
171
+ if (start.getUTCDay() !== 0)
172
+ return false;
173
+ for (let offset = 0; offset < 7; offset += 1)
174
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
175
+ return true;
176
+ }
177
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
178
+ const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
179
+ if (match == null)
180
+ return false;
181
+ const weekYear = Number(match[1]);
182
+ const week = Number(match[2]);
183
+ if (!Number.isInteger(week) || week < 1 || week > 53)
184
+ return false;
185
+ const jan4 = new Date(Date.UTC(weekYear, 0, 4));
186
+ const isoWeekday = jan4.getUTCDay() || 7;
187
+ const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
188
+ const start = addUtcDays(weekOneMonday, (week - 1) * 7);
189
+ for (let offset = 0; offset < 7; offset += 1)
190
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
191
+ return true;
192
+ }
193
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH: {
194
+ const match = /^(\d{4})-(\d{2})$/.exec(scopeField);
195
+ if (match == null)
196
+ return false;
197
+ return addMonthDays(Number(match[1]), Number(match[2]), 1, days);
198
+ }
199
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER: {
200
+ const match = /^(\d{4})-Q([1-4])$/.exec(scopeField);
201
+ if (match == null)
202
+ return false;
203
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 3 + 1, 3, days);
204
+ }
205
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER: {
206
+ const match = /^(\d{4})-S([12])$/.exec(scopeField);
207
+ if (match == null)
208
+ return false;
209
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 6 + 1, 6, days);
210
+ }
211
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR: {
212
+ const match = /^(\d{4})$/.exec(scopeField);
213
+ if (match == null)
214
+ return false;
215
+ return addMonthDays(Number(match[1]), 1, 12, days);
216
+ }
217
+ default:
218
+ return false;
219
+ }
220
+ };
221
+ /**
222
+ * Every `localDate` label whose DAY documents can contribute to the period scopes the
223
+ * given date rolls into. The close-day writer uses it to fetch exactly the sibling DAY
224
+ * documents a period re-fold needs - never a full-period document.
225
+ *
226
+ * Returns `null` (never throws) for a malformed date or scope field.
227
+ */
228
+ function enumerateMaterializedPeriodDays(localDate, scopes) {
229
+ const periodFields = getMaterializedPeriodScopeFields(localDate);
230
+ if (periodFields == null)
231
+ return null;
232
+ const days = new Set([localDate]);
233
+ for (const scope of scopes) {
234
+ const scopeField = periodFields[scope];
235
+ if (typeof scopeField !== 'string' || scopeField.length === 0)
236
+ return null;
237
+ if (!addPeriodDays(scope, scopeField, days))
238
+ return null;
239
+ }
240
+ return [...days].sort();
241
+ }
@@ -15,6 +15,8 @@ import { IMaterializedTenantDeliveryReport } from '../../schemas/types/materiali
15
15
  */
16
16
  /** Request-level filters. Scope selection itself is resolved server-side. */
17
17
  export interface IFormattedDeliveryFilters {
18
+ /** Restrict to these order statuses (the ORDER_STATUS component of a key). */
19
+ order_statuses?: string[] | null;
18
20
  /** Restrict to these platforms (the PLATFORM component of a key). */
19
21
  platforms?: string[] | null;
20
22
  /** Restrict to these cities (the CITY component of a key). */
@@ -32,14 +34,29 @@ export interface IFormattedDeliveryAdoption {
32
34
  with_dropoff_proof: number;
33
35
  }
34
36
  export interface IFormattedDeliverySummary {
37
+ /** Delivery ORDERS - the adoption denominator and the order-side money population. */
38
+ orders: number;
39
+ /** Unique orders with at least one delivery document. */
40
+ app_orders: number;
41
+ /** Delivery orders with NO delivery document (never delivery rows). */
42
+ off_app_orders: number;
43
+ /** Delivery DOCUMENTS / attempts - one order may have several after reassignment. */
44
+ delivery_records: number;
45
+ /** Alias of `delivery_records` kept for the existing page components. */
35
46
  deliveries: number;
36
47
  completed: number;
37
48
  cancelled: number;
38
49
  in_progress: number;
50
+ /** CENTS, finalized rider payout only (app side). */
39
51
  rider_revenue: number;
52
+ /** Alias of `rider_revenue` (the Sales tab's label). */
53
+ rider_payout: number;
40
54
  net_sale: number;
41
55
  collected: number;
56
+ /** CENTS, order-side delivery fees (off-app orders included). */
42
57
  charges_levied: number;
58
+ /** Alias of `charges_levied` (the Sales tab's label). */
59
+ delivery_fees: number;
43
60
  total_distance_km: number;
44
61
  average_distance_km: number | null;
45
62
  average_rider_revenue: number | null;
@@ -57,6 +74,8 @@ export interface IFormattedDeliverySummary {
57
74
  average_status_updates: number | null;
58
75
  cancelled_after_pickup: number;
59
76
  promise_known: number;
77
+ /** `promise_known / completed` as a percentage; null when nothing was completed. */
78
+ eta_coverage_percent: number | null;
60
79
  on_time: number;
61
80
  on_time_percent: number | null;
62
81
  late: number;
@@ -71,12 +90,29 @@ export interface IFormattedDeliveryPlatformRow {
71
90
  rider_revenue: number;
72
91
  avg_distance_km: number | null;
73
92
  }
93
+ /**
94
+ * One area row. The two populations are separate columns on purpose:
95
+ * `delivery_orders` (order side, off-app included) is NOT `delivery_records` (app side,
96
+ * attempts), and `app_orders` is the unique-order intersection.
97
+ */
74
98
  export interface IFormattedDeliveryAreaRow {
75
99
  city: string;
100
+ delivery_orders: number;
101
+ app_orders: number;
102
+ off_app_orders: number;
103
+ delivery_records: number;
104
+ /** `app_orders / delivery_orders` as a percentage; null with no delivery orders. */
105
+ app_coverage_percent: number | null;
106
+ /** Alias of `delivery_records`, kept for the existing page components. */
76
107
  deliveries: number;
77
108
  completed: number;
109
+ cancelled: number;
78
110
  net_sale: number;
111
+ delivery_fees: number;
112
+ /** Alias of `delivery_fees`, kept for the existing page components. */
79
113
  charges_levied: number;
114
+ rider_payout: number;
115
+ /** Alias of `rider_payout`, kept for the existing page components. */
80
116
  rider_revenue: number;
81
117
  avg_distance_km: number | null;
82
118
  }
@@ -95,9 +131,14 @@ export interface IFormattedDeliveryDistanceBucket {
95
131
  count: number;
96
132
  percent: number;
97
133
  }
134
+ /**
135
+ * One demand-heat bucket: DELIVERY ORDERS in a city at the JOINED ORDER's local hour.
136
+ * `deliveries` is kept as a compatibility alias for the page's existing label.
137
+ */
98
138
  export interface IFormattedDeliveryHotArea {
99
139
  city: string;
100
140
  hour: number;
141
+ orders: number;
101
142
  deliveries: number;
102
143
  }
103
144
  export interface IFormattedDeliveryWeekdayRow {
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getFormattedTenantDeliveryReporting = getFormattedTenantDeliveryReporting;
4
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
4
5
  const price_conversion_1 = require("../utils/price-conversion");
5
- const materialized_delivery_classification_helpers_1 = require("./materialized-delivery-classification-helpers");
6
6
  const materialized_delivery_accumulator_helpers_1 = require("./materialized-delivery-accumulator-helpers");
7
- const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
7
+ const materialized_delivery_classification_helpers_1 = require("./materialized-delivery-classification-helpers");
8
8
  const toDecimal = (cents) => (0, price_conversion_1.convertPriceFromCents)(cents ?? 0);
9
9
  const km = (meters) => Math.round(((meters ?? 0) / 1000) * 100) / 100;
10
10
  const safeAverage = (total, count) => count > 0 ? Math.round((total / count) * 100) / 100 : null;
@@ -14,6 +14,10 @@ function keyPassesFilters(key, filters) {
14
14
  const parsed = (0, materialized_delivery_classification_helpers_1.parseMaterializedDeliveryKey)(key);
15
15
  if (parsed == null)
16
16
  return true; // never hide a key we cannot parse
17
+ const orderStatuses = filters.order_statuses;
18
+ if (orderStatuses != null && orderStatuses.length > 0 && !orderStatuses.includes(parsed.order_status)) {
19
+ return false;
20
+ }
17
21
  const platforms = filters.platforms;
18
22
  if (platforms != null && platforms.length > 0 && !platforms.includes(parsed.platform))
19
23
  return false;
@@ -98,17 +102,21 @@ function buildPageForTenant(tenantIds, docs, filters) {
98
102
  last_delivery_at: row.last_delivery_at == null ? null : new Date(row.last_delivery_at),
99
103
  });
100
104
  }
101
- riders.sort((a, b) => b.deliveries - a.deliveries);
105
+ // Deterministic: deliveries DESC, rider id ASC (a tie must never depend on key order).
106
+ riders.sort((a, b) => b.deliveries - a.deliveries || (a.rider_id < b.rider_id ? -1 : a.rider_id > b.rider_id ? 1 : 0));
107
+ // DEMAND heat: every delivery ORDER (off-app included), bucketed by the JOINED
108
+ // ORDER's local hour. It is deliberately NOT the delivery-record count - the map must
109
+ // show where delivery demand IS, not only where the rider app was used.
102
110
  const hotAreas = [];
103
111
  for (const [city, row] of Object.entries(total.areas ?? {})) {
104
112
  for (const [hour, count] of Object.entries(row.by_hour ?? {})) {
105
113
  const numeric = Number(count) || 0;
106
114
  if (numeric === 0)
107
115
  continue;
108
- hotAreas.push({ city, hour: Number(hour) || 0, deliveries: numeric });
116
+ hotAreas.push({ city, hour: Number(hour) || 0, orders: numeric, deliveries: numeric });
109
117
  }
110
118
  }
111
- hotAreas.sort((a, b) => b.deliveries - a.deliveries);
119
+ hotAreas.sort((a, b) => b.orders - a.orders || (a.city < b.city ? -1 : a.city > b.city ? 1 : 0) || a.hour - b.hour);
112
120
  const totalDistance = Number(distance.sum_meters) || 0;
113
121
  const distanceCount = Number(distance.count) || 0;
114
122
  return {
@@ -127,14 +135,26 @@ function buildPageForTenant(tenantIds, docs, filters) {
127
135
  with_dropoff_proof: Number(adoption.proof_dropoff_count) || 0,
128
136
  },
129
137
  summary: {
138
+ // The POPULATIONS, side by side and never conflated.
139
+ orders: Number(adoption.delivery_order_count) || 0,
140
+ app_orders: Number(adoption.delivered_via_app_count) || 0,
141
+ off_app_orders: Number(adoption.off_app_count) || 0,
142
+ delivery_records: Number(deliveries.count) || 0,
130
143
  deliveries: Number(deliveries.count) || 0,
131
144
  completed: completedForTiming,
132
145
  cancelled: Number(deliveries.cancelled_count) || 0,
133
- in_progress: Number(deliveries.in_progress_count) || 0,
146
+ // "Open" = PENDING + ASSIGNED + IN_PROGRESS (one definition shared with the
147
+ // statement view and the volume chart's Open bucket). The status-specific counters
148
+ // remain available on the counter block.
149
+ in_progress: (Number(deliveries.pending_count) || 0) +
150
+ (Number(deliveries.assigned_count) || 0) +
151
+ (Number(deliveries.in_progress_count) || 0),
134
152
  rider_revenue: toDecimal(money.rider_revenue_amount),
153
+ rider_payout: toDecimal(money.rider_revenue_amount),
135
154
  net_sale: toDecimal(money.net_sale_amount),
136
155
  collected: toDecimal(money.collected_amount),
137
156
  charges_levied: toDecimal(money.delivery_charge_amount),
157
+ delivery_fees: toDecimal(money.delivery_charge_amount),
138
158
  tips: toDecimal(money.tip_amount),
139
159
  discounts: toDecimal(money.discount_amount),
140
160
  refunds: toDecimal(money.refund_amount),
@@ -142,9 +162,9 @@ function buildPageForTenant(tenantIds, docs, filters) {
142
162
  total_distance_km: km(totalDistance),
143
163
  average_distance_km: safeAverage(km(totalDistance), distanceCount),
144
164
  average_rider_revenue: safeAverage(toDecimal(money.rider_revenue_amount), Number(money.rider_revenue_count) || 0),
145
- average_dispatch_lag_minutes: safeAverage(Number(timing?.dispatch_lag_sum_minutes) || 0, Number(timing?.graded_count) || 0),
146
- average_complete_minutes: safeAverage(Number(timing?.complete_sum_minutes) || 0, Number(timing?.graded_count) || 0),
147
- average_total_minutes: safeAverage(Number(timing?.total_sum_minutes) || 0, Number(timing?.graded_count) || 0),
165
+ average_dispatch_lag_minutes: safeAverage(Number(timing?.dispatch_lag_sum_minutes) || 0, Number(timing?.dispatch_lag_count ?? timing?.graded_count) || 0),
166
+ average_complete_minutes: safeAverage(Number(timing?.complete_sum_minutes) || 0, Number(timing?.complete_count ?? completedForTiming) || 0),
167
+ average_total_minutes: safeAverage(Number(timing?.total_sum_minutes) || 0, Number(timing?.total_count ?? completedForTiming) || 0),
148
168
  average_assignment_minutes: safeAverage(Number(timing?.assignment_sum_minutes) || 0, Number(timing?.assignment_count) || 0),
149
169
  average_pickup_wait_minutes: safeAverage(Number(timing?.pickup_wait_sum_minutes) || 0, Number(timing?.pickup_wait_count) || 0),
150
170
  average_transit_minutes: safeAverage(Number(timing?.transit_sum_minutes) || 0, Number(timing?.transit_count) || 0),
@@ -152,6 +172,9 @@ function buildPageForTenant(tenantIds, docs, filters) {
152
172
  average_status_updates: safeAverage(Number(timing?.status_updates_sum) || 0, Number(timing?.status_updates_count) || 0),
153
173
  cancelled_after_pickup: Number(timing?.cancelled_after_pickup_count) || 0,
154
174
  promise_known: Number(timing?.promise_known_count) || 0,
175
+ eta_coverage_percent: completedForTiming > 0
176
+ ? Math.round(((Number(timing?.promise_known_count) || 0) / completedForTiming) * 1000) / 10
177
+ : null,
155
178
  on_time: Number(timing?.on_time_count) || 0,
156
179
  on_time_percent: Number(timing?.promise_known_count) > 0
157
180
  ? Math.round(((Number(timing?.on_time_count) || 0) / Number(timing?.promise_known_count)) * 1000) / 10
@@ -169,18 +192,45 @@ function buildPageForTenant(tenantIds, docs, filters) {
169
192
  rider_revenue: toDecimal(block.money?.rider_revenue_amount),
170
193
  avg_distance_km: safeAverage(km(Number(block.distance.sum_meters) || 0), Number(block.distance.count) || 0),
171
194
  }))
172
- .sort((a, b) => b.deliveries - a.deliveries),
195
+ .sort((a, b) => b.deliveries - a.deliveries || (a.platform < b.platform ? -1 : a.platform > b.platform ? 1 : 0)),
173
196
  by_area: [...byCity.entries()]
174
- .map(([city, block]) => ({
175
- city,
176
- deliveries: Number(block.deliveries?.count) || 0,
177
- completed: Number(block.deliveries?.completed_count) || 0,
178
- net_sale: toDecimal(block.money?.net_sale_amount),
179
- charges_levied: toDecimal(block.money?.delivery_charge_amount),
180
- rider_revenue: toDecimal(block.money?.rider_revenue_amount),
181
- avg_distance_km: safeAverage(km(Number(block.distance.sum_meters) || 0), Number(block.distance.count) || 0),
182
- }))
183
- .sort((a, b) => b.deliveries - a.deliveries),
197
+ .map(([city, block]) => {
198
+ const rows = Object.values(block.areas ?? {});
199
+ const deliveryOrders = rows.reduce((sum, row) => sum + (Number(row?.delivery_orders) || 0), 0);
200
+ const appOrders = rows.reduce((sum, row) => sum + (Number(row?.app_orders) || 0), 0);
201
+ const offAppOrders = rows.reduce((sum, row) => sum + (Number(row?.off_app_orders) || 0), 0);
202
+ const deliveryRecords = rows.reduce((sum, row) => sum + (Number(row?.delivery_records ?? row?.count) || 0), 0);
203
+ const completed = rows.reduce((sum, row) => sum + (Number(row?.completed_count) || 0), 0);
204
+ const cancelled = rows.reduce((sum, row) => sum + (Number(row?.cancelled_count) || 0), 0);
205
+ const riderPayout = rows.reduce((sum, row) => sum + (Number(row?.rider_revenue_amount) || 0), 0);
206
+ const orderNetSale = rows.reduce((sum, row) => sum + (Number(row?.net_sale_amount) || 0), 0);
207
+ const orderFees = rows.reduce((sum, row) => sum + (Number(row?.delivery_charge_amount) || 0), 0);
208
+ const distanceMeters = rows.reduce((sum, row) => sum + (Number(row?.distance_sum_meters) || 0), 0);
209
+ // Fallback for documents written before area rows carried the order side.
210
+ const netSale = deliveryOrders > 0 ? orderNetSale : Number(block.money?.net_sale_amount) || 0;
211
+ const fees = deliveryOrders > 0 ? orderFees : Number(block.money?.delivery_charge_amount) || 0;
212
+ const payout = rows.length > 0 ? riderPayout : Number(block.money?.rider_revenue_amount) || 0;
213
+ return {
214
+ city,
215
+ delivery_orders: deliveryOrders,
216
+ app_orders: appOrders,
217
+ off_app_orders: offAppOrders,
218
+ delivery_records: deliveryRecords,
219
+ app_coverage_percent: deliveryOrders > 0 ? Math.round((appOrders / deliveryOrders) * 1000) / 10 : null,
220
+ deliveries: deliveryRecords,
221
+ completed,
222
+ cancelled,
223
+ net_sale: toDecimal(netSale),
224
+ delivery_fees: toDecimal(fees),
225
+ charges_levied: toDecimal(fees),
226
+ rider_payout: toDecimal(payout),
227
+ rider_revenue: toDecimal(payout),
228
+ avg_distance_km: safeAverage(km(distanceMeters), deliveryRecords),
229
+ };
230
+ })
231
+ .sort((a, b) => b.delivery_orders - a.delivery_orders ||
232
+ b.deliveries - a.deliveries ||
233
+ (a.city < b.city ? -1 : a.city > b.city ? 1 : 0)),
184
234
  by_rider: riders,
185
235
  distance_buckets: MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_DISTANCE_BUCKETS.map((bucket) => ({
186
236
  label: bucket.key,
@@ -0,0 +1,25 @@
1
+ import { IOrderPayment } from '../../schemas/types/orders';
2
+ /**
3
+ * Server-owned `collected_at` stamping for order payments.
4
+ *
5
+ * A payment line is the unit a credit bill lives on: the sale is issued on the
6
+ * punch day, and money may arrive later (full or partial). `order_settled_at`
7
+ * only moves on FULL settlement, so it cannot anchor a partial collection.
8
+ * This helper records the LAST collection moment on the payment itself,
9
+ * derived by comparing `amount_paid` with the stored previous version.
10
+ *
11
+ * Rules:
12
+ * - never trust the incoming `collected_at` (clients may send anything);
13
+ * - a NEW payment line with money in (`amount_paid > 0`) gets `now`;
14
+ * - an EXISTING line whose `amount_paid` increased gets `now`;
15
+ * - unchanged / decreased / zero-amount lines keep the stored timestamp
16
+ * (`null` when unknown — legacy rows are not backfilled here).
17
+ *
18
+ * Pure and never throws. `previousPayments` must be the SERVER copy of the
19
+ * order's payments before the write (pass none on create).
20
+ */
21
+ export interface IStampPaymentCollectionTimestampsOptions {
22
+ /** Override for the collection instant (tests / offline replays). */
23
+ now?: Date | string | null;
24
+ }
25
+ export declare function stampPaymentCollectionTimestamps(payments: IOrderPayment[] | null | undefined, previousPayments?: IOrderPayment[] | null | undefined, options?: IStampPaymentCollectionTimestampsOptions): IOrderPayment[];