@managesome/eposmatic-toolkit 0.4.5 → 0.4.7

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 (27) hide show
  1. package/esm/constants/REPORT_CALENDAR.js +47 -0
  2. package/esm/constants/index.js +1 -0
  3. package/esm/helpers/materialized-reports/index.js +1 -0
  4. package/esm/helpers/materialized-reports/materialized-reports-read-helpers.js +1 -76
  5. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +473 -0
  6. package/esm/helpers/types/index.js +1 -0
  7. package/lib/constants/REPORT_CALENDAR.d.ts +31 -0
  8. package/lib/constants/REPORT_CALENDAR.js +50 -0
  9. package/lib/constants/index.d.ts +1 -0
  10. package/lib/constants/index.js +1 -0
  11. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  12. package/lib/helpers/materialized-reports/index.js +1 -0
  13. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.d.ts +0 -30
  14. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.js +0 -76
  15. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +25 -0
  16. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +479 -0
  17. package/lib/helpers/types/index.d.ts +1 -0
  18. package/lib/helpers/types/index.js +1 -0
  19. package/lib/helpers/types/materialized-reports-apis.d.ts +14 -12
  20. package/lib/helpers/types/report-calendar.d.ts +20 -0
  21. package/lib/helpers/types/report-calendar.js +2 -0
  22. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +3 -3
  23. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.d.ts +1 -0
  24. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +166 -0
  25. package/package.json +1 -1
  26. package/lib/tests/materialized-reports/materialized-reports-read-helpers.test.js +0 -100
  27. /package/{lib/tests/materialized-reports/materialized-reports-read-helpers.test.d.ts → esm/helpers/types/report-calendar.js} +0 -0
