@managesome/eposmatic-toolkit 0.4.7 → 0.4.9

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 (54) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +33 -0
  2. package/esm/constants/enums/communications.js +1 -0
  3. package/esm/helpers/materialized-reports/index.js +1 -0
  4. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +982 -0
  5. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +276 -33
  6. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +327 -41
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +118 -235
  9. package/esm/schemas/models/index.js +1 -0
  10. package/esm/schemas/models/materialized_credit_bills.js +265 -0
  11. package/esm/schemas/models/materialized_tenant_reports_iterations.js +13 -0
  12. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +39 -97
  13. package/esm/schemas/types/index.js +1 -0
  14. package/esm/schemas/types/materialized_credit_bills.js +1 -0
  15. package/lib/constants/MATERIALIZED_REPORTS.d.ts +28 -2
  16. package/lib/constants/MATERIALIZED_REPORTS.js +34 -1
  17. package/lib/constants/enums/communications.d.ts +1 -0
  18. package/lib/constants/enums/communications.js +2 -1
  19. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  20. package/lib/helpers/materialized-reports/index.js +1 -0
  21. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +307 -0
  22. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +1003 -0
  23. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +36 -2
  24. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +278 -34
  25. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +66 -8
  26. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +326 -40
  27. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +18 -2
  28. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  29. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +46 -37
  30. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +119 -238
  31. package/lib/helpers/types/materialized-reports-apis.d.ts +32 -5
  32. package/lib/schemas/models/index.d.ts +1 -0
  33. package/lib/schemas/models/index.js +1 -0
  34. package/lib/schemas/models/materialized_credit_bills.d.ts +337 -0
  35. package/lib/schemas/models/materialized_credit_bills.js +268 -0
  36. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +20 -6
  37. package/lib/schemas/models/materialized_tenant_reports_iterations.js +14 -1
  38. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +37 -165
  39. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +40 -98
  40. package/lib/schemas/types/index.d.ts +1 -0
  41. package/lib/schemas/types/index.js +1 -0
  42. package/lib/schemas/types/materialized_credit_bills.d.ts +139 -0
  43. package/lib/schemas/types/materialized_credit_bills.js +2 -0
  44. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +32 -77
  45. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.d.ts +1 -0
  46. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +715 -0
  47. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +96 -0
  48. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +9 -0
  49. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +23 -24
  50. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +327 -22
  51. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +27 -2
  52. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +12 -27
  53. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +79 -146
  54. package/package.json +1 -1
@@ -1,5 +1,12 @@
1
1
  import { IGetMaterializedReportScopeGroup } from '../types/materialized-reports-apis';
2
2
  import { IReportCalendarSelection } from '../types/report-calendar';
3
+ /**
4
+ * Upper bound on the raw day span one selection may cover (~10 years).
5
+ * Bounds every date-walk expansion in the decoder; read services surface an
6
+ * over-bound selection as `selectionTooLarge` (400 "narrow the selection")
7
+ * BEFORE any decoding work happens.
8
+ */
9
+ export declare const MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN = 3660;
3
10
  /**
4
11
  * All day keys covered by a selection — keeps only days that match the
5
12
  * active weekday refinement, so non-matching days never contribute to
@@ -16,10 +23,37 @@ export declare const getDayKeysFromCalendarSelection: (selection: IReportCalenda
16
23
  * invalid window can never be composed for the read request.
17
24
  */
18
25
  export declare const isValidBusinessHourWindow: (fromHour: number, toHour: number) => boolean;
26
+ export type TMaterializedReportSelectionValidation = {
27
+ ok: true;
28
+ } | {
29
+ ok: false;
30
+ reason: 'invalid' | 'tooLarge';
31
+ };
32
+ /**
33
+ * Validates the RAW calendar selection BEFORE any decoding work happens:
34
+ * - time keys, when present, must be whole `'HH:00'` hours (minute-level keys
35
+ * are malformed wire values — they must never silently truncate);
36
+ * - the weekday refinement must carry real `DAY_INDEX_ENUM` entries;
37
+ * - every date key (`rangeStart` / `rangeEnd` / `selectedDates` / week-start
38
+ * picks) must be a REAL `'YYYY-MM-DD'` calendar date;
39
+ * - `selectedPeriods` picks must match their view's period grammar and
40
+ * semantics (months 01–12, ISO weeks within the year's week count,
41
+ * quarters Q1–Q4, semesters S1–S2, four-digit years);
42
+ * - contiguous range walks may not cover more than
43
+ * `MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN` days, and discrete picks may
44
+ * not exceed that count — both are `tooLarge` (narrow the selection).
45
+ *
46
+ * The decoder calls this first and maps BOTH failures to `null`; read
47
+ * services call it (via their read parser) to answer a clean 400 before the
48
+ * decoder is ever entered — a malformed request can never reach a date walk.
49
+ */
50
+ export declare const validateMaterializedReportSelectionInput: (selection: IReportCalendarSelection) => TMaterializedReportSelectionValidation;
19
51
  /**
20
52
  * Maps a committed calendar selection to the exact `scope_groups` of the
21
- * overview read. Returns `null` when the selection cannot be served (LIVE
22
- * without a committed day, a malformed/empty selection, or unservable
53
+ * overview read — the PUBLIC decoder: it validates the raw selection
54
+ * (`validateMaterializedReportSelectionInput`) first and NEVER throws.
55
+ * Returns `null` when the selection cannot be served (LIVE without a
56
+ * committed day, a malformed/oversized/empty selection, or unservable
23
57
  * refinement input).
24
58
  */
