@managesome/eposmatic-toolkit 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/esm/helpers/materialized-reports/index.js +1 -0
  2. package/esm/helpers/materialized-reports/materialized-reports-read-helpers.js +96 -22
  3. package/esm/helpers/materialized-reports/materialized-reports-scope-group-helpers.js +281 -0
  4. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +126 -7
  5. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +47 -1
  6. package/esm/helpers/order/generate-order.js +11 -0
  7. package/esm/helpers/store/common-order-actions.js +7 -3
  8. package/esm/helpers/types/materialized-reports-apis.js +1 -1
  9. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +20 -26
  10. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  11. package/lib/helpers/materialized-reports/index.js +1 -0
  12. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.d.ts +50 -21
  13. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.js +96 -21
  14. package/lib/helpers/materialized-reports/materialized-reports-scope-group-helpers.d.ts +58 -0
  15. package/lib/helpers/materialized-reports/materialized-reports-scope-group-helpers.js +286 -0
  16. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +24 -0
  17. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +127 -7
  18. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +47 -1
  19. package/lib/helpers/order/generate-order.d.ts +2 -0
  20. package/lib/helpers/order/generate-order.js +13 -0
  21. package/lib/helpers/store/common-order-actions.js +7 -3
  22. package/lib/helpers/types/materialized-reports-apis.d.ts +115 -25
  23. package/lib/helpers/types/materialized-reports-apis.js +1 -0
  24. package/lib/schemas/models/internal_invoices.d.ts +3 -3
  25. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +26 -34
  26. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +20 -26
  27. package/lib/schemas/models/orders.d.ts +692 -692
  28. package/lib/schemas/models/tenant_purchase_orders.d.ts +90 -90
  29. package/lib/schemas/models/tenants.d.ts +9 -9
  30. package/lib/schemas/models/warehouse_communications.d.ts +3 -3
  31. package/lib/schemas/models/warehouse_internal_movements.d.ts +48 -48
  32. package/lib/schemas/models/warehouse_purchase_order_rfqs.d.ts +63 -63
  33. package/lib/schemas/models/warehouse_purchase_orders.d.ts +96 -96
  34. package/lib/schemas/models/warehouse_sale_invoices.d.ts +3 -3
  35. package/lib/schemas/models/warehouse_sale_order_rfqs.d.ts +69 -69
  36. package/lib/schemas/models/warehouse_sale_orders.d.ts +45 -45
  37. package/lib/schemas/models/warehouses.d.ts +6 -6
  38. package/lib/tests/materialized-reports/materialized-reports-read-helpers.test.d.ts +1 -0
  39. package/lib/tests/materialized-reports/materialized-reports-read-helpers.test.js +100 -0
  40. package/lib/tests/materialized-reports/materialized-reports-scope-group-helpers.test.d.ts +1 -0
  41. package/lib/tests/materialized-reports/materialized-reports-scope-group-helpers.test.js +275 -0
  42. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +11 -0
  43. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.d.ts +1 -0
  44. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +143 -0
  45. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +22 -0
  46. package/lib/tests/num-of-guests-limit.test.d.ts +1 -0
  47. package/lib/tests/num-of-guests-limit.test.js +76 -0
  48. package/package.json +1 -1
@@ -241,6 +241,50 @@ function finalizeMetrics(metrics) {
241
241
  }
242
242
  return finalized;
243
243
  }
