@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,81 @@
1
+ /**
2
+ * Loader for the live-store order fixtures used by materialized-report tests.
3
+ *
4
+ * Two datasets are checked into `src/tests/` (one month of live orders each):
5
+ * - `basha-orders.json` — tenant `basha-istanbul-f7`, 2026-09-01 → 2026-09-30
6
+ * - `bruzo-orders.json` — tenant `z2-isb`, 2026-09-01 → 2026-09-30
7
+ *
8
+ * Both files are full order documents (Mongo export shape): dates are ISO
9
+ * strings, `_id`s are hex strings, and `payment_type`/`payment_status` are
10
+ * OPEN strings — live stores contain values that are not in the current
11
+ * toolkit enums (e.g. `CARD_PAYMENT`, `FOODPANDA`, `ONLINE`, `PLAZA`,
12
+ * `GOLOOTLO`, `MARKETING`). Materialization logic must pass unknown payment
13
+ * types through, never enum-validate them.
14
+ *
15
+ * The loader normalizes date strings to `Date` objects for computation and
16
+ * caches parsed datasets per process (the JSON files are 10–18 MB).
17
+ */
18
+ export type OrdersDatasetName = 'basha' | 'bruzo';
19
+ export interface OrdersDatasetInfo {
20
+ /** Fixture file base name, `src/tests/<fileName>`. */
21
+ fileName: string;
22
+ /** Tenant the dataset belongs to (from `orders[].tenant_id`). */
23
+ tenantId: string;
24
+ /** UTC range covered by `createdAt` values (inclusive). */
25
+ createdFrom: string;
26
+ createdTo: string;
27
+ /** Expected number of orders — asserted by dataset sanity tests. */
28
+ orderCount: number;
29
+ /** Tenant GMT offset the enriched local fields are computed with (both stores: +5). */
30
+ gmtOffset: number;
31
+ /** Business-day boundary — 6am–6am days (punches before 06:00 local belong to the previous day). */
32
+ businessDayStartHour: number;
33
+ /** Human-readable note about what this dataset is good for. */
34
+ note: string;
35
+ }
36
+ export declare const ORDERS_DATASETS: Record<OrdersDatasetName, OrdersDatasetInfo>;
37
+ export declare const ALL_ORDERS_DATASET_NAMES: OrdersDatasetName[];
38
+ /** Payment as stored in the fixture JSON (open `payment_type`/`payment_status`). */
39
+ export interface FixturePayment {
40
+ _id?: string;
41
+ payment_type: string;
42
+ payment_status: string;
43
+ amount_due: number;
44
+ amount_paid: number;
45
+ amount_refunded: number;
46
+ card_details?: {
47
+ card_charges?: number;
48
+ } | null;
49
+ }
50
+ /** Order as stored in the fixture JSON (dates are ISO strings). */
51
+ export interface RawFixtureOrder {
52
+ _id: string;
53
+ tenant_id: string;
54
+ platform: string;
55
+ order_status: string;
56
+ createdAt: string;
57
+ order_settled_at: string | null;
58
+ order_settled_at_mins?: number;
59
+ amount_collected: number;
60
+ amount_earned: number;
61
+ deferred_settlement?: boolean;
62
+ is_deleted?: boolean;
63
+ payments?: FixturePayment[];
64
+ /** Enriched ILocalTimeFields (`scripts/enrich-order-fixtures.ts`). */
65
+ localDate?: string;
66
+ localHour?: number;
67
+ day_index?: string;
68
+ }
69
+ /** Fixture order normalized for computation (dates parsed, payments always an array). */
70
+ export interface FixtureOrder extends Omit<RawFixtureOrder, 'createdAt' | 'order_settled_at' | 'payments'> {
71
+ createdAt: Date;
72
+ order_settled_at: Date | null;
73
+ payments: FixturePayment[];
74
+ }
75
+ /** Load a dataset with dates normalized to `Date` objects (cached per process). */
76
+ export declare function loadOrdersDataset(name: OrdersDatasetName): FixtureOrder[];
77
+ /**
78
+ * Load the dataset WITHOUT date normalization — useful when asserting the raw
79
+ * JSON shape (sanity tests) or when a future test wants to re-serialize.
80
+ */
81
+ export declare function loadRawOrdersDatasetForTest(name: OrdersDatasetName): RawFixtureOrder[];
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ALL_ORDERS_DATASET_NAMES = exports.ORDERS_DATASETS = void 0;
7
+ exports.loadOrdersDataset = loadOrdersDataset;
8
+ exports.loadRawOrdersDatasetForTest = loadRawOrdersDatasetForTest;
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const path_1 = __importDefault(require("path"));
11
+ exports.ORDERS_DATASETS = {
12
+ basha: {
13
+ fileName: 'basha-orders.json',
14
+ tenantId: 'basha-istanbul-f7',
15
+ createdFrom: '2026-09-01T07:37:13.237Z',
16
+ createdTo: '2026-09-30T10:48:19.538Z',
17
+ orderCount: 2931,
18
+ gmtOffset: 5,
19
+ businessDayStartHour: 6,
20
+ note: 'Single-platform-dominant store (APP_DINE-IN); card-payment heavy with legacy CARD_PAYMENT ids; UNPAID + COMPLIMENTARY payments. Enriched (scripts/enrich-order-fixtures.ts): ILocalTimeFields on a 6am–6am GMT+5 business day, all 8 order statuses, 8 issued credit bills (`PAY_LATER`/PENDING) and 6 settled-later credit bills (fully paid, `order_settled_at` on a later day).',
21
+ },
22
+ bruzo: {
23
+ fileName: 'bruzo-orders.json',
24
+ tenantId: 'z2-isb',
25
+ createdFrom: '2026-09-01T04:36:43.631Z',
26
+ createdTo: '2026-09-30T10:45:30.592Z',
27
+ orderCount: 2166,
28
+ gmtOffset: 5,
29
+ businessDayStartHour: 6,
30
+ note: 'Multi-platform store (FOODPANDA/POS/APP/WEB); 96 cancelled orders; aggregator + legacy payment types (FOODPANDA, PLAZA, GOLOOTLO, MARKETING, ONLINE, CARD_PAYMENT). Enriched (scripts/enrich-order-fixtures.ts): ILocalTimeFields on a 6am–6am GMT+5 business day, all 8 order statuses, 8 issued credit bills + 6 settled-later credit bills, and 11 orders settling on a later UTC day (5 original + 6 settled-later).',
31
+ },
32
+ };
33
+ exports.ALL_ORDERS_DATASET_NAMES = ['basha', 'bruzo'];
34
+ const cache = new Map();
35
+ const rawCache = new Map();
36
+ /**
37
+ * Resolve a fixture file from either the source tree (`src/tests/...`) or a
38
+ * compiled tree (`lib/tests/materialized-reports/...` — the repo compiles
39
+ * tests, and JSON files are not copied to `lib`, so fall back to the source
40
+ * file relative to the repo root).
41
+ */
42
+ function resolveDataFile(fileName) {
43
+ const candidates = [
44
+ path_1.default.join(__dirname, '..', fileName),
45
+ path_1.default.join(__dirname, '..', '..', '..', 'src', 'tests', fileName),
46
+ path_1.default.join(process.cwd(), 'src', 'tests', fileName),
47
+ ];
48
+ for (const candidate of candidates) {
49
+ if (fs_1.default.existsSync(candidate))
50
+ return candidate;
51
+ }
52
+ throw new Error(`Fixture file "${fileName}" not found. Looked in:\n${candidates.join('\n')}`);
53
+ }
54
+ function loadRawOrdersDataset(name) {
55
+ const cached = rawCache.get(name);
56
+ if (cached)
57
+ return cached;
58
+ const info = exports.ORDERS_DATASETS[name];
59
+ const filePath = resolveDataFile(info.fileName);
60
+ const parsed = JSON.parse(fs_1.default.readFileSync(filePath, 'utf8'));
61
+ if (!Array.isArray(parsed)) {
62
+ throw new Error(`Fixture "${info.fileName}" must contain an array of orders`);
63
+ }
64
+ rawCache.set(name, parsed);
65
+ return parsed;
66
+ }
67
+ /** Load a dataset with dates normalized to `Date` objects (cached per process). */
68
+ function loadOrdersDataset(name) {
69
+ const cached = cache.get(name);
70
+ if (cached)
71
+ return cached;
72
+ const orders = loadRawOrdersDataset(name).map((order) => ({
73
+ ...order,
74
+ createdAt: new Date(order.createdAt),
75
+ order_settled_at: order.order_settled_at != null ? new Date(order.order_settled_at) : null,
76
+ payments: order.payments ?? [],
77
+ }));
78
+ cache.set(name, orders);
79
+ return orders;
80
+ }
81
+ /**
82
+ * Load the dataset WITHOUT date normalization — useful when asserting the raw
83
+ * JSON shape (sanity tests) or when a future test wants to re-serialize.
84
+ */
85
+ function loadRawOrdersDatasetForTest(name) {
86
+ return loadRawOrdersDataset(name);
87
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../../constants");
4
+ const fixtures_1 = require("./fixtures");
5
+ /**
6
+ * Sanity + coverage tests for the live-store order fixtures themselves.
7
+ * If these fail after a fixture change, review `ORDERS_DATASETS` metadata and
8
+ * every pinned baseline in `sales-overview-baseline.test.ts`.
9
+ */
10
+ describe('order fixtures', () => {
11
+ it('loads both datasets with the expected order counts', () => {
12
+ for (const name of fixtures_1.ALL_ORDERS_DATASET_NAMES) {
13
+ const orders = (0, fixtures_1.loadOrdersDataset)(name);
14
+ expect(orders).toHaveLength(fixtures_1.ORDERS_DATASETS[name].orderCount);
15
+ }
16
+ });
17
+ it('normalizes dates to Date objects and keeps payments as arrays', () => {
18
+ for (const name of fixtures_1.ALL_ORDERS_DATASET_NAMES) {
19
+ const { tenantId, createdFrom, createdTo } = fixtures_1.ORDERS_DATASETS[name];
20
+ const orders = (0, fixtures_1.loadOrdersDataset)(name);
21
+ for (const order of orders) {
22
+ expect(order.tenant_id).toBe(tenantId);
23
+ expect(order.createdAt).toBeInstanceOf(Date);
24
+ expect(order.is_deleted).toBe(false);
25
+ expect(Array.isArray(order.payments)).toBe(true);
26
+ // Every fixture order is settled (materialization day-bucketing relies on it).
27
+ expect(order.order_settled_at).toBeInstanceOf(Date);
28
+ }
29
+ const createdTimes = orders.map((o) => o.createdAt.getTime());
30
+ expect(new Date(Math.min(...createdTimes)).toISOString()).toBe(createdFrom);
31
+ expect(new Date(Math.max(...createdTimes)).toISOString()).toBe(createdTo);
32
+ }
33
+ });
34
+ it('keeps raw ISO dates available through the raw loader', () => {
35
+ const raw = (0, fixtures_1.loadRawOrdersDatasetForTest)('basha');
36
+ expect(typeof raw[0].createdAt).toBe('string');
37
+ expect(raw[0].createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
38
+ });
39
+ it('covers the report dimensions the baselines rely on', () => {
40
+ const basha = (0, fixtures_1.loadOrdersDataset)('basha');
41
+ const bruzo = (0, fixtures_1.loadOrdersDataset)('bruzo');
42
+ const platforms = (orders) => new Set(orders.map((o) => o.platform));
43
+ const statuses = (orders) => new Set(orders.map((o) => o.order_status));
44
+ const paymentTypes = (orders) => new Set(orders.flatMap((o) => o.payments.map((p) => p.payment_type)));
45
+ // Every ORDER_STATUS value exists in each dataset (status-filter coverage).
46
+ for (const name of fixtures_1.ALL_ORDERS_DATASET_NAMES) {
47
+ expect(statuses((0, fixtures_1.loadOrdersDataset)(name))).toEqual(new Set(constants_1.ALL_ORDER_STATUS_NAMES));
48
+ }
49
+ // Cancelled orders exist in both stores (required by the CANCELLED facet).
50
+ expect(basha.filter((o) => o.order_status === 'CANCELLED')).toHaveLength(15);
51
+ expect(bruzo.filter((o) => o.order_status === 'CANCELLED')).toHaveLength(96);
52
+ // Platform spread: one dominant platform vs a true multi-platform store,
53
+ // plus the representative "main platform" set across both datasets.
54
+ expect(platforms(basha)).toContain('APP_DINE-IN');
55
+ expect(platforms(bruzo)).toContain('FOODPANDA_TAKE-AWAY');
56
+ const mainPlatforms = [
57
+ 'APP_DINE-IN',
58
+ 'APP_DELIVERY',
59
+ 'APP_TAKE-AWAY',
60
+ 'POS_WALK-IN',
61
+ 'POS_TAKE-AWAY',
62
+ 'POS_DINE-IN',
63
+ 'POS_DELIVERY',
64
+ 'POS_DRIVE-THRU',
65
+ 'POS_KIOSK',
66
+ 'WEB_TAKE-AWAY',
67
+ 'WEB_DELIVERY',
68
+ 'WEB_DINE-IN',
69
+ 'FOODPANDA_TAKE-AWAY',
70
+ 'FOODPANDA_DELIVERY',
71
+ 'TALABAT_DELIVERY',
72
+ 'UBER-EATS_DELIVERY',
73
+ ];
74
+ const allPlatforms = new Set([...platforms(basha), ...platforms(bruzo)]);
75
+ for (const platform of mainPlatforms)
76
+ expect(allPlatforms).toContain(platform);
77
+ // Live stores contain payment types that are NOT in PAYMENT_TYPE_ENUM —
78
+ // these must pass through reporting untouched.
79
+ expect(paymentTypes(basha)).toContain('CARD_PAYMENT');
80
+ for (const legacy of ['CARD_PAYMENT', 'FOODPANDA', 'ONLINE', 'PLAZA', 'GOLOOTLO', 'MARKETING']) {
81
+ expect(paymentTypes(bruzo)).toContain(legacy);
82
+ }
83
+ // Credit bills per store: 8 issued (`PAY_LATER`/PENDING + deferred tag)
84
+ // and 6 settled later (fully paid, `order_settled_at` on a later day).
85
+ for (const orders of [basha, bruzo]) {
86
+ expect(orders.filter((o) => o.deferred_settlement === true)).toHaveLength(8);
87
+ const settledLater = orders.filter((o) => o.order_settled_at != null &&
88
+ o.localDate != null &&
89
+ o.order_settled_at.toISOString().slice(0, 10) > o.localDate &&
90
+ o.payments.some((p) => p.payment_type === 'PAY_LATER' && p.payment_status === 'SETTLED'));
91
+ expect(settledLater).toHaveLength(6);
92
+ }
93
+ });
94
+ it('assigns ILocalTimeFields on a 6am–6am (+5) business day', () => {
95
+ for (const name of fixtures_1.ALL_ORDERS_DATASET_NAMES) {
96
+ const { gmtOffset, businessDayStartHour } = fixtures_1.ORDERS_DATASETS[name];
97
+ for (const order of (0, fixtures_1.loadOrdersDataset)(name)) {
98
+ expect(order.localDate).toMatch(/^\d{4}-\d{2}-\d{2}$/);
99
+ expect(typeof order.localHour).toBe('number');
100
+ expect(order.day_index).toBeDefined();
101
+ // 6am–6am rule: at/after 06:00 local → the local calendar day, before
102
+ // 06:00 → the previous day.
103
+ const shifted = new Date(order.createdAt.getTime() + gmtOffset * 60 * 60 * 1000);
104
+ const calendarDay = shifted.toISOString().slice(0, 10);
105
+ const previousDay = new Date(shifted.getTime() - 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
106
+ const expectedDay = shifted.getUTCHours() < businessDayStartHour ? previousDay : calendarDay;
107
+ expect(order.localDate).toBe(expectedDay);
108
+ }
109
+ }
110
+ });
111
+ it('covers cross-day settlement for time-bias tests (incl. settled-later credit bills)', () => {
112
+ const utcDay = (date) => date.toISOString().slice(0, 10);
113
+ const crossMidnight = (name) => (0, fixtures_1.loadOrdersDataset)(name).filter((o) => o.order_settled_at != null && utcDay(o.order_settled_at) !== utcDay(o.createdAt));
114
+ // basha: the 6 settled-later credit bills settle on the UTC day after.
115
+ expect(crossMidnight('basha')).toHaveLength(6);
116
+ // bruzo: 5 original cross-midnight settlements + 6 settled-later credit bills.
117
+ expect(crossMidnight('bruzo')).toHaveLength(11);
118
+ });
119
+ it('caches parsed datasets per process', () => {
120
+ expect((0, fixtures_1.loadOrdersDataset)('basha')).toBe((0, fixtures_1.loadOrdersDataset)('basha'));
121
+ expect((0, fixtures_1.loadOrdersDataset)('bruzo')).toBe((0, fixtures_1.loadOrdersDataset)('bruzo'));
122
+ });
123
+ });
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const mongoose_1 = __importDefault(require("mongoose"));
7
+ const ENUMS_1 = require("../../constants/ENUMS");
8
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
9
+ const materialized_tenant_reports_iterations_helpers_1 = require("../../helpers/materialized-reports/materialized-tenant-reports-iterations-helpers");
10
+ /** Narrows helper results that are `null` on invalid data (tests expect valid data). */
11
+ const expectNonNull = (value) => {
12
+ if (value == null)
13
+ throw new Error('expected a non-null helper result');
14
+ return value;
15
+ };
16
+ const materializedReport = (overrides = {}) => ({
17
+ _id: '68dd3f9c9f1b2c3d4e5f6a7b',
18
+ tenant_id: 'z2-isb',
19
+ brand_id: 'brand-1',
20
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
21
+ scope_field: '2026-09-30',
22
+ day_index: ENUMS_1.DAY_INDEX_ENUM.WED,
23
+ sale_type_key_filters: [...MATERIALIZED_REPORTS_1.SALES_OVERVIEW_KEY_FILTERS],
24
+ sale_type_metrics: {},
25
+ iteration: 3,
26
+ schema_version: 1,
27
+ source_watermark: new Date('2026-09-30T10:00:00.000Z'),
28
+ computed_at: new Date('2026-09-30T11:00:00.000Z'),
29
+ createdAt: new Date('2026-09-30T10:00:00.000Z'),
30
+ updatedAt: new Date('2026-09-30T11:00:00.000Z'),
31
+ ...overrides,
32
+ });
33
+ const SALES_OVERVIEW = { reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW, reason: 'NEW_DAY' };
34
+ describe('buildMaterializedTenantReportIteration', () => {
35
+ it('builds the history row for the report document’s current iteration', () => {
36
+ const report = materializedReport();
37
+ const computedAt = new Date('2026-09-30T12:00:00.000Z');
38
+ const row = expectNonNull((0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(report, { ...SALES_OVERVIEW, computedAt }));
39
+ expect(row.report_type).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW);
40
+ expect(row.report_id).toBe(report._id);
41
+ expect(row.iteration).toBe(3);
42
+ expect(row.schema_version).toBe(1);
43
+ expect(row.reason).toBe('NEW_DAY');
44
+ expect(row.snapshot).toBe(report); // full post-write document, by reference
45
+ expect(row.createdAt).toEqual(computedAt);
46
+ expect(row.updatedAt).toEqual(computedAt);
47
+ expect(row).not.toHaveProperty('_id'); // assigned by MongoDB on the write
48
+ });
49
+ it('defaults documents that never went through an update to iteration 1', () => {
50
+ const fresh = materializedReport({ iteration: undefined }); // raw convert output
51
+ const row = expectNonNull((0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(fresh, SALES_OVERVIEW));
52
+ expect(row.iteration).toBe(1);
53
+ });
54
+ it('accepts a hydrated ObjectId `_id` and stores the string form as report_id', () => {
55
+ const objectId = new mongoose_1.default.Types.ObjectId('68dd3f9c9f1b2c3d4e5f6a7b');
56
+ const hydrated = { ...materializedReport(), _id: objectId };
57
+ const row = expectNonNull((0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(hydrated, SALES_OVERVIEW));
58
+ expect(row.report_id).toBe('68dd3f9c9f1b2c3d4e5f6a7b');
59
+ });
60
+ it('returns null (never throws) for invalid input', () => {
61
+ expect((0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(null, SALES_OVERVIEW)).toBeNull();
62
+ expect((0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(undefined, SALES_OVERVIEW)).toBeNull();
63
+ expect((0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(materializedReport({ _id: '' }), SALES_OVERVIEW)).toBeNull();
64
+ expect((0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(materializedReport({ schema_version: undefined }), SALES_OVERVIEW)).toBeNull();
65
+ expect((0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(materializedReport({ iteration: 0 }), SALES_OVERVIEW)).toBeNull();
66
+ expect((0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(materializedReport(), {
67
+ reportType: 'NOPE',
68
+ reason: 'NEW_DAY',
69
+ })).toBeNull();
70
+ expect((0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(materializedReport(), {
71
+ reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
72
+ reason: '',
73
+ })).toBeNull();
74
+ });
75
+ });
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const mongoose_1 = __importDefault(require("mongoose"));
7
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
8
+ const materialized_tenant_reports_iterations_1 = require("../../schemas/models/materialized_tenant_reports_iterations");
9
+ const Model = mongoose_1.default.models[materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME] ??
10
+ mongoose_1.default.model(materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME, materialized_tenant_reports_iterations_1.MaterializedTenantReportIterationSchema, materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME);
11
+ const validRow = () => ({
12
+ _id: new mongoose_1.default.Types.ObjectId().toString(),
13
+ report_type: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
14
+ report_id: new mongoose_1.default.Types.ObjectId().toString(),
15
+ iteration: 2,
16
+ schema_version: 1,
17
+ reason: 'RECLOSE',
18
+ snapshot: {
19
+ _id: new mongoose_1.default.Types.ObjectId().toString(),
20
+ tenant_id: 'z2-isb',
21
+ scope_context: 'localDate',
22
+ scope_field: '2026-09-30',
23
+ sale_type_metrics: { 'COMPLETED:POS_WALK-IN': { marker: true } },
24
+ },
25
+ createdAt: new Date('2026-09-30T11:00:00.000Z'),
26
+ updatedAt: new Date('2026-09-30T11:00:00.000Z'),
27
+ });
28
+ describe('materialized_tenant_reports_iterations schema', () => {
29
+ it('exposes the agreed collection name', () => {
30
+ expect(materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME).toBe('materialized_tenant_reports_iterations');
31
+ });
32
+ it('validates a well-formed iteration row', () => {
33
+ const doc = new Model(validRow());
34
+ expect(doc.validateSync()).toBeUndefined();
35
+ expect(doc.get('report_type')).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW);
36
+ expect(doc.get('iteration')).toBe(2);
37
+ expect(doc.get('schema_version')).toBe(1);
38
+ expect(doc.get('reason')).toBe('RECLOSE');
39
+ });
40
+ it('stores the full report snapshot untouched (Mixed — no nested casting)', () => {
41
+ const row = validRow();
42
+ const doc = new Model(row);
43
+ const snapshot = doc.get('snapshot');
44
+ expect(snapshot).toMatchObject(row.snapshot);
45
+ expect(snapshot['sale_type_metrics']).toEqual({ 'COMPLETED:POS_WALK-IN': { marker: true } });
46
+ });
47
+ it('rejects an unknown report_type', () => {
48
+ const error = new Model({ ...validRow(), report_type: 'NOPE' }).validateSync();
49
+ expect(error?.errors).toHaveProperty('report_type');
50
+ });
51
+ it('rejects missing required fields (report_id, snapshot, reason)', () => {
52
+ const missingReportId = { ...validRow() };
53
+ delete missingReportId.report_id;
54
+ expect(new Model(missingReportId).validateSync()?.errors).toHaveProperty('report_id');
55
+ const missingSnapshot = { ...validRow() };
56
+ delete missingSnapshot.snapshot;
57
+ expect(new Model(missingSnapshot).validateSync()?.errors).toHaveProperty('snapshot');
58
+ const missingReason = { ...validRow() };
59
+ delete missingReason.reason;
60
+ expect(new Model(missingReason).validateSync()?.errors).toHaveProperty('reason');
61
+ });
62
+ it('enforces iteration >= 1', () => {
63
+ const error = new Model({ ...validRow(), iteration: 0 }).validateSync();
64
+ expect(error?.errors).toHaveProperty('iteration');
65
+ });
66
+ it('declares the unique (report_id, iteration) index and covers every report type', () => {
67
+ expect(materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_INDEXES.report_id__iteration).toEqual({
68
+ report_id: 1,
69
+ iteration: -1,
70
+ });
71
+ expect(MATERIALIZED_REPORTS_1.ALL_MATERIALIZED_REPORT_TYPES).toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW);
72
+ });
73
+ });