@managesome/eposmatic-toolkit 0.4.55 → 0.4.57
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 +91 -0
- package/esm/helpers/materialized-reports/index.js +7 -0
- package/esm/helpers/materialized-reports/materialized-dialer-accumulator-helpers.js +100 -0
- package/esm/helpers/materialized-reports/materialized-dialer-close-day-helpers.js +328 -0
- package/esm/helpers/materialized-reports/materialized-dialer-compile-helpers.js +180 -0
- package/esm/helpers/materialized-reports/materialized-dialer-entry-pages.js +222 -0
- package/esm/helpers/materialized-reports/materialized-dialer-key-helpers.js +82 -0
- package/esm/helpers/materialized-reports/materialized-dialer-masking.js +54 -0
- package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
- package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +13 -1
- package/esm/helpers/materialized-reports/report-platform/definition.js +87 -3
- package/esm/helpers/materialized-reports/tenant-dialer-formatter.js +95 -0
- package/esm/helpers/reporting-contract/report-contract.js +3 -0
- package/esm/schemas/models/index.js +2 -0
- package/esm/schemas/models/materialized_report_drilldown_rows.js +1 -0
- package/esm/schemas/models/materialized_tenant_delivery_entries.js +5 -5
- package/esm/schemas/models/materialized_tenant_delivery_reports.js +7 -7
- package/esm/schemas/models/materialized_tenant_dialer_entries.js +65 -0
- package/esm/schemas/models/materialized_tenant_dialer_reports.js +66 -0
- package/esm/schemas/types/index.js +2 -0
- package/esm/schemas/types/materialized_report_drilldown_rows.js +1 -0
- package/esm/schemas/types/materialized_tenant_dialer_entries.js +1 -0
- package/esm/schemas/types/materialized_tenant_dialer_reports.js +7 -0
- package/lib/constants/MATERIALIZED_REPORTS.d.ts +72 -2
- package/lib/constants/MATERIALIZED_REPORTS.js +93 -1
- package/lib/helpers/materialized-reports/index.d.ts +7 -0
- package/lib/helpers/materialized-reports/index.js +7 -0
- package/lib/helpers/materialized-reports/materialized-dialer-accumulator-helpers.d.ts +39 -0
- package/lib/helpers/materialized-reports/materialized-dialer-accumulator-helpers.js +110 -0
- package/lib/helpers/materialized-reports/materialized-dialer-close-day-helpers.d.ts +90 -0
- package/lib/helpers/materialized-reports/materialized-dialer-close-day-helpers.js +340 -0
- package/lib/helpers/materialized-reports/materialized-dialer-compile-helpers.d.ts +67 -0
- package/lib/helpers/materialized-reports/materialized-dialer-compile-helpers.js +183 -0
- package/lib/helpers/materialized-reports/materialized-dialer-entry-pages.d.ts +97 -0
- package/lib/helpers/materialized-reports/materialized-dialer-entry-pages.js +235 -0
- package/lib/helpers/materialized-reports/materialized-dialer-key-helpers.d.ts +51 -0
- package/lib/helpers/materialized-reports/materialized-dialer-key-helpers.js +90 -0
- package/lib/helpers/materialized-reports/materialized-dialer-masking.d.ts +35 -0
- package/lib/helpers/materialized-reports/materialized-dialer-masking.js +57 -0
- package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
- package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +13 -1
- package/lib/helpers/materialized-reports/report-platform/definition.js +86 -2
- package/lib/helpers/materialized-reports/tenant-dialer-formatter.d.ts +91 -0
- package/lib/helpers/materialized-reports/tenant-dialer-formatter.js +98 -0
- package/lib/helpers/reporting-contract/report-contract.d.ts +1 -0
- package/lib/helpers/reporting-contract/report-contract.js +3 -0
- package/lib/schemas/models/index.d.ts +2 -0
- package/lib/schemas/models/index.js +2 -0
- package/lib/schemas/models/materialized_report_drilldown_rows.js +1 -0
- package/lib/schemas/models/materialized_tenant_delivery_entries.d.ts +5 -5
- package/lib/schemas/models/materialized_tenant_delivery_entries.js +5 -5
- package/lib/schemas/models/materialized_tenant_delivery_reports.d.ts +7 -7
- package/lib/schemas/models/materialized_tenant_delivery_reports.js +7 -7
- package/lib/schemas/models/materialized_tenant_dialer_entries.d.ts +107 -0
- package/lib/schemas/models/materialized_tenant_dialer_entries.js +68 -0
- package/lib/schemas/models/materialized_tenant_dialer_reports.d.ts +100 -0
- package/lib/schemas/models/materialized_tenant_dialer_reports.js +69 -0
- package/lib/schemas/models/tenant_dialer_events.d.ts +3 -3
- package/lib/schemas/types/index.d.ts +2 -0
- package/lib/schemas/types/index.js +2 -0
- package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +1 -1
- package/lib/schemas/types/materialized_report_drilldown_rows.js +1 -0
- package/lib/schemas/types/materialized_tenant_dialer_entries.d.ts +83 -0
- package/lib/schemas/types/materialized_tenant_dialer_entries.js +2 -0
- package/lib/schemas/types/materialized_tenant_dialer_reports.d.ts +77 -0
- package/lib/schemas/types/materialized_tenant_dialer_reports.js +10 -0
- package/lib/tests/materialized-reports/materialized-delivery-plan.test.js +1 -1
- package/lib/tests/materialized-reports/materialized-delivery-practical.test.js +1 -1
- package/lib/tests/materialized-reports/materialized-dialer-compile.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-dialer-compile.test.js +213 -0
- package/lib/tests/materialized-reports/materialized-dialer-formatter.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-dialer-formatter.test.js +159 -0
- package/lib/tests/materialized-reports/materialized-dialer-plan.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-dialer-plan.test.js +223 -0
- package/lib/tests/materialized-reports/materialized-tenant-dialer-schema.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-tenant-dialer-schema.test.js +183 -0
- package/lib/tests/materialized-reports/report-platform/registry-conformance.test.js +16 -3
- package/package.json +1 -1
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.isMaterializedDialerDayScope = exports.MATERIALIZED_DIALER_PERIOD_SCOPES = void 0;
|
|
7
|
+
exports.getMaterializedDialerReportPeriodDayScopeFields = getMaterializedDialerReportPeriodDayScopeFields;
|
|
8
|
+
exports.needsMaterializedDialerReportWrite = needsMaterializedDialerReportWrite;
|
|
9
|
+
exports.needsMaterializedDialerEntriesWrite = needsMaterializedDialerEntriesWrite;
|
|
10
|
+
exports.foldMaterializedDialerPeriodCounters = foldMaterializedDialerPeriodCounters;
|
|
11
|
+
exports.buildTenantDialerCloseDayPlan = buildTenantDialerCloseDayPlan;
|
|
12
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
13
|
+
const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
|
|
14
|
+
const materialized_tenant_dialer_reports_1 = require("../../schemas/models/materialized_tenant_dialer_reports");
|
|
15
|
+
const materialized_dialer_accumulator_helpers_1 = require("./materialized-dialer-accumulator-helpers");
|
|
16
|
+
const materialized_dialer_entry_pages_1 = require("./materialized-dialer-entry-pages");
|
|
17
|
+
const materialized_document_size_1 = require("./materialized-document-size");
|
|
18
|
+
const materialized_tenant_reports_iterations_helpers_1 = require("./materialized-tenant-reports-iterations-helpers");
|
|
19
|
+
const scope_helpers_1 = require("./scope-helpers");
|
|
20
|
+
/**
|
|
21
|
+
* Dialer close-day helpers.
|
|
22
|
+
*
|
|
23
|
+
* ## Period counters are RE-FOLDED from sibling DAY documents
|
|
24
|
+
*
|
|
25
|
+
* A period document is a plain sum of its days' event counters, so removing a
|
|
26
|
+
* day from a period is subtractable in principle — but re-folding is the
|
|
27
|
+
* platform rule and the only way an emptied/recompiled day stays exact. Every
|
|
28
|
+
* touched period is rebuilt from its whole day set (the closing day's fresh
|
|
29
|
+
* document plus the stored sibling DAY documents the caller fetched).
|
|
30
|
+
*
|
|
31
|
+
* ## ENTRY pages are NEVER folded
|
|
32
|
+
*
|
|
33
|
+
* `materialized_tenant_dialer_entries` is page-partitioned by source day: the
|
|
34
|
+
* caller fetches exactly the closing day's pages, each is replaced by its page
|
|
35
|
+
* identity, and a fetched page the day no longer owns is deleted. No other
|
|
36
|
+
* day's page is read, merged or rewritten.
|
|
37
|
+
*/
|
|
38
|
+
/** Period COUNTER scopes this report materializes (everything but the day scope). */
|
|
39
|
+
exports.MATERIALIZED_DIALER_PERIOD_SCOPES = MATERIALIZED_REPORTS_1.MATERIALIZED_DIALER_REPORT_SCOPES.filter((scope) => String(scope) !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
|
|
40
|
+
/**
|
|
41
|
+
* Every `localDate` label whose DAY counter document can contribute to a period
|
|
42
|
+
* the closing day rolls into. The worker uses it to fetch exactly the sibling
|
|
43
|
+
* DAY counters the period re-fold needs.
|
|
44
|
+
*/
|
|
45
|
+
function getMaterializedDialerReportPeriodDayScopeFields(localDate) {
|
|
46
|
+
return (0, scope_helpers_1.enumerateMaterializedPeriodDays)(localDate, exports.MATERIALIZED_DIALER_PERIOD_SCOPES);
|
|
47
|
+
}
|
|
48
|
+
/** True when the scope is the plain day scope. */
|
|
49
|
+
const isMaterializedDialerDayScope = (scopeContext) => String(scopeContext) === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE;
|
|
50
|
+
exports.isMaterializedDialerDayScope = isMaterializedDialerDayScope;
|
|
51
|
+
const dialerScopeKey = (doc) => String(doc.scope_context) + '|' + String(doc.scope_field);
|
|
52
|
+
/** True when the stored document does not already carry this exact content. */
|
|
53
|
+
function needsMaterializedDialerReportWrite(existing, next) {
|
|
54
|
+
if (existing == null)
|
|
55
|
+
return true;
|
|
56
|
+
const stored = new Date(existing.source_watermark ?? 0).getTime();
|
|
57
|
+
const incoming = new Date(next.source_watermark ?? 0).getTime();
|
|
58
|
+
if (Number.isNaN(stored) || Number.isNaN(incoming))
|
|
59
|
+
return true;
|
|
60
|
+
return incoming > stored;
|
|
61
|
+
}
|
|
62
|
+
/** True when the stored entry page does not already carry these exact rows. */
|
|
63
|
+
function needsMaterializedDialerEntriesWrite(existing, next) {
|
|
64
|
+
if (existing == null)
|
|
65
|
+
return true;
|
|
66
|
+
const stored = new Date(existing.source_watermark ?? 0).getTime();
|
|
67
|
+
const incoming = new Date(next.source_watermark ?? 0).getTime();
|
|
68
|
+
if (Number.isNaN(stored) || Number.isNaN(incoming))
|
|
69
|
+
return true;
|
|
70
|
+
return incoming > stored;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Folds the counters of every DAY document belonging to one period scope.
|
|
74
|
+
*
|
|
75
|
+
* The fold is key-addressed: two days that observed the same
|
|
76
|
+
* `<ACTION>:<POS_ID>:<STAFF_ID>` merge their counters; keys only one day
|
|
77
|
+
* observed keep their own block.
|
|
78
|
+
*/
|
|
79
|
+
function foldMaterializedDialerPeriodCounters(input) {
|
|
80
|
+
const { periodScope, periodScopeField, dayDocuments } = input;
|
|
81
|
+
const folded = {};
|
|
82
|
+
for (const dayDocument of dayDocuments ?? []) {
|
|
83
|
+
if (!(0, exports.isMaterializedDialerDayScope)(String(dayDocument?.scope_context)))
|
|
84
|
+
continue;
|
|
85
|
+
const fields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(String(dayDocument.scope_field));
|
|
86
|
+
if (fields == null)
|
|
87
|
+
continue;
|
|
88
|
+
if (fields[periodScope] !== periodScopeField)
|
|
89
|
+
continue;
|
|
90
|
+
for (const [key, block] of Object.entries(dayDocument.dialer_counters ?? {})) {
|
|
91
|
+
const target = folded[key] ?? (0, materialized_dialer_accumulator_helpers_1.freshDialerCounters)();
|
|
92
|
+
(0, materialized_dialer_accumulator_helpers_1.mergeDialerCounters)(target, block);
|
|
93
|
+
folded[key] = target;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return folded;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Builds the close-day plan for ONE tenant-day.
|
|
100
|
+
*
|
|
101
|
+
* The DAY scope comes from the compile. Every touched PERIOD scope is re-folded
|
|
102
|
+
* from its whole day set; the touched set is the union of the closing day's
|
|
103
|
+
* periods AND the periods of any day document this close removes.
|
|
104
|
+
*/
|
|
105
|
+
function buildTenantDialerCloseDayPlan(input) {
|
|
106
|
+
if (input == null)
|
|
107
|
+
return null;
|
|
108
|
+
const { tenantId, reports, entries, reason } = input;
|
|
109
|
+
if (typeof tenantId !== 'string' || tenantId.length === 0)
|
|
110
|
+
return null;
|
|
111
|
+
if (typeof reason !== 'string' || reason.length === 0)
|
|
112
|
+
return null;
|
|
113
|
+
const computedAt = input.computedAt ?? new Date();
|
|
114
|
+
const force = input.force === true;
|
|
115
|
+
const compiledReports = (reports ?? []).filter((doc) => String(doc?.tenant_id) === tenantId);
|
|
116
|
+
const compiledEntries = (entries ?? []).filter((doc) => String(doc?.tenant_id) === tenantId);
|
|
117
|
+
const storedReports = (input.existing ?? []).filter((doc) => String(doc?.tenant_id) === tenantId);
|
|
118
|
+
const storedEntries = (input.existingEntries ?? []).filter((doc) => String(doc?.tenant_id) === tenantId);
|
|
119
|
+
const compiledDateDoc = compiledReports.find((doc) => (0, exports.isMaterializedDialerDayScope)(String(doc.scope_context)));
|
|
120
|
+
const localDate = input.localDate ?? (compiledDateDoc == null ? null : String(compiledDateDoc.scope_field));
|
|
121
|
+
if (localDate == null || localDate === '')
|
|
122
|
+
return null;
|
|
123
|
+
const writes = [];
|
|
124
|
+
const entryWrites = [];
|
|
125
|
+
const staleDocuments = [];
|
|
126
|
+
const staleEntryDocuments = [];
|
|
127
|
+
const skippedDocuments = [];
|
|
128
|
+
const skippedEntryDocuments = [];
|
|
129
|
+
const storedReportsByScope = new Map();
|
|
130
|
+
for (const doc of storedReports)
|
|
131
|
+
storedReportsByScope.set(dialerScopeKey(doc), doc);
|
|
132
|
+
const storedEntriesByPage = new Map();
|
|
133
|
+
for (const doc of storedEntries) {
|
|
134
|
+
// Legacy page-less entry documents are inconsistent input: the caller must
|
|
135
|
+
// fetch page-partitioned documents only.
|
|
136
|
+
if (typeof doc.page !== 'string' || doc.page === '')
|
|
137
|
+
return null;
|
|
138
|
+
storedEntriesByPage.set((0, materialized_dialer_entry_pages_1.materializedDialerEntryPageKey)(doc), doc);
|
|
139
|
+
}
|
|
140
|
+
const addWrite = (report) => {
|
|
141
|
+
const persisted = report.iteration == null ? { ...report, iteration: 1 } : report;
|
|
142
|
+
const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(persisted, {
|
|
143
|
+
reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DIALER_REPORTS,
|
|
144
|
+
reason,
|
|
145
|
+
computedAt,
|
|
146
|
+
});
|
|
147
|
+
if (iteration == null)
|
|
148
|
+
return false;
|
|
149
|
+
writes.push({ report: persisted, iteration: iteration });
|
|
150
|
+
return true;
|
|
151
|
+
};
|
|
152
|
+
const addEntryWrite = (report) => {
|
|
153
|
+
const persisted = report.iteration == null ? { ...report, iteration: 1 } : report;
|
|
154
|
+
const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(persisted, {
|
|
155
|
+
reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DIALER_ENTRIES,
|
|
156
|
+
reason,
|
|
157
|
+
computedAt,
|
|
158
|
+
});
|
|
159
|
+
if (iteration == null)
|
|
160
|
+
return false;
|
|
161
|
+
entryWrites.push({ report: persisted, iteration: iteration });
|
|
162
|
+
return true;
|
|
163
|
+
};
|
|
164
|
+
// ---- the DAY scope, straight from the compile ----
|
|
165
|
+
if (compiledDateDoc != null) {
|
|
166
|
+
const existing = storedReportsByScope.get(dialerScopeKey(compiledDateDoc));
|
|
167
|
+
const next = {
|
|
168
|
+
...compiledDateDoc,
|
|
169
|
+
_id: existing?._id ?? new mongoose_1.default.Types.ObjectId().toHexString(),
|
|
170
|
+
iteration: Number(existing?.iteration ?? 0) + 1,
|
|
171
|
+
};
|
|
172
|
+
if (force || needsMaterializedDialerReportWrite(existing, next))
|
|
173
|
+
addWrite(next);
|
|
174
|
+
else
|
|
175
|
+
skippedDocuments.push(existing);
|
|
176
|
+
}
|
|
177
|
+
// ---- ENTRY PAGES: exactly the pages the closing day owns ----
|
|
178
|
+
const compiledEntriesByPage = new Map();
|
|
179
|
+
for (const doc of compiledEntries) {
|
|
180
|
+
const expectedPage = (0, materialized_dialer_entry_pages_1.dialerEntryPageOf)(doc.scope_context, localDate);
|
|
181
|
+
if (expectedPage == null || (doc.page !== expectedPage && !String(doc.page ?? '').startsWith(expectedPage + '#'))) {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
const key = (0, materialized_dialer_entry_pages_1.materializedDialerEntryPageKey)(doc);
|
|
185
|
+
if (compiledEntriesByPage.has(key))
|
|
186
|
+
return null; // duplicate page — data issue
|
|
187
|
+
compiledEntriesByPage.set(key, doc);
|
|
188
|
+
}
|
|
189
|
+
// ---- DAY deletion: a stored day doc that no longer compiled ----
|
|
190
|
+
const compiledDateKeys = new Set(compiledReports
|
|
191
|
+
.filter((doc) => (0, exports.isMaterializedDialerDayScope)(String(doc.scope_context)))
|
|
192
|
+
.map((doc) => dialerScopeKey(doc)));
|
|
193
|
+
const removedDates = [];
|
|
194
|
+
for (const doc of storedReports) {
|
|
195
|
+
if (!(0, exports.isMaterializedDialerDayScope)(String(doc.scope_context)))
|
|
196
|
+
continue;
|
|
197
|
+
if (String(doc.scope_field) !== localDate)
|
|
198
|
+
continue;
|
|
199
|
+
if (compiledDateKeys.has(dialerScopeKey(doc)))
|
|
200
|
+
continue;
|
|
201
|
+
staleDocuments.push(doc);
|
|
202
|
+
removedDates.push(String(doc.scope_field));
|
|
203
|
+
}
|
|
204
|
+
// ---- PERIOD re-fold ----
|
|
205
|
+
const nextDayDocs = storedReports.filter((doc) => (0, exports.isMaterializedDialerDayScope)(String(doc.scope_context)) && String(doc.scope_field) !== localDate);
|
|
206
|
+
if (compiledDateDoc != null) {
|
|
207
|
+
nextDayDocs.push(writes.find((write) => (0, exports.isMaterializedDialerDayScope)(String(write.report.scope_context)))?.report ??
|
|
208
|
+
compiledDateDoc);
|
|
209
|
+
}
|
|
210
|
+
const touchedPeriods = new Map();
|
|
211
|
+
const noteDay = (day) => {
|
|
212
|
+
const fields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(day);
|
|
213
|
+
if (fields == null)
|
|
214
|
+
return;
|
|
215
|
+
for (const scope of exports.MATERIALIZED_DIALER_PERIOD_SCOPES) {
|
|
216
|
+
const field = fields[String(scope)];
|
|
217
|
+
if (field == null || field === '')
|
|
218
|
+
continue;
|
|
219
|
+
touchedPeriods.set(String(scope) + '|' + field, { scope: String(scope), field });
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
noteDay(localDate);
|
|
223
|
+
for (const day of removedDates)
|
|
224
|
+
noteDay(day);
|
|
225
|
+
for (const { scope, field } of touchedPeriods.values()) {
|
|
226
|
+
const folded = foldMaterializedDialerPeriodCounters({
|
|
227
|
+
periodScope: scope,
|
|
228
|
+
periodScopeField: field,
|
|
229
|
+
dayDocuments: nextDayDocs,
|
|
230
|
+
});
|
|
231
|
+
const existing = storedReportsByScope.get(scope + '|' + field);
|
|
232
|
+
const keys = Object.keys(folded).sort();
|
|
233
|
+
if (keys.length === 0) {
|
|
234
|
+
if (existing != null)
|
|
235
|
+
staleDocuments.push(existing);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const counters = {};
|
|
239
|
+
for (const key of keys)
|
|
240
|
+
counters[key] = folded[key];
|
|
241
|
+
const report = {
|
|
242
|
+
_id: existing?._id ?? new mongoose_1.default.Types.ObjectId().toHexString(),
|
|
243
|
+
tenant_id: tenantId,
|
|
244
|
+
brand_id: existing?.brand_id ?? compiledDateDoc?.brand_id ?? '',
|
|
245
|
+
scope_context: scope,
|
|
246
|
+
scope_field: field,
|
|
247
|
+
day_index: null,
|
|
248
|
+
sale_type_key_filters: [...MATERIALIZED_REPORTS_1.DIALER_KEY_FILTERS],
|
|
249
|
+
dialer_counters: counters,
|
|
250
|
+
iteration: existing?.iteration,
|
|
251
|
+
schema_version: compiledDateDoc?.schema_version ?? materialized_tenant_dialer_reports_1.MATERIALIZED_TENANT_DIALER_REPORTS_SCHEMA_VERSION,
|
|
252
|
+
// FROM THE DAYS THAT BELONG TO THIS PERIOD — never the stored watermark,
|
|
253
|
+
// and never an unrelated day from another period.
|
|
254
|
+
source_watermark: watermarkOfDays(nextDayDocs.filter((dayDoc) => {
|
|
255
|
+
const fields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(String(dayDoc?.scope_field));
|
|
256
|
+
return fields != null && fields[scope] === field;
|
|
257
|
+
}), existing?.source_watermark ?? computedAt),
|
|
258
|
+
computed_at: computedAt,
|
|
259
|
+
createdAt: existing?.createdAt ?? computedAt,
|
|
260
|
+
updatedAt: computedAt,
|
|
261
|
+
};
|
|
262
|
+
const next = { ...report, iteration: Number(existing?.iteration ?? 0) + 1 };
|
|
263
|
+
if (force || needsMaterializedDialerReportWrite(existing, next))
|
|
264
|
+
addWrite(next);
|
|
265
|
+
else
|
|
266
|
+
skippedDocuments.push(existing);
|
|
267
|
+
}
|
|
268
|
+
// ---- entry PAGE writes (replace by page identity) ----
|
|
269
|
+
for (const compiled of compiledEntriesByPage.values()) {
|
|
270
|
+
const key = (0, materialized_dialer_entry_pages_1.materializedDialerEntryPageKey)(compiled);
|
|
271
|
+
const existing = storedEntriesByPage.get(key) ?? null;
|
|
272
|
+
const next = {
|
|
273
|
+
...compiled,
|
|
274
|
+
_id: existing?._id ?? new mongoose_1.default.Types.ObjectId().toHexString(),
|
|
275
|
+
iteration: Number(existing?.iteration ?? 0) + 1,
|
|
276
|
+
};
|
|
277
|
+
if (existing == null || force || needsMaterializedDialerEntriesWrite(existing, next)) {
|
|
278
|
+
if (!addEntryWrite(next))
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
else {
|
|
282
|
+
skippedEntryDocuments.push(existing);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
// Anything fetched but not recompiled is a page this day no longer owns (an
|
|
286
|
+
// emptied day, or a row set that disappeared): delete exactly that page.
|
|
287
|
+
for (const doc of storedEntriesByPage.values()) {
|
|
288
|
+
if (compiledEntriesByPage.has((0, materialized_dialer_entry_pages_1.materializedDialerEntryPageKey)(doc)))
|
|
289
|
+
continue;
|
|
290
|
+
staleEntryDocuments.push(doc);
|
|
291
|
+
}
|
|
292
|
+
// BSON budgets: a counter fold or one day's page can exceed its budget even
|
|
293
|
+
// when the compile looked fine. Fail here, naming the collection + day + scope.
|
|
294
|
+
for (const write of writes) {
|
|
295
|
+
(0, materialized_document_size_1.assertMaterializedDocumentSize)(write.report, {
|
|
296
|
+
label: 'materialized_tenant_dialer_reports:' +
|
|
297
|
+
tenantId +
|
|
298
|
+
':' +
|
|
299
|
+
localDate +
|
|
300
|
+
':' +
|
|
301
|
+
String(write.report.scope_context) +
|
|
302
|
+
':' +
|
|
303
|
+
write.report.scope_field,
|
|
304
|
+
maxBytes: MATERIALIZED_REPORTS_1.MATERIALIZED_DIALER_REPORT_MAX_BSON_BYTES,
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
for (const write of entryWrites) {
|
|
308
|
+
(0, materialized_document_size_1.assertMaterializedDocumentSize)(write.report, {
|
|
309
|
+
label: 'materialized_tenant_dialer_entries:' +
|
|
310
|
+
tenantId +
|
|
311
|
+
':' +
|
|
312
|
+
localDate +
|
|
313
|
+
':' +
|
|
314
|
+
String(write.report.scope_context) +
|
|
315
|
+
':' +
|
|
316
|
+
write.report.scope_field +
|
|
317
|
+
':page=' +
|
|
318
|
+
write.report.page,
|
|
319
|
+
maxBytes: MATERIALIZED_REPORTS_1.MATERIALIZED_DIALER_ENTRY_MAX_BSON_BYTES,
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
return {
|
|
323
|
+
writes,
|
|
324
|
+
entryWrites,
|
|
325
|
+
staleDocuments,
|
|
326
|
+
staleEntryDocuments,
|
|
327
|
+
skippedDocuments,
|
|
328
|
+
skippedEntryDocuments,
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
/** Max watermark across the day documents that feed a fold. */
|
|
332
|
+
function watermarkOfDays(dayDocs, fallback) {
|
|
333
|
+
let latest = fallback.getTime();
|
|
334
|
+
for (const doc of dayDocs) {
|
|
335
|
+
const time = new Date(doc?.source_watermark ?? 0).getTime();
|
|
336
|
+
if (!Number.isNaN(time) && time > latest)
|
|
337
|
+
latest = time;
|
|
338
|
+
}
|
|
339
|
+
return new Date(latest);
|
|
340
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { DIALER_TYPES_ENUM } from '../../constants/DIALER_ENUMS';
|
|
2
|
+
import { ILocalTimeFields } from '../types/common';
|
|
3
|
+
import { IMaterializedTenantDialerEntry } from '../../schemas/types/materialized_tenant_dialer_entries';
|
|
4
|
+
import { IMaterializedTenantDialerReport } from '../../schemas/types/materialized_tenant_dialer_reports';
|
|
5
|
+
/**
|
|
6
|
+
* Dialer — the day compile.
|
|
7
|
+
*
|
|
8
|
+
* Turns ONE business day's `tenant_dialer_events` into:
|
|
9
|
+
* - the `localDate` COUNTER document (period counters are folded by the close
|
|
10
|
+
* plan from the sibling DAY documents);
|
|
11
|
+
* - ONE ENTRY PAGE per entry scope (date / week / ISO week / month). The day
|
|
12
|
+
* page uses `page='all'`; each period page is partitioned by the source date,
|
|
13
|
+
* so a document is bounded by ONE day's rows.
|
|
14
|
+
*
|
|
15
|
+
* ## Attribution is strict and never invented
|
|
16
|
+
*
|
|
17
|
+
* An event is attributable to the day only when it carries BOTH its own
|
|
18
|
+
* tenant-local `localDate` (equal to the compiled day) AND a whole
|
|
19
|
+
* `localHour` 0..23 (the statement's row contract has a numeric hour, and the
|
|
20
|
+
* writer emits the local fields all-or-nothing). An event without local fields
|
|
21
|
+
* is UNATTRIBUTED and is excluded — no guessed day, no `UNKNOWN` date. An event
|
|
22
|
+
* whose local date is another day is excluded as OUT-OF-DAY, never moved into
|
|
23
|
+
* this day. The caller reports both counts.
|
|
24
|
+
*
|
|
25
|
+
* ## No duration, no order attribution
|
|
26
|
+
*
|
|
27
|
+
* Nothing is derived from event pairs: `CALL_ENDED` increments `ended`, it does
|
|
28
|
+
* not close a duration. The report is counts only.
|
|
29
|
+
*
|
|
30
|
+
* Returns `null` for invalid arguments or a day with NO attributable event:
|
|
31
|
+
* an emptied day writes nothing, and the close plan deletes the pages/documents
|
|
32
|
+
* it used to own. Absence in a historical read means zero.
|
|
33
|
+
*/
|
|
34
|
+
/** The source shape the compiler consumes (a `tenant_dialer_events` row). */
|
|
35
|
+
export interface IDialerEventSource extends Partial<ILocalTimeFields> {
|
|
36
|
+
_id: string;
|
|
37
|
+
tenant_id?: string;
|
|
38
|
+
request_id: string;
|
|
39
|
+
action: DIALER_TYPES_ENUM | string;
|
|
40
|
+
phone_number: string;
|
|
41
|
+
pos_id: string;
|
|
42
|
+
staff_id?: string | null;
|
|
43
|
+
staff_phone?: string | null;
|
|
44
|
+
schema_version?: number;
|
|
45
|
+
createdAt?: Date | string;
|
|
46
|
+
updatedAt?: Date | string;
|
|
47
|
+
}
|
|
48
|
+
export interface IDialerDayCompileInput {
|
|
49
|
+
tenantId: string;
|
|
50
|
+
brandId: string;
|
|
51
|
+
/** The closing tenant-local business day (`YYYY-MM-DD`). */
|
|
52
|
+
localDate: string;
|
|
53
|
+
events?: IDialerEventSource[];
|
|
54
|
+
computedAt?: Date;
|
|
55
|
+
}
|
|
56
|
+
export interface IDialerDayCompileResult {
|
|
57
|
+
reports: IMaterializedTenantDialerReport[];
|
|
58
|
+
entries: IMaterializedTenantDialerEntry[];
|
|
59
|
+
/** Events folded into this day (strictly attributed). */
|
|
60
|
+
attributed_events: number;
|
|
61
|
+
/** Events in the input WITHOUT a usable local date/hour — never attributed. */
|
|
62
|
+
unattributed_events: number;
|
|
63
|
+
/** Events attributed to a DIFFERENT business day — not this compile. */
|
|
64
|
+
out_of_day_events: number;
|
|
65
|
+
}
|
|
66
|
+
/** Compiles one business day into a counter document plus its entry pages. */
|
|
67
|
+
export declare function compileTenantDialerReports(input: IDialerDayCompileInput): IDialerDayCompileResult | null;
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.compileTenantDialerReports = compileTenantDialerReports;
|
|
4
|
+
const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
|
|
5
|
+
const materialized_tenant_dialer_entries_1 = require("../../schemas/models/materialized_tenant_dialer_entries");
|
|
6
|
+
const materialized_tenant_dialer_reports_1 = require("../../schemas/models/materialized_tenant_dialer_reports");
|
|
7
|
+
const materialized_tenant_dialer_reports_2 = require("../../schemas/types/materialized_tenant_dialer_reports");
|
|
8
|
+
const materialized_dialer_accumulator_helpers_1 = require("./materialized-dialer-accumulator-helpers");
|
|
9
|
+
const materialized_dialer_entry_pages_1 = require("./materialized-dialer-entry-pages");
|
|
10
|
+
const materialized_dialer_key_helpers_1 = require("./materialized-dialer-key-helpers");
|
|
11
|
+
const materialized_dialer_masking_1 = require("./materialized-dialer-masking");
|
|
12
|
+
const materialized_document_size_1 = require("./materialized-document-size");
|
|
13
|
+
const scope_helpers_1 = require("./scope-helpers");
|
|
14
|
+
const toDate = (value) => {
|
|
15
|
+
if (value == null)
|
|
16
|
+
return null;
|
|
17
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
18
|
+
return Number.isNaN(date.getTime()) ? null : date;
|
|
19
|
+
};
|
|
20
|
+
/** Builds one statement row from an attributed event (phones masked). */
|
|
21
|
+
function buildDialerEntryRow(event, localDate, localHour) {
|
|
22
|
+
return {
|
|
23
|
+
event_id: String(event._id ?? ''),
|
|
24
|
+
request_id: String(event.request_id ?? ''),
|
|
25
|
+
action: String(event.action ?? ''),
|
|
26
|
+
phone_number_masked: (0, materialized_dialer_masking_1.maskDialerPhoneNumber)(event.phone_number) ?? '',
|
|
27
|
+
staff_id: event.staff_id == null || String(event.staff_id).trim() === '' ? null : String(event.staff_id),
|
|
28
|
+
staff_phone_masked: (0, materialized_dialer_masking_1.maskDialerPhoneNumber)(event.staff_phone),
|
|
29
|
+
pos_id: String(event.pos_id ?? ''),
|
|
30
|
+
created_at: new Date(event.createdAt).toISOString(),
|
|
31
|
+
local_date: localDate,
|
|
32
|
+
local_hour: localHour,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** Compiles one business day into a counter document plus its entry pages. */
|
|
36
|
+
function compileTenantDialerReports(input) {
|
|
37
|
+
if (input == null)
|
|
38
|
+
return null;
|
|
39
|
+
const { tenantId, brandId, localDate } = input;
|
|
40
|
+
if (typeof tenantId !== 'string' ||
|
|
41
|
+
tenantId === '' ||
|
|
42
|
+
typeof brandId !== 'string' ||
|
|
43
|
+
brandId === '' ||
|
|
44
|
+
typeof localDate !== 'string' ||
|
|
45
|
+
(0, scope_helpers_1.parseMaterializedLocalDate)(localDate) == null) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
const computedAt = input.computedAt ?? new Date();
|
|
49
|
+
const countersByKey = new Map();
|
|
50
|
+
const rowsByKey = new Map();
|
|
51
|
+
const watermarks = [];
|
|
52
|
+
let attributed = 0;
|
|
53
|
+
let unattributed = 0;
|
|
54
|
+
let outOfDay = 0;
|
|
55
|
+
for (const event of Array.isArray(input.events) ? input.events : []) {
|
|
56
|
+
if (event == null) {
|
|
57
|
+
unattributed += 1;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (String(event.tenant_id ?? tenantId) !== tenantId)
|
|
61
|
+
continue;
|
|
62
|
+
const eventDay = String(event.localDate ?? '');
|
|
63
|
+
const hour = (0, materialized_dialer_accumulator_helpers_1.dialerHourKey)(event.localHour);
|
|
64
|
+
const createdAt = toDate(event.createdAt);
|
|
65
|
+
if (eventDay !== '' && (0, scope_helpers_1.parseMaterializedLocalDate)(eventDay) != null) {
|
|
66
|
+
if (eventDay !== localDate) {
|
|
67
|
+
outOfDay += 1;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (eventDay === '' || hour == null || createdAt == null) {
|
|
72
|
+
// No local day, no whole local hour, or no canonical instant: the event
|
|
73
|
+
// is UNATTRIBUTED. Nothing is invented for it.
|
|
74
|
+
unattributed += 1;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const key = (0, materialized_dialer_key_helpers_1.buildMaterializedDialerKey)(event.action, event.pos_id, event.staff_id);
|
|
78
|
+
const counters = countersByKey.get(key) ?? (0, materialized_dialer_accumulator_helpers_1.freshDialerCounters)();
|
|
79
|
+
(0, materialized_dialer_accumulator_helpers_1.addDialerEvent)(counters, { action: event.action, localHour: event.localHour });
|
|
80
|
+
countersByKey.set(key, counters);
|
|
81
|
+
const row = buildDialerEntryRow(event, localDate, Number(hour));
|
|
82
|
+
const bucket = rowsByKey.get(key);
|
|
83
|
+
if (bucket == null)
|
|
84
|
+
rowsByKey.set(key, [row]);
|
|
85
|
+
else
|
|
86
|
+
bucket.push(row);
|
|
87
|
+
watermarks.push(toDate(event.updatedAt) ?? createdAt);
|
|
88
|
+
attributed += 1;
|
|
89
|
+
}
|
|
90
|
+
if (attributed === 0)
|
|
91
|
+
return null;
|
|
92
|
+
const dayIndex = (0, scope_helpers_1.getDayIndexFromLocalDate)(localDate);
|
|
93
|
+
// The SOURCE watermark: the newest folded event. It is NOT clamped to
|
|
94
|
+
// `computedAt` — an unchanged re-close must stay below the stored watermark
|
|
95
|
+
// so the plan can skip it, while a late event (a newer `updatedAt`) advances
|
|
96
|
+
// it and forces the rewrite.
|
|
97
|
+
const watermark = watermarks.reduce((latest, current) => (current.getTime() > latest.getTime() ? current : latest), watermarks[0] ?? computedAt);
|
|
98
|
+
const dialerCounters = {};
|
|
99
|
+
for (const key of [...countersByKey.keys()].sort()) {
|
|
100
|
+
dialerCounters[key] = countersByKey.get(key);
|
|
101
|
+
}
|
|
102
|
+
const sections = {};
|
|
103
|
+
for (const key of [...rowsByKey.keys()].sort()) {
|
|
104
|
+
const rows = rowsByKey.get(key);
|
|
105
|
+
// NEWEST FIRST with a total tie-break: the same order the keyset reader
|
|
106
|
+
// uses, so the stored page and the API agree.
|
|
107
|
+
rows.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime() ||
|
|
108
|
+
(a.event_id < b.event_id ? 1 : a.event_id > b.event_id ? -1 : 0));
|
|
109
|
+
sections[key] = { rows };
|
|
110
|
+
}
|
|
111
|
+
const reports = [
|
|
112
|
+
{
|
|
113
|
+
_id: undefined,
|
|
114
|
+
tenant_id: tenantId,
|
|
115
|
+
brand_id: brandId,
|
|
116
|
+
scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
117
|
+
scope_field: localDate,
|
|
118
|
+
day_index: dayIndex,
|
|
119
|
+
sale_type_key_filters: [...materialized_tenant_dialer_reports_2.MATERIALIZED_DIALER_REPORT_KEY_FILTERS],
|
|
120
|
+
dialer_counters: dialerCounters,
|
|
121
|
+
schema_version: materialized_tenant_dialer_reports_1.MATERIALIZED_TENANT_DIALER_REPORTS_SCHEMA_VERSION,
|
|
122
|
+
source_watermark: watermark,
|
|
123
|
+
computed_at: computedAt,
|
|
124
|
+
createdAt: computedAt,
|
|
125
|
+
updatedAt: computedAt,
|
|
126
|
+
},
|
|
127
|
+
];
|
|
128
|
+
const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
|
|
129
|
+
if (periodFields == null)
|
|
130
|
+
return null;
|
|
131
|
+
const entrySections = Object.keys(sections).length === 0 ? null : sections;
|
|
132
|
+
const entries = [];
|
|
133
|
+
for (const scope of MATERIALIZED_REPORTS_1.MATERIALIZED_DIALER_ENTRY_SCOPES) {
|
|
134
|
+
const scopeField = periodFields[scope];
|
|
135
|
+
const page = (0, materialized_dialer_entry_pages_1.dialerEntryPageOf)(scope, localDate);
|
|
136
|
+
if (typeof scopeField !== 'string' || scopeField === '' || page == null)
|
|
137
|
+
return null;
|
|
138
|
+
const pageDoc = {
|
|
139
|
+
_id: undefined,
|
|
140
|
+
tenant_id: tenantId,
|
|
141
|
+
brand_id: brandId,
|
|
142
|
+
scope_context: scope,
|
|
143
|
+
scope_field: scopeField,
|
|
144
|
+
page,
|
|
145
|
+
day_index: scope === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ? dayIndex : null,
|
|
146
|
+
dialer_entries: entrySections,
|
|
147
|
+
schema_version: materialized_tenant_dialer_entries_1.MATERIALIZED_TENANT_DIALER_ENTRIES_SCHEMA_VERSION,
|
|
148
|
+
source_watermark: watermark,
|
|
149
|
+
computed_at: computedAt,
|
|
150
|
+
createdAt: computedAt,
|
|
151
|
+
updatedAt: computedAt,
|
|
152
|
+
};
|
|
153
|
+
entries.push(...(0, materialized_dialer_entry_pages_1.splitMaterializedDialerEntryPage)(pageDoc));
|
|
154
|
+
}
|
|
155
|
+
// BSON budgets: fail at COMPILE time, naming the collection + day + scope,
|
|
156
|
+
// rather than at insert time inside the close transaction.
|
|
157
|
+
(0, materialized_document_size_1.assertMaterializedDocumentSize)(reports[0], {
|
|
158
|
+
label: `materialized_tenant_dialer_reports:${tenantId}:${localDate}:localDate:${localDate}`,
|
|
159
|
+
maxBytes: MATERIALIZED_REPORTS_1.MATERIALIZED_DIALER_REPORT_MAX_BSON_BYTES,
|
|
160
|
+
});
|
|
161
|
+
for (const page of entries) {
|
|
162
|
+
(0, materialized_document_size_1.assertMaterializedDocumentSize)(page, {
|
|
163
|
+
label: 'materialized_tenant_dialer_entries:' +
|
|
164
|
+
tenantId +
|
|
165
|
+
':' +
|
|
166
|
+
localDate +
|
|
167
|
+
':' +
|
|
168
|
+
String(page.scope_context) +
|
|
169
|
+
':' +
|
|
170
|
+
page.scope_field +
|
|
171
|
+
':page=' +
|
|
172
|
+
page.page,
|
|
173
|
+
maxBytes: MATERIALIZED_REPORTS_1.MATERIALIZED_DIALER_ENTRY_MAX_BSON_BYTES,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
reports,
|
|
178
|
+
entries,
|
|
179
|
+
attributed_events: attributed,
|
|
180
|
+
unattributed_events: unattributed,
|
|
181
|
+
out_of_day_events: outOfDay,
|
|
182
|
+
};
|
|
183
|
+
}
|