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