@managesome/eposmatic-toolkit 0.4.28 → 0.4.30
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 +9 -12
- package/esm/helpers/materialized-reports/index.js +2 -0
- package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +178 -40
- package/esm/helpers/materialized-reports/materialized-day-input-signature.js +103 -0
- package/esm/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
- package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +299 -227
- package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +20 -1
- package/esm/helpers/materialized-reports/materialized-discount-source-helpers.js +176 -0
- package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +64 -0
- package/esm/helpers/materialized-reports/materialized-integer-contract.js +30 -4
- package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
- package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
- package/esm/helpers/materialized-reports/scope-helpers.js +27 -0
- package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +400 -46
- package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +28 -6
- package/esm/schemas/models/materialized_credit_bills.js +8 -0
- package/esm/schemas/models/materialized_report_drilldown_rows.js +39 -12
- package/esm/schemas/models/materialized_tenant_discount_entries.js +18 -12
- package/esm/schemas/models/materialized_tenant_discount_reports.js +9 -0
- package/esm/schemas/models/materialized_tenant_discount_sources.js +1 -1
- package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
- package/esm/schemas/models/orders.js +5 -0
- package/esm/schemas/models/tenant_active_jobs.js +8 -0
- package/esm/schemas/models/tenant_calendar.js +12 -0
- package/lib/constants/MATERIALIZED_REPORTS.d.ts +9 -12
- package/lib/constants/MATERIALIZED_REPORTS.js +11 -14
- package/lib/helpers/materialized-reports/index.d.ts +2 -0
- package/lib/helpers/materialized-reports/index.js +2 -0
- package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +66 -2
- package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +179 -39
- package/lib/helpers/materialized-reports/materialized-day-input-signature.d.ts +66 -0
- package/lib/helpers/materialized-reports/materialized-day-input-signature.js +108 -0
- package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
- package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +41 -60
- package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +298 -226
- package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.d.ts +4 -4
- package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +19 -0
- package/lib/helpers/materialized-reports/materialized-discount-source-helpers.d.ts +17 -0
- package/lib/helpers/materialized-reports/materialized-discount-source-helpers.js +178 -0
- package/lib/helpers/materialized-reports/materialized-index-bootstrap.d.ts +7 -0
- package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +68 -0
- package/lib/helpers/materialized-reports/materialized-integer-contract.d.ts +3 -1
- package/lib/helpers/materialized-reports/materialized-integer-contract.js +30 -4
- package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.d.ts +2 -2
- package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +4 -2
- package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +7 -0
- package/lib/helpers/materialized-reports/scope-helpers.d.ts +22 -0
- package/lib/helpers/materialized-reports/scope-helpers.js +28 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +49 -3
- package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +398 -44
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +4 -1
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +28 -6
- package/lib/schemas/models/materialized_credit_bills.d.ts +3 -0
- package/lib/schemas/models/materialized_credit_bills.js +8 -0
- package/lib/schemas/models/materialized_report_drilldown_rows.d.ts +40 -6
- package/lib/schemas/models/materialized_report_drilldown_rows.js +39 -12
- package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +33 -29
- package/lib/schemas/models/materialized_tenant_discount_entries.js +18 -12
- package/lib/schemas/models/materialized_tenant_discount_reports.d.ts +3 -0
- package/lib/schemas/models/materialized_tenant_discount_reports.js +9 -0
- package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +6 -6
- package/lib/schemas/models/materialized_tenant_discount_sources.js +1 -1
- package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +3 -0
- package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +9 -0
- package/lib/schemas/models/orders.d.ts +5 -0
- package/lib/schemas/models/orders.js +5 -0
- package/lib/schemas/models/tenant_active_jobs.d.ts +3 -0
- package/lib/schemas/models/tenant_active_jobs.js +8 -0
- package/lib/schemas/models/tenant_calendar.d.ts +13 -0
- package/lib/schemas/models/tenant_calendar.js +13 -1
- package/lib/schemas/types/materialized_credit_bills.d.ts +6 -0
- package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +8 -0
- package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +9 -5
- package/lib/schemas/types/materialized_tenant_discount_reports.d.ts +6 -0
- package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +9 -0
- package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +14 -0
- package/lib/schemas/types/tenant_active_jobs.d.ts +8 -0
- package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +56 -1
- package/lib/tests/materialized-reports/materialized-day-input-signature.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-day-input-signature.test.js +81 -0
- package/lib/tests/materialized-reports/materialized-discount-classification.test.js +17 -0
- package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +148 -53
- package/lib/tests/materialized-reports/materialized-discount-entries-accumulation.test.js +14 -13
- package/lib/tests/materialized-reports/materialized-discount-sources.test.js +76 -0
- package/lib/tests/materialized-reports/materialized-integer-contract.test.js +11 -0
- package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +2 -2
- package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +311 -4
- package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +89 -0
- package/package.json +1 -1
|
@@ -121,24 +121,21 @@ export const SALES_OVERVIEW_KEY_FILTERS = [
|
|
|
121
121
|
/* Discounts report (M1) */
|
|
122
122
|
/* ======================================================================== */
|
|
123
123
|
/**
|
|
124
|
-
* Scopes materialized by `materialized_tenant_discount_reports
|
|
125
|
-
* month-capped set as the credit ledger, for the same reason: the itemized
|
|
126
|
-
* discount rows live in the SIBLING entries collection
|
|
127
|
-
* (`materialized_tenant_discount_entries`), capped at `LOCAL_MONTH` so a
|
|
128
|
-
* document can never grow unboundedly.
|
|
124
|
+
* Scopes materialized by `materialized_tenant_discount_reports`.
|
|
129
125
|
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
136
|
-
* decodes to a wider scope is refused by the historical route
|
|
126
|
+
* Period ENTRY documents are now day-partitioned (`page = source localDate`), so
|
|
127
|
+
* the old 16 MB constraint no longer binds. The scope set intentionally stays
|
|
128
|
+
* at `LOCAL_MONTH` for this change: widening the report surface is a report
|
|
129
|
+
* calculation/API change, not part of the page redesign. The page rule itself is
|
|
130
|
+
* generic and already supports quarter/semester/year if they are enabled.
|
|
131
|
+
* A selection that decodes to a wider scope is refused by the historical route
|
|
137
132
|
* (`allowedScopeContexts`), never silently narrowed to a month.
|
|
138
133
|
*
|
|
139
134
|
* The report documents themselves are COUNTERS ONLY (see
|
|
140
135
|
* `schemas/types/materialized_tenant_discount_reports.ts`).
|
|
141
136
|
*/
|
|
137
|
+
/** Entry-document page key for the day/hour scopes (they are already day-bounded). */
|
|
138
|
+
export const MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL = 'all';
|
|
142
139
|
export const MATERIALIZED_DISCOUNT_REPORT_SCOPES = [
|
|
143
140
|
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
|
|
144
141
|
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export * from './key-helpers';
|
|
2
2
|
export * from './materialized-credit-bills-helpers';
|
|
3
|
+
export * from './materialized-index-bootstrap';
|
|
3
4
|
export * from './materialized-integer-contract';
|
|
4
5
|
export * from './materialized-discount-accumulator-helpers';
|
|
5
6
|
export * from './materialized-discount-classification-helpers';
|
|
@@ -18,6 +19,7 @@ export * from './materialized-delivery-accumulator-helpers';
|
|
|
18
19
|
export * from './materialized-delivery-compile-helpers';
|
|
19
20
|
export * from './materialized-delivery-classification-helpers';
|
|
20
21
|
export * from './materialized-delivery-close-day-helpers';
|
|
22
|
+
export * from './materialized-day-input-signature';
|
|
21
23
|
export * from './materialized-cash-classification-helpers';
|
|
22
24
|
export * from './materialized-cash-close-day-helpers';
|
|
23
25
|
export * from './materialized-cash-compile-helpers';
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import mongoose from 'mongoose';
|
|
2
|
-
import { PAYMENT_TYPE_ENUM } from '../../constants';
|
|
2
|
+
import { PAYMENT_TYPE_ENUM, REPORT_SALE_TYPE_ENUM } from '../../constants';
|
|
3
3
|
import { ALL_MATERIALIZED_REPORT_SCOPES, MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM, MATERIALIZED_REPORT_SCOPE_ENUM, SALES_OVERVIEW_KEY_FILTERS, } from '../../constants/MATERIALIZED_REPORTS';
|
|
4
4
|
import { MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION } from '../../schemas/models/materialized_credit_bills';
|
|
5
5
|
import { getLocalDocumentFields, getLocalFieldsFromLocalDate } from '../utils/time-helpers';
|
|
6
6
|
import { buildMaterializedReportKey } from './key-helpers';
|
|
7
|
+
import { materializedDayInputSignatureChanged } from './materialized-day-input-signature';
|
|
7
8
|
import { getDayIndexFromLocalDate, getMaterializedHourScopeField, getMaterializedPeriodScopeFields, } from './scope-helpers';
|
|
8
9
|
/**
|
|
9
10
|
* The shared credit-bill ledger (`materialized_tenant_credit_bills`) —
|
|
@@ -111,11 +112,11 @@ export function buildCreditBillIssuedCandidatesFromOrder(order, orderLocalDate,
|
|
|
111
112
|
const paymentId = payment.payment_id ?? payment._id ?? null;
|
|
112
113
|
if (paymentId == null || paymentId.length === 0)
|
|
113
114
|
return null; // un-keyable bill — data issue
|
|
114
|
-
// Money is integer CENTS
|
|
115
|
-
//
|
|
116
|
-
//
|
|
117
|
-
const amount =
|
|
118
|
-
const receivedAmount =
|
|
115
|
+
// Money is integer CENTS. Do NOT round here: a fractional source amount is
|
|
116
|
+
// a data defect and the materialized-write integer gate must fail the close
|
|
117
|
+
// loudly, never silently change the ledger.
|
|
118
|
+
const amount = payment.amount_due ?? 0;
|
|
119
|
+
const receivedAmount = payment.amount_paid ?? 0;
|
|
119
120
|
const settled = !settledLater && receivedAmount >= amount;
|
|
120
121
|
candidates.push({
|
|
121
122
|
order_id: order._id,
|
|
@@ -151,7 +152,7 @@ export function buildCreditBillEventCandidatesFromOrder(order, eventLocalDate, o
|
|
|
151
152
|
if (paymentId == null || paymentId.length === 0)
|
|
152
153
|
return null; // un-keyable bill — data issue
|
|
153
154
|
// Money is integer CENTS (see the issued-bill candidate above).
|
|
154
|
-
const receivedAmount =
|
|
155
|
+
const receivedAmount = payment.amount_paid ?? 0;
|
|
155
156
|
if (receivedAmount <= 0)
|
|
156
157
|
continue; // nothing collected yet
|
|
157
158
|
candidates.push({
|
|
@@ -160,7 +161,7 @@ export function buildCreditBillEventCandidatesFromOrder(order, eventLocalDate, o
|
|
|
160
161
|
order_status: order.order_status,
|
|
161
162
|
platform: order.platform,
|
|
162
163
|
// Money is integer CENTS.
|
|
163
|
-
amount:
|
|
164
|
+
amount: payment.amount_due ?? 0,
|
|
164
165
|
issued_at: issuedAt,
|
|
165
166
|
issued_local_date: orderLocalDate,
|
|
166
167
|
issued_local_hour: issuedHourLabel,
|
|
@@ -217,12 +218,12 @@ export function resolveCreditBillDay(input) {
|
|
|
217
218
|
for (const report of input.stored ?? []) {
|
|
218
219
|
if (report == null || report.tenant_id !== tenantId)
|
|
219
220
|
continue;
|
|
220
|
-
for (const [, section] of sectionsOf(report)) {
|
|
221
|
+
for (const [sectionKey, section] of sectionsOf(report)) {
|
|
221
222
|
for (const entry of section?.issued ?? []) {
|
|
222
|
-
const
|
|
223
|
-
const prior = storedIssuedByKey.get(
|
|
224
|
-
if (prior == null || (entry.received_amount ?? 0) > (prior.received_amount ?? 0)) {
|
|
225
|
-
storedIssuedByKey.set(
|
|
223
|
+
const identity = creditBillIdentityKey(entry.order_id, entry.payment_id);
|
|
224
|
+
const prior = storedIssuedByKey.get(identity);
|
|
225
|
+
if (prior == null || (entry.received_amount ?? 0) > (prior.entry.received_amount ?? 0)) {
|
|
226
|
+
storedIssuedByKey.set(identity, { entry, key: sectionKey });
|
|
226
227
|
}
|
|
227
228
|
}
|
|
228
229
|
for (const entry of section?.received ?? []) {
|
|
@@ -243,7 +244,7 @@ export function resolveCreditBillDay(input) {
|
|
|
243
244
|
const key = buildMaterializedReportKey([candidate.order_status, candidate.platform]);
|
|
244
245
|
if (key == null)
|
|
245
246
|
return null; // un-keyable sale-type fields — data issue
|
|
246
|
-
const stored = storedIssuedByKey.get(creditBillIdentityKey(candidate.order_id, candidate.payment_id));
|
|
247
|
+
const stored = storedIssuedByKey.get(creditBillIdentityKey(candidate.order_id, candidate.payment_id))?.entry;
|
|
247
248
|
issued.push({
|
|
248
249
|
key,
|
|
249
250
|
source_watermark: candidate.source_watermark,
|
|
@@ -264,12 +265,14 @@ export function resolveCreditBillDay(input) {
|
|
|
264
265
|
}
|
|
265
266
|
const received_events = [];
|
|
266
267
|
const settled_bills = [];
|
|
268
|
+
const receipt_bills = [];
|
|
267
269
|
for (const candidate of input.events ?? []) {
|
|
268
270
|
const key = buildMaterializedReportKey([candidate.order_status, candidate.platform]);
|
|
269
271
|
if (key == null)
|
|
270
272
|
return null; // un-keyable sale-type fields — data issue
|
|
271
273
|
const identity = creditBillIdentityKey(candidate.order_id, candidate.payment_id);
|
|
272
|
-
const
|
|
274
|
+
const storedIssuedRecord = storedIssuedByKey.get(identity) ?? null;
|
|
275
|
+
const storedIssued = storedIssuedRecord?.entry ?? null;
|
|
273
276
|
const storedEvent = storedReceivedByKey.get(`${identity}|${candidate.event.event_local_date}`) ?? null;
|
|
274
277
|
let delta;
|
|
275
278
|
let cumulativeAfter;
|
|
@@ -319,11 +322,15 @@ export function resolveCreditBillDay(input) {
|
|
|
319
322
|
});
|
|
320
323
|
// The issue scopes must be patched exactly once per settlement — only
|
|
321
324
|
// for EARLIER issue days (a same-day settlement rides the issued payload).
|
|
322
|
-
|
|
325
|
+
// The section key comes from the STORED entry, not the current order
|
|
326
|
+
// status/platform: an order may move PLACED -> COMPLETED between issue and
|
|
327
|
+
// collection, and the issue documents remain under the old key.
|
|
328
|
+
if (storedIssued != null && candidate.issued_local_date !== localDate) {
|
|
323
329
|
const alreadySettled = storedIssued.settled_at != null || storedIssued.settled_local_date != null;
|
|
324
|
-
if (!alreadySettled) {
|
|
330
|
+
if (settled && !alreadySettled) {
|
|
325
331
|
settled_bills.push({
|
|
326
332
|
key,
|
|
333
|
+
stored_key: storedIssuedRecord?.key ?? null,
|
|
327
334
|
order_id: candidate.order_id,
|
|
328
335
|
payment_id: candidate.payment_id,
|
|
329
336
|
amount,
|
|
@@ -335,12 +342,119 @@ export function resolveCreditBillDay(input) {
|
|
|
335
342
|
issued_local_hour: storedIssued.issued_local_hour ?? candidate.issued_local_hour ?? null,
|
|
336
343
|
});
|
|
337
344
|
}
|
|
345
|
+
else if (!settled && (storedIssued.received_amount ?? 0) < cumulativeAfter) {
|
|
346
|
+
// PARTIAL receipt: update the SAME bill's cumulative received_amount so
|
|
347
|
+
// outstanding_now reflects every installment, not only the final one.
|
|
348
|
+
receipt_bills.push({
|
|
349
|
+
key,
|
|
350
|
+
stored_key: storedIssuedRecord?.key ?? null,
|
|
351
|
+
order_id: candidate.order_id,
|
|
352
|
+
payment_id: candidate.payment_id,
|
|
353
|
+
amount,
|
|
354
|
+
received_amount: cumulativeAfter,
|
|
355
|
+
credit_note: candidate.event.credit_note ?? storedIssued.credit_note ?? null,
|
|
356
|
+
issued_local_date: candidate.issued_local_date,
|
|
357
|
+
issued_local_hour: storedIssued.issued_local_hour ?? candidate.issued_local_hour ?? null,
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return { issued, received_events, settled_bills, receipt_bills };
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Applies one day's credit resolution to the compiled Overview documents:
|
|
366
|
+
* overwrites each key's received counters from the resolved event deltas and
|
|
367
|
+
* its issued settled counters from the stored anchors. Shared by the close-day
|
|
368
|
+
* plan and the LIVE Overview adapter so both use one rule.
|
|
369
|
+
*/
|
|
370
|
+
export function applyCreditResolutionToReportDocuments(reports, resolution) {
|
|
371
|
+
const receivedByScopeKey = new Map();
|
|
372
|
+
for (const resolved of resolution.received_events) {
|
|
373
|
+
const delta = resolved.entry.received_delta ?? 0;
|
|
374
|
+
for (const doc of reports) {
|
|
375
|
+
if (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
376
|
+
doc.scope_field !== resolved.entry.event_local_hour) {
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
const mapKey = doc.scope_context + '|' + doc.scope_field + '|' + resolved.key;
|
|
380
|
+
const entry = receivedByScopeKey.get(mapKey) ?? { count: 0, amount: 0 };
|
|
381
|
+
entry.count += 1;
|
|
382
|
+
entry.amount += delta;
|
|
383
|
+
receivedByScopeKey.set(mapKey, entry);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
for (const doc of reports) {
|
|
387
|
+
const metrics = doc.sale_type_metrics;
|
|
388
|
+
for (const [key, metric] of Object.entries(metrics ?? {})) {
|
|
389
|
+
const entry = receivedByScopeKey.get(doc.scope_context + '|' + doc.scope_field + '|' + key);
|
|
390
|
+
metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received = entry != null ? { ...entry } : { count: 0, amount: 0 };
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
const settledByKey = new Map();
|
|
394
|
+
for (const resolved of resolution.issued) {
|
|
395
|
+
const entry = resolved.entry;
|
|
396
|
+
if (entry.settled_at == null && entry.settled_local_date == null)
|
|
397
|
+
continue;
|
|
398
|
+
const totals = settledByKey.get(resolved.key) ?? { count: 0, amount: 0 };
|
|
399
|
+
totals.count += 1;
|
|
400
|
+
totals.amount += entry.amount ?? 0;
|
|
401
|
+
settledByKey.set(resolved.key, totals);
|
|
402
|
+
}
|
|
403
|
+
for (const doc of reports) {
|
|
404
|
+
const metrics = doc.sale_type_metrics;
|
|
405
|
+
for (const [key, metric] of Object.entries(metrics ?? {})) {
|
|
406
|
+
const entry = settledByKey.get(key);
|
|
407
|
+
metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_count = entry?.count ?? 0;
|
|
408
|
+
metric[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_amount = entry?.amount ?? 0;
|
|
338
409
|
}
|
|
339
410
|
}
|
|
340
|
-
|
|
411
|
+
const collectedAtIssue = {};
|
|
412
|
+
for (const resolved of resolution.issued) {
|
|
413
|
+
const atIssue = resolved.entry.received_at_issue ?? 0;
|
|
414
|
+
if (atIssue <= 0)
|
|
415
|
+
continue;
|
|
416
|
+
const totals = collectedAtIssue[resolved.key] ?? { count: 0, amount: 0 };
|
|
417
|
+
totals.count += 1;
|
|
418
|
+
totals.amount += atIssue;
|
|
419
|
+
collectedAtIssue[resolved.key] = totals;
|
|
420
|
+
}
|
|
421
|
+
return { collected_at_issue: collectedAtIssue };
|
|
341
422
|
}
|
|
342
423
|
const emptySection = () => ({ issued: [], received: [] });
|
|
343
424
|
const sectionFor = (map, key) => map[key] ?? (map[key] = emptySection());
|
|
425
|
+
/**
|
|
426
|
+
* Folds `source` sections INTO `target` (mutating it), identity-matched:
|
|
427
|
+
* an ISSUED entry is one `(order_id, payment_id)` bill; a RECEIVED entry is one
|
|
428
|
+
* `(order_id, payment_id, event_local_date)` collection event. A source entry
|
|
429
|
+
* REPLACES its target counterpart (fresh wins), so re-applying the same day is
|
|
430
|
+
* idempotent.
|
|
431
|
+
*
|
|
432
|
+
* Exported because the close-day plan uses the SAME merge when it rebuilds a
|
|
433
|
+
* MISSING period document from the stored day documents (a deleted period
|
|
434
|
+
* document must not be recreated from the closing day alone; see
|
|
435
|
+
* `buildTenantSalesOverviewCloseDayPlan`'s period repair).
|
|
436
|
+
*/
|
|
437
|
+
export function mergeMaterializedCreditBillSections(target, source) {
|
|
438
|
+
for (const [key, section] of Object.entries(source ?? {})) {
|
|
439
|
+
const bucket = target[key] ?? (target[key] = emptySection());
|
|
440
|
+
for (const entry of section?.issued ?? []) {
|
|
441
|
+
const identity = creditBillIdentityKey(entry.order_id, entry.payment_id);
|
|
442
|
+
const index = bucket.issued.findIndex((current) => creditBillIdentityKey(current.order_id, current.payment_id) === identity);
|
|
443
|
+
if (index >= 0)
|
|
444
|
+
bucket.issued[index] = entry;
|
|
445
|
+
else
|
|
446
|
+
bucket.issued.push(entry);
|
|
447
|
+
}
|
|
448
|
+
for (const entry of section?.received ?? []) {
|
|
449
|
+
const identity = `${creditBillIdentityKey(entry.order_id, entry.payment_id)}|${entry.event_local_date}`;
|
|
450
|
+
const index = bucket.received.findIndex((current) => `${creditBillIdentityKey(current.order_id, current.payment_id)}|${current.event_local_date}` === identity);
|
|
451
|
+
if (index >= 0)
|
|
452
|
+
bucket.received[index] = entry;
|
|
453
|
+
else
|
|
454
|
+
bucket.received.push(entry);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
344
458
|
/**
|
|
345
459
|
* Materializes ONE day's credit documents from its resolution — the
|
|
346
460
|
* month-capped scope set (`MATERIALIZED_CREDIT_BILLS_SCOPES`): one document per
|
|
@@ -351,6 +465,7 @@ export function buildMaterializedCreditBillDayReports(input) {
|
|
|
351
465
|
if (input == null)
|
|
352
466
|
return null;
|
|
353
467
|
const { tenantId, brandId, localDate, resolution, computedAt } = input;
|
|
468
|
+
const sourceInputSignature = input.sourceInputSignature ?? undefined;
|
|
354
469
|
const periodFields = getMaterializedPeriodScopeFields(localDate);
|
|
355
470
|
if (periodFields == null)
|
|
356
471
|
return null;
|
|
@@ -420,6 +535,7 @@ export function buildMaterializedCreditBillDayReports(input) {
|
|
|
420
535
|
iteration: 1,
|
|
421
536
|
schema_version: MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION,
|
|
422
537
|
source_watermark: sourceWatermark,
|
|
538
|
+
source_input_signature: sourceInputSignature,
|
|
423
539
|
computed_at: computedAt,
|
|
424
540
|
createdAt: computedAt,
|
|
425
541
|
updatedAt: computedAt,
|
|
@@ -520,33 +636,21 @@ export function updateMaterializedCreditBillsReport(existing, updates, options =
|
|
|
520
636
|
}
|
|
521
637
|
}
|
|
522
638
|
for (const delta of updates.additions ?? []) {
|
|
523
|
-
|
|
524
|
-
const target = sections[key] ?? (sections[key] = emptySection());
|
|
525
|
-
for (const entry of section.issued) {
|
|
526
|
-
const identity = creditBillIdentityKey(entry.order_id, entry.payment_id);
|
|
527
|
-
const index = target.issued.findIndex((current) => creditBillIdentityKey(current.order_id, current.payment_id) === identity);
|
|
528
|
-
if (index >= 0)
|
|
529
|
-
target.issued[index] = entry;
|
|
530
|
-
else
|
|
531
|
-
target.issued.push(entry);
|
|
532
|
-
}
|
|
533
|
-
for (const entry of section.received) {
|
|
534
|
-
const identity = `${creditBillIdentityKey(entry.order_id, entry.payment_id)}|${entry.event_local_date}`;
|
|
535
|
-
const index = target.received.findIndex((current) => `${creditBillIdentityKey(current.order_id, current.payment_id)}|${current.event_local_date}` === identity);
|
|
536
|
-
if (index >= 0)
|
|
537
|
-
target.received[index] = entry;
|
|
538
|
-
else
|
|
539
|
-
target.received.push(entry);
|
|
540
|
-
}
|
|
541
|
-
}
|
|
639
|
+
mergeMaterializedCreditBillSections(sections, toMutableSections(delta.credit_bills));
|
|
542
640
|
}
|
|
543
641
|
for (const delta of updates.additions ?? []) {
|
|
544
642
|
sourceWatermark = maxDate(sourceWatermark, delta.source_watermark) ?? sourceWatermark;
|
|
545
643
|
}
|
|
546
644
|
}
|
|
645
|
+
/** Find the issue section by the stored key (status drift), then fall back to the current key. */
|
|
646
|
+
const findIssueTarget = (key, storedKey) => {
|
|
647
|
+
if (storedKey != null && sections[storedKey] != null)
|
|
648
|
+
return sections[storedKey];
|
|
649
|
+
return sections[key] ?? null;
|
|
650
|
+
};
|
|
547
651
|
let ledgerPatched = false;
|
|
548
652
|
for (const settlement of updates.settled_bills ?? []) {
|
|
549
|
-
const target =
|
|
653
|
+
const target = findIssueTarget(settlement.key, settlement.stored_key);
|
|
550
654
|
if (target == null)
|
|
551
655
|
continue;
|
|
552
656
|
const index = target.issued.findIndex((entry) => creditBillIdentityKey(entry.order_id, entry.payment_id) ===
|
|
@@ -565,12 +669,38 @@ export function updateMaterializedCreditBillsReport(existing, updates, options =
|
|
|
565
669
|
};
|
|
566
670
|
ledgerPatched = true;
|
|
567
671
|
}
|
|
672
|
+
// Partial receipts update the SAME issue entry's cumulative amount. They are
|
|
673
|
+
// not new bills and never create a second receivable.
|
|
674
|
+
for (const receipt of updates.receipt_bills ?? []) {
|
|
675
|
+
const target = findIssueTarget(receipt.key, receipt.stored_key);
|
|
676
|
+
if (target == null)
|
|
677
|
+
continue;
|
|
678
|
+
const index = target.issued.findIndex((entry) => creditBillIdentityKey(entry.order_id, entry.payment_id) ===
|
|
679
|
+
creditBillIdentityKey(receipt.order_id, receipt.payment_id));
|
|
680
|
+
if (index < 0)
|
|
681
|
+
continue;
|
|
682
|
+
const entry = target.issued[index];
|
|
683
|
+
if ((entry.received_amount ?? 0) >= receipt.received_amount)
|
|
684
|
+
continue; // idempotent
|
|
685
|
+
target.issued[index] = {
|
|
686
|
+
...entry,
|
|
687
|
+
received_amount: receipt.received_amount,
|
|
688
|
+
credit_note: receipt.credit_note ?? entry.credit_note ?? null,
|
|
689
|
+
};
|
|
690
|
+
ledgerPatched = true;
|
|
691
|
+
}
|
|
568
692
|
const pruned = pruneSections(sections);
|
|
569
693
|
const changed = serializeSections(pruned) !== serializeSections(toMutableSections(existing.credit_bills));
|
|
694
|
+
const envelopeChanged = (updates.replacement != null &&
|
|
695
|
+
(updates.replacement.source_input_signature ?? null) !== (existing.source_input_signature ?? null)) ||
|
|
696
|
+
new Date(sourceWatermark).getTime() > new Date(existing.source_watermark).getTime();
|
|
570
697
|
return {
|
|
571
698
|
...existing,
|
|
572
699
|
credit_bills: pruned,
|
|
573
|
-
iteration: (existing.iteration ?? 1) + (changed || ledgerPatched ? 1 : 0),
|
|
700
|
+
iteration: (existing.iteration ?? 1) + (changed || ledgerPatched || envelopeChanged ? 1 : 0),
|
|
701
|
+
// A REPLACEMENT carries the freshly compiled day digest; period folds keep
|
|
702
|
+
// the stored value (their payload is a running ledger, not one day's input).
|
|
703
|
+
source_input_signature: updates.replacement?.source_input_signature ?? existing.source_input_signature,
|
|
574
704
|
source_watermark: sourceWatermark,
|
|
575
705
|
computed_at: computedAt,
|
|
576
706
|
updatedAt: computedAt,
|
|
@@ -596,7 +726,12 @@ const creditPeriodRefs = (localDate) => {
|
|
|
596
726
|
},
|
|
597
727
|
];
|
|
598
728
|
};
|
|
599
|
-
/**
|
|
729
|
+
/**
|
|
730
|
+
* `Writes the watermarks / day-input signature / schema / key-filter grammar
|
|
731
|
+
* allow a write?` (mirrors the sales-report guard). The signature is checked
|
|
732
|
+
* FIRST so a deleted / moved order still corrects the ledger when the incoming
|
|
733
|
+
* watermark regressed.
|
|
734
|
+
*/
|
|
600
735
|
export const needsMaterializedCreditBillsReportWrite = (existing, incoming) => {
|
|
601
736
|
if (existing == null)
|
|
602
737
|
return true;
|
|
@@ -605,6 +740,9 @@ export const needsMaterializedCreditBillsReportWrite = (existing, incoming) => {
|
|
|
605
740
|
if (JSON.stringify(existing.sale_type_key_filters ?? []) !== JSON.stringify(incoming.sale_type_key_filters ?? [])) {
|
|
606
741
|
return true;
|
|
607
742
|
}
|
|
743
|
+
if (materializedDayInputSignatureChanged(existing.source_input_signature, incoming.source_input_signature)) {
|
|
744
|
+
return true;
|
|
745
|
+
}
|
|
608
746
|
return new Date(incoming.source_watermark).getTime() > new Date(existing.source_watermark).getTime();
|
|
609
747
|
};
|
|
610
748
|
/**
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Day-input SIGNATURE — the change-detection token of a materialized day.
|
|
3
|
+
*
|
|
4
|
+
* ## Why a watermark alone is not enough
|
|
5
|
+
*
|
|
6
|
+
* Every report document stores `source_watermark` = the MAX `orders.updatedAt`
|
|
7
|
+
* folded into it, and the close-day plans skip a document when the incoming
|
|
8
|
+
* watermark is not NEWER than the stored one. That is sound for an UPDATE of an
|
|
9
|
+
* order (its `updatedAt` advances), but it is blind to the order set SHRINKING:
|
|
10
|
+
*
|
|
11
|
+
* - delete the order that carried the maximum `updatedAt`, then re-close the
|
|
12
|
+
* day → the incoming max is LOWER than the stored watermark, the guard
|
|
13
|
+
* reports "nothing new", and the deleted order stays in every report
|
|
14
|
+
* (date/hour/period/credit/discount) forever;
|
|
15
|
+
* - move that order to another `localDate` → same regression on the old day,
|
|
16
|
+
* so the old day keeps a sale it no longer owns.
|
|
17
|
+
*
|
|
18
|
+
* The fix is a SECOND, set-shaped signal: a deterministic digest of the exact
|
|
19
|
+
* order identities (and their versions) the day was compiled from. A delete or
|
|
20
|
+
* a move changes the digest even when the watermark regresses, so the guard can
|
|
21
|
+
* trigger the corrective writes. A re-close of the SAME input reproduces the
|
|
22
|
+
* same digest, so the no-churn skip is preserved.
|
|
23
|
+
*
|
|
24
|
+
* ## Shape
|
|
25
|
+
*
|
|
26
|
+
* `v1:<count>:<hash>` where
|
|
27
|
+
* - `count` is the number of orders in the input (cheap first check);
|
|
28
|
+
* - `hash` is two independent 32-bit FNV-1a passes over the sorted
|
|
29
|
+
* `id|updatedAt` lines, emitted as 16 hex chars (a ~64-bit digest).
|
|
30
|
+
*
|
|
31
|
+
* The leading `v1:` version tag makes the value a non-numeric string, which
|
|
32
|
+
* keeps it outside the integer-only storage contract's numeric-string rule; a
|
|
33
|
+
* future algorithm change must bump the tag so old documents are re-materialized
|
|
34
|
+
* exactly once instead of being silently compared with a different digest.
|
|
35
|
+
*
|
|
36
|
+
* The digest is NOT a security primitive — it detects accidental divergence,
|
|
37
|
+
* and a full re-close always repairs the document regardless.
|
|
38
|
+
*/
|
|
39
|
+
/** Version tag of the digest algorithm; bump when the line format changes. */
|
|
40
|
+
export const MATERIALIZED_DAY_INPUT_SIGNATURE_VERSION = 'v1';
|
|
41
|
+
/** One stable line per order: identity + the version that produced its numbers. */
|
|
42
|
+
const signatureLine = (order) => {
|
|
43
|
+
const id = order._id == null ? '' : String(order._id);
|
|
44
|
+
const updatedAt = order.updatedAt == null ? '' : new Date(order.updatedAt).toISOString();
|
|
45
|
+
return `${id}|${updatedAt}`;
|
|
46
|
+
};
|
|
47
|
+
/** Two independent FNV-1a 32-bit passes over `value`, as 16 hex chars. */
|
|
48
|
+
const hashSignatureLines = (value) => {
|
|
49
|
+
let first = 0x811c9dc5;
|
|
50
|
+
let second = 0x01000193 ^ 0x9e3779b9;
|
|
51
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
52
|
+
const code = value.charCodeAt(index);
|
|
53
|
+
first ^= code;
|
|
54
|
+
first = Math.imul(first, 0x01000193) >>> 0;
|
|
55
|
+
second = Math.imul(second ^ code, 0x85ebca6b) >>> 0;
|
|
56
|
+
second = (second ^ (second >>> 13)) >>> 0;
|
|
57
|
+
}
|
|
58
|
+
return `${first.toString(16).padStart(8, '0')}${second.toString(16).padStart(8, '0')}`;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Builds the day-input signature for the orders a materializer compiled.
|
|
62
|
+
*
|
|
63
|
+
* The caller passes the SAME array the compile used (and the same tenant
|
|
64
|
+
* filter); the digest is order-independent (lines are sorted) and idempotent
|
|
65
|
+
* (identical input → identical value). An empty input yields the stable
|
|
66
|
+
* `v1:0:<hash of ''>` value, which is deliberately DIFFERENT from "no stored
|
|
67
|
+
* signature" (`undefined`) — a legacy document with no signature is therefore
|
|
68
|
+
* rewritten once, and an order-less day keeps skipping on later re-closes.
|
|
69
|
+
*
|
|
70
|
+
* Returns `null` (never throws) when the input is not an array.
|
|
71
|
+
*/
|
|
72
|
+
export function buildMaterializedDayInputSignature(orders) {
|
|
73
|
+
if (!Array.isArray(orders))
|
|
74
|
+
return null;
|
|
75
|
+
const lines = [];
|
|
76
|
+
for (const order of orders) {
|
|
77
|
+
if (order == null)
|
|
78
|
+
continue;
|
|
79
|
+
lines.push(signatureLine(order));
|
|
80
|
+
}
|
|
81
|
+
lines.sort();
|
|
82
|
+
return `${MATERIALIZED_DAY_INPUT_SIGNATURE_VERSION}:${lines.length}:${hashSignatureLines(lines.join('\n'))}`;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Does a stored / incoming signature pair require a write?
|
|
86
|
+
*
|
|
87
|
+
* - BOTH missing → `false`: neither side describes an input set (legacy
|
|
88
|
+
* fixtures / documents), so the watermark guard decides — exactly the
|
|
89
|
+
* pre-signature behaviour;
|
|
90
|
+
* - exactly ONE missing → `true`: a legacy stored document meets a compiled
|
|
91
|
+
* day (or the reverse), so the corrective write happens once;
|
|
92
|
+
* - different values → `true` (the input SET changed, e.g. a delete or move);
|
|
93
|
+
* - identical → `false` (the watermark guard then decides).
|
|
94
|
+
*/
|
|
95
|
+
export const materializedDayInputSignatureChanged = (stored, incoming) => {
|
|
96
|
+
const storedMissing = typeof stored !== 'string';
|
|
97
|
+
const incomingMissing = typeof incoming !== 'string';
|
|
98
|
+
if (storedMissing && incomingMissing)
|
|
99
|
+
return false;
|
|
100
|
+
if (storedMissing || incomingMissing)
|
|
101
|
+
return true;
|
|
102
|
+
return stored !== incoming;
|
|
103
|
+
};
|
|
@@ -139,13 +139,20 @@ export function resolveRowMoney(details, rowTotal) {
|
|
|
139
139
|
return { perSlot, row_total: total, allocated: resolved, unallocated: Math.max(0, total - resolved) };
|
|
140
140
|
}
|
|
141
141
|
// Several active slots (allocated offers): every slot is a FIXED amount when
|
|
142
|
-
// more than one is active in practice
|
|
143
|
-
//
|
|
142
|
+
// more than one is active in practice. Allocate in slot order against the
|
|
143
|
+
// headline, EXACTLY like a single fixed slot: a slot can never contribute
|
|
144
|
+
// more than the remaining discount. This prevents 500 + 300 against a 600
|
|
145
|
+
// headline from emitting 800 of entry money while the report total is 600.
|
|
144
146
|
let allocated = 0;
|
|
145
147
|
for (const reading of readings) {
|
|
146
148
|
if (reading.is_percentage)
|
|
147
149
|
continue; // a % mixed with other slots is unsplittable
|
|
148
|
-
const
|
|
150
|
+
const remaining = Math.max(0, total - allocated);
|
|
151
|
+
if (remaining <= 0)
|
|
152
|
+
break;
|
|
153
|
+
const value = Math.min(Math.max(0, reading.rate), remaining);
|
|
154
|
+
if (value <= 0)
|
|
155
|
+
continue;
|
|
149
156
|
perSlot.set(reading.slot, value);
|
|
150
157
|
allocated += value;
|
|
151
158
|
}
|