244
+ /** True for a number that is zero (or broken beyond being distinguishable). */
245
+ const isZeroNumber = (value) => !value;
246
+ const isZeroPaymentMetric = (payment) => isZeroNumber(payment.count) &&
247
+ isZeroNumber(payment.gross_amount) &&
248
+ isZeroNumber(payment.amount_due) &&
249
+ isZeroNumber(payment.amount_paid) &&
250
+ isZeroNumber(payment.amount_refunded) &&
251
+ isZeroNumber(payment.card_charges);
252
+ const isZeroOrderReportMetric = (orders) => isZeroNumber(orders.count) &&
253
+ isZeroNumber(orders.gross_amount) &&
254
+ isZeroNumber(orders.discount_amount) &&
255
+ isZeroNumber(orders.discount_by_type.special_discount) &&
256
+ isZeroNumber(orders.discount_by_type.loyalty_discount) &&
257
+ isZeroNumber(orders.discount_by_type.voucher_discount) &&
258
+ isZeroNumber(orders.gst_amount) &&
259
+ isZeroNumber(orders.tax_amount) &&
260
+ isZeroNumber(orders.tip_amount) &&
261
+ isZeroNumber(orders.tax_invoice_provider_charges) &&
262
+ isZeroNumber(orders.delivery_charges);
263
+ /**
264
+ * Reconcile-time cleanup: subtracting a day can zero a key out while leaving
265
+ * it behind — a "zombie" key that would make accumulated period documents
266
+ * diverge from day / hour reads (which simply lose the key). Compile output
267
+ * never carries all-zero keys, so pruning only removes reconcile artifacts.
268
+ * A key whose payments are all zero-valued counts as empty (subtraction can
269
+ * leave zero-count payment entries behind).
270
+ */
271
+ const pruneZeroReportKeys = (metrics) => {
272
+ const pruned = {};
273
+ for (const [key, metric] of Object.entries(metrics)) {
274
+ const totalSales = metric[REPORT_SALE_TYPE_ENUM.TOTAL_SALES];
275
+ const amountCollected = metric[REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED];
276
+ const creditBills = metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
277
+ const isZero = isZeroOrderReportMetric(totalSales.orders) &&
278
+ totalSales.payments.every(isZeroPaymentMetric) &&
279
+ isZeroOrderReportMetric(amountCollected.orders) &&
280
+ (amountCollected.payments ?? []).every(isZeroPaymentMetric) &&
281
+ creditBills.issued.bills.length === 0 &&
282
+ creditBills.received.bills.length === 0;
283
+ if (!isZero)
284
+ pruned[key] = metric;
285
+ }
286
+ return pruned;
287
+ };
244
288
  /**
245
289
  * Deep plain-value conversion for mongoose-hydrated values: subdocuments
246
290
  * (`toObject()`), nested `Map`s and document arrays. Plain JSON values are
@@ -862,7 +906,9 @@ export function updateMaterializedTenantSalesOverviewReport(existing, updates, o
862
906
  }
863
907
  return {
864
908
  ...existing,
865
- sale_type_metrics: finalizeMetrics(metrics),
909
+ // Reconcile artifacts: a fully-subtracted key is pruned so accumulated
910
+ // period documents keep the same key set as day / hour reads.
911
+ sale_type_metrics: pruneZeroReportKeys(finalizeMetrics(metrics)),
866
912
  // Version metric writes AND ledger-changing received-payment patches (both
867
913
  // append a history row via the caller). No-op patches bump nothing, so
868
914
  // replays stay churn-free.
@@ -1,5 +1,15 @@
1
1
  import Mongoose from 'mongoose';
2
2
  import { PAYMENT_STATUS_ENUM, PAYMENT_TYPE_ENUM } from '../../constants';
3
+ // num_of_guests is persisted as a BSON int32 (orders collection validator: bsonType 'int', minimum 1).
4
+ // Corrupt client values (e.g. 3257330333) serialize as a double and make the whole order write fail
5
+ // document validation — clamp to a sane range on every normalization pass.
6
+ export const MAX_NUM_OF_GUESTS = 1000;
7
+ export function getValidNumOfGuests(num_of_guests) {
8
+ const numOfGuests = Number(num_of_guests);
9
+ if (!Number.isFinite(numOfGuests) || numOfGuests < 1)
10
+ return 1;
11
+ return Math.min(Math.floor(numOfGuests), MAX_NUM_OF_GUESTS);
12
+ }
3
13
  export function generateOrderDineinDetails(dinein_details) {
4
14
  if (!dinein_details)
5
15
  return null;
@@ -7,6 +17,7 @@ export function generateOrderDineinDetails(dinein_details) {
7
17
  ...dinein_details,
8
18
  floor_id: new Mongoose.Types.ObjectId(dinein_details.floor_id),
9
19
  table_id: new Mongoose.Types.ObjectId(dinein_details.table_id),
20
+ num_of_guests: getValidNumOfGuests(dinein_details.num_of_guests),
10
21
  reservation_time: new Date(dinein_details.reservation_time),
11
22
  start_time: new Date(dinein_details.start_time),
12
23
  };
@@ -1,5 +1,6 @@
1
1
  import ObjectID from 'bson-objectid';
2
2
  import { ORDER_TYPE_ENUM, SPLIT_BILL_TYPE_ENUM } from '../../constants';
3
+ import { getValidNumOfGuests } from '../order/generate-order';
3
4
  import { convertPriceFromCents, convertPriceToCents, parseNum } from '../utils';
4
5
  import { calculateCartOrderInfoAndSyncData, getCartItemsObj } from './cart-actions';
5
6
  /* ======================>Order Object<====================== */
