@managesome/eposmatic-toolkit 0.4.53 → 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 (61) hide show
  1. package/esm/helpers/materialized-reports/index.js +1 -0
  2. package/esm/helpers/materialized-reports/report-platform/definition.js +508 -0
  3. package/esm/helpers/materialized-reports/report-platform/index.js +4 -0
  4. package/esm/helpers/materialized-reports/report-platform/lifecycle/budget.js +27 -0
  5. package/esm/helpers/materialized-reports/report-platform/lifecycle/cap-metadata.js +12 -0
  6. package/esm/helpers/materialized-reports/report-platform/lifecycle/entry-pages.js +121 -0
  7. package/esm/helpers/materialized-reports/report-platform/lifecycle/flat-projection.js +14 -0
  8. package/esm/helpers/materialized-reports/report-platform/lifecycle/index.js +8 -0
  9. package/esm/helpers/materialized-reports/report-platform/lifecycle/iteration-row.js +10 -0
  10. package/esm/helpers/materialized-reports/report-platform/lifecycle/run-stats.js +42 -0
  11. package/esm/helpers/materialized-reports/report-platform/lifecycle/scope-refs.js +28 -0
  12. package/esm/helpers/materialized-reports/report-platform/lifecycle/top-n.js +24 -0
  13. package/esm/helpers/materialized-reports/report-platform/registry.js +23 -0
  14. package/esm/helpers/materialized-reports/report-platform/validate-report-registry.js +214 -0
  15. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  16. package/lib/helpers/materialized-reports/index.js +1 -0
  17. package/lib/helpers/materialized-reports/report-platform/definition.d.ts +133 -0
  18. package/lib/helpers/materialized-reports/report-platform/definition.js +511 -0
  19. package/lib/helpers/materialized-reports/report-platform/index.d.ts +4 -0
  20. package/lib/helpers/materialized-reports/report-platform/index.js +20 -0
  21. package/lib/helpers/materialized-reports/report-platform/lifecycle/budget.d.ts +8 -0
  22. package/lib/helpers/materialized-reports/report-platform/lifecycle/budget.js +31 -0
  23. package/lib/helpers/materialized-reports/report-platform/lifecycle/cap-metadata.d.ts +8 -0
  24. package/lib/helpers/materialized-reports/report-platform/lifecycle/cap-metadata.js +16 -0
  25. package/lib/helpers/materialized-reports/report-platform/lifecycle/entry-pages.d.ts +40 -0
  26. package/lib/helpers/materialized-reports/report-platform/lifecycle/entry-pages.js +130 -0
  27. package/lib/helpers/materialized-reports/report-platform/lifecycle/flat-projection.d.ts +22 -0
  28. package/lib/helpers/materialized-reports/report-platform/lifecycle/flat-projection.js +17 -0
  29. package/lib/helpers/materialized-reports/report-platform/lifecycle/index.d.ts +8 -0
  30. package/lib/helpers/materialized-reports/report-platform/lifecycle/index.js +24 -0
  31. package/lib/helpers/materialized-reports/report-platform/lifecycle/iteration-row.d.ts +13 -0
  32. package/lib/helpers/materialized-reports/report-platform/lifecycle/iteration-row.js +13 -0
  33. package/lib/helpers/materialized-reports/report-platform/lifecycle/run-stats.d.ts +20 -0
  34. package/lib/helpers/materialized-reports/report-platform/lifecycle/run-stats.js +47 -0
  35. package/lib/helpers/materialized-reports/report-platform/lifecycle/scope-refs.d.ts +13 -0
  36. package/lib/helpers/materialized-reports/report-platform/lifecycle/scope-refs.js +31 -0
  37. package/lib/helpers/materialized-reports/report-platform/lifecycle/top-n.d.ts +16 -0
  38. package/lib/helpers/materialized-reports/report-platform/lifecycle/top-n.js +29 -0
  39. package/lib/helpers/materialized-reports/report-platform/registry.d.ts +13 -0
  40. package/lib/helpers/materialized-reports/report-platform/registry.js +31 -0
  41. package/lib/helpers/materialized-reports/report-platform/validate-report-registry.d.ts +20 -0
  42. package/lib/helpers/materialized-reports/report-platform/validate-report-registry.js +218 -0
  43. package/lib/tests/materialized-reports/characterization/delivery.characterization.test.d.ts +1 -0
  44. package/lib/tests/materialized-reports/characterization/delivery.characterization.test.js +229 -0
  45. package/lib/tests/materialized-reports/characterization/discount.characterization.test.d.ts +1 -0
  46. package/lib/tests/materialized-reports/characterization/discount.characterization.test.js +99 -0
  47. package/lib/tests/materialized-reports/characterization/fixtures.d.ts +30 -0
  48. package/lib/tests/materialized-reports/characterization/fixtures.js +402 -0
  49. package/lib/tests/materialized-reports/characterization/golden.d.ts +18 -0
  50. package/lib/tests/materialized-reports/characterization/golden.js +127 -0
  51. package/lib/tests/materialized-reports/characterization/overview.characterization.test.d.ts +1 -0
  52. package/lib/tests/materialized-reports/characterization/overview.characterization.test.js +69 -0
  53. package/lib/tests/materialized-reports/characterization/prep-time.characterization.test.d.ts +1 -0
  54. package/lib/tests/materialized-reports/characterization/prep-time.characterization.test.js +102 -0
  55. package/lib/tests/materialized-reports/report-platform/lifecycle-primitives.test.d.ts +1 -0
  56. package/lib/tests/materialized-reports/report-platform/lifecycle-primitives.test.js +177 -0
  57. package/lib/tests/materialized-reports/report-platform/registry-conformance.test.d.ts +1 -0
  58. package/lib/tests/materialized-reports/report-platform/registry-conformance.test.js +214 -0
  59. package/lib/tests/materialized-reports/report-platform/registry-validation.test.d.ts +1 -0
  60. package/lib/tests/materialized-reports/report-platform/registry-validation.test.js +103 -0
  61. package/package.json +4 -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();
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const MATERIALIZED_REPORTS_1 = require("../../../constants/MATERIALIZED_REPORTS");
4
+ const materialized_reports_1 = require("../../../helpers/materialized-reports");
5
+ const golden_1 = require("./golden");
6
+ const fixtures_1 = require("./fixtures");
7
+ /**
8
+ * DELIVERY characterization — counters, page entries, geo cells/scopes,
9
+ * suppression/cap metadata, `#N` splitting and the formatter.
10
+ *
11
+ * Current behaviour captured deliberately:
12
+ * - entry pages use `page='all'` for the day scope and the source date for
13
+ * periods; only Delivery has the deterministic `#N` splitter;
14
+ * - ONLY Delivery has BSON budgets (report 15 MiB / page 15 MiB / cell 2 MiB);
15
+ * - off-app orders are counted but never rows; orphan deliveries are records;
16
+ * - the geo `__UNKNOWN__` aggregate is stored but never returned as a cell.
17
+ */
18
+ describe('characterization: Delivery', () => {
19
+ const fixtures = (0, fixtures_1.buildCharacterizationFixtures)();
20
+ const compiled = (0, materialized_reports_1.compileTenantDeliveryReports)({
21
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
22
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
23
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
24
+ orders: fixtures.dayOrders,
25
+ deliveries: fixtures.deliveries,
26
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
27
+ });
28
+ it('compiles counters and one entry page per entry scope', () => {
29
+ expect(compiled).not.toBeNull();
30
+ (0, golden_1.expectGolden)('delivery.compile.day', compiled);
31
+ const dayEntry = compiled.entries.find((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && entry.scope_field === fixtures_1.CHARACTERIZATION_DAY);
32
+ expect(dayEntry.page).toBe('all');
33
+ expect(compiled.entries
34
+ .filter((entry) => entry.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
35
+ .every((entry) => entry.page === fixtures_1.CHARACTERIZATION_DAY)).toBe(true);
36
+ expect(compiled.entries).toHaveLength(4); // date + week + ISO week + month
37
+ });
38
+ it('captures the off-app / orphan / adoption populations', () => {
39
+ const dayReport = compiled.reports.find((report) => report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
40
+ report.scope_field === fixtures_1.CHARACTERIZATION_DAY);
41
+ const counters = Object.values(dayReport.delivery_counters ?? {});
42
+ const adoptionOrders = counters.reduce((sum, counter) => sum + Number(counter?.adoption?.delivery_order_count ?? 0), 0);
43
+ const offApp = counters.reduce((sum, counter) => sum + Number(counter?.adoption?.off_app_count ?? 0), 0);
44
+ expect(adoptionOrders).toBe(4);
45
+ expect(offApp).toBe(1);
46
+ });
47
+ it('builds the flat drill-down projection tagged by source day', () => {
48
+ const rows = [];
49
+ const scopes = [];
50
+ for (const entry of compiled.entries) {
51
+ const sourceLocalDate = String(entry.page) === 'all' ? String(entry.scope_field) : String(entry.page);
52
+ const flattened = (0, materialized_reports_1.buildMaterializedDrilldownRows)(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DELIVERY_ENTRIES, entry, sourceLocalDate);
53
+ rows.push(...flattened.rows);
54
+ const scope = (0, materialized_reports_1.buildMaterializedDrilldownScope)(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DELIVERY_ENTRIES, entry, flattened.rows, sourceLocalDate);
55
+ if (scope != null)
56
+ scopes.push(scope);
57
+ }
58
+ (0, golden_1.expectGolden)('delivery.flat', { rows, scopes });
59
+ expect(rows.length).toBeGreaterThan(0);
60
+ expect(rows.every((row) => row.source_local_date === fixtures_1.CHARACTERIZATION_DAY)).toBe(true);
61
+ });
62
+ it('compiles H3 cells with the current suppression / cap / unknown metadata', () => {
63
+ const result = (0, materialized_reports_1.compileTenantDeliveryGeoCellsWithStats)({
64
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
65
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
66
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
67
+ orders: fixtures.dayOrders,
68
+ deliveries: fixtures.deliveries,
69
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
70
+ maxCells: 1,
71
+ });
72
+ (0, golden_1.expectGolden)('delivery.geo.day', result);
73
+ expect(result.cells.length).toBeLessThanOrEqual(1);
74
+ expect(result.cappedCellCount).toBeGreaterThanOrEqual(0);
75
+ const response = (0, materialized_reports_1.buildDeliveryGeoResponse)({
76
+ cells: result.cells,
77
+ totalOrders: 4,
78
+ totalAppOrders: 3,
79
+ cappedCellCount: result.cappedCellCount,
80
+ cappedOrderCount: result.cappedOrderCount,
81
+ maxCells: 1,
82
+ });
83
+ (0, golden_1.expectGolden)('delivery.geo.response', response);
84
+ // The geometry-less aggregate is never a plotted cell.
85
+ expect(response.cells.every((cell) => cell.h3_cell !== '__UNKNOWN__')).toBe(true);
86
+ });
87
+ it('disables the map for the folded __OTHER__ area', () => {
88
+ const disabled = (0, materialized_reports_1.buildDeliveryGeoResponse)({
89
+ cells: [],
90
+ totalOrders: 4,
91
+ totalAppOrders: 3,
92
+ mapDisabled: true,
93
+ mapDisabledReason: 'OTHER_AREAS',
94
+ });
95
+ (0, golden_1.expectGolden)('delivery.geo.map-disabled', disabled);
96
+ expect(disabled.map_disabled).toBe(true);
97
+ expect(disabled.cells).toEqual([]);
98
+ });
99
+ it('formats the day and month documents, with and without filters', () => {
100
+ const dayReport = compiled.reports.find((report) => report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
101
+ report.scope_field === fixtures_1.CHARACTERIZATION_DAY);
102
+ (0, golden_1.expectGolden)('delivery.formatted.day', (0, materialized_reports_1.getFormattedTenantDeliveryReporting)([dayReport]));
103
+ (0, golden_1.expectGolden)('delivery.formatted.day-filtered', (0, materialized_reports_1.getFormattedTenantDeliveryReporting)([dayReport], {
104
+ platforms: ['POS_DELIVERY', 'APP_DELIVERY'],
105
+ order_statuses: ['COMPLETED'],
106
+ cities: ['Istanbul', 'Ankara'],
107
+ }));
108
+ (0, golden_1.expectGolden)('delivery.formatted.day-rider-filtered', (0, materialized_reports_1.getFormattedTenantDeliveryReporting)([dayReport], { rider_ids: ['rider-1'] }));
109
+ const monthReport = compiled.reports.find((report) => report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
110
+ (0, golden_1.expectGolden)('delivery.formatted.month', (0, materialized_reports_1.getFormattedTenantDeliveryReporting)([monthReport]));
111
+ });
112
+ it('splits an oversized page deterministically and keeps page identities exact', () => {
113
+ const dayEntry = compiled.entries.find((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
114
+ // Force the split path with a deliberately small budget. The row order and
115
+ // the resulting #N names are the current contract.
116
+ const split = (0, materialized_reports_1.splitMaterializedDeliveryEntryPage)(dayEntry, 3000);
117
+ (0, golden_1.expectGolden)('delivery.split.reduced-budget', split);
118
+ expect(split.length).toBeGreaterThan(1);
119
+ expect(split.every((page) => page.page.includes('#'))).toBe(true);
120
+ expect(split.every((page) => page.page === dayEntry.page || page.page.startsWith(`${dayEntry.page}#`))).toBe(true);
121
+ // A page that fits keeps its unsuffixed identity.
122
+ const fitting = (0, materialized_reports_1.splitMaterializedDeliveryEntryPage)(dayEntry, MATERIALIZED_REPORTS_1.MATERIALIZED_DELIVERY_ENTRY_MAX_BSON_BYTES);
123
+ expect(fitting).toHaveLength(1);
124
+ expect(fitting[0].page).toBe(dayEntry.page);
125
+ });
126
+ it('bounds the city and rider dimensions to top-N + __OTHER__', () => {
127
+ const otherOrders = [];
128
+ const otherDeliveries = [];
129
+ for (let index = 0; index < 51; index += 1) {
130
+ const city = `City-${String(index).padStart(2, '0')}`;
131
+ const orderId = `other-order-${index}`;
132
+ otherOrders.push({
133
+ _id: orderId,
134
+ tenant_id: fixtures_1.CHARACTERIZATION_TENANT_ID,
135
+ platform: 'POS_DELIVERY',
136
+ order_status: 'COMPLETED',
137
+ order_number: 500 + index,
138
+ price: 1000,
139
+ amount_earned: 1000,
140
+ amount_collected: 1000,
141
+ total_discount_applied: 0,
142
+ tip_amount: 0,
143
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
144
+ localHour: 12,
145
+ is_deleted: false,
146
+ createdAt: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T11:00:00.000Z`),
147
+ updatedAt: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T12:00:00.000Z`),
148
+ order_settled_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T12:00:00.000Z`),
149
+ categories: [],
150
+ payments: [],
151
+ delivery_details: {
152
+ city,
153
+ state: city,
154
+ delivery_cost: 100,
155
+ distance_in_meters_from_store: 1000,
156
+ lat: 41 + index / 1000,
157
+ lng: 29 + index / 1000,
158
+ },
159
+ });
160
+ otherDeliveries.push({
161
+ _id: `other-delivery-${index}`,
162
+ tenant_id: fixtures_1.CHARACTERIZATION_TENANT_ID,
163
+ order_id: orderId,
164
+ rider_id: `rider-${String(index).padStart(2, '0')}`,
165
+ rider_name: `Rider ${index}`,
166
+ status: 'COMPLETED',
167
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
168
+ distance_in_meters_from_store: 1000,
169
+ tracking_enabled: false,
170
+ assigned_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:00:00.000Z`),
171
+ picked_up_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:10:00.000Z`),
172
+ expected_delivery_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:40:00.000Z`),
173
+ delivered_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:20:00.000Z`),
174
+ cancelled_at: null,
175
+ status_updated_count: 2,
176
+ delivery_minutes: 20,
177
+ rider_earnings: {
178
+ amount: 100,
179
+ status: 'FINAL',
180
+ rule_type: 'DISTANCE_ONE_WAY',
181
+ per_meter: 5000,
182
+ distance_step: 1000,
183
+ distance_meters: 1000,
184
+ delivery_charge: 100,
185
+ calculated_at: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:20:00.000Z`),
186
+ version: 1,
187
+ },
188
+ createdAt: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:00:00.000Z`),
189
+ updatedAt: new Date(`${fixtures_1.CHARACTERIZATION_DAY}T10:20:00.000Z`),
190
+ });
191
+ }
192
+ const other = (0, materialized_reports_1.compileTenantDeliveryReports)({
193
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
194
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
195
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
196
+ orders: otherOrders,
197
+ deliveries: otherDeliveries,
198
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
199
+ });
200
+ const report = other.reports.find((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
201
+ const keys = Object.keys(report.delivery_counters ?? {}).sort();
202
+ const formatted = (0, materialized_reports_1.getFormattedTenantDeliveryReporting)([report])[0][0];
203
+ (0, golden_1.expectGolden)('delivery.__other__.summary', {
204
+ key_count: keys.length,
205
+ has_other_city: keys.some((key) => key.endsWith(':__OTHER__')),
206
+ area_keys: formatted.by_area.map((row) => row.city),
207
+ rider_keys: formatted.by_rider.map((row) => row.rider_id),
208
+ summary: {
209
+ orders: formatted.summary.orders,
210
+ delivery_records: formatted.summary.delivery_records,
211
+ rider_revenue: formatted.summary.rider_revenue,
212
+ },
213
+ });
214
+ expect(keys.some((key) => key.endsWith(':__OTHER__'))).toBe(true);
215
+ expect(formatted.by_area.some((row) => row.city === '__OTHER__')).toBe(true);
216
+ expect(formatted.by_rider.some((row) => row.rider_id === '__OTHER__')).toBe(true);
217
+ });
218
+ it('returns null for a day with no delivery orders and no deliveries', () => {
219
+ const empty = (0, materialized_reports_1.compileTenantDeliveryReports)({
220
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
221
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
222
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
223
+ orders: [],
224
+ deliveries: [],
225
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
226
+ });
227
+ expect(empty).toBeNull();
228
+ });
229
+ });
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const MATERIALIZED_REPORTS_1 = require("../../../constants/MATERIALIZED_REPORTS");
4
+ const materialized_reports_1 = require("../../../helpers/materialized-reports");
5
+ const golden_1 = require("./golden");
6
+ const fixtures_1 = require("./fixtures");
7
+ /**
8
+ * DISCOUNTS characterization — compile, page identity, source projection,
9
+ * flat projection and formatter.
10
+ *
11
+ * Current behaviour captured deliberately:
12
+ * - entry pages use `page='all'` for day/hour and the SOURCE DATE for periods;
13
+ * - there is NO `#N` splitter and NO BSON budget guard on Discounts;
14
+ * - the derived source projection is written from the post-plan entries.
15
+ */
16
+ describe('characterization: Discounts', () => {
17
+ const fixtures = (0, fixtures_1.buildCharacterizationFixtures)();
18
+ const compiled = (0, materialized_reports_1.compileTenantDiscountReports)({
19
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
20
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
21
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
22
+ orders: fixtures.dayOrders,
23
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
24
+ });
25
+ it('compiles counters + entry pages with the current page identity', () => {
26
+ expect(compiled).not.toBeNull();
27
+ (0, golden_1.expectGolden)('discount.compile.day', compiled);
28
+ const dayEntries = compiled.entries.filter((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && entry.scope_field === fixtures_1.CHARACTERIZATION_DAY);
29
+ expect(dayEntries).toHaveLength(1);
30
+ expect(dayEntries[0].page).toBe('all');
31
+ const monthEntries = compiled.entries.filter((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
32
+ expect(monthEntries).toHaveLength(1);
33
+ expect(monthEntries[0].page).toBe(fixtures_1.CHARACTERIZATION_DAY);
34
+ // Current behaviour: the Discounts writer has no #N sub-page path.
35
+ expect(compiled.entries.every((entry) => !entry.page.includes('#'))).toBe(true);
36
+ });
37
+ it('builds the source projection from the post-plan day entries', () => {
38
+ const dayEntry = compiled.entries.find((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && entry.scope_field === fixtures_1.CHARACTERIZATION_DAY);
39
+ const sources = (0, materialized_reports_1.buildDiscountSourcesForScope)({
40
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
41
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
42
+ scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
43
+ scopeField: fixtures_1.CHARACTERIZATION_DAY,
44
+ sections: dayEntry.discount_entries,
45
+ sourceWatermark: dayEntry.source_watermark,
46
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
47
+ });
48
+ expect(sources).not.toBeNull();
49
+ (0, golden_1.expectGolden)('discount.sources.day', sources);
50
+ expect(sources.every((source) => source.scope_field === fixtures_1.CHARACTERIZATION_DAY)).toBe(true);
51
+ });
52
+ it('builds the flat drill-down projection for every stored scope', () => {
53
+ const rows = [];
54
+ const scopes = [];
55
+ for (const entry of compiled.entries) {
56
+ const flattened = (0, materialized_reports_1.buildMaterializedDrilldownRows)(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DISCOUNT_ENTRIES, entry, fixtures_1.CHARACTERIZATION_DAY);
57
+ rows.push(...flattened.rows);
58
+ const scope = (0, materialized_reports_1.buildMaterializedDrilldownScope)(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DISCOUNT_ENTRIES, entry, flattened.rows, fixtures_1.CHARACTERIZATION_DAY);
59
+ if (scope != null)
60
+ scopes.push(scope);
61
+ }
62
+ (0, golden_1.expectGolden)('discount.flat', { rows, scopes });
63
+ expect(rows.length).toBeGreaterThan(0);
64
+ });
65
+ it('formats the raw day documents and the aggregated read record', () => {
66
+ const dayDoc = compiled.reports.find((report) => report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
67
+ report.scope_field === fixtures_1.CHARACTERIZATION_DAY);
68
+ (0, golden_1.expectGolden)('discount.formatted.raw-day', (0, materialized_reports_1.getFormattedTenantDiscountsReporting)([dayDoc]));
69
+ (0, golden_1.expectGolden)('discount.formatted.raw-day-filtered', (0, materialized_reports_1.getFormattedTenantDiscountsReporting)([dayDoc], {
70
+ platforms: ['POS_DINE-IN', 'POS_TAKE-AWAY'],
71
+ order_statuses: ['COMPLETED'],
72
+ }));
73
+ const aggregated = {
74
+ tenant_id: dayDoc.tenant_id,
75
+ brand_id: dayDoc.brand_id,
76
+ max_iteration: dayDoc.iteration ?? 1,
77
+ max_updated_at: dayDoc.updatedAt ?? null,
78
+ matched_documents: 1,
79
+ sale_type_key_filters: dayDoc.sale_type_key_filters,
80
+ discount_counters: dayDoc.discount_counters ?? {},
81
+ first_scope_field: dayDoc.scope_field,
82
+ last_scope_field: dayDoc.scope_field,
83
+ };
84
+ (0, golden_1.expectGolden)('discount.formatted.aggregated', (0, materialized_reports_1.getFormattedTenantDiscountsAggregatedReporting)([aggregated]));
85
+ });
86
+ it('compiles an empty day to empty arrays without inventing pages', () => {
87
+ const empty = (0, materialized_reports_1.compileTenantDiscountReports)({
88
+ tenantId: fixtures_1.CHARACTERIZATION_TENANT_ID,
89
+ brandId: fixtures_1.CHARACTERIZATION_BRAND_ID,
90
+ localDate: fixtures_1.CHARACTERIZATION_DAY,
91
+ orders: [],
92
+ computedAt: fixtures_1.CHARACTERIZATION_COMPUTED_AT,
93
+ });
94
+ (0, golden_1.expectGolden)('discount.compile.empty-day', empty);
95
+ expect(empty.entries).toEqual([]);
96
+ // Current behaviour: an empty day emits NO counter documents either.
97
+ expect(empty.reports).toEqual([]);
98
+ });
99
+ });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * PHASE 1 CHARACTERIZATION FIXTURES (test-only).
3
+ *
4
+ * One compact tenant-day corpus used by the toolkit compile/formatter goldens and
5
+ * mirrored by the workers close-day goldens. It deliberately contains the known
6
+ * oddities so later platform work cannot "fix" them silently:
7
+ *
8
+ * - a deferred PAY_LATER credit bill issued on the day;
9
+ * - a prior-day credit bill collected on the day;
10
+ * - MEASURED / zero-minute / UNMEASURED prep rows and all four target sources;
11
+ * - order-level and item-level discounts, a cancellation and a free item;
12
+ * - delivery adoption (off-app order), reassignment, an orphan delivery,
13
+ * a cancelled delivery and invalid (0,0) coordinates.
14
+ *
15
+ * Dates are fixed. `_id`s are fixed strings; the golden helper still replaces them
16
+ * with stable placeholders because several production builders mint ObjectIds.
17
+ */
18
+ export declare const CHARACTERIZATION_TENANT_ID = "tenant-characterization";
19
+ export declare const CHARACTERIZATION_BRAND_ID = "brand-characterization";
20
+ export declare const CHARACTERIZATION_TENANT_NAME = "Characterization Store";
21
+ export declare const CHARACTERIZATION_DAY = "2026-09-14";
22
+ export declare const CHARACTERIZATION_PREV_DAY = "2026-09-13";
23
+ export declare const CHARACTERIZATION_NEXT_DAY = "2026-09-15";
24
+ export declare const CHARACTERIZATION_COMPUTED_AT: Date;
25
+ export interface ICharacterizationFixtures {
26
+ orders: any[];
27
+ deliveries: any[];
28
+ dayOrders: any[];
29
+ }
30
+ export declare function buildCharacterizationFixtures(): ICharacterizationFixtures;