@managesome/eposmatic-toolkit 0.4.7 → 0.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +33 -0
  2. package/esm/constants/enums/communications.js +1 -0
  3. package/esm/helpers/materialized-reports/index.js +1 -0
  4. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +982 -0
  5. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +276 -33
  6. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +327 -41
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +118 -235
  9. package/esm/schemas/models/index.js +1 -0
  10. package/esm/schemas/models/materialized_credit_bills.js +265 -0
  11. package/esm/schemas/models/materialized_tenant_reports_iterations.js +13 -0
  12. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +39 -97
  13. package/esm/schemas/types/index.js +1 -0
  14. package/esm/schemas/types/materialized_credit_bills.js +1 -0
  15. package/lib/constants/MATERIALIZED_REPORTS.d.ts +28 -2
  16. package/lib/constants/MATERIALIZED_REPORTS.js +34 -1
  17. package/lib/constants/enums/communications.d.ts +1 -0
  18. package/lib/constants/enums/communications.js +2 -1
  19. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  20. package/lib/helpers/materialized-reports/index.js +1 -0
  21. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.d.ts +307 -0
  22. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +1003 -0
  23. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +36 -2
  24. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +278 -34
  25. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +66 -8
  26. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +326 -40
  27. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +18 -2
  28. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +72 -11
  29. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +46 -37
  30. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +119 -238
  31. package/lib/helpers/types/materialized-reports-apis.d.ts +32 -5
  32. package/lib/schemas/models/index.d.ts +1 -0
  33. package/lib/schemas/models/index.js +1 -0
  34. package/lib/schemas/models/materialized_credit_bills.d.ts +337 -0
  35. package/lib/schemas/models/materialized_credit_bills.js +268 -0
  36. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +20 -6
  37. package/lib/schemas/models/materialized_tenant_reports_iterations.js +14 -1
  38. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +37 -165
  39. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +40 -98
  40. package/lib/schemas/types/index.d.ts +1 -0
  41. package/lib/schemas/types/index.js +1 -0
  42. package/lib/schemas/types/materialized_credit_bills.d.ts +139 -0
  43. package/lib/schemas/types/materialized_credit_bills.js +2 -0
  44. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +32 -77
  45. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.d.ts +1 -0
  46. package/lib/tests/materialized-reports/materialized-credit-bills-helpers.test.js +715 -0
  47. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +96 -0
  48. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +9 -0
  49. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +23 -24
  50. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +327 -22
  51. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +27 -2
  52. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +12 -27
  53. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +79 -146
  54. package/package.json +1 -1