25
59
  export declare const buildMaterializedReportScopeGroupsFromSelection: (selection: IReportCalendarSelection) => IGetMaterializedReportScopeGroup[] | null;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildMaterializedReportScopeGroupsFromSelection = exports.isValidBusinessHourWindow = exports.getDayKeysFromCalendarSelection = void 0;
3
+ exports.buildMaterializedReportScopeGroupsFromSelection = exports.validateMaterializedReportSelectionInput = exports.isValidBusinessHourWindow = exports.getDayKeysFromCalendarSelection = exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN = void 0;
4
+ const ENUMS_1 = require("../../constants/ENUMS");
4
5
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
5
6
  const REPORT_CALENDAR_1 = require("../../constants/REPORT_CALENDAR");
6
7
  const materialized_reports_scope_group_helpers_1 = require("./materialized-reports-scope-group-helpers");
@@ -31,6 +32,13 @@ const scope_helpers_1 = require("./scope-helpers");
31
32
  * - period views read their exact period keys directly (week starts, ISO week
32
33
  * labels, months, quarters, semesters, years).
33
34
  *
35
+ * Validation: the raw selection is validated FIRST
36
+ * (`validateMaterializedReportSelectionInput`) — every date/period/time key
37
+ * must be well-formed (real calendar dates, exact period keys, whole-hour
38
+ * times) and the raw day span is bounded by
39
+ * `MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN`; malformed or oversized
40
+ * selections return `null` before any walk allocates anything.
41
+ *
34
42
  * Returns `null` (never throws) when the selection cannot be served (missing
35
43
  * range on a range view, malformed keys, an invalid refinement window, or an
36
44
  * unservable empty result). Group values are exact; empty groups are dropped.
@@ -54,6 +62,13 @@ const RANGE_LIKE_VIEWS = new Set([
54
62
  REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.QUARTER,
55
63
  REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.SEMESTER,
56
64
  ]);
65
+ /**
66
+ * Upper bound on the raw day span one selection may cover (~10 years).
67
+ * Bounds every date-walk expansion in the decoder; read services surface an
68
+ * over-bound selection as `selectionTooLarge` (400 "narrow the selection")
69
+ * BEFORE any decoding work happens.
70
+ */
71
+ exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN = 3660;
57
72
  /* ==================== Date-key primitives ==================== */
58
73
  // Local 'YYYY-MM-DD' key for a Date (NOT UTC — the tenant's local day).