@@ -0,0 +1,479 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildMaterializedReportScopeGroupsFromSelection = exports.isValidBusinessHourWindow = exports.getDayKeysFromCalendarSelection = void 0;
4
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
5
+ const REPORT_CALENDAR_1 = require("../../constants/REPORT_CALENDAR");
6
+ const materialized_reports_scope_group_helpers_1 = require("./materialized-reports-scope-group-helpers");
7
+ const scope_helpers_1 = require("./scope-helpers");
8
+ /**
9
+ * Calendar-selection DECODER for the materialized report READ APIs — the
10
+ * backend-side twin of the calendar: it maps one `IReportCalendarSelection`
11
+ * to the exact `scope_groups` a read request needs, so clients ship the
12
+ * selection (a few hundred bytes) instead of enumerating tens of thousands
13
+ * of scope values.
14
+ *
15
+ * Semantics (identical to what the frontend compiler produced before this
16
+ * moved server-side):
17
+ * - LIVE reads ONLY the running business day — all of its exact `localHour`
18
+ * labels (the calendar commits the running day as `rangeStart`); summed by
19
+ * the backend it yields the running day's metrics so far, finalized at day
20
+ * close;
21
+ * - day-based selections compile through the SMART compiler
22
+ * (`buildMaterializedReportScopeGroups`): contiguous day runs fold into the
23
+ * LARGEST exact periods they fully cover (week → month → quarter → semester
24
+ * → year; anything left stays `localDate`);
25
+ * - a time-of-day window compiles to `localHour` labels: a CONTINUOUS SPAN on
26
+ * range-like views (toggle), the SAME hours on each selected day otherwise
27
+ * (dedicated window view / discrete selections);
28
+ * - the weekday refinement degenerates the read to standalone day documents
29
+ * (`localDate` / `localHour` docs carry `day_index`; period docs do not):
30
+ * it filters the effective day set BEFORE hour-window expansion;
31
+ * - period views read their exact period keys directly (week starts, ISO week
32
+ * labels, months, quarters, semesters, years).
33
+ *
34
+ * Returns `null` (never throws) when the selection cannot be served (missing
35
+ * range on a range view, malformed keys, an invalid refinement window, or an
36
+ * unservable empty result). Group values are exact; empty groups are dropped.
37
+ */
38
+ /** Range-like views whose toggle window is a CONTINUOUS span. */
39
+ const SPAN_VIEWS = new Set([
40
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DATE_RANGE,
41
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK,
42
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK_OF_YEAR,
43
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MONTH,
44
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.QUARTER,
45
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.SEMESTER,
46
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.YEAR,
47
+ ]);
48
+ /** Views whose day set is one contiguous `rangeStart … rangeEnd` walk. */
49
+ const RANGE_LIKE_VIEWS = new Set([
50
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DATE_RANGE,
51
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DATE_RANGE_TIME_WINDOW,
52
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK,
53
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK_OF_YEAR,
54
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.QUARTER,
55
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.SEMESTER,
56
+ ]);
57
+ /* ==================== Date-key primitives ==================== */
58
+ // Local 'YYYY-MM-DD' key for a Date (NOT UTC — the tenant's local day).
59
+ const formatLocalDateKey = (date) => {
60
+ const year = date.getFullYear();
61
+ const month = `${date.getMonth() + 1}`.padStart(2, '0');
62
+ const day = `${date.getDate()}`.padStart(2, '0');
63
+ return `${year}-${month}-${day}`;
64
+ };
65
+ const getDateFromKey = (key) => {
66
+ const [year, month, day] = key.split('-').map(Number);
67
+ return new Date(year, month - 1, day);
68
+ };
69
+ const addDaysToKey = (dateKey, days) => {
70
+ const date = getDateFromKey(dateKey);
71
+ date.setDate(date.getDate() + days);
72
+ return formatLocalDateKey(date);
73
+ };
74
+ // 'YYYY-Qn' quarter start ('YYYY-MM-01') — accepts a quarter key
75
+ const getQuarterStartKey = (quarterKey) => {
76
+ const [year, quarter] = quarterKey.split('-');
77
+ const month = (Number(quarter.slice(1)) - 1) * 3 + 1;
78
+ return `${year}-${`${month}`.padStart(2, '0')}-01`;
79
+ };
80
+ // 'YYYY-Qn' quarter end (last day of the quarter) — accepts a quarter key
81
+ const getQuarterEndKey = (quarterKey) => {
82
+ const [year, quarter] = quarterKey.split('-');
83
+ return formatLocalDateKey(new Date(Number(year), Number(quarter.slice(1)) * 3, 0));
84
+ };
85
+ // 'YYYY-Sn' semester start ('YYYY-MM-01') — accepts a semester key
86
+ const getSemesterStartKey = (semesterKey) => {
87
+ const [year, semester] = semesterKey.split('-');
88
+ return `${year}-${semester === 'S1' ? '01' : '07'}-01`;
89
+ };
90
+ // 'YYYY-Sn' semester end — accepts a semester key
91
+ const getSemesterEndKey = (semesterKey) => {
92
+ const [year, semester] = semesterKey.split('-');
93
+ return semester === 'S1' ? `${year}-06-30` : `${year}-12-31`;
94
+ };
95
+ // Monday start of the ISO week containing the given day key
96
+ const getIsoWeekStartKey = (dateKey) => {
97
+ const date = getDateFromKey(dateKey);
98
+ const offset = (date.getDay() + 6) % 7; // days since Monday
99
+ date.setDate(date.getDate() - offset);
100
+ return formatLocalDateKey(date);
101
+ };
102
+ // 'YYYY-Wnn' ISO label of a day key — `YYYY` is the ISO week-year, so
103
+ // boundary weeks (e.g. 2027-01-01 → '2026-W53') label correctly.
104
+ const getIsoWeekKey = (dateKey) => (0, scope_helpers_1.getMaterializedPeriodScopeFields)(dateKey)?.[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR] ?? null;
105
+ // Monday day key of an ISO week label ('YYYY-Wnn'); null for malformed input
106
+ const getIsoWeekStartKeyFromLabel = (weekKey) => {
107
+ const match = /^(\d{4})-W(\d{2})$/.exec(weekKey);
108
+ if (!match)
109
+ return null;
110
+ const week = Number(match[2]);
111
+ if (week < 1 || week > 53)
112
+ return null;
113
+ // ISO week 1 is the week containing Jan 4 — its Monday anchors numbering
114
+ const weekOneMonday = getDateFromKey(getIsoWeekStartKey(`${match[1]}-01-04`));
115
+ weekOneMonday.setDate(weekOneMonday.getDate() + (week - 1) * 7);
116
+ return formatLocalDateKey(weekOneMonday);
117
+ };
118
+ /* ==================== Weekday refinement ==================== */
119
+ /**
120
+ * Active weekday refinement — `null` when unset (= every day). The decoder,
121
+ * the calendar's grid highlight and the selection summary all use the SAME
122
+ * effective-day semantics, so the UI can never claim days the report won't
123
+ * read.
124
+ */
125
+ const getActiveWeekdayFilter = (weekdays) => {
126
+ if (!Array.isArray(weekdays) || weekdays.length === 0)
127
+ return null;
128
+ if (weekdays.length >= 7)
129
+ return null;
130
+ return weekdays;
131
+ };
132
+ /** Whether a day key is kept by the active weekday refinement. */
133
+ const isDayKeptByWeekdayFilter = (dateKey, weekdays) => {
134
+ if (weekdays == null)
135
+ return true;
136
+ const dayIndex = (0, scope_helpers_1.getDayIndexFromLocalDate)(dateKey);
137
+ return dayIndex != null && weekdays.includes(dayIndex);
138
+ };
139
+ /* ==================== Effective day set ==================== */
140
+ // All day keys covered by the current selection — BEFORE the weekday
141
+ // refinement.
142
+ const getBaseSelectedDayKeys = (selection) => {
143
+ const { view, rangeStart, rangeEnd, selectedDates, selectedPeriods } = selection;
144
+ const expandRange = (start, end) => {
145
+ const keys = [];
146
+ let cursor = start;
147
+ while (cursor <= end) {
148
+ keys.push(cursor);
149
+ cursor = addDaysToKey(cursor, 1);
150
+ }
151
+ return keys;
152
+ };
153
+ if (RANGE_LIKE_VIEWS.has(view)) {
154
+ if (!rangeStart)
155
+ return [];
156
+ return expandRange(rangeStart, rangeEnd ?? rangeStart);
157
+ }
158
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MULTI_DATE)
159
+ return selectedDates;
160
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS) {
161
+ return selectedPeriods.flatMap((weekStart) => expandRange(weekStart, addDaysToKey(weekStart, 6)));
162
+ }
163
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR) {
164
+ return selectedPeriods.flatMap((weekKey) => {
165
+ const weekStart = getIsoWeekStartKeyFromLabel(weekKey);
166
+ return weekStart == null ? [] : expandRange(weekStart, addDaysToKey(weekStart, 6));
167
+ });
168
+ }
169
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MONTH || view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.YEAR) {
170
+ if (!rangeStart)
171
+ return [];
172
+ return expandRange(rangeStart, rangeEnd ?? rangeStart);
173
+ }
174
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS) {
175
+ return selectedPeriods.flatMap((monthKey) => {
176
+ const [year, month] = monthKey.split('-').map(Number);
177
+ return expandRange(`${monthKey}-01`, formatLocalDateKey(new Date(year, month, 0)));
178
+ });
179
+ }
180
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS) {
181
+ return selectedPeriods.flatMap((quarterKey) => expandRange(getQuarterStartKey(quarterKey), getQuarterEndKey(quarterKey)));
182
+ }
183
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS) {
184
+ return selectedPeriods.flatMap((semesterKey) => expandRange(getSemesterStartKey(semesterKey), getSemesterEndKey(semesterKey)));
185
+ }
186
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS) {
187
+ return selectedPeriods.flatMap((yearKey) => expandRange(`${yearKey}-01-01`, `${yearKey}-12-31`));
188
+ }
189
+ return [];
190
+ };
191
+ /**
192
+ * All day keys covered by a selection — keeps only days that match the
193
+ * active weekday refinement, so non-matching days never contribute to
194
+ * summaries, DateContext bounds, or requests.
195
+ */
196
+ const getDayKeysFromCalendarSelection = (selection) => {
197
+ const keys = getBaseSelectedDayKeys(selection);
198
+ const weekdays = getActiveWeekdayFilter(selection.weekdays);
199
+ if (weekdays == null)
200
+ return keys;
201
+ return keys.filter((key) => isDayKeptByWeekdayFilter(key, weekdays));
202
+ };
203
+ exports.getDayKeysFromCalendarSelection = getDayKeysFromCalendarSelection;
204
+ /* ==================== Hour-window validity ==================== */
205
+ /**
206
+ * Whether an hour window `[fromHour, toHour)` fits one business day
207
+ * (06:00 → 06:00) — mirrors the toolkit's materialized window rule
208
+ * (`getMaterializedHourWindowScopeFields`): whole-hour buckets, end-exclusive
209
+ * (18 → 20 = hours 18, 19), midnight wrap allowed (22 → 2), but never a walk
210
+ * crossing the 06:00 business-morning boundary (4 → 8 is invalid). The
211
+ * calendar's time field uses this to disable unservable picker options, so an
212
+ * invalid window can never be composed for the read request.
213
+ */
214
+ const isValidBusinessHourWindow = (fromHour, toHour) => {
215
+ if (!Number.isInteger(fromHour) || fromHour < 0 || fromHour > 23) {
216
+ return false;
217
+ }
218
+ if (!Number.isInteger(toHour) || toHour < 0 || toHour > 23)
219
+ return false;
220
+ const hourCount = (((toHour - fromHour) % 24) + 24) % 24;
221
+ if (hourCount === 0)
222
+ return false; // ambiguous empty window
223
+ const startPosition = (fromHour + 18) % 24;
224
+ return startPosition + hourCount <= 24;
225
+ };
226
+ exports.isValidBusinessHourWindow = isValidBusinessHourWindow;
227
+ /* ==================== Decode internals ==================== */
228
+ /** `'HH:mm'` → hour number (whole hours only). */
229
+ const hourOf = (time) => {
230
+ if (time == null)
231
+ return null;
232
+ const hour = Number.parseInt(time.split(':')[0] ?? '', 10);
233
+ return Number.isInteger(hour) && hour >= 0 && hour <= 23 ? hour : null;
234
+ };
235
+ /** Active time-of-day window (both ends set and servable) — else `null`. */
236
+ const resolveTimeOfDayWindow = (selection) => {
237
+ const fromHour = hourOf(selection.timeStart);
238
+ const toHour = hourOf(selection.timeEnd);
239
+ if (fromHour == null || toHour == null)
240
+ return null;
241
+ if (!(0, exports.isValidBusinessHourWindow)(fromHour, toHour))
242
+ return null;
243
+ return { fromHour, toHour };
244
+ };
245
+ const periodKeyOf = (dayKey, scope) => {
246
+ const fields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(dayKey);
247
+ if (fields == null)
248
+ return null;
249
+ switch (scope) {
250
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK:
251
+ return fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK];
252
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH:
253
+ return fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH];
254
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER:
255
+ return fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER];
256
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER:
257
+ return fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER];
258
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR:
259
+ return fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR];
260
+ default:
261
+ return null;
262
+ }
263
+ };
264
+ /** Groups with at least one value — dropped groups leave `null`. */
265
+ const usableGroups = (groups) => {
266
+ const usable = (groups ?? []).filter((group) => group.scope_field.length > 0);
267
+ return usable.length > 0 ? usable : null;
268
+ };
269
+ /** Groups with the exact period values of one scope (period views). */
270
+ const scopedGroups = (scope, values) => usableGroups([{ scope_context: scope, scope_field: values }]);
271
+ /** Business-hour order of one day's hour buckets — 06…23 then 00…05. */
272
+ const BUSINESS_DAY_HOURS = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5];
273
+ /**
274
+ * Every exact `localHour` label of one business day — the LIVE read. Summed
275
+ * by the backend it yields the running day's metrics so far (the day close
276
+ * finalizes them); a closed day's hours sum to its `localDate` totals.
277
+ */
278
+ const runningDayHourLabels = (dayKey) => BUSINESS_DAY_HOURS.map((hour) => (0, scope_helpers_1.getMaterializedHourScopeField)(dayKey, hour)).filter((label) => label != null);
279
+ /** Week-start day keys from `startKey` to `endKey`, stepping 7 days. */
280
+ const enumerateWeekStarts = (startKey, endKey) => {
281
+ const keys = [];
282
+ let cursor = startKey;
283
+ while (cursor <= endKey) {
284
+ keys.push(cursor);
285
+ cursor = addDaysToKey(cursor, 7);
286
+ }
287
+ return keys;
288
+ };
289
+ /** ISO week labels ('YYYY-Wnn') covering `startDayKey` … `endDayKey`. */
290
+ const enumerateIsoWeeks = (startDayKey, endDayKey) => {
291
+ const keys = [];
292
+ const end = getIsoWeekStartKey(endDayKey);
293
+ let cursor = getIsoWeekStartKey(startDayKey);
294
+ while (cursor <= end) {
295
+ const label = getIsoWeekKey(cursor);
296
+ if (label != null)
297
+ keys.push(label);
298
+ cursor = addDaysToKey(cursor, 7);
299
+ }
300
+ return keys;
301
+ };
302
+ /** 'YYYY-MM' keys from `from` to `to` (inclusive). */
303
+ const enumerateMonths = (from, to) => {
304
+ const keys = [];
305
+ let [year, month] = from.split('-').map(Number);
306
+ const [endYear, endMonth] = to.split('-').map(Number);
307
+ while (year < endYear || (year === endYear && month <= endMonth)) {
308
+ keys.push(`${year}-${`${month}`.padStart(2, '0')}`);
309
+ month += 1;
310
+ if (month > 12) {
311
+ month = 1;
312
+ year += 1;
313
+ }
314
+ }
315
+ return keys;
316
+ };
317
+ /** 'YYYY-Qn' keys from `from` to `to` (inclusive). */
318
+ const enumerateQuarters = (from, to) => {
319
+ const asIndex = (key) => {
320
+ const [year, quarter] = key.split('-');
321
+ return Number(year) * 4 + (Number(quarter.slice(1)) - 1);
322
+ };
323
+ const keys = [];
324
+ for (let index = asIndex(from); index <= asIndex(to); index += 1) {
325
+ keys.push(`${Math.floor(index / 4)}-Q${(index % 4) + 1}`);
326
+ }
327
+ return keys;
328
+ };
329
+ /** 'YYYY-Sn' keys from `from` to `to` (inclusive). */
330
+ const enumerateSemesters = (from, to) => {
331
+ const asIndex = (key) => {
332
+ const [year, semester] = key.split('-');
333
+ return Number(year) * 2 + (Number(semester.slice(1)) - 1);
334
+ };
335
+ const keys = [];
336
+ for (let index = asIndex(from); index <= asIndex(to); index += 1) {
337
+ keys.push(`${Math.floor(index / 2)}-S${(index % 2) + 1}`);
338
+ }
339
+ return keys;
340
+ };
341
+ /** 'YYYY' keys from `from` to `to` (inclusive). */
342
+ const enumerateYears = (from, to) => Array.from({ length: Number(to) - Number(from) + 1 }, (_, index) => `${Number(from) + index}`);
343
+ /** Exact period keys covered by a contiguous range of the given scope. */
344
+ const periodRangeFields = (rangeStart, rangeEnd, scope) => {
345
+ if (rangeStart == null)
346
+ return [];
347
+ const from = periodKeyOf(rangeStart, scope);
348
+ const to = periodKeyOf(rangeEnd ?? rangeStart, scope);
349
+ if (from == null || to == null)
350
+ return [];
351
+ switch (scope) {
352
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK:
353
+ return enumerateWeekStarts(from, to);
354
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH:
355
+ return enumerateMonths(from, to);
356
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER:
357
+ return enumerateQuarters(from, to);
358
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER:
359
+ return enumerateSemesters(from, to);
360
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR:
361
+ return enumerateYears(from, to);
362
+ default:
363
+ return [];
364
+ }
365
+ };
366
+ /* ==================== Decode ==================== */
367
+ /**
368
+ * Maps a committed calendar selection to the exact `scope_groups` of the
369
+ * overview read. Returns `null` when the selection cannot be served (LIVE
370
+ * without a committed day, a malformed/empty selection, or unservable
371
+ * refinement input).
372
+ */
373
+ const buildMaterializedReportScopeGroupsFromSelection = (selection) => {
374
+ // LIVE reads ONLY the running business day — all of its exact hour labels
375
+ // (the calendar commits the running day as `rangeStart`). The backend sums
376
+ // them into one record; the day close finalizes the documents.
377
+ if (selection.mode === REPORT_CALENDAR_1.CALENDAR_MODE_ENUM.LIVE) {
378
+ const dayKey = selection.rangeStart ?? selection.rangeEnd;
379
+ if (dayKey == null)
380
+ return null;
381
+ return usableGroups([
382
+ {
383
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
384
+ scope_field: runningDayHourLabels(dayKey),
385
+ },
386
+ ]);
387
+ }
388
+ const { view, rangeStart, rangeEnd, selectedDates, selectedPeriods } = selection;
389
+ // =====================Refinements (every view)=====================
390
+ //
391
+ // Both refinements degenerate the read to standalone day/hour documents:
392
+ // - time window → `localHour`: the exact hour labels for the selected days;
393
+ // - weekday filter → `localDate`: the matching day keys (`localDate` /
394
+ // `localHour` docs carry `day_index`; period docs do not, hence the scope
395
+ // switch). The weekday refinement is applied inside the effective-day
396
+ // helper BEFORE hour-window expansion — the same helper feeds the
397
+ // calendar's grid highlight and summary aggregate, so UI and request can
398
+ // never disagree.
399
+ const window = resolveTimeOfDayWindow(selection);
400
+ const weekdayFilter = getActiveWeekdayFilter(selection.weekdays);
401
+ if (window != null || weekdayFilter != null) {
402
+ const days = (0, exports.getDayKeysFromCalendarSelection)(selection);
403
+ if (days.length === 0)
404
+ return null;
405
+ // Compile the effective days (+ window) into the minimal scope groups:
406
+ // day runs compact into the largest exact periods they fully cover, and
407
+ // a window becomes exact hour labels — a continuous SPAN on range-like
408
+ // views (toggle), the same hours on each selected day otherwise
409
+ // (dedicated window view / discrete selections).
410
+ const groups = (0, materialized_reports_scope_group_helpers_1.buildMaterializedReportScopeGroups)({
411
+ days,
412
+ ...(window != null
413
+ ? {
414
+ window: {
415
+ fromHour: window.fromHour,
416
+ toHour: window.toHour,
417
+ kind: SPAN_VIEWS.has(view)
418
+ ? materialized_reports_scope_group_helpers_1.MATERIALIZED_REPORT_WINDOW_KIND.SPAN
419
+ : materialized_reports_scope_group_helpers_1.MATERIALIZED_REPORT_WINDOW_KIND.RECURRING,
420
+ },
421
+ }
422
+ : {}),
423
+ });
424
+ if (groups != null) {
425
+ return usableGroups(groups);
426
+ }
427
+ // Uncompilable refinement selection (the picker mirrors the compiler
428
+ // rules, so this should be unreachable) — return `null` instead of
429
+ // silently dropping the window / weekday refinement and reading full
430
+ // days the UI never advertised.
431
+ return null;
432
+ }
433
+ // =====================Period views=====================
434
+ switch (view) {
435
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DATE_RANGE:
436
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DATE_RANGE_TIME_WINDOW:
437
+ // Every day of the range, compacted into the largest exact periods
438
+ // they fully cover; the dedicated window view without a complete
439
+ // window falls back here (same totals, no window).
440
+ return usableGroups((0, materialized_reports_scope_group_helpers_1.buildMaterializedReportScopeGroups)({
441
+ days: (0, exports.getDayKeysFromCalendarSelection)(selection),
442
+ }));
443
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MULTI_DATE:
444
+ // Discrete days still compact — adjacent runs that exactly cover a
445
+ // whole week / month / … fold into it, the rest stays `localDate`.
446
+ return usableGroups((0, materialized_reports_scope_group_helpers_1.buildMaterializedReportScopeGroups)({
447
+ days: Array.isArray(selectedDates) ? selectedDates : [],
448
+ }));
449
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK:
450
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK));
451
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS:
452
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, Array.isArray(selectedPeriods) ? selectedPeriods : []);
453
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.WEEK_OF_YEAR:
454
+ return rangeStart == null
455
+ ? null
456
+ : scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR, enumerateIsoWeeks(rangeStart, rangeEnd ?? rangeStart));
457
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR:
458
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR, Array.isArray(selectedPeriods) ? selectedPeriods : []);
459
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MONTH:
460
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH));
461
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS:
462
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, Array.isArray(selectedPeriods) ? selectedPeriods : []);
463
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.QUARTER:
464
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER));
465
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS:
466
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER, Array.isArray(selectedPeriods) ? selectedPeriods : []);
467
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.SEMESTER:
468
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER));
469
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS:
470
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER, Array.isArray(selectedPeriods) ? selectedPeriods : []);
471
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.YEAR:
472
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR, periodRangeFields(rangeStart, rangeEnd, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR));
473
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS:
474
+ return scopedGroups(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR, Array.isArray(selectedPeriods) ? selectedPeriods : []);
475
+ default:
476
+ return null;
477
+ }
478
+ };
479
+ exports.buildMaterializedReportScopeGroupsFromSelection = buildMaterializedReportScopeGroupsFromSelection;
@@ -18,6 +18,7 @@ export * from './marketing';
18
18
  export * from './materialized-reports-apis';
