@managesome/eposmatic-toolkit 0.3.11 → 0.4.1

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.
Files changed (71) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +105 -0
  2. package/esm/constants/index.js +1 -0
  3. package/esm/helpers/index.js +1 -0
  4. package/esm/helpers/materialized-reports/index.js +5 -0
  5. package/esm/helpers/materialized-reports/key-helpers.js +59 -0
  6. package/esm/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +60 -0
  7. package/esm/helpers/materialized-reports/scope-helpers.js +107 -0
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +251 -0
  9. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +860 -0
  10. package/esm/schemas/models/index.js +2 -0
  11. package/esm/schemas/models/materialized_tenant_reports_iterations.js +82 -0
  12. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +399 -0
  13. package/esm/schemas/types/index.js +2 -0
  14. package/esm/schemas/types/materialized_tenant_reports_iterations.js +1 -0
  15. package/esm/schemas/types/materialized_tenant_sales_overview_reports.js +1 -0
  16. package/lib/constants/MATERIALIZED_REPORTS.d.ts +96 -0
  17. package/lib/constants/MATERIALIZED_REPORTS.js +108 -0
  18. package/lib/constants/index.d.ts +1 -0
  19. package/lib/constants/index.js +1 -0
  20. package/lib/helpers/index.d.ts +1 -0
  21. package/lib/helpers/index.js +1 -0
  22. package/lib/helpers/materialized-reports/index.d.ts +5 -0
  23. package/lib/helpers/materialized-reports/index.js +21 -0
  24. package/lib/helpers/materialized-reports/key-helpers.d.ts +35 -0
  25. package/lib/helpers/materialized-reports/key-helpers.js +64 -0
  26. package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.d.ts +66 -0
  27. package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +63 -0
  28. package/lib/helpers/materialized-reports/scope-helpers.d.ts +57 -0
  29. package/lib/helpers/materialized-reports/scope-helpers.js +114 -0
  30. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +125 -0
  31. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +256 -0
  32. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +223 -0
  33. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +875 -0
  34. package/lib/schemas/models/index.d.ts +2 -0
  35. package/lib/schemas/models/index.js +2 -0
  36. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +80 -0
  37. package/lib/schemas/models/materialized_tenant_reports_iterations.js +85 -0
  38. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +569 -0
  39. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +402 -0
  40. package/lib/schemas/models/orders.d.ts +24 -24
  41. package/lib/schemas/models/tenant_active_jobs.d.ts +3 -3
  42. package/lib/schemas/models/tenant_calendar.d.ts +3 -3
  43. package/lib/schemas/models/tenant_cash_drawer_sessions.d.ts +24 -24
  44. package/lib/schemas/models/tenant_cash_in_out.d.ts +24 -24
  45. package/lib/schemas/models/tenant_day_sessions.d.ts +24 -24
  46. package/lib/schemas/models/tenant_instore_shift_sessions.d.ts +24 -24
  47. package/lib/schemas/types/index.d.ts +2 -0
  48. package/lib/schemas/types/index.js +2 -0
  49. package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +62 -0
  50. package/lib/schemas/types/materialized_tenant_reports_iterations.js +2 -0
  51. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +242 -0
  52. package/lib/schemas/types/materialized_tenant_sales_overview_reports.js +3 -0
  53. package/lib/tests/materialized-reports/fixtures.d.ts +81 -0
  54. package/lib/tests/materialized-reports/fixtures.js +87 -0
  55. package/lib/tests/materialized-reports/fixtures.test.d.ts +1 -0
  56. package/lib/tests/materialized-reports/fixtures.test.js +123 -0
  57. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.d.ts +1 -0
  58. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.js +75 -0
  59. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.d.ts +1 -0
  60. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +73 -0
  61. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.d.ts +1 -0
  62. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +207 -0
  63. package/lib/tests/materialized-reports/sales-overview-baseline.test.d.ts +1 -0
  64. package/lib/tests/materialized-reports/sales-overview-baseline.test.js +326 -0
  65. package/lib/tests/materialized-reports/sales-overview-reference.d.ts +63 -0
  66. package/lib/tests/materialized-reports/sales-overview-reference.js +131 -0
  67. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.d.ts +1 -0
  68. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +335 -0
  69. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.d.ts +1 -0
  70. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +885 -0
  71. package/package.json +5 -2
