@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.
- package/esm/constants/MATERIALIZED_REPORTS.js +105 -0
- package/esm/constants/index.js +1 -0
- package/esm/helpers/index.js +1 -0
- package/esm/helpers/materialized-reports/index.js +5 -0
- package/esm/helpers/materialized-reports/key-helpers.js +59 -0
- package/esm/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +60 -0
- package/esm/helpers/materialized-reports/scope-helpers.js +107 -0
- package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +251 -0
- package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +860 -0
- package/esm/schemas/models/index.js +2 -0
- package/esm/schemas/models/materialized_tenant_reports_iterations.js +82 -0
- package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +399 -0
- package/esm/schemas/types/index.js +2 -0
- package/esm/schemas/types/materialized_tenant_reports_iterations.js +1 -0
- package/esm/schemas/types/materialized_tenant_sales_overview_reports.js +1 -0
- package/lib/constants/MATERIALIZED_REPORTS.d.ts +96 -0
- package/lib/constants/MATERIALIZED_REPORTS.js +108 -0
- package/lib/constants/index.d.ts +1 -0
- package/lib/constants/index.js +1 -0
- package/lib/helpers/index.d.ts +1 -0
- package/lib/helpers/index.js +1 -0
- package/lib/helpers/materialized-reports/index.d.ts +5 -0
- package/lib/helpers/materialized-reports/index.js +21 -0
- package/lib/helpers/materialized-reports/key-helpers.d.ts +35 -0
- package/lib/helpers/materialized-reports/key-helpers.js +64 -0
- package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.d.ts +66 -0
- package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +63 -0
- package/lib/helpers/materialized-reports/scope-helpers.d.ts +57 -0
- package/lib/helpers/materialized-reports/scope-helpers.js +114 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +125 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +256 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +223 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +875 -0
- package/lib/schemas/models/index.d.ts +2 -0
- package/lib/schemas/models/index.js +2 -0
- package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +80 -0
- package/lib/schemas/models/materialized_tenant_reports_iterations.js +85 -0
- package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +569 -0
- package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +402 -0
- package/lib/schemas/models/orders.d.ts +24 -24
- package/lib/schemas/models/tenant_active_jobs.d.ts +3 -3
- package/lib/schemas/models/tenant_calendar.d.ts +3 -3
- package/lib/schemas/models/tenant_cash_drawer_sessions.d.ts +24 -24
- package/lib/schemas/models/tenant_cash_in_out.d.ts +24 -24
- package/lib/schemas/models/tenant_day_sessions.d.ts +24 -24
- package/lib/schemas/models/tenant_instore_shift_sessions.d.ts +24 -24
- package/lib/schemas/types/index.d.ts +2 -0
- package/lib/schemas/types/index.js +2 -0
- package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +62 -0
- package/lib/schemas/types/materialized_tenant_reports_iterations.js +2 -0
- package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +242 -0
- package/lib/schemas/types/materialized_tenant_sales_overview_reports.js +3 -0
- package/lib/tests/materialized-reports/fixtures.d.ts +81 -0
- package/lib/tests/materialized-reports/fixtures.js +87 -0
- package/lib/tests/materialized-reports/fixtures.test.d.ts +1 -0
- package/lib/tests/materialized-reports/fixtures.test.js +123 -0
- package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.js +75 -0
- package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +73 -0
- package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +207 -0
- package/lib/tests/materialized-reports/sales-overview-baseline.test.d.ts +1 -0
- package/lib/tests/materialized-reports/sales-overview-baseline.test.js +326 -0
- package/lib/tests/materialized-reports/sales-overview-reference.d.ts +63 -0
- package/lib/tests/materialized-reports/sales-overview-reference.js +131 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.d.ts +1 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +335 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.d.ts +1 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +885 -0
- package/package.json +5 -2
|
@@ -0,0 +1,885 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const constants_1 = require("../../constants");
|
|
4
|
+
const ENUMS_1 = require("../../constants/ENUMS");
|
|
5
|
+
const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
|
|
6
|
+
const key_helpers_1 = require("../../helpers/materialized-reports/key-helpers");
|
|
7
|
+
const materialized_tenant_reports_iterations_helpers_1 = require("../../helpers/materialized-reports/materialized-tenant-reports-iterations-helpers");
|
|
8
|
+
const scope_helpers_1 = require("../../helpers/materialized-reports/scope-helpers");
|
|
9
|
+
const tenant_sales_overview_helpers_1 = require("../../helpers/materialized-reports/tenant-sales-overview-helpers");
|
|
10
|
+
const time_helpers_1 = require("../../helpers/utils/time-helpers");
|
|
11
|
+
const fixtures_1 = require("./fixtures");
|
|
12
|
+
const sales_overview_reference_1 = require("./sales-overview-reference");
|
|
13
|
+
const round2 = (value) => Math.round(value * 100) / 100;
|
|
14
|
+
/** Narrows helper results that are `null` on invalid data (tests expect valid data). */
|
|
15
|
+
const expectNonNull = (value) => {
|
|
16
|
+
if (value == null)
|
|
17
|
+
throw new Error('expected a non-null helper result');
|
|
18
|
+
return value;
|
|
19
|
+
};
|
|
20
|
+
const BASHA = 'basha-istanbul-f7';
|
|
21
|
+
const BRAND = 'brand-basha';
|
|
22
|
+
const DAY = '2026-09-30';
|
|
23
|
+
const DAY_WINDOW = {
|
|
24
|
+
from: new Date('2026-09-30T00:00:00.000Z'),
|
|
25
|
+
to: new Date('2026-09-30T23:59:59.999Z'),
|
|
26
|
+
};
|
|
27
|
+
const getKeyMetrics = (doc, key) => doc.sale_type_metrics?.[key];
|
|
28
|
+
const statusOfKey = (key) => expectNonNull((0, key_helpers_1.parseMaterializedReportKey)(key))[0];
|
|
29
|
+
const zeroOrderMetric = () => ({
|
|
30
|
+
count: 0,
|
|
31
|
+
gross_amount: 0,
|
|
32
|
+
discount_amount: 0,
|
|
33
|
+
discount_by_type: { special_discount: 0, loyalty_discount: 0, voucher_discount: 0 },
|
|
34
|
+
gst_amount: 0,
|
|
35
|
+
tax_amount: 0,
|
|
36
|
+
tip_amount: 0,
|
|
37
|
+
tax_invoice_provider_charges: 0,
|
|
38
|
+
delivery_charges: 0,
|
|
39
|
+
});
|
|
40
|
+
const makePayLaterOrder = (args) => ({
|
|
41
|
+
_id: args.orderId,
|
|
42
|
+
tenant_id: 'z2-isb',
|
|
43
|
+
platform: 'POS_WALK-IN',
|
|
44
|
+
order_status: args.orderStatus ?? constants_1.ORDER_STATUS_ENUM.COMPLETED,
|
|
45
|
+
amount_earned: args.amountDue,
|
|
46
|
+
amount_collected: args.amountPaid,
|
|
47
|
+
total_discount_applied: 0,
|
|
48
|
+
gst_amount: 0,
|
|
49
|
+
tax_amount: 0,
|
|
50
|
+
tip_amount: 0,
|
|
51
|
+
tax_invoice_provider_charges: 0,
|
|
52
|
+
is_deleted: false,
|
|
53
|
+
deferred_settlement: true,
|
|
54
|
+
localDate: args.localDate,
|
|
55
|
+
order_settled_at: new Date(args.settledAt),
|
|
56
|
+
order_settled_at_mins: new Date(args.settledAt).getUTCHours() * 60 + new Date(args.settledAt).getUTCMinutes(),
|
|
57
|
+
createdAt: new Date(args.settledAt),
|
|
58
|
+
updatedAt: new Date(args.updatedAt),
|
|
59
|
+
payments: [
|
|
60
|
+
{
|
|
61
|
+
payment_id: 'pay-1',
|
|
62
|
+
payment_type: constants_1.PAYMENT_TYPE_ENUM.PAY_LATER,
|
|
63
|
+
payment_status: args.paymentStatus,
|
|
64
|
+
amount_due: args.amountDue,
|
|
65
|
+
amount_paid: args.amountPaid,
|
|
66
|
+
amount_refunded: 0,
|
|
67
|
+
card_details: null,
|
|
68
|
+
note: args.note ?? null,
|
|
69
|
+
},
|
|
70
|
+
],
|
|
71
|
+
});
|
|
72
|
+
describe('materialized report key helpers', () => {
|
|
73
|
+
it('builds and parses the ordered key grammar', () => {
|
|
74
|
+
expect((0, key_helpers_1.buildMaterializedReportKey)(['COMPLETED', 'POS_TAKE-AWAY'])).toBe('COMPLETED:POS_TAKE-AWAY');
|
|
75
|
+
expect((0, key_helpers_1.parseMaterializedReportKey)('COMPLETED:POS_TAKE-AWAY')).toEqual(['COMPLETED', 'POS_TAKE-AWAY']);
|
|
76
|
+
});
|
|
77
|
+
it('returns null for invalid components / malformed keys (never throws)', () => {
|
|
78
|
+
expect((0, key_helpers_1.buildMaterializedReportKey)([])).toBeNull();
|
|
79
|
+
expect((0, key_helpers_1.buildMaterializedReportKey)([''])).toBeNull();
|
|
80
|
+
expect((0, key_helpers_1.buildMaterializedReportKey)(['A:B', 'C'])).toBeNull();
|
|
81
|
+
expect((0, key_helpers_1.buildMaterializedReportKey)(['A.B', 'C'])).toBeNull();
|
|
82
|
+
expect((0, key_helpers_1.buildMaterializedReportKey)(['A$B', 'C'])).toBeNull();
|
|
83
|
+
expect((0, key_helpers_1.parseMaterializedReportKey)('COMPLETED:')).toBeNull();
|
|
84
|
+
expect((0, key_helpers_1.parseMaterializedReportKey)('')).toBeNull();
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
describe('materialized report scope helpers', () => {
|
|
88
|
+
it('derives every period scope field from a local date', () => {
|
|
89
|
+
const fields = expectNonNull((0, scope_helpers_1.getMaterializedPeriodScopeFields)(DAY));
|
|
90
|
+
expect(fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE]).toBe(DAY);
|
|
91
|
+
expect(fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK]).toBe('2026-09-27'); // Sun–Sat week start
|
|
92
|
+
expect(fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR]).toBe(`2026-W${String((0, time_helpers_1.getIsoWeekOfYear)(2026, 9, 30)).padStart(2, '0')}`);
|
|
93
|
+
expect(fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH]).toBe('2026-09');
|
|
94
|
+
expect(fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER]).toBe('2026-Q3');
|
|
95
|
+
expect(fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER]).toBe('2026-S2');
|
|
96
|
+
expect(fields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR]).toBe('2026');
|
|
97
|
+
});
|
|
98
|
+
it('bounds ISO boundary weeks with the ISO week-year', () => {
|
|
99
|
+
expect((0, scope_helpers_1.getIsoWeekYear)('2027-01-01')).toBe(2026);
|
|
100
|
+
expect(expectNonNull((0, scope_helpers_1.getMaterializedPeriodScopeFields)('2027-01-01'))[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR]).toBe('2026-W53');
|
|
101
|
+
});
|
|
102
|
+
it('returns null for malformed local dates — including impossible calendar dates (never throws)', () => {
|
|
103
|
+
expect((0, scope_helpers_1.getMaterializedPeriodScopeFields)('2026-13-40')).toBeNull();
|
|
104
|
+
expect((0, scope_helpers_1.getMaterializedPeriodScopeFields)('30-09-2026')).toBeNull();
|
|
105
|
+
expect((0, scope_helpers_1.getIsoWeekYear)('2026-13-40')).toBeNull();
|
|
106
|
+
// No Date.UTC rollover: impossible dates must not derive next-month scopes.
|
|
107
|
+
expect((0, scope_helpers_1.getMaterializedPeriodScopeFields)('2026-02-31')).toBeNull();
|
|
108
|
+
expect((0, scope_helpers_1.getMaterializedPeriodScopeFields)('2026-04-31')).toBeNull();
|
|
109
|
+
expect((0, scope_helpers_1.getMaterializedHourScopeField)('2026-02-31', 5)).toBeNull();
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
describe('convertOrdersToMaterializedTenantSalesOverviewReports — live parity (basha 2026-09-30)', () => {
|
|
113
|
+
const allOrders = (0, fixtures_1.loadOrdersDataset)('basha');
|
|
114
|
+
const dayOrders = allOrders.filter((order) => order.order_settled_at != null &&
|
|
115
|
+
order.order_settled_at >= DAY_WINDOW.from &&
|
|
116
|
+
order.order_settled_at <= DAY_WINDOW.to);
|
|
117
|
+
const result = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(DAY, dayOrders, { brandId: BRAND }));
|
|
118
|
+
const dateDoc = result.materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === DAY);
|
|
119
|
+
it('emits the period documents plus one document per active hour, with day_index on hour/date only', () => {
|
|
120
|
+
expect(dayOrders.length).toBeGreaterThan(0);
|
|
121
|
+
expect(dateDoc).toBeDefined();
|
|
122
|
+
const hourDocs = result.materializedReports.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR);
|
|
123
|
+
expect(hourDocs.length).toBeGreaterThan(0);
|
|
124
|
+
expect(hourDocs.length).toBeLessThanOrEqual(24);
|
|
125
|
+
for (const doc of hourDocs) {
|
|
126
|
+
expect(doc.scope_field).toMatch(/^2026-09-30 \d{2}$/);
|
|
127
|
+
expect(doc.day_index).toBe(ENUMS_1.DAY_INDEX_ENUM.WED);
|
|
128
|
+
}
|
|
129
|
+
// 7 period scopes + N hour scopes.
|
|
130
|
+
expect(result.materializedReports.length).toBe(7 + hourDocs.length);
|
|
131
|
+
for (const doc of result.materializedReports) {
|
|
132
|
+
expect(doc.tenant_id).toBe(BASHA);
|
|
133
|
+
expect(doc.brand_id).toBe(BRAND);
|
|
134
|
+
expect(doc.sale_type_key_filters).toEqual(MATERIALIZED_REPORTS_1.SALES_OVERVIEW_KEY_FILTERS);
|
|
135
|
+
expect(doc.schema_version).toBe(1);
|
|
136
|
+
if (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
137
|
+
doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE) {
|
|
138
|
+
// only the localHour / localDate documents carry the weekday
|
|
139
|
+
expect(doc.day_index).toBeNull();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
expect(dateDoc.day_index).toBe(ENUMS_1.DAY_INDEX_ENUM.WED);
|
|
143
|
+
expect(result.received_payments).toEqual([]);
|
|
144
|
+
});
|
|
145
|
+
it('reproduces the live TOTAL_SALES / AMOUNT_COLLECTED facets for the day (cancelled keys excluded)', () => {
|
|
146
|
+
const reference = (0, sales_overview_reference_1.computeSalesOverviewReference)(allOrders, {
|
|
147
|
+
...DAY_WINDOW,
|
|
148
|
+
tenants: [BASHA],
|
|
149
|
+
groupId: BASHA,
|
|
150
|
+
});
|
|
151
|
+
const referenceCollected = (0, sales_overview_reference_1.computeSalesOverviewReference)(allOrders, {
|
|
152
|
+
...DAY_WINDOW,
|
|
153
|
+
tenants: [BASHA],
|
|
154
|
+
groupId: BASHA,
|
|
155
|
+
saleType: constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED,
|
|
156
|
+
});
|
|
157
|
+
const totalSales = reference[constants_1.REPORT_TYPE_ENUM.TOTAL_SALES][0];
|
|
158
|
+
const collected = referenceCollected[constants_1.REPORT_TYPE_ENUM.TOTAL_SALES][0];
|
|
159
|
+
expect(totalSales).toBeDefined();
|
|
160
|
+
expect(collected).toBeDefined();
|
|
161
|
+
let count = 0;
|
|
162
|
+
let gross = 0;
|
|
163
|
+
let collectedCount = 0;
|
|
164
|
+
let collectedGross = 0;
|
|
165
|
+
for (const [key, metric] of Object.entries(dateDoc.sale_type_metrics ?? {})) {
|
|
166
|
+
if (statusOfKey(key) === constants_1.ORDER_STATUS_ENUM.CANCELLED)
|
|
167
|
+
continue;
|
|
168
|
+
count += metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count;
|
|
169
|
+
gross += metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount;
|
|
170
|
+
collectedCount += metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders.count;
|
|
171
|
+
collectedGross += metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED].orders.gross_amount;
|
|
172
|
+
}
|
|
173
|
+
expect(count).toBe(totalSales.count);
|
|
174
|
+
expect(round2(gross)).toBe(round2(totalSales.grossAmount));
|
|
175
|
+
expect(collectedCount).toBe(collected.count);
|
|
176
|
+
expect(round2(collectedGross)).toBe(round2(collected.grossAmount));
|
|
177
|
+
});
|
|
178
|
+
it('reproduces the payments breakdown and the money breakdown for the day', () => {
|
|
179
|
+
const reference = (0, sales_overview_reference_1.computeSalesOverviewReference)(allOrders, {
|
|
180
|
+
...DAY_WINDOW,
|
|
181
|
+
tenants: [BASHA],
|
|
182
|
+
groupId: BASHA,
|
|
183
|
+
});
|
|
184
|
+
const cubePayments = new Map();
|
|
185
|
+
let gstAmount = 0;
|
|
186
|
+
let discountAmount = 0;
|
|
187
|
+
let loyaltyDiscount = 0;
|
|
188
|
+
let tipAmount = 0;
|
|
189
|
+
let deliveryCharges = 0;
|
|
190
|
+
let providerCharges = 0;
|
|
191
|
+
for (const [key, metric] of Object.entries(dateDoc.sale_type_metrics ?? {})) {
|
|
192
|
+
if (statusOfKey(key) === constants_1.ORDER_STATUS_ENUM.CANCELLED)
|
|
193
|
+
continue;
|
|
194
|
+
for (const payment of metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments) {
|
|
195
|
+
const entry = cubePayments.get(payment.payment_type) ?? { count: 0, gross_amount: 0 };
|
|
196
|
+
entry.count += payment.count;
|
|
197
|
+
entry.gross_amount += payment.gross_amount;
|
|
198
|
+
cubePayments.set(payment.payment_type, entry);
|
|
199
|
+
}
|
|
200
|
+
const orders = metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders;
|
|
201
|
+
gstAmount += orders.gst_amount;
|
|
202
|
+
discountAmount += orders.discount_amount;
|
|
203
|
+
loyaltyDiscount += orders.discount_by_type.loyalty_discount;
|
|
204
|
+
tipAmount += orders.tip_amount;
|
|
205
|
+
deliveryCharges += orders.delivery_charges;
|
|
206
|
+
providerCharges += orders.tax_invoice_provider_charges;
|
|
207
|
+
}
|
|
208
|
+
const referencePayments = new Map(reference[constants_1.REPORT_TYPE_ENUM.TOTAL_PAYMENT_SALES].map((summary) => [
|
|
209
|
+
summary._id,
|
|
210
|
+
{ count: summary.count, gross_amount: round2(summary.grossAmount) },
|
|
211
|
+
]));
|
|
212
|
+
expect(cubePayments.size).toBe(referencePayments.size);
|
|
213
|
+
for (const [paymentType, expected] of referencePayments) {
|
|
214
|
+
const actual = cubePayments.get(paymentType);
|
|
215
|
+
expect(actual).toBeDefined();
|
|
216
|
+
expect(actual?.count).toBe(expected.count);
|
|
217
|
+
expect(round2(actual?.gross_amount ?? 0)).toBe(expected.gross_amount);
|
|
218
|
+
}
|
|
219
|
+
const nonCancelled = dayOrders.filter((order) => order.is_deleted === false && order.order_status !== constants_1.ORDER_STATUS_ENUM.CANCELLED);
|
|
220
|
+
const sumBy = (selector) => nonCancelled.reduce((total, order) => total + (selector(order) ?? 0), 0);
|
|
221
|
+
expect(gstAmount).toBe(sumBy((order) => order.gst_amount));
|
|
222
|
+
expect(discountAmount).toBe(sumBy((order) => order.total_discount_applied));
|
|
223
|
+
expect(loyaltyDiscount).toBe(sumBy((order) => order.order_discount_details?.loyalty_discount));
|
|
224
|
+
expect(tipAmount).toBe(sumBy((order) => order.tip_amount));
|
|
225
|
+
expect(deliveryCharges).toBe(sumBy((order) => order.delivery_details?.delivery_cost));
|
|
226
|
+
expect(providerCharges).toBe(sumBy((order) => order.tax_invoice_provider_charges));
|
|
227
|
+
});
|
|
228
|
+
it('materializes cancelled orders under their CANCELLED:* keys', () => {
|
|
229
|
+
const reference = (0, sales_overview_reference_1.computeSalesOverviewReference)(allOrders, {
|
|
230
|
+
...DAY_WINDOW,
|
|
231
|
+
tenants: [BASHA],
|
|
232
|
+
groupId: BASHA,
|
|
233
|
+
});
|
|
234
|
+
const referenceCancelled = reference[constants_1.REPORT_TYPE_ENUM.CANCELLED_ORDERS][0];
|
|
235
|
+
let cancelledCount = 0;
|
|
236
|
+
let cancelledGross = 0;
|
|
237
|
+
for (const [key, metric] of Object.entries(dateDoc.sale_type_metrics ?? {})) {
|
|
238
|
+
if (statusOfKey(key) !== constants_1.ORDER_STATUS_ENUM.CANCELLED)
|
|
239
|
+
continue;
|
|
240
|
+
cancelledCount += metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count;
|
|
241
|
+
cancelledGross += metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount;
|
|
242
|
+
}
|
|
243
|
+
expect(cancelledCount).toBe(referenceCancelled?.count ?? 0);
|
|
244
|
+
expect(round2(cancelledGross)).toBe(round2(referenceCancelled?.grossAmount ?? 0));
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
describe('credit-bill lifecycle (synthetic PAY_LATER orders)', () => {
|
|
248
|
+
const ISSUE_DAY = '2026-09-29';
|
|
249
|
+
const issueOrder = makePayLaterOrder({
|
|
250
|
+
orderId: 'order-credit-1',
|
|
251
|
+
localDate: ISSUE_DAY,
|
|
252
|
+
amountDue: 1200,
|
|
253
|
+
amountPaid: 0,
|
|
254
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING,
|
|
255
|
+
settledAt: '2026-09-29T20:10:00.000Z',
|
|
256
|
+
updatedAt: '2026-09-29T20:10:00.000Z',
|
|
257
|
+
});
|
|
258
|
+
const collectedOrder = makePayLaterOrder({
|
|
259
|
+
orderId: 'order-credit-1',
|
|
260
|
+
localDate: ISSUE_DAY,
|
|
261
|
+
amountDue: 1200,
|
|
262
|
+
amountPaid: 1200,
|
|
263
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
|
|
264
|
+
settledAt: '2026-09-30T14:30:00.000Z',
|
|
265
|
+
updatedAt: '2026-09-30T14:30:00.000Z',
|
|
266
|
+
note: 'CN-2026-09-30',
|
|
267
|
+
});
|
|
268
|
+
const issueCompile = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(ISSUE_DAY, [issueOrder], {
|
|
269
|
+
brandId: BRAND,
|
|
270
|
+
}));
|
|
271
|
+
const issueDateDoc = issueCompile.materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
272
|
+
const collectCompile = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(DAY, [collectedOrder], {
|
|
273
|
+
brandId: BRAND,
|
|
274
|
+
}));
|
|
275
|
+
const collectDateDoc = collectCompile.materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
276
|
+
it('records the issued bill on the issue day and keeps the sale there', () => {
|
|
277
|
+
const metrics = getKeyMetrics(issueDateDoc, 'COMPLETED:POS_WALK-IN');
|
|
278
|
+
expect(metrics).toBeDefined();
|
|
279
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(1);
|
|
280
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.count).toBe(1);
|
|
281
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills[0]).toMatchObject({
|
|
282
|
+
order_id: 'order-credit-1',
|
|
283
|
+
payment_id: 'pay-1',
|
|
284
|
+
amount: 1200,
|
|
285
|
+
received_amount: 0,
|
|
286
|
+
settled_at: null,
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
it('anchors issued_at to the punch time, not the later collection time (backfill close)', () => {
|
|
290
|
+
const backfill = makePayLaterOrder({
|
|
291
|
+
orderId: 'order-credit-1',
|
|
292
|
+
localDate: ISSUE_DAY,
|
|
293
|
+
amountDue: 1200,
|
|
294
|
+
amountPaid: 1200,
|
|
295
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
|
|
296
|
+
settledAt: '2026-09-30T14:30:00.000Z',
|
|
297
|
+
updatedAt: '2026-09-30T14:30:00.000Z',
|
|
298
|
+
});
|
|
299
|
+
backfill.createdAt = new Date('2026-09-29T20:10:00.000Z'); // punch time ≠ collection time
|
|
300
|
+
const backfillCompile = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(ISSUE_DAY, [backfill], { brandId: BRAND }));
|
|
301
|
+
const backfillDateDoc = backfillCompile.materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
302
|
+
const bill = getKeyMetrics(backfillDateDoc, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued
|
|
303
|
+
.bills[0];
|
|
304
|
+
expect(bill?.issued_at).toEqual(new Date('2026-09-29T20:10:00.000Z'));
|
|
305
|
+
expect(bill?.settled_at).toEqual(new Date('2026-09-30T14:30:00.000Z'));
|
|
306
|
+
expect(bill?.received_amount).toBe(1200);
|
|
307
|
+
});
|
|
308
|
+
it('compiles the collection day as received_payments only (no sales)', () => {
|
|
309
|
+
expect(collectCompile.received_payments).toHaveLength(1);
|
|
310
|
+
expect(collectCompile.received_payments[0]).toMatchObject({
|
|
311
|
+
order_id: 'order-credit-1',
|
|
312
|
+
payment_id: 'pay-1',
|
|
313
|
+
amount: 1200,
|
|
314
|
+
received_amount: 1200,
|
|
315
|
+
credit_note: 'CN-2026-09-30',
|
|
316
|
+
issued_local_date: ISSUE_DAY,
|
|
317
|
+
});
|
|
318
|
+
const metrics = getKeyMetrics(collectDateDoc, 'COMPLETED:POS_WALK-IN');
|
|
319
|
+
expect(metrics).toBeDefined();
|
|
320
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(0);
|
|
321
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.count).toBe(1);
|
|
322
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received.amount).toBe(1200);
|
|
323
|
+
});
|
|
324
|
+
it('patches the issue-day ledger through updateMaterializedTenantSalesOverviewReport', () => {
|
|
325
|
+
const computedAt = new Date('2026-09-30T23:00:00.000Z');
|
|
326
|
+
const patched = expectNonNull((0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(issueDateDoc, { received_payments: collectCompile.received_payments }, { computedAt }));
|
|
327
|
+
const metrics = getKeyMetrics(patched, 'COMPLETED:POS_WALK-IN');
|
|
328
|
+
const issued = metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued;
|
|
329
|
+
expect(issued?.count).toBe(1);
|
|
330
|
+
expect(issued?.bills[0].received_amount).toBe(1200);
|
|
331
|
+
expect(issued?.bills[0].credit_note).toBe('CN-2026-09-30');
|
|
332
|
+
expect(issued?.bills[0].settled_at).toEqual(new Date('2026-09-30T14:30:00.000Z')); // true collection timestamp (order_settled_at)
|
|
333
|
+
expect(issued?.settled_count).toBe(1);
|
|
334
|
+
expect(issued?.settled_amount).toBe(1200);
|
|
335
|
+
expect(patched.iteration).toBe(2); // ledger changed → versioned write (history row appended by the caller)
|
|
336
|
+
// gross / order numbers stay untouched
|
|
337
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(1200);
|
|
338
|
+
});
|
|
339
|
+
it('derives issued-bill settled-ness from received_amount, not payment_status', () => {
|
|
340
|
+
const paidButPending = makePayLaterOrder({
|
|
341
|
+
orderId: 'order-credit-2',
|
|
342
|
+
localDate: ISSUE_DAY,
|
|
343
|
+
amountDue: 1200,
|
|
344
|
+
amountPaid: 1200,
|
|
345
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING, // fully paid but still PENDING — the rule wins
|
|
346
|
+
settledAt: '2026-09-30T11:00:00.000Z',
|
|
347
|
+
updatedAt: '2026-09-30T11:00:00.000Z',
|
|
348
|
+
});
|
|
349
|
+
const settledButUnderpaid = makePayLaterOrder({
|
|
350
|
+
orderId: 'order-credit-3',
|
|
351
|
+
localDate: ISSUE_DAY,
|
|
352
|
+
amountDue: 1200,
|
|
353
|
+
amountPaid: 400,
|
|
354
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED, // settled status but under-paid — NOT settled
|
|
355
|
+
settledAt: '2026-09-30T11:00:00.000Z',
|
|
356
|
+
updatedAt: '2026-09-30T11:00:00.000Z',
|
|
357
|
+
});
|
|
358
|
+
const settledRuleCompile = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(ISSUE_DAY, [paidButPending, settledButUnderpaid], {
|
|
359
|
+
brandId: BRAND,
|
|
360
|
+
}));
|
|
361
|
+
const settledRuleDoc = settledRuleCompile.materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
362
|
+
const bills = getKeyMetrics(settledRuleDoc, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued
|
|
363
|
+
.bills;
|
|
364
|
+
expect(bills?.find((bill) => bill.order_id === 'order-credit-2')?.settled_at).toEqual(new Date('2026-09-30T11:00:00.000Z'));
|
|
365
|
+
expect(bills?.find((bill) => bill.order_id === 'order-credit-3')?.settled_at).toBeNull();
|
|
366
|
+
});
|
|
367
|
+
it('rejects un-keyable PAY_LATER payments (no payment_id and no subdocument _id)', () => {
|
|
368
|
+
const unkeyable = makePayLaterOrder({
|
|
369
|
+
orderId: 'order-credit-4',
|
|
370
|
+
localDate: ISSUE_DAY,
|
|
371
|
+
amountDue: 500,
|
|
372
|
+
amountPaid: 0,
|
|
373
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING,
|
|
374
|
+
settledAt: '2026-09-29T10:00:00.000Z',
|
|
375
|
+
updatedAt: '2026-09-29T10:00:00.000Z',
|
|
376
|
+
});
|
|
377
|
+
unkeyable.payments[0].payment_id = null;
|
|
378
|
+
expect((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(ISSUE_DAY, [unkeyable], { brandId: BRAND })).toBeNull();
|
|
379
|
+
// With only the subdocument `_id` the bill stays keyable.
|
|
380
|
+
const withSubdocId = makePayLaterOrder({
|
|
381
|
+
orderId: 'order-credit-5',
|
|
382
|
+
localDate: ISSUE_DAY,
|
|
383
|
+
amountDue: 500,
|
|
384
|
+
amountPaid: 0,
|
|
385
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING,
|
|
386
|
+
settledAt: '2026-09-29T10:00:00.000Z',
|
|
387
|
+
updatedAt: '2026-09-29T10:00:00.000Z',
|
|
388
|
+
});
|
|
389
|
+
withSubdocId.payments[0].payment_id = null;
|
|
390
|
+
withSubdocId.payments[0]._id = 'pay-subdoc-1';
|
|
391
|
+
const withIdCompile = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(ISSUE_DAY, [withSubdocId], { brandId: BRAND }));
|
|
392
|
+
const withIdDoc = withIdCompile.materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
393
|
+
const bill = getKeyMetrics(withIdDoc, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued
|
|
394
|
+
.bills[0];
|
|
395
|
+
expect(bill?.payment_id).toBe('pay-subdoc-1');
|
|
396
|
+
});
|
|
397
|
+
it('buckets collection events by the settlement hour, not the punch hour', () => {
|
|
398
|
+
const collectOrder = makePayLaterOrder({
|
|
399
|
+
orderId: 'order-credit-6',
|
|
400
|
+
localDate: ISSUE_DAY,
|
|
401
|
+
amountDue: 900,
|
|
402
|
+
amountPaid: 900,
|
|
403
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
|
|
404
|
+
settledAt: '2026-09-30T07:00:00.000Z', // 12:00 tenant-local (+5) on the collection day
|
|
405
|
+
updatedAt: '2026-09-30T07:00:00.000Z',
|
|
406
|
+
});
|
|
407
|
+
const withOffset = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(DAY, [collectOrder], { brandId: BRAND, gmtOffset: 5 }));
|
|
408
|
+
expect(withOffset.materializedReports
|
|
409
|
+
.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR)
|
|
410
|
+
.map((doc) => doc.scope_field)).toEqual([`${DAY} 12`]);
|
|
411
|
+
// Without gmtOffset the chain falls back to the UTC-mins convention.
|
|
412
|
+
const noOffset = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(DAY, [collectOrder], { brandId: BRAND }));
|
|
413
|
+
expect(noOffset.materializedReports
|
|
414
|
+
.filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR)
|
|
415
|
+
.map((doc) => doc.scope_field)).toEqual([`${DAY} 07`]);
|
|
416
|
+
});
|
|
417
|
+
it('anchors a bill without any timestamps to the compile time (deterministic — no Date.now())', () => {
|
|
418
|
+
const bare = makePayLaterOrder({
|
|
419
|
+
orderId: 'order-credit-7',
|
|
420
|
+
localDate: ISSUE_DAY,
|
|
421
|
+
amountDue: 300,
|
|
422
|
+
amountPaid: 0,
|
|
423
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING,
|
|
424
|
+
settledAt: '2026-09-29T10:00:00.000Z',
|
|
425
|
+
updatedAt: '2026-09-29T10:00:00.000Z',
|
|
426
|
+
});
|
|
427
|
+
bare.createdAt = undefined;
|
|
428
|
+
bare.order_settled_at = undefined;
|
|
429
|
+
bare.order_settled_at_mins = undefined;
|
|
430
|
+
const computedAt = new Date('2026-10-01T03:00:00.000Z');
|
|
431
|
+
const bareCompile = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(ISSUE_DAY, [bare], { brandId: BRAND, computedAt }));
|
|
432
|
+
const bareDoc = bareCompile.materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
433
|
+
const bill = getKeyMetrics(bareDoc, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.bills[0];
|
|
434
|
+
expect(bill?.issued_at).toEqual(computedAt);
|
|
435
|
+
});
|
|
436
|
+
it('converts the JSON document to a mongoose (BSON) document', () => {
|
|
437
|
+
const hydrated = (0, tenant_sales_overview_helpers_1.convertMaterializedTenantSalesOverviewReportJsonToBson)(issueDateDoc);
|
|
438
|
+
expect(hydrated.get('scope_context')).toBe('localDate');
|
|
439
|
+
expect(hydrated.get('sale_type_metrics')).toBeInstanceOf(Map);
|
|
440
|
+
const metrics = hydrated.get('sale_type_metrics');
|
|
441
|
+
const issued = metrics.get('COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued;
|
|
442
|
+
expect(issued?.bills[0].received_amount).toBe(0);
|
|
443
|
+
expect(issued?.bills[0].issued_at).toBeInstanceOf(Date);
|
|
444
|
+
const hydratedCollect = (0, tenant_sales_overview_helpers_1.convertMaterializedTenantSalesOverviewReportJsonToBson)(collectDateDoc);
|
|
445
|
+
const collectedMetrics = hydratedCollect.get('sale_type_metrics');
|
|
446
|
+
const received = collectedMetrics.get('COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received;
|
|
447
|
+
expect(received?.bills[0].received_amount).toBe(1200);
|
|
448
|
+
expect(received?.bills[0].credit_note).toBe('CN-2026-09-30');
|
|
449
|
+
});
|
|
450
|
+
});
|
|
451
|
+
describe('sumMaterializedTenantSalesOverviewReports', () => {
|
|
452
|
+
const makeIssuedBill = (receivedAmount) => ({
|
|
453
|
+
order_id: 'order-1',
|
|
454
|
+
payment_id: 'pay-1',
|
|
455
|
+
amount: 1000,
|
|
456
|
+
received_amount: receivedAmount,
|
|
457
|
+
issued_at: new Date('2026-09-28T10:00:00.000Z'),
|
|
458
|
+
settled_at: null,
|
|
459
|
+
});
|
|
460
|
+
const makeReport = (args) => ({
|
|
461
|
+
_id: 'id',
|
|
462
|
+
tenant_id: 'z2-isb',
|
|
463
|
+
brand_id: BRAND,
|
|
464
|
+
scope_context: args.scopeContext,
|
|
465
|
+
scope_field: args.scopeField,
|
|
466
|
+
day_index: null,
|
|
467
|
+
sale_type_key_filters: [...MATERIALIZED_REPORTS_1.SALES_OVERVIEW_KEY_FILTERS],
|
|
468
|
+
sale_type_metrics: {
|
|
469
|
+
'COMPLETED:POS_WALK-IN': {
|
|
470
|
+
[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: {
|
|
471
|
+
orders: { ...zeroOrderMetric(), count: args.orderCount, gross_amount: args.grossAmount },
|
|
472
|
+
payments: [
|
|
473
|
+
{
|
|
474
|
+
payment_type: 'CASH',
|
|
475
|
+
count: args.orderCount,
|
|
476
|
+
gross_amount: args.grossAmount,
|
|
477
|
+
amount_due: args.grossAmount,
|
|
478
|
+
amount_paid: args.grossAmount,
|
|
479
|
+
amount_refunded: 0,
|
|
480
|
+
card_charges: 0,
|
|
481
|
+
},
|
|
482
|
+
],
|
|
483
|
+
},
|
|
484
|
+
[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]: { orders: zeroOrderMetric(), payments: [] },
|
|
485
|
+
[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: {
|
|
486
|
+
issued: {
|
|
487
|
+
count: 1,
|
|
488
|
+
amount: 1000,
|
|
489
|
+
settled_count: 0,
|
|
490
|
+
settled_amount: args.issuedReceipt,
|
|
491
|
+
bills: [makeIssuedBill(args.issuedReceipt)],
|
|
492
|
+
},
|
|
493
|
+
received: { count: 0, amount: 0, bills: [] },
|
|
494
|
+
},
|
|
495
|
+
},
|
|
496
|
+
},
|
|
497
|
+
schema_version: 1,
|
|
498
|
+
source_watermark: new Date('2026-09-28T10:00:00.000Z'),
|
|
499
|
+
computed_at: new Date('2026-09-28T10:00:00.000Z'),
|
|
500
|
+
createdAt: new Date('2026-09-28T10:00:00.000Z'),
|
|
501
|
+
updatedAt: new Date('2026-09-28T10:00:00.000Z'),
|
|
502
|
+
});
|
|
503
|
+
it('accumulates day documents into the period document (result keeps the period identity)', () => {
|
|
504
|
+
const monthDoc = makeReport({
|
|
505
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
|
|
506
|
+
scopeField: '2026-09',
|
|
507
|
+
orderCount: 0,
|
|
508
|
+
grossAmount: 0,
|
|
509
|
+
issuedReceipt: 0,
|
|
510
|
+
});
|
|
511
|
+
// remove the synthetic bill from the empty month base
|
|
512
|
+
monthDoc.sale_type_metrics = {};
|
|
513
|
+
const dayA = makeReport({
|
|
514
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
515
|
+
scopeField: '2026-09-28',
|
|
516
|
+
orderCount: 2,
|
|
517
|
+
grossAmount: 2000,
|
|
518
|
+
issuedReceipt: 0,
|
|
519
|
+
});
|
|
520
|
+
const dayB = makeReport({
|
|
521
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
522
|
+
scopeField: '2026-09-29',
|
|
523
|
+
orderCount: 3,
|
|
524
|
+
grossAmount: 3000,
|
|
525
|
+
issuedReceipt: 400,
|
|
526
|
+
});
|
|
527
|
+
const merged = expectNonNull((0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)([monthDoc, dayA, dayB]));
|
|
528
|
+
expect(merged.scope_context).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
|
|
529
|
+
expect(merged.scope_field).toBe('2026-09');
|
|
530
|
+
const metrics = getKeyMetrics(merged, 'COMPLETED:POS_WALK-IN');
|
|
531
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(5);
|
|
532
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(5000);
|
|
533
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments[0].gross_amount).toBe(5000);
|
|
534
|
+
// the same bill compiled by both days de-dupes; counters recompute from bills
|
|
535
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.count).toBe(1);
|
|
536
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_amount).toBe(400);
|
|
537
|
+
expect(merged.source_watermark).toEqual(new Date('2026-09-28T10:00:00.000Z'));
|
|
538
|
+
});
|
|
539
|
+
it('returns null for invalid sum inputs (never throws)', () => {
|
|
540
|
+
const base = makeReport({
|
|
541
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
542
|
+
scopeField: '2026-09-28',
|
|
543
|
+
orderCount: 1,
|
|
544
|
+
grossAmount: 100,
|
|
545
|
+
issuedReceipt: 0,
|
|
546
|
+
});
|
|
547
|
+
expect((0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)([])).toBeNull();
|
|
548
|
+
expect((0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)([base, { ...base, tenant_id: 'other' }])).toBeNull();
|
|
549
|
+
expect((0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)([base, { ...base, schema_version: 2 }])).toBeNull();
|
|
550
|
+
expect((0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)([
|
|
551
|
+
base,
|
|
552
|
+
{ ...base, sale_type_key_filters: [MATERIALIZED_REPORTS_1.SALES_OVERVIEW_KEY_FILTERS[1], MATERIALIZED_REPORTS_1.SALES_OVERVIEW_KEY_FILTERS[0]] },
|
|
553
|
+
])).toBeNull();
|
|
554
|
+
});
|
|
555
|
+
});
|
|
556
|
+
describe('empty-day compile + update additions', () => {
|
|
557
|
+
it('emits the period documents with empty metrics for an order-less day', () => {
|
|
558
|
+
const result = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(DAY, [], {
|
|
559
|
+
tenantId: 'z2-isb',
|
|
560
|
+
brandId: BRAND,
|
|
561
|
+
}));
|
|
562
|
+
expect(result.materializedReports).toHaveLength(7);
|
|
563
|
+
expect(result.received_payments).toEqual([]);
|
|
564
|
+
for (const doc of result.materializedReports) {
|
|
565
|
+
expect(doc.sale_type_metrics).toEqual({});
|
|
566
|
+
expect(doc.source_watermark).toBeInstanceOf(Date);
|
|
567
|
+
}
|
|
568
|
+
});
|
|
569
|
+
it('sums additions into the existing document, preserving its identity', () => {
|
|
570
|
+
const emptyDay = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(DAY, [], {
|
|
571
|
+
tenantId: 'z2-isb',
|
|
572
|
+
brandId: BRAND,
|
|
573
|
+
})).materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
574
|
+
const dayDoc = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(DAY, [
|
|
575
|
+
makePayLaterOrder({
|
|
576
|
+
orderId: 'order-update-1',
|
|
577
|
+
localDate: DAY,
|
|
578
|
+
amountDue: 500,
|
|
579
|
+
amountPaid: 500,
|
|
580
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
|
|
581
|
+
settledAt: '2026-09-30T12:00:00.000Z',
|
|
582
|
+
updatedAt: '2026-09-30T12:00:00.000Z',
|
|
583
|
+
}),
|
|
584
|
+
], { brandId: BRAND })).materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
585
|
+
const monthBase = {
|
|
586
|
+
...emptyDay,
|
|
587
|
+
scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
|
|
588
|
+
scope_field: '2026-09',
|
|
589
|
+
};
|
|
590
|
+
const updated = expectNonNull((0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(monthBase, { additions: [dayDoc] }));
|
|
591
|
+
expect(updated.scope_context).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
|
|
592
|
+
expect(updated.scope_field).toBe('2026-09');
|
|
593
|
+
const metrics = getKeyMetrics(updated, 'COMPLETED:POS_WALK-IN');
|
|
594
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(1);
|
|
595
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(500);
|
|
596
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.count).toBe(1);
|
|
597
|
+
});
|
|
598
|
+
});
|
|
599
|
+
describe('null results signal data issues (helpers never throw)', () => {
|
|
600
|
+
it('convert returns null for a malformed localDate', () => {
|
|
601
|
+
expect((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)('2026-9-30', [])).toBeNull();
|
|
602
|
+
expect((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)('', [])).toBeNull();
|
|
603
|
+
});
|
|
604
|
+
it('convert returns null when an order cannot be keyed', () => {
|
|
605
|
+
const order = makePayLaterOrder({
|
|
606
|
+
orderId: 'order-bad-1',
|
|
607
|
+
localDate: DAY,
|
|
608
|
+
amountDue: 100,
|
|
609
|
+
amountPaid: 0,
|
|
610
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING,
|
|
611
|
+
settledAt: '2026-09-30T10:00:00.000Z',
|
|
612
|
+
updatedAt: '2026-09-30T10:00:00.000Z',
|
|
613
|
+
});
|
|
614
|
+
order.platform = '';
|
|
615
|
+
expect((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(DAY, [order], { brandId: BRAND })).toBeNull();
|
|
616
|
+
});
|
|
617
|
+
it('update returns null when additions cannot be summed', () => {
|
|
618
|
+
const compile = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(DAY, [], {
|
|
619
|
+
tenantId: 'z2-isb',
|
|
620
|
+
brandId: BRAND,
|
|
621
|
+
}));
|
|
622
|
+
const existing = compile.materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
623
|
+
expect((0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(existing, {
|
|
624
|
+
additions: [{ ...existing, tenant_id: 'other' }],
|
|
625
|
+
})).toBeNull();
|
|
626
|
+
});
|
|
627
|
+
});
|
|
628
|
+
describe('subtract + versioned reconcile (iteration bump)', () => {
|
|
629
|
+
const report = (args) => ({
|
|
630
|
+
_id: 'id',
|
|
631
|
+
tenant_id: 'z2-isb',
|
|
632
|
+
brand_id: BRAND,
|
|
633
|
+
scope_context: args.scopeContext,
|
|
634
|
+
scope_field: args.scopeField,
|
|
635
|
+
day_index: null,
|
|
636
|
+
sale_type_key_filters: [...MATERIALIZED_REPORTS_1.SALES_OVERVIEW_KEY_FILTERS],
|
|
637
|
+
sale_type_metrics: {
|
|
638
|
+
'COMPLETED:POS_WALK-IN': {
|
|
639
|
+
[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: {
|
|
640
|
+
orders: { ...zeroOrderMetric(), count: args.count, gross_amount: args.gross },
|
|
641
|
+
payments: [
|
|
642
|
+
{
|
|
643
|
+
payment_type: 'CASH',
|
|
644
|
+
count: args.count,
|
|
645
|
+
gross_amount: args.gross,
|
|
646
|
+
amount_due: args.gross,
|
|
647
|
+
amount_paid: args.gross,
|
|
648
|
+
amount_refunded: 0,
|
|
649
|
+
card_charges: 0,
|
|
650
|
+
},
|
|
651
|
+
],
|
|
652
|
+
},
|
|
653
|
+
[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]: { orders: zeroOrderMetric(), payments: [] },
|
|
654
|
+
[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: {
|
|
655
|
+
issued: {
|
|
656
|
+
count: args.billReceived != null ? 1 : 0,
|
|
657
|
+
amount: args.billReceived != null ? 1000 : 0,
|
|
658
|
+
settled_count: 0,
|
|
659
|
+
settled_amount: args.billReceived ?? 0,
|
|
660
|
+
bills: args.billReceived != null
|
|
661
|
+
? [
|
|
662
|
+
{
|
|
663
|
+
order_id: 'order-1',
|
|
664
|
+
payment_id: 'pay-1',
|
|
665
|
+
amount: 1000,
|
|
666
|
+
received_amount: args.billReceived,
|
|
667
|
+
issued_at: new Date('2026-09-28T10:00:00.000Z'),
|
|
668
|
+
settled_at: null,
|
|
669
|
+
},
|
|
670
|
+
]
|
|
671
|
+
: [],
|
|
672
|
+
},
|
|
673
|
+
received: { count: 0, amount: 0, bills: [] },
|
|
674
|
+
},
|
|
675
|
+
},
|
|
676
|
+
},
|
|
677
|
+
schema_version: 1,
|
|
678
|
+
source_watermark: new Date('2026-09-28T10:00:00.000Z'),
|
|
679
|
+
computed_at: new Date('2026-09-28T10:00:00.000Z'),
|
|
680
|
+
createdAt: new Date('2026-09-28T10:00:00.000Z'),
|
|
681
|
+
updatedAt: new Date('2026-09-28T10:00:00.000Z'),
|
|
682
|
+
});
|
|
683
|
+
it('subtracts a report (metrics, payments, bills) and recomputes the ledger', () => {
|
|
684
|
+
const month = report({
|
|
685
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
|
|
686
|
+
scopeField: '2026-09',
|
|
687
|
+
count: 5,
|
|
688
|
+
gross: 5000,
|
|
689
|
+
billReceived: 300,
|
|
690
|
+
});
|
|
691
|
+
const day = report({
|
|
692
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
693
|
+
scopeField: '2026-09-28',
|
|
694
|
+
count: 2,
|
|
695
|
+
gross: 2000,
|
|
696
|
+
billReceived: 300,
|
|
697
|
+
});
|
|
698
|
+
const result = expectNonNull((0, tenant_sales_overview_helpers_1.subtractMaterializedTenantSalesOverviewReports)(month, day));
|
|
699
|
+
const metrics = getKeyMetrics(result, 'COMPLETED:POS_WALK-IN');
|
|
700
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(3);
|
|
701
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(3000);
|
|
702
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].payments[0].count).toBe(3);
|
|
703
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.count).toBe(0); // bill removed
|
|
704
|
+
expect(result.scope_context).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH);
|
|
705
|
+
expect((0, tenant_sales_overview_helpers_1.subtractMaterializedTenantSalesOverviewReports)(month, { ...month, tenant_id: 'other' })).toBeNull();
|
|
706
|
+
});
|
|
707
|
+
it('reconciles a day: subtract the previous delta, add the recalculated one', () => {
|
|
708
|
+
const month = report({
|
|
709
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
|
|
710
|
+
scopeField: '2026-09',
|
|
711
|
+
count: 5,
|
|
712
|
+
gross: 5000,
|
|
713
|
+
billReceived: 300,
|
|
714
|
+
});
|
|
715
|
+
const previousDay = report({
|
|
716
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
717
|
+
scopeField: '2026-09-28',
|
|
718
|
+
count: 2,
|
|
719
|
+
gross: 2000,
|
|
720
|
+
billReceived: 300,
|
|
721
|
+
});
|
|
722
|
+
const nextDay = report({
|
|
723
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
724
|
+
scopeField: '2026-09-28',
|
|
725
|
+
count: 3,
|
|
726
|
+
gross: 2500,
|
|
727
|
+
});
|
|
728
|
+
const reconciled = expectNonNull((0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(month, { subtract: [previousDay], additions: [nextDay] }));
|
|
729
|
+
const metrics = getKeyMetrics(reconciled, 'COMPLETED:POS_WALK-IN');
|
|
730
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(6); // 5 - 2 + 3
|
|
731
|
+
expect(metrics?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.gross_amount).toBe(5500); // 5000 - 2000 + 2500
|
|
732
|
+
expect(reconciled.iteration).toBe(2);
|
|
733
|
+
// The pre-write state stays recoverable through the shared iteration
|
|
734
|
+
// history — one row per structural write (see materialized_tenant_reports_iterations).
|
|
735
|
+
const previousIteration = expectNonNull((0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(month, {
|
|
736
|
+
reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
|
|
737
|
+
reason: 'RECONCILE',
|
|
738
|
+
}));
|
|
739
|
+
expect(getKeyMetrics(previousIteration.snapshot, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders
|
|
740
|
+
.count).toBe(5); // pre-write state
|
|
741
|
+
});
|
|
742
|
+
it('replaces metrics wholesale (day/hour write) and bumps the iteration', () => {
|
|
743
|
+
const existing = report({
|
|
744
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
745
|
+
scopeField: '2026-09-28',
|
|
746
|
+
count: 2,
|
|
747
|
+
gross: 2000,
|
|
748
|
+
});
|
|
749
|
+
const recalculated = report({
|
|
750
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
751
|
+
scopeField: '2026-09-28',
|
|
752
|
+
count: 4,
|
|
753
|
+
gross: 4000,
|
|
754
|
+
});
|
|
755
|
+
const updated = expectNonNull((0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(existing, { replacement: recalculated }));
|
|
756
|
+
expect(getKeyMetrics(updated, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(4);
|
|
757
|
+
expect(updated.scope_context).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
758
|
+
expect(updated.iteration).toBe(2);
|
|
759
|
+
});
|
|
760
|
+
it('versions a ledger-changing received-payment patch (and skips no-op replays)', () => {
|
|
761
|
+
const existing = report({
|
|
762
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
763
|
+
scopeField: '2026-09-28',
|
|
764
|
+
count: 2,
|
|
765
|
+
gross: 2000,
|
|
766
|
+
billReceived: 0,
|
|
767
|
+
});
|
|
768
|
+
const computedAt = new Date('2026-09-30T23:00:00.000Z');
|
|
769
|
+
const patched = expectNonNull((0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(existing, {
|
|
770
|
+
received_payments: [
|
|
771
|
+
{
|
|
772
|
+
order_id: 'order-1',
|
|
773
|
+
payment_id: 'pay-1',
|
|
774
|
+
amount: 1000,
|
|
775
|
+
received_amount: 1000,
|
|
776
|
+
issued_local_date: '2026-09-28',
|
|
777
|
+
},
|
|
778
|
+
],
|
|
779
|
+
}, { computedAt }));
|
|
780
|
+
const issued = getKeyMetrics(patched, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued;
|
|
781
|
+
expect(issued?.bills[0].received_amount).toBe(1000);
|
|
782
|
+
expect(issued?.settled_count).toBe(1);
|
|
783
|
+
expect(issued?.bills[0].settled_at).toEqual(computedAt); // payload has no collection timestamp → falls back to computedAt
|
|
784
|
+
expect(patched.iteration).toBe(2); // ledger changed → versioned write
|
|
785
|
+
expect(patched).not.toHaveProperty('previous_sale_type_metrics'); // history lives in materialized_tenant_reports_iterations
|
|
786
|
+
expect(patched.updatedAt).toEqual(computedAt);
|
|
787
|
+
// Replaying the same collection changes nothing → not versioned.
|
|
788
|
+
const replay = expectNonNull((0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(patched, {
|
|
789
|
+
received_payments: [
|
|
790
|
+
{
|
|
791
|
+
order_id: 'order-1',
|
|
792
|
+
payment_id: 'pay-1',
|
|
793
|
+
amount: 1000,
|
|
794
|
+
received_amount: 1000,
|
|
795
|
+
issued_local_date: '2026-09-28',
|
|
796
|
+
settled_at: new Date('2026-09-30T13:00:00.000Z'),
|
|
797
|
+
},
|
|
798
|
+
],
|
|
799
|
+
}, { computedAt }));
|
|
800
|
+
expect(replay.iteration ?? 1).toBe(2);
|
|
801
|
+
});
|
|
802
|
+
it('keeps a partially collected bill unsettled until received_amount covers the amount', () => {
|
|
803
|
+
const issueDay = '2026-09-29';
|
|
804
|
+
const issueDateDoc = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(issueDay, [
|
|
805
|
+
makePayLaterOrder({
|
|
806
|
+
orderId: 'order-credit-1',
|
|
807
|
+
localDate: issueDay,
|
|
808
|
+
amountDue: 1200,
|
|
809
|
+
amountPaid: 0,
|
|
810
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING,
|
|
811
|
+
settledAt: '2026-09-29T20:10:00.000Z',
|
|
812
|
+
updatedAt: '2026-09-29T20:10:00.000Z',
|
|
813
|
+
}),
|
|
814
|
+
], { brandId: BRAND })).materializedReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
815
|
+
const partial = makePayLaterOrder({
|
|
816
|
+
orderId: 'order-credit-1',
|
|
817
|
+
localDate: issueDay,
|
|
818
|
+
amountDue: 1200,
|
|
819
|
+
amountPaid: 500,
|
|
820
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.PENDING,
|
|
821
|
+
settledAt: '2026-09-30T10:00:00.000Z',
|
|
822
|
+
updatedAt: '2026-09-30T10:00:00.000Z',
|
|
823
|
+
});
|
|
824
|
+
const partialCompile = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(DAY, [partial], { brandId: BRAND }));
|
|
825
|
+
expect(partialCompile.received_payments[0]).toMatchObject({ amount: 1200, received_amount: 500 });
|
|
826
|
+
const partiallyPatched = expectNonNull((0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(issueDateDoc, { received_payments: partialCompile.received_payments }, { computedAt: new Date('2026-09-30T23:00:00.000Z') }));
|
|
827
|
+
const issuedPartial = getKeyMetrics(partiallyPatched, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]
|
|
828
|
+
.issued;
|
|
829
|
+
expect(issuedPartial?.bills[0].received_amount).toBe(500);
|
|
830
|
+
expect(issuedPartial?.bills[0].settled_at).toBeNull(); // 500 < 1200 → not settled
|
|
831
|
+
expect(issuedPartial?.settled_count).toBe(0);
|
|
832
|
+
expect(issuedPartial?.settled_amount).toBe(500);
|
|
833
|
+
// The final installment completes the bill → settled with its true collection timestamp.
|
|
834
|
+
const finalPayment = makePayLaterOrder({
|
|
835
|
+
orderId: 'order-credit-1',
|
|
836
|
+
localDate: issueDay,
|
|
837
|
+
amountDue: 1200,
|
|
838
|
+
amountPaid: 1200,
|
|
839
|
+
paymentStatus: constants_1.PAYMENT_STATUS_ENUM.SETTLED,
|
|
840
|
+
settledAt: '2026-10-01T09:15:00.000Z',
|
|
841
|
+
updatedAt: '2026-10-01T09:15:00.000Z',
|
|
842
|
+
});
|
|
843
|
+
const fullCompile = expectNonNull((0, tenant_sales_overview_helpers_1.convertOrdersToMaterializedTenantSalesOverviewReports)(DAY, [finalPayment], { brandId: BRAND }));
|
|
844
|
+
const fullyPatched = expectNonNull((0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(partiallyPatched, { received_payments: fullCompile.received_payments }, { computedAt: new Date('2026-10-01T23:00:00.000Z') }));
|
|
845
|
+
const issuedFull = getKeyMetrics(fullyPatched, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]
|
|
846
|
+
.issued;
|
|
847
|
+
expect(issuedFull?.bills[0].received_amount).toBe(1200);
|
|
848
|
+
expect(issuedFull?.bills[0].settled_at).toEqual(new Date('2026-10-01T09:15:00.000Z'));
|
|
849
|
+
expect(issuedFull?.settled_count).toBe(1);
|
|
850
|
+
});
|
|
851
|
+
it('normalizes hydrated (mongoose-cast) sale_type_metrics instead of corrupting them', () => {
|
|
852
|
+
const stored = report({
|
|
853
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
|
|
854
|
+
scopeField: '2026-09',
|
|
855
|
+
count: 5,
|
|
856
|
+
gross: 5000,
|
|
857
|
+
});
|
|
858
|
+
// Real hydration shapes: `Model.find()` / json→BSON cast docs carry the Map
|
|
859
|
+
// with mongoose subdocument values; `.toObject()` output keeps them too.
|
|
860
|
+
const hydrated = (0, tenant_sales_overview_helpers_1.convertMaterializedTenantSalesOverviewReportJsonToBson)({
|
|
861
|
+
...stored,
|
|
862
|
+
_id: '68dd3f9c9f1b2c3d4e5f6a7b',
|
|
863
|
+
}).toObject();
|
|
864
|
+
const hydratedFlattened = (0, tenant_sales_overview_helpers_1.convertMaterializedTenantSalesOverviewReportJsonToBson)({
|
|
865
|
+
...stored,
|
|
866
|
+
_id: '68dd3f9c9f1b2c3d4e5f6a7b',
|
|
867
|
+
}).toObject({ flattenMaps: true });
|
|
868
|
+
const dayDelta = report({
|
|
869
|
+
scopeContext: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
870
|
+
scopeField: '2026-09-30',
|
|
871
|
+
count: 1,
|
|
872
|
+
gross: 500,
|
|
873
|
+
});
|
|
874
|
+
for (const hydratedShape of [hydrated, hydratedFlattened]) {
|
|
875
|
+
const updated = expectNonNull((0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(hydratedShape, { additions: [dayDelta] }));
|
|
876
|
+
expect(getKeyMetrics(updated, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(6);
|
|
877
|
+
expect(JSON.stringify(updated)).not.toContain('$__');
|
|
878
|
+
expect(JSON.stringify(updated)).not.toContain('"count":null');
|
|
879
|
+
const summed = expectNonNull((0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)([hydratedShape, dayDelta]));
|
|
880
|
+
expect(getKeyMetrics(summed, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(6);
|
|
881
|
+
const subtracted = expectNonNull((0, tenant_sales_overview_helpers_1.subtractMaterializedTenantSalesOverviewReports)(hydratedShape, dayDelta));
|
|
882
|
+
expect(getKeyMetrics(subtracted, 'COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES].orders.count).toBe(4);
|
|
883
|
+
}
|
|
884
|
+
});
|
|
885
|
+
});
|