19
19
  export * from './order-engine';
20
20
  export * from './pra-generate-invoice';
21
+ export * from './report-calendar';
21
22
  export * from './report-webview';
22
23
  export * from './reports';
23
24
  export * from './smartpay-apis';
@@ -34,6 +34,7 @@ __exportStar(require("./marketing"), exports);
34
34
  __exportStar(require("./materialized-reports-apis"), exports);
35
35
  __exportStar(require("./order-engine"), exports);
36
36
  __exportStar(require("./pra-generate-invoice"), exports);
37
+ __exportStar(require("./report-calendar"), exports);
37
38
  __exportStar(require("./report-webview"), exports);
38
39
  __exportStar(require("./reports"), exports);
39
40
  __exportStar(require("./smartpay-apis"), exports);
@@ -1,6 +1,7 @@
1
1
  import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, REPORT_SALE_TYPE_ENUM } from '../../constants';
2
2
  import { MATERIALIZED_REPORT_KEY_FILTER_ENUM } from '../../constants/MATERIALIZED_REPORTS';
3
3
  import { IMaterializedReportOrderMetric, IMaterializedReportPaymentMetric } from '../../schemas/types/materialized_tenant_sales_overview_reports';
4
+ import { IGetMaterializedReportSelectionSpec } from './report-calendar';
4
5
  /**
5
6
  * Request body contracts for the materialized reports READ APIs
6
7
  * (operations-service, mounted at `/reports`) — shared between
@@ -33,25 +34,26 @@ export interface IGetMaterializedReportScopeGroup {
33
34
  /**
34
35
  * Shared body of the materialized reports READ APIs — every report endpoint
35
36
  * (`POST /reports/overview` today; X / Z / Riders / Items / … as they land)
36
- * takes the same shape. Build it with `buildMaterializedReportReadBody`
37
- * (toolkit) and derive the groups from a calendar selection with
38
- * `buildMaterializedReportScopeGroups` (toolkit) — never ad-hoc literals.
37
+ * takes the same shape: the TENANTS plus the CALENDAR SELECTION to serve.
39
38
  *
40
- * The scope query is a LIST of exact-value groups (`scope_groups`, minimum
41
- * length 1, one `scope_context` per group). The backend derives, per group,
42
- * the query shape (a single value is matched with direct equality, multiple
43
- * values with `$in`), folds each group inside MongoDB and answers with ONE
44
- * aggregated record per tenant — the response shape never varies.
39
+ * The client ships the selection itself (`IReportCalendarSelection` — a few
40
+ * hundred bytes regardless of range); the BACKEND decodes it into the exact
41
+ * scope values (`buildMaterializedReportScopeGroupsFromSelection`) and folds
42
+ * each scope group inside MongoDB into ONE aggregated record per tenant — the
43
+ * response shape never varies. Enumerating scope values client-side is NOT
44
+ * part of the wire contract anymore.
45
45
  */
