@managesome/eposmatic-toolkit 0.4.4 → 0.4.5
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.
- package/esm/helpers/materialized-reports/index.js +1 -0
- package/esm/helpers/materialized-reports/materialized-reports-read-helpers.js +96 -22
- package/esm/helpers/materialized-reports/materialized-reports-scope-group-helpers.js +281 -0
- package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +126 -7
- package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +47 -1
- package/esm/helpers/order/generate-order.js +11 -0
- package/esm/helpers/store/common-order-actions.js +7 -3
- package/esm/helpers/types/materialized-reports-apis.js +1 -1
- package/lib/helpers/materialized-reports/index.d.ts +1 -0
- package/lib/helpers/materialized-reports/index.js +1 -0
- package/lib/helpers/materialized-reports/materialized-reports-read-helpers.d.ts +50 -21
- package/lib/helpers/materialized-reports/materialized-reports-read-helpers.js +96 -21
- package/lib/helpers/materialized-reports/materialized-reports-scope-group-helpers.d.ts +58 -0
- package/lib/helpers/materialized-reports/materialized-reports-scope-group-helpers.js +286 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +24 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +127 -7
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +47 -1
- package/lib/helpers/order/generate-order.d.ts +2 -0
- package/lib/helpers/order/generate-order.js +13 -0
- package/lib/helpers/store/common-order-actions.js +7 -3
- package/lib/helpers/types/materialized-reports-apis.d.ts +115 -25
- package/lib/helpers/types/materialized-reports-apis.js +1 -0
- package/lib/schemas/models/internal_invoices.d.ts +3 -3
- package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +9 -9
- package/lib/schemas/models/orders.d.ts +692 -692
- package/lib/schemas/models/tenant_purchase_orders.d.ts +90 -90
- package/lib/schemas/models/tenants.d.ts +9 -9
- package/lib/schemas/models/warehouse_communications.d.ts +3 -3
- package/lib/schemas/models/warehouse_internal_movements.d.ts +48 -48
- package/lib/schemas/models/warehouse_purchase_order_rfqs.d.ts +63 -63
- package/lib/schemas/models/warehouse_purchase_orders.d.ts +96 -96
- package/lib/schemas/models/warehouse_sale_invoices.d.ts +3 -3
- package/lib/schemas/models/warehouse_sale_order_rfqs.d.ts +69 -69
- package/lib/schemas/models/warehouse_sale_orders.d.ts +45 -45
- package/lib/schemas/models/warehouses.d.ts +6 -6
- package/lib/tests/materialized-reports/materialized-reports-read-helpers.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-reports-read-helpers.test.js +100 -0
- package/lib/tests/materialized-reports/materialized-reports-scope-group-helpers.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-reports-scope-group-helpers.test.js +275 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.d.ts +1 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +143 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +22 -0
- package/lib/tests/num-of-guests-limit.test.d.ts +1 -0
- package/lib/tests/num-of-guests-limit.test.js +76 -0
- package/package.json +1 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export * from './key-helpers';
|
|
2
2
|
export * from './materialized-reports-read-helpers';
|
|
3
|
+
export * from './materialized-reports-scope-group-helpers';
|
|
3
4
|
export * from './materialized-tenant-reports-iterations-helpers';
|
|
4
5
|
export * from './scope-helpers';
|
|
5
6
|
export * from './tenant-sales-overview-close-day-helpers';
|
|
@@ -1,18 +1,19 @@
|
|
|
1
|
-
import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
|
|
1
|
+
import { ALL_MATERIALIZED_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
|
|
2
2
|
import { getMaterializedHourScopeField, parseMaterializedLocalDate } from './scope-helpers';
|
|
3
3
|
/**
|
|
4
4
|
* Read-side helpers for materialized-report documents — the frontend-facing
|
|
5
5
|
* half of the query story (see `MATERIALIZED_REPORTS.md` "Time scopes").
|
|
6
6
|
*
|
|
7
|
-
* The ops-service read API takes `{ scope_context, scope_field
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
7
|
+
* The ops-service read API takes `{ scope_context, scope_field }` where
|
|
8
|
+
* `scope_field` is an EXACT value or an `$in` list of exact values — the
|
|
9
|
+
* request itself never carries ranges:
|
|
10
|
+
* - every selection (contiguous periods, discrete picks, hour windows,
|
|
11
|
+
* weekday filters) is compiled by the caller into the exact value list it
|
|
12
|
+
* wants;
|
|
13
13
|
* - recurring hour windows (e.g. 6–8pm on every day of a range) expand to the
|
|
14
|
-
* exact hour labels with `getMaterializedHourWindowScopeFields
|
|
15
|
-
*
|
|
14
|
+
* exact hour labels with `getMaterializedHourWindowScopeFields`;
|
|
15
|
+
* - `getMaterializedScopeSpan` / `getMaterializedHourScopeSpan` remain as
|
|
16
|
+
* min..max bounds utilities for key sets (not part of the read path).
|
|
16
17
|
*
|
|
17
18
|
* Validation convention: helpers return `null` instead of throwing — `null`
|
|
18
19
|
* means the caller passed invalid data.
|
|
@@ -94,12 +95,9 @@ export function getMaterializedHourWindowScopeFields(businessDays, fromHour, toH
|
|
|
94
95
|
return labels;
|
|
95
96
|
}
|
|
96
97
|
/**
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
* `'D 00'`…`'D 23'`, spanning the post-midnight hours too). Filter the
|
|
101
|
-
* fetched documents afterwards with `getMaterializedHourWindowScopeFields` /
|
|
102
|
-
* `filterMaterializedTenantSalesOverviewReportsByScopeFields`.
|
|
98
|
+
* Min..max `localHour` bounds of a list of business days:
|
|
99
|
+
* `{ from: '<first> 00', to: '<last> 23' }`. A bounds utility for key sets —
|
|
100
|
+
* the READ API takes exact values / `$in` lists, never ranges.
|
|
103
101
|
*
|
|
104
102
|
* Returns `null` (never throws) for a malformed list.
|
|
105
103
|
*/
|
|
@@ -116,11 +114,11 @@ export function getMaterializedHourScopeSpan(businessDays) {
|
|
|
116
114
|
return { from: `${sorted[0]} 00`, to: `${sorted[sorted.length - 1]} 23` };
|
|
117
115
|
}
|
|
118
116
|
/**
|
|
119
|
-
* Inclusive min..max
|
|
120
|
-
*
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
* malformed list.
|
|
117
|
+
* Inclusive min..max bounds of exact non-hour scope values (all non-hour
|
|
118
|
+
* scope fields are fixed-width, so lexicographic order equals chronological
|
|
119
|
+
* order). A bounds utility for key sets — the READ API takes exact values /
|
|
120
|
+
* `$in` lists, never ranges. Returns `null` (never throws) for the hour
|
|
121
|
+
* scope or a malformed list.
|
|
124
122
|
*/
|
|
125
123
|
export function getMaterializedScopeSpan(scope_context, scopeFields) {
|
|
126
124
|
if (scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
|
|
@@ -139,8 +137,9 @@ export function getMaterializedScopeSpan(scope_context, scopeFields) {
|
|
|
139
137
|
}
|
|
140
138
|
/**
|
|
141
139
|
* Keeps only the documents whose `scope_field` is one of the requested keys —
|
|
142
|
-
*
|
|
143
|
-
*
|
|
140
|
+
* a client-side refinement utility for arbitrary document sets (the read API
|
|
141
|
+
* returns exactly the requested values, so it needs no refinement). Returns
|
|
142
|
+
* `null` (never throws) for malformed input; unknown keys simply match
|
|
144
143
|
* nothing (absence = zero).
|
|
145
144
|
*/
|
|
146
145
|
export function filterMaterializedTenantSalesOverviewReportsByScopeFields(docs, scopeFields) {
|
|
@@ -150,3 +149,78 @@ export function filterMaterializedTenantSalesOverviewReportsByScopeFields(docs,
|
|
|
150
149
|
const wanted = new Set(scopeFields);
|
|
151
150
|
return docs.filter((doc) => doc != null && wanted.has(doc.scope_field));
|
|
152
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* Builds the canonical body of a materialized reports READ call —
|
|
154
|
+
* `{ tenants, scope_groups }`, the shared shape of every report endpoint.
|
|
155
|
+
*
|
|
156
|
+
* Normalization (invalid input → `null`, never throws):
|
|
157
|
+
* - tenants are trimmed + deduped (whitespace-only tenants are rejected);
|
|
158
|
+
* - each group's `scope_context` is RESOLVED to its server default
|
|
159
|
+
* (`localDate`) BEFORE bucketing, so an omitted context and an explicit
|
|
160
|
+
* `localDate` group merge into ONE — never two semantically identical
|
|
161
|
+
* groups (the backend merges branch rows with `$sum`, so overlapping
|
|
162
|
+
* groups would double-count every shared document);
|
|
163
|
+
* - values are trimmed + deduped + sorted (lexicographic order is
|
|
164
|
+
* chronological for the fixed-width period formats; hour labels are
|
|
165
|
+
* `$in`-matched, so their order is cosmetic only);
|
|
166
|
+
* - groups with the same context are merged (values unioned); every emitted
|
|
167
|
+
* group carries an explicit `scope_context`.
|
|
168
|
+
*
|
|
169
|
+
* The body carries NO response-mode switch: every read is answered with
|
|
170
|
+
* the aggregated record(s). Per group, `scope_field.length` only picks the
|
|
171
|
+
* backend's query strategy (a single value → direct equality; multiple →
|
|
172
|
+
* `$in`).
|
|
173
|
+
*
|
|
174
|
+
* Returns `null` (never throws) for invalid input — `null` means the caller
|
|
175
|
+
* passed invalid data.
|
|
176
|
+
*/
|
|
177
|
+
export function buildMaterializedReportReadBody(input) {
|
|
178
|
+
if (input == null)
|
|
179
|
+
return null;
|
|
180
|
+
const { tenants, groups } = input;
|
|
181
|
+
if (!Array.isArray(tenants) || tenants.length === 0)
|
|
182
|
+
return null;
|
|
183
|
+
if (tenants.some((tenantId) => typeof tenantId !== 'string' || tenantId.trim() === '')) {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
if (!Array.isArray(groups) || groups.length === 0)
|
|
187
|
+
return null;
|
|
188
|
+
const buckets = new Map();
|
|
189
|
+
for (const group of groups) {
|
|
190
|
+
if (group == null || !Array.isArray(group.scope_field) || group.scope_field.length === 0)
|
|
191
|
+
return null;
|
|
192
|
+
const { scope_context } = group;
|
|
193
|
+
if (scope_context != null && !ALL_MATERIALIZED_REPORT_SCOPES.includes(scope_context))
|
|
194
|
+
return null;
|
|
195
|
+
// Resolve the context default BEFORE bucketing — an omitted context IS
|
|
196
|
+
// `localDate` (the server default), so it must merge with an explicit
|
|
197
|
+
// `localDate` group instead of surviving as a second, overlapping group.
|
|
198
|
+
const context = scope_context ?? MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE;
|
|
199
|
+
let values = buckets.get(context);
|
|
200
|
+
if (values == null) {
|
|
201
|
+
values = new Set();
|
|
202
|
+
buckets.set(context, values);
|
|
203
|
+
}
|
|
204
|
+
for (const field of group.scope_field) {
|
|
205
|
+
if (typeof field !== 'string')
|
|
206
|
+
return null;
|
|
207
|
+
const trimmed = field.trim();
|
|
208
|
+
if (trimmed === '')
|
|
209
|
+
return null;
|
|
210
|
+
values.add(trimmed);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const scope_groups = [];
|
|
214
|
+
for (const [scope_context, values] of buckets) {
|
|
215
|
+
const scope_field = [...values].sort();
|
|
216
|
+
if (scope_field.length === 0)
|
|
217
|
+
continue;
|
|
218
|
+
scope_groups.push({ scope_context, scope_field });
|
|
219
|
+
}
|
|
220
|
+
if (scope_groups.length === 0)
|
|
221
|
+
return null;
|
|
222
|
+
return {
|
|
223
|
+
tenants: Array.from(new Set(tenants.map((tenantId) => tenantId.trim()))),
|
|
224
|
+
scope_groups,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
|
|
2
|
+
import { getMaterializedHourWindowScopeFields } from './materialized-reports-read-helpers';
|
|
3
|
+
/**
|
|
4
|
+
* Smart scope-group compiler for materialized-report reads — turns a
|
|
5
|
+
* selection into the FEWEST exact-scope groups the read needs
|
|
6
|
+
* (`IGetMaterializedReportScopeGroup[]`, the `scope_groups` body field):
|
|
7
|
+
*
|
|
8
|
+
* - **compaction**: a contiguous day set is folded into the largest EXACT
|
|
9
|
+
* periods (year → semester → quarter → month → week) before falling back
|
|
10
|
+
* to `localDate` values — e.g. Sep 1–30 becomes ONE `localMonth: ['2026-09']`
|
|
11
|
+
* instead of 30 day values (one document instead of 30);
|
|
12
|
+
* - **recurring window**: the same hours on every selected day → a single
|
|
13
|
+
* `localHour` group (the dedicated time-of-day-window read);
|
|
14
|
+
* - **span window**: from `x:00` on the first day CONTINUOUSLY through
|
|
15
|
+
* `y:00` on the last day — boundary days carry only their partial hour
|
|
16
|
+
* labels (business-day continuous: the start day runs to its 06:00
|
|
17
|
+
* boundary including the post-midnight tail, the end day starts at 06:00),
|
|
18
|
+
* the full days in between compact through the same period logic. What the
|
|
19
|
+
* span does NOT read (absent documents) counts as zero, and groups NEVER
|
|
20
|
+
* overlap — the backend simply unions them.
|
|
21
|
+
*
|
|
22
|
+
* `compactMaterializedReportDayKeys` is exported for direct testing.
|
|
23
|
+
*
|
|
24
|
+
* Returns `null` (never throws) for malformed input — `null` means the
|
|
25
|
+
* caller passed invalid data.
|
|
26
|
+
*/
|
|
27
|
+
/** Window refinement kinds (see the module docblock). */
|
|
28
|
+
export const MATERIALIZED_REPORT_WINDOW_KIND = {
|
|
29
|
+
RECURRING: 'RECURRING',
|
|
30
|
+
SPAN: 'SPAN',
|
|
31
|
+
};
|
|
32
|
+
/* ------------------------------------------------------------------------ */
|
|
33
|
+
/* Date-key math (UTC — keys are timezone-less) */
|
|
34
|
+
/* ------------------------------------------------------------------------ */
|
|
35
|
+
const KEY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
36
|
+
const keyToDate = (key) => {
|
|
37
|
+
if (typeof key !== 'string' || !KEY_PATTERN.test(key))
|
|
38
|
+
return null;
|
|
39
|
+
const [year, month, day] = key.split('-').map(Number);
|
|
40
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
41
|
+
// reject impossible dates (e.g. 2026-02-30)
|
|
42
|
+
if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
return date;
|
|
46
|
+
};
|
|
47
|
+
const dateToKey = (date) => `${date.getUTCFullYear()}-${`${date.getUTCMonth() + 1}`.padStart(2, '0')}-${`${date.getUTCDate()}`.padStart(2, '0')}`;
|
|
48
|
+
const addDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
|
|
49
|
+
const DAY_MS = 86400000;
|
|
50
|
+
/** Whole days from `from` to `to` (negative when `to` precedes `from`). */
|
|
51
|
+
const daysBetween = (from, to) => Math.round((to.getTime() - from.getTime()) / DAY_MS);
|
|
52
|
+
/** Sunday-based week start (the `localWeek` bucket identity). */
|
|
53
|
+
const weekStartOf = (date) => addDays(date, -date.getUTCDay());
|
|
54
|
+
/**
|
|
55
|
+
* Periods that START exactly on `date`, largest first: year → semester →
|
|
56
|
+
* quarter → month → week (Sunday-based). Only exact starts are candidates —
|
|
57
|
+
* a run can only compact at its boundaries.
|
|
58
|
+
*/
|
|
59
|
+
const periodCandidatesAt = (date) => {
|
|
60
|
+
const year = date.getUTCFullYear();
|
|
61
|
+
const month = date.getUTCMonth() + 1;
|
|
62
|
+
const day = date.getUTCDate();
|
|
63
|
+
const candidates = [];
|
|
64
|
+
const span = (startMonth, months) => {
|
|
65
|
+
const start = new Date(Date.UTC(year, startMonth - 1, 1));
|
|
66
|
+
const end = addDays(new Date(Date.UTC(year, startMonth - 1 + months, 1)), -1);
|
|
67
|
+
return { startKey: dateToKey(start), endKey: dateToKey(end) };
|
|
68
|
+
};
|
|
69
|
+
if (month === 1 && day === 1) {
|
|
70
|
+
const { startKey, endKey } = span(1, 12);
|
|
71
|
+
candidates.push({ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR, label: `${year}`, startKey, endKey });
|
|
72
|
+
}
|
|
73
|
+
if ((month === 1 || month === 7) && day === 1) {
|
|
74
|
+
const { startKey, endKey } = span(month, 6);
|
|
75
|
+
candidates.push({
|
|
76
|
+
scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
|
|
77
|
+
label: `${year}-S${month === 1 ? 1 : 2}`,
|
|
78
|
+
startKey,
|
|
79
|
+
endKey,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if ([1, 4, 7, 10].includes(month) && day === 1) {
|
|
83
|
+
const { startKey, endKey } = span(month, 3);
|
|
84
|
+
candidates.push({
|
|
85
|
+
scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
|
|
86
|
+
label: `${year}-Q${Math.floor((month - 1) / 3) + 1}`,
|
|
87
|
+
startKey,
|
|
88
|
+
endKey,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
if (day === 1) {
|
|
92
|
+
const { startKey, endKey } = span(month, 1);
|
|
93
|
+
candidates.push({
|
|
94
|
+
scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
|
|
95
|
+
label: `${year}-${`${month}`.padStart(2, '0')}`,
|
|
96
|
+
startKey,
|
|
97
|
+
endKey,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
if (date.getUTCDay() === 0) {
|
|
101
|
+
const startKey = dateToKey(date);
|
|
102
|
+
const endKey = dateToKey(addDays(date, 6));
|
|
103
|
+
candidates.push({ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, label: startKey, startKey, endKey });
|
|
104
|
+
}
|
|
105
|
+
return candidates;
|
|
106
|
+
};
|
|
107
|
+
/* ------------------------------------------------------------------------ */
|
|
108
|
+
/* Compaction */
|
|
109
|
+
/* ------------------------------------------------------------------------ */
|
|
110
|
+
const GROUP_ORDER = [
|
|
111
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
|
|
112
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
|
|
113
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
|
|
114
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
|
|
115
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
|
|
116
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
117
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
|
|
118
|
+
];
|
|
119
|
+
/** Ordered, deduped, non-empty groups from a context → values map. */
|
|
120
|
+
const toGroups = (values) => {
|
|
121
|
+
const groups = [];
|
|
122
|
+
for (const scope_context of GROUP_ORDER) {
|
|
123
|
+
const set = values.get(scope_context);
|
|
124
|
+
if (set != null && set.size > 0) {
|
|
125
|
+
groups.push({ scope_context, scope_field: [...set].sort() });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return groups;
|
|
129
|
+
};
|
|
130
|
+
const addValue = (values, scope_context, value) => {
|
|
131
|
+
const set = values.get(scope_context) ?? new Set();
|
|
132
|
+
set.add(value);
|
|
133
|
+
values.set(scope_context, set);
|
|
134
|
+
};
|
|
135
|
+
/**
|
|
136
|
+
* Folds a contiguous day set into the largest EXACT periods (year →
|
|
137
|
+
* semester → quarter → month → week) + `localDate` leftovers — never
|
|
138
|
+
* partial coverage: a period compacts only when the WHOLE period is inside
|
|
139
|
+
* a contiguous run. Returns `null` for malformed/empty input.
|
|
140
|
+
*/
|
|
141
|
+
export function compactMaterializedReportDayKeys(days) {
|
|
142
|
+
if (!Array.isArray(days) || days.length === 0)
|
|
143
|
+
return null;
|
|
144
|
+
const dates = [];
|
|
145
|
+
for (const day of days) {
|
|
146
|
+
const date = keyToDate(day);
|
|
147
|
+
if (date == null)
|
|
148
|
+
return null;
|
|
149
|
+
dates.push(date);
|
|
150
|
+
}
|
|
151
|
+
dates.sort((a, b) => a.getTime() - b.getTime());
|
|
152
|
+
const values = new Map();
|
|
153
|
+
let index = 0;
|
|
154
|
+
while (index < dates.length) {
|
|
155
|
+
// contiguous run [runStart..runEnd]
|
|
156
|
+
const runStart = dates[index];
|
|
157
|
+
let runEnd = runStart;
|
|
158
|
+
let next = index + 1;
|
|
159
|
+
while (next < dates.length && daysBetween(runEnd, dates[next]) === 1) {
|
|
160
|
+
runEnd = dates[next];
|
|
161
|
+
next += 1;
|
|
162
|
+
}
|
|
163
|
+
let cursor = runStart;
|
|
164
|
+
while (cursor.getTime() <= runEnd.getTime()) {
|
|
165
|
+
const candidate = periodCandidatesAt(cursor).find((entry) => keyToDate(entry.endKey).getTime() <= runEnd.getTime());
|
|
166
|
+
if (candidate != null) {
|
|
167
|
+
addValue(values, candidate.scope_context, candidate.label);
|
|
168
|
+
cursor = addDays(keyToDate(candidate.endKey), 1);
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
addValue(values, MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, dateToKey(cursor));
|
|
172
|
+
cursor = addDays(cursor, 1);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
index = next;
|
|
176
|
+
}
|
|
177
|
+
return toGroups(values);
|
|
178
|
+
}
|
|
179
|
+
/* ------------------------------------------------------------------------ */
|
|
180
|
+
/* Scope groups */
|
|
181
|
+
/* ------------------------------------------------------------------------ */
|
|
182
|
+
const isValidHour = (hour, max) => Number.isInteger(hour) && hour >= 0 && hour <= max;
|
|
183
|
+
/**
|
|
184
|
+
* Builds the read's scope groups from a selection spec (see the module
|
|
185
|
+
* docblock). Returns `null` for malformed input or an unservable window.
|
|
186
|
+
*/
|
|
187
|
+
export function buildMaterializedReportScopeGroups(spec) {
|
|
188
|
+
if (spec == null)
|
|
189
|
+
return null;
|
|
190
|
+
const { days, window } = spec;
|
|
191
|
+
if (!Array.isArray(days) || days.length === 0)
|
|
192
|
+
return null;
|
|
193
|
+
const dates = [];
|
|
194
|
+
for (const day of days) {
|
|
195
|
+
const date = keyToDate(day);
|
|
196
|
+
if (date == null)
|
|
197
|
+
return null;
|
|
198
|
+
dates.push(date);
|
|
199
|
+
}
|
|
200
|
+
dates.sort((a, b) => a.getTime() - b.getTime());
|
|
201
|
+
const dayKeys = [...new Set(dates.map(dateToKey))];
|
|
202
|
+
const uniqueDates = dayKeys.map((key) => keyToDate(key));
|
|
203
|
+
// A SPAN window reads the CONTINUOUS interval first-day → last-day — a day
|
|
204
|
+
// set with gaps would silently pull the gap days in as full middle days.
|
|
205
|
+
if (window != null && window.kind === MATERIALIZED_REPORT_WINDOW_KIND.SPAN) {
|
|
206
|
+
for (let index = 1; index < uniqueDates.length; index += 1) {
|
|
207
|
+
if (daysBetween(uniqueDates[index - 1], uniqueDates[index]) !== 1) {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
// No window → compaction only.
|
|
213
|
+
if (window == null) {
|
|
214
|
+
return compactMaterializedReportDayKeys(dayKeys);
|
|
215
|
+
}
|
|
216
|
+
const { fromHour, toHour, kind } = window;
|
|
217
|
+
if (!isValidHour(fromHour, 23) || !isValidHour(toHour, 23))
|
|
218
|
+
return null;
|
|
219
|
+
// Recurring: the same hours on every selected day.
|
|
220
|
+
if (kind === MATERIALIZED_REPORT_WINDOW_KIND.RECURRING) {
|
|
221
|
+
const labels = getMaterializedHourWindowScopeFields(dayKeys, fromHour, toHour);
|
|
222
|
+
return labels == null ? null : [{ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: labels }];
|
|
223
|
+
}
|
|
224
|
+
// Span (business-day continuous).
|
|
225
|
+
const startDate = uniqueDates[0];
|
|
226
|
+
const endDate = uniqueDates[uniqueDates.length - 1];
|
|
227
|
+
const x = fromHour;
|
|
228
|
+
const y = toHour;
|
|
229
|
+
// Single calendar day, overnight window (e.g. 18:00 → 2:00): one business
|
|
230
|
+
// day covers it whole.
|
|
231
|
+
if (daysBetween(startDate, endDate) === 0 && x >= 6 && y <= 6) {
|
|
232
|
+
if (x === 6 && y === 6) {
|
|
233
|
+
return compactMaterializedReportDayKeys([dateToKey(startDate)]);
|
|
234
|
+
}
|
|
235
|
+
const labels = getMaterializedHourWindowScopeFields([dateToKey(startDate)], x, y);
|
|
236
|
+
return labels == null ? null : [{ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: labels }];
|
|
237
|
+
}
|
|
238
|
+
// Boundary business days: a start before 06:00 belongs to the previous
|
|
239
|
+
// business day's tail; an end at/before 06:00 ends the previous business
|
|
240
|
+
// day.
|
|
241
|
+
const startBus = x >= 6 ? startDate : addDays(startDate, -1);
|
|
242
|
+
const endBus = y > 6 ? endDate : addDays(endDate, -1);
|
|
243
|
+
// One business day hosts both boundaries (e.g. a full day 06:00 → 06:00).
|
|
244
|
+
if (startBus.getTime() === endBus.getTime()) {
|
|
245
|
+
if (x === 6 && y === 6) {
|
|
246
|
+
return compactMaterializedReportDayKeys([dateToKey(startBus)]);
|
|
247
|
+
}
|
|
248
|
+
const labels = getMaterializedHourWindowScopeFields([dateToKey(startBus)], x, y);
|
|
249
|
+
return labels == null ? null : [{ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: labels }];
|
|
250
|
+
}
|
|
251
|
+
const startLabels = x === 6 ? null : getMaterializedHourWindowScopeFields([dateToKey(startBus)], x, 6);
|
|
252
|
+
const endLabels = y === 6 ? null : getMaterializedHourWindowScopeFields([dateToKey(endBus)], 6, y);
|
|
253
|
+
if (x !== 6 && startLabels == null)
|
|
254
|
+
return null;
|
|
255
|
+
if (y !== 6 && endLabels == null)
|
|
256
|
+
return null;
|
|
257
|
+
const values = new Map();
|
|
258
|
+
// Full business days between the boundaries — compacted like any day set
|
|
259
|
+
// (a month-long span middle becomes period values, not day values).
|
|
260
|
+
const firstFullDate = x === 6 ? startBus : addDays(startBus, 1);
|
|
261
|
+
const lastFullDate = y === 6 ? endBus : addDays(endBus, -1);
|
|
262
|
+
if (firstFullDate.getTime() <= lastFullDate.getTime()) {
|
|
263
|
+
const fullDays = [];
|
|
264
|
+
for (let cursor = firstFullDate; cursor.getTime() <= lastFullDate.getTime(); cursor = addDays(cursor, 1)) {
|
|
265
|
+
fullDays.push(dateToKey(cursor));
|
|
266
|
+
}
|
|
267
|
+
const compacted = compactMaterializedReportDayKeys(fullDays);
|
|
268
|
+
if (compacted == null)
|
|
269
|
+
return null;
|
|
270
|
+
for (const group of compacted) {
|
|
271
|
+
for (const value of group.scope_field) {
|
|
272
|
+
addValue(values, group.scope_context, value);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
for (const label of [...(startLabels ?? []), ...(endLabels ?? [])]) {
|
|
277
|
+
addValue(values, MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, label);
|
|
278
|
+
}
|
|
279
|
+
const groups = toGroups(values);
|
|
280
|
+
return groups.length === 0 ? null : groups;
|
|
281
|
+
}
|
|
@@ -74,11 +74,10 @@ const matchesFilters = (components, keyFilters, filters) => {
|
|
|
74
74
|
}
|
|
75
75
|
return true;
|
|
76
76
|
};
|
|
77
|
-
/** Drops non-matching keys from a
|
|
78
|
-
const
|
|
79
|
-
const keyFilters = doc.sale_type_key_filters ?? [];
|
|
77
|
+
/** Drops non-matching keys from a key map (raw documents and aggregated records share this). */
|
|
78
|
+
const pruneMetricsMap = (keyFilters, metrics, filters) => {
|
|
80
79
|
const kept = {};
|
|
81
|
-
for (const [key, metric] of Object.entries(
|
|
80
|
+
for (const [key, metric] of Object.entries(metrics ?? {})) {
|
|
82
81
|
const components = parseMaterializedReportKey(key);
|
|
83
82
|
// Unparseable key — cannot be matched; skipping keeps the sums honest
|
|
84
83
|
// (the write side rejects such keys, so this is defensive only).
|
|
@@ -88,6 +87,11 @@ const pruneReportForFilters = (doc, filters) => {
|
|
|
88
87
|
continue;
|
|
89
88
|
kept[key] = metric;
|
|
90
89
|
}
|
|
90
|
+
return kept;
|
|
91
|
+
};
|
|
92
|
+
/** Drops non-matching keys from a document's metric map (bills included). */
|
|
93
|
+
const pruneReportForFilters = (doc, filters) => {
|
|
94
|
+
const kept = pruneMetricsMap(doc.sale_type_key_filters ?? [], doc.sale_type_metrics, filters);
|
|
91
95
|
return { ...doc, sale_type_metrics: kept };
|
|
92
96
|
};
|
|
93
97
|
/* ------------------------------------------------------------------------ */
|
|
@@ -245,6 +249,17 @@ const buildPageDataForDocs = (docs, scopeContext, filters) => {
|
|
|
245
249
|
const merged = sumMaterializedTenantSalesOverviewReports(pruned, { allowTenantMismatch: true });
|
|
246
250
|
if (merged == null)
|
|
247
251
|
return null;
|
|
252
|
+
const supportsDayIndex = scopeContext != null && MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext);
|
|
253
|
+
return buildPageDataFromMetrics(merged, tenantIds, supportsDayIndex ? buildWeekdaySection(scopedDocs, filters) : null, scopeContext === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? buildHourlySection(scopedDocs, filters) : null);
|
|
254
|
+
};
|
|
255
|
+
/**
|
|
256
|
+
* Shared page assembly — identical for the raw read (one merged document) and
|
|
257
|
+
* the AGGREGATED read (one pipeline record): every section derives from the
|
|
258
|
+
* pruned key map. The slice-derived sections are inputs: the raw read passes
|
|
259
|
+
* the weekday / hourly grouping of its documents; the aggregated read passes
|
|
260
|
+
* `null` (its response carries no per-scope slices).
|
|
261
|
+
*/
|
|
262
|
+
const buildPageDataFromMetrics = (merged, tenantIds, weekday, hourly) => {
|
|
248
263
|
const keyFilters = merged.sale_type_key_filters ?? [];
|
|
249
264
|
const summaryRaw = createRawOrderMetric();
|
|
250
265
|
const collectedRaw = createRawOrderMetric();
|
|
@@ -304,7 +319,6 @@ const buildPageDataForDocs = (docs, scopeContext, filters) => {
|
|
|
304
319
|
gross_amount: toDecimal(channel.gross_amount),
|
|
305
320
|
}))
|
|
306
321
|
.sort((a, b) => b.count - a.count || a.platform.localeCompare(b.platform));
|
|
307
|
-
const supportsDayIndex = scopeContext != null && MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext);
|
|
308
322
|
return {
|
|
309
323
|
tenant_ids: tenantIds,
|
|
310
324
|
summary: formatRawOrderMetric(summaryRaw),
|
|
@@ -322,8 +336,8 @@ const buildPageDataForDocs = (docs, scopeContext, filters) => {
|
|
|
322
336
|
received: { count: receivedRaw.count, amount: toDecimal(receivedRaw.amount) },
|
|
323
337
|
outstanding_amount: toDecimal(issuedRaw.amount - issuedRaw.settled_amount),
|
|
324
338
|
},
|
|
325
|
-
weekday
|
|
326
|
-
hourly
|
|
339
|
+
weekday,
|
|
340
|
+
hourly,
|
|
327
341
|
};
|
|
328
342
|
};
|
|
329
343
|
/* ------------------------------------------------------------------------ */
|
|
@@ -377,3 +391,108 @@ export function getFormattedTenantSalesOverviewReporting(docs, filters = null, s
|
|
|
377
391
|
}
|
|
378
392
|
return [results, null];
|
|
379
393
|
}
|
|
394
|
+
/* ------------------------------------------------------------------------ */
|
|
395
|
+
/* Aggregated read (pipeline records) */
|
|
396
|
+
/* ------------------------------------------------------------------------ */
|
|
397
|
+
/** Folds a group of aggregated records into ONE combined key-map slice. */
|
|
398
|
+
const mergeAggregatedKeyMetrics = (reports) => {
|
|
399
|
+
const merged = {};
|
|
400
|
+
const TOTAL_SALES = REPORT_SALE_TYPE_ENUM.TOTAL_SALES;
|
|
401
|
+
const AMOUNT_COLLECTED = REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED;
|
|
402
|
+
const CREDIT_BILLS = REPORT_SALE_TYPE_ENUM.CREDIT_BILLS;
|
|
403
|
+
for (const report of reports) {
|
|
404
|
+
for (const [key, metrics] of Object.entries(report.sale_type_metrics ?? {})) {
|
|
405
|
+
const entry = merged[key] ??
|
|
406
|
+
(merged[key] = {
|
|
407
|
+
[TOTAL_SALES]: { orders: createRawOrderMetric(), payments: [] },
|
|
408
|
+
[AMOUNT_COLLECTED]: { orders: createRawOrderMetric() },
|
|
409
|
+
[CREDIT_BILLS]: {
|
|
410
|
+
issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
|
|
411
|
+
received: { count: 0, amount: 0 },
|
|
412
|
+
},
|
|
413
|
+
});
|
|
414
|
+
addRawOrderMetric(entry[TOTAL_SALES].orders, metrics[TOTAL_SALES]?.orders);
|
|
415
|
+
addRawOrderMetric(entry[AMOUNT_COLLECTED].orders, metrics[AMOUNT_COLLECTED]?.orders);
|
|
416
|
+
for (const payment of metrics[TOTAL_SALES]?.payments ?? []) {
|
|
417
|
+
entry[TOTAL_SALES].payments.push(payment);
|
|
418
|
+
}
|
|
419
|
+
entry[CREDIT_BILLS].issued.count += metrics[CREDIT_BILLS]?.issued?.count ?? 0;
|
|
420
|
+
entry[CREDIT_BILLS].issued.amount += metrics[CREDIT_BILLS]?.issued?.amount ?? 0;
|
|
421
|
+
entry[CREDIT_BILLS].issued.settled_count += metrics[CREDIT_BILLS]?.issued?.settled_count ?? 0;
|
|
422
|
+
entry[CREDIT_BILLS].issued.settled_amount += metrics[CREDIT_BILLS]?.issued?.settled_amount ?? 0;
|
|
423
|
+
entry[CREDIT_BILLS].received.count += metrics[CREDIT_BILLS]?.received?.count ?? 0;
|
|
424
|
+
entry[CREDIT_BILLS].received.amount += metrics[CREDIT_BILLS]?.received?.amount ?? 0;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return {
|
|
428
|
+
sale_type_key_filters: reports[0]?.sale_type_key_filters ?? [],
|
|
429
|
+
sale_type_metrics: merged,
|
|
430
|
+
};
|
|
431
|
+
};
|
|
432
|
+
/**
|
|
433
|
+
* Frontend formatter for the overview response —
|
|
434
|
+
* `IMaterializedTenantSalesOverviewAggregatedReport[]` (one pipeline-computed
|
|
435
|
+
* record per tenant — the shape of every read).
|
|
436
|
+
*
|
|
437
|
+
* Same page-ready output as `getFormattedTenantSalesOverviewReporting`, with
|
|
438
|
+
* the platform / order-status filters applied client-side on the records'
|
|
439
|
+
* preserved key maps (zero refetches). Differences, by construction:
|
|
440
|
+
* - the slice-derived sections are ALWAYS `null`: `weekday` and `hourly`
|
|
441
|
+
* need per-scope documents — the aggregated record has none (most recent
|
|
442
|
+
* period reads must use the raw response if those sections are ever
|
|
443
|
+
* rendered);
|
|
444
|
+
* - an explicit `day_indexes` filter is REJECTED (`null`): the weekday
|
|
445
|
+
* refinement must narrow the request scope (the calendar selection),
|
|
446
|
+
* never the response;
|
|
447
|
+
* - the combined view (default) folds the tenants' records together; with
|
|
448
|
+
* `separate_view_per_tenant: true` each tenant keeps its own entry.
|
|
449
|
+
*
|
|
450
|
+
* Returns `null` (never throws) when the records cannot be formatted
|
|
451
|
+
* together (mixed key grammars, mismatched brands in the combined view,
|
|
452
|
+
* unsupported filter).
|
|
453
|
+
*/
|
|
454
|
+
export function getFormattedTenantSalesOverviewAggregatedReporting(reports, filters = null, separate_view_per_tenant = false) {
|
|
455
|
+
if (!Array.isArray(reports) || reports.some((report) => report == null)) {
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
if (filters != null && Array.isArray(filters.day_indexes) && filters.day_indexes.length > 0) {
|
|
459
|
+
return null;
|
|
460
|
+
}
|
|
461
|
+
if (reports.length > 0) {
|
|
462
|
+
const keyFilterSignature = (reports[0].sale_type_key_filters ?? []).join(':');
|
|
463
|
+
for (const report of reports) {
|
|
464
|
+
// The combined view folds the tenants' records together — same guard as
|
|
465
|
+
// the raw merge (`canMergeMaterializedReportsIgnoringTenant`): one brand.
|
|
466
|
+
// Per-tenant views (`separate_view_per_tenant`) never cross brands.
|
|
467
|
+
if (!separate_view_per_tenant && report.brand_id !== reports[0].brand_id)
|
|
468
|
+
return null;
|
|
469
|
+
if ((report.sale_type_key_filters ?? []).join(':') !== keyFilterSignature)
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
if (reports.length === 0) {
|
|
474
|
+
return [[buildEmptyPageData(null, [])], null];
|
|
475
|
+
}
|
|
476
|
+
const groups = [];
|
|
477
|
+
if (separate_view_per_tenant) {
|
|
478
|
+
const byTenant = new Map();
|
|
479
|
+
for (const report of reports) {
|
|
480
|
+
const group = byTenant.get(report.tenant_id) ?? [];
|
|
481
|
+
group.push(report);
|
|
482
|
+
byTenant.set(report.tenant_id, group);
|
|
483
|
+
}
|
|
484
|
+
for (const tenantId of [...byTenant.keys()].sort()) {
|
|
485
|
+
groups.push(byTenant.get(tenantId));
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
else {
|
|
489
|
+
groups.push(reports);
|
|
490
|
+
}
|
|
491
|
+
const results = [];
|
|
492
|
+
for (const group of groups) {
|
|
493
|
+
const merged = mergeAggregatedKeyMetrics(group);
|
|
494
|
+
const pruned = pruneMetricsMap(merged.sale_type_key_filters, merged.sale_type_metrics, filters);
|
|
495
|
+
results.push(buildPageDataFromMetrics({ sale_type_key_filters: merged.sale_type_key_filters, sale_type_metrics: pruned }, uniqueTenantIds(group), null, null));
|
|
496
|
+
}
|
|
497
|
+
return [results, null];
|
|
498
|
+
}
|