@managesome/eposmatic-toolkit 0.3.11 → 0.4.1

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 (71) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +105 -0
  2. package/esm/constants/index.js +1 -0
  3. package/esm/helpers/index.js +1 -0
  4. package/esm/helpers/materialized-reports/index.js +5 -0
  5. package/esm/helpers/materialized-reports/key-helpers.js +59 -0
  6. package/esm/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +60 -0
  7. package/esm/helpers/materialized-reports/scope-helpers.js +107 -0
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +251 -0
  9. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +860 -0
  10. package/esm/schemas/models/index.js +2 -0
  11. package/esm/schemas/models/materialized_tenant_reports_iterations.js +82 -0
  12. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +399 -0
  13. package/esm/schemas/types/index.js +2 -0
  14. package/esm/schemas/types/materialized_tenant_reports_iterations.js +1 -0
  15. package/esm/schemas/types/materialized_tenant_sales_overview_reports.js +1 -0
  16. package/lib/constants/MATERIALIZED_REPORTS.d.ts +96 -0
  17. package/lib/constants/MATERIALIZED_REPORTS.js +108 -0
  18. package/lib/constants/index.d.ts +1 -0
  19. package/lib/constants/index.js +1 -0
  20. package/lib/helpers/index.d.ts +1 -0
  21. package/lib/helpers/index.js +1 -0
  22. package/lib/helpers/materialized-reports/index.d.ts +5 -0
  23. package/lib/helpers/materialized-reports/index.js +21 -0
  24. package/lib/helpers/materialized-reports/key-helpers.d.ts +35 -0
  25. package/lib/helpers/materialized-reports/key-helpers.js +64 -0
  26. package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.d.ts +66 -0
  27. package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +63 -0
  28. package/lib/helpers/materialized-reports/scope-helpers.d.ts +57 -0
  29. package/lib/helpers/materialized-reports/scope-helpers.js +114 -0
  30. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +125 -0
  31. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +256 -0
  32. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +223 -0
  33. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +875 -0
  34. package/lib/schemas/models/index.d.ts +2 -0
  35. package/lib/schemas/models/index.js +2 -0
  36. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +80 -0
  37. package/lib/schemas/models/materialized_tenant_reports_iterations.js +85 -0
  38. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +569 -0
  39. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +402 -0
  40. package/lib/schemas/models/orders.d.ts +24 -24
  41. package/lib/schemas/models/tenant_active_jobs.d.ts +3 -3
  42. package/lib/schemas/models/tenant_calendar.d.ts +3 -3
  43. package/lib/schemas/models/tenant_cash_drawer_sessions.d.ts +24 -24
  44. package/lib/schemas/models/tenant_cash_in_out.d.ts +24 -24
  45. package/lib/schemas/models/tenant_day_sessions.d.ts +24 -24
  46. package/lib/schemas/models/tenant_instore_shift_sessions.d.ts +24 -24
  47. package/lib/schemas/types/index.d.ts +2 -0
  48. package/lib/schemas/types/index.js +2 -0
  49. package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +62 -0
  50. package/lib/schemas/types/materialized_tenant_reports_iterations.js +2 -0
  51. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +242 -0
  52. package/lib/schemas/types/materialized_tenant_sales_overview_reports.js +3 -0
  53. package/lib/tests/materialized-reports/fixtures.d.ts +81 -0
  54. package/lib/tests/materialized-reports/fixtures.js +87 -0
  55. package/lib/tests/materialized-reports/fixtures.test.d.ts +1 -0
  56. package/lib/tests/materialized-reports/fixtures.test.js +123 -0
  57. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.d.ts +1 -0
  58. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.js +75 -0
  59. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.d.ts +1 -0
  60. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +73 -0
  61. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.d.ts +1 -0
  62. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +207 -0
  63. package/lib/tests/materialized-reports/sales-overview-baseline.test.d.ts +1 -0
  64. package/lib/tests/materialized-reports/sales-overview-baseline.test.js +326 -0
  65. package/lib/tests/materialized-reports/sales-overview-reference.d.ts +63 -0
  66. package/lib/tests/materialized-reports/sales-overview-reference.js +131 -0
  67. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.d.ts +1 -0
  68. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +335 -0
  69. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.d.ts +1 -0
  70. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +885 -0
  71. package/package.json +5 -2
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ /**
3
+ * Constants for the `materialized_*` report collections (see
4
+ * `MATERIALIZED_REPORTS.md`).
5
+ *
6
+ * NOTE: during the current development phase the materialized-report files
7
+ * stay self-contained — this file is NOT (yet) re-exported from
8
+ * `src/constants/index.ts`; the report schema/type files import it via
9
+ * relative paths. Wiring re-exports into the barrels is a separate,
10
+ * explicitly-enabled step.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.ALL_MATERIALIZED_REPORT_TYPES = exports.MATERIALIZED_REPORT_TYPE_ENUM = exports.MATERIALIZED_CREDIT_SETTLEMENT_PAYMENT_TYPE = exports.SALES_OVERVIEW_KEY_FILTERS = exports.ALL_MATERIALIZED_REPORT_KEY_FILTERS = exports.MATERIALIZED_REPORT_KEY_FILTER_ENUM = exports.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX = exports.ALL_MATERIALIZED_REPORT_SCOPES = exports.MATERIALIZED_REPORT_SCOPE_ENUM = void 0;
14
+ /**
15
+ * Time-scope of a materialized report document. Every document covers exactly
16
+ * one tenant × one scope context × one scope value (`scope_field`), and the
17
+ * same scope set is shared by every materialized report collection.
18
+ *
19
+ * `scope_field` formats (all strings), derived from the existing toolkit time
20
+ * helpers (`getLocalDocumentFields`, `getIsoWeekOfYear`, `getCalendarWeekStart`)
21
+ * for the order's business day (`order.localDate`) — hours use the PUNCH hour
22
+ * for sales and the SETTLEMENT hour for credit-bill collections:
23
+ * - `LOCAL_HOUR`: 'YYYY-MM-DD HH' — e.g. '2026-09-15 18' (one hour of one day)
24
+ * - `LOCAL_DATE`: 'YYYY-MM-DD' — e.g. '2026-09-15'
25
+ * - `LOCAL_WEEK`: 'YYYY-MM-DD' — week start (Sun–Sat, the calendar UI's
26
+ * convention: `getCalendarWeekStart(date, 0)`)
27
+ * - `LOCAL_WEEK_OF_YEAR`: 'YYYY-Wnn' — ISO week (`getIsoWeekOfYear`); `YYYY` is the
28
+ * ISO week-year for boundary weeks
29
+ * - `LOCAL_MONTH`: 'YYYY-MM' — e.g. '2026-09'
30
+ * - `LOCAL_QUARTER`: 'YYYY-Qn' — e.g. '2026-Q3'
31
+ * - `LOCAL_SEMESTER`: 'YYYY-Sn' — e.g. '2026-S2'
32
+ * - `LOCAL_YEAR`: 'YYYY' — e.g. '2026'
33
+ *
34
+ * `DAY_INDEX` is intentionally NOT a scope: a weekday accumulator has no time
35
+ * anchor — it cannot honor date-range filters and would grow forever. Instead,
36
+ * `LOCAL_HOUR` and `LOCAL_DATE` documents carry a denormalized `day_index`
37
+ * field (`DAY_INDEX_ENUM`) so weekday filtering/grouping is a plain query over
38
+ * the date/hour slices (see `MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX`).
39
+ *
40
+ * The day-end materialization job compiles the tenant's day into the report
41
+ * collections: up to 24 `LOCAL_HOUR` documents plus one document for each
42
+ * other scope (31 per tenant-day; the longer-period documents accumulate until
43
+ * their period ends). Changing scope values or their formats requires a
44
+ * `schema_version` bump and re-materialization of history.
45
+ */
46
+ var MATERIALIZED_REPORT_SCOPE_ENUM;
47
+ (function (MATERIALIZED_REPORT_SCOPE_ENUM) {
48
+ MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_HOUR"] = "localHour";
49
+ MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_DATE"] = "localDate";
50
+ MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_WEEK"] = "localWeek";
51
+ MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_WEEK_OF_YEAR"] = "localWeekOfYear";
52
+ MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_MONTH"] = "localMonth";
53
+ MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_QUARTER"] = "localQuarter";
54
+ MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_SEMESTER"] = "localSemester";
55
+ MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_YEAR"] = "localYear";
56
+ })(MATERIALIZED_REPORT_SCOPE_ENUM || (exports.MATERIALIZED_REPORT_SCOPE_ENUM = MATERIALIZED_REPORT_SCOPE_ENUM = {}));
57
+ exports.ALL_MATERIALIZED_REPORT_SCOPES = Object.values(MATERIALIZED_REPORT_SCOPE_ENUM);
58
+ /**
59
+ * Scopes whose documents carry the denormalized `day_index` weekday field
60
+ * (derived from `scope_field` by the materializer, `DAY_INDEX_ENUM`). All
61
+ * other scopes must leave it `null` — weekday analysis reads date/hour slices
62
+ * (`LOCAL_HOUR` / `LOCAL_DATE`) instead of an all-time accumulator document.
63
+ */
64
+ exports.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX = [
65
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
66
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
67
+ ];
68
+ /**
69
+ * Filter dimensions that can be encoded into the metric keys of a materialized
70
+ * report document (`sale_type_metrics`). The declaration order defines the key
71
+ * grammar: `<DIM_1>:<DIM_2>:...` built from raw enum/live string values
72
+ * (e.g. `PLACED:POS_WALK-IN`). Changing the dimensions or their order requires
73
+ * a `schema_version` bump and re-materialization of historical documents.
74
+ */
75
+ var MATERIALIZED_REPORT_KEY_FILTER_ENUM;
76
+ (function (MATERIALIZED_REPORT_KEY_FILTER_ENUM) {
77
+ MATERIALIZED_REPORT_KEY_FILTER_ENUM["ORDER_STATUS"] = "ORDER_STATUS";
78
+ MATERIALIZED_REPORT_KEY_FILTER_ENUM["PLATFORM"] = "PLATFORM";
79
+ })(MATERIALIZED_REPORT_KEY_FILTER_ENUM || (exports.MATERIALIZED_REPORT_KEY_FILTER_ENUM = MATERIALIZED_REPORT_KEY_FILTER_ENUM = {}));
80
+ exports.ALL_MATERIALIZED_REPORT_KEY_FILTERS = Object.values(MATERIALIZED_REPORT_KEY_FILTER_ENUM);
81
+ /** Ordered key filters of the tenant sales overview report (`PLACED:POS_WALK-IN`). */
82
+ exports.SALES_OVERVIEW_KEY_FILTERS = [
83
+ MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS,
84
+ MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM,
85
+ ];
86
+ /**
87
+ * Payment-type label used by the frontend report formatter for the derived
88
+ * credit-settlement line in a collection day's payments breakdown (a
89
+ * `PAY_LATER` bill collected on a later day). NOT stored in materialized docs —
90
+ * the formatter composes the line from the `CREDIT_BILLS` ledger's `received`
91
+ * bucket. The line is excluded from method buckets (CASH/CARD/…) and never
92
+ * feeds gross: gross stays sales-only, so cross-day gross sums stay equal to
93
+ * total sales.
94
+ */
95
+ exports.MATERIALIZED_CREDIT_SETTLEMENT_PAYMENT_TYPE = 'CREDIT_SETTLEMENT';
96
+ /**
97
+ * Materialized report kinds — the discriminator stored on
98
+ * `materialized_tenant_reports_iterations` rows. A single shared history collection records
99
+ * the structural iterations of EVERY materialized report, so each row must
100
+ * declare which report collection its `report_id` belongs to. Add one member
101
+ * per new report collection (Summary / X / Z / Riders / Items / Void Items …)
102
+ * as it lands.
103
+ */
104
+ var MATERIALIZED_REPORT_TYPE_ENUM;
105
+ (function (MATERIALIZED_REPORT_TYPE_ENUM) {
106
+ MATERIALIZED_REPORT_TYPE_ENUM["TENANT_SALES_OVERVIEW"] = "TENANT_SALES_OVERVIEW";
107
+ })(MATERIALIZED_REPORT_TYPE_ENUM || (exports.MATERIALIZED_REPORT_TYPE_ENUM = MATERIALIZED_REPORT_TYPE_ENUM = {}));
108
+ exports.ALL_MATERIALIZED_REPORT_TYPES = Object.values(MATERIALIZED_REPORT_TYPE_ENUM);
@@ -7,6 +7,7 @@ export * from './ENUMS';
7
7
  export * from './FBR_ENUMS';
