@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,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeReportedPaymentType = normalizeReportedPaymentType;
4
+ exports.isPaymentIncludedInSalesOverview = isPaymentIncludedInSalesOverview;
5
+ exports.getSalesOverviewPaymentGross = getSalesOverviewPaymentGross;
6
+ exports.computeSalesOverviewReference = computeSalesOverviewReference;
7
+ const constants_1 = require("../../constants");
8
+ /** `PAY_LATER` is reported as `UNPAID` (TODO in the live aggregation). */
9
+ function normalizeReportedPaymentType(paymentType) {
10
+ return paymentType === constants_1.PAYMENT_TYPE_ENUM.PAY_LATER ? constants_1.PAYMENT_TYPE_ENUM.UNPAID : paymentType;
11
+ }
12
+ /**
13
+ * Payment-level inclusion rule of the `TOTAL_PAYMENT_SALES` facet:
14
+ * settled/refunded payments, plus pending `UNPAID`/`PAY_LATER` (credit) payments.
15
+ */
16
+ function isPaymentIncludedInSalesOverview(payment) {
17
+ if (payment.payment_status === constants_1.PAYMENT_STATUS_ENUM.SETTLED ||
18
+ payment.payment_status === constants_1.PAYMENT_STATUS_ENUM.REFUNDED) {
19
+ return true;
20
+ }
21
+ return (payment.payment_status === constants_1.PAYMENT_STATUS_ENUM.PENDING &&
22
+ (payment.payment_type === constants_1.PAYMENT_TYPE_ENUM.UNPAID || payment.payment_type === constants_1.PAYMENT_TYPE_ENUM.PAY_LATER));
23
+ }
24
+ /**
25
+ * Payment gross contribution in cents, mirroring the live aggregation:
26
+ * - no refund: `amount_due` for UNPAID, else `min(amount_paid, amount_due)`;
27
+ * card charges are subtracted when `card_details` is present;
28
+ * - refunded: negative — `-amount_due` for UNPAID, else `-amount_refunded`.
29
+ */
30
+ function getSalesOverviewPaymentGross(payment) {
31
+ const reportedType = normalizeReportedPaymentType(payment.payment_type);
32
+ const isUnpaid = reportedType === constants_1.PAYMENT_TYPE_ENUM.UNPAID;
33
+ if (payment.amount_refunded === 0) {
34
+ let gross = isUnpaid ? payment.amount_due : Math.min(payment.amount_paid, payment.amount_due);
35
+ if (payment.card_details != null) {
36
+ gross -= payment.card_details.card_charges ?? 0;
37
+ }
38
+ return gross;
39
+ }
40
+ return -(isUnpaid ? payment.amount_due : payment.amount_refunded);
41
+ }
42
+ function matchesSaleType(order, saleType) {
43
+ switch (saleType) {
44
+ case constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED:
45
+ return order.amount_collected > 0;
46
+ case constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS:
47
+ return order.deferred_settlement === true;
48
+ default:
49
+ return true;
50
+ }
51
+ }
52
+ function matchesFilters(order, filters) {
53
+ const { tenants, timeBias = constants_1.REPORT_TIME_BIAS_ENUM.SETTLED_AT, platforms, orderStatuses } = filters;
54
+ if (tenants != null && tenants.length > 0 && !tenants.includes(order.tenant_id))
55
+ return false;
56
+ // Mongo `{ is_deleted: false }` equality does not match missing fields.
57
+ if (order.is_deleted !== false)
58
+ return false;
59
+ const anchor = timeBias === constants_1.REPORT_TIME_BIAS_ENUM.CREATED_AT ? order.createdAt : order.order_settled_at;
60
+ // Mongo `$gte`/`$lte` on a null/missing field never matches.
61
+ if (anchor == null)
62
+ return false;
63
+ if (anchor.getTime() < filters.from.getTime() || anchor.getTime() > filters.to.getTime()) {
64
+ return false;
65
+ }
66
+ if (platforms != null && platforms.length > 0 && !platforms.includes(order.platform))
67
+ return false;
68
+ if (orderStatuses != null && orderStatuses.length > 0 && !orderStatuses.includes(order.order_status)) {
69
+ return false;
70
+ }
71
+ return matchesSaleType(order, filters.saleType);
72
+ }
73
+ /** Count desc, then `_id` asc — deterministic variant of the client-side sort. */
74
+ function sortSummaries(summaries) {
75
+ return [...summaries].sort((a, b) => (b.count ?? 0) - (a.count ?? 0) || a._id.localeCompare(b._id));
76
+ }
77
+ /**
78
+ * Compute the Reports > Overview facets from raw orders (cents).
79
+ * Mirrors `getSalesOverview()` — see the module comment for the exact rules.
80
+ */
81
+ function computeSalesOverviewReference(orders, filters) {
82
+ const matched = orders.filter((order) => matchesFilters(order, filters));
83
+ const nonCancelled = matched.filter((order) => order.order_status !== constants_1.ORDER_STATUS_ENUM.CANCELLED);
84
+ const cancelled = matched.filter((order) => order.order_status === constants_1.ORDER_STATUS_ENUM.CANCELLED);
85
+ const groupId = filters.groupId ?? filters.tenants?.[0] ?? 'UNKNOWN';
86
+ const totalSales = { _id: groupId, count: 0, grossAmount: 0 };
87
+ for (const order of nonCancelled) {
88
+ totalSales.count++;
89
+ totalSales.grossAmount += order.amount_earned;
90
+ }
91
+ const cancelledOrders = { _id: groupId, count: 0, grossAmount: 0 };
92
+ for (const order of cancelled) {
93
+ cancelledOrders.count++;
94
+ cancelledOrders.grossAmount += order.amount_earned;
95
+ }
96
+ const byPlatform = new Map();
97
+ for (const order of nonCancelled) {
98
+ const summary = byPlatform.get(order.platform) ?? {
99
+ _id: order.platform,
100
+ count: 0,
101
+ grossAmount: 0,
102
+ };
103
+ summary.count++;
104
+ summary.grossAmount += order.amount_earned;
105
+ byPlatform.set(order.platform, summary);
106
+ }
107
+ const byPaymentType = new Map();
108
+ for (const order of nonCancelled) {
109
+ for (const payment of order.payments) {
110
+ if (!isPaymentIncludedInSalesOverview(payment))
111
+ continue;
112
+ const paymentType = normalizeReportedPaymentType(payment.payment_type);
113
+ const summary = byPaymentType.get(paymentType) ?? {
114
+ _id: paymentType,
115
+ count: 0,
116
+ grossAmount: 0,
117
+ };
118
+ summary.count++;
119
+ summary.grossAmount += getSalesOverviewPaymentGross(payment);
120
+ byPaymentType.set(paymentType, summary);
121
+ }
122
+ }
123
+ return {
124
+ // `$group` emits nothing when nothing matches — empty facets are `[]`,
125
+ // and the admin panel renders "No Data" when `TOTAL_SALES[0]` is absent.
126
+ [constants_1.REPORT_TYPE_ENUM.TOTAL_SALES]: totalSales.count > 0 ? [totalSales] : [],
127
+ [constants_1.REPORT_TYPE_ENUM.TOTAL_PAYMENT_SALES]: sortSummaries([...byPaymentType.values()]),
128
+ [constants_1.REPORT_TYPE_ENUM.SALES_BY_PLATFORM]: sortSummaries([...byPlatform.values()]),
129
+ [constants_1.REPORT_TYPE_ENUM.CANCELLED_ORDERS]: cancelledOrders.count > 0 ? [cancelledOrders] : [],
130
+ };
131
+ }
@@ -0,0 +1,335 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../../constants");
4
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
5
+ const tenant_sales_overview_close_day_helpers_1 = require("../../helpers/materialized-reports/tenant-sales-overview-close-day-helpers");
6
+ const tenant_sales_overview_helpers_1 = require("../../helpers/materialized-reports/tenant-sales-overview-helpers");
7
+ /** Narrows helper results that are `null` on invalid data (tests expect valid data). */
8
+ const expectNonNull = (value) => {
9
+ if (value == null)
10
+ throw new Error('expected a non-null helper result');
11
+ return value;
12
+ };
13
+ const TENANT = 'z2-isb';
14
+ const BRAND = 'brand-1';
15
+ const D1 = '2026-09-29';
16
+ const D2 = '2026-09-30';
17
+ const KEY = 'COMPLETED:POS_WALK-IN';
18
+ const LOCAL_DATE = MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE;
19
+ const LOCAL_HOUR = MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR;
20
+ const LOCAL_WEEK = MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK;
21
+ const LOCAL_MONTH = MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH;
22
+ const makeOrder = (args) => {
23
+ const paymentType = args.paymentType ?? constants_1.PAYMENT_TYPE_ENUM.CASH;
24
+ const amountPaid = args.amountPaid ?? (paymentType === constants_1.PAYMENT_TYPE_ENUM.PAY_LATER ? 0 : args.amount);
25
+ const settledAt = new Date(`${args.localDate}T12:00:00.000Z`);
26
+ return {
27
+ _id: args.orderId,
28
+ tenant_id: TENANT,
29
+ platform: 'POS_WALK-IN',
30
+ order_status: constants_1.ORDER_STATUS_ENUM.COMPLETED,
31
+ amount_earned: args.amount,
32
+ amount_collected: amountPaid,
33
+ total_discount_applied: 0,
34
+ gst_amount: 0,
35
+ tax_amount: 0,
36
+ tip_amount: 0,
37
+ tax_invoice_provider_charges: 0,
38
+ is_deleted: args.isDeleted === true,
39
+ deferred_settlement: paymentType === constants_1.PAYMENT_TYPE_ENUM.PAY_LATER,
40
+ localDate: args.localDate,
41
+ localHour: args.localHour,
42
+ order_settled_at: settledAt,
43
+ createdAt: settledAt,
44
+ updatedAt: new Date(args.updatedAt),
45
+ payments: [
46
+ {
47
+ payment_id: 'pay-1',
48
+ payment_type: paymentType,
49
+ payment_status: args.paymentStatus ?? constants_1.PAYMENT_STATUS_ENUM.SETTLED,
50
+ amount_due: args.amount,
51
+ amount_paid: amountPaid,
52
+ amount_refunded: 0,
53
+ card_details: null,
54
+ note: args.note ?? null,
55
+ },
56
+ ],
57
+ };
58
+ };
59
+ const compileDay = (localDate, orders, computedAt) => expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(localDate, orders, {
60
+ brandId: BRAND,
61
+ tenantId: TENANT,
62
+ computedAt,
63
+ }));
64
+ const closeDay = (localDate, orders, existing, computedAt, force = false) => expectNonNull((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
65
+ tenantId: TENANT,
66
+ compile: compileDay(localDate, orders, computedAt),
67
+ reason: 'TEST_CLOSE',
68
+ existing,
69
+ force,
70
+ computedAt,
71
+ }));
72
+ const scopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
73
+ /** Mongoose applies the schema default (`iteration: 1`) on the first insert. */
74
+ const withDefaultIteration = (doc) => doc.iteration == null ? { ...doc, iteration: 1 } : doc;
75
+ /** Simulates the job persisting a plan (structural writes, then patches, minus stale deletions). */
76
+ const persistPlan = (stored, plan) => {
77
+ const byKey = new Map(stored.map((doc) => [scopeKey(doc), doc]));
78
+ for (const write of plan.writes)
79
+ byKey.set(scopeKey(write.report), withDefaultIteration(write.report));
80
+ for (const patch of plan.receivedPatches)
81
+ byKey.set(scopeKey(patch.report), patch.report);
82
+ for (const stale of plan.staleHourDocuments)
83
+ byKey.delete(scopeKey(stale));
84
+ return Array.from(byKey.values());
85
+ };
86
+ const findWrite = (plan, scope, field) => plan.writes.find((write) => write.report.scope_context === scope && write.report.scope_field === field);
87
+ const getKeyMetrics = (doc, key = KEY) => doc.sale_type_metrics?.[key];
88
+ describe('tenant sales overview close-day plan', () => {
89
+ const CT1 = new Date('2026-09-29T23:00:00.000Z');
90
+ const CT2 = new Date('2026-09-30T23:00:00.000Z');
91
+ const CT3 = new Date('2026-10-01T01:00:00.000Z');
92
+ const CT4 = new Date('2026-10-01T02:00:00.000Z');
93
+ const CT5 = new Date('2026-10-01T03:00:00.000Z');
94
+ const T1 = '2026-09-29T20:10:00.000Z';
95
+ const T2_CASH = '2026-09-30T12:30:00.000Z';
96
+ const T2_COLLECTED = '2026-09-30T14:30:00.000Z';
97
+ const T4_EXTRA = '2026-09-30T18:00:00.000Z';
98
+ const T5_DELETED = '2026-10-01T00:30:00.000Z';
99
+ const creditIssue = makeOrder({
100
+ orderId: 'order-credit-1',
101
+ localDate: D1,
102
+ localHour: 20,
103
+ amount: 1200,
104
+ paymentType: constants_1.PAYMENT_TYPE_ENUM.PAY_LATER,
105
+ paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING,
106
+ updatedAt: T1,
107
+ });
108
+ const cashD2 = makeOrder({ orderId: 'order-cash-2', localDate: D2, localHour: 12, amount: 800, updatedAt: T2_CASH });
109
+ const collectedCredit = makeOrder({
110
+ orderId: 'order-credit-1',
111
+ localDate: D1,
112
+ localHour: 14,
113
+ amount: 1200,
114
+ amountPaid: 1200,
115
+ paymentType: constants_1.PAYMENT_TYPE_ENUM.PAY_LATER,
116
+ paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
117
+ updatedAt: T2_COLLECTED,
118
+ note: 'CN-2026-09-30',
119
+ });
120
+ const extraD2 = makeOrder({
121
+ orderId: 'order-cash-3',
122
+ localDate: D2,
123
+ localHour: 18,
124
+ amount: 500,
125
+ updatedAt: T4_EXTRA,
126
+ });
127
+ const deletedIssue = makeOrder({
128
+ orderId: 'order-credit-1',
129
+ localDate: D1,
130
+ localHour: 20,
131
+ amount: 1200,
132
+ paymentType: constants_1.PAYMENT_TYPE_ENUM.PAY_LATER,
133
+ paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING,
134
+ updatedAt: T5_DELETED,
135
+ isDeleted: true,
136
+ });
137
+ // Lifecycle: close D1 → close D2 (collecting the D1 bill) → re-close D2.
138
+ const plan1 = closeDay(D1, [creditIssue], [], CT1);
139
+ const stored1 = persistPlan([], plan1);
140
+ const plan2 = closeDay(D2, [cashD2, collectedCredit], stored1, CT2);
141
+ const stored2 = persistPlan(stored1, plan2);
142
+ const plan3 = closeDay(D2, [cashD2, collectedCredit], stored2, CT3);
143
+ const plan4 = closeDay(D2, [cashD2, collectedCredit, extraD2], stored2, CT4);
144
+ const plan5 = closeDay(D1, [deletedIssue], stored1, CT5);
145
+ it('plans the first close: hour + date + period day-deltas, each with an iteration-1 history row', () => {
146
+ expect(plan1.writes).toHaveLength(8); // 1 hour + 7 period scopes
147
+ expect(plan1.staleHourDocuments).toEqual([]);
148
+ expect(plan1.receivedPatches).toEqual([]);
149
+ expect(plan1.skippedDocuments).toEqual([]);
150
+ // First materialized close of the period: all six accumulated scopes are created.
151
+ expect(plan1.createdPeriodDocuments.map((ref) => ref.scope_context)).toEqual([
152
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
153
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
154
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
155
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
156
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
157
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
158
+ ]);
159
+ for (const write of plan1.writes) {
160
+ expect(write.iteration.report_type).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW);
161
+ expect(write.iteration.report_id).toBe(write.report._id);
162
+ expect(write.iteration.iteration).toBe(1);
163
+ expect(write.iteration.reason).toBe('TEST_CLOSE');
164
+ expect(write.iteration.snapshot).toBe(write.report);
165
+ }
166
+ const dateWrite = expectNonNull(findWrite(plan1, LOCAL_DATE, D1));
167
+ expect(dateWrite.report.source_watermark).toEqual(new Date(T1));
168
+ // Explicit first materialization — raw `replaceOne` upserts stay schema-conformant.
169
+ expect(dateWrite.report.iteration).toBe(1);
170
+ const metrics = getKeyMetrics(dateWrite.report);
171
+ expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(1);
172
+ expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.count).toBe(1);
173
+ expect(findWrite(plan1, LOCAL_HOUR, `${D1} 20`)).toBeDefined();
174
+ expect(findWrite(plan1, LOCAL_WEEK, '2026-09-27')).toBeDefined();
175
+ expect(findWrite(plan1, LOCAL_MONTH, '2026-09')).toBeDefined();
176
+ });
177
+ it('plans the collection day: accumulates periods and patches the issue-day ledger', () => {
178
+ expect(plan2.writes).toHaveLength(8); // date + 1 hour (sales 12 and the collection bucket at 12) + 6 periods
179
+ // The collection event buckets by the SETTLEMENT hour (mins 720 → 12), not the punch hour (14).
180
+ const hourWrite = expectNonNull(findWrite(plan2, LOCAL_HOUR, `${D2} 12`));
181
+ expect(getKeyMetrics(hourWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.count).toBe(1);
182
+ expect(plan2.createdPeriodDocuments).toEqual([]); // periods already materialized by the first close
183
+ const monthWrite = expectNonNull(findWrite(plan2, LOCAL_MONTH, '2026-09'));
184
+ expect(monthWrite.report.source_watermark).toEqual(new Date(T2_COLLECTED)); // max folded watermark
185
+ const monthMetrics = getKeyMetrics(monthWrite.report);
186
+ expect(monthMetrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(2); // D1 credit + D2 cash
187
+ expect(monthMetrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.count).toBe(1);
188
+ const dateWrite = expectNonNull(findWrite(plan2, LOCAL_DATE, D2));
189
+ const dateMetrics = getKeyMetrics(dateWrite.report);
190
+ expect(dateMetrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(1); // D2 sales only
191
+ expect(dateMetrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.amount).toBe(1200);
192
+ // Every stored D1 doc holds the issued bill → all get patched as
193
+ // versioned writes (ledger changed → iteration bump + history row).
194
+ expect(plan2.receivedPatches).toHaveLength(8);
195
+ expect(plan2.receivedPatches.some((write) => write.report.scope_context === LOCAL_HOUR)).toBe(true);
196
+ const patchedDate = expectNonNull(plan2.receivedPatches.find((write) => write.report.scope_context === LOCAL_DATE && write.report.scope_field === D1));
197
+ const issued = getKeyMetrics(patchedDate.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued;
198
+ expect(issued?.settled_count).toBe(1);
199
+ expect(issued?.settled_amount).toBe(1200);
200
+ expect(issued?.bills[0]).toMatchObject({
201
+ received_amount: 1200,
202
+ credit_note: 'CN-2026-09-30',
203
+ });
204
+ expect(patchedDate.report.iteration).toBe(2); // was 1 — the patch bumped it
205
+ expect(patchedDate.iteration.iteration).toBe(2); // history row for the patched version
206
+ expect(patchedDate.iteration.reason).toBe('TEST_CLOSE');
207
+ expect(patchedDate.iteration.snapshot).toBe(patchedDate.report);
208
+ expect(patchedDate.report.updatedAt).toEqual(CT2);
209
+ });
210
+ it('skips an unchanged re-close (watermark guard) and reapplies nothing', () => {
211
+ expect(plan3.writes).toHaveLength(0);
212
+ expect(plan3.receivedPatches).toEqual([]);
213
+ expect(plan3.staleHourDocuments).toEqual([]);
214
+ expect(plan3.skippedDocuments).toHaveLength(8); // date + 1 hour + 6 periods
215
+ });
216
+ it('re-closes a changed day: subtracts the stored delta, adds the recalculated one', () => {
217
+ expect(plan4.writes).toHaveLength(9); // date + 2 hours (12 merged collection, 18 extra) + 6 periods
218
+ const monthWrite = expectNonNull(findWrite(plan4, LOCAL_MONTH, '2026-09'));
219
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(3); // D1 + D2 + extra
220
+ // 1 (first close) → 2 (accumulation write) + 3 (bill patch) on the collection day → 4 (re-close)
221
+ expect(monthWrite.report.iteration).toBe(4);
222
+ expect(monthWrite.report.source_watermark).toEqual(new Date(T4_EXTRA));
223
+ const dateWrite = expectNonNull(findWrite(plan4, LOCAL_DATE, D2));
224
+ expect(dateWrite.report.iteration).toBe(2);
225
+ expect(getKeyMetrics(dateWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(2); // D2 cash + extra
226
+ expect(findWrite(plan4, LOCAL_HOUR, `${D2} 18`)).toBeDefined();
227
+ });
228
+ it('repairs stale hours and removes a deleted day from the period documents', () => {
229
+ expect(plan5.staleHourDocuments.map((doc) => doc.scope_field)).toEqual([`${D1} 20`]);
230
+ const monthWrite = expectNonNull(findWrite(plan5, LOCAL_MONTH, '2026-09'));
231
+ expect(getKeyMetrics(monthWrite.report)?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count ?? 0).toBe(0);
232
+ const dateWrite = expectNonNull(findWrite(plan5, LOCAL_DATE, D1));
233
+ expect(getKeyMetrics(dateWrite.report)).toBeUndefined(); // empty metrics
234
+ expect(plan5.receivedPatches).toEqual([]);
235
+ });
236
+ it('rewrites everything on force even when the watermark says up to date', () => {
237
+ const forced = closeDay(D2, [cashD2, collectedCredit], stored2, CT3, true);
238
+ expect(forced.writes).toHaveLength(8);
239
+ expect(forced.skippedDocuments).toHaveLength(0);
240
+ });
241
+ it('treats order-less days as a stable date marker (epoch watermark, no re-close churn)', () => {
242
+ const emptyPlan = closeDay(D2, [], [], CT1);
243
+ expect(emptyPlan.writes.map((write) => write.report.scope_context)).toEqual([LOCAL_DATE]);
244
+ expect(emptyPlan.writes[0].report.source_watermark).toEqual(new Date(0));
245
+ const emptyReClose = closeDay(D2, [], persistPlan([], emptyPlan), CT2);
246
+ expect(emptyReClose.writes).toHaveLength(0);
247
+ expect(emptyReClose.skippedDocuments).toHaveLength(1);
248
+ });
249
+ it('returns null for inconsistent input (never throws)', () => {
250
+ expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)(null)).toBeNull();
251
+ const compile = compileDay(D2, [cashD2], CT1);
252
+ expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({ tenantId: 'other', compile, reason: 'TEST_CLOSE' })).toBeNull();
253
+ expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({ tenantId: TENANT, compile, reason: '' })).toBeNull();
254
+ const duplicated = [...compile.materializedReports, compile.materializedReports[0]];
255
+ expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
256
+ tenantId: TENANT,
257
+ compile: { ...compile, materializedReports: duplicated },
258
+ reason: 'TEST_CLOSE',
259
+ })).toBeNull();
260
+ const withoutDate = compile.materializedReports.filter((doc) => doc.scope_context !== LOCAL_DATE);
261
+ expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
262
+ tenantId: TENANT,
263
+ compile: { ...compile, materializedReports: withoutDate },
264
+ reason: 'TEST_CLOSE',
265
+ })).toBeNull();
266
+ });
267
+ it('rejects duplicate STORED rows for one scope key (missing unique index)', () => {
268
+ const compile = compileDay(D2, [cashD2], CT1);
269
+ const dateDoc = compile.materializedReports.find((doc) => doc.scope_context === LOCAL_DATE);
270
+ const duplicateRow = { ...dateDoc, _id: 'other-id' };
271
+ expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
272
+ tenantId: TENANT,
273
+ compile,
274
+ reason: 'TEST_CLOSE',
275
+ existing: [dateDoc, duplicateRow],
276
+ })).toBeNull();
277
+ // Repeating the SAME document (overlapping fetch refs) is fine.
278
+ expect((0, tenant_sales_overview_close_day_helpers_1.buildTenantSalesOverviewCloseDayPlan)({
279
+ tenantId: TENANT,
280
+ compile,
281
+ reason: 'TEST_CLOSE',
282
+ existing: [dateDoc, dateDoc],
283
+ })).not.toBeNull();
284
+ });
285
+ it('normalizes hydrated (mongoose-cast) stored docs when planning patches', () => {
286
+ // Real hydration shape: `Model.find()` docs carry the `sale_type_metrics` Map
287
+ // with mongoose subdocument values (NOT plain objects).
288
+ const hydratedStored = stored1.map((doc) => doc.scope_context === LOCAL_DATE && doc.scope_field === D1
289
+ ? (0, tenant_sales_overview_helpers_1.convertMaterializedTenantSalesOverviewReportJsonToBson)(doc).toObject()
290
+ : doc);
291
+ const plan = closeDay(D2, [cashD2, collectedCredit], hydratedStored, CT2);
292
+ expect(plan.receivedPatches).toHaveLength(8); // the hydrated D1 date doc is still detected + patched
293
+ expect(plan.receivedPatches.some((write) => write.report.scope_field === D1)).toBe(true);
294
+ expect(JSON.stringify(plan.receivedPatches)).not.toContain('$__'); // no mongoose internals leak through
295
+ });
296
+ });
297
+ describe('needsMaterializedTenantSalesOverviewReportWrite', () => {
298
+ const reportDoc = (watermark) => ({
299
+ _id: '68dd3f9c9f1b2c3d4e5f6a7b',
300
+ tenant_id: TENANT,
301
+ brand_id: BRAND,
302
+ scope_context: LOCAL_DATE,
303
+ scope_field: D1,
304
+ sale_type_key_filters: [...MATERIALIZED_REPORTS_1.SALES_OVERVIEW_KEY_FILTERS],
305
+ sale_type_metrics: {},
306
+ schema_version: 1,
307
+ source_watermark: new Date(watermark),
308
+ computed_at: new Date('2026-09-29T23:00:00.000Z'),
309
+ createdAt: new Date('2026-09-29T23:00:00.000Z'),
310
+ updatedAt: new Date('2026-09-29T23:00:00.000Z'),
311
+ });
312
+ it('compares watermarks (monotonic) and schema / key-filter grammar', () => {
313
+ const base = reportDoc('2026-09-29T20:00:00.000Z');
314
+ expect((0, tenant_sales_overview_close_day_helpers_1.needsMaterializedTenantSalesOverviewReportWrite)(null, base)).toBe(true);
315
+ expect((0, tenant_sales_overview_close_day_helpers_1.needsMaterializedTenantSalesOverviewReportWrite)(base, reportDoc('2026-09-29T20:00:00.000Z'))).toBe(false);
316
+ expect((0, tenant_sales_overview_close_day_helpers_1.needsMaterializedTenantSalesOverviewReportWrite)(base, reportDoc('2026-09-29T21:00:00.000Z'))).toBe(true);
317
+ expect((0, tenant_sales_overview_close_day_helpers_1.needsMaterializedTenantSalesOverviewReportWrite)(base, reportDoc('2026-09-29T19:00:00.000Z'))).toBe(false);
318
+ expect((0, tenant_sales_overview_close_day_helpers_1.needsMaterializedTenantSalesOverviewReportWrite)(base, { ...base, schema_version: 2 })).toBe(true);
319
+ expect((0, tenant_sales_overview_close_day_helpers_1.needsMaterializedTenantSalesOverviewReportWrite)(base, {
320
+ ...base,
321
+ sale_type_key_filters: [...MATERIALIZED_REPORTS_1.SALES_OVERVIEW_KEY_FILTERS].reverse(),
322
+ })).toBe(true);
323
+ });
324
+ });
325
+ describe('getMaterializedTenantSalesOverviewScopeRefsForDay', () => {
326
+ it('lists the day fan-out: date + 6 periods + all 24 hour buckets', () => {
327
+ const refs = expectNonNull((0, tenant_sales_overview_close_day_helpers_1.getMaterializedTenantSalesOverviewScopeRefsForDay)(D1));
328
+ expect(refs).toHaveLength(31);
329
+ expect(refs[0]).toEqual({ scope_context: LOCAL_DATE, scope_field: D1 });
330
+ expect(refs).toContainEqual({ scope_context: LOCAL_WEEK, scope_field: '2026-09-27' });
331
+ expect(refs).toContainEqual({ scope_context: LOCAL_HOUR, scope_field: `${D1} 00` });
332
+ expect(refs).toContainEqual({ scope_context: LOCAL_HOUR, scope_field: `${D1} 23` });
333
+ expect((0, tenant_sales_overview_close_day_helpers_1.getMaterializedTenantSalesOverviewScopeRefsForDay)('2026-9-30')).toBeNull();
334
+ });
335
+ });