@managesome/eposmatic-toolkit 0.3.11 → 0.4.0

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 (52) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +105 -0
  2. package/esm/helpers/materialized-reports/index.js +5 -0
  3. package/esm/helpers/materialized-reports/key-helpers.js +59 -0
  4. package/esm/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +60 -0
  5. package/esm/helpers/materialized-reports/scope-helpers.js +107 -0
  6. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +251 -0
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +860 -0
  8. package/esm/schemas/models/materialized_tenant_reports_iterations.js +82 -0
  9. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +399 -0
  10. package/esm/schemas/types/materialized_tenant_reports_iterations.js +1 -0
  11. package/esm/schemas/types/materialized_tenant_sales_overview_reports.js +1 -0
  12. package/lib/constants/MATERIALIZED_REPORTS.d.ts +96 -0
  13. package/lib/constants/MATERIALIZED_REPORTS.js +108 -0
  14. package/lib/helpers/materialized-reports/index.d.ts +5 -0
  15. package/lib/helpers/materialized-reports/index.js +21 -0
  16. package/lib/helpers/materialized-reports/key-helpers.d.ts +35 -0
  17. package/lib/helpers/materialized-reports/key-helpers.js +64 -0
  18. package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.d.ts +66 -0
  19. package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +63 -0
  20. package/lib/helpers/materialized-reports/scope-helpers.d.ts +57 -0
  21. package/lib/helpers/materialized-reports/scope-helpers.js +114 -0
  22. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +125 -0
  23. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +256 -0
  24. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +223 -0
  25. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +875 -0
  26. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +80 -0
  27. package/lib/schemas/models/materialized_tenant_reports_iterations.js +85 -0
  28. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +569 -0
  29. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +402 -0
  30. package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +62 -0
  31. package/lib/schemas/types/materialized_tenant_reports_iterations.js +2 -0
  32. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +242 -0
  33. package/lib/schemas/types/materialized_tenant_sales_overview_reports.js +3 -0
  34. package/lib/tests/materialized-reports/fixtures.d.ts +81 -0
  35. package/lib/tests/materialized-reports/fixtures.js +87 -0
  36. package/lib/tests/materialized-reports/fixtures.test.d.ts +1 -0
  37. package/lib/tests/materialized-reports/fixtures.test.js +123 -0
  38. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.d.ts +1 -0
  39. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.js +75 -0
  40. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.d.ts +1 -0
  41. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +73 -0
  42. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.d.ts +1 -0
  43. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +207 -0
  44. package/lib/tests/materialized-reports/sales-overview-baseline.test.d.ts +1 -0
  45. package/lib/tests/materialized-reports/sales-overview-baseline.test.js +326 -0
  46. package/lib/tests/materialized-reports/sales-overview-reference.d.ts +63 -0
  47. package/lib/tests/materialized-reports/sales-overview-reference.js +131 -0
  48. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.d.ts +1 -0
  49. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +335 -0
  50. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.d.ts +1 -0
  51. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +885 -0
  52. package/package.json +5 -2