8
8
  export * from './HUBRISE_ENUMS';
9
9
  export * from './INTERNAL_ENUMS';
10
+ export * from './MATERIALIZED_REPORTS';
10
11
  export * from './NOTIFICATIONS';
11
12
  export * from './ORDER';
12
13
  export * from './PRA_ENUMS';
@@ -23,6 +23,7 @@ __exportStar(require("./ENUMS"), exports);
23
23
  __exportStar(require("./FBR_ENUMS"), exports);
24
24
  __exportStar(require("./HUBRISE_ENUMS"), exports);
25
25
  __exportStar(require("./INTERNAL_ENUMS"), exports);
26
+ __exportStar(require("./MATERIALIZED_REPORTS"), exports);
26
27
  __exportStar(require("./NOTIFICATIONS"), exports);
27
28
  __exportStar(require("./ORDER"), exports);
28
29
  __exportStar(require("./PRA_ENUMS"), exports);
@@ -1,6 +1,7 @@
1
1
  export * from './fbr';
2
2
  export * from './hubrise';
3
3
  export * from './kpra';
4
+ export * from './materialized-reports';
4
5
  export * from './order';
5
6
  export * from './pra';
6
7
  export * from './srb';
@@ -17,6 +17,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./fbr"), exports);
18
18
  __exportStar(require("./hubrise"), exports);