59
74
  const formatLocalDateKey = (date) => {
@@ -137,34 +152,64 @@ const isDayKeptByWeekdayFilter = (dateKey, weekdays) => {
137
152
  return dayIndex != null && weekdays.includes(dayIndex);
138
153
  };
139
154
  /* ==================== Effective day set ==================== */
140
- // All day keys covered by the current selection — BEFORE the weekday
141
- // refinement.
142
- const getBaseSelectedDayKeys = (selection) => {
155
+ // All day keys covered by the current selection — the weekday refinement is
156
+ // applied INSIDE the walks so the cap counts the EFFECTIVE day set (a
157
+ // weekday-filtered multi-year selection stays servable while its raw day
158
+ // count exceeds the bound). Every walk is iteration-guarded; an over-bound
159
+ // expansion yields `null` (the decoder maps it to `[]` — unservable; the
160
+ // selection validator classifies it as `tooLarge`).
161
+ const getBaseSelectedDayKeys = (selection, weekdays) => {
143
162
  const { view, rangeStart, rangeEnd, selectedDates, selectedPeriods } = selection;
163
+ const keys = [];
164
+ const appendWithinCap = (list) => {
165
+ for (const key of list) {
166
+ keys.push(key);
167
+ if (keys.length > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
168
+ return false;
169
+ }
170
+ return true;
171
+ };
144
172
  const expandRange = (start, end) => {
145
- const keys = [];
173
+ const expanded = [];
146
174
  let cursor = start;
147
175
  while (cursor <= end) {
148
- keys.push(cursor);
176
+ if (weekdays == null || isDayKeptByWeekdayFilter(cursor, weekdays)) {
177
+ expanded.push(cursor);
178
+ if (expanded.length > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
179
+ return null;
180
+ }
149
181
  cursor = addDaysToKey(cursor, 1);
150
182
  }
151
- return keys;
183
+ return expanded;
152
184
  };
153
185
  if (RANGE_LIKE_VIEWS.has(view)) {
154
186
  if (!rangeStart)
155
187
  return [];
156
188
  return expandRange(rangeStart, rangeEnd ?? rangeStart);
157
189
  }
158
- if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MULTI_DATE)
159
- return selectedDates;
190
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MULTI_DATE) {
191
+ if (selectedDates.length > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
192
+ return null;
193
+ return weekdays == null ? selectedDates : selectedDates.filter((key) => isDayKeptByWeekdayFilter(key, weekdays));
194
+ }
160
195
  if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS) {
161
- return selectedPeriods.flatMap((weekStart) => expandRange(weekStart, addDaysToKey(weekStart, 6)));
196
+ for (const weekStart of selectedPeriods) {
197
+ const days = expandRange(weekStart, addDaysToKey(weekStart, 6));
198
+ if (days == null || !appendWithinCap(days))
199
+ return null;
200
+ }
201
+ return keys;
162
202
  }
163
203
  if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR) {
164
- return selectedPeriods.flatMap((weekKey) => {
204
+ for (const weekKey of selectedPeriods) {
165
205
  const weekStart = getIsoWeekStartKeyFromLabel(weekKey);
166
- return weekStart == null ? [] : expandRange(weekStart, addDaysToKey(weekStart, 6));
167
- });
206
+ if (weekStart == null)
207
+ continue;
208
+ const days = expandRange(weekStart, addDaysToKey(weekStart, 6));
209
+ if (days == null || !appendWithinCap(days))
210
+ return null;
211
+ }
212
+ return keys;
168
213
  }
169
214
  if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MONTH || view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.YEAR) {
170
215
  if (!rangeStart)
@@ -172,19 +217,37 @@ const getBaseSelectedDayKeys = (selection) => {
172
217
  return expandRange(rangeStart, rangeEnd ?? rangeStart);
173
218
  }
174
219
  if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS) {
175
- return selectedPeriods.flatMap((monthKey) => {
220
+ for (const monthKey of selectedPeriods) {
176
221
  const [year, month] = monthKey.split('-').map(Number);
177
- return expandRange(`${monthKey}-01`, formatLocalDateKey(new Date(year, month, 0)));
178
- });
222
+ const days = expandRange(`${monthKey}-01`, formatLocalDateKey(new Date(year, month, 0)));
223
+ if (days == null || !appendWithinCap(days))
224
+ return null;
225
+ }
226
+ return keys;
179
227
  }
180
228
  if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS) {
181
- return selectedPeriods.flatMap((quarterKey) => expandRange(getQuarterStartKey(quarterKey), getQuarterEndKey(quarterKey)));
229
+ for (const quarterKey of selectedPeriods) {
230
+ const days = expandRange(getQuarterStartKey(quarterKey), getQuarterEndKey(quarterKey));
231
+ if (days == null || !appendWithinCap(days))
232
+ return null;
233
+ }
234
+ return keys;
182
235
  }
183
236
  if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS) {
184
- return selectedPeriods.flatMap((semesterKey) => expandRange(getSemesterStartKey(semesterKey), getSemesterEndKey(semesterKey)));
237
+ for (const semesterKey of selectedPeriods) {
238
+ const days = expandRange(getSemesterStartKey(semesterKey), getSemesterEndKey(semesterKey));
239
+ if (days == null || !appendWithinCap(days))
240
+ return null;
241
+ }
242
+ return keys;
185
243
  }
186
244
  if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS) {
187
- return selectedPeriods.flatMap((yearKey) => expandRange(`${yearKey}-01-01`, `${yearKey}-12-31`));
245
+ for (const yearKey of selectedPeriods) {
246
+ const days = expandRange(`${yearKey}-01-01`, `${yearKey}-12-31`);
247
+ if (days == null || !appendWithinCap(days))
248
+ return null;
249
+ }
250
+ return keys;
188
251
  }
189
252
  return [];
190
253
  };
@@ -194,11 +257,16 @@ const getBaseSelectedDayKeys = (selection) => {
194
257
  * summaries, DateContext bounds, or requests.
195
258
  */
196
259
  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));
