@managesome/eposmatic-toolkit 0.4.29 → 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 +1 -0
- package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +129 -20
- package/esm/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
- package/esm/helpers/materialized-reports/materialized-discount-close-day-helpers.js +251 -240
- package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +2 -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/tenant-sales-overview-close-day-helpers.js +284 -43
- package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -4
- 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_sources.js +1 -1
- package/esm/schemas/models/orders.js +5 -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 +1 -0
- package/lib/helpers/materialized-reports/index.js +1 -0
- package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +38 -0
- package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +129 -19
- package/lib/helpers/materialized-reports/materialized-discount-classification-helpers.js +10 -3
- package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.d.ts +23 -61
- package/lib/helpers/materialized-reports/materialized-discount-close-day-helpers.js +250 -239
- package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.d.ts +4 -4
- package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +1 -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/tenant-sales-overview-close-day-helpers.d.ts +8 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +283 -42
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -4
- 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_sources.d.ts +6 -6
- package/lib/schemas/models/materialized_tenant_discount_sources.js +1 -1
- package/lib/schemas/models/orders.d.ts +5 -0
- package/lib/schemas/models/orders.js +5 -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_report_drilldown_rows.d.ts +8 -0
- package/lib/schemas/types/materialized_tenant_discount_entries.d.ts +9 -5
- package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +56 -1
- package/lib/tests/materialized-reports/materialized-discount-classification.test.js +17 -0
- package/lib/tests/materialized-reports/materialized-discount-close-day.test.js +60 -54
- 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 +152 -7
- package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +89 -0
- package/package.json +1 -1
|
@@ -26,6 +26,7 @@ const DISCOUNT_ACCUMULATED_SCOPES = MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT
|
|
|
26
26
|
/** True for the accumulating (period) scopes. */
|
|
27
27
|
const isAccumulatedScope = (scope) => DISCOUNT_ACCUMULATED_SCOPES.includes(scope);
|
|
28
28
|
const scopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
|
|
29
|
+
const entryPageKey = (doc) => `${scopeKey(doc)}|${doc.page}`;
|
|
29
30
|
/** Every stored scope one local day's plan needs (date + 3 periods + 24 hours). */
|
|
30
31
|
function getMaterializedDiscountScopeRefsForDay(localDate) {
|
|
31
32
|
const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
|
|
@@ -46,15 +47,12 @@ function getMaterializedDiscountScopeRefsForDay(localDate) {
|
|
|
46
47
|
return refs;
|
|
47
48
|
}
|
|
48
49
|
/* ------------------------------------------------------------------------ */
|
|
49
|
-
/* Period sibling-day enumeration
|
|
50
|
+
/* Period sibling-day enumeration for COUNTER repair only */
|
|
50
51
|
/* ------------------------------------------------------------------------ */
|
|
51
52
|
const pad2 = (value) => String(value).padStart(2, '0');
|
|
52
|
-
/** `'YYYY-MM-DD'` of a UTC calendar date. */
|
|
53
53
|
const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
|
|
54
|
-
/** Adds whole days to a UTC calendar date. */
|
|
55
54
|
const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
|
|
56
55
|
const daysInUtcMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
57
|
-
/** Adds every day of `count` whole months starting at (year, month). */
|
|
58
56
|
const addMonthDays = (year, month, count, days) => {
|
|
59
57
|
for (let offset = 0; offset < count; offset += 1) {
|
|
60
58
|
const date = new Date(Date.UTC(year, month - 1 + offset, 1));
|
|
@@ -67,17 +65,9 @@ const addMonthDays = (year, month, count, days) => {
|
|
|
67
65
|
}
|
|
68
66
|
return true;
|
|
69
67
|
};
|
|
70
|
-
/**
|
|
71
|
-
* Adds the day labels covered by ONE stored period scope value to `days`.
|
|
72
|
-
*
|
|
73
|
-
* Returns `false` (never throws) for a malformed / non-canonical scope value —
|
|
74
|
-
* a caller must not silently treat an unparseable period as "no sibling days",
|
|
75
|
-
* because that would make the `existingEntriesComplete` acknowledgement lie.
|
|
76
|
-
*/
|
|
77
68
|
const addPeriodDays = (scope, scopeField, days) => {
|
|
78
69
|
switch (scope) {
|
|
79
70
|
case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
|
|
80
|
-
// Sunday-based week start (the `localWeek` bucket identity).
|
|
81
71
|
const parts = (0, scope_helpers_1.parseMaterializedLocalDate)(scopeField);
|
|
82
72
|
if (parts == null)
|
|
83
73
|
return false;
|
|
@@ -89,7 +79,6 @@ const addPeriodDays = (scope, scopeField, days) => {
|
|
|
89
79
|
return true;
|
|
90
80
|
}
|
|
91
81
|
case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
|
|
92
|
-
// ISO week: the week-year may differ from the calendar year at boundaries.
|
|
93
82
|
const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
|
|
94
83
|
if (match == null)
|
|
95
84
|
return false;
|
|
@@ -97,7 +86,6 @@ const addPeriodDays = (scope, scopeField, days) => {
|
|
|
97
86
|
const week = Number(match[2]);
|
|
98
87
|
if (!Number.isInteger(week) || week < 1 || week > 53)
|
|
99
88
|
return false;
|
|
100
|
-
// ISO week 1 always contains Jan 4; its Monday is the week-1 Monday.
|
|
101
89
|
const jan4 = new Date(Date.UTC(weekYear, 0, 4));
|
|
102
90
|
const isoWeekday = jan4.getUTCDay() || 7;
|
|
103
91
|
const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
|
|
@@ -139,22 +127,9 @@ const addPeriodDays = (scope, scopeField, days) => {
|
|
|
139
127
|
}
|
|
140
128
|
};
|
|
141
129
|
/**
|
|
142
|
-
* Every `localDate`
|
|
143
|
-
* periods the closing day rolls into
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
* This is the **sibling-day fetch contract** in code: a close caller must fetch
|
|
147
|
-
* every `localDate` entry document whose `scope_field` is in this set, in
|
|
148
|
-
* addition to the day's own scope refs. Period entry documents are DERIVED from
|
|
149
|
-
* day rows, so a period document that was never persisted can only be rebuilt
|
|
150
|
-
* from the sibling days — without them the plan rebuilds the period from the
|
|
151
|
-
* closing day alone and every other day silently disappears from the period
|
|
152
|
-
* drill-down (see `buildTenantDiscountCloseDayPlan`).
|
|
153
|
-
*
|
|
154
|
-
* The returned set always contains `localDate` itself and is sorted. Returns
|
|
155
|
-
* `null` (never throws) for a malformed date or an unparseable period value —
|
|
156
|
-
* a `null` means the caller must fail loudly rather than pass an incomplete
|
|
157
|
-
* `existingEntries` set with `existingEntriesComplete: true`.
|
|
130
|
+
* Every `localDate` label whose day-scoped COUNTER documents can belong to the
|
|
131
|
+
* periods the closing day rolls into. Used ONLY to repair a missing period
|
|
132
|
+
* counter; entry pages are keyed by the closed day and never use this set.
|
|
158
133
|
*/
|
|
159
134
|
function getMaterializedDiscountPeriodDayScopeFields(localDate) {
|
|
160
135
|
const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
|
|
@@ -226,6 +201,36 @@ function isZeroCounters(counters) {
|
|
|
226
201
|
}
|
|
227
202
|
return true;
|
|
228
203
|
}
|
|
204
|
+
/** Sums a compiled period counter with sibling DAY counters (repair path). */
|
|
205
|
+
function buildDiscountCounterReplacement(existing, compiled, siblings) {
|
|
206
|
+
const counters = JSON.parse(JSON.stringify(compiled?.discount_counters ?? {}));
|
|
207
|
+
let watermark = new Date(compiled?.source_watermark ?? existing.source_watermark);
|
|
208
|
+
for (const sibling of siblings) {
|
|
209
|
+
if (sibling.schema_version !== existing.schema_version)
|
|
210
|
+
return null;
|
|
211
|
+
if ((sibling.sale_type_key_filters ?? []).join(':') !== (existing.sale_type_key_filters ?? []).join(':')) {
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
applyCounters(counters, sibling.discount_counters, 1);
|
|
215
|
+
const siblingWatermark = new Date(sibling.source_watermark);
|
|
216
|
+
if (siblingWatermark.getTime() > watermark.getTime())
|
|
217
|
+
watermark = siblingWatermark;
|
|
218
|
+
}
|
|
219
|
+
for (const key of Object.keys(counters)) {
|
|
220
|
+
if (isZeroCounters(counters[key]))
|
|
221
|
+
delete counters[key];
|
|
222
|
+
}
|
|
223
|
+
const finalCounters = Object.keys(counters).length === 0 ? null : counters;
|
|
224
|
+
return {
|
|
225
|
+
...existing,
|
|
226
|
+
discount_counters: finalCounters,
|
|
227
|
+
discount_counter_rows: finalCounters == null ? null : Object.entries(finalCounters).map(([key, value]) => ({ key, counters: value })),
|
|
228
|
+
source_watermark: watermark,
|
|
229
|
+
computed_at: existing.computed_at,
|
|
230
|
+
updatedAt: existing.updatedAt,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
const countDiscountEntryRows = (sections) => Object.values(sections ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
|
|
229
234
|
/**
|
|
230
235
|
* Applies a counter update to a stored document: optionally REPLACE the counter
|
|
231
236
|
* map wholesale, else subtract the given deltas and add the compiled ones. Keys
|
|
@@ -351,23 +356,18 @@ const subtractMaterializedDiscountEntrySections = (stored, removed) => {
|
|
|
351
356
|
};
|
|
352
357
|
exports.subtractMaterializedDiscountEntrySections = subtractMaterializedDiscountEntrySections;
|
|
353
358
|
/**
|
|
354
|
-
* Updates
|
|
355
|
-
*
|
|
356
|
-
* - DAY scopes (`localHour` / `localDate`) are REPLACED wholesale: the day's rows
|
|
357
|
-
* are the whole truth for that scope.
|
|
358
|
-
* - PERIOD scopes (`localWeek` / `localWeekOfYear` / `localMonth`) MERGE, because
|
|
359
|
-
* the compile produces only ONE day of rows: replacing would leave the period
|
|
360
|
-
* showing just its final day.
|
|
359
|
+
* Updates ONE stored ENTRY PAGE by replacing it with the compiled page. Rows
|
|
360
|
+
* never merge across pages; a source day is the whole truth for its page.
|
|
361
361
|
*
|
|
362
|
-
* Returns null when the documents disagree on schema/scope
|
|
363
|
-
* caller must surface).
|
|
362
|
+
* Returns null when the documents disagree on schema/scope/page.
|
|
364
363
|
*/
|
|
365
364
|
function updateMaterializedDiscountEntries(existing, compiled, options = {}) {
|
|
366
365
|
if (existing == null || compiled == null)
|
|
367
366
|
return null;
|
|
368
367
|
if (existing.schema_version !== compiled.schema_version ||
|
|
369
368
|
existing.scope_context !== compiled.scope_context ||
|
|
370
|
-
existing.scope_field !== compiled.scope_field
|
|
369
|
+
existing.scope_field !== compiled.scope_field ||
|
|
370
|
+
existing.page !== compiled.page) {
|
|
371
371
|
return null;
|
|
372
372
|
}
|
|
373
373
|
const computedAt = options.computedAt ?? new Date();
|
|
@@ -375,9 +375,8 @@ function updateMaterializedDiscountEntries(existing, compiled, options = {}) {
|
|
|
375
375
|
const compiledTime = new Date(compiled.source_watermark ?? 0).getTime();
|
|
376
376
|
return {
|
|
377
377
|
...existing,
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
: compiled.discount_entries,
|
|
378
|
+
page: compiled.page,
|
|
379
|
+
discount_entries: compiled.discount_entries,
|
|
381
380
|
source_watermark: compiledTime > existingTime ? compiled.source_watermark : existing.source_watermark,
|
|
382
381
|
computed_at: computedAt,
|
|
383
382
|
updatedAt: computedAt,
|
|
@@ -390,6 +389,8 @@ function needsMaterializedDiscountEntriesWrite(existing, incoming) {
|
|
|
390
389
|
return true;
|
|
391
390
|
if (existing.schema_version !== incoming.schema_version)
|
|
392
391
|
return true;
|
|
392
|
+
if (existing.page !== incoming.page)
|
|
393
|
+
return true;
|
|
393
394
|
if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
|
|
394
395
|
return true;
|
|
395
396
|
}
|
|
@@ -446,41 +447,46 @@ function buildTenantDiscountCloseDayPlan(input) {
|
|
|
446
447
|
if (String(prior._id) !== String(doc._id))
|
|
447
448
|
return null; // two rows for one scope
|
|
448
449
|
}
|
|
449
|
-
const
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
if (
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
450
|
+
const existingEntriesByPage = new Map();
|
|
451
|
+
const upperPeriodScopes = [
|
|
452
|
+
MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
|
|
453
|
+
MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
|
|
454
|
+
MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
|
|
455
|
+
];
|
|
456
|
+
const counterSiblingsForScope = (scopeContext, scopeField, referenceDoc) => {
|
|
457
|
+
const upper = upperPeriodScopes.includes(scopeContext);
|
|
458
|
+
const source = upper
|
|
459
|
+
? (input.existingPeriodMonthDocuments ?? []).filter((doc) => doc?.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH)
|
|
460
|
+
: (input.existingPeriodDayDocuments ?? []);
|
|
461
|
+
return source.filter((doc) => {
|
|
462
|
+
if (doc == null || doc.tenant_id !== tenantId)
|
|
463
|
+
return false;
|
|
464
|
+
if (!upper &&
|
|
465
|
+
(doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ||
|
|
466
|
+
typeof doc.scope_field !== 'string' ||
|
|
467
|
+
doc.scope_field === localDate)) {
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
if (typeof doc.scope_field !== 'string')
|
|
471
|
+
return false;
|
|
472
|
+
if (doc.schema_version !== referenceDoc.schema_version)
|
|
473
|
+
return false;
|
|
474
|
+
if ((doc.sale_type_key_filters ?? []).join(':') !== (referenceDoc.sale_type_key_filters ?? []).join(':')) {
|
|
475
|
+
return false;
|
|
476
|
+
}
|
|
477
|
+
const refs = getMaterializedDiscountScopeRefsForDay(doc.scope_field);
|
|
478
|
+
return refs != null && refs.some((ref) => ref.scope_context === scopeContext && ref.scope_field === scopeField);
|
|
479
|
+
});
|
|
476
480
|
};
|
|
477
481
|
for (const doc of input.existingEntries ?? []) {
|
|
478
482
|
if (doc == null || doc.tenant_id !== tenantId)
|
|
479
483
|
continue;
|
|
480
|
-
|
|
481
|
-
|
|
484
|
+
if (typeof doc.page !== 'string' || doc.page.length === 0)
|
|
485
|
+
return null; // no legacy guess
|
|
486
|
+
const key = entryPageKey(doc);
|
|
487
|
+
const prior = existingEntriesByPage.get(key);
|
|
482
488
|
if (prior == null) {
|
|
483
|
-
|
|
489
|
+
existingEntriesByPage.set(key, doc);
|
|
484
490
|
continue;
|
|
485
491
|
}
|
|
486
492
|
if (String(prior._id) !== String(doc._id))
|
|
@@ -520,34 +526,57 @@ function buildTenantDiscountCloseDayPlan(input) {
|
|
|
520
526
|
};
|
|
521
527
|
const storedDateDoc = existingByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
|
|
522
528
|
const storedDateDocInCompiled = compiledByScope.get(`${MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE}|${localDate}`) ?? null;
|
|
523
|
-
//
|
|
524
|
-
//
|
|
525
|
-
//
|
|
526
|
-
//
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
const storedDayEntrySections = {};
|
|
530
|
-
const isThisDayEntryDoc = (doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
|
|
531
|
-
? doc.scope_field === localDate
|
|
532
|
-
: doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
529
|
+
// A missing date document on a day with NO day-scoped counter/entry page is
|
|
530
|
+
// a FIRST close (additive). A surviving day page means the date counter was
|
|
531
|
+
// lost on an already-materialized day; period counters still repair by
|
|
532
|
+
// subtraction from the stored date counter.
|
|
533
|
+
const dayWasMaterialized = [...existingByScope.values()].some((doc) => (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
|
|
534
|
+
(doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
533
535
|
typeof doc.scope_field === 'string' &&
|
|
534
|
-
doc.scope_field.startsWith(`${localDate} `)
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
536
|
+
doc.scope_field.startsWith(`${localDate} `))) ||
|
|
537
|
+
[...existingEntriesByPage.values()].some((doc) => doc.page === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL &&
|
|
538
|
+
((doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && doc.scope_field === localDate) ||
|
|
539
|
+
(doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
540
|
+
typeof doc.scope_field === 'string' &&
|
|
541
|
+
doc.scope_field.startsWith(`${localDate} `))));
|
|
542
|
+
const isThisDayEntryPage = (doc) => doc.page === MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL &&
|
|
543
|
+
(doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
|
|
544
|
+
? doc.scope_field === localDate
|
|
545
|
+
: doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
546
|
+
typeof doc.scope_field === 'string' &&
|
|
547
|
+
doc.scope_field.startsWith(`${localDate} `));
|
|
544
548
|
if (reports.length === 0) {
|
|
545
|
-
// The day has NO discounts anymore (orders deleted / moved)
|
|
546
|
-
//
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
549
|
+
// The day has NO discounts anymore (orders deleted / moved). When the date
|
|
550
|
+
// document exists, subtract it; when it is MISSING, rebuild every period
|
|
551
|
+
// from the sibling DAY documents. Never silently leave a stale delta.
|
|
552
|
+
if (storedDateDoc == null && !dayWasMaterialized) {
|
|
553
|
+
const siblings = (input.existingPeriodDayDocuments ?? []).filter((sibling) => sibling?.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE && sibling.scope_field !== localDate);
|
|
554
|
+
const hasNonZeroPeriodCounter = [...existingByScope.values()].some((doc) => isAccumulatedScope(doc.scope_context) &&
|
|
555
|
+
!isZeroCounters(doc.discount_counters));
|
|
556
|
+
// A new empty day after earlier days is harmless (zero delta), but a
|
|
557
|
+
// lost date with no day evidence and no sibling proof must not be
|
|
558
|
+
// surfaced as "empty": the old delta may still sit in the periods.
|
|
559
|
+
if (hasNonZeroPeriodCounter && siblings.length === 0)
|
|
560
|
+
return null;
|
|
561
|
+
if (siblings.length === 0) {
|
|
562
|
+
return {
|
|
563
|
+
writes,
|
|
564
|
+
entryWrites,
|
|
565
|
+
staleDocuments,
|
|
566
|
+
staleEntryDocuments,
|
|
567
|
+
skippedDocuments,
|
|
568
|
+
skippedEntryDocuments,
|
|
569
|
+
createdPeriodDocuments,
|
|
570
|
+
foldedPeriodDayDocuments,
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
// Fall through: rebuild period counters from the sibling days (the
|
|
574
|
+
// current day contributes nothing), which removes any stale lost delta.
|
|
575
|
+
}
|
|
576
|
+
for (const doc of existingByScope.values()) {
|
|
577
|
+
if (!isAccumulatedScope(doc.scope_context))
|
|
578
|
+
continue;
|
|
579
|
+
if (storedDateDoc != null) {
|
|
551
580
|
const updated = updateMaterializedDiscountReport(doc, { subtract: [storedDateDoc] }, { computedAt });
|
|
552
581
|
if (updated == null)
|
|
553
582
|
return null;
|
|
@@ -555,47 +584,43 @@ function buildTenantDiscountCloseDayPlan(input) {
|
|
|
555
584
|
continue;
|
|
556
585
|
if (addWrite(updated) == null)
|
|
557
586
|
return null;
|
|
587
|
+
continue;
|
|
558
588
|
}
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
staleEntryDocuments.push(doc);
|
|
572
|
-
}
|
|
573
|
-
for (const doc of existingEntriesByScope.values()) {
|
|
574
|
-
// Another day's document is not this close's business - never touch it.
|
|
575
|
-
if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
|
|
576
|
-
continue;
|
|
577
|
-
const remaining = (0, exports.subtractMaterializedDiscountEntrySections)(doc.discount_entries, storedDayEntrySections);
|
|
578
|
-
const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
|
|
579
|
-
const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
|
|
580
|
-
// Nothing of this day was in that period: leave it untouched.
|
|
581
|
-
if (rowsAfter === rowsBefore)
|
|
582
|
-
continue;
|
|
583
|
-
// No rows left anywhere in the period: the document itself goes.
|
|
584
|
-
if (rowsAfter === 0) {
|
|
585
|
-
staleEntryDocuments.push(doc);
|
|
586
|
-
continue;
|
|
587
|
-
}
|
|
588
|
-
if (addEntryWrite({
|
|
589
|
-
...doc,
|
|
590
|
-
discount_entries: remaining,
|
|
591
|
-
computed_at: computedAt,
|
|
592
|
-
updatedAt: computedAt,
|
|
593
|
-
iteration: (doc.iteration ?? 1) + 1,
|
|
594
|
-
}) == null) {
|
|
595
|
-
return null;
|
|
589
|
+
const referenceDoc = storedDateDocInCompiled ?? reports[0] ?? doc;
|
|
590
|
+
const siblings = (input.existingPeriodDayDocuments ?? []).filter((sibling) => {
|
|
591
|
+
if (sibling == null || sibling.tenant_id !== tenantId)
|
|
592
|
+
return false;
|
|
593
|
+
if (sibling.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
|
|
594
|
+
return false;
|
|
595
|
+
if (typeof sibling.scope_field !== 'string' || sibling.scope_field === localDate)
|
|
596
|
+
return false;
|
|
597
|
+
if (sibling.schema_version !== referenceDoc.schema_version)
|
|
598
|
+
return false;
|
|
599
|
+
if ((sibling.sale_type_key_filters ?? []).join(':') !== (referenceDoc.sale_type_key_filters ?? []).join(':')) {
|
|
600
|
+
return false;
|
|
596
601
|
}
|
|
602
|
+
const refs = getMaterializedDiscountScopeRefsForDay(sibling.scope_field);
|
|
603
|
+
return (refs != null &&
|
|
604
|
+
refs.some((ref) => ref.scope_context === doc.scope_context && ref.scope_field === doc.scope_field));
|
|
605
|
+
});
|
|
606
|
+
if (siblings.length === 0 && !isZeroCounters(doc.discount_counters)) {
|
|
607
|
+
return null; // unprovable repair: non-empty period with no sibling evidence
|
|
597
608
|
}
|
|
609
|
+
const replacement = buildDiscountCounterReplacement(doc, null, siblings);
|
|
610
|
+
if (replacement == null)
|
|
611
|
+
return null;
|
|
612
|
+
const updated = updateMaterializedDiscountReport(doc, { replacement }, { computedAt });
|
|
613
|
+
if (updated == null || addWrite(updated) == null)
|
|
614
|
+
return null;
|
|
615
|
+
}
|
|
616
|
+
for (const doc of existingByScope.values()) {
|
|
617
|
+
if (DISCOUNT_DAY_SCOPES.includes(doc.scope_context))
|
|
618
|
+
staleDocuments.push(doc);
|
|
598
619
|
}
|
|
620
|
+
// Every entry page fetched by this close belongs to the closing day; an
|
|
621
|
+
// emptied day deletes exactly those pages.
|
|
622
|
+
for (const doc of existingEntriesByPage.values())
|
|
623
|
+
staleEntryDocuments.push(doc);
|
|
599
624
|
return {
|
|
600
625
|
writes,
|
|
601
626
|
entryWrites,
|
|
@@ -641,22 +666,28 @@ function buildTenantDiscountCloseDayPlan(input) {
|
|
|
641
666
|
// the period equals the sum of its days again. The closing day's own
|
|
642
667
|
// stored date document is excluded by the input contract.
|
|
643
668
|
const referenceDoc = storedDateDocInCompiled ?? reports[0];
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
if (
|
|
648
|
-
return
|
|
649
|
-
if (
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
669
|
+
let siblings = counterSiblingsForScope(compiled.scope_context, String(compiled.scope_field), referenceDoc);
|
|
670
|
+
if (upperPeriodScopes.includes(compiled.scope_context)) {
|
|
671
|
+
const currentMonth = localDate.slice(0, 7);
|
|
672
|
+
if (storedDateDoc == null && dayWasMaterialized)
|
|
673
|
+
return null;
|
|
674
|
+
if (storedDateDoc != null) {
|
|
675
|
+
if (!siblings.some((doc) => doc.scope_field === currentMonth))
|
|
676
|
+
return null;
|
|
677
|
+
const corrected = [];
|
|
678
|
+
for (const month of siblings) {
|
|
679
|
+
if (month.scope_field !== currentMonth) {
|
|
680
|
+
corrected.push(month);
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
const withoutDay = updateMaterializedDiscountReport(month, { subtract: [storedDateDoc] }, { computedAt });
|
|
684
|
+
if (withoutDay == null)
|
|
685
|
+
return null;
|
|
686
|
+
corrected.push(withoutDay);
|
|
687
|
+
}
|
|
688
|
+
siblings = corrected;
|
|
655
689
|
}
|
|
656
|
-
|
|
657
|
-
return (refs != null &&
|
|
658
|
-
refs.some((ref) => ref.scope_context === compiled.scope_context && ref.scope_field === compiled.scope_field));
|
|
659
|
-
});
|
|
690
|
+
}
|
|
660
691
|
let created = compiled;
|
|
661
692
|
if (siblings.length > 0) {
|
|
662
693
|
const counters = JSON.parse(JSON.stringify(compiled.discount_counters ?? {}));
|
|
@@ -690,7 +721,49 @@ function buildTenantDiscountCloseDayPlan(input) {
|
|
|
690
721
|
createdPeriodDocuments.push({ scope_context: compiled.scope_context, scope_field: compiled.scope_field });
|
|
691
722
|
continue;
|
|
692
723
|
}
|
|
693
|
-
|
|
724
|
+
if (storedDateDoc == null && dayWasMaterialized && upperPeriodScopes.includes(compiled.scope_context)) {
|
|
725
|
+
return null; // month docs may still contain the lost day
|
|
726
|
+
}
|
|
727
|
+
if (storedDateDoc == null && !dayWasMaterialized) {
|
|
728
|
+
const siblings = counterSiblingsForScope(compiled.scope_context, String(compiled.scope_field), compiled);
|
|
729
|
+
if (siblings.length === 0) {
|
|
730
|
+
if (!isZeroCounters(existing.discount_counters)) {
|
|
731
|
+
return null;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
else {
|
|
735
|
+
const siblingOnly = buildDiscountCounterReplacement(existing, null, siblings);
|
|
736
|
+
if (siblingOnly == null ||
|
|
737
|
+
JSON.stringify(siblingOnly.discount_counters ?? {}) !== JSON.stringify(existing.discount_counters ?? {})) {
|
|
738
|
+
return null;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
const updated = updateMaterializedDiscountReport(existing, { additions: [compiled] }, { computedAt });
|
|
742
|
+
if (updated == null)
|
|
743
|
+
return null;
|
|
744
|
+
if ((updated.iteration ?? 1) === (existing.iteration ?? 1)) {
|
|
745
|
+
skippedDocuments.push(existing);
|
|
746
|
+
continue;
|
|
747
|
+
}
|
|
748
|
+
if (addWrite(updated) == null)
|
|
749
|
+
return null;
|
|
750
|
+
continue;
|
|
751
|
+
}
|
|
752
|
+
if (storedDateDoc == null) {
|
|
753
|
+
const siblings = counterSiblingsForScope(compiled.scope_context, String(compiled.scope_field), compiled);
|
|
754
|
+
if (siblings.length === 0 &&
|
|
755
|
+
!isZeroCounters(existing.discount_counters)) {
|
|
756
|
+
return null; // unprovable repair: non-empty period with no sibling evidence
|
|
757
|
+
}
|
|
758
|
+
const replacement = buildDiscountCounterReplacement(existing, compiled, siblings);
|
|
759
|
+
if (replacement == null)
|
|
760
|
+
return null;
|
|
761
|
+
const updated = updateMaterializedDiscountReport(existing, { replacement }, { computedAt });
|
|
762
|
+
if (updated == null || addWrite(updated) == null)
|
|
763
|
+
return null;
|
|
764
|
+
continue;
|
|
765
|
+
}
|
|
766
|
+
const updated = updateMaterializedDiscountReport(existing, { subtract: [storedDateDoc], additions: [compiled] }, { computedAt });
|
|
694
767
|
if (updated == null || addWrite(updated) == null)
|
|
695
768
|
return null;
|
|
696
769
|
}
|
|
@@ -704,110 +777,48 @@ function buildTenantDiscountCloseDayPlan(input) {
|
|
|
704
777
|
}
|
|
705
778
|
}
|
|
706
779
|
}
|
|
707
|
-
// ---- entry
|
|
708
|
-
//
|
|
709
|
-
//
|
|
710
|
-
|
|
780
|
+
// ---- entry pages ---------------------------------------------------------
|
|
781
|
+
// Each period scope is partitioned by the source day; day/hour pages are the
|
|
782
|
+
// single 'all' page. A close replaces ONLY the closing day's pages and deletes
|
|
783
|
+
// that page if the day no longer has rows.
|
|
784
|
+
const compiledEntriesByPage = new Map();
|
|
711
785
|
for (const doc of entries) {
|
|
712
786
|
if (doc == null || doc.tenant_id !== tenantId)
|
|
713
787
|
return null;
|
|
714
|
-
|
|
715
|
-
|
|
788
|
+
if (typeof doc.page !== 'string' || doc.page.length === 0)
|
|
789
|
+
return null;
|
|
790
|
+
const expectedPage = DISCOUNT_DAY_SCOPES.includes(doc.scope_context)
|
|
791
|
+
? MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL
|
|
792
|
+
: localDate;
|
|
793
|
+
if (doc.page !== expectedPage)
|
|
794
|
+
return null;
|
|
795
|
+
const key = entryPageKey(doc);
|
|
796
|
+
if (compiledEntriesByPage.has(key))
|
|
716
797
|
return null; // duplicate — data issue
|
|
717
|
-
|
|
798
|
+
compiledEntriesByPage.set(key, doc);
|
|
718
799
|
}
|
|
719
|
-
for (const compiled of
|
|
720
|
-
const
|
|
800
|
+
for (const compiled of compiledEntriesByPage.values()) {
|
|
801
|
+
const key = entryPageKey(compiled);
|
|
802
|
+
const existing = existingEntriesByPage.get(key) ?? null;
|
|
721
803
|
if (!dayChanged && existing != null && !needsMaterializedDiscountEntriesWrite(existing, compiled)) {
|
|
722
804
|
skippedEntryDocuments.push(existing);
|
|
723
805
|
continue;
|
|
724
806
|
}
|
|
725
807
|
if (existing == null) {
|
|
726
|
-
|
|
727
|
-
if (!missingIsPeriod) {
|
|
728
|
-
if (addEntryWrite(compiled) == null)
|
|
729
|
-
return null;
|
|
730
|
-
continue;
|
|
731
|
-
}
|
|
732
|
-
// A missing period entry document is a partial write only when the period
|
|
733
|
-
// COUNTER document exists. Refuse to rebuild from an unverified fetch.
|
|
734
|
-
const periodCounterExists = existingByScope.has(scopeKey(compiled));
|
|
735
|
-
if (periodCounterExists && input.existingEntriesComplete !== true) {
|
|
736
|
-
return null;
|
|
737
|
-
}
|
|
738
|
-
// Never persisted: rebuild from the sibling days, minus this day's stored rows (a
|
|
739
|
-
// correction may have REMOVED rows), then merge this day's fresh rows on top.
|
|
740
|
-
const folded = (0, exports.subtractMaterializedDiscountEntrySections)(refoldPeriodEntrySections(compiled.scope_context, String(compiled.scope_field)), storedDayEntrySections);
|
|
741
|
-
const rebuilt = (0, exports.mergeMaterializedDiscountEntrySections)(folded, compiled.discount_entries);
|
|
742
|
-
if (addEntryWrite({ ...compiled, discount_entries: rebuilt }) == null)
|
|
808
|
+
if (addEntryWrite(compiled) == null)
|
|
743
809
|
return null;
|
|
744
810
|
continue;
|
|
745
811
|
}
|
|
746
|
-
|
|
747
|
-
// the day itself. Replacing a period wholesale left it holding only the
|
|
748
|
-
// final closed day (measured).
|
|
749
|
-
const isPeriodEntry = !DISCOUNT_DAY_SCOPES.includes(compiled.scope_context);
|
|
750
|
-
// PERIOD documents: remove this day's STORED rows FIRST, then merge the fresh ones.
|
|
751
|
-
// Merging alone cannot remove, so a correction that dropped a row left it behind in
|
|
752
|
-
// the period while the day document shrank - a phantom row in the period drill-down.
|
|
753
|
-
// DAY documents are replaced wholesale and need no subtraction.
|
|
754
|
-
const updated = updateMaterializedDiscountEntries(isPeriodEntry
|
|
755
|
-
? {
|
|
756
|
-
...existing,
|
|
757
|
-
discount_entries: (0, exports.subtractMaterializedDiscountEntrySections)(existing.discount_entries, storedDayEntrySections),
|
|
758
|
-
}
|
|
759
|
-
: existing, compiled, { computedAt, mergePeriodRows: isPeriodEntry });
|
|
812
|
+
const updated = updateMaterializedDiscountEntries(existing, compiled, { computedAt });
|
|
760
813
|
if (updated == null || addEntryWrite(updated) == null)
|
|
761
814
|
return null;
|
|
762
815
|
}
|
|
763
|
-
//
|
|
764
|
-
|
|
765
|
-
|
|
816
|
+
// Only the closing day's pages were fetched, so anything not recompiled is a
|
|
817
|
+
// page this day no longer owns: delete it. Other days' pages are untouched.
|
|
818
|
+
for (const doc of existingEntriesByPage.values()) {
|
|
819
|
+
if (compiledEntriesByPage.has(entryPageKey(doc)))
|
|
766
820
|
continue;
|
|
767
|
-
|
|
768
|
-
? doc.scope_field === localDate
|
|
769
|
-
: doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
770
|
-
typeof doc.scope_field === 'string' &&
|
|
771
|
-
doc.scope_field.startsWith(`${localDate} `);
|
|
772
|
-
if (isDayScoped) {
|
|
773
|
-
staleEntryDocuments.push(doc);
|
|
774
|
-
continue;
|
|
775
|
-
}
|
|
776
|
-
// A DAY-scoped document belonging to ANOTHER day is simply not this close's
|
|
777
|
-
// business. Without this guard it fell through to the period branch below, where
|
|
778
|
-
// the compile had (correctly) not emitted it, so it was marked STALE and DELETED -
|
|
779
|
-
// meaning every close wiped every OTHER day's entry rows. Measured in the demo data
|
|
780
|
-
// before the fix: counters covered 19 discount days while only ONE day of entry rows
|
|
781
|
-
// survived, so the drill-down was empty for 18 days that the summary said had
|
|
782
|
-
// discounts. The period branch must only ever see PERIOD scopes.
|
|
783
|
-
if (doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ||
|
|
784
|
-
doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
|
|
785
|
-
continue;
|
|
786
|
-
}
|
|
787
|
-
// The compiled day has no rows in this period scope. That does NOT mean the
|
|
788
|
-
// period is empty: a period entry document accumulates EVERY day's rows, so
|
|
789
|
-
// deleting it would wipe the sibling days that exist nowhere else. Subtract
|
|
790
|
-
// the rows this day currently contributes (read from its day-scoped entry
|
|
791
|
-
// documents) and drop the document only when nothing remains.
|
|
792
|
-
const remaining = (0, exports.subtractMaterializedDiscountEntrySections)(doc.discount_entries, storedDayEntrySections);
|
|
793
|
-
const rowsBefore = Object.values(doc.discount_entries ?? {}).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
|
|
794
|
-
const rowsAfter = Object.values(remaining).reduce((sum, section) => sum + (section?.rows ?? []).length, 0);
|
|
795
|
-
// Nothing of this day was in that period: leave it untouched.
|
|
796
|
-
if (rowsAfter === rowsBefore)
|
|
797
|
-
continue;
|
|
798
|
-
if (rowsAfter === 0) {
|
|
799
|
-
staleEntryDocuments.push(doc);
|
|
800
|
-
continue;
|
|
801
|
-
}
|
|
802
|
-
if (addEntryWrite({
|
|
803
|
-
...doc,
|
|
804
|
-
discount_entries: remaining,
|
|
805
|
-
computed_at: computedAt,
|
|
806
|
-
updatedAt: computedAt,
|
|
807
|
-
iteration: (doc.iteration ?? 1) + 1,
|
|
808
|
-
}) == null) {
|
|
809
|
-
return null;
|
|
810
|
-
}
|
|
821
|
+
staleEntryDocuments.push(doc);
|
|
811
822
|
}
|
|
812
823
|
return {
|
|
813
824
|
writes,
|