@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
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { REPORT_SALE_TYPE_ENUM } from '../../constants';
|
|
2
2
|
import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
|
|
3
|
-
import { buildMaterializedCreditBillDayReports, getMaterializedCreditBillScopeRefsForIssue, needsMaterializedCreditBillsReportWrite, resolveCreditBillDay, updateMaterializedCreditBillsReport, } from './materialized-credit-bills-helpers';
|
|
3
|
+
import { buildMaterializedCreditBillDayReports, getMaterializedCreditBillScopeRefsForDay, getMaterializedCreditBillScopeRefsForIssue, mergeMaterializedCreditBillSections, needsMaterializedCreditBillsReportWrite, resolveCreditBillDay, updateMaterializedCreditBillsReport, } from './materialized-credit-bills-helpers';
|
|
4
4
|
import { buildMaterializedTenantReportIteration } from './materialized-tenant-reports-iterations-helpers';
|
|
5
|
+
import { materializedDayInputSignatureChanged } from './materialized-day-input-signature';
|
|
5
6
|
import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields } from './scope-helpers';
|
|
6
|
-
import { normalizeMaterializedSaleTypeMetrics, updateMaterializedTenantSalesOverviewReport, } from './tenant-sales-overview-helpers';
|
|
7
|
+
import { normalizeMaterializedSaleTypeMetrics, subtractMaterializedTenantSalesOverviewReports, sumMaterializedTenantSalesOverviewReports, updateMaterializedTenantSalesOverviewReport, } from './tenant-sales-overview-helpers';
|
|
7
8
|
/** Scopes written wholesale for the compiled day (replacement semantics). */
|
|
8
9
|
const CLOSE_DAY_DAY_SCOPES = [
|
|
9
10
|
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
|
|
@@ -50,9 +51,12 @@ export function getMaterializedTenantSalesOverviewScopeRefsForDay(localDate) {
|
|
|
50
51
|
* structural write for the incoming compiled version?
|
|
51
52
|
*
|
|
52
53
|
* `false` (skip) when the incoming `source_watermark` is not newer than the
|
|
53
|
-
* stored one and the schema version +
|
|
54
|
-
*
|
|
55
|
-
*
|
|
54
|
+
* stored one, the day-input SIGNATURE is unchanged, and the schema version +
|
|
55
|
+
* key-filter grammar match. Watermarks are monotonic
|
|
56
|
+
* (`updateMaterializedTenantSalesOverviewReport` never regresses them); the
|
|
57
|
+
* signature is the SET-shaped signal that detects a deleted / moved order even
|
|
58
|
+
* when the incoming watermark is lower than the stored one. A missing stored
|
|
59
|
+
* document always needs a write.
|
|
56
60
|
*/
|
|
57
61
|
export function needsMaterializedTenantSalesOverviewReportWrite(existing, incoming) {
|
|
58
62
|
if (existing == null || incoming == null)
|
|
@@ -62,6 +66,11 @@ export function needsMaterializedTenantSalesOverviewReportWrite(existing, incomi
|
|
|
62
66
|
if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
|
|
63
67
|
return true;
|
|
64
68
|
}
|
|
69
|
+
// Set-shaped signal FIRST: a delete / move must correct even when the
|
|
70
|
+
// incoming watermark regressed below the stored one.
|
|
71
|
+
if (materializedDayInputSignatureChanged(existing.source_input_signature, incoming.source_input_signature)) {
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
65
74
|
const existingTime = new Date(existing.source_watermark ?? 0).getTime();
|
|
66
75
|
const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
|
|
67
76
|
if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
|
|
@@ -120,6 +129,68 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
120
129
|
if (String(prior._id) !== String(doc._id))
|
|
121
130
|
return null;
|
|
122
131
|
}
|
|
132
|
+
// REPAIR SOURCE: stored sibling DAY documents, used only when a period
|
|
133
|
+
// document has to be CREATED. A period is a running sum, so seeding it with
|
|
134
|
+
// the closing day alone would leave every earlier materialized day out of
|
|
135
|
+
// the period while its `localDate` document still exists (month ≠ Σ days).
|
|
136
|
+
// The closing day itself is excluded: the freshly compiled day replaces it.
|
|
137
|
+
const periodDayDocuments = [];
|
|
138
|
+
const periodDayDocumentsByField = new Map();
|
|
139
|
+
for (const doc of input.existingPeriodDayDocuments ?? []) {
|
|
140
|
+
if (doc == null || doc.tenant_id !== tenantId)
|
|
141
|
+
continue;
|
|
142
|
+
if (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
|
|
143
|
+
continue;
|
|
144
|
+
if (typeof doc.scope_field !== 'string' || doc.scope_field === localDate)
|
|
145
|
+
continue;
|
|
146
|
+
// A day document from another schema version / brand cannot be summed
|
|
147
|
+
// (`sumMaterialized…` would return null and fail the whole close); it is
|
|
148
|
+
// ignored here and re-materialized by its own close.
|
|
149
|
+
if (doc.schema_version !== compiledDateDoc.schema_version)
|
|
150
|
+
continue;
|
|
151
|
+
if ((doc.sale_type_key_filters ?? []).join(':') !== (compiledDateDoc.sale_type_key_filters ?? []).join(':')) {
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (doc.brand_id !== compiledDateDoc.brand_id)
|
|
155
|
+
continue;
|
|
156
|
+
periodDayDocumentsByField.set(doc.scope_field, doc);
|
|
157
|
+
periodDayDocuments.push(doc);
|
|
158
|
+
}
|
|
159
|
+
// Month siblings for the upper levels (quarter/semester/year). A month is
|
|
160
|
+
// NEVER derived from weeks: Sunday-based weeks cross month boundaries.
|
|
161
|
+
const periodMonthDocuments = [];
|
|
162
|
+
for (const doc of input.existingPeriodMonthDocuments ?? []) {
|
|
163
|
+
if (doc == null || doc.tenant_id !== tenantId)
|
|
164
|
+
continue;
|
|
165
|
+
if (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)
|
|
166
|
+
continue;
|
|
167
|
+
if (typeof doc.scope_field !== 'string')
|
|
168
|
+
continue;
|
|
169
|
+
if (doc.schema_version !== compiledDateDoc.schema_version)
|
|
170
|
+
continue;
|
|
171
|
+
if ((doc.sale_type_key_filters ?? []).join(':') !== (compiledDateDoc.sale_type_key_filters ?? []).join(':')) {
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (doc.brand_id !== compiledDateDoc.brand_id)
|
|
175
|
+
continue;
|
|
176
|
+
periodMonthDocuments.push(doc);
|
|
177
|
+
}
|
|
178
|
+
const upperPeriodScopes = [
|
|
179
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
|
|
180
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
|
|
181
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
|
|
182
|
+
];
|
|
183
|
+
const dayDocumentBelongsToScope = (doc, scopeContext, scopeField) => {
|
|
184
|
+
const refs = getMaterializedTenantSalesOverviewScopeRefsForDay(doc.scope_field);
|
|
185
|
+
return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
|
|
186
|
+
};
|
|
187
|
+
/** The sibling documents the hierarchy says to fold into a missing period. */
|
|
188
|
+
const periodSiblingsFor = (scopeContext, scopeField) => upperPeriodScopes.includes(scopeContext)
|
|
189
|
+
? periodMonthDocuments.filter((doc) => {
|
|
190
|
+
const fields = getMaterializedPeriodScopeFields(`${doc.scope_field}-01`);
|
|
191
|
+
return fields != null && fields[scopeContext] === scopeField;
|
|
192
|
+
})
|
|
193
|
+
: periodDayDocuments.filter((doc) => dayDocumentBelongsToScope(doc, scopeContext, scopeField));
|
|
123
194
|
// ------------------------------------------------------------------
|
|
124
195
|
// Resolve THIS day against the stored credit ledger documents — the only
|
|
125
196
|
// stateful step (receipt deltas, carried anchors, settlements), executed
|
|
@@ -215,11 +286,25 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
215
286
|
// counters). The resolution emits each settlement exactly once.
|
|
216
287
|
const settledTransitions = creditResolution.settled_bills;
|
|
217
288
|
const storedDateDoc = existingByScope.get(materializedScopeKey(compiledDateDoc)) ?? null;
|
|
289
|
+
// A missing date document is a NEW day when no day-scoped document (date or
|
|
290
|
+
// hour) exists at all; otherwise it is a LOST document on a previously
|
|
291
|
+
// materialized day and needs the sibling rebuild. Without this distinction a
|
|
292
|
+
// first close after an earlier day of the same period would look like an
|
|
293
|
+
// unprovable repair.
|
|
294
|
+
const dayWasMaterialized = [...existingByScope.values()].some((doc) => (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
|
|
295
|
+
(doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
296
|
+
typeof doc.scope_field === 'string' &&
|
|
297
|
+
doc.scope_field.startsWith(`${localDate} `))) ||
|
|
298
|
+
(input.existingCreditBills ?? []).some((doc) => (doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
|
|
299
|
+
(doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
300
|
+
typeof doc.scope_field === 'string' &&
|
|
301
|
+
doc.scope_field.startsWith(`${localDate} `)));
|
|
218
302
|
const dayChanged = force || needsMaterializedTenantSalesOverviewReportWrite(storedDateDoc, compiledDateDoc);
|
|
219
|
-
const dayDeltaEmpty = !hasMaterializedMetrics(compiledDateDoc);
|
|
220
303
|
const writes = [];
|
|
221
304
|
const skippedDocuments = [];
|
|
222
305
|
const createdPeriodDocuments = [];
|
|
306
|
+
let foldedPeriodDayDocuments = 0;
|
|
307
|
+
let foldedPeriodDayCreditDocuments = 0;
|
|
223
308
|
const addStructuralWrite = (report) => {
|
|
224
309
|
const iteration = buildMaterializedTenantReportIteration(report, {
|
|
225
310
|
reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
|
|
@@ -256,9 +341,55 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
256
341
|
if (!CLOSE_DAY_ACCUMULATED_SCOPES.includes(compiledDoc.scope_context))
|
|
257
342
|
return null; // unknown scope — data issue
|
|
258
343
|
if (existing == null) {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
344
|
+
// Missing period document: REPAIR it from the stored sibling days that
|
|
345
|
+
// belong to this exact scope, then add the closing day. Without the fold
|
|
346
|
+
// the period would hold only this close's delta while the earlier days'
|
|
347
|
+
// `localDate` documents still exist — `localMonth` would no longer equal
|
|
348
|
+
// the sum of its days.
|
|
349
|
+
let siblings = periodSiblingsFor(compiledDoc.scope_context, String(compiledDoc.scope_field));
|
|
350
|
+
if (upperPeriodScopes.includes(compiledDoc.scope_context)) {
|
|
351
|
+
const currentMonth = localDate.slice(0, 7);
|
|
352
|
+
if (storedDateDoc == null && dayWasMaterialized)
|
|
353
|
+
return null; // month docs may still contain the lost day
|
|
354
|
+
if (storedDateDoc != null) {
|
|
355
|
+
// A stored date document proves the current month should exist. If
|
|
356
|
+
// the month sibling set is empty/incomplete, creating the upper
|
|
357
|
+
// period from the closing day alone would silently undercount it.
|
|
358
|
+
if (!siblings.some((doc) => doc.scope_field === currentMonth))
|
|
359
|
+
return null;
|
|
360
|
+
const corrected = [];
|
|
361
|
+
for (const month of siblings) {
|
|
362
|
+
if (month.scope_field !== currentMonth) {
|
|
363
|
+
corrected.push(month);
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
const dayDelta = {
|
|
367
|
+
...storedDateDoc,
|
|
368
|
+
scope_context: month.scope_context,
|
|
369
|
+
scope_field: month.scope_field,
|
|
370
|
+
day_index: null,
|
|
371
|
+
};
|
|
372
|
+
const withoutDay = subtractMaterializedTenantSalesOverviewReports(month, dayDelta);
|
|
373
|
+
if (withoutDay == null)
|
|
374
|
+
return null;
|
|
375
|
+
corrected.push(withoutDay);
|
|
376
|
+
}
|
|
377
|
+
siblings = corrected;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
// Even an order-less close writes its period marker: the Overview
|
|
381
|
+
// completeness probe needs a zero document for a legitimately empty
|
|
382
|
+
// period instead of reporting the period as "not materialized".
|
|
383
|
+
let createdReport = compiledDoc;
|
|
384
|
+
if (siblings.length > 0) {
|
|
385
|
+
createdReport = sumMaterializedTenantSalesOverviewReports([compiledDoc, ...siblings], {
|
|
386
|
+
computedAt,
|
|
387
|
+
});
|
|
388
|
+
if (createdReport == null)
|
|
389
|
+
return null; // inconsistent sibling — data issue
|
|
390
|
+
foldedPeriodDayDocuments += siblings.length;
|
|
391
|
+
}
|
|
392
|
+
if (createdReport == null || !addStructuralWrite(createdReport))
|
|
262
393
|
return null;
|
|
263
394
|
createdPeriodDocuments.push({
|
|
264
395
|
scope_context: compiledDoc.scope_context,
|
|
@@ -270,11 +401,67 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
270
401
|
skippedDocuments.push(existing);
|
|
271
402
|
continue;
|
|
272
403
|
}
|
|
273
|
-
|
|
274
|
-
|
|
404
|
+
// MISSING DATE DOCUMENT: the stored day delta is unknown. Do NOT add the
|
|
405
|
+
// fresh day to a running sum that may already contain it. Rebuild the
|
|
406
|
+
// period from the stored sibling DAY documents + the fresh day. If the
|
|
407
|
+
// period has data but no sibling evidence at all, the repair is unprovable;
|
|
408
|
+
// fail loudly instead of guessing.
|
|
409
|
+
if (storedDateDoc == null) {
|
|
410
|
+
if (dayWasMaterialized && upperPeriodScopes.includes(compiledDoc.scope_context)) {
|
|
411
|
+
// The month documents may still contain the lost day; a quarter cannot
|
|
412
|
+
// be repaired by adding the fresh day. Fail loudly.
|
|
413
|
+
return null;
|
|
414
|
+
}
|
|
415
|
+
let siblings = periodSiblingsFor(compiledDoc.scope_context, String(compiledDoc.scope_field));
|
|
416
|
+
if (upperPeriodScopes.includes(compiledDoc.scope_context) && siblings.length === 0) {
|
|
417
|
+
// The month document may be the one that was lost. The stored localDate
|
|
418
|
+
// documents are still valid evidence for this upper period; use them
|
|
419
|
+
// instead of falling back to an unprovable additive write.
|
|
420
|
+
siblings = periodDayDocuments.filter((doc) => dayDocumentBelongsToScope(doc, compiledDoc.scope_context, String(compiledDoc.scope_field)));
|
|
421
|
+
}
|
|
422
|
+
if (!dayWasMaterialized) {
|
|
423
|
+
// No day-scoped document survives, so the stored day delta is unknown.
|
|
424
|
+
// The period is additive ONLY if it currently equals the sibling days
|
|
425
|
+
// exactly (the day contributed nothing / this is its first close).
|
|
426
|
+
// Otherwise the missing day is still INSIDE the period and adding the
|
|
427
|
+
// fresh delta would double it — fail loudly instead of guessing.
|
|
428
|
+
if (siblings.length === 0) {
|
|
429
|
+
// The period exists but the old day delta is unprovable. Adding the
|
|
430
|
+
// fresh day could double it; fail loudly instead.
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
const siblingSum = sumMaterializedTenantSalesOverviewReports(siblings, { computedAt });
|
|
434
|
+
if (siblingSum == null ||
|
|
435
|
+
JSON.stringify(existing.sale_type_metrics ?? {}) !== JSON.stringify(siblingSum.sale_type_metrics ?? {})) {
|
|
436
|
+
return null;
|
|
437
|
+
}
|
|
438
|
+
const updated = updateMaterializedTenantSalesOverviewReport(existing, { additions: [compiledDoc] }, { computedAt });
|
|
439
|
+
if (updated == null)
|
|
440
|
+
return null;
|
|
441
|
+
if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
|
|
442
|
+
skippedDocuments.push(existing);
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
if (!addStructuralWrite(updated))
|
|
446
|
+
return null;
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
if (siblings.length === 0 && hasMaterializedMetrics(existing)) {
|
|
450
|
+
// Unprovable repair: a non-empty period with no sibling day evidence.
|
|
451
|
+
// The worker turns a null plan into a permanent, logged close failure.
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
const rebuilt = siblings.length > 0
|
|
455
|
+
? sumMaterializedTenantSalesOverviewReports([compiledDoc, ...siblings], { computedAt })
|
|
456
|
+
: compiledDoc;
|
|
457
|
+
if (rebuilt == null)
|
|
458
|
+
return null;
|
|
459
|
+
const updated = updateMaterializedTenantSalesOverviewReport(existing, { replacement: rebuilt }, { computedAt });
|
|
460
|
+
if (updated == null || !addStructuralWrite(updated))
|
|
461
|
+
return null;
|
|
275
462
|
continue;
|
|
276
463
|
}
|
|
277
|
-
const updated = updateMaterializedTenantSalesOverviewReport(existing, { subtract:
|
|
464
|
+
const updated = updateMaterializedTenantSalesOverviewReport(existing, { subtract: [storedDateDoc], additions: [compiledDoc] }, { computedAt });
|
|
278
465
|
if (updated == null || !addStructuralWrite(updated))
|
|
279
466
|
return null;
|
|
280
467
|
}
|
|
@@ -302,10 +489,12 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
302
489
|
// pre-patch state with ALL deltas applied in a single update.
|
|
303
490
|
const settledDeltasByDoc = new Map();
|
|
304
491
|
for (const transition of settledTransitions) {
|
|
305
|
-
|
|
492
|
+
// Patch the section the ISSUE document actually holds — the order status
|
|
493
|
+
// may have changed between the issue day and the collection day.
|
|
494
|
+
const billKey = transition.stored_key ?? transition.key;
|
|
306
495
|
const issuePeriodFields = getMaterializedPeriodScopeFields(transition.issued_local_date);
|
|
307
496
|
if (issuePeriodFields == null)
|
|
308
|
-
return null;
|
|
497
|
+
return null;
|
|
309
498
|
const issueScopeValues = new Set([transition.issued_local_date, ...Object.values(issuePeriodFields)]);
|
|
310
499
|
for (const [scopeKey, doc] of postWriteByScope) {
|
|
311
500
|
const scopeOnIssueDay = issueScopeValues.has(doc.scope_field) ||
|
|
@@ -361,9 +550,61 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
361
550
|
localDate,
|
|
362
551
|
resolution: creditResolution,
|
|
363
552
|
computedAt,
|
|
553
|
+
sourceInputSignature: compiledDateDoc.source_input_signature ?? null,
|
|
364
554
|
});
|
|
365
555
|
if (creditCompiledDocs == null)
|
|
366
556
|
return null;
|
|
557
|
+
// REPAIR SOURCE for missing credit PERIOD documents — the stored sibling
|
|
558
|
+
// DAY documents (the closing day is replaced by the compiled one). Mirrors
|
|
559
|
+
// the sales-overview fold above; without it a recreated month document would
|
|
560
|
+
// hold only this close's bills while the other days' date documents exist.
|
|
561
|
+
const creditPeriodDayDocuments = [];
|
|
562
|
+
// The credit collection has its OWN schema version / key grammar — compare
|
|
563
|
+
// siblings against a compiled CREDIT document, never the overview envelope.
|
|
564
|
+
const creditReferenceDoc = creditCompiledDocs[0] ?? null;
|
|
565
|
+
for (const doc of input.existingPeriodDayCreditDocuments ?? []) {
|
|
566
|
+
if (creditReferenceDoc == null)
|
|
567
|
+
break;
|
|
568
|
+
if (doc == null || doc.tenant_id !== tenantId)
|
|
569
|
+
continue;
|
|
570
|
+
if (doc.scope_context !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
|
|
571
|
+
continue;
|
|
572
|
+
if (typeof doc.scope_field !== 'string' || doc.scope_field === localDate)
|
|
573
|
+
continue;
|
|
574
|
+
if (doc.schema_version !== creditReferenceDoc.schema_version)
|
|
575
|
+
continue;
|
|
576
|
+
if (JSON.stringify(doc.sale_type_key_filters ?? []) !== JSON.stringify(creditReferenceDoc.sale_type_key_filters ?? [])) {
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
creditPeriodDayDocuments.push(doc);
|
|
580
|
+
}
|
|
581
|
+
const creditDayDocumentBelongsToScope = (doc, scopeContext, scopeField) => {
|
|
582
|
+
const refs = getMaterializedCreditBillScopeRefsForDay(doc.scope_field);
|
|
583
|
+
return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
|
|
584
|
+
};
|
|
585
|
+
const hasCreditBillEntries = (doc) => Object.values(doc.credit_bills ?? {}).some((section) => (section?.issued ?? []).length > 0 || (section?.received ?? []).length > 0);
|
|
586
|
+
const buildCreditPeriodReplacement = (existing, compiled, siblings) => {
|
|
587
|
+
const sections = {};
|
|
588
|
+
let watermark = new Date(existing.source_watermark);
|
|
589
|
+
if (compiled != null) {
|
|
590
|
+
mergeMaterializedCreditBillSections(sections, compiled.credit_bills);
|
|
591
|
+
const compiledWatermark = new Date(compiled.source_watermark);
|
|
592
|
+
if (compiledWatermark.getTime() > watermark.getTime())
|
|
593
|
+
watermark = compiledWatermark;
|
|
594
|
+
}
|
|
595
|
+
for (const sibling of siblings) {
|
|
596
|
+
mergeMaterializedCreditBillSections(sections, sibling.credit_bills);
|
|
597
|
+
const siblingWatermark = new Date(sibling.source_watermark);
|
|
598
|
+
if (siblingWatermark.getTime() > watermark.getTime())
|
|
599
|
+
watermark = siblingWatermark;
|
|
600
|
+
}
|
|
601
|
+
return {
|
|
602
|
+
...existing,
|
|
603
|
+
credit_bills: sections,
|
|
604
|
+
source_watermark: watermark,
|
|
605
|
+
source_input_signature: existing.source_input_signature,
|
|
606
|
+
};
|
|
607
|
+
};
|
|
367
608
|
const creditExistingByScope = new Map();
|
|
368
609
|
for (const doc of input.existingCreditBills ?? []) {
|
|
369
610
|
if (doc == null || doc.tenant_id !== tenantId)
|
|
@@ -381,6 +622,7 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
381
622
|
const creditSkippedDocuments = [];
|
|
382
623
|
const creditStaleHourDocuments = [];
|
|
383
624
|
const creditSettlementPatches = [];
|
|
625
|
+
const creditReceiptPatches = [];
|
|
384
626
|
const addCreditWrite = (report) => {
|
|
385
627
|
const iteration = buildMaterializedTenantReportIteration(report, {
|
|
386
628
|
reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_CREDIT_BILLS,
|
|
@@ -395,28 +637,45 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
395
637
|
const creditStoredDateDoc = creditExistingByScope.get(`${MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
|
|
396
638
|
if (creditCompiledDocs.length === 0) {
|
|
397
639
|
// Orders deleted / moved left the day with NO credit activity: subtract
|
|
398
|
-
// the stored day from the period docs
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
640
|
+
// the stored day from the period docs (or rebuild them from siblings when
|
|
641
|
+
// the date document itself is missing) and drop the day/hour documents.
|
|
642
|
+
for (const doc of creditExistingByScope.values()) {
|
|
643
|
+
if (!creditAccumulatedScopes.includes(doc.scope_context))
|
|
644
|
+
continue;
|
|
645
|
+
if (creditStoredDateDoc == null && !dayWasMaterialized)
|
|
646
|
+
continue; // new order-less day — no stored delta
|
|
647
|
+
if (creditStoredDateDoc == null) {
|
|
648
|
+
const siblings = creditPeriodDayDocuments.filter((sibling) => creditDayDocumentBelongsToScope(sibling, doc.scope_context, doc.scope_field));
|
|
649
|
+
if (siblings.length === 0 && hasCreditBillEntries(doc))
|
|
650
|
+
return null; // unprovable repair
|
|
651
|
+
const replacement = buildCreditPeriodReplacement(doc, null, siblings);
|
|
652
|
+
if (replacement == null)
|
|
653
|
+
return null;
|
|
654
|
+
const updated = updateMaterializedCreditBillsReport(doc, { replacement }, { computedAt });
|
|
404
655
|
if (updated == null)
|
|
405
656
|
return null;
|
|
406
657
|
if ((updated.iteration ?? 1) === (doc.iteration ?? 1))
|
|
407
|
-
continue;
|
|
658
|
+
continue;
|
|
408
659
|
if (!addCreditWrite(updated))
|
|
409
660
|
return null;
|
|
661
|
+
continue;
|
|
410
662
|
}
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
663
|
+
const updated = updateMaterializedCreditBillsReport(doc, { subtract: [creditStoredDateDoc] }, { computedAt });
|
|
664
|
+
if (updated == null)
|
|
665
|
+
return null;
|
|
666
|
+
if ((updated.iteration ?? 1) === (doc.iteration ?? 1))
|
|
667
|
+
continue; // day not in this doc — no-op
|
|
668
|
+
if (!addCreditWrite(updated))
|
|
669
|
+
return null;
|
|
670
|
+
}
|
|
671
|
+
for (const doc of creditExistingByScope.values()) {
|
|
672
|
+
const onDay = doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
|
|
673
|
+
? doc.scope_field === localDate
|
|
674
|
+
: doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
675
|
+
typeof doc.scope_field === 'string' &&
|
|
676
|
+
doc.scope_field.startsWith(`${localDate} `);
|
|
677
|
+
if (onDay)
|
|
678
|
+
creditStaleHourDocuments.push(doc);
|
|
420
679
|
}
|
|
421
680
|
}
|
|
422
681
|
else {
|
|
@@ -456,7 +715,30 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
456
715
|
if (!creditAccumulatedScopes.includes(compiledCreditDoc.scope_context))
|
|
457
716
|
return null; // unknown scope — data issue
|
|
458
717
|
if (existing == null) {
|
|
459
|
-
|
|
718
|
+
// Missing period document: rebuild it from the sibling DAY documents
|
|
719
|
+
// that belong to this exact scope (the closing day is the compiled
|
|
720
|
+
// document), so the ledger stays equal to the sum of its days.
|
|
721
|
+
const siblings = creditPeriodDayDocuments.filter((doc) => creditDayDocumentBelongsToScope(doc, compiledCreditDoc.scope_context, compiledCreditDoc.scope_field));
|
|
722
|
+
let created = compiledCreditDoc;
|
|
723
|
+
if (siblings.length > 0) {
|
|
724
|
+
const sections = {};
|
|
725
|
+
mergeMaterializedCreditBillSections(sections, compiledCreditDoc.credit_bills);
|
|
726
|
+
let watermark = new Date(compiledCreditDoc.source_watermark);
|
|
727
|
+
for (const sibling of siblings) {
|
|
728
|
+
mergeMaterializedCreditBillSections(sections, sibling.credit_bills);
|
|
729
|
+
const siblingWatermark = new Date(sibling.source_watermark);
|
|
730
|
+
if (siblingWatermark.getTime() > watermark.getTime())
|
|
731
|
+
watermark = siblingWatermark;
|
|
732
|
+
}
|
|
733
|
+
created = {
|
|
734
|
+
...compiledCreditDoc,
|
|
735
|
+
credit_bills: sections,
|
|
736
|
+
source_watermark: watermark,
|
|
737
|
+
iteration: 1,
|
|
738
|
+
};
|
|
739
|
+
foldedPeriodDayCreditDocuments += siblings.length;
|
|
740
|
+
}
|
|
741
|
+
if (!addCreditWrite(created))
|
|
460
742
|
return null;
|
|
461
743
|
continue;
|
|
462
744
|
}
|
|
@@ -464,8 +746,55 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
464
746
|
creditSkippedDocuments.push(existing);
|
|
465
747
|
continue;
|
|
466
748
|
}
|
|
467
|
-
|
|
468
|
-
|
|
749
|
+
if (creditStoredDateDoc == null) {
|
|
750
|
+
const siblings = creditPeriodDayDocuments.filter((sibling) => creditDayDocumentBelongsToScope(sibling, compiledCreditDoc.scope_context, compiledCreditDoc.scope_field));
|
|
751
|
+
if (!dayWasMaterialized) {
|
|
752
|
+
if (siblings.length === 0) {
|
|
753
|
+
if (hasCreditBillEntries(existing))
|
|
754
|
+
return null;
|
|
755
|
+
}
|
|
756
|
+
else {
|
|
757
|
+
const siblingOnly = buildCreditPeriodReplacement(existing, null, siblings);
|
|
758
|
+
if (siblingOnly == null ||
|
|
759
|
+
JSON.stringify(siblingOnly.credit_bills ?? {}) !== JSON.stringify(existing.credit_bills ?? {})) {
|
|
760
|
+
return null;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
const updated = updateMaterializedCreditBillsReport(existing, { additions: [compiledCreditDoc] }, { computedAt });
|
|
764
|
+
if (updated == null)
|
|
765
|
+
return null;
|
|
766
|
+
if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
|
|
767
|
+
creditSkippedDocuments.push(existing);
|
|
768
|
+
continue;
|
|
769
|
+
}
|
|
770
|
+
if (!addCreditWrite(updated))
|
|
771
|
+
return null;
|
|
772
|
+
continue;
|
|
773
|
+
}
|
|
774
|
+
if (siblings.length === 0 && hasCreditBillEntries(existing))
|
|
775
|
+
return null; // unprovable repair
|
|
776
|
+
const replacement = buildCreditPeriodReplacement(existing, compiledCreditDoc, siblings);
|
|
777
|
+
if (replacement == null)
|
|
778
|
+
return null;
|
|
779
|
+
const updated = updateMaterializedCreditBillsReport(existing, { replacement }, { computedAt });
|
|
780
|
+
if (updated == null)
|
|
781
|
+
return null;
|
|
782
|
+
if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
|
|
783
|
+
creditSkippedDocuments.push(existing);
|
|
784
|
+
continue;
|
|
785
|
+
}
|
|
786
|
+
if (!addCreditWrite(updated))
|
|
787
|
+
return null;
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
const updated = updateMaterializedCreditBillsReport(existing, { subtract: [creditStoredDateDoc], additions: [compiledCreditDoc] }, { computedAt });
|
|
791
|
+
if (updated == null)
|
|
792
|
+
return null;
|
|
793
|
+
if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
|
|
794
|
+
creditSkippedDocuments.push(existing);
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
if (!addCreditWrite(updated))
|
|
469
798
|
return null;
|
|
470
799
|
}
|
|
471
800
|
if (creditDayChanged) {
|
|
@@ -478,10 +807,11 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
478
807
|
}
|
|
479
808
|
}
|
|
480
809
|
}
|
|
481
|
-
// Settlements patch the ISSUE scopes exactly once —
|
|
482
|
-
// POST-write credit documents (persist after
|
|
483
|
-
// document so several
|
|
484
|
-
|
|
810
|
+
// Settlements AND partial receipts patch the ISSUE scopes exactly once —
|
|
811
|
+
// computed against the POST-write credit documents (persist after
|
|
812
|
+
// `creditWrites`), batched per document so several patches apply in one
|
|
813
|
+
// versioned update.
|
|
814
|
+
if (creditResolution.settled_bills.length > 0 || creditResolution.receipt_bills.length > 0) {
|
|
485
815
|
const creditPostWriteByScope = new Map();
|
|
486
816
|
for (const doc of creditExistingByScope.values())
|
|
487
817
|
creditPostWriteByScope.set(materializedScopeKey(doc), doc);
|
|
@@ -490,24 +820,39 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
490
820
|
for (const stale of creditStaleHourDocuments)
|
|
491
821
|
creditPostWriteByScope.delete(materializedScopeKey(stale));
|
|
492
822
|
const settlementsByScope = new Map();
|
|
493
|
-
|
|
494
|
-
|
|
823
|
+
const receiptsByScope = new Map();
|
|
824
|
+
const addScopePatch = (map, patch, issuedLocalDate, issuedLocalHour) => {
|
|
825
|
+
const refs = getMaterializedCreditBillScopeRefsForIssue(issuedLocalDate, issuedLocalHour);
|
|
495
826
|
if (refs == null)
|
|
496
|
-
return
|
|
827
|
+
return false; // malformed issue date — data issue
|
|
497
828
|
for (const ref of refs) {
|
|
498
829
|
const scopeKey = `${ref.scope_context}|${ref.scope_field}`;
|
|
499
830
|
if (!creditPostWriteByScope.has(scopeKey))
|
|
500
831
|
continue;
|
|
501
|
-
const entries =
|
|
502
|
-
entries.push(
|
|
503
|
-
|
|
832
|
+
const entries = map.get(scopeKey) ?? [];
|
|
833
|
+
entries.push(patch);
|
|
834
|
+
map.set(scopeKey, entries);
|
|
835
|
+
}
|
|
836
|
+
return true;
|
|
837
|
+
};
|
|
838
|
+
for (const settlement of creditResolution.settled_bills) {
|
|
839
|
+
if (!addScopePatch(settlementsByScope, settlement, settlement.issued_local_date, settlement.issued_local_hour)) {
|
|
840
|
+
return null;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
for (const receipt of creditResolution.receipt_bills) {
|
|
844
|
+
if (!addScopePatch(receiptsByScope, receipt, receipt.issued_local_date, receipt.issued_local_hour)) {
|
|
845
|
+
return null;
|
|
504
846
|
}
|
|
505
847
|
}
|
|
506
|
-
|
|
848
|
+
const patchScopeKeys = new Set([...settlementsByScope.keys(), ...receiptsByScope.keys()]);
|
|
849
|
+
for (const scopeKey of patchScopeKeys) {
|
|
507
850
|
const doc = creditPostWriteByScope.get(scopeKey);
|
|
508
851
|
if (doc == null)
|
|
509
852
|
continue;
|
|
510
|
-
const
|
|
853
|
+
const settlements = settlementsByScope.get(scopeKey) ?? [];
|
|
854
|
+
const receipts = receiptsByScope.get(scopeKey) ?? [];
|
|
855
|
+
const patched = updateMaterializedCreditBillsReport(doc, { settled_bills: settlements, receipt_bills: receipts }, { computedAt });
|
|
511
856
|
if (patched == null)
|
|
512
857
|
return null;
|
|
513
858
|
if ((patched.iteration ?? 1) === (doc.iteration ?? 1))
|
|
@@ -519,7 +864,13 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
519
864
|
});
|
|
520
865
|
if (iteration == null)
|
|
521
866
|
return null;
|
|
522
|
-
|
|
867
|
+
// A document carrying a settlement goes in the settlement list (the
|
|
868
|
+
// report counters are handled separately); a partial-only patch goes in
|
|
869
|
+
// the receipt list.
|
|
870
|
+
if (settlements.length > 0)
|
|
871
|
+
creditSettlementPatches.push({ report: patched, iteration });
|
|
872
|
+
else
|
|
873
|
+
creditReceiptPatches.push({ report: patched, iteration });
|
|
523
874
|
}
|
|
524
875
|
}
|
|
525
876
|
}
|
|
@@ -530,8 +881,11 @@ export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
|
530
881
|
creditWrites,
|
|
531
882
|
creditStaleHourDocuments,
|
|
532
883
|
creditSettlementPatches,
|
|
884
|
+
creditReceiptPatches,
|
|
533
885
|
creditSkippedDocuments,
|
|
534
886
|
skippedDocuments,
|
|
535
887
|
createdPeriodDocuments,
|
|
888
|
+
foldedPeriodDayDocuments,
|
|
889
|
+
foldedPeriodDayCreditDocuments,
|
|
536
890
|
};
|
|
537
891
|
}
|