@@ -177,7 +178,7 @@ export function getOrderWithPrice(order, toCents) {
177
178
  ? {
178
179
  dinein_details: {
179
180
  ...order.dinein_details,
180
- num_of_guests: order.dinein_details.num_of_guests || 1,
181
+ num_of_guests: getValidNumOfGuests(order.dinein_details.num_of_guests),
181
182
  },
182
183
  }
183
184
  : {}),
@@ -235,9 +236,12 @@ function getCommonOptionalBoolFields(order, partial) {
235
236
  }
236
237
  function getCommonOptionalNullFields(order, partial) {
237
238
  const defaultValue = partial ? undefined : null;
239
+ const dineinDetails = order['dinein_details'];
238
240
  return {
239
241
  delivery_details: order['delivery_details'] || defaultValue,
240
- dinein_details: order['dinein_details'] || defaultValue,
242
+ dinein_details: dineinDetails != null
243
+ ? { ...dineinDetails, num_of_guests: getValidNumOfGuests(dineinDetails.num_of_guests) }
244
+ : defaultValue,
241
245
  takeaway_details: order['takeaway_details'] || defaultValue,
242
246
  staff_details: order['staff_details'] || defaultValue,
243
247
  order_taker_details: order['order_taker_details'] || defaultValue,
@@ -509,7 +513,7 @@ function syncDineinCoursesOnSplit(dinein_details, swapedItemIdsMap, totalChecks,
509
513
  }
510
514
  const result = {
511
515
  ...dinein_details,
512
- num_of_guests,
516
+ num_of_guests: getValidNumOfGuests(num_of_guests),
513
517
  courses: newCourses,
514
518
  };
515
519
  return result;
@@ -1 +1 @@
1
- export {};
1
+ import { REPORT_SALE_TYPE_ENUM } from '../../constants';
@@ -362,38 +362,32 @@ export const MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME = 'mater
362
362
  /**
363
363
  * Describes the indexes for `materialized_tenant_sales_overview_reports`.
364
364
  * Values are Mongo key patterns that can be passed straight to `.hint()`.
365
- * - `_id`: unique primary key.
366
- * - `tenant_id__scope_context__scope_field`: UNIQUE index — one document per
367
- * (tenant, scope context, scope value); also serves the standardized query
368
- * (`tenant_id` + `scope_context` + `scope_field`).
369
- * - `brand_id__scope_context__scope_field`: brand-level reads across the
370
- * brand's tenants (sum across their tenant documents).
371
- * - `tenant_id__scope_context__day_index__scope_field` (+ brand variant):
372
- * weekday queries over LOCAL_HOUR / LOCAL_DATE slices
373
- * (`day_index` + `scope_field` range).
365
+ *
366
+ * ONE compound index carries the whole read story (plus `_id`):
367
+ * `tenant_id__scope_context__scope_field__day_index` — UNIQUE:
368
+ * - identity — one document per (tenant, scope context, scope value);
369
+ * `day_index` is a deterministic function of `scope_field` (null for period
370
+ * scopes), so including it keeps the uniqueness exactly on that identity;
371
+ * - the standardized read — the `{ tenant_id, scope_context, scope_field }`
372
+ * PREFIX serves single-tenant and `$in` tenant-list queries (exact or range
373
+ * on `scope_field`) without a second index;
374
+ * - weekday queries — a `scope_field` range bounded by the prefix, with
375
+ * `day_index` filtered straight from the index keys.
376
+ *
377
+ * There are NO `brand_id` indexes: brand-level reads always pass the brand's
378
+ * explicit tenant list (`tenant_id: { $in }` — including user-filtered tenant
379
+ * subsets, which a `brand_id` index could not serve at all). Add a brand
380
+ * index only if a future reader genuinely scans whole brands without a
381
+ * tenant list.
374
382
  */
375
383
  export const MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_INDEXES = {
376
384
  _id: { _id: 1 }, // Unique Index
377
- tenant_id__scope_context__scope_field: {
378
- tenant_id: 1,
379
- scope_context: 1,
380
- scope_field: 1,
381
- }, // unique — one document per (tenant, scope context, scope value)
382
- brand_id__scope_context__scope_field: {
383
- brand_id: 1,
384
- scope_context: 1,
385
- scope_field: 1,
386
- }, // brand-level reads across the brand's tenants
385
+ // unique — one document per (tenant, scope context, scope value); the prefix
386
+ // serves the standardized query, the trailing day_index covers weekday reads
387
387
  tenant_id__scope_context__scope_field__day_index: {
388
388
  tenant_id: 1,
389
389
  scope_context: 1,
390
390
  scope_field: 1,
391
391
  day_index: 1,
392
- }, // weekday queries over LOCAL_HOUR / LOCAL_DATE slices
393
- brand_id__scope_context__scope_field__day_index: {
394
- brand_id: 1,
395
- scope_context: 1,
396
- scope_field: 1,
397
- day_index: 1,
398
- }, // brand-level weekday queries over LOCAL_HOUR / LOCAL_DATE slices
392
+ },
399
393
  };
@@ -1,5 +1,6 @@
1
1
  export * from './key-helpers';
2
2
  export * from './materialized-reports-read-helpers';
3
+ export * from './materialized-reports-scope-group-helpers';
3
4
  export * from './materialized-tenant-reports-iterations-helpers';
4
5
  export * from './scope-helpers';
5
6
  export * from './tenant-sales-overview-close-day-helpers';
@@ -16,6 +16,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./key-helpers"), exports);
18
18
  __exportStar(require("./materialized-reports-read-helpers"), exports);
19
+ __exportStar(require("./materialized-reports-scope-group-helpers"), exports);
19
20
  __exportStar(require("./materialized-tenant-reports-iterations-helpers"), exports);
20
21
  __exportStar(require("./scope-helpers"), exports);
21
22
  __exportStar(require("./tenant-sales-overview-close-day-helpers"), exports);
@@ -1,18 +1,20 @@
1
1
  import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
2
  import { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
3
+ import { IGetMaterializedReportBody, IGetMaterializedReportScopeGroup } from '../types/materialized-reports-apis';
3
4
  /**
4
5
  * Read-side helpers for materialized-report documents — the frontend-facing
5
6
  * half of the query story (see `MATERIALIZED_REPORTS.md` "Time scopes").
6
7
  *
7
- * The ops-service read API takes `{ scope_context, scope_field | from/to }`:
8
- * - contiguous selections go through `from`/`to` directly (callers can use
9
- * `getMaterializedScopeSpan` / `getMaterializedHourScopeSpan` to derive the
10
- * span of a set of keys);
11
- * - discrete selections fetch the min..max SPAN and keep the exact keys with
12
- * `filterMaterializedTenantSalesOverviewReportsByScopeFields`;
8
+ * The ops-service read API takes `{ scope_context, scope_field }` where
9
+ * `scope_field` is an EXACT value or an `$in` list of exact values — the
10
+ * request itself never carries ranges:
11
+ * - every selection (contiguous periods, discrete picks, hour windows,
12
+ * weekday filters) is compiled by the caller into the exact value list it
13
+ * wants;
13
14
  * - recurring hour windows (e.g. 6–8pm on every day of a range) expand to the
14
- * exact hour labels with `getMaterializedHourWindowScopeFields` (span-fetch
15
- * the full days first, then filter to the labels).
15
+ * exact hour labels with `getMaterializedHourWindowScopeFields`;
16
+ * - `getMaterializedScopeSpan` / `getMaterializedHourScopeSpan` remain as
17
+ * min..max bounds utilities for key sets (not part of the read path).
16
18
  *
17
19
  * Validation convention: helpers return `null` instead of throwing — `null`
18
20
  * means the caller passed invalid data.
@@ -46,12 +48,9 @@ export declare function getMaterializedBusinessHourIndex(hour: number): number |
46
48
  */
47
49
  export declare function getMaterializedHourWindowScopeFields(businessDays: string[], fromHour: number, toHour: number): string[] | null;
48
50
  /**
49
- * Full-day span of a list of business days for `localHour` reads: the
50
- * inclusive `{ from: '<first> 00', to: '<last> 23' }` range covers ALL 24
51
- * hour buckets of every label day in between (a label day's buckets are
52
- * `'D 00'`…`'D 23'`, spanning the post-midnight hours too). Filter the
53
- * fetched documents afterwards with `getMaterializedHourWindowScopeFields` /
54
- * `filterMaterializedTenantSalesOverviewReportsByScopeFields`.
51
+ * Min..max `localHour` bounds of a list of business days:
52
+ * `{ from: '<first> 00', to: '<last> 23' }`. A bounds utility for key sets —
53
+ * the READ API takes exact values / `$in` lists, never ranges.
55
54
  *
56
55
  * Returns `null` (never throws) for a malformed list.
57
56
  */
@@ -60,11 +59,11 @@ export declare function getMaterializedHourScopeSpan(businessDays: string[]): {
60
59
  to: string;
61
60
  } | null;
62
61
  /**
63
- * Inclusive min..max span of exact non-hour scope values — the fetch range
64
- * for discrete selections (all non-hour scope fields are fixed-width, so
65
- * lexicographic order equals chronological order). Returns `null` (never
66
- * throws) for the hour scope (use `getMaterializedHourScopeSpan`) or a
67
- * malformed list.
62
+ * Inclusive min..max bounds of exact non-hour scope values (all non-hour
63
+ * scope fields are fixed-width, so lexicographic order equals chronological
64
+ * order). A bounds utility for key sets — the READ API takes exact values /
65
+ * `$in` lists, never ranges. Returns `null` (never throws) for the hour
66
+ * scope or a malformed list.
68
67
  */
69
68
  export declare function getMaterializedScopeSpan(scope_context: MATERIALIZED_REPORT_SCOPE_ENUM, scopeFields: string[]): {
70
69
  from: string;
@@ -72,8 +71,38 @@ export declare function getMaterializedScopeSpan(scope_context: MATERIALIZED_REP
72
71
  } | null;
73
72
  /**
74
73
  * Keeps only the documents whose `scope_field` is one of the requested keys —
75
- * the client-side refinement for discrete selections fetched as a span.
76
- * Returns `null` (never throws) for malformed input; unknown keys simply match
74
+ * a client-side refinement utility for arbitrary document sets (the read API
75
+ * returns exactly the requested values, so it needs no refinement). Returns
76
+ * `null` (never throws) for malformed input; unknown keys simply match
77
77
  * nothing (absence = zero).
78
78
  */
79
79
  export declare function filterMaterializedTenantSalesOverviewReportsByScopeFields(docs: IMaterializedTenantSalesOverviewReport[], scopeFields: string[]): IMaterializedTenantSalesOverviewReport[] | null;
80
+ /**
81
+ * Builds the canonical body of a materialized reports READ call —
82
+ * `{ tenants, scope_groups }`, the shared shape of every report endpoint.
83
+ *
84
+ * Normalization (invalid input → `null`, never throws):
85
+ * - tenants are trimmed + deduped (whitespace-only tenants are rejected);
86
+ * - each group's `scope_context` is RESOLVED to its server default
87
+ * (`localDate`) BEFORE bucketing, so an omitted context and an explicit
88
+ * `localDate` group merge into ONE — never two semantically identical
89
+ * groups (the backend merges branch rows with `$sum`, so overlapping
90
+ * groups would double-count every shared document);
91
+ * - values are trimmed + deduped + sorted (lexicographic order is
92
+ * chronological for the fixed-width period formats; hour labels are
93
+ * `$in`-matched, so their order is cosmetic only);
94
+ * - groups with the same context are merged (values unioned); every emitted
95
+ * group carries an explicit `scope_context`.
96
+ *
97
+ * The body carries NO response-mode switch: every read is answered with
98
+ * the aggregated record(s). Per group, `scope_field.length` only picks the
99
+ * backend's query strategy (a single value → direct equality; multiple →
100
+ * `$in`).
101
+ *
102
+ * Returns `null` (never throws) for invalid input — `null` means the caller
103
+ * passed invalid data.
104
+ */
105
+ export declare function buildMaterializedReportReadBody(input: {
106
+ tenants: string[];
107
+ groups: IGetMaterializedReportScopeGroup[];
108
+ }): IGetMaterializedReportBody | null;
@@ -5,21 +5,23 @@ exports.getMaterializedHourWindowScopeFields = getMaterializedHourWindowScopeFie
5
5
  exports.getMaterializedHourScopeSpan = getMaterializedHourScopeSpan;
6
6
  exports.getMaterializedScopeSpan = getMaterializedScopeSpan;
7
7
  exports.filterMaterializedTenantSalesOverviewReportsByScopeFields = filterMaterializedTenantSalesOverviewReportsByScopeFields;
8
+ exports.buildMaterializedReportReadBody = buildMaterializedReportReadBody;
8
9
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
9
10
  const scope_helpers_1 = require("./scope-helpers");
10
11
  /**
11
12
  * Read-side helpers for materialized-report documents — the frontend-facing
12
13
  * half of the query story (see `MATERIALIZED_REPORTS.md` "Time scopes").
13
14
  *
14
- * The ops-service read API takes `{ scope_context, scope_field | from/to }`:
15
- * - contiguous selections go through `from`/`to` directly (callers can use
16
- * `getMaterializedScopeSpan` / `getMaterializedHourScopeSpan` to derive the
17
- * span of a set of keys);
18
- * - discrete selections fetch the min..max SPAN and keep the exact keys with
19
- * `filterMaterializedTenantSalesOverviewReportsByScopeFields`;
15
+ * The ops-service read API takes `{ scope_context, scope_field }` where
16
+ * `scope_field` is an EXACT value or an `$in` list of exact values — the
17
+ * request itself never carries ranges:
18
+ * - every selection (contiguous periods, discrete picks, hour windows,
19
+ * weekday filters) is compiled by the caller into the exact value list it
20
+ * wants;
20
21
  * - recurring hour windows (e.g. 6–8pm on every day of a range) expand to the
21
- * exact hour labels with `getMaterializedHourWindowScopeFields` (span-fetch
22
- * the full days first, then filter to the labels).
22
+ * exact hour labels with `getMaterializedHourWindowScopeFields`;
23
+ * - `getMaterializedScopeSpan` / `getMaterializedHourScopeSpan` remain as
24
+ * min..max bounds utilities for key sets (not part of the read path).
23
25
  *
24
26
  * Validation convention: helpers return `null` instead of throwing — `null`
25
27
  * means the caller passed invalid data.
@@ -101,12 +103,9 @@ function getMaterializedHourWindowScopeFields(businessDays, fromHour, toHour) {
101
103
  return labels;
102
104
  }
103
105
  /**
104
- * Full-day span of a list of business days for `localHour` reads: the
105
- * inclusive `{ from: '<first> 00', to: '<last> 23' }` range covers ALL 24
106
- * hour buckets of every label day in between (a label day's buckets are
107
- * `'D 00'`…`'D 23'`, spanning the post-midnight hours too). Filter the
108
- * fetched documents afterwards with `getMaterializedHourWindowScopeFields` /
109
- * `filterMaterializedTenantSalesOverviewReportsByScopeFields`.
106
+ * Min..max `localHour` bounds of a list of business days:
107
+ * `{ from: '<first> 00', to: '<last> 23' }`. A bounds utility for key sets —
108
+ * the READ API takes exact values / `$in` lists, never ranges.
110
109
  *
111
110
  * Returns `null` (never throws) for a malformed list.
112
111
  */
@@ -123,11 +122,11 @@ function getMaterializedHourScopeSpan(businessDays) {
123
122
  return { from: `${sorted[0]} 00`, to: `${sorted[sorted.length - 1]} 23` };
124
123
  }
125
124
  /**
126
- * Inclusive min..max span of exact non-hour scope values — the fetch range
127
- * for discrete selections (all non-hour scope fields are fixed-width, so
128
- * lexicographic order equals chronological order). Returns `null` (never
129
- * throws) for the hour scope (use `getMaterializedHourScopeSpan`) or a
130
- * malformed list.
125
+ * Inclusive min..max bounds of exact non-hour scope values (all non-hour
126
+ * scope fields are fixed-width, so lexicographic order equals chronological
127
+ * order). A bounds utility for key sets — the READ API takes exact values /
128
+ * `$in` lists, never ranges. Returns `null` (never throws) for the hour
129
+ * scope or a malformed list.
131
130
  */
132
131
  function getMaterializedScopeSpan(scope_context, scopeFields) {
133
132
  if (scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
@@ -146,8 +145,9 @@ function getMaterializedScopeSpan(scope_context, scopeFields) {
146
145
  }
147
146
  /**
148
147
  * Keeps only the documents whose `scope_field` is one of the requested keys —
149
- * the client-side refinement for discrete selections fetched as a span.
150
- * Returns `null` (never throws) for malformed input; unknown keys simply match
148
+ * a client-side refinement utility for arbitrary document sets (the read API
149
+ * returns exactly the requested values, so it needs no refinement). Returns
150
+ * `null` (never throws) for malformed input; unknown keys simply match
151
151
  * nothing (absence = zero).
152
152
  */
153
153
  function filterMaterializedTenantSalesOverviewReportsByScopeFields(docs, scopeFields) {
@@ -157,3 +157,78 @@ function filterMaterializedTenantSalesOverviewReportsByScopeFields(docs, scopeFi
157
157
  const wanted = new Set(scopeFields);
158
158
  return docs.filter((doc) => doc != null && wanted.has(doc.scope_field));
159
159
  }
160
+ /**
161
+ * Builds the canonical body of a materialized reports READ call —
162
+ * `{ tenants, scope_groups }`, the shared shape of every report endpoint.
163
+ *
164
+ * Normalization (invalid input → `null`, never throws):
165
+ * - tenants are trimmed + deduped (whitespace-only tenants are rejected);
166
+ * - each group's `scope_context` is RESOLVED to its server default
167
+ * (`localDate`) BEFORE bucketing, so an omitted context and an explicit
168
+ * `localDate` group merge into ONE — never two semantically identical
169
+ * groups (the backend merges branch rows with `$sum`, so overlapping
170
+ * groups would double-count every shared document);
171
+ * - values are trimmed + deduped + sorted (lexicographic order is
172
+ * chronological for the fixed-width period formats; hour labels are
173
+ * `$in`-matched, so their order is cosmetic only);
174
+ * - groups with the same context are merged (values unioned); every emitted
175
+ * group carries an explicit `scope_context`.
176
+ *
177
+ * The body carries NO response-mode switch: every read is answered with
178
+ * the aggregated record(s). Per group, `scope_field.length` only picks the
179
+ * backend's query strategy (a single value → direct equality; multiple →
180
+ * `$in`).
181
+ *
182
+ * Returns `null` (never throws) for invalid input — `null` means the caller
183
+ * passed invalid data.
184
+ */
185
+ function buildMaterializedReportReadBody(input) {
186
+ if (input == null)
187
+ return null;
188
+ const { tenants, groups } = input;
189
+ if (!Array.isArray(tenants) || tenants.length === 0)
190
+ return null;
191
+ if (tenants.some((tenantId) => typeof tenantId !== 'string' || tenantId.trim() === '')) {
192
+ return null;
193
+ }
194
+ if (!Array.isArray(groups) || groups.length === 0)
195
+ return null;
196
+ const buckets = new Map();
197
+ for (const group of groups) {
198
+ if (group == null || !Array.isArray(group.scope_field) || group.scope_field.length === 0)
199
+ return null;
200
+ const { scope_context } = group;
201
+ if (scope_context != null && !MATERIALIZED_REPORTS_1.ALL_MATERIALIZED_REPORT_SCOPES.includes(scope_context))
202
+ return null;
203
+ // Resolve the context default BEFORE bucketing — an omitted context IS
204
+ // `localDate` (the server default), so it must merge with an explicit
205
+ // `localDate` group instead of surviving as a second, overlapping group.
206
+ const context = scope_context ?? MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE;
207
+ let values = buckets.get(context);
208
+ if (values == null) {
209
+ values = new Set();
210
+ buckets.set(context, values);
211
+ }
212
+ for (const field of group.scope_field) {
213
+ if (typeof field !== 'string')
214
+ return null;
215
+ const trimmed = field.trim();
216
+ if (trimmed === '')
217
+ return null;
218
+ values.add(trimmed);
219
+ }
220
+ }
221
+ const scope_groups = [];
222
+ for (const [scope_context, values] of buckets) {
223
+ const scope_field = [...values].sort();
224
+ if (scope_field.length === 0)
225
+ continue;
226
+ scope_groups.push({ scope_context, scope_field });
227
+ }
228
+ if (scope_groups.length === 0)
229
+ return null;
230
+ return {
231
+ tenants: Array.from(new Set(tenants.map((tenantId) => tenantId.trim()))),
232
+ scope_groups,
233
+ };
234
+ }
@@ -0,0 +1,58 @@
1
+ import { IGetMaterializedReportScopeGroup } from '../types/materialized-reports-apis';
2
+ /**
3
+ * Smart scope-group compiler for materialized-report reads — turns a
4
+ * selection into the FEWEST exact-scope groups the read needs
5
+ * (`IGetMaterializedReportScopeGroup[]`, the `scope_groups` body field):
6
+ *
7
+ * - **compaction**: a contiguous day set is folded into the largest EXACT
8
+ * periods (year → semester → quarter → month → week) before falling back
9
+ * to `localDate` values — e.g. Sep 1–30 becomes ONE `localMonth: ['2026-09']`
10
+ * instead of 30 day values (one document instead of 30);
11
+ * - **recurring window**: the same hours on every selected day → a single
12
+ * `localHour` group (the dedicated time-of-day-window read);
13
+ * - **span window**: from `x:00` on the first day CONTINUOUSLY through
14
+ * `y:00` on the last day — boundary days carry only their partial hour
15
+ * labels (business-day continuous: the start day runs to its 06:00
16
+ * boundary including the post-midnight tail, the end day starts at 06:00),
17
+ * the full days in between compact through the same period logic. What the
18
+ * span does NOT read (absent documents) counts as zero, and groups NEVER
19
+ * overlap — the backend simply unions them.
20
+ *
21
+ * `compactMaterializedReportDayKeys` is exported for direct testing.
22
+ *
23
+ * Returns `null` (never throws) for malformed input — `null` means the
24
+ * caller passed invalid data.
25
+ */
26
+ /** Window refinement kinds (see the module docblock). */
27
+ export declare const MATERIALIZED_REPORT_WINDOW_KIND: {
28
+ readonly RECURRING: "RECURRING";
29
+ readonly SPAN: "SPAN";
30
+ };
31
+ export type TMaterializedReportWindowKind = (typeof MATERIALIZED_REPORT_WINDOW_KIND)[keyof typeof MATERIALIZED_REPORT_WINDOW_KIND];
32
+ export interface IMaterializedReportScopeSelectionSpec {
33
+ /**
34
+ * Effective business-day keys ('YYYY-MM-DD'), sorted or not — deduped
35
+ * here. A SPAN window reads the CONTINUOUS interval first-day →
36
+ * last-day: non-contiguous days would silently read the gap days as
37
+ * full middle days, so a gapped set returns `null`.
38
+ */
39
+ days: string[];
40
+ /** Optional hour window refinement. `toHour` is end-EXCLUSIVE (0 = midnight). */
41
+ window?: {
42
+ fromHour: number;
43
+ toHour: number;
44
+ kind: TMaterializedReportWindowKind;
45
+ } | null;
46
+ }
47
+ /**
48
+ * Folds a contiguous day set into the largest EXACT periods (year →
49
+ * semester → quarter → month → week) + `localDate` leftovers — never
50
+ * partial coverage: a period compacts only when the WHOLE period is inside
51
+ * a contiguous run. Returns `null` for malformed/empty input.
52
+ */
53
+ export declare function compactMaterializedReportDayKeys(days: string[]): IGetMaterializedReportScopeGroup[] | null;
54
+ /**
55
+ * Builds the read's scope groups from a selection spec (see the module
56
+ * docblock). Returns `null` for malformed input or an unservable window.
57
+ */
58
+ export declare function buildMaterializedReportScopeGroups(spec: IMaterializedReportScopeSelectionSpec): IGetMaterializedReportScopeGroup[] | null;