19
19
  __exportStar(require("./kpra"), exports);
20
+ __exportStar(require("./materialized-reports"), exports);
20
21
  __exportStar(require("./order"), exports);
21
22
  __exportStar(require("./pra"), exports);
22
23
  __exportStar(require("./srb"), exports);
@@ -0,0 +1,5 @@
1
+ export * from './key-helpers';
2
+ export * from './materialized-tenant-reports-iterations-helpers';
3
+ export * from './scope-helpers';
4
+ export * from './tenant-sales-overview-close-day-helpers';
5
+ export * from './tenant-sales-overview-helpers';
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./key-helpers"), exports);
18
+ __exportStar(require("./materialized-tenant-reports-iterations-helpers"), exports);
19
+ __exportStar(require("./scope-helpers"), exports);
20
+ __exportStar(require("./tenant-sales-overview-close-day-helpers"), exports);
21
+ __exportStar(require("./tenant-sales-overview-helpers"), exports);
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Shared key grammar for materialized-report documents (see
3
+ * `MATERIALIZED_REPORTS.md`).
4
+ *
5
+ * Every `sale_type_metrics` key is the ordered join of the document's
6
+ * `sale_type_key_filters` values (the key dimensions), e.g.
7
+ * `"COMPLETED:POS_TAKE-AWAY"` for `[ORDER_STATUS, PLATFORM]`. The grammar must
8
+ * live in exactly one place — readers and writers must never build or parse
9
+ * keys ad hoc.
10
+ *
11
+ * Reserved characters: the separator `":"` plus Mongo field-name hazards
12
+ * (`"."`, `"$"`) — map keys are stored as document field names, so components
13
+ * containing them are rejected at build time.
14
+ */
15
+ /** Delimiter between key components. */
16
+ export declare const MATERIALIZED_REPORT_KEY_SEPARATOR = ":";
17
+ /**
18
+ * Builds a `sale_type_metrics` key from its ordered components
19
+ * (`buildMaterializedReportKey(['COMPLETED', 'POS_TAKE-AWAY'])` →
20
+ * `"COMPLETED:POS_TAKE-AWAY"`).
21
+ *
22
+ * Returns `null` (never throws) when a component is missing, non-string or
23
+ * contains a reserved character — `null` means the source data is invalid and
24
+ * the caller must treat it as a data issue.
25
+ */
26
+ export declare function buildMaterializedReportKey(components: string[]): string | null;
27
+ /**
28
+ * Parses a `sale_type_metrics` key back into its ordered components —
29
+ * `"COMPLETED:POS_TAKE-AWAY"` → `['COMPLETED', 'POS_TAKE-AWAY']`.
30
+ *
31
+ * The caller maps components to dimensions using the document's
32
+ * `sale_type_key_filters` order. Returns `null` (never throws) for empty or
33
+ * malformed keys — `null` means the stored data / input is corrupt.
34
+ */
35
+ export declare function parseMaterializedReportKey(key: string): string[] | null;
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ /**
3
+ * Shared key grammar for materialized-report documents (see
4
+ * `MATERIALIZED_REPORTS.md`).
5
+ *
6
+ * Every `sale_type_metrics` key is the ordered join of the document's
7
+ * `sale_type_key_filters` values (the key dimensions), e.g.
8
+ * `"COMPLETED:POS_TAKE-AWAY"` for `[ORDER_STATUS, PLATFORM]`. The grammar must
9
+ * live in exactly one place — readers and writers must never build or parse
10
+ * keys ad hoc.
11
+ *
12
+ * Reserved characters: the separator `":"` plus Mongo field-name hazards
13
+ * (`"."`, `"$"`) — map keys are stored as document field names, so components
14
+ * containing them are rejected at build time.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.MATERIALIZED_REPORT_KEY_SEPARATOR = void 0;
18
+ exports.buildMaterializedReportKey = buildMaterializedReportKey;
19
+ exports.parseMaterializedReportKey = parseMaterializedReportKey;
20
+ /** Delimiter between key components. */
21
+ exports.MATERIALIZED_REPORT_KEY_SEPARATOR = ':';
22
+ // The separator itself plus Mongo field-name hazards (map keys are document field names).
23
+ const RESERVED_KEY_CHARACTERS = /[:.$]/;
24
+ /**
25
+ * Builds a `sale_type_metrics` key from its ordered components
26
+ * (`buildMaterializedReportKey(['COMPLETED', 'POS_TAKE-AWAY'])` →
27
+ * `"COMPLETED:POS_TAKE-AWAY"`).
28
+ *
29
+ * Returns `null` (never throws) when a component is missing, non-string or
30
+ * contains a reserved character — `null` means the source data is invalid and
31
+ * the caller must treat it as a data issue.
32
+ */
33
+ function buildMaterializedReportKey(components) {
34
+ if (!Array.isArray(components) || components.length === 0) {
35
+ return null;
36
+ }
37
+ for (const component of components) {
38
+ if (typeof component !== 'string' || component.length === 0) {
39
+ return null;
40
+ }
41
+ if (RESERVED_KEY_CHARACTERS.test(component)) {
42
+ return null;
43
+ }
44
+ }
45
+ return components.join(exports.MATERIALIZED_REPORT_KEY_SEPARATOR);
46
+ }
47
+ /**
48
+ * Parses a `sale_type_metrics` key back into its ordered components —
49
+ * `"COMPLETED:POS_TAKE-AWAY"` → `['COMPLETED', 'POS_TAKE-AWAY']`.
50
+ *
51
+ * The caller maps components to dimensions using the document's
52
+ * `sale_type_key_filters` order. Returns `null` (never throws) for empty or
53
+ * malformed keys — `null` means the stored data / input is corrupt.
54
+ */
55
+ function parseMaterializedReportKey(key) {
56
+ if (typeof key !== 'string' || key.length === 0) {
57
+ return null;
58
+ }
59
+ const components = key.split(exports.MATERIALIZED_REPORT_KEY_SEPARATOR);
60
+ if (components.some((component) => component.length === 0)) {
61
+ return null;
62
+ }
63
+ return components;
64
+ }
@@ -0,0 +1,66 @@
1
+ import { MATERIALIZED_REPORT_TYPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { IMaterializedTenantReportIterationInput } from '../../schemas/types/materialized_tenant_reports_iterations';
3
+ /**
4
+ * Iteration-history helper for `materialized_tenant_reports_iterations` (see
5
+ * `MATERIALIZED_REPORTS.md`, "Iteration history").
6
+ *
7
+ * Every STRUCTURAL write of a materialized report appends one row whose
8
+ * `snapshot` is the full report document AFTER the write:
9
+ *
10
+ * ```ts
11
+ * const updated = updateMaterializedTenantSalesOverviewReport(existing, { replacement });
12
+ * if (updated != null) {
13
+ * const row = buildMaterializedTenantReportIteration(updated, {
14
+ * reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
15
+ * reason: 'NEW_DAY', // backend-generated: why this iteration happened
16
+ * });
17
+ * // await ReportModel.replaceOne({ _id: updated._id }, updated);
18
+ * // await IterationModel.replaceOne(
19
+ * // { report_id: updated._id, iteration: updated.iteration },
20
+ * // row,
21
+ * // { upsert: true },
22
+ * // );
23
+ * }
24
+ * ```
25
+ *
26
+ * Received-payment patches that change the ledger are versioned too (the
27
+ * caller appends their rows the same way); no-op patches write nothing.
28
+ * Helpers never throw — invalid input returns `null`.
29
+ */
30
+ /** Options of `buildMaterializedTenantReportIteration`. */
31
+ export interface IBuildMaterializedTenantReportIterationOptions {
32
+ /** Which report collection the snapshot belongs to (the row's discriminator). */
33
+ reportType: MATERIALIZED_REPORT_TYPE_ENUM;
34
+ /**
35
+ * Why the iteration happened — backend-generated free string, e.g.
36
+ * `NEW_DAY` (first close of a day), `RECLOSE` (day re-run),
37
+ * `RECONCILE` (repair/backfill), `CREDIT_BILL_COLLECTED` (ledger patch).
38
+ * Required — the history must always explain itself.
39
+ */
40
+ reason: string;
41
+ /** Override for `createdAt` / `updatedAt` (tests, replays). */
42
+ computedAt?: Date;
43
+ }
44
+ /**
45
+ * Builds the `materialized_tenant_reports_iterations` row for a report document's current
46
+ * structural iteration — plain JSON, ready to upsert with
47
+ * `replaceOne({ report_id, iteration }, row, { upsert: true })` (`_id` is
48
+ * assigned by MongoDB; replays rewrite the same row idempotently).
49
+ *
50
+ * Documents that never went through an update (no explicit `iteration`, e.g.
51
+ * raw `convertOrdersToMaterializedTenantSalesOverviewReports` output) default
52
+ * to `iteration: 1` — matching the report schema's first-materialization
53
+ * default.
54
+ *
55
+ * `_id` may be a plain string (`.lean()` / JSON) or a mongoose `ObjectId`
56
+ * (hydrated documents) — the row's `report_id` is always the string form.
57
+ *
58
+ * Returns `null` (never throws) when the snapshot lacks `_id` /
59
+ * `schema_version`, carries an invalid `iteration`, or `reportType` is not a
60
+ * known report type.
61
+ */
62
+ export declare function buildMaterializedTenantReportIteration<TReportSnapshot extends {
63
+ _id: string;
64
+ iteration?: number | null;
65
+ schema_version: number;
66
+ }>(snapshot: TReportSnapshot | null | undefined, options: IBuildMaterializedTenantReportIterationOptions): IMaterializedTenantReportIterationInput<TReportSnapshot> | null;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildMaterializedTenantReportIteration = buildMaterializedTenantReportIteration;
4
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
5
+ /**
6
+ * `_id` as the report id string: plain strings pass through; a mongoose
7
+ * `ObjectId` (hydrated documents) stringifies via `toHexString()`.
8
+ */
9
+ const normalizeMaterializedReportId = (value) => {
10
+ if (typeof value === 'string')
11
+ return value.length > 0 ? value : null;
12
+ if (value != null && typeof value.toHexString === 'function') {
13
+ const hex = value.toHexString();
14
+ return typeof hex === 'string' && hex.length > 0 ? hex : null;
15
+ }
16
+ return null;
17
+ };
18
+ /**
19
+ * Builds the `materialized_tenant_reports_iterations` row for a report document's current
20
+ * structural iteration — plain JSON, ready to upsert with
21
+ * `replaceOne({ report_id, iteration }, row, { upsert: true })` (`_id` is
22
+ * assigned by MongoDB; replays rewrite the same row idempotently).
23
+ *
24
+ * Documents that never went through an update (no explicit `iteration`, e.g.
25
+ * raw `convertOrdersToMaterializedTenantSalesOverviewReports` output) default
26
+ * to `iteration: 1` — matching the report schema's first-materialization
27
+ * default.
28
+ *
29
+ * `_id` may be a plain string (`.lean()` / JSON) or a mongoose `ObjectId`
30
+ * (hydrated documents) — the row's `report_id` is always the string form.
31
+ *
32
+ * Returns `null` (never throws) when the snapshot lacks `_id` /
33
+ * `schema_version`, carries an invalid `iteration`, or `reportType` is not a
34
+ * known report type.
35
+ */
36
+ function buildMaterializedTenantReportIteration(snapshot, options) {
37
+ if (snapshot == null || options == null)
38
+ return null;
39
+ if (!MATERIALIZED_REPORTS_1.ALL_MATERIALIZED_REPORT_TYPES.includes(options.reportType))
40
+ return null;
41
+ if (typeof options.reason !== 'string' || options.reason.length === 0)
42
+ return null;
43
+ const { _id, schema_version } = snapshot;
44
+ const reportId = normalizeMaterializedReportId(_id);
45
+ if (reportId == null)
46
+ return null;
47
+ if (typeof schema_version !== 'number' || !Number.isFinite(schema_version))
48
+ return null;
49
+ const iteration = snapshot.iteration ?? 1;
50
+ if (!Number.isInteger(iteration) || iteration < 1)
51
+ return null;
52
+ const computedAt = options.computedAt ?? new Date();
53
+ return {
54
+ report_type: options.reportType,
55
+ report_id: reportId,
56
+ iteration,
57
+ schema_version,
58
+ reason: options.reason,
59
+ snapshot,
60
+ createdAt: computedAt,
61
+ updatedAt: computedAt,
62
+ };
63
+ }
@@ -0,0 +1,57 @@
1
+ import { DAY_INDEX_ENUM } from '../../constants/ENUMS';
2
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
3
+ /** Parsed parts of a `'YYYY-MM-DD'` local date. */
4
+ export interface IMaterializedLocalDateParts {
5
+ year: number;
6
+ month: number;
7
+ day: number;
8
+ }
9
+ /**
10
+ * Parses + validates a `'YYYY-MM-DD'` local date into its numeric parts.
11
+ * Returns `null` (never throws) for malformed dates — `null` means the caller
12
+ * passed invalid data.
13
+ */
14
+ export declare function parseMaterializedLocalDate(localDate: string): IMaterializedLocalDateParts | null;
15
+ /**
16
+ * ISO 8601 week-year of a local date — the year of the Thursday of that date's
17
+ * ISO week. Differs from the calendar year for boundary weeks (e.g.
18
+ * `'2027-01-01'` is `2026-W53`), which is exactly why `'YYYY-Wnn'` scope
19
+ * fields need it. Returns `null` for malformed dates.
20
+ */
21
+ export declare function getIsoWeekYear(localDate: string): number | null;
22
+ /**
23
+ * Denormalized weekday (`DAY_INDEX_ENUM`) of a local date. Returns `null`
24
+ * (never throws) for malformed dates.
25
+ */
26
+ export declare function getDayIndexFromLocalDate(localDate: string): DAY_INDEX_ENUM | null;
27
+ /** `scope_field` of every non-hour scope for one local date. */
28
+ export interface IMaterializedPeriodScopeFields {
29
+ [MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE]: string;
30
+ [MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK]: string;
31
+ [MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR]: string;
32
+ [MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH]: string;
33
+ [MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER]: string;
34
+ [MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER]: string;
35
+ [MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR]: string;
36
+ }
37
+ /**
38
+ * Builds the `scope_field` of every period scope for a compiled local date:
39
+ *
40
+ * - `localDate`: `'2026-09-30'`
41
+ * - `localWeek`: Sun–Sat week start (the calendar UI convention —
42
+ * `getCalendarWeekStart(date, 0)`) → `'2026-09-27'`
43
+ * - `localWeekOfYear`: ISO week `'YYYY-Wnn'` where `YYYY` is the ISO week-year
44
+ * - `localMonth`: `'2026-09'`
45
+ * - `localQuarter`: `'2026-Q3'`
46
+ * - `localSemester`: `'2026-S2'`
47
+ * - `localYear`: `'2026'`
48
+ *
49
+ * Returns `null` (never throws) for malformed dates.
50
+ */
51
+ export declare function getMaterializedPeriodScopeFields(localDate: string): IMaterializedPeriodScopeFields | null;
52
+ /**
53
+ * `scope_field` of a `localHour` bucket — `'2026-09-30 18'` (zero-padded).
54
+ * Returns `null` (never throws) for a malformed local date or an out-of-range
55
+ * hour.
56
+ */
57
+ export declare function getMaterializedHourScopeField(localDate: string, hour: number): string | null;
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseMaterializedLocalDate = parseMaterializedLocalDate;
4
+ exports.getIsoWeekYear = getIsoWeekYear;
5
+ exports.getDayIndexFromLocalDate = getDayIndexFromLocalDate;
6
+ exports.getMaterializedPeriodScopeFields = getMaterializedPeriodScopeFields;
7
+ exports.getMaterializedHourScopeField = getMaterializedHourScopeField;
8
+ const ENUMS_1 = require("../../constants/ENUMS");
9
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
10
+ const time_helpers_1 = require("../utils/time-helpers");
11
+ /**
12
+ * Scope-field builders for materialized-report documents (see
13
+ * `MATERIALIZED_REPORTS.md` "Time scopes"). Given the tenant-local business
14
+ * date (`YYYY-MM-DD`) of a compiled day, these derive the `scope_field` value
15
+ * of every period scope plus the denormalized weekday.
16
+ *
17
+ * All math is pure UTC calendar arithmetic on the date string — independent of
18
+ * the server timezone. The hour scope (`'YYYY-MM-DD HH'`) is built per bucket
19
+ * via `getMaterializedHourScopeField`.
20
+ *
21
+ * Validation convention: builders return `null` instead of throwing — a `null`
22
+ * result means the caller passed invalid data.
23
+ */
24
+ const LOCAL_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
25
+ const pad = (value) => String(value).padStart(2, '0');
26
+ /**
27
+ * Parses + validates a `'YYYY-MM-DD'` local date into its numeric parts.
28
+ * Returns `null` (never throws) for malformed dates — `null` means the caller
29
+ * passed invalid data.
30
+ */
31
+ function parseMaterializedLocalDate(localDate) {
32
+ if (typeof localDate !== 'string' || !LOCAL_DATE_PATTERN.test(localDate)) {
33
+ return null;
34
+ }
35
+ const [year, month, day] = localDate.split('-').map(Number);
36
+ if (month < 1 || month > 12 || day < 1 || day > 31) {
37
+ return null;
38
+ }
39
+ // Real-calendar check: impossible dates (e.g. '2026-02-31') must never slip
40
+ // through — `Date.UTC` rollover would silently derive WRONG scope fields
41
+ // (week/day_index pointing into the next month).
42
+ const utc = new Date(Date.UTC(year, month - 1, day));
43
+ if (utc.getUTCFullYear() !== year || utc.getUTCMonth() !== month - 1 || utc.getUTCDate() !== day) {
44
+ return null;
45
+ }
46
+ return { year, month, day };
47
+ }
48
+ /**
49
+ * ISO 8601 week-year of a local date — the year of the Thursday of that date's
50
+ * ISO week. Differs from the calendar year for boundary weeks (e.g.
51
+ * `'2027-01-01'` is `2026-W53`), which is exactly why `'YYYY-Wnn'` scope
52
+ * fields need it. Returns `null` for malformed dates.
53
+ */
54
+ function getIsoWeekYear(localDate) {
55
+ const parts = parseMaterializedLocalDate(localDate);
56
+ return parts != null ? getIsoWeekYearFromParts(parts) : null;
57
+ }
58
+ function getIsoWeekYearFromParts({ year, month, day }) {
59
+ const date = new Date(Date.UTC(year, month - 1, day));
60
+ const isoWeekday = date.getUTCDay() || 7; // Monday = 1 … Sunday = 7
61
+ date.setUTCDate(date.getUTCDate() + 4 - isoWeekday); // move to the ISO week's Thursday
62
+ return date.getUTCFullYear();
63
+ }
64
+ /**
65
+ * Denormalized weekday (`DAY_INDEX_ENUM`) of a local date. Returns `null`
66
+ * (never throws) for malformed dates.
67
+ */
68
+ function getDayIndexFromLocalDate(localDate) {
69
+ const parts = parseMaterializedLocalDate(localDate);
70
+ if (parts == null)
71
+ return null;
72
+ return ENUMS_1.ALL_DAY_INDEX[new Date(Date.UTC(parts.year, parts.month - 1, parts.day)).getUTCDay()];
73
+ }
74
+ /**
75
+ * Builds the `scope_field` of every period scope for a compiled local date:
76
+ *
77
+ * - `localDate`: `'2026-09-30'`
78
+ * - `localWeek`: Sun–Sat week start (the calendar UI convention —
79
+ * `getCalendarWeekStart(date, 0)`) → `'2026-09-27'`
80
+ * - `localWeekOfYear`: ISO week `'YYYY-Wnn'` where `YYYY` is the ISO week-year
81
+ * - `localMonth`: `'2026-09'`
82
+ * - `localQuarter`: `'2026-Q3'`
83
+ * - `localSemester`: `'2026-S2'`
84
+ * - `localYear`: `'2026'`
85
+ *
86
+ * Returns `null` (never throws) for malformed dates.
87
+ */
88
+ function getMaterializedPeriodScopeFields(localDate) {
89
+ const parts = parseMaterializedLocalDate(localDate);
90
+ if (parts == null)
91
+ return null;
92
+ const { year, month, day } = parts;
93
+ return {
94
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE]: localDate,
95
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK]: (0, time_helpers_1.getCalendarWeekStart)(localDate, 0),
96
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR]: `${getIsoWeekYearFromParts(parts)}-W${pad((0, time_helpers_1.getIsoWeekOfYear)(year, month, day))}`,
97
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH]: `${year}-${pad(month)}`,
98
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER]: `${year}-Q${Math.ceil(month / 3)}`,
99
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER]: `${year}-S${month <= 6 ? 1 : 2}`,
100
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR]: `${year}`,
101
+ };
102
+ }
103
+ /**
104
+ * `scope_field` of a `localHour` bucket — `'2026-09-30 18'` (zero-padded).
105
+ * Returns `null` (never throws) for a malformed local date or an out-of-range
106
+ * hour.
107
+ */
108
+ function getMaterializedHourScopeField(localDate, hour) {
109
+ if (parseMaterializedLocalDate(localDate) == null)
110
+ return null;
111
+ if (!Number.isInteger(hour) || hour < 0 || hour > 23)
112
+ return null;
113
+ return `${localDate} ${pad(hour)}`;
114
+ }