@@ -0,0 +1,125 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { IMaterializedTenantReportIterationInput } from '../../schemas/types/materialized_tenant_reports_iterations';
3
+ import { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
4
+ import { IConvertOrdersToMaterializedReportsResult } from './tenant-sales-overview-helpers';
5
+ /**
6
+ * Close-day planning for `materialized_tenant_sales_overview_reports` (see
7
+ * `MATERIALIZED_REPORTS.md` “Backend materialization cycle”).
8
+ *
9
+ * The day-close job compiles one tenant-day (`convertOrdersTo…`), fetches the
10
+ * stored documents the plan needs (`getMaterializedTenantSalesOverviewScopeRefsForDay`
11
+ * + the issue-day docs of collected bills), and asks this module for the
12
+ * complete write plan:
13
+ *
14
+ * - **`writes`** — hour + date documents (insert, or `replacement` when stored
15
+ * so `iteration` bumps without `_id` churn) and the six accumulated period
16
+ * documents (`additions`, or — when the day was previously folded —
17
+ * `subtract` the stored day delta first). Each write carries its
18
+ * `materialized_tenant_reports_iterations` history row; persist both.
19
+ * - **`staleHourDocuments`** — stored `localHour` docs of the day with no
20
+ * activity anymore (orders deleted / moved) — delete by `_id`.
21
+ * - **`receivedPatches`** — issue-day docs holding bills collected on the
22
+ * compiled day, patched through `update(…, { received_payments })`. A
23
+ * ledger-changing patch is a versioned write, so each patched document
24
+ * comes with its history row; computed against the POST-write documents,
25
+ * so a period doc that both accumulates the day and holds an earlier bill
26
+ * keeps the accumulation — persist them AFTER `writes`.
27
+ * - **`skippedDocuments`** — already up to date (see
28
+ * `needsMaterializedTenantSalesOverviewReportWrite`).
29
+ * - **`createdPeriodDocuments`** — period docs that were absent from
30
+ * `existing` and are created by this close (also present in `writes`): a
31
+ * first materialized close of the period, an order-less prefix, or a
32
+ * genuinely missing document — in the last case the caller must alert and
33
+ * run the documented period backfill (a deleted doc cannot be reconstructed
34
+ * from one day's delta alone).
35
+ *
36
+ * The watermark guard skips nothing when `force` is set (repairs / schema
37
+ * rollouts). Helpers never throw — invalid input returns `null`.
38
+ */
39
+ /** Options of `buildTenantSalesOverviewCloseDayPlan`. */
40
+ export interface IBuildTenantSalesOverviewCloseDayPlanInput {
41
+ /** Tenant the compile belongs to (one plan = one tenant-day). */
42
+ tenantId: string;
43
+ /** The tenant-day compile (`convertOrdersToMaterializedTenantSalesOverviewReports`). */
44
+ compile: IConvertOrdersToMaterializedReportsResult;
45
+ /**
46
+ * Why this close is applied — stored as the `reason` of every history row
47
+ * the plan produces (`NEW_DAY`, `RECLOSE`, `RECONCILE`, …). Required: the
48
+ * iteration history must always explain itself.
49
+ */
50
+ reason: string;
51
+ /**
52
+ * Stored documents the job fetched: the compiled scopes that already exist
53
+ * plus, for every collected bill's `issued_local_date`, that day's stored
54
+ * documents (`getMaterializedTenantSalesOverviewScopeRefsForDay`). Pass
55
+ * plain JSON (`.lean()` recommended — a hydrated document's map-cast
56
+ * `sale_type_metrics` is normalized defensively, but its other mongoose
57
+ * internals are not supported). Repeating the SAME document (overlapping
58
+ * fetch refs) is fine; two different rows for one scope key → `null`.
59
+ */
60
+ existing?: IMaterializedTenantSalesOverviewReport[];
61
+ /** Force structural writes even when the watermarks are up to date. */
62
+ force?: boolean;
63
+ /** Override for write timestamps (tests, replays). */
64
+ computedAt?: Date;
65
+ }
66
+ /** One versioned write (structural write or ledger-changing patch): persist `report` + upsert its history row. */
67
+ export interface ITenantSalesOverviewCloseDayWrite {
68
+ /** Post-write document (stored `_id` kept for replacements). */
69
+ report: IMaterializedTenantSalesOverviewReport;
70
+ /** `materialized_tenant_reports_iterations` row — upsert by `(report_id, iteration)`. */
71
+ iteration: IMaterializedTenantReportIterationInput;
72
+ }
73
+ /** The complete close-day write plan (see the module docs). */
74
+ export interface ITenantSalesOverviewCloseDayPlan {
75
+ /** Structural writes (report + history row) — persist in any order. */
76
+ writes: ITenantSalesOverviewCloseDayWrite[];
77
+ /** Stored hour docs of the compiled day no longer backed by activity — delete by `_id`. */
78
+ staleHourDocuments: IMaterializedTenantSalesOverviewReport[];
79
+ /** Issued-ledger patches (versioned writes) — persist AFTER `writes`. */
80
+ receivedPatches: ITenantSalesOverviewCloseDayWrite[];
81
+ /** Stored docs that were already up to date (job logging). */
82
+ skippedDocuments: IMaterializedTenantSalesOverviewReport[];
83
+ /**
84
+ * Period-scope documents this close CREATED because they were absent from
85
+ * `existing` — a first materialized close of the period (including when
86
+ * earlier days of the period were order-less), or a document that is simply
87
+ * missing. A missing document folds only the closing day's delta: if
88
+ * earlier days of the period were already materialized, run the documented
89
+ * period backfill — a deleted document cannot be reconstructed from one
90
+ * day. These writes are also present in `writes`; alert on a non-empty list
91
+ * when the day is not the period's first materialized close.
92
+ */
93
+ createdPeriodDocuments: IMaterializedReportScopeRef[];
94
+ }
95
+ /** `(scope_context, scope_field)` pair of a stored / compiled document. */
96
+ export interface IMaterializedReportScopeRef {
97
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
98
+ scope_field: string;
99
+ }
100
+ /**
101
+ * Every stored scope the fan-out of one local day needs: the six period
102
+ * scopes + `localDate` of that day and all 24 `localHour` buckets (`null` for
103
+ * a malformed date). A bill's hour is unknowable from the received entry
104
+ * alone, so settlement patches always consider the whole day.
105
+ */
106
+ export declare function getMaterializedTenantSalesOverviewScopeRefsForDay(localDate: string): IMaterializedReportScopeRef[] | null;
107
+ /**
108
+ * Watermark guard of the write path: does the stored document need a
109
+ * structural write for the incoming compiled version?
110
+ *
111
+ * `false` (skip) when the incoming `source_watermark` is not newer than the
112
+ * stored one and the schema version + key-filter grammar match. Watermarks are
113
+ * monotonic (`updateMaterializedTenantSalesOverviewReport` never regresses
114
+ * them). A missing stored document always needs a write.
115
+ */
116
+ export declare function needsMaterializedTenantSalesOverviewReportWrite(existing: IMaterializedTenantSalesOverviewReport | null | undefined, incoming: IMaterializedTenantSalesOverviewReport | null | undefined): boolean;
117
+ /**
118
+ * Builds the close-day write plan for ONE tenant-day (see the module docs).
119
+ * Returns `null` (never throws) when the input is inconsistent — compiled
120
+ * docs of another tenant, duplicate compiled scope documents, a malformed
121
+ * `localDate`, duplicate STORED rows for one scope key (missing unique index
122
+ * — a data issue to fix, never silently deduplicated), or a merge conflict
123
+ * with a stored document (schema / brand).
124
+ */
125
+ export declare function buildTenantSalesOverviewCloseDayPlan(input: IBuildTenantSalesOverviewCloseDayPlanInput | null | undefined): ITenantSalesOverviewCloseDayPlan | null;
@@ -0,0 +1,256 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMaterializedTenantSalesOverviewScopeRefsForDay = getMaterializedTenantSalesOverviewScopeRefsForDay;
4
+ exports.needsMaterializedTenantSalesOverviewReportWrite = needsMaterializedTenantSalesOverviewReportWrite;
5
+ exports.buildTenantSalesOverviewCloseDayPlan = buildTenantSalesOverviewCloseDayPlan;
6
+ const constants_1 = require("../../constants");
7
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
8
+ const materialized_tenant_reports_iterations_helpers_1 = require("./materialized-tenant-reports-iterations-helpers");
9
+ const scope_helpers_1 = require("./scope-helpers");
10
+ const tenant_sales_overview_helpers_1 = require("./tenant-sales-overview-helpers");
11
+ /** Scopes written wholesale for the compiled day (replacement semantics). */
12
+ const CLOSE_DAY_DAY_SCOPES = [
13
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
14
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
15
+ ];
16
+ /** Scopes that accumulate day deltas (subtract the stored delta, add the fresh one). */
17
+ const CLOSE_DAY_ACCUMULATED_SCOPES = [
18
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
19
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
20
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
21
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
22
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
23
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
24
+ ];
25
+ const materializedScopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
26
+ const materializedCreditBillKey = (orderId, paymentId) => `${orderId}|${paymentId}`;
27
+ const hasMaterializedMetrics = (doc) => Object.keys((0, tenant_sales_overview_helpers_1.normalizeMaterializedSaleTypeMetrics)(doc.sale_type_metrics)).length > 0;
28
+ /**
29
+ * Every stored scope the fan-out of one local day needs: the six period
30
+ * scopes + `localDate` of that day and all 24 `localHour` buckets (`null` for
31
+ * a malformed date). A bill's hour is unknowable from the received entry
32
+ * alone, so settlement patches always consider the whole day.
33
+ */
34
+ function getMaterializedTenantSalesOverviewScopeRefsForDay(localDate) {
35
+ const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
36
+ if (periodFields == null)
37
+ return null;
38
+ const refs = [];
39
+ for (const scopeContext of Object.keys(periodFields)) {
40
+ refs.push({
41
+ scope_context: scopeContext,
42
+ scope_field: periodFields[scopeContext],
43
+ });
44
+ }
45
+ for (let hour = 0; hour < 24; hour++) {
46
+ const scopeField = (0, scope_helpers_1.getMaterializedHourScopeField)(localDate, hour);
47
+ if (scopeField == null)
48
+ return null;
49
+ refs.push({ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: scopeField });
50
+ }
51
+ return refs;
52
+ }
53
+ /**
54
+ * Watermark guard of the write path: does the stored document need a
55
+ * structural write for the incoming compiled version?
56
+ *
57
+ * `false` (skip) when the incoming `source_watermark` is not newer than the
58
+ * stored one and the schema version + key-filter grammar match. Watermarks are
59
+ * monotonic (`updateMaterializedTenantSalesOverviewReport` never regresses
60
+ * them). A missing stored document always needs a write.
61
+ */
62
+ function needsMaterializedTenantSalesOverviewReportWrite(existing, incoming) {
63
+ if (existing == null || incoming == null)
64
+ return true;
65
+ if (existing.schema_version !== incoming.schema_version)
66
+ return true;
67
+ if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
68
+ return true;
69
+ }
70
+ const existingTime = new Date(existing.source_watermark ?? 0).getTime();
71
+ const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
72
+ if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
73
+ return true;
74
+ return incomingTime > existingTime;
75
+ }
76
+ /** Would a received-payment patch change the stored bill? (settlement/note/received) */
77
+ const creditBillWouldChange = (bill, collected) => {
78
+ const received = Math.max(bill.received_amount ?? 0, collected.received_amount ?? 0);
79
+ if (received !== (bill.received_amount ?? 0))
80
+ return true;
81
+ const note = bill.credit_note ?? collected.credit_note;
82
+ if ((note ?? null) !== (bill.credit_note ?? null))
83
+ return true;
84
+ return bill.settled_at == null && received >= (bill.amount ?? 0);
85
+ };
86
+ /** Does the document hold an issued bill that one of the collected payments would change? */
87
+ const documentHoldsUnpatchedCreditBill = (doc, collectedByBill) => {
88
+ for (const keyMetrics of Object.values((0, tenant_sales_overview_helpers_1.normalizeMaterializedSaleTypeMetrics)(doc.sale_type_metrics))) {
89
+ for (const bill of keyMetrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]?.issued?.bills ?? []) {
90
+ const collected = collectedByBill.get(materializedCreditBillKey(bill.order_id, bill.payment_id));
91
+ if (collected != null && creditBillWouldChange(bill, collected))
92
+ return true;
93
+ }
94
+ }
95
+ return false;
96
+ };
97
+ /**
98
+ * Builds the close-day write plan for ONE tenant-day (see the module docs).
99
+ * Returns `null` (never throws) when the input is inconsistent — compiled
100
+ * docs of another tenant, duplicate compiled scope documents, a malformed
101
+ * `localDate`, duplicate STORED rows for one scope key (missing unique index
102
+ * — a data issue to fix, never silently deduplicated), or a merge conflict
103
+ * with a stored document (schema / brand).
104
+ */
105
+ function buildTenantSalesOverviewCloseDayPlan(input) {
106
+ if (input == null)
107
+ return null;
108
+ const { tenantId, compile, reason } = input;
109
+ if (typeof tenantId !== 'string' || tenantId.length === 0)
110
+ return null;
111
+ if (compile == null)
112
+ return null;
113
+ if (typeof reason !== 'string' || reason.length === 0)
114
+ return null;
115
+ const compiledReports = compile.materializedReports ?? [];
116
+ if (compiledReports.some((doc) => doc == null || doc.tenant_id !== tenantId))
117
+ return null;
118
+ const computedAt = input.computedAt ?? new Date();
119
+ const force = input.force === true;
120
+ const compiledByScope = new Map();
121
+ for (const doc of compiledReports) {
122
+ const key = materializedScopeKey(doc);
123
+ if (compiledByScope.has(key))
124
+ return null; // duplicate scope doc — data issue
125
+ compiledByScope.set(key, doc);
126
+ }
127
+ const compiledDateDoc = compiledReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE) ?? null;
128
+ if (compiledDateDoc == null)
129
+ return null;
130
+ const localDate = compiledDateDoc.scope_field;
131
+ if (getMaterializedTenantSalesOverviewScopeRefsForDay(localDate) == null)
132
+ return null;
133
+ const existingByScope = new Map();
134
+ for (const doc of input.existing ?? []) {
135
+ if (doc == null || doc.tenant_id !== tenantId)
136
+ continue;
137
+ const key = materializedScopeKey(doc);
138
+ const prior = existingByScope.get(key);
139
+ if (prior == null) {
140
+ existingByScope.set(key, doc);
141
+ continue;
142
+ }
143
+ // Repeating the SAME document (overlapping fetch refs) is fine; two
144
+ // different rows for one scope key mean the unique index is missing.
145
+ // String comparison keeps hydrated ObjectId `_id`s compatible with plain ids.
146
+ if (String(prior._id) !== String(doc._id))
147
+ return null;
148
+ }
149
+ const storedDateDoc = existingByScope.get(materializedScopeKey(compiledDateDoc)) ?? null;
150
+ const dayChanged = force || needsMaterializedTenantSalesOverviewReportWrite(storedDateDoc, compiledDateDoc);
151
+ const dayDeltaEmpty = !hasMaterializedMetrics(compiledDateDoc);
152
+ const writes = [];
153
+ const skippedDocuments = [];
154
+ const createdPeriodDocuments = [];
155
+ const addStructuralWrite = (report) => {
156
+ const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(report, {
157
+ reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
158
+ reason,
159
+ computedAt,
160
+ });
161
+ if (iteration == null)
162
+ return false;
163
+ writes.push({ report, iteration });
164
+ return true;
165
+ };
166
+ for (const compiledDoc of compiledReports) {
167
+ const existing = existingByScope.get(materializedScopeKey(compiledDoc)) ?? null;
168
+ if (CLOSE_DAY_DAY_SCOPES.includes(compiledDoc.scope_context)) {
169
+ if (!dayChanged) {
170
+ if (existing != null)
171
+ skippedDocuments.push(existing);
172
+ // Partial-failure repair: the day is up to date but this scope doc was never persisted.
173
+ else if (!addStructuralWrite(compiledDoc))
174
+ return null;
175
+ continue;
176
+ }
177
+ if (existing == null) {
178
+ if (!addStructuralWrite(compiledDoc))
179
+ return null;
180
+ }
181
+ else {
182
+ const updated = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(existing, { replacement: compiledDoc }, { computedAt });
183
+ if (updated == null || !addStructuralWrite(updated))
184
+ return null;
185
+ }
186
+ continue;
187
+ }
188
+ if (!CLOSE_DAY_ACCUMULATED_SCOPES.includes(compiledDoc.scope_context))
189
+ return null; // unknown scope — data issue
190
+ if (existing == null) {
191
+ if (dayDeltaEmpty)
192
+ continue; // nothing to fold into a (new) period document
193
+ if (!addStructuralWrite(compiledDoc))
194
+ return null;
195
+ createdPeriodDocuments.push({
196
+ scope_context: compiledDoc.scope_context,
197
+ scope_field: compiledDoc.scope_field,
198
+ });
199
+ continue;
200
+ }
201
+ if (!dayChanged) {
202
+ skippedDocuments.push(existing);
203
+ continue;
204
+ }
205
+ if (dayDeltaEmpty && storedDateDoc == null) {
206
+ skippedDocuments.push(existing); // first close of an order-less day — nothing to fold
207
+ continue;
208
+ }
209
+ const updated = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(existing, { subtract: storedDateDoc != null ? [storedDateDoc] : [], additions: [compiledDoc] }, { computedAt });
210
+ if (updated == null || !addStructuralWrite(updated))
211
+ return null;
212
+ }
213
+ // Orders deleted / moved shrank the day's active hours — drop the stale docs.
214
+ const staleHourDocuments = dayChanged
215
+ ? Array.from(existingByScope.values()).filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
216
+ typeof doc.scope_field === 'string' &&
217
+ doc.scope_field.startsWith(`${localDate} `) &&
218
+ !compiledByScope.has(materializedScopeKey(doc)))
219
+ : [];
220
+ // Collected bills patch the ISSUE-day docs that still hold the issued
221
+ // ledger. Compute the patches against the POST-write documents — a period
222
+ // doc that both accumulates the day and holds an earlier issued bill must
223
+ // keep the accumulation in its patched version (persist patches AFTER
224
+ // writes).
225
+ const postWriteByScope = new Map();
226
+ for (const doc of existingByScope.values())
227
+ postWriteByScope.set(materializedScopeKey(doc), doc);
228
+ for (const write of writes)
229
+ postWriteByScope.set(materializedScopeKey(write.report), write.report);
230
+ for (const stale of staleHourDocuments)
231
+ postWriteByScope.delete(materializedScopeKey(stale));
232
+ const receivedPatches = [];
233
+ const receivedPayments = compile.received_payments ?? [];
234
+ if (receivedPayments.length > 0) {
235
+ const collectedByBill = new Map();
236
+ for (const collected of receivedPayments) {
237
+ collectedByBill.set(materializedCreditBillKey(collected.order_id, collected.payment_id), collected);
238
+ }
239
+ for (const doc of postWriteByScope.values()) {
240
+ if (!documentHoldsUnpatchedCreditBill(doc, collectedByBill))
241
+ continue;
242
+ const patched = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(doc, { received_payments: receivedPayments }, { computedAt });
243
+ if (patched == null)
244
+ return null;
245
+ const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(patched, {
246
+ reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
247
+ reason,
248
+ computedAt,
249
+ });
250
+ if (iteration == null)
251
+ return null;
252
+ receivedPatches.push({ report: patched, iteration });
253
+ }
254
+ }
255
+ return { writes, staleHourDocuments, receivedPatches, skippedDocuments, createdPeriodDocuments };
256
+ }
@@ -0,0 +1,223 @@
1
+ import mongoose from 'mongoose';
2
+ import { IOrder, IOrderPayment } from '../../schemas';
3
+ import { IMaterializedReportKeyMetrics, IMaterializedReportReceivedCreditBill, IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
4
+ /**
5
+ * Backend materialization helpers for `materialized_tenant_sales_overview_reports`
6
+ * (see `MATERIALIZED_REPORTS.md` "Backend materialization cycle").
7
+ *
8
+ * The backend cycle has two halves:
9
+ *
10
+ * 1. **JSON building** — `convertOrdersToMaterializedTenantSalesOverviewReports`
11
+ * compiles one tenant-day of raw orders into plain-JSON scope documents
12
+ * (24h-hour + period scopes) plus the credit bills collected that day.
13
+ * `sumMaterializedTenantSalesOverviewReports` accumulates those into
14
+ * longer-period documents (week → year) and
15
+ * `updateMaterializedTenantSalesOverviewReport` patches an existing document
16
+ * (delta amounts / credit-bill receipt tracking).
17
+ * 2. **Persistence** — `convertMaterializedTenantSalesOverviewReportJsonToBson`
18
+ * casts a JSON document through the mongoose schema so the job can upsert it.
19
+ *
20
+ * Conventions:
21
+ * - amounts are CENTS; every metric mirrors the live Reports > Overview
22
+ * aggregation (`sales-overview-reference.ts` is the test-time twin of the
23
+ * payment/order rules below — keep them in sync);
24
+ * - orders are attributed to the tenant-local BUSINESS day held by
25
+ * `order.localDate` (falls back to the `localDate` argument when absent);
26
+ * orders whose business day differs from the day being compiled only
27
+ * produce `received_payments` (credit-bill collections), never sales;
28
+ * - hour buckets: SALES orders use the punch hour (`order.localHour` →
29
+ * `gmtOffset` → `order_settled_at_mins ÷ 60`); credit-bill COLLECTION
30
+ * events use the SETTLEMENT hour (`gmtOffset` + `order_settled_at` →
31
+ * `order_settled_at_mins ÷ 60` → punch-hour fallback) — hour views must
32
+ * reflect when money was collected, not when the bill was punched;
33
+ * - INPUT CONTRACT: pass plain JSON documents (`.lean()` recommended). A
34
+ * hydrated document's map-cast `sale_type_metrics` is normalized
35
+ * defensively, but its other mongoose internals are not supported;
36
+ * - `CREDIT_BILLS` ledger: `issued.bills[].received_amount` and
37
+ * `received.bills[].received_amount` are CUMULATIVE "received so far" values
38
+ * (never event deltas) — a bill is settled when `received_amount >= amount`
39
+ * (the patch stamps `settled_at` with the received entry's true collection
40
+ * timestamp, falling back to `computedAt`); patches are absolute and
41
+ * idempotent, and a patch that CHANGES the ledger is a versioned write
42
+ * (bumps `iteration`);
43
+ * - cancelled orders are materialized fully under their `CANCELLED:*` keys —
44
+ * the read layer excludes them for TOTAL_SALES parity and derives the
45
+ * Cancelled facet from those keys;
46
+ * - reconcile/retry of a day re-applies it as
47
+ * `update(periodDoc, { subtract: [previousDayDoc], additions: [newDayDoc] })`
48
+ * (the stored `localDate` doc of D IS the delta previously folded into the
49
+ * period docs); every versioned write bumps `iteration` — the caller records
50
+ * the post-write state through `buildMaterializedTenantReportIteration` into
51
+ * the shared `materialized_tenant_reports_iterations` history (see
52
+ * `MATERIALIZED_REPORTS.md`);
53
+ * - VALIDATION: these helpers never throw — invalid input (malformed
54
+ * `localDate`, un-keyable `order_status` / `platform`, a `PAY_LATER`
55
+ * payment with no `payment_id`/`_id`, mismatched sums) returns `null`,
56
+ * which callers must treat as a data issue to surface/fix.
57
+ */
58
+ /** Options of `convertOrdersToMaterializedTenantSalesOverviewReports`. */
59
+ export interface IConvertOrdersToMaterializedReportsOptions {
60
+ /** Tenant brand id stored on every document (brand-level reads). */
61
+ brandId?: string;
62
+ /**
63
+ * Tenant GMT offset (e.g. `+5`) used to derive an order's local hour when
64
+ * the order does not carry local time fields itself (`order.localHour`).
65
+ * When omitted, the pre-computed `order.order_settled_at_mins` is used as
66
+ * minutes-of-the-local-day (the convention of the test fixtures).
67
+ */
68
+ gmtOffset?: number;
69
+ /**
70
+ * Tenant id used to emit the (empty) period documents for an order-less day.
71
+ * Ignored when `orders` is non-empty (tenant ids come from the orders).
72
+ */
73
+ tenantId?: string;
74
+ /** Override for `computed_at` / `createdAt` / `updatedAt` (tests, replays). */
75
+ computedAt?: Date;
76
+ }
77
+ /** Result of a tenant-day compile. */
78
+ export interface IConvertOrdersToMaterializedReportsResult {
79
+ materializedReports: IMaterializedTenantSalesOverviewReport[];
80
+ received_payments: IMaterializedReportReceivedCreditBill[];
81
+ }
82
+ /** `PAY_LATER` is reported as `UNPAID` (live-aggregation behavior). */
83
+ export declare function normalizeMaterializedPaymentType(paymentType: string): string;
84
+ /**
85
+ * Payment-level inclusion rule of the `TOTAL_PAYMENT_SALES` facet:
86
+ * settled/refunded payments, plus pending `UNPAID`/`PAY_LATER` (credit)
87
+ * payments.
88
+ */
89
+ export declare function isPaymentIncludedInMaterializedSalesOverview(payment: IOrderPayment): boolean;
90
+ /**
91
+ * Payment gross contribution in cents (mirrors the live aggregation):
92
+ * - no refund: `amount_due` for UNPAID, else `min(amount_paid, amount_due)`;
93
+ * card charges subtracted when `card_details` is present;
94
+ * - refunded: negative — `-amount_due` for UNPAID, else `-amount_refunded`.
95
+ */
96
+ export declare function getMaterializedPaymentGross(payment: IOrderPayment): number;
97
+ /** Whether a payment row represents a credit bill (`PAY_LATER`). */
98
+ export declare function isMaterializedCreditBillPayment(payment: IOrderPayment): boolean;
99
+ /**
100
+ * Plain-record view of a report's `sale_type_metrics`. The schema stores the
101
+ * map as a mongoose `Map` of subdocuments, so a hydrated document
102
+ * (`Model.find()` / the json→BSON cast) carries non-plain values — and
103
+ * `Object.entries` on the raw `Map` is EMPTY, which would silently wipe the
104
+ * stored metrics. This guard deep-converts hydrated shapes (Map container,
105
+ * subdocument values, document arrays) into plain values. Callers should still
106
+ * pass plain JSON (`.lean()`); this guard is the defensive net, not the
107
+ * contract.
108
+ */
109
+ export declare function normalizeMaterializedSaleTypeMetrics(metrics: IMaterializedTenantSalesOverviewReport['sale_type_metrics'] | Map<string, IMaterializedReportKeyMetrics> | null | undefined): Record<string, IMaterializedReportKeyMetrics>;
110
+ /**
111
+ * Compiles one tenant-day of orders into materialized scope documents:
112
+ *
113
+ * - one `localHour` document for every hour with activity (never more than 24);
114
+ * - one document per period scope (`localDate` … `localYear`) — always emitted,
115
+ * even for order-less days (empty metrics map), so reconcile/watermark
116
+ * comparisons stay uniform;
117
+ * - `day_index` is set on the `localHour` / `localDate` documents only;
118
+ * - `CREDIT_BILLS`: bills issued by the day's orders are itemized on every
119
+ * scope document of the day; bills collected that day (orders whose business
120
+ * `order.localDate` is earlier) itemize into `received` and are returned as
121
+ * `received_payments` so the caller can patch the issue-day documents.
122
+ *
123
+ * All outputs are plain JSON (dates are `Date` instances — JSON-serializable).
124
+ * Returns `null` (never throws) when the input is invalid — a malformed
125
+ * `localDate` or an order that cannot be keyed (`order_status` / `platform`
126
+ * missing or containing reserved characters) — `null` means a data issue.
127
+ */
128
+ export declare function convertOrdersToMaterializedTenantSalesOverviewReports(localDate: string, orders: IOrder[], options?: IConvertOrdersToMaterializedReportsOptions): IConvertOrdersToMaterializedReportsResult | null;
129
+ /**
130
+ * Casts a JSON materialized report through the collection's mongoose schema,
131
+ * returning a hydrated document ready to be saved / bulk-written (the
132
+ * `sale_type_metrics` plain object becomes a `Map`, date strings become
133
+ * `Date` instances, etc.).
134
+ *
135
+ * The document is NOT validated here — `save()` / `Model.validate()` still
136
+ * runs the schema validators.
137
+ */
138
+ export declare function convertMaterializedTenantSalesOverviewReportJsonToBson(report: IMaterializedTenantSalesOverviewReport): mongoose.HydratedDocument<IMaterializedTenantSalesOverviewReport>;
139
+ /**
140
+ * Sums materialized reports that share the same tenant, brand, key filters and
141
+ * `schema_version` — the period accumulation path. The scope MAY differ: pass
142
+ * the period document (month / quarter / year …) FIRST so the result keeps its
143
+ * identity while day documents are accumulated into it.
144
+ *
145
+ * Metric trees are summed per key; credit-bill bills are concatenated and
146
+ * de-duplicated by `(order_id, payment_id)` keeping the most-collected state,
147
+ * then all ledger counters are recomputed from the itemized bills — so
148
+ * overlapping compiles never double-count.
149
+ *
150
+ * Returns `null` (never throws) when the inputs cannot be summed — empty list
151
+ * or mismatched tenant / brand / schema version / key filters. `null` means a
152
+ * data issue the caller must surface.
153
+ */
154
+ export declare function sumMaterializedTenantSalesOverviewReports(reports: IMaterializedTenantSalesOverviewReport[], options?: {
155
+ computedAt?: Date;
156
+ }): IMaterializedTenantSalesOverviewReport | null;
157
+ /**
158
+ * Subtracts `subtrahend`'s metric tree from `minuend` — the first half of the
159
+ * reconcile/retry flow
160
+ * (`update(periodDoc, { subtract: [previousDayDoc], additions: [newDayDoc] })`):
161
+ * the stored `localDate` doc of day D IS the delta previously folded into the
162
+ * period docs.
163
+ *
164
+ * Bills are removed by `(order_id, payment_id)`; ledger counters are recomputed
165
+ * from the remaining bills. Returns `null` (never throws) on mismatched inputs.
166
+ */
167
+ export declare function subtractMaterializedTenantSalesOverviewReports(minuend: IMaterializedTenantSalesOverviewReport, subtrahend: IMaterializedTenantSalesOverviewReport): IMaterializedTenantSalesOverviewReport | null;
168
+ /** Update descriptor of `updateMaterializedTenantSalesOverviewReport`. */
169
+ export interface IUpdateMaterializedTenantSalesOverviewReportInput {
170
+ /**
171
+ * Replaces the metric tree wholesale (the envelope is kept) — the day-close
172
+ * write for `localHour` / `localDate` documents.
173
+ */
174
+ replacement?: IMaterializedTenantSalesOverviewReport;
175
+ /**
176
+ * Reports subtracted from the existing metrics BEFORE `additions` — the
177
+ * reconcile/retry flow: subtract the previously applied day delta, then add
178
+ * the newly calculated one.
179
+ */
180
+ subtract?: IMaterializedTenantSalesOverviewReport[];
181
+ /**
182
+ * Reports whose metrics are summed INTO the existing document (delta
183
+ * amounts) — e.g. a fresh day compile folded into an accumulating
184
+ * month document.
185
+ */
186
+ additions?: IMaterializedTenantSalesOverviewReport[];
187
+ /**
188
+ * Credit-bill collection events (`received_payments` of a day compile) used
189
+ * to patch the document's `issued` ledger — applies to the ISSUE-day
190
+ * documents: `received_amount` is set to the cumulative received value;
191
+ * `credit_note` and `settled_at` (the received entry's collection timestamp,
192
+ * falling back to `computedAt`) are recorded when full collection is
193
+ * reached. Absolute values keep replays idempotent; a patch that changes
194
+ * the ledger is a versioned write (bumps `iteration` — append its history
195
+ * row), a no-op patch bumps nothing.
196
+ */
197
+ received_payments?: IMaterializedReportReceivedCreditBill[];
198
+ }
199
+ /**
200
+ * Versioned write on an existing JSON report (never throws; `null` on
201
+ * mismatched inputs) — the single place that mutates a stored document:
202
+ *
203
+ * 1. metrics: `replacement` swaps the tree wholesale (day/hour docs);
204
+ * otherwise `subtract` first (previously applied deltas), then `additions`
205
+ * (newly calculated ones) — the reconcile/retry pattern;
206
+ * 2. `received_payments` patches matching `issued` bills (`received_amount`
207
+ * cumulative, `credit_note`, `settled_at` — the received entry's true
208
+ * collection timestamp, falling back to `computedAt`, stamped when
209
+ * `received_amount >= amount`);
210
+ * 3. versioning: metric writes (`replacement` / `subtract` / `additions`) AND
211
+ * received-payment patches that change the ledger bump `iteration` — the
212
+ * returned document is recorded as a `materialized_tenant_reports_iterations`
213
+ * row by the caller (`buildMaterializedTenantReportIteration`); no-op
214
+ * patches bump nothing, so replays stay churn-free;
215
+ * 4. `source_watermark` advances to the max of the existing and the incoming
216
+ * (`replacement` / `additions`) watermarks — monotonic, never regressed
217
+ * (rollbacks / replays keep the previously folded maximum).
218
+ *
219
+ * Returns a new JSON report; the input is not mutated.
220
+ */
221
+ export declare function updateMaterializedTenantSalesOverviewReport(existing: IMaterializedTenantSalesOverviewReport, updates: IUpdateMaterializedTenantSalesOverviewReportInput, options?: {
222
+ computedAt?: Date;
223
+ }): IMaterializedTenantSalesOverviewReport | null;