260
+ try {
261
+ if (!(0, exports.validateMaterializedReportSelectionInput)(selection).ok)
262
+ return [];
263
+ // The base walk already applies the weekday refinement, so its cap counts
264
+ // the EFFECTIVE day set — `null` = over-bound → unservable.
265
+ return getBaseSelectedDayKeys(selection, getActiveWeekdayFilter(selection.weekdays)) ?? [];
266
+ }
267
+ catch {
268
+ return [];
269
+ }
202
270
  };
203
271
  exports.getDayKeysFromCalendarSelection = getDayKeysFromCalendarSelection;
204
272
  /* ==================== Hour-window validity ==================== */
@@ -225,12 +293,15 @@ const isValidBusinessHourWindow = (fromHour, toHour) => {
225
293
  };
226
294
  exports.isValidBusinessHourWindow = isValidBusinessHourWindow;
227
295
  /* ==================== Decode internals ==================== */
228
- /** `'HH:mm'` → hour number (whole hours only). */
296
+ /** `'HH:mm'` → hour number — whole `:00` hours only (minute keys are not servable). */
229
297
  const hourOf = (time) => {
230
298
  if (time == null)
231
299
  return null;
232
- const hour = Number.parseInt(time.split(':')[0] ?? '', 10);
233
- return Number.isInteger(hour) && hour >= 0 && hour <= 23 ? hour : null;
300
+ const match = /^(\d{2}):(\d{2})$/.exec(time);
301
+ if (match == null || match[2] !== '00')
302
+ return null;
303
+ const hour = Number(match[1]);
304
+ return hour >= 0 && hour <= 23 ? hour : null;
234
305
  };
235
306
  /** Active time-of-day window (both ends set and servable) — else `null`. */