@@ -0,0 +1,982 @@
1
+ import mongoose from 'mongoose';
2
+ import { PAYMENT_TYPE_ENUM } from '../../constants';
3
+ import { ALL_MATERIALIZED_REPORT_SCOPES, MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM, MATERIALIZED_REPORT_SCOPE_ENUM, SALES_OVERVIEW_KEY_FILTERS, } from '../../constants/MATERIALIZED_REPORTS';
4
+ import { MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION } from '../../schemas/models/materialized_credit_bills';
5
+ import { getLocalDocumentFields, getLocalFieldsFromLocalDate } from '../utils/time-helpers';
6
+ import { buildMaterializedReportKey } from './key-helpers';
7
+ import { getDayIndexFromLocalDate, getMaterializedHourScopeField, getMaterializedPeriodScopeFields, } from './scope-helpers';
8
+ /**
9
+ * The shared credit-bill ledger (`materialized_tenant_credit_bills`) —
10
+ * builders, resolution and math (see `MATERIALIZED_REPORTS.md`).
11
+ *
12
+ * The ledger is materialized EXACTLY like every other report collection (one
13
+ * document per tenant × scope context × scope value), but capped at
14
+ * `LOCAL_MONTH` (`MATERIALIZED_CREDIT_BILLS_SCOPES`) so no document grows
15
+ * unboundedly. Each document carries a per-key map of slim `issued[]` /
16
+ * `received[]` entries — ids + credit facts; the order document stays the
17
+ * single source of the sale.
18
+ *
19
+ * This module owns the whole credit pipeline:
20
+ * - `buildCreditBillIssuedCandidatesFromOrder` / `buildCreditBillEventCandidatesFromOrder`
21
+ * — order-pure candidates (the compile emits them, resolution happens at
22
+ * close-plan time);
23
+ * - `resolveCreditBillDay` — the ONLY stateful step: resolves receipt deltas
24
+ * against the stored documents (idempotent re-closes), carries issue anchors
25
+ * forward and emits the settlements the close must patch (exactly once);
26
+ * - `buildMaterializedCreditBillDayReports` — materializes one day's scope
27
+ * documents (hour/date/week/weekOfYear/month) from the resolution;
28
+ * - `updateMaterializedCreditBillsReport` — replacement / subtract / add /
29
+ * settlement-patch document updates (mirrors the sales report updater);
30
+ * - `computeMaterializedCreditBillTotalsFromReports` — the read-side counter
31
+ * spec (the ops aggregation mirrors this).
32
+ *
33
+ * Amounts are cents. `IOrderPayment` values are read, never mutated.
34
+ */
35
+ /** Whether a payment row represents a credit bill (`PAY_LATER`). */
36
+ export const isMaterializedCreditBillPayment = (payment) => payment.payment_type === PAYMENT_TYPE_ENUM.PAY_LATER;
37
+ /* ------------------------------------------------------------------------ */
38
+ /* Hour anchors (tenant-local) */
39
+ /* ------------------------------------------------------------------------ */
40
+ /** Punch hour of an issued bill — mirrors the report documents' sales anchor. */
41
+ export const resolveOrderLocalHour = (order, localDate, gmtOffset) => {
42
+ if (typeof order.localHour === 'number' && order.localHour >= 0 && order.localHour <= 23) {
43
+ return order.localHour;
44
+ }
45
+ if (typeof gmtOffset === 'number') {
46
+ const fields = getLocalFieldsFromLocalDate(order.localDate ?? localDate, gmtOffset, order.order_settled_at ?? order.createdAt);
47
+ return fields.localHour;
48
+ }
49
+ if (typeof order.order_settled_at_mins === 'number' && order.order_settled_at_mins >= 0) {
50
+ return Math.min(23, Math.floor(order.order_settled_at_mins / 60));
51
+ }
52
+ return null;
53
+ };
54
+ /**
55
+ * Hour bucket of a credit-bill COLLECTION event: the SETTLEMENT anchor
56
+ * resolves the hour — never the punch hour. Chain: `gmtOffset` +
57
+ * `order_settled_at` (tenant-local hour) → `order_settled_at_mins ÷ 60` →
58
+ * the settlement timestamp's UTC hour → punch-hour fallback (last resort).
59
+ */
60
+ export const resolveReceivedLocalHour = (order, localDate, gmtOffset) => {
61
+ if (typeof gmtOffset === 'number' && order.order_settled_at != null) {
62
+ const settledAt = new Date(order.order_settled_at);
63
+ if (!Number.isNaN(settledAt.getTime()))
64
+ return getLocalDocumentFields(gmtOffset, settledAt).localHour;
65
+ }
66
+ if (typeof order.order_settled_at_mins === 'number' && order.order_settled_at_mins >= 0) {
67
+ return Math.min(23, Math.floor(order.order_settled_at_mins / 60));
68
+ }
69
+ if (order.order_settled_at != null) {
70
+ const settledUtc = new Date(order.order_settled_at);
71
+ if (!Number.isNaN(settledUtc.getTime()))
72
+ return settledUtc.getUTCHours();
73
+ }
74
+ return resolveOrderLocalHour(order, localDate, gmtOffset);
75
+ };
76
+ /** `'YYYY-MM-DD HH'` hour label of a resolved hour (null when unknown). */
77
+ export const toMaterializedHourLabel = (localDate, hour) => hour == null ? null : `${localDate} ${`${hour}`.padStart(2, '0')}`;
78
+ const creditBillIdentityKey = (orderId, paymentId) => `${orderId}|${paymentId}`;
79
+ const maxDate = (a, b) => {
80
+ if (a == null)
81
+ return b ?? null;
82
+ if (b == null)
83
+ return a;
84
+ return a.getTime() >= b.getTime() ? a : b;
85
+ };
86
+ /**
87
+ * ISSUE candidates of one order (its business day is the compiled day): one
88
+ * per `PAY_LATER` payment. Un-keyable payments (no `payment_id` / `_id`) →
89
+ * `null` (the identity must never collapse).
90
+ *
91
+ * N2 backfill rule: a bill settled NOW whose settlement local day is AFTER
92
+ * this compiled business day (a from-`orders` backfill) is emitted
93
+ * UNPAID-at-issue (`received_at_issue 0`, unsettled, `received_amount 0`) —
94
+ * exactly the state the live close saw; the collection day then carries the
95
+ * receipt delta. Without `gmtOffset` the comparison is skipped (live closes
96
+ * never need it — the order is not settled yet at the day's close).
97
+ */
98
+ export function buildCreditBillIssuedCandidatesFromOrder(order, orderLocalDate, options) {
99
+ const { now, gmtOffset } = options;
100
+ const candidates = [];
101
+ const issuedAt = new Date(order.createdAt ?? order.order_settled_at ?? now);
102
+ const settledAt = order.order_settled_at != null ? new Date(order.order_settled_at) : null;
103
+ const settledAtValid = settledAt != null && !Number.isNaN(settledAt.getTime());
104
+ const settlementLocalDate = settledAtValid && typeof gmtOffset === 'number' ? getLocalDocumentFields(gmtOffset, settledAt).localDate : null;
105
+ const settledLater = settlementLocalDate != null && settlementLocalDate > orderLocalDate;
106
+ const issuedHourLabel = toMaterializedHourLabel(orderLocalDate, resolveOrderLocalHour(order, orderLocalDate, gmtOffset));
107
+ const watermark = new Date(order.updatedAt ?? now);
108
+ for (const payment of order.payments ?? []) {
109
+ if (!isMaterializedCreditBillPayment(payment))
110
+ continue;
111
+ const paymentId = payment.payment_id ?? payment._id ?? null;
112
+ if (paymentId == null || paymentId.length === 0)
113
+ return null; // un-keyable bill — data issue
114
+ const amount = payment.amount_due ?? 0;
115
+ const receivedAmount = payment.amount_paid ?? 0;
116
+ const settled = !settledLater && receivedAmount >= amount;
117
+ candidates.push({
118
+ order_id: order._id,
119
+ payment_id: paymentId,
120
+ order_status: order.order_status,
121
+ platform: order.platform,
122
+ amount,
123
+ issued_at: issuedAt,
124
+ issued_local_hour: issuedHourLabel,
125
+ received_at_issue: settledLater ? 0 : receivedAmount,
126
+ received_amount: settledLater ? 0 : receivedAmount,
127
+ settled_at: settled ? (settledAt ?? now) : null,
128
+ settled_local_date: settled ? orderLocalDate : null,
129
+ credit_note: payment.note ?? null,
130
+ source_watermark: watermark,
131
+ });
132
+ }
133
+ return candidates;
134
+ }
135
+ export function buildCreditBillEventCandidatesFromOrder(order, eventLocalDate, options) {
136
+ const { now, gmtOffset } = options;
137
+ const candidates = [];
138
+ const orderLocalDate = order.localDate ?? eventLocalDate;
139
+ const issuedAt = new Date(order.createdAt ?? order.order_settled_at ?? now);
140
+ const issuedHourLabel = toMaterializedHourLabel(orderLocalDate, resolveOrderLocalHour(order, orderLocalDate, gmtOffset));
141
+ const eventHourLabel = toMaterializedHourLabel(eventLocalDate, resolveReceivedLocalHour(order, eventLocalDate, gmtOffset));
142
+ const settledAt = order.order_settled_at != null ? new Date(order.order_settled_at) : null;
143
+ const watermark = new Date(order.updatedAt ?? now);
144
+ for (const payment of order.payments ?? []) {
145
+ if (!isMaterializedCreditBillPayment(payment))
146
+ continue;
147
+ const paymentId = payment.payment_id ?? payment._id ?? null;
148
+ if (paymentId == null || paymentId.length === 0)
149
+ return null; // un-keyable bill — data issue
150
+ const receivedAmount = payment.amount_paid ?? 0;
151
+ if (receivedAmount <= 0)
152
+ continue; // nothing collected yet
153
+ candidates.push({
154
+ order_id: order._id,
155
+ payment_id: paymentId,
156
+ order_status: order.order_status,
157
+ platform: order.platform,
158
+ amount: payment.amount_due ?? 0,
159
+ issued_at: issuedAt,
160
+ issued_local_date: orderLocalDate,
161
+ issued_local_hour: issuedHourLabel,
162
+ candidate_cumulative: receivedAmount,
163
+ event: {
164
+ event_local_date: eventLocalDate,
165
+ event_local_hour: eventHourLabel,
166
+ received_delta: 0,
167
+ event_type: MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM.RECEIPT,
168
+ credit_note: payment.note ?? null,
169
+ settled_at: settledAt,
170
+ },
171
+ source_watermark: watermark,
172
+ });
173
+ }
174
+ return candidates;
175
+ }
176
+ /** Plain-object iteration over a possibly hydrated `credit_bills` map. */
177
+ const sectionsOf = (report) => {
178
+ const raw = report.credit_bills;
179
+ if (raw == null)
180
+ return [];
181
+ const plain = typeof raw.entries === 'function' ? undefined : raw;
182
+ if (plain != null)
183
+ return Object.entries(plain);
184
+ return Array.from(raw.entries());
185
+ };
186
+ /**
187
+ * Resolves one compiled day against the stored ledger documents — NEVER
188
+ * throws (`null` on inconsistent input):
189
+ * - EVENT deltas: a stored receipt entry for the same `(bill, event day)`
190
+ * keeps its own delta and cumulative (idempotent re-closes); a first-seen
191
+ * event's delta resolves as `candidate_cumulative − stored issued
192
+ * received_amount` (the stored cumulative is the pre-event total; 0 when the
193
+ * bill was never materialized), clamped ≥ 0;
194
+ * - ISSUE anchors: `received_at_issue` / settlement fields carry forward from
195
+ * the stored issued entry — a re-close after collection never re-anchors
196
+ * them;
197
+ * - SETTLEMENTS: a resolved event whose cumulative now covers the amount
198
+ * emits a settlement (patched onto the issue scopes) exactly once — only
199
+ * for issue days EARLIER than the compiled day and only when the stored
200
+ * entry is not settled yet.
201
+ */
202
+ export function resolveCreditBillDay(input) {
203
+ if (input == null)
204
+ return null;
205
+ const { tenantId, localDate, computedAt } = input;
206
+ if (typeof tenantId !== 'string' || tenantId.length === 0)
207
+ return null;
208
+ if (typeof localDate !== 'string' || localDate.length === 0)
209
+ return null;
210
+ const storedIssuedByKey = new Map();
211
+ const storedReceivedByKey = new Map();
212
+ for (const report of input.stored ?? []) {
213
+ if (report == null || report.tenant_id !== tenantId)
214
+ continue;
215
+ for (const [, section] of sectionsOf(report)) {
216
+ for (const entry of section?.issued ?? []) {
217
+ const key = creditBillIdentityKey(entry.order_id, entry.payment_id);
218
+ const prior = storedIssuedByKey.get(key);
219
+ if (prior == null || (entry.received_amount ?? 0) > (prior.received_amount ?? 0)) {
220
+ storedIssuedByKey.set(key, entry);
221
+ }
222
+ }
223
+ for (const entry of section?.received ?? []) {
224
+ storedReceivedByKey.set(`${creditBillIdentityKey(entry.order_id, entry.payment_id)}|${entry.event_local_date ?? ''}`, entry);
225
+ }
226
+ }
227
+ }
228
+ // Authoritative pre-event cumulative per bill: the DEDUPED stored receipt
229
+ // deltas (the issued entry's `received_amount` is patched only at
230
+ // settlement, so it can be stale between partial receipts).
231
+ const storedReceivedDeltasByBill = new Map();
232
+ for (const entry of storedReceivedByKey.values()) {
233
+ const identity = creditBillIdentityKey(entry.order_id, entry.payment_id);
234
+ storedReceivedDeltasByBill.set(identity, (storedReceivedDeltasByBill.get(identity) ?? 0) + (entry.received_delta ?? 0));
235
+ }
236
+ const issued = [];
237
+ for (const candidate of input.issued ?? []) {
238
+ const key = buildMaterializedReportKey([candidate.order_status, candidate.platform]);
239
+ if (key == null)
240
+ return null; // un-keyable sale-type fields — data issue
241
+ const stored = storedIssuedByKey.get(creditBillIdentityKey(candidate.order_id, candidate.payment_id));
242
+ issued.push({
243
+ key,
244
+ source_watermark: candidate.source_watermark,
245
+ entry: {
246
+ order_id: candidate.order_id,
247
+ payment_id: candidate.payment_id,
248
+ amount: candidate.amount,
249
+ issued_at: candidate.issued_at,
250
+ issued_local_hour: candidate.issued_local_hour ?? stored?.issued_local_hour ?? null,
251
+ // Carry-forward anchors — never re-anchored to the current payment state.
252
+ received_at_issue: stored?.received_at_issue ?? candidate.received_at_issue,
253
+ received_amount: Math.max(stored?.received_amount ?? 0, candidate.received_amount),
254
+ settled_at: stored?.settled_at ?? candidate.settled_at,
255
+ settled_local_date: stored?.settled_local_date ?? candidate.settled_local_date,
256
+ credit_note: candidate.credit_note ?? stored?.credit_note ?? null,
257
+ },
258
+ });
259
+ }
260
+ const received_events = [];
261
+ const settled_bills = [];
262
+ for (const candidate of input.events ?? []) {
263
+ const key = buildMaterializedReportKey([candidate.order_status, candidate.platform]);
264
+ if (key == null)
265
+ return null; // un-keyable sale-type fields — data issue
266
+ const identity = creditBillIdentityKey(candidate.order_id, candidate.payment_id);
267
+ const storedIssued = storedIssuedByKey.get(identity) ?? null;
268
+ const storedEvent = storedReceivedByKey.get(`${identity}|${candidate.event.event_local_date}`) ?? null;
269
+ let delta;
270
+ let cumulativeAfter;
271
+ let hourLabel = candidate.event.event_local_hour ?? storedEvent?.event_local_hour ?? null;
272
+ if (storedEvent != null) {
273
+ // Idempotent: the stored event keeps its own delta; only a missing hour fills.
274
+ delta = storedEvent.received_delta ?? 0;
275
+ cumulativeAfter = storedEvent.received_amount ?? 0;
276
+ }
277
+ else {
278
+ const priorFromReceipts = (storedIssued?.received_at_issue ?? 0) + (storedReceivedDeltasByBill.get(identity) ?? 0);
279
+ const prior = Math.max(storedIssued?.received_amount ?? 0, priorFromReceipts);
280
+ delta = Math.max(0, (candidate.candidate_cumulative ?? 0) - prior);
281
+ cumulativeAfter = Math.max(prior, candidate.candidate_cumulative ?? 0);
282
+ }
283
+ if (hourLabel == null && candidate.event.event_local_hour != null) {
284
+ hourLabel = candidate.event.event_local_hour;
285
+ }
286
+ const amount = candidate.amount;
287
+ const settled = cumulativeAfter >= amount;
288
+ const settledAt = settled && storedIssued?.settled_at == null
289
+ ? candidate.event.settled_at != null
290
+ ? new Date(candidate.event.settled_at)
291
+ : computedAt
292
+ : null;
293
+ const settledLocalDate = settled && storedIssued?.settled_local_date == null ? candidate.event.event_local_date : null;
294
+ received_events.push({
295
+ key,
296
+ entry: {
297
+ order_id: candidate.order_id,
298
+ payment_id: candidate.payment_id,
299
+ event_local_date: candidate.event.event_local_date,
300
+ amount,
301
+ received_amount: cumulativeAfter,
302
+ received_delta: delta,
303
+ received_at: candidate.event.settled_at != null ? new Date(candidate.event.settled_at) : null,
304
+ event_local_hour: hourLabel,
305
+ credit_note: candidate.event.credit_note ?? storedEvent?.credit_note ?? null,
306
+ issued_local_date: candidate.issued_local_date,
307
+ },
308
+ received_at: candidate.event.settled_at != null ? new Date(candidate.event.settled_at) : null,
309
+ credit_note: candidate.event.credit_note ?? storedEvent?.credit_note ?? null,
310
+ settled,
311
+ settled_at: settled && storedIssued?.settled_at == null ? (settledAt ?? computedAt) : null,
312
+ settled_local_date: settledLocalDate ?? candidate.event.event_local_date,
313
+ source_watermark: candidate.source_watermark,
314
+ });
315
+ // The issue scopes must be patched exactly once per settlement — only
316
+ // for EARLIER issue days (a same-day settlement rides the issued payload).
317
+ if (settled && storedIssued != null && candidate.issued_local_date !== localDate) {
318
+ const alreadySettled = storedIssued.settled_at != null || storedIssued.settled_local_date != null;
319
+ if (!alreadySettled) {
320
+ settled_bills.push({
321
+ key,
322
+ order_id: candidate.order_id,
323
+ payment_id: candidate.payment_id,
324
+ amount,
325
+ received_amount: cumulativeAfter,
326
+ settled_at: settledAt ?? computedAt,
327
+ settled_local_date: candidate.event.event_local_date,
328
+ credit_note: candidate.event.credit_note ?? storedIssued.credit_note ?? null,
329
+ issued_local_date: candidate.issued_local_date,
330
+ issued_local_hour: storedIssued.issued_local_hour ?? candidate.issued_local_hour ?? null,
331
+ });
332
+ }
333
+ }
334
+ }
335
+ return { issued, received_events, settled_bills };
336
+ }
337
+ const emptySection = () => ({ issued: [], received: [] });
338
+ const sectionFor = (map, key) => map[key] ?? (map[key] = emptySection());
339
+ /**
340
+ * Materializes ONE day's credit documents from its resolution — the
341
+ * month-capped scope set (`MATERIALIZED_CREDIT_BILLS_SCOPES`): one document per
342
+ * active hour, plus date, week, ISO week-of-year and month. Returns `[]` when
343
+ * the day has no credit activity; `null` on malformed input (never throws).
344
+ */
345
+ export function buildMaterializedCreditBillDayReports(input) {
346
+ if (input == null)
347
+ return null;
348
+ const { tenantId, brandId, localDate, resolution, computedAt } = input;
349
+ const periodFields = getMaterializedPeriodScopeFields(localDate);
350
+ if (periodFields == null)
351
+ return null;
352
+ const dayIndex = getDayIndexFromLocalDate(localDate);
353
+ const hourSections = new Map();
354
+ const sectionsForHour = (hourLabel) => {
355
+ let sections = hourSections.get(hourLabel);
356
+ if (sections == null) {
357
+ sections = {};
358
+ hourSections.set(hourLabel, sections);
359
+ }
360
+ return sections;
361
+ };
362
+ const dateSections = {};
363
+ const weekSections = {};
364
+ const weekOfYearSections = {};
365
+ const monthSections = {};
366
+ let watermark = null;
367
+ const foldWatermark = (value) => {
368
+ watermark = maxDate(watermark, value);
369
+ };
370
+ for (const resolved of resolution.issued) {
371
+ foldWatermark(resolved.source_watermark);
372
+ const targets = [
373
+ dateSections,
374
+ weekSections,
375
+ weekOfYearSections,
376
+ monthSections,
377
+ ];
378
+ if (resolved.entry.issued_local_hour != null) {
379
+ targets.push(sectionsForHour(resolved.entry.issued_local_hour));
380
+ }
381
+ for (const target of targets) {
382
+ sectionFor(target, resolved.key).issued.push({ ...resolved.entry });
383
+ }
384
+ }
385
+ for (const resolved of resolution.received_events) {
386
+ foldWatermark(resolved.source_watermark);
387
+ const targets = [
388
+ dateSections,
389
+ weekSections,
390
+ weekOfYearSections,
391
+ monthSections,
392
+ ];
393
+ if (resolved.entry.event_local_hour != null) {
394
+ targets.push(sectionsForHour(resolved.entry.event_local_hour));
395
+ }
396
+ for (const target of targets) {
397
+ sectionFor(target, resolved.key).received.push({ ...resolved.entry });
398
+ }
399
+ }
400
+ if (hourSections.size === 0 && Object.keys(dateSections).length === 0)
401
+ return [];
402
+ const sourceWatermark = watermark ?? computedAt;
403
+ const makeDoc = (scopeContext, scopeField, sections) => ({
404
+ _id: new mongoose.Types.ObjectId().toHexString(),
405
+ tenant_id: tenantId,
406
+ brand_id: brandId,
407
+ scope_context: scopeContext,
408
+ scope_field: scopeField,
409
+ day_index: scopeContext === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ||
410
+ scopeContext === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE
411
+ ? dayIndex
412
+ : null,
413
+ sale_type_key_filters: [...SALES_OVERVIEW_KEY_FILTERS],
414
+ credit_bills: sections,
415
+ iteration: 1,
416
+ schema_version: MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION,
417
+ source_watermark: sourceWatermark,
418
+ computed_at: computedAt,
419
+ createdAt: computedAt,
420
+ updatedAt: computedAt,
421
+ });
422
+ const docs = [];
423
+ for (const hourLabel of [...hourSections.keys()].sort()) {
424
+ docs.push(makeDoc(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, hourLabel, sectionsForHour(hourLabel)));
425
+ }
426
+ docs.push(makeDoc(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, localDate, dateSections));
427
+ docs.push(makeDoc(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK, periodFields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK], weekSections));
428
+ docs.push(makeDoc(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR, periodFields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR], weekOfYearSections));
429
+ docs.push(makeDoc(MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH, periodFields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH], monthSections));
430
+ return docs;
431
+ }
432
+ const canMergeCreditBillsReports = (a, b) => a.tenant_id === b.tenant_id &&
433
+ a.scope_context === b.scope_context &&
434
+ a.scope_field === b.scope_field &&
435
+ a.schema_version === b.schema_version &&
436
+ JSON.stringify(a.sale_type_key_filters ?? []) === JSON.stringify(b.sale_type_key_filters ?? []);
437
+ const toMutableSections = (source) => {
438
+ const mut = {};
439
+ const raw = source;
440
+ if (raw == null)
441
+ return mut;
442
+ const entries = typeof raw.entries === 'function'
443
+ ? Array.from(raw.entries())
444
+ : Object.entries(raw);
445
+ for (const [key, section] of entries) {
446
+ mut[key] = {
447
+ issued: (section?.issued ?? []).map((entry) => ({ ...entry })),
448
+ received: (section?.received ?? []).map((entry) => ({ ...entry })),
449
+ };
450
+ }
451
+ return mut;
452
+ };
453
+ const serializeSections = (sections) => JSON.stringify(Object.keys(sections)
454
+ .sort()
455
+ .map((key) => [key, sections[key]]));
456
+ const pruneSections = (sections) => {
457
+ const pruned = {};
458
+ for (const [key, section] of Object.entries(sections)) {
459
+ if ((section.issued ?? []).length === 0 && (section.received ?? []).length === 0)
460
+ continue;
461
+ pruned[key] = section;
462
+ }
463
+ return pruned;
464
+ };
465
+ /**
466
+ * Applies one write to a stored credit document — NEVER throws (`null` on
467
+ * inconsistent input). Mirrors `updateMaterializedTenantSalesOverviewReport`:
468
+ * replacement swaps the payload; `subtract` removes the identity-matched
469
+ * entries a re-close must drop; `additions` folds the recompiled day's entries
470
+ * back in; `settled_bills` patches issue-scope `issued[]` entries (received
471
+ * cumulative + settlement anchors + note) exactly once. Versioned writes: the
472
+ * iteration bumps when the payload or the ledger state actually changed.
473
+ */
474
+ export function updateMaterializedCreditBillsReport(existing, updates, options = {}) {
475
+ if (existing == null || updates == null)
476
+ return null;
477
+ const computedAt = options.computedAt ?? new Date();
478
+ for (const doc of [updates.replacement, ...(updates.additions ?? [])]) {
479
+ if (doc == null)
480
+ continue; // patch-only / subtract-only updates pass no identity docs
481
+ if (!canMergeCreditBillsReports(existing, doc))
482
+ return null;
483
+ }
484
+ for (const doc of updates.subtract ?? []) {
485
+ // A re-close subtracts the STORED DAY document — a DIFFERENT scope than
486
+ // the period document being updated; only tenant / schema / key grammar
487
+ // must agree (the removed entries are identity-matched inside).
488
+ if (doc == null ||
489
+ existing.tenant_id !== doc.tenant_id ||
490
+ existing.schema_version !== doc.schema_version ||
491
+ JSON.stringify(existing.sale_type_key_filters ?? []) !== JSON.stringify(doc.sale_type_key_filters ?? [])) {
492
+ return null;
493
+ }
494
+ }
495
+ let sections;
496
+ let sourceWatermark = existing.source_watermark;
497
+ if (updates.replacement != null) {
498
+ sections = toMutableSections(updates.replacement.credit_bills);
499
+ sourceWatermark =
500
+ maxDate(existing.source_watermark, updates.replacement.source_watermark) ?? existing.source_watermark;
501
+ }
502
+ else {
503
+ sections = toMutableSections(existing.credit_bills);
504
+ for (const delta of updates.subtract ?? []) {
505
+ for (const [key, section] of Object.entries(toMutableSections(delta.credit_bills))) {
506
+ const target = sections[key];
507
+ if (target == null)
508
+ continue;
509
+ const issuedIdentities = new Set(section.issued.map((entry) => creditBillIdentityKey(entry.order_id, entry.payment_id)));
510
+ const receivedIdentities = new Set(section.received.map((entry) => `${creditBillIdentityKey(entry.order_id, entry.payment_id)}|${entry.event_local_date}`));
511
+ target.issued = target.issued.filter((entry) => !issuedIdentities.has(creditBillIdentityKey(entry.order_id, entry.payment_id)));
512
+ target.received = target.received.filter((entry) => !receivedIdentities.has(`${creditBillIdentityKey(entry.order_id, entry.payment_id)}|${entry.event_local_date}`));
513
+ if (target.issued.length === 0 && target.received.length === 0)
514
+ delete sections[key];
515
+ }
516
+ }
517
+ for (const delta of updates.additions ?? []) {
518
+ for (const [key, section] of Object.entries(toMutableSections(delta.credit_bills))) {
519
+ const target = sections[key] ?? (sections[key] = emptySection());
520
+ for (const entry of section.issued) {
521
+ const identity = creditBillIdentityKey(entry.order_id, entry.payment_id);
522
+ const index = target.issued.findIndex((current) => creditBillIdentityKey(current.order_id, current.payment_id) === identity);
523
+ if (index >= 0)
524
+ target.issued[index] = entry;
525
+ else
526
+ target.issued.push(entry);
527
+ }
528
+ for (const entry of section.received) {
529
+ const identity = `${creditBillIdentityKey(entry.order_id, entry.payment_id)}|${entry.event_local_date}`;
530
+ const index = target.received.findIndex((current) => `${creditBillIdentityKey(current.order_id, current.payment_id)}|${current.event_local_date}` === identity);
531
+ if (index >= 0)
532
+ target.received[index] = entry;
533
+ else
534
+ target.received.push(entry);
535
+ }
536
+ }
537
+ }
538
+ for (const delta of updates.additions ?? []) {
539
+ sourceWatermark = maxDate(sourceWatermark, delta.source_watermark) ?? sourceWatermark;
540
+ }
541
+ }
542
+ let ledgerPatched = false;
543
+ for (const settlement of updates.settled_bills ?? []) {
544
+ const target = sections[settlement.key];
545
+ if (target == null)
546
+ continue;
547
+ const index = target.issued.findIndex((entry) => creditBillIdentityKey(entry.order_id, entry.payment_id) ===
548
+ creditBillIdentityKey(settlement.order_id, settlement.payment_id));
549
+ if (index < 0)
550
+ continue;
551
+ const entry = target.issued[index];
552
+ if (entry.settled_local_date != null || entry.settled_at != null)
553
+ continue; // already settled — idempotent
554
+ target.issued[index] = {
555
+ ...entry,
556
+ received_amount: Math.max(entry.received_amount ?? 0, settlement.received_amount),
557
+ settled_at: settlement.settled_at,
558
+ settled_local_date: settlement.settled_local_date,
559
+ credit_note: settlement.credit_note ?? entry.credit_note ?? null,
560
+ };
561
+ ledgerPatched = true;
562
+ }
563
+ const pruned = pruneSections(sections);
564
+ const changed = serializeSections(pruned) !== serializeSections(toMutableSections(existing.credit_bills));
565
+ return {
566
+ ...existing,
567
+ credit_bills: pruned,
568
+ iteration: (existing.iteration ?? 1) + (changed || ledgerPatched ? 1 : 0),
569
+ source_watermark: sourceWatermark,
570
+ computed_at: computedAt,
571
+ updatedAt: computedAt,
572
+ };
573
+ }
574
+ /** Month-capped period refs of a local date (week, ISO week-of-year, month). */
575
+ const creditPeriodRefs = (localDate) => {
576
+ const fields = getMaterializedPeriodScopeFields(localDate);
577
+ if (fields == null)
578
+ return null;
579
+ return [
580
+ {
581
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
582
+ scope_field: fields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK],
583
+ },
584
+ {
585
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
586
+ scope_field: fields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR],
587
+ },
588
+ {
589
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
590
+ scope_field: fields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH],
591
+ },
592
+ ];
593
+ };
594
+ /** `Writes the watermarks / schema / key-filter grammar allow a write?` (mirrors the sales-report guard). */
595
+ export const needsMaterializedCreditBillsReportWrite = (existing, incoming) => {
596
+ if (existing == null)
597
+ return true;
598
+ if (existing.schema_version !== incoming.schema_version)
599
+ return true;
600
+ if (JSON.stringify(existing.sale_type_key_filters ?? []) !== JSON.stringify(incoming.sale_type_key_filters ?? [])) {
601
+ return true;
602
+ }
603
+ return new Date(incoming.source_watermark).getTime() > new Date(existing.source_watermark).getTime();
604
+ };
605
+ /**
606
+ * The day-close fetch plan: every scope document one compiled day may touch —
607
+ * date + 3 period scopes + all 24 hour buckets (28 refs). Returns `null` for
608
+ * a malformed local date.
609
+ */
610
+ export function getMaterializedCreditBillScopeRefsForDay(localDate) {
611
+ const periodRefs = creditPeriodRefs(localDate);
612
+ if (periodRefs == null)
613
+ return null;
614
+ const refs = [
615
+ { scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, scope_field: localDate },
616
+ ...periodRefs,
617
+ ];
618
+ for (let hour = 0; hour < 24; hour += 1) {
619
+ const scopeField = getMaterializedHourScopeField(localDate, hour);
620
+ if (scopeField == null)
621
+ return null;
622
+ refs.push({ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: scopeField });
623
+ }
624
+ return refs;
625
+ }
626
+ /**
627
+ * Issue-scope refs of a bill — the documents a SETTLEMENT patch must target:
628
+ * date + 3 period scopes, plus the punch-hour document when the hour is known.
629
+ * Returns `null` for a malformed date (the hour label is used as provided).
630
+ */
631
+ export function getMaterializedCreditBillScopeRefsForIssue(issuedLocalDate, issuedLocalHour) {
632
+ const periodRefs = creditPeriodRefs(issuedLocalDate);
633
+ if (periodRefs == null)
634
+ return null;
635
+ const refs = [
636
+ { scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE, scope_field: issuedLocalDate },
637
+ ...periodRefs,
638
+ ];
639
+ if (issuedLocalHour != null) {
640
+ refs.push({ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: issuedLocalHour });
641
+ }
642
+ return refs;
643
+ }
644
+ /**
645
+ * Derives the range-pure credit counters from the ledger DOCUMENTS the read
646
+ * fetched (a non-overlapping covering set — each bill/receipt appears exactly
647
+ * once):
648
+ * - `received` — Σ `received_delta` of IN-SELECTION receipt entries; `count`
649
+ * is the entry count itself — every collection event counts once (audit
650
+ * R5-2: aligned with the report documents' `received.count` and the
651
+ * RECEIVED drill-down list);
652
+ * - `settled` / `outstanding` (as of the selection END) — RANGE-PURE, unlike
653
+ * the report documents' ever-settled (NOW) counters (audit R5-4): for bills
654
+ * ISSUED in the selection, settled iff the patched `settled_local_date` ≤ end
655
+ * (or the in-selection deltas cover the amount); `outstanding_amount` uses
656
+ * the in-selection deltas that fall ≤ end;
657
+ * - `outstanding_now` — `amount − max(received_amount, at-issue + Σ deltas)`
658
+ * (the stored cumulative is the NOW state);
659
+ * - `collected_at_issue_*` — Σ `received_at_issue` of issued-in-selection bills.
660
+ *
661
+ * Events collected AFTER the selection end are invisible here by design:
662
+ * as-of-end math never needs them (the patched cumulative on the issued entry
663
+ * still carries the NOW state for `outstanding_now`).
664
+ */
665
+ /**
666
+ * Last covered DAY of an inclusive end boundary — the anchor for every
667
+ * as-of-end comparison (settled/outstanding math and the ≤-end delta sum).
668
+ * Day/hour labels pass through (their date part); coarser period labels are
669
+ * expanded: `'2026-10'` → `'2026-10-31'`, `'2026'` → `'2026-12-31'`,
670
+ * `'2026-Q3'` → `'2026-09-30'`, `'2026-S2'` → `'2026-12-31'`. A raw
671
+ * month/quarter scope-field string MUST never reach a comparison — it is
672
+ * lexicographically greater than every day string inside it (audit R5-1).
673
+ */
674
+ const resolveEndDayLabel = (endLabel) => {
675
+ if (endLabel.length >= 10)
676
+ return endLabel.slice(0, 10); // day or hour label
677
+ const monthMatch = /^(\d{4})-(\d{2})$/.exec(endLabel);
678
+ if (monthMatch != null) {
679
+ const lastDay = new Date(Date.UTC(Number(monthMatch[1]), Number(monthMatch[2]), 0)).getUTCDate();
680
+ return `${monthMatch[1]}-${monthMatch[2]}-${`${lastDay}`.padStart(2, '0')}`;
681
+ }
682
+ const quarterMatch = /^(\d{4})-Q([1-4])$/.exec(endLabel);
683
+ if (quarterMatch != null) {
684
+ const month = Number(quarterMatch[2]) * 3;
685
+ const lastDay = new Date(Date.UTC(Number(quarterMatch[1]), month, 0)).getUTCDate();
686
+ return `${quarterMatch[1]}-${`${month}`.padStart(2, '0')}-${`${lastDay}`.padStart(2, '0')}`;
687
+ }
688
+ const semesterMatch = /^(\d{4})-S([12])$/.exec(endLabel);
689
+ if (semesterMatch != null) {
690
+ const month = Number(semesterMatch[2]) * 6;
691
+ const lastDay = new Date(Date.UTC(Number(semesterMatch[1]), month, 0)).getUTCDate();
692
+ return `${semesterMatch[1]}-${`${month}`.padStart(2, '0')}-${`${lastDay}`.padStart(2, '0')}`;
693
+ }
694
+ const yearMatch = /^(\d{4})$/.exec(endLabel);
695
+ if (yearMatch != null)
696
+ return `${yearMatch[1]}-12-31`;
697
+ return endLabel; // week-of-year labels are not an end boundary — caller contract
698
+ };
699
+ /** Entries of the selection, bucketed by sale-type key. */
700
+ const collectCreditEntriesByKey = (reports, labels) => {
701
+ const byKey = new Map();
702
+ for (const report of reports ?? []) {
703
+ if (report == null)
704
+ continue;
705
+ if (!labels.has(report.scope_field))
706
+ continue;
707
+ for (const [key, section] of sectionsOf(report)) {
708
+ let bucket = byKey.get(key);
709
+ if (bucket == null) {
710
+ bucket = { issued: [], received: [] };
711
+ byKey.set(key, bucket);
712
+ }
713
+ for (const entry of section?.issued ?? [])
714
+ bucket.issued.push(entry);
715
+ for (const entry of section?.received ?? [])
716
+ bucket.received.push(entry);
717
+ }
718
+ }
719
+ return byKey;
720
+ };
721
+ const creditTotalsBoundaries = (selection) => {
722
+ const endDayLabel = resolveEndDayLabel(selection.end_label);
723
+ return {
724
+ granularity: selection.granularity,
725
+ endDayLabel,
726
+ endEventLabel: selection.granularity === 'hour'
727
+ ? selection.end_label.length > 10
728
+ ? selection.end_label
729
+ : `${endDayLabel} 23`
730
+ : endDayLabel,
731
+ };
732
+ };
733
+ /** The shared math — one entry bucket in, one totals object out. */
734
+ const totalsFromCreditEntries = (issuedEntries, receivedEntries, boundaries) => {
735
+ const { granularity, endDayLabel, endEventLabel } = boundaries;
736
+ let issuedCount = 0;
737
+ let issuedAmount = 0;
738
+ let settledCount = 0;
739
+ let settledAmount = 0;
740
+ let outstandingCount = 0;
741
+ let outstandingAmount = 0;
742
+ let outstandingNowCount = 0;
743
+ let outstandingNowAmount = 0;
744
+ let collectedAtIssueCount = 0;
745
+ let collectedAtIssueAmount = 0;
746
+ let receivedCount = 0;
747
+ let receivedAmount = 0;
748
+ const deltasByBill = new Map();
749
+ const entryEventLabel = (entry) => granularity === 'hour' ? (entry.event_local_hour ?? `${entry.event_local_date} 23`) : entry.event_local_date;
750
+ for (const entry of receivedEntries) {
751
+ const billKey = creditBillIdentityKey(entry.order_id, entry.payment_id);
752
+ const label = entryEventLabel(entry);
753
+ if (label <= endEventLabel) {
754
+ deltasByBill.set(billKey, (deltasByBill.get(billKey) ?? 0) + (entry.received_delta ?? 0));
755
+ }
756
+ // Event semantics: one receipt entry = one count (a two-installment bill
757
+ // counts twice) — aligned with the report counters and the drill-down.
758
+ receivedCount += 1;
759
+ receivedAmount += entry.received_delta ?? 0;
760
+ }
761
+ for (const entry of issuedEntries) {
762
+ const billKey = creditBillIdentityKey(entry.order_id, entry.payment_id);
763
+ issuedCount += 1;
764
+ issuedAmount += entry.amount ?? 0;
765
+ const atIssue = entry.received_at_issue ?? 0;
766
+ if (atIssue > 0) {
767
+ collectedAtIssueCount += 1;
768
+ collectedAtIssueAmount += atIssue;
769
+ }
770
+ const settledAtEnd = entry.settled_local_date != null && entry.settled_local_date <= endDayLabel;
771
+ if (settledAtEnd) {
772
+ settledCount += 1;
773
+ settledAmount += entry.amount ?? 0;
774
+ }
775
+ else {
776
+ outstandingCount += 1;
777
+ outstandingAmount += Math.max(0, (entry.amount ?? 0) - atIssue - (deltasByBill.get(billKey) ?? 0));
778
+ }
779
+ const receivedNow = Math.max(entry.received_amount ?? 0, atIssue + (deltasByBill.get(billKey) ?? 0));
780
+ if (receivedNow < (entry.amount ?? 0)) {
781
+ outstandingNowCount += 1;
782
+ outstandingNowAmount += Math.max(0, (entry.amount ?? 0) - receivedNow);
783
+ }
784
+ }
785
+ return {
786
+ issued: {
787
+ count: issuedCount,
788
+ amount: issuedAmount,
789
+ settled_count: settledCount,
790
+ settled_amount: settledAmount,
791
+ outstanding_count: outstandingCount,
792
+ outstanding_amount: outstandingAmount,
793
+ outstanding_now_count: outstandingNowCount,
794
+ outstanding_now_amount: outstandingNowAmount,
795
+ },
796
+ received: { count: receivedCount, amount: receivedAmount },
797
+ collected_at_issue_count: collectedAtIssueCount,
798
+ collected_at_issue_amount: collectedAtIssueAmount,
799
+ };
800
+ };
801
+ export function computeMaterializedCreditBillTotalsFromReports(reports, selection) {
802
+ const boundaries = creditTotalsBoundaries(selection);
803
+ const issuedEntries = [];
804
+ const receivedEntries = [];
805
+ for (const bucket of collectCreditEntriesByKey(reports, selection.labels).values()) {
806
+ issuedEntries.push(...bucket.issued);
807
+ receivedEntries.push(...bucket.received);
808
+ }
809
+ return totalsFromCreditEntries(issuedEntries, receivedEntries, boundaries);
810
+ }
811
+ /**
812
+ * Per-key variant of `computeMaterializedCreditBillTotalsFromReports` — the
813
+ * SAME spec and math, one totals object per sale-type key (ordered by key).
814
+ * Used by the ops aggregation to splice the range-pure extras
815
+ * (`settled*` / `outstanding*` / `collected_at_issue*`) per key; summing the
816
+ * per-key values across keys equals the aggregate result.
817
+ */
818
+ export function computeMaterializedCreditBillTotalsFromReportsByKey(reports, selection) {
819
+ const boundaries = creditTotalsBoundaries(selection);
820
+ const totals = {};
821
+ const sortedKeys = [...collectCreditEntriesByKey(reports, selection.labels).entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
822
+ for (const [key, bucket] of sortedKeys) {
823
+ totals[key] = totalsFromCreditEntries(bucket.issued, bucket.received, boundaries);
824
+ }
825
+ return totals;
826
+ }
827
+ /* ------------------------------------------------------------------------ */
828
+ /* Read mapping (decoded overview groups → credit fetch + selection) */
829
+ /* ------------------------------------------------------------------------ */
830
+ const padTwo = (value) => `${value}`.padStart(2, '0');
831
+ const dayKeyOfUtcDate = (date) => `${date.getUTCFullYear()}-${padTwo(date.getUTCMonth() + 1)}-${padTwo(date.getUTCDate())}`;
832
+ const monthLabelsOf = (year, startMonth, count) => Array.from({ length: count }, (_, index) => `${year}-${padTwo(startMonth + index)}`);
833
+ /**
834
+ * Last covered DAY of one scope label — context-aware, because week labels
835
+ * are NOT end boundaries for `resolveEndDayLabel` (it passes them through):
836
+ * a Sunday-based week ends at start + 6; an ISO week ends on its Sunday.
837
+ * Everything else defers to `resolveEndDayLabel` (day/hour pass through,
838
+ * month/quarter/semester/year expand) AFTER a format check.
839
+ */
840
+ const endDayOfLabel = (scopeContext, label) => {
841
+ switch (scopeContext) {
842
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
843
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(label))
844
+ return null;
845
+ const [year, month, day] = label.split('-').map(Number);
846
+ return dayKeyOfUtcDate(new Date(Date.UTC(year, month - 1, day + 6)));
847
+ }
848
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
849
+ const match = /^(\d{4})-W(\d{2})$/.exec(label);
850
+ if (match == null)
851
+ return null;
852
+ const week = Number(match[2]);
853
+ if (week < 1 || week > 53)
854
+ return null;
855
+ // ISO: week 1 always contains Jan 4; its Monday = Jan 4 − (isoDow−1).
856
+ const jan4 = new Date(Date.UTC(Number(match[1]), 0, 4));
857
+ const mondayOfWeek1 = Date.UTC(Number(match[1]), 0, 4 - ((jan4.getUTCDay() + 6) % 7));
858
+ return dayKeyOfUtcDate(new Date(mondayOfWeek1 + ((week - 1) * 7 + 6) * 86400000));
859
+ }
860
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH:
861
+ return /^\d{4}-\d{2}$/.test(label) ? resolveEndDayLabel(label) : null;
862
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER:
863
+ return /^\d{4}-Q[1-4]$/.test(label) ? resolveEndDayLabel(label) : null;
864
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER:
865
+ return /^\d{4}-S[12]$/.test(label) ? resolveEndDayLabel(label) : null;
866
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR:
867
+ return /^\d{4}$/.test(label) ? resolveEndDayLabel(label) : null;
868
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR:
869
+ return /^\d{4}-\d{2}-\d{2} \d{2}$/.test(label) ? label.slice(0, 10) : null;
870
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE:
871
+ return /^\d{4}-\d{2}-\d{2}$/.test(label) ? label : null;
872
+ default:
873
+ return null;
874
+ }
875
+ };
876
+ /**
877
+ * Credit-side values of one read label: quarter / semester / year expand to
878
+ * their constituent MONTH labels (the credit ledger is month-capped — no
879
+ * coarser documents exist); every other context mirrors 1:1.
880
+ */
881
+ const creditValuesOfLabel = (scopeContext, label) => {
882
+ switch (scopeContext) {
883
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER: {
884
+ const match = /^(\d{4})-Q([1-4])$/.exec(label);
885
+ if (match == null)
886
+ return null;
887
+ return {
888
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
889
+ scope_field: monthLabelsOf(Number(match[1]), (Number(match[2]) - 1) * 3 + 1, 3),
890
+ };
891
+ }
892
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER: {
893
+ const match = /^(\d{4})-S([12])$/.exec(label);
894
+ if (match == null)
895
+ return null;
896
+ return {
897
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
898
+ scope_field: monthLabelsOf(Number(match[1]), (Number(match[2]) - 1) * 6 + 1, 6),
899
+ };
900
+ }
901
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR: {
902
+ const match = /^(\d{4})$/.exec(label);
903
+ if (match == null)
904
+ return null;
905
+ return {
906
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
907
+ scope_field: monthLabelsOf(Number(match[1]), 1, 12),
908
+ };
909
+ }
910
+ default:
911
+ return { scope_context: scopeContext, scope_field: [label] };
912
+ }
913
+ };
914
+ /**
915
+ * Maps ONE read's decoded overview scope groups onto the credit-side read:
916
+ * the fetch groups for `materialized_tenant_credit_bills` (quarter/semester/
917
+ * year → their months; month-capped mirror), the exact fetched-`scope_field`
918
+ * label set, and the `IMaterializedCreditBillSelection` for the range-pure
919
+ * counters — `granularity` `hour` iff the read carries `localHour` labels,
920
+ * `end_label` the LAST covered hour (hour reads) or DAY (day reads), where a
921
+ * Sunday-based week ends at start + 6 and an ISO week on its Sunday.
922
+ *
923
+ * Returns `null` for malformed input — callers fall back to the pipeline's
924
+ * NOW-basis counters instead of splicing partial math.
925
+ */
926
+ export function buildMaterializedCreditBillSelectionFromScopeGroups(groups) {
927
+ if (!Array.isArray(groups) || groups.length === 0)
928
+ return null;
929
+ const buckets = new Map();
930
+ const labels = new Set();
931
+ let endDay = null;
932
+ let maxHourLabel = null;
933
+ let hasHour = false;
934
+ for (const group of groups) {
935
+ if (group == null || !Array.isArray(group.scope_field) || group.scope_field.length === 0)
936
+ return null;
937
+ const scopeContext = group.scope_context ?? MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE;
938
+ if (!ALL_MATERIALIZED_REPORT_SCOPES.includes(scopeContext))
939
+ return null;
940
+ for (const field of group.scope_field) {
941
+ if (typeof field !== 'string' || field.trim() === '')
942
+ return null;
943
+ const label = field.trim();
944
+ const labelEndDay = endDayOfLabel(scopeContext, label);
945
+ if (labelEndDay == null)
946
+ return null;
947
+ if (endDay == null || labelEndDay > endDay)
948
+ endDay = labelEndDay;
949
+ const mapped = creditValuesOfLabel(scopeContext, label);
950
+ if (mapped == null)
951
+ return null;
952
+ let bucket = buckets.get(mapped.scope_context);
953
+ if (bucket == null) {
954
+ bucket = new Set();
955
+ buckets.set(mapped.scope_context, bucket);
956
+ }
957
+ for (const value of mapped.scope_field) {
958
+ bucket.add(value);
959
+ labels.add(value);
960
+ }
961
+ if (scopeContext === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
962
+ hasHour = true;
963
+ if (maxHourLabel == null || label > maxHourLabel)
964
+ maxHourLabel = label;
965
+ }
966
+ }
967
+ }
968
+ if (endDay == null)
969
+ return null;
970
+ const credit_groups = [...buckets.entries()]
971
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
972
+ .map(([scope_context, values]) => ({ scope_context, scope_field: [...values].sort() }));
973
+ const selection = {
974
+ granularity: hasHour ? 'hour' : 'day',
975
+ labels,
976
+ // Hour reads anchor on the LAST covered hour; when hours do not reach the
977
+ // selection's last day the day boundary is passed instead and the toolkit
978
+ // derives the `${day} 23` hour cutoff itself.
979
+ end_label: hasHour && maxHourLabel != null && maxHourLabel.slice(0, 10) === endDay ? maxHourLabel : endDay,
980
+ };
981
+ return { credit_groups, labels, selection };
982
+ }