@managesome/eposmatic-toolkit 0.4.7 → 0.4.9
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 +33 -0
- package/esm/constants/enums/communications.js +1 -0
- package/esm/helpers/materialized-reports/index.js +1 -0
- package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +982 -0
- package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +276 -33
- package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +327 -41
- package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
- package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +118 -235
- package/esm/schemas/models/index.js +1 -0
- package/esm/schemas/models/materialized_credit_bills.js +265 -0
- package/esm/schemas/models/materialized_tenant_reports_iterations.js +13 -0
- package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +39 -97
- package/esm/schemas/types/index.js +1 -0
- package/esm/schemas/types/materialized_credit_bills.js +1 -0
- package/lib/constants/MATERIALIZED_REPORTS.d.ts +28 -2
- package/lib/constants/MATERIALIZED_REPORTS.js +34 -1
- package/lib/constants/enums/communications.d.ts +1 -0
- package/lib/constants/enums/communications.js +2 -1
- package/lib/helpers/materialized-reports/index.d.ts +1 -0
- package/lib/helpers/materialized-reports/index.js +1 -0
- package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +307 -0
- package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +1003 -0
- package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +36 -2
- package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +278 -34
- package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +66 -8
- package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +326 -40
- package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +18 -2
- package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +46 -37
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +119 -238
- package/lib/helpers/types/materialized-reports-apis.d.ts +32 -5
- package/lib/schemas/models/index.d.ts +1 -0
- package/lib/schemas/models/index.js +1 -0
- package/lib/schemas/models/materialized_credit_bills.d.ts +337 -0
- package/lib/schemas/models/materialized_credit_bills.js +268 -0
- package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +20 -6
- package/lib/schemas/models/materialized_tenant_reports_iterations.js +14 -1
- package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +37 -165
- package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +40 -98
- package/lib/schemas/types/index.d.ts +1 -0
- package/lib/schemas/types/index.js +1 -0
- package/lib/schemas/types/materialized_credit_bills.d.ts +139 -0
- package/lib/schemas/types/materialized_credit_bills.js +2 -0
- package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +32 -77
- package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +715 -0
- package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +96 -0
- package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +9 -0
- package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +23 -24
- package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +327 -22
- package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +27 -2
- package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +12 -27
- package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +79 -146
- package/package.json +1 -1
|
@@ -5,6 +5,7 @@ exports.needsMaterializedTenantSalesOverviewReportWrite = needsMaterializedTenan
|
|
|
5
5
|
exports.buildTenantSalesOverviewCloseDayPlan = buildTenantSalesOverviewCloseDayPlan;
|
|
6
6
|
const constants_1 = require("../../constants");
|
|
7
7
|
const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
|
|
8
|
+
const materialized_credit_bills_helpers_1 = require("./materialized-credit-bills-helpers");
|
|
8
9
|
const materialized_tenant_reports_iterations_helpers_1 = require("./materialized-tenant-reports-iterations-helpers");
|
|
9
10
|
const scope_helpers_1 = require("./scope-helpers");
|
|
10
11
|
const tenant_sales_overview_helpers_1 = require("./tenant-sales-overview-helpers");
|
|
@@ -23,7 +24,6 @@ const CLOSE_DAY_ACCUMULATED_SCOPES = [
|
|
|
23
24
|
MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
|
|
24
25
|
];
|
|
25
26
|
const materializedScopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
|
|
26
|
-
const materializedCreditBillKey = (orderId, paymentId) => `${orderId}|${paymentId}`;
|
|
27
27
|
const hasMaterializedMetrics = (doc) => Object.keys((0, tenant_sales_overview_helpers_1.normalizeMaterializedSaleTypeMetrics)(doc.sale_type_metrics)).length > 0;
|
|
28
28
|
/**
|
|
29
29
|
* Every stored scope the fan-out of one local day needs: the six period
|
|
@@ -73,27 +73,6 @@ function needsMaterializedTenantSalesOverviewReportWrite(existing, incoming) {
|
|
|
73
73
|
return true;
|
|
74
74
|
return incomingTime > existingTime;
|
|
75
75
|
}
|
|
76
|
-
/** Would a received-payment patch change the stored bill? (settlement/note/received) */
|
|
77
|
-
const creditBillWouldChange = (bill, collected) => {
|
|
78
|
-
const received = Math.max(bill.received_amount ?? 0, collected.received_amount ?? 0);
|
|
79
|
-
if (received !== (bill.received_amount ?? 0))
|
|
80
|
-
return true;
|
|
81
|
-
const note = bill.credit_note ?? collected.credit_note;
|
|
82
|
-
if ((note ?? null) !== (bill.credit_note ?? null))
|
|
83
|
-
return true;
|
|
84
|
-
return bill.settled_at == null && received >= (bill.amount ?? 0);
|
|
85
|
-
};
|
|
86
|
-
/** Does the document hold an issued bill that one of the collected payments would change? */
|
|
87
|
-
const documentHoldsUnpatchedCreditBill = (doc, collectedByBill) => {
|
|
88
|
-
for (const keyMetrics of Object.values((0, tenant_sales_overview_helpers_1.normalizeMaterializedSaleTypeMetrics)(doc.sale_type_metrics))) {
|
|
89
|
-
for (const bill of keyMetrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]?.issued?.bills ?? []) {
|
|
90
|
-
const collected = collectedByBill.get(materializedCreditBillKey(bill.order_id, bill.payment_id));
|
|
91
|
-
if (collected != null && creditBillWouldChange(bill, collected))
|
|
92
|
-
return true;
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
return false;
|
|
96
|
-
};
|
|
97
76
|
/**
|
|
98
77
|
* Builds the close-day write plan for ONE tenant-day (see the module docs).
|
|
99
78
|
* Returns `null` (never throws) when the input is inconsistent — compiled
|
|
@@ -146,6 +125,100 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
146
125
|
if (String(prior._id) !== String(doc._id))
|
|
147
126
|
return null;
|
|
148
127
|
}
|
|
128
|
+
// ------------------------------------------------------------------
|
|
129
|
+
// Resolve THIS day against the stored credit ledger documents — the only
|
|
130
|
+
// stateful step (receipt deltas, carried anchors, settlements), executed
|
|
131
|
+
// ONCE and shared by the report counters and the credit documents below
|
|
132
|
+
// (single writer: the two collections can never drift).
|
|
133
|
+
// - receipt events: a stored same-day event keeps its own `received_delta`
|
|
134
|
+
// (idempotent re-closes); a new event's delta resolves as the compile
|
|
135
|
+
// cumulative minus the stored cumulative (clamped at 0). Out-of-order
|
|
136
|
+
// backfills of a MISSED day can still misattribute a large delta to that
|
|
137
|
+
// day — closes are assumed to run chronologically per tenant (documented).
|
|
138
|
+
// - issued bills: `received_at_issue` / settlement anchors carry forward —
|
|
139
|
+
// a re-close AFTER collection never re-anchors them.
|
|
140
|
+
const creditResolution = (0, materialized_credit_bills_helpers_1.resolveCreditBillDay)({
|
|
141
|
+
tenantId,
|
|
142
|
+
localDate,
|
|
143
|
+
issued: compile.credit_bill_issues,
|
|
144
|
+
events: compile.credit_bill_events,
|
|
145
|
+
stored: input.existingCreditBills,
|
|
146
|
+
computedAt,
|
|
147
|
+
});
|
|
148
|
+
if (creditResolution == null)
|
|
149
|
+
return null;
|
|
150
|
+
// Fill the compiled collection-day documents' `received` COUNTERS from the
|
|
151
|
+
// resolved deltas (the compile cannot know them): hour docs take their
|
|
152
|
+
// event's hour, period docs the whole day; null-hour events count on the
|
|
153
|
+
// day-shaped scopes only (never on an hour doc).
|
|
154
|
+
const periodFieldsNow = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
|
|
155
|
+
if (periodFieldsNow == null)
|
|
156
|
+
return null;
|
|
157
|
+
const receivedByScopeKey = new Map();
|
|
158
|
+
for (const resolved of creditResolution.received_events) {
|
|
159
|
+
const key = resolved.key;
|
|
160
|
+
const delta = resolved.entry.received_delta ?? 0;
|
|
161
|
+
const scopeFields = Object.entries(periodFieldsNow).map(([scopeContext, scopeField]) => ({
|
|
162
|
+
scope_context: scopeContext,
|
|
163
|
+
scope_field: scopeField,
|
|
164
|
+
}));
|
|
165
|
+
if (resolved.entry.event_local_hour != null) {
|
|
166
|
+
scopeFields.push({
|
|
167
|
+
scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
|
|
168
|
+
scope_field: resolved.entry.event_local_hour,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
for (const scope of scopeFields) {
|
|
172
|
+
const mapKey = `${scope.scope_context}|${scope.scope_field}|${key}`;
|
|
173
|
+
const entry = receivedByScopeKey.get(mapKey) ?? { count: 0, amount: 0 };
|
|
174
|
+
entry.count += 1;
|
|
175
|
+
entry.amount += delta;
|
|
176
|
+
receivedByScopeKey.set(mapKey, entry);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
for (const compiledDoc of compiledReports) {
|
|
180
|
+
const metrics = compiledDoc.sale_type_metrics;
|
|
181
|
+
for (const [key, metric] of Object.entries(metrics ?? {})) {
|
|
182
|
+
const entry = receivedByScopeKey.get(`${compiledDoc.scope_context}|${compiledDoc.scope_field}|${key}`);
|
|
183
|
+
metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received = entry != null ? { ...entry } : { count: 0, amount: 0 };
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
// The compile derives ISSUED counters from the CURRENT order state — a
|
|
187
|
+
// never-settled view — so an ISSUE-DAY re-close after collection would
|
|
188
|
+
// regress the settled counters (and the N2 rule reads settled-later bills
|
|
189
|
+
// as unsettled at issue). The resolution carries the stored settlement
|
|
190
|
+
// anchors forward: OVERWRITE the compiled day's settled counters from the
|
|
191
|
+
// resolved issued entries (all of today's issues by construction).
|
|
192
|
+
//
|
|
193
|
+
// SEMANTICS (audit R5-4): these REPORT counters are EVER-SETTLED (NOW
|
|
194
|
+
// state) — a bill settled on any later day counts here. The range-pure
|
|
195
|
+
// as-of-end answer (`settled_local_date <= selection end`) comes from
|
|
196
|
+
// `computeMaterializedCreditBillTotalsFromReports` over the credit
|
|
197
|
+
// documents; the two legitimately differ for historical ranges and must
|
|
198
|
+
// never be rendered side-by-side without labeling (Phase C).
|
|
199
|
+
const settledByKey = new Map();
|
|
200
|
+
for (const resolved of creditResolution.issued) {
|
|
201
|
+
const entry = resolved.entry;
|
|
202
|
+
if (entry.settled_at == null && entry.settled_local_date == null)
|
|
203
|
+
continue;
|
|
204
|
+
const totals = settledByKey.get(resolved.key) ?? { count: 0, amount: 0 };
|
|
205
|
+
totals.count += 1;
|
|
206
|
+
totals.amount += entry.amount ?? 0;
|
|
207
|
+
settledByKey.set(resolved.key, totals);
|
|
208
|
+
}
|
|
209
|
+
for (const compiledDoc of compiledReports) {
|
|
210
|
+
const metrics = compiledDoc.sale_type_metrics;
|
|
211
|
+
for (const [key, metric] of Object.entries(metrics ?? {})) {
|
|
212
|
+
const entry = settledByKey.get(key);
|
|
213
|
+
metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_count = entry?.count ?? 0;
|
|
214
|
+
metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued.settled_amount = entry?.amount ?? 0;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
// Bills that settled on a LATER day than their issue day need the issue-day
|
|
218
|
+
// documents' SETTLED counters patched (the itemized ledger lives in
|
|
219
|
+
// `materialized_tenant_credit_bills`; report documents keep constant-size
|
|
220
|
+
// counters). The resolution emits each settlement exactly once.
|
|
221
|
+
const settledTransitions = creditResolution.settled_bills;
|
|
149
222
|
const storedDateDoc = existingByScope.get(materializedScopeKey(compiledDateDoc)) ?? null;
|
|
150
223
|
const dayChanged = force || needsMaterializedTenantSalesOverviewReportWrite(storedDateDoc, compiledDateDoc);
|
|
151
224
|
const dayDeltaEmpty = !hasMaterializedMetrics(compiledDateDoc);
|
|
@@ -229,28 +302,241 @@ function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
229
302
|
postWriteByScope.set(materializedScopeKey(write.report), write.report);
|
|
230
303
|
for (const stale of staleHourDocuments)
|
|
231
304
|
postWriteByScope.delete(materializedScopeKey(stale));
|
|
305
|
+
// Batch the settled-counter deltas per document first — several transitions
|
|
306
|
+
// can hit one document, and every patch must be computed from the same
|
|
307
|
+
// pre-patch state with ALL deltas applied in a single update.
|
|
308
|
+
const settledDeltasByDoc = new Map();
|
|
309
|
+
for (const transition of settledTransitions) {
|
|
310
|
+
const billKey = transition.key;
|
|
311
|
+
const issuePeriodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(transition.issued_local_date);
|
|
312
|
+
if (issuePeriodFields == null)
|
|
313
|
+
return null; // malformed issue date — data issue
|
|
314
|
+
const issueScopeValues = new Set([transition.issued_local_date, ...Object.values(issuePeriodFields)]);
|
|
315
|
+
for (const [scopeKey, doc] of postWriteByScope) {
|
|
316
|
+
const scopeOnIssueDay = issueScopeValues.has(doc.scope_field) ||
|
|
317
|
+
(doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
318
|
+
typeof doc.scope_field === 'string' &&
|
|
319
|
+
doc.scope_field.startsWith(`${transition.issued_local_date} `));
|
|
320
|
+
if (!scopeOnIssueDay)
|
|
321
|
+
continue;
|
|
322
|
+
const metrics = (0, tenant_sales_overview_helpers_1.normalizeMaterializedSaleTypeMetrics)(doc.sale_type_metrics);
|
|
323
|
+
if (metrics[billKey]?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS] == null)
|
|
324
|
+
continue;
|
|
325
|
+
const entries = settledDeltasByDoc.get(scopeKey) ?? [];
|
|
326
|
+
entries.push({ key: billKey, amount: transition.amount });
|
|
327
|
+
settledDeltasByDoc.set(scopeKey, entries);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
232
330
|
const receivedPatches = [];
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
331
|
+
for (const [scopeKey, entries] of settledDeltasByDoc) {
|
|
332
|
+
const doc = postWriteByScope.get(scopeKey);
|
|
333
|
+
if (doc == null)
|
|
334
|
+
continue;
|
|
335
|
+
const patched = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(doc, { settled_credit_bills: entries }, { computedAt });
|
|
336
|
+
if (patched == null)
|
|
337
|
+
return null;
|
|
338
|
+
const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(patched, {
|
|
339
|
+
reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
|
|
340
|
+
reason,
|
|
341
|
+
computedAt,
|
|
342
|
+
});
|
|
343
|
+
if (iteration == null)
|
|
344
|
+
return null;
|
|
345
|
+
receivedPatches.push({ report: patched, iteration });
|
|
346
|
+
}
|
|
347
|
+
// ------------------------------------------------------------------
|
|
348
|
+
// Credit-bill documents (`materialized_tenant_credit_bills`) — materialized
|
|
349
|
+
// from the SAME resolution as the counters above (single writer): the
|
|
350
|
+
// month-capped scopes only (hour/date/week/ISO-week/month), so no document
|
|
351
|
+
// can grow unbounded while year/multi-year reads cover their range with the
|
|
352
|
+
// month documents.
|
|
353
|
+
// ------------------------------------------------------------------
|
|
354
|
+
const creditDayScopes = [
|
|
355
|
+
MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
|
|
356
|
+
MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
357
|
+
];
|
|
358
|
+
const creditAccumulatedScopes = [
|
|
359
|
+
MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
|
|
360
|
+
MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
|
|
361
|
+
MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
|
|
362
|
+
];
|
|
363
|
+
const creditCompiledDocs = (0, materialized_credit_bills_helpers_1.buildMaterializedCreditBillDayReports)({
|
|
364
|
+
tenantId,
|
|
365
|
+
brandId: compiledDateDoc.brand_id,
|
|
366
|
+
localDate,
|
|
367
|
+
resolution: creditResolution,
|
|
368
|
+
computedAt,
|
|
369
|
+
});
|
|
370
|
+
if (creditCompiledDocs == null)
|
|
371
|
+
return null;
|
|
372
|
+
const creditExistingByScope = new Map();
|
|
373
|
+
for (const doc of input.existingCreditBills ?? []) {
|
|
374
|
+
if (doc == null || doc.tenant_id !== tenantId)
|
|
375
|
+
continue;
|
|
376
|
+
const key = materializedScopeKey(doc);
|
|
377
|
+
const prior = creditExistingByScope.get(key);
|
|
378
|
+
if (prior == null) {
|
|
379
|
+
creditExistingByScope.set(key, doc);
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
if (String(prior._id) !== String(doc._id))
|
|
383
|
+
return null; // duplicate rows — data issue
|
|
384
|
+
}
|
|
385
|
+
const creditWrites = [];
|
|
386
|
+
const creditSkippedDocuments = [];
|
|
387
|
+
const creditStaleHourDocuments = [];
|
|
388
|
+
const creditSettlementPatches = [];
|
|
389
|
+
const addCreditWrite = (report) => {
|
|
390
|
+
const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(report, {
|
|
391
|
+
reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_CREDIT_BILLS,
|
|
392
|
+
reason,
|
|
393
|
+
computedAt,
|
|
394
|
+
});
|
|
395
|
+
if (iteration == null)
|
|
396
|
+
return false;
|
|
397
|
+
creditWrites.push({ report, iteration });
|
|
398
|
+
return true;
|
|
399
|
+
};
|
|
400
|
+
const creditStoredDateDoc = creditExistingByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
|
|
401
|
+
if (creditCompiledDocs.length === 0) {
|
|
402
|
+
// Orders deleted / moved left the day with NO credit activity: subtract
|
|
403
|
+
// the stored day from the period docs and drop the day/hour documents.
|
|
404
|
+
if (creditStoredDateDoc != null) {
|
|
405
|
+
for (const doc of creditExistingByScope.values()) {
|
|
406
|
+
if (!creditAccumulatedScopes.includes(doc.scope_context))
|
|
407
|
+
continue;
|
|
408
|
+
const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(doc, { subtract: [creditStoredDateDoc] }, { computedAt });
|
|
409
|
+
if (updated == null)
|
|
410
|
+
return null;
|
|
411
|
+
if ((updated.iteration ?? 1) === (doc.iteration ?? 1))
|
|
412
|
+
continue; // day not in this doc — no-op
|
|
413
|
+
if (!addCreditWrite(updated))
|
|
414
|
+
return null;
|
|
415
|
+
}
|
|
416
|
+
for (const doc of creditExistingByScope.values()) {
|
|
417
|
+
const onDay = doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
|
|
418
|
+
? doc.scope_field === localDate
|
|
419
|
+
: doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
420
|
+
typeof doc.scope_field === 'string' &&
|
|
421
|
+
doc.scope_field.startsWith(`${localDate} `);
|
|
422
|
+
if (onDay)
|
|
423
|
+
creditStaleHourDocuments.push(doc);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
const creditCompiledByScope = new Map();
|
|
429
|
+
for (const doc of creditCompiledDocs) {
|
|
430
|
+
const key = materializedScopeKey(doc);
|
|
431
|
+
if (creditCompiledByScope.has(key))
|
|
432
|
+
return null; // duplicate scope doc — data issue
|
|
433
|
+
creditCompiledByScope.set(key, doc);
|
|
238
434
|
}
|
|
239
|
-
|
|
240
|
-
|
|
435
|
+
const creditDateDoc = creditCompiledByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
|
|
436
|
+
if (creditDateDoc == null)
|
|
437
|
+
return null;
|
|
438
|
+
const creditDayChanged = force || (0, materialized_credit_bills_helpers_1.needsMaterializedCreditBillsReportWrite)(creditStoredDateDoc, creditDateDoc);
|
|
439
|
+
for (const compiledCreditDoc of creditCompiledDocs) {
|
|
440
|
+
const existing = creditExistingByScope.get(materializedScopeKey(compiledCreditDoc)) ?? null;
|
|
441
|
+
if (creditDayScopes.includes(compiledCreditDoc.scope_context)) {
|
|
442
|
+
if (!creditDayChanged) {
|
|
443
|
+
if (existing != null)
|
|
444
|
+
creditSkippedDocuments.push(existing);
|
|
445
|
+
// Partial-failure repair: the day is up to date but this doc was never persisted.
|
|
446
|
+
else if (!addCreditWrite(compiledCreditDoc))
|
|
447
|
+
return null;
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
if (existing == null) {
|
|
451
|
+
if (!addCreditWrite(compiledCreditDoc))
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
else {
|
|
455
|
+
const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { replacement: compiledCreditDoc }, { computedAt });
|
|
456
|
+
if (updated == null || !addCreditWrite(updated))
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
241
459
|
continue;
|
|
242
|
-
|
|
243
|
-
if (
|
|
244
|
-
return null;
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
}
|
|
250
|
-
if (
|
|
460
|
+
}
|
|
461
|
+
if (!creditAccumulatedScopes.includes(compiledCreditDoc.scope_context))
|
|
462
|
+
return null; // unknown scope — data issue
|
|
463
|
+
if (existing == null) {
|
|
464
|
+
if (!addCreditWrite(compiledCreditDoc))
|
|
465
|
+
return null;
|
|
466
|
+
continue;
|
|
467
|
+
}
|
|
468
|
+
if (!creditDayChanged) {
|
|
469
|
+
creditSkippedDocuments.push(existing);
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
const updated = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(existing, { subtract: creditStoredDateDoc != null ? [creditStoredDateDoc] : [], additions: [compiledCreditDoc] }, { computedAt });
|
|
473
|
+
if (updated == null || !addCreditWrite(updated))
|
|
251
474
|
return null;
|
|
252
|
-
|
|
475
|
+
}
|
|
476
|
+
if (creditDayChanged) {
|
|
477
|
+
for (const doc of creditExistingByScope.values()) {
|
|
478
|
+
if (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
479
|
+
typeof doc.scope_field === 'string' &&
|
|
480
|
+
doc.scope_field.startsWith(`${localDate} `) &&
|
|
481
|
+
!creditCompiledByScope.has(materializedScopeKey(doc))) {
|
|
482
|
+
creditStaleHourDocuments.push(doc);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
// Settlements patch the ISSUE scopes exactly once — computed against the
|
|
487
|
+
// POST-write credit documents (persist after `creditWrites`), batched per
|
|
488
|
+
// document so several settlements apply in one versioned update.
|
|
489
|
+
if (creditResolution.settled_bills.length > 0) {
|
|
490
|
+
const creditPostWriteByScope = new Map();
|
|
491
|
+
for (const doc of creditExistingByScope.values())
|
|
492
|
+
creditPostWriteByScope.set(materializedScopeKey(doc), doc);
|
|
493
|
+
for (const write of creditWrites)
|
|
494
|
+
creditPostWriteByScope.set(materializedScopeKey(write.report), write.report);
|
|
495
|
+
for (const stale of creditStaleHourDocuments)
|
|
496
|
+
creditPostWriteByScope.delete(materializedScopeKey(stale));
|
|
497
|
+
const settlementsByScope = new Map();
|
|
498
|
+
for (const settlement of creditResolution.settled_bills) {
|
|
499
|
+
const refs = (0, materialized_credit_bills_helpers_1.getMaterializedCreditBillScopeRefsForIssue)(settlement.issued_local_date, settlement.issued_local_hour);
|
|
500
|
+
if (refs == null)
|
|
501
|
+
return null; // malformed issue date — data issue
|
|
502
|
+
for (const ref of refs) {
|
|
503
|
+
const scopeKey = `${ref.scope_context}|${ref.scope_field}`;
|
|
504
|
+
if (!creditPostWriteByScope.has(scopeKey))
|
|
505
|
+
continue;
|
|
506
|
+
const entries = settlementsByScope.get(scopeKey) ?? [];
|
|
507
|
+
entries.push(settlement);
|
|
508
|
+
settlementsByScope.set(scopeKey, entries);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
for (const [scopeKey, settlements] of settlementsByScope) {
|
|
512
|
+
const doc = creditPostWriteByScope.get(scopeKey);
|
|
513
|
+
if (doc == null)
|
|
514
|
+
continue;
|
|
515
|
+
const patched = (0, materialized_credit_bills_helpers_1.updateMaterializedCreditBillsReport)(doc, { settled_bills: settlements }, { computedAt });
|
|
516
|
+
if (patched == null)
|
|
517
|
+
return null;
|
|
518
|
+
if ((patched.iteration ?? 1) === (doc.iteration ?? 1))
|
|
519
|
+
continue; // this doc holds none of the bills — no-op
|
|
520
|
+
const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(patched, {
|
|
521
|
+
reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_CREDIT_BILLS,
|
|
522
|
+
reason,
|
|
523
|
+
computedAt,
|
|
524
|
+
});
|
|
525
|
+
if (iteration == null)
|
|
526
|
+
return null;
|
|
527
|
+
creditSettlementPatches.push({ report: patched, iteration });
|
|
528
|
+
}
|
|
253
529
|
}
|
|
254
530
|
}
|
|
255
|
-
return {
|
|
531
|
+
return {
|
|
532
|
+
writes,
|
|
533
|
+
staleHourDocuments,
|
|
534
|
+
receivedPatches,
|
|
535
|
+
creditWrites,
|
|
536
|
+
creditStaleHourDocuments,
|
|
537
|
+
creditSettlementPatches,
|
|
538
|
+
creditSkippedDocuments,
|
|
539
|
+
skippedDocuments,
|
|
540
|
+
createdPeriodDocuments,
|
|
541
|
+
};
|
|
256
542
|
}
|
|
@@ -18,7 +18,8 @@ import { IMaterializedTenantSalesOverviewAggregatedReport } from '../types/mater
|
|
|
18
18
|
* scopes only) and hour series are ordered by business-hour index
|
|
19
19
|
* (`06…23, 00…05`) — never lexicographically;
|
|
20
20
|
* - the brand-level combined view sums across tenants (`allowTenantMismatch`
|
|
21
|
-
* on the sum helper;
|
|
21
|
+
* on the sum helper; credit COUNTERS sum by key — the itemized ledger
|
|
22
|
+
* lives in `materialized_tenant_credit_bills`).
|
|
22
23
|
*
|
|
23
24
|
* Validation convention: returns `null` instead of throwing when the input
|
|
24
25
|
* cannot be formatted (non-array, mixed scopes / key filters / schema
|
|
@@ -82,15 +83,30 @@ export interface IFormattedSalesOverviewCreditBills {
|
|
|
82
83
|
issued: {
|
|
83
84
|
count: number;
|
|
84
85
|
amount: number;
|
|
86
|
+
/** Fully settled BY THE SELECTION END (range-pure on aggregated reads). */
|
|
85
87
|
settled_count: number;
|
|
88
|
+
/** Σ `amount` of fully settled bills — partial receipts never count here. */
|
|
86
89
|
settled_amount: number;
|
|
87
90
|
};
|
|
88
91
|
received: {
|
|
89
92
|
count: number;
|
|
90
93
|
amount: number;
|
|
91
94
|
};
|
|
92
|
-
/**
|
|
95
|
+
/**
|
|
96
|
+
* Money in hand AT ISSUE across the issued-in-selection bills (Σ
|
|
97
|
+
* `received_at_issue`): same-day settled credit + the prepaid part of
|
|
98
|
+
* partial bills. The Amount Collected KPI adds this to `received.amount`
|
|
99
|
+
* (later-day receipt events) — together they are ALL credit money in.
|
|
100
|
+
*/
|
|
101
|
+
collected_at_issue_count: number;
|
|
102
|
+
collected_at_issue_amount: number;
|
|
103
|
+
/** Issued-in-selection bills NOT fully settled by the selection end. */
|
|
104
|
+
outstanding_count: number;
|
|
105
|
+
/** Owed at the selection end (per-bill remainder, clamped at 0). */
|
|
93
106
|
outstanding_amount: number;
|
|
107
|
+
/** Today's state — see the module contract. */
|
|
108
|
+
outstanding_now_count: number;
|
|
109
|
+
outstanding_now_amount: number;
|
|
94
110
|
}
|
|
95
111
|
/** Weekday grouping (date/hour scopes only). */
|
|
96
112
|
export interface IFormattedSalesOverviewWeekday {
|
|
@@ -93,7 +93,7 @@ const pruneMetricsMap = (keyFilters, metrics, filters) => {
|
|
|
93
93
|
}
|
|
94
94
|
return kept;
|
|
95
95
|
};
|
|
96
|
-
/** Drops non-matching keys from a document's metric map (
|
|
96
|
+
/** Drops non-matching keys from a document's metric map (credit counters included). */
|
|
97
97
|
const pruneReportForFilters = (doc, filters) => {
|
|
98
98
|
const kept = pruneMetricsMap(doc.sale_type_key_filters ?? [], doc.sale_type_metrics, filters);
|
|
99
99
|
return { ...doc, sale_type_metrics: kept };
|
|
@@ -180,7 +180,12 @@ const buildEmptyPageData = (scopeContext, tenantIds) => ({
|
|
|
180
180
|
credit_bills: {
|
|
181
181
|
issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
|
|
182
182
|
received: { count: 0, amount: 0 },
|
|
183
|
+
outstanding_count: 0,
|
|
183
184
|
outstanding_amount: 0,
|
|
185
|
+
outstanding_now_count: 0,
|
|
186
|
+
outstanding_now_amount: 0,
|
|
187
|
+
collected_at_issue_count: 0,
|
|
188
|
+
collected_at_issue_amount: 0,
|
|
184
189
|
},
|
|
185
190
|
weekday: scopeContext != null && MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext) ? [] : null,
|
|
186
191
|
hourly: scopeContext === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? [] : null,
|
|
@@ -256,6 +261,7 @@ const buildPageDataForDocs = (docs, scopeContext, filters) => {
|
|
|
256
261
|
const supportsDayIndex = scopeContext != null && MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext);
|
|
257
262
|
return buildPageDataFromMetrics(merged, tenantIds, supportsDayIndex ? buildWeekdaySection(scopedDocs, filters) : null, scopeContext === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? buildHourlySection(scopedDocs, filters) : null);
|
|
258
263
|
};
|
|
264
|
+
const creditLedgerCountersOf = (entry) => entry[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS] ?? {};
|
|
259
265
|
/**
|
|
260
266
|
* Shared page assembly — identical for the raw read (one merged document) and
|
|
261
267
|
* the AGGREGATED read (one pipeline record): every section derives from the
|
|
@@ -270,7 +276,18 @@ const buildPageDataFromMetrics = (merged, tenantIds, weekday, hourly) => {
|
|
|
270
276
|
const cancelledRaw = createRawOrderMetric();
|
|
271
277
|
const paymentsMap = {};
|
|
272
278
|
const channelsMap = {};
|
|
273
|
-
const issuedRaw = {
|
|
279
|
+
const issuedRaw = {
|
|
280
|
+
count: 0,
|
|
281
|
+
amount: 0,
|
|
282
|
+
settled_count: 0,
|
|
283
|
+
settled_amount: 0,
|
|
284
|
+
outstanding_count: 0,
|
|
285
|
+
outstanding_amount: 0,
|
|
286
|
+
outstanding_now_count: 0,
|
|
287
|
+
outstanding_now_amount: 0,
|
|
288
|
+
collected_at_issue_count: 0,
|
|
289
|
+
collected_at_issue_amount: 0,
|
|
290
|
+
};
|
|
274
291
|
const receivedRaw = { count: 0, amount: 0 };
|
|
275
292
|
for (const [key, entry] of Object.entries(merged.sale_type_metrics ?? {})) {
|
|
276
293
|
const components = (0, key_helpers_1.parseMaterializedReportKey)(key);
|
|
@@ -278,7 +295,7 @@ const buildPageDataFromMetrics = (merged, tenantIds, weekday, hourly) => {
|
|
|
278
295
|
continue;
|
|
279
296
|
const totalSales = entry[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES];
|
|
280
297
|
const amountCollected = entry[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED];
|
|
281
|
-
const creditBills = entry
|
|
298
|
+
const creditBills = creditLedgerCountersOf(entry);
|
|
282
299
|
// Cancelled facet: cancelled orders are materialized under `CANCELLED:*`
|
|
283
300
|
// keys and excluded from every other facet (payments included).
|
|
284
301
|
if (isCancelledKey(components, keyFilters)) {
|
|
@@ -290,12 +307,30 @@ const buildPageDataFromMetrics = (merged, tenantIds, weekday, hourly) => {
|
|
|
290
307
|
for (const payment of totalSales?.payments ?? []) {
|
|
291
308
|
addRawPayment(paymentsMap, payment);
|
|
292
309
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
310
|
+
const issuedCounters = creditBills.issued ?? {};
|
|
311
|
+
const receivedCounters = creditBills.received ?? {};
|
|
312
|
+
// Stored documents carry COUNTERS only (the itemized ledger lives in
|
|
313
|
+
// `materialized_tenant_credit_bills`) — sum them per KEPT key (client-side
|
|
314
|
+
// filters included). Range-pure extras (`outstanding*`,
|
|
315
|
+
// `collected_at_issue_*`) ride only on AGGREGATED records; stored
|
|
316
|
+
// documents fall back to the ever-settled / zero basis (direct-
|
|
317
|
+
// inspection seam only — the aggregation is the canonical read).
|
|
318
|
+
issuedRaw.count += issuedCounters.count ?? 0;
|
|
319
|
+
issuedRaw.amount += issuedCounters.amount ?? 0;
|
|
320
|
+
issuedRaw.settled_count += issuedCounters.settled_count ?? 0;
|
|
321
|
+
issuedRaw.settled_amount += issuedCounters.settled_amount ?? 0;
|
|
322
|
+
const outstandingCountFallback = Math.max(0, (issuedCounters.count ?? 0) - (issuedCounters.settled_count ?? 0));
|
|
323
|
+
const outstandingAmountFallback = Math.max(0, (issuedCounters.amount ?? 0) - (issuedCounters.settled_amount ?? 0));
|
|
324
|
+
issuedRaw.outstanding_count += issuedCounters.outstanding_count ?? outstandingCountFallback;
|
|
325
|
+
issuedRaw.outstanding_amount += issuedCounters.outstanding_amount ?? outstandingAmountFallback;
|
|
326
|
+
issuedRaw.outstanding_now_count +=
|
|
327
|
+
issuedCounters.outstanding_now_count ?? issuedCounters.outstanding_count ?? outstandingCountFallback;
|
|
328
|
+
issuedRaw.outstanding_now_amount +=
|
|
329
|
+
issuedCounters.outstanding_now_amount ?? issuedCounters.outstanding_amount ?? outstandingAmountFallback;
|
|
330
|
+
issuedRaw.collected_at_issue_count += issuedCounters.collected_at_issue_count ?? 0;
|
|
331
|
+
issuedRaw.collected_at_issue_amount += issuedCounters.collected_at_issue_amount ?? 0;
|
|
332
|
+
receivedRaw.count += receivedCounters.count ?? 0;
|
|
333
|
+
receivedRaw.amount += receivedCounters.amount ?? 0;
|
|
299
334
|
const platform = getKeyDimValue(components, keyFilters, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM) ?? '';
|
|
300
335
|
const channel = channelsMap[platform] ?? (channelsMap[platform] = { platform, count: 0, gross_amount: 0 });
|
|
301
336
|
channel.count += totalSales?.orders?.count ?? 0;
|
|
@@ -338,7 +373,12 @@ const buildPageDataFromMetrics = (merged, tenantIds, weekday, hourly) => {
|
|
|
338
373
|
settled_amount: toDecimal(issuedRaw.settled_amount),
|
|
339
374
|
},
|
|
340
375
|
received: { count: receivedRaw.count, amount: toDecimal(receivedRaw.amount) },
|
|
341
|
-
|
|
376
|
+
outstanding_count: issuedRaw.outstanding_count,
|
|
377
|
+
outstanding_amount: toDecimal(issuedRaw.outstanding_amount),
|
|
378
|
+
outstanding_now_count: issuedRaw.outstanding_now_count,
|
|
379
|
+
outstanding_now_amount: toDecimal(issuedRaw.outstanding_now_amount),
|
|
380
|
+
collected_at_issue_count: issuedRaw.collected_at_issue_count,
|
|
381
|
+
collected_at_issue_amount: toDecimal(issuedRaw.collected_at_issue_amount),
|
|
342
382
|
},
|
|
343
383
|
weekday,
|
|
344
384
|
hourly,
|
|
@@ -411,7 +451,18 @@ const mergeAggregatedKeyMetrics = (reports) => {
|
|
|
411
451
|
[TOTAL_SALES]: { orders: createRawOrderMetric(), payments: [] },
|
|
412
452
|
[AMOUNT_COLLECTED]: { orders: createRawOrderMetric() },
|
|
413
453
|
[CREDIT_BILLS]: {
|
|
414
|
-
issued: {
|
|
454
|
+
issued: {
|
|
455
|
+
count: 0,
|
|
456
|
+
amount: 0,
|
|
457
|
+
settled_count: 0,
|
|
458
|
+
settled_amount: 0,
|
|
459
|
+
outstanding_count: 0,
|
|
460
|
+
outstanding_amount: 0,
|
|
461
|
+
outstanding_now_count: 0,
|
|
462
|
+
outstanding_now_amount: 0,
|
|
463
|
+
collected_at_issue_count: 0,
|
|
464
|
+
collected_at_issue_amount: 0,
|
|
465
|
+
},
|
|
415
466
|
received: { count: 0, amount: 0 },
|
|
416
467
|
},
|
|
417
468
|
});
|
|
@@ -424,6 +475,16 @@ const mergeAggregatedKeyMetrics = (reports) => {
|
|
|
424
475
|
entry[CREDIT_BILLS].issued.amount += metrics[CREDIT_BILLS]?.issued?.amount ?? 0;
|
|
425
476
|
entry[CREDIT_BILLS].issued.settled_count += metrics[CREDIT_BILLS]?.issued?.settled_count ?? 0;
|
|
426
477
|
entry[CREDIT_BILLS].issued.settled_amount += metrics[CREDIT_BILLS]?.issued?.settled_amount ?? 0;
|
|
478
|
+
entry[CREDIT_BILLS].issued.outstanding_count += metrics[CREDIT_BILLS]?.issued?.outstanding_count ?? 0;
|
|
479
|
+
entry[CREDIT_BILLS].issued.outstanding_amount += metrics[CREDIT_BILLS]?.issued?.outstanding_amount ?? 0;
|
|
480
|
+
entry[CREDIT_BILLS].issued.outstanding_now_count += metrics[CREDIT_BILLS]?.issued?.outstanding_now_count ?? 0;
|
|
481
|
+
entry[CREDIT_BILLS].issued.outstanding_now_amount += metrics[CREDIT_BILLS]?.issued?.outstanding_now_amount ?? 0;
|
|
482
|
+
// At-issue money rides as a COUNTER on aggregated records (derived from
|
|
483
|
+
// the ledger rows server-side); stored documents degrade to 0.
|
|
484
|
+
entry[CREDIT_BILLS].issued.collected_at_issue_count +=
|
|
485
|
+
metrics[CREDIT_BILLS]?.issued?.collected_at_issue_count ?? 0;
|
|
486
|
+
entry[CREDIT_BILLS].issued.collected_at_issue_amount +=
|
|
487
|
+
metrics[CREDIT_BILLS]?.issued?.collected_at_issue_amount ?? 0;
|
|
427
488
|
entry[CREDIT_BILLS].received.count += metrics[CREDIT_BILLS]?.received?.count ?? 0;
|
|
428
489
|
entry[CREDIT_BILLS].received.amount += metrics[CREDIT_BILLS]?.received?.amount ?? 0;
|
|
429
490
|
}
|