@@ -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
+ }
@@ -0,0 +1,125 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { IMaterializedTenantReportIterationInput } from '../../schemas/types/materialized_tenant_reports_iterations';
3
+ import { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
4
+ import { IConvertOrdersToMaterializedReportsResult } from './tenant-sales-overview-helpers';
5
+ /**
6
+ * Close-day planning for `materialized_tenant_sales_overview_reports` (see
7
+ * `MATERIALIZED_REPORTS.md` “Backend materialization cycle”).
8
+ *
9
+ * The day-close job compiles one tenant-day (`convertOrdersTo…`), fetches the
10
+ * stored documents the plan needs (`getMaterializedTenantSalesOverviewScopeRefsForDay`
11
+ * + the issue-day docs of collected bills), and asks this module for the
12
+ * complete write plan:
13
+ *
14
+ * - **`writes`** — hour + date documents (insert, or `replacement` when stored
15
+ * so `iteration` bumps without `_id` churn) and the six accumulated period
16
+ * documents (`additions`, or — when the day was previously folded —
17
+ * `subtract` the stored day delta first). Each write carries its
18
+ * `materialized_tenant_reports_iterations` history row; persist both.
19
+ * - **`staleHourDocuments`** — stored `localHour` docs of the day with no
20
+ * 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`.
27
+ * - **`skippedDocuments`** — already up to date (see
28
+ * `needsMaterializedTenantSalesOverviewReportWrite`).
29
+ * - **`createdPeriodDocuments`** — period docs that were absent from
30
+ * `existing` and are created by this close (also present in `writes`): a
31
+ * first materialized close of the period, an order-less prefix, or a
32
+ * genuinely missing document — in the last case the caller must alert and
33
+ * run the documented period backfill (a deleted doc cannot be reconstructed
34
+ * from one day's delta alone).
35
+ *
36
+ * The watermark guard skips nothing when `force` is set (repairs / schema
37
+ * rollouts). Helpers never throw — invalid input returns `null`.
38
+ */
39
+ /** Options of `buildTenantSalesOverviewCloseDayPlan`. */
40
+ export interface IBuildTenantSalesOverviewCloseDayPlanInput {
41
+ /** Tenant the compile belongs to (one plan = one tenant-day). */
42
+ tenantId: string;
43
+ /** The tenant-day compile (`convertOrdersToMaterializedTenantSalesOverviewReports`). */
44
+ compile: IConvertOrdersToMaterializedReportsResult;
45
+ /**
46
+ * Why this close is applied — stored as the `reason` of every history row
47
+ * the plan produces (`NEW_DAY`, `RECLOSE`, `RECONCILE`, …). Required: the
48
+ * iteration history must always explain itself.
49
+ */
50
+ reason: string;
51
+ /**
52
+ * Stored documents the job fetched: the compiled scopes that already exist
53
+ * plus, for every collected bill's `issued_local_date`, that day's stored
54
+ * documents (`getMaterializedTenantSalesOverviewScopeRefsForDay`). Pass
55
+ * plain JSON (`.lean()` recommended — a hydrated document's map-cast
56
+ * `sale_type_metrics` is normalized defensively, but its other mongoose
57
+ * internals are not supported). Repeating the SAME document (overlapping
58
+ * fetch refs) is fine; two different rows for one scope key → `null`.
59
+ */
60
+ existing?: IMaterializedTenantSalesOverviewReport[];
61
+ /** Force structural writes even when the watermarks are up to date. */
62
+ force?: boolean;
63
+ /** Override for write timestamps (tests, replays). */
64
+ computedAt?: Date;
65
+ }
66
+ /** One versioned write (structural write or ledger-changing patch): persist `report` + upsert its history row. */
67
+ export interface ITenantSalesOverviewCloseDayWrite {
68
+ /** Post-write document (stored `_id` kept for replacements). */
69
+ report: IMaterializedTenantSalesOverviewReport;
70
+ /** `materialized_tenant_reports_iterations` row — upsert by `(report_id, iteration)`. */
71
+ iteration: IMaterializedTenantReportIterationInput;
72
+ }
73
+ /** The complete close-day write plan (see the module docs). */
74
+ export interface ITenantSalesOverviewCloseDayPlan {
75
+ /** Structural writes (report + history row) — persist in any order. */
76
+ writes: ITenantSalesOverviewCloseDayWrite[];
77
+ /** Stored hour docs of the compiled day no longer backed by activity — delete by `_id`. */
78
+ staleHourDocuments: IMaterializedTenantSalesOverviewReport[];
79
+ /** Issued-ledger patches (versioned writes) — persist AFTER `writes`. */
80
+ receivedPatches: ITenantSalesOverviewCloseDayWrite[];
81
+ /** Stored docs that were already up to date (job logging). */
82
+ skippedDocuments: IMaterializedTenantSalesOverviewReport[];
83
+ /**
84
+ * Period-scope documents this close CREATED because they were absent from
85
+ * `existing` — a first materialized close of the period (including when
86
+ * earlier days of the period were order-less), or a document that is simply
87
+ * missing. A missing document folds only the closing day's delta: if
88
+ * earlier days of the period were already materialized, run the documented
89
+ * period backfill — a deleted document cannot be reconstructed from one
90
+ * day. These writes are also present in `writes`; alert on a non-empty list
91
+ * when the day is not the period's first materialized close.
92
+ */
93
+ createdPeriodDocuments: IMaterializedReportScopeRef[];
94
+ }
95
+ /** `(scope_context, scope_field)` pair of a stored / compiled document. */
96
+ export interface IMaterializedReportScopeRef {
97
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
98
+ scope_field: string;
99
+ }
100
+ /**
101
+ * Every stored scope the fan-out of one local day needs: the six period
102
+ * scopes + `localDate` of that day and all 24 `localHour` buckets (`null` for
103
+ * a malformed date). A bill's hour is unknowable from the received entry
104
+ * alone, so settlement patches always consider the whole day.
105
+ */
106
+ export declare function getMaterializedTenantSalesOverviewScopeRefsForDay(localDate: string): IMaterializedReportScopeRef[] | null;
107
+ /**
108
+ * Watermark guard of the write path: does the stored document need a
109
+ * structural write for the incoming compiled version?
110
+ *
111
+ * `false` (skip) when the incoming `source_watermark` is not newer than the
112
+ * stored one and the schema version + key-filter grammar match. Watermarks are
113
+ * monotonic (`updateMaterializedTenantSalesOverviewReport` never regresses
114
+ * them). A missing stored document always needs a write.
115
+ */
116
+ export declare function needsMaterializedTenantSalesOverviewReportWrite(existing: IMaterializedTenantSalesOverviewReport | null | undefined, incoming: IMaterializedTenantSalesOverviewReport | null | undefined): boolean;
117
+ /**
118
+ * Builds the close-day write plan for ONE tenant-day (see the module docs).
119
+ * Returns `null` (never throws) when the input is inconsistent — compiled
120
+ * docs of another tenant, duplicate compiled scope documents, a malformed
121
+ * `localDate`, duplicate STORED rows for one scope key (missing unique index
122
+ * — a data issue to fix, never silently deduplicated), or a merge conflict
123
+ * with a stored document (schema / brand).
124
+ */
125
+ export declare function buildTenantSalesOverviewCloseDayPlan(input: IBuildTenantSalesOverviewCloseDayPlanInput | null | undefined): ITenantSalesOverviewCloseDayPlan | null;