46
46
  export interface IGetMaterializedReportBody {
47
47
  /** One or more tenant ids to read (minimum length 1). */
48
48
  tenants: string[];
49
49
  /**
50
- * One or more scope groups (minimum length 1). Groups may use DIFFERENT
51
- * scope contexts (a span read mixes `localHour` boundary labels with full
52
- * `localDate` / period values); their scopes must not overlap.
50
+ * The committed calendar selection to serve. `spec_version` pins the
51
+ * selection model version (`MATERIALIZED_REPORT_SELECTION_SPEC_VERSION`) —
52
+ * the read API rejects unknown versions with a 400, so rolling deploys
53
+ * (old client → new backend) fail loudly instead of decoding a stale
54
+ * shape.
53
55
  */
54
- scope_groups: IGetMaterializedReportScopeGroup[];
56
+ selection: IGetMaterializedReportSelectionSpec;
55
57
  }
56
58
  /**
57
59
  * Body of `POST /reports/overview` — materialized sales overview
@@ -0,0 +1,20 @@
1
+ import { DAY_INDEX_ENUM } from '../../constants/ENUMS';
2
+ import { CALENDAR_MODE_ENUM, CALENDAR_VIEW_MODE_ENUM } from '../../constants/REPORT_CALENDAR';
3
+ export interface IReportCalendarSelection {
4
+ mode: CALENDAR_MODE_ENUM;
5
+ view: CALENDAR_VIEW_MODE_ENUM;
6
+ rangeStart: string | null;
7
+ rangeEnd: string | null;
8
+ selectedDates: string[];
9
+ timeStart: string | null;
10
+ timeEnd: string | null;
11
+ selectedPeriods: string[];
12
+ weekdays: DAY_INDEX_ENUM[];
13
+ }
14
+ /**
15
+ * A read body's `selection` — the calendar selection plus the spec version
16
+ * the request was built against (`MATERIALIZED_REPORT_SELECTION_SPEC_VERSION`).
17
+ */
18
+ export interface IGetMaterializedReportSelectionSpec extends IReportCalendarSelection {
19
+ spec_version: number;
20
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -37,8 +37,8 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
37
37
  brand_id: string;
38
38
  day_index: import("../../constants").DAY_INDEX_ENUM;
39
39
  iteration: number;
40
- scope_context: import("../../constants").MATERIALIZED_REPORT_SCOPE_ENUM;
41
40
  schema_version: number;
41
+ scope_context: import("../../constants").MATERIALIZED_REPORT_SCOPE_ENUM;
42
42
  scope_field: string;
43
43
  sale_type_key_filters: string[];
44
44
  sale_type_metrics: Map<string, {
@@ -202,8 +202,8 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
202
202
  brand_id: string;
203
203
  day_index: import("../../constants").DAY_INDEX_ENUM;
204
204
  iteration: number;
205
- scope_context: import("../../constants").MATERIALIZED_REPORT_SCOPE_ENUM;
206
205
  schema_version: number;
206
+ scope_context: import("../../constants").MATERIALIZED_REPORT_SCOPE_ENUM;
207
207
  scope_field: string;
208
208
  sale_type_key_filters: string[];
209
209
  sale_type_metrics: Map<string, {
@@ -367,8 +367,8 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
367
367
  brand_id: string;
368
368
  day_index: import("../../constants").DAY_INDEX_ENUM;
369
369
  iteration: number;
370
- scope_context: import("../../constants").MATERIALIZED_REPORT_SCOPE_ENUM;
371
370
  schema_version: number;
371
+ scope_context: import("../../constants").MATERIALIZED_REPORT_SCOPE_ENUM;
372
372
  scope_field: string;
373
373
  sale_type_key_filters: string[];
374
374
  sale_type_metrics: Map<string, {