236
307
  const resolveTimeOfDayWindow = (selection) => {
@@ -266,8 +337,12 @@ const usableGroups = (groups) => {
266
337
  const usable = (groups ?? []).filter((group) => group.scope_field.length > 0);
267
338
  return usable.length > 0 ? usable : null;
268
339
  };
269
- /** Groups with the exact period values of one scope (period views). */
270
- const scopedGroups = (scope, values) => usableGroups([{ scope_context: scope, scope_field: values }]);
340
+ /**
341
+ * Groups with the exact period values of one scope (period views) — the
342
+ * values are canonicalized (first-occurrence order) so duplicate picks never
343
+ * reach the read as duplicate `$in` entries.
344
+ */
345
+ const scopedGroups = (scope, values) => usableGroups([{ scope_context: scope, scope_field: [...new Set(values)] }]);
271
346
  /** Business-hour order of one day's hour buckets — 06…23 then 00…05. */
272
347
  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
348
  /**
@@ -282,6 +357,8 @@ const enumerateWeekStarts = (startKey, endKey) => {
282
357
  let cursor = startKey;
283
358
  while (cursor <= endKey) {
284
359
  keys.push(cursor);
360
+ if (keys.length > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
361
+ return [];
285
362
  cursor = addDaysToKey(cursor, 7);
286
363
  }
287
364
  return keys;
@@ -295,6 +372,8 @@ const enumerateIsoWeeks = (startDayKey, endDayKey) => {
295
372
  const label = getIsoWeekKey(cursor);
296
373
  if (label != null)
297
374
  keys.push(label);
375
+ if (keys.length > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
376
+ return [];
298
377
  cursor = addDaysToKey(cursor, 7);
299
378
  }
300
379
  return keys;
@@ -306,6 +385,8 @@ const enumerateMonths = (from, to) => {
306
385
  const [endYear, endMonth] = to.split('-').map(Number);
307
386
  while (year < endYear || (year === endYear && month <= endMonth)) {
308
387
  keys.push(`${year}-${`${month}`.padStart(2, '0')}`);
388
+ if (keys.length > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
389
+ return [];
309
390
  month += 1;
310
391
  if (month > 12) {
311
392
  month = 1;
@@ -323,6 +404,8 @@ const enumerateQuarters = (from, to) => {
323
404
  const keys = [];
324
405
  for (let index = asIndex(from); index <= asIndex(to); index += 1) {
325
406
  keys.push(`${Math.floor(index / 4)}-Q${(index % 4) + 1}`);
407
+ if (keys.length > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
408
+ return [];
326
409
  }
327
410
  return keys;
328
411
  };
@@ -335,11 +418,18 @@ const enumerateSemesters = (from, to) => {
335
418
  const keys = [];
336
419
  for (let index = asIndex(from); index <= asIndex(to); index += 1) {
337
420
  keys.push(`${Math.floor(index / 2)}-S${(index % 2) + 1}`);
421
+ if (keys.length > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
422
+ return [];
338
423
  }
339
424
  return keys;
340
425
  };
341
426
  /** 'YYYY' keys from `from` to `to` (inclusive). */
342
- const enumerateYears = (from, to) => Array.from({ length: Number(to) - Number(from) + 1 }, (_, index) => `${Number(from) + index}`);
427
+ const enumerateYears = (from, to) => {
428
+ const count = Number(to) - Number(from) + 1;
429
+ if (!Number.isFinite(count) || count < 0 || count > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN)
430
+ return [];
431
+ return Array.from({ length: count }, (_, index) => `${Number(from) + index}`);
432
+ };
343
433
  /** Exact period keys covered by a contiguous range of the given scope. */
344
434
  const periodRangeFields = (rangeStart, rangeEnd, scope) => {
345
435
  if (rangeStart == null)
@@ -363,14 +453,166 @@ const periodRangeFields = (rangeStart, rangeEnd, scope) => {
363
453
  return [];
364
454
  }
365
455
  };
456
+ /** Whole-hour `'HH:00'` time key — minute-level keys are not servable. */
457
+ const WHOLE_HOUR_TIME_PATTERN = /^([01]\d|2[0-3]):00$/;
458
+ const isRealLocalDateKey = (key) => (0, scope_helpers_1.parseMaterializedLocalDate)(key) != null;
459
+ const epochDayOfLocalDateKey = (key) => {
460
+ const parts = (0, scope_helpers_1.parseMaterializedLocalDate)(key);
461
+ if (parts == null)
462
+ return null;
463
+ return Date.UTC(parts.year, parts.month - 1, parts.day) / 86400000;
464
+ };
465
+ /** ISO week count (52/53) of an ISO week-year — Dec 28 is always in its last ISO week. */
466
+ const getIsoWeeksInYear = (isoYear) => {
467
+ const label = getIsoWeekKey(`${isoYear}-12-28`);
468
+ const match = label == null ? null : /W(\d{2})$/.exec(label);
469
+ return match == null ? 52 : Number(match[1]);
470
+ };
471
+ /** Views whose day set is one contiguous `rangeStart … rangeEnd` walk (incl. MONTH/YEAR). */
472
+ const RANGE_EXPANDING_VIEWS = new Set([
473
+ ...RANGE_LIKE_VIEWS,
474
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MONTH,
475
+ REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.YEAR,
476
+ ]);
477
+ /**
478
+ * Validates the RAW calendar selection BEFORE any decoding work happens:
479
+ * - time keys, when present, must be whole `'HH:00'` hours (minute-level keys
480
+ * are malformed wire values — they must never silently truncate);
481
+ * - the weekday refinement must carry real `DAY_INDEX_ENUM` entries;
482
+ * - every date key (`rangeStart` / `rangeEnd` / `selectedDates` / week-start
483
+ * picks) must be a REAL `'YYYY-MM-DD'` calendar date;
484
+ * - `selectedPeriods` picks must match their view's period grammar and
485
+ * semantics (months 01–12, ISO weeks within the year's week count,
486
+ * quarters Q1–Q4, semesters S1–S2, four-digit years);
487
+ * - contiguous range walks may not cover more than
488
+ * `MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN` days, and discrete picks may
489
+ * not exceed that count — both are `tooLarge` (narrow the selection).
490
+ *
491
+ * The decoder calls this first and maps BOTH failures to `null`; read
492
+ * services call it (via their read parser) to answer a clean 400 before the
493
+ * decoder is ever entered — a malformed request can never reach a date walk.
494
+ */
495
+ const validateMaterializedReportSelectionInput = (selection) => {
496
+ const invalid = { ok: false, reason: 'invalid' };
497
+ const tooLarge = { ok: false, reason: 'tooLarge' };
498
+ if (selection == null || typeof selection !== 'object')
499
+ return invalid;
500
+ const { view, rangeStart, rangeEnd, selectedDates, selectedPeriods } = selection;
501
+ // Whole-hour time keys only — `'18:45'` must not silently read 18:00–18:44.
502
+ if (selection.timeStart != null && !WHOLE_HOUR_TIME_PATTERN.test(selection.timeStart))
503
+ return invalid;
504
+ if (selection.timeEnd != null && !WHOLE_HOUR_TIME_PATTERN.test(selection.timeEnd))
505
+ return invalid;
506
+ // Weekday refinement entries must be real day-index keys.
507
+ const weekdays = Array.isArray(selection.weekdays) ? selection.weekdays : [];
508
+ if (!weekdays.every((entry) => ENUMS_1.ALL_DAY_INDEX.includes(entry)))
509
+ return invalid;
510
+ // Every date key that could reach a date walk must be a REAL calendar date.
511
+ const dates = Array.isArray(selectedDates) ? selectedDates : [];
512
+ const dateKeys = [rangeStart, rangeEnd, ...dates];
513
+ if (dateKeys.some((key) => key != null && !isRealLocalDateKey(key)))
514
+ return invalid;
515
+ if (view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.MULTI_DATE && dates.length > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN) {
516
+ return tooLarge;
517
+ }
518
+ // Period picks — strict per-view grammar + semantics (a bad key would
519
+ // otherwise surface as a 200 "No Data" instead of a 400).
520
+ const periods = Array.isArray(selectedPeriods) ? selectedPeriods : [];
521
+ const overPicked = periods.length > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN ? tooLarge : null;
522
+ switch (view) {
523
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS:
524
+ if (overPicked != null)
525
+ return overPicked;
526
+ if (!periods.every((key) => isRealLocalDateKey(key)))
527
+ return invalid;
528
+ break;
529
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR:
530
+ if (overPicked != null)
531
+ return overPicked;
532
+ for (const key of periods) {
533
+ const match = /^(\d{4})-W(\d{2})$/.exec(key);
534
+ if (match == null)
535
+ return invalid;
536
+ const week = Number(match[2]);
537
+ if (week < 1 || week > getIsoWeeksInYear(Number(match[1])))
538
+ return invalid;
539
+ }
540
+ break;
541
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS:
542
+ if (overPicked != null)
543
+ return overPicked;
544
+ if (!periods.every((key) => /^\d{4}-(0[1-9]|1[0-2])$/.test(key)))
545
+ return invalid;
546
+ break;
547
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS:
548
+ if (overPicked != null)
549
+ return overPicked;
550
+ if (!periods.every((key) => /^\d{4}-Q[1-4]$/.test(key)))
551
+ return invalid;
552
+ break;
553
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS:
554
+ if (overPicked != null)
555
+ return overPicked;
556
+ if (!periods.every((key) => /^\d{4}-S[12]$/.test(key)))
557
+ return invalid;
558
+ break;
559
+ case REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS:
560
+ if (overPicked != null)
561
+ return overPicked;
562
+ if (!periods.every((key) => /^\d{4}$/.test(key)))
563
+ return invalid;
564
+ break;
565
+ default:
566
+ break;
567
+ }
568
+ // Contiguous range walks are bounded by the raw day span (~10 years).
569
+ if (RANGE_EXPANDING_VIEWS.has(view) && rangeStart != null && rangeEnd != null) {
570
+ const start = epochDayOfLocalDateKey(rangeStart);
571
+ const end = epochDayOfLocalDateKey(rangeEnd);
572
+ if (start != null && end != null && Math.abs(end - start) > exports.MATERIALIZED_REPORT_MAX_SELECTION_DAY_SPAN - 1) {
573
+ return tooLarge;
574
+ }
575
+ }
576
+ // DIFFERENT_* picks expand to REAL days at decode time — with the weekday
577
+ // refinement applied. The decode caps the EFFECTIVE day set, so an
578
+ // oversize expansion must classify as `tooLarge` HERE instead of surfacing
579
+ // downstream as an unexplained "invalid" (the decoder maps it to `null`).
580
+ const expandsPicksToDays = view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS ||
581
+ view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_WEEKS_OF_YEAR ||
582
+ view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_MONTHS ||
583
+ view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_QUARTERS ||
584
+ view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_SEMESTERS ||
585
+ view === REPORT_CALENDAR_1.CALENDAR_VIEW_MODE_ENUM.DIFFERENT_YEARS;
586
+ if (expandsPicksToDays && getBaseSelectedDayKeys(selection, getActiveWeekdayFilter(selection.weekdays)) == null) {
587
+ return tooLarge;
588
+ }
589
+ return { ok: true };
590
+ };
591
+ exports.validateMaterializedReportSelectionInput = validateMaterializedReportSelectionInput;
366
592
  /* ==================== Decode ==================== */
367
593
  /**
368
594
  * 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
595
+ * overview read — the PUBLIC decoder: it validates the raw selection
596
+ * (`validateMaterializedReportSelectionInput`) first and NEVER throws.
597
+ * Returns `null` when the selection cannot be served (LIVE without a
598
+ * committed day, a malformed/oversized/empty selection, or unservable
371
599
  * refinement input).
372
600
  */
373
601
  const buildMaterializedReportScopeGroupsFromSelection = (selection) => {
602
+ try {
603
+ if (selection == null || typeof selection !== 'object')
604
+ return null;
605
+ if (!(0, exports.validateMaterializedReportSelectionInput)(selection).ok)
606
+ return null;
607
+ return decodeMaterializedReportScopeGroups(selection);
608
+ }
609
+ catch {
610
+ return null;
611
+ }
612
+ };
613
+ exports.buildMaterializedReportScopeGroupsFromSelection = buildMaterializedReportScopeGroupsFromSelection;
614
+ /** Internal decode — the public entry above validates + backstops first. */
615
+ const decodeMaterializedReportScopeGroups = (selection) => {
374
616
  // LIVE reads ONLY the running business day — all of its exact hour labels
375
617
  // (the calendar commits the running day as `rangeStart`). The backend sums
376
618
  // them into one record; the day close finalizes the documents.
@@ -414,7 +656,10 @@ const buildMaterializedReportScopeGroupsFromSelection = (selection) => {
414
656
  window: {
415
657
  fromHour: window.fromHour,
416
658
  toHour: window.toHour,
417
- kind: SPAN_VIEWS.has(view)
659
+ // A weekday-refined day set is GAPPED — a continuous SPAN can
660
+ // never compile it. Weekday + window therefore always compiles
661
+ // RECURRING (the same hours on each matching weekday).
662
+ kind: SPAN_VIEWS.has(view) && weekdayFilter == null
418
663
  ? materialized_reports_scope_group_helpers_1.MATERIALIZED_REPORT_WINDOW_KIND.SPAN
419
664
  : materialized_reports_scope_group_helpers_1.MATERIALIZED_REPORT_WINDOW_KIND.RECURRING,
420
665
  },
@@ -476,4 +721,3 @@ const buildMaterializedReportScopeGroupsFromSelection = (selection) => {
476
721
  return null;
477
722
  }
478
723
  };
479
- exports.buildMaterializedReportScopeGroupsFromSelection = buildMaterializedReportScopeGroupsFromSelection;
@@ -1,4 +1,5 @@
1
1
  import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { IMaterializedTenantCreditBillsReport } from '../../schemas/types/materialized_credit_bills';
2
3
  import { IMaterializedTenantReportIterationInput } from '../../schemas/types/materialized_tenant_reports_iterations';
3
4
  import { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
4
5
  import { IConvertOrdersToMaterializedReportsResult } from './tenant-sales-overview-helpers';
@@ -8,7 +9,9 @@ import { IConvertOrdersToMaterializedReportsResult } from './tenant-sales-overvi
8
9
  *
9
10
  * The day-close job compiles one tenant-day (`convertOrdersTo…`), fetches the
10
11
  * stored documents the plan needs (`getMaterializedTenantSalesOverviewScopeRefsForDay`
11
- * + the issue-day docs of collected bills), and asks this module for the
12
+ * + `getMaterializedCreditBillScopeRefsForDay` of the compiled day and, for
13
+ * every collected bill's issue day,
14
+ * `getMaterializedCreditBillScopeRefsForIssue`), and asks this module for the
12
15
  * complete write plan:
13
16
  *
14
17
  * - **`writes`** — hour + date documents (insert, or `replacement` when stored
@@ -18,12 +21,32 @@ import { IConvertOrdersToMaterializedReportsResult } from './tenant-sales-overvi
18
21
  * `materialized_tenant_reports_iterations` history row; persist both.
19
22
  * - **`staleHourDocuments`** — stored `localHour` docs of the day with no
20
23
  * activity anymore (orders deleted / moved) — delete by `_id`.
21
- * - **`receivedPatches`** — issue-day docs holding bills collected on the
22
- * compiled day, patched through `update(…, { received_payments })`. A
23
- * ledger-changing patch is a versioned write, so each patched document
24
- * comes with its history row; computed against the POST-write documents,
25
- * so a period doc that both accumulates the day and holds an earlier bill
26
- * keeps the accumulation — persist them AFTER `writes`.
24
+ * - **`creditWrites`** — the day's `materialized_tenant_credit_bills`
25
+ * documents (month-capped scopes: hour/date/week/ISO-week/month), fed by the
26
+ * SAME resolution as the counters (single writer — the two collections can
27
+ * never drift). The ledger is single-source: report documents hold credit
28
+ * COUNTERS only.
29
+ * - **`creditSettlementPatches`** — issue-scope credit documents patched with
30
+ * settlement anchors (`received_amount` + `settled_*` + note) exactly once
31
+ * per settlement; versioned writes, persist AFTER `creditWrites`.
32
+ * - **`creditStaleHourDocuments`** — stored credit hour docs of the day with
33
+ * no entries anymore (orders deleted / moved; an emptied day also drops its
34
+ * date doc) — delete by `_id`.
35
+ * - **`creditSkippedDocuments`** — credit documents already up to date.
36
+ * - **`receivedPatches`** — issued-day documents patched with SETTLED
37
+ * COUNTER deltas (`settled_count` +1 / `settled_amount` + `amount`) when a
38
+ * stored ledger row passes its unsettled→settled transition; counters only,
39
+ * a versioned write each, computed against the POST-write documents — so a
40
+ * period doc that both accumulates the day and holds an earlier bill keeps
41
+ * the accumulation; persist them AFTER `writes`.
42
+ * - **resolution (the only stateful step)** — `resolveCreditBillDay` resolves
43
+ * each receipt event's `received_delta` against the stored credit DOCUMENTS
44
+ * (a stored same-day event's delta is preserved → idempotent re-closes),
45
+ * carries each bill's `received_at_issue` / settlement anchors forward (a
46
+ * re-close after collection must never re-anchor them) and emits the
47
+ * settlements the close must patch. The plan fills the compiled
48
+ * collection-day documents' `received` COUNTERS and builds the credit
49
+ * documents from that ONE resolution.
27
50
  * - **`skippedDocuments`** — already up to date (see
28
51
  * `needsMaterializedTenantSalesOverviewReportWrite`).
29
52
  * - **`createdPeriodDocuments`** — period docs that were absent from
@@ -58,6 +81,17 @@ export interface IBuildTenantSalesOverviewCloseDayPlanInput {
58
81
  * fetch refs) is fine; two different rows for one scope key → `null`.
59
82
  */
60
83
  existing?: IMaterializedTenantSalesOverviewReport[];
84
+ /**
85
+ * Stored `materialized_tenant_credit_bills` documents the job fetched: the
86
+ * compiled day's scopes (`getMaterializedCreditBillScopeRefsForDay`) PLUS
87
+ * the issue scopes of every collected bill
88
+ * (`getMaterializedCreditBillScopeRefsForIssue`). The close plan resolves
89
+ * receipt deltas and carries settlement anchors forward against THESE
90
+ * documents, then materializes the day's credit documents from the same
91
+ * resolution. Repeating the SAME document is fine; two different rows for
92
+ * one scope key → `null`.
93
+ */
94
+ existingCreditBills?: IMaterializedTenantCreditBillsReport[];
61
95
  /** Force structural writes even when the watermarks are up to date. */
62
96
  force?: boolean;
63
97
  /** Override for write timestamps (tests, replays). */
@@ -70,13 +104,37 @@ export interface ITenantSalesOverviewCloseDayWrite {
70
104
  /** `materialized_tenant_reports_iterations` row — upsert by `(report_id, iteration)`. */
71
105
  iteration: IMaterializedTenantReportIterationInput;
72
106
  }
107
+ /** One versioned credit write (structural write or settlement patch): persist `report` + upsert its history row. */
108
+ export interface ITenantCreditBillsCloseDayWrite {
109
+ /** Post-write document (stored `_id` kept for replacements). */
110
+ report: IMaterializedTenantCreditBillsReport;
111
+ /** `materialized_tenant_reports_iterations` row — upsert by `(report_id, iteration)`. */
112
+ iteration: IMaterializedTenantReportIterationInput<IMaterializedTenantCreditBillsReport>;
113
+ }
73
114
  /** The complete close-day write plan (see the module docs). */
74
115
  export interface ITenantSalesOverviewCloseDayPlan {
75
116
  /** Structural writes (report + history row) — persist in any order. */
76
117
  writes: ITenantSalesOverviewCloseDayWrite[];
77
118
  /** Stored hour docs of the compiled day no longer backed by activity — delete by `_id`. */
78
119
  staleHourDocuments: IMaterializedTenantSalesOverviewReport[];
79
- /** Issued-ledger patches (versioned writes) — persist AFTER `writes`. */
120
+ /**
121
+ * `materialized_tenant_credit_bills` writes (month-capped scopes) — the
122
+ * itemized ledger; persist BEFORE the settlement patches below.
123
+ */
124
+ creditWrites: ITenantCreditBillsCloseDayWrite[];
125
+ /** Stored credit hour/docs of the day no longer backed by entries — delete by `_id`. */
126
+ creditStaleHourDocuments: IMaterializedTenantCreditBillsReport[];
127
+ /** Credit documents already up to date (freshness proven by the watermark guard). */
128
+ creditSkippedDocuments: IMaterializedTenantCreditBillsReport[];
129
+ /**
130
+ * Issue-scope settlement patches (versioned credit writes) — persist AFTER
131
+ * `creditWrites` (computed against the post-write documents).
132
+ */
133
+ creditSettlementPatches: ITenantCreditBillsCloseDayWrite[];
134
+ /**
135
+ * Issued-day SETTLED counter patches (versioned writes, counters only) —
136
+ * persist AFTER `writes` (computed against the post-write documents).
137
+ */
80
138
  receivedPatches: ITenantSalesOverviewCloseDayWrite[];
81
139
  /** Stored docs that were already up to date (job logging). */
82
140
  skippedDocuments: IMaterializedTenantSalesOverviewReport[];