@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,307 @@
1
+ import { MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM, MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { IOrder, IOrderPayment } from '../../schemas';
3
+ import { IMaterializedCreditBillIssuedEntry, IMaterializedCreditBillReceivedEntry, IMaterializedTenantCreditBillsReport } from '../../schemas/types/materialized_credit_bills';
4
+ import { IGetMaterializedReportScopeGroup } from '../types/materialized-reports-apis';
5
+ /**
6
+ * The shared credit-bill ledger (`materialized_tenant_credit_bills`) —
7
+ * builders, resolution and math (see `MATERIALIZED_REPORTS.md`).
8
+ *
9
+ * The ledger is materialized EXACTLY like every other report collection (one
10
+ * document per tenant × scope context × scope value), but capped at
11
+ * `LOCAL_MONTH` (`MATERIALIZED_CREDIT_BILLS_SCOPES`) so no document grows
12
+ * unboundedly. Each document carries a per-key map of slim `issued[]` /
13
+ * `received[]` entries — ids + credit facts; the order document stays the
14
+ * single source of the sale.
15
+ *
16
+ * This module owns the whole credit pipeline:
17
+ * - `buildCreditBillIssuedCandidatesFromOrder` / `buildCreditBillEventCandidatesFromOrder`
18
+ * — order-pure candidates (the compile emits them, resolution happens at
19
+ * close-plan time);
20
+ * - `resolveCreditBillDay` — the ONLY stateful step: resolves receipt deltas
21
+ * against the stored documents (idempotent re-closes), carries issue anchors
22
+ * forward and emits the settlements the close must patch (exactly once);
23
+ * - `buildMaterializedCreditBillDayReports` — materializes one day's scope
24
+ * documents (hour/date/week/weekOfYear/month) from the resolution;
25
+ * - `updateMaterializedCreditBillsReport` — replacement / subtract / add /
26
+ * settlement-patch document updates (mirrors the sales report updater);
27
+ * - `computeMaterializedCreditBillTotalsFromReports` — the read-side counter
28
+ * spec (the ops aggregation mirrors this).
29
+ *
30
+ * Amounts are cents. `IOrderPayment` values are read, never mutated.
31
+ */
32
+ /** Whether a payment row represents a credit bill (`PAY_LATER`). */
33
+ export declare const isMaterializedCreditBillPayment: (payment: IOrderPayment) => boolean;
34
+ /** Punch hour of an issued bill — mirrors the report documents' sales anchor. */
35
+ export declare const resolveOrderLocalHour: (order: IOrder, localDate: string, gmtOffset?: number) => number | null;
36
+ /**
37
+ * Hour bucket of a credit-bill COLLECTION event: the SETTLEMENT anchor
38
+ * resolves the hour — never the punch hour. Chain: `gmtOffset` +
39
+ * `order_settled_at` (tenant-local hour) → `order_settled_at_mins ÷ 60` →
40
+ * the settlement timestamp's UTC hour → punch-hour fallback (last resort).
41
+ */
42
+ export declare const resolveReceivedLocalHour: (order: IOrder, localDate: string, gmtOffset?: number) => number | null;
43
+ /** `'YYYY-MM-DD HH'` hour label of a resolved hour (null when unknown). */
44
+ export declare const toMaterializedHourLabel: (localDate: string, hour: number | null) => string | null;
45
+ export interface IBuildCreditBillCandidatesOptions {
46
+ /** Compile timestamp (deterministic per run — never `Date.now()`). */
47
+ now: Date;
48
+ /** Tenant-local offset; required for the settlement-day comparison (N2). */
49
+ gmtOffset?: number;
50
+ }
51
+ /** ISSUE candidate — an issued entry plus its sale-type key parts and watermark. */
52
+ export interface ICreditBillIssuedCandidate extends IMaterializedCreditBillIssuedEntry {
53
+ order_status: string;
54
+ platform: string;
55
+ source_watermark: Date;
56
+ }
57
+ /**
58
+ * ISSUE candidates of one order (its business day is the compiled day): one
59
+ * per `PAY_LATER` payment. Un-keyable payments (no `payment_id` / `_id`) →
60
+ * `null` (the identity must never collapse).
61
+ *
62
+ * N2 backfill rule: a bill settled NOW whose settlement local day is AFTER
63
+ * this compiled business day (a from-`orders` backfill) is emitted
64
+ * UNPAID-at-issue (`received_at_issue 0`, unsettled, `received_amount 0`) —
65
+ * exactly the state the live close saw; the collection day then carries the
66
+ * receipt delta. Without `gmtOffset` the comparison is skipped (live closes
67
+ * never need it — the order is not settled yet at the day's close).
68
+ */
69
+ export declare function buildCreditBillIssuedCandidatesFromOrder(order: IOrder, orderLocalDate: string, options: IBuildCreditBillCandidatesOptions): ICreditBillIssuedCandidate[] | null;
70
+ /**
71
+ * RECEIPT-EVENT candidate of one collected order (its business day is BEFORE
72
+ * the compiled day): one candidate per `PAY_LATER` payment that actually
73
+ * received money (a settled payment with nothing paid is a data anomaly, not
74
+ * a collection event). The event's `received_delta` starts at 0 — the
75
+ * resolution resolves it against the stored documents (order-pure compile:
76
+ * identical inputs reproduce identical candidates).
77
+ */
78
+ export interface ICreditBillEventCandidate {
79
+ order_id: string;
80
+ payment_id: string;
81
+ order_status: string;
82
+ platform: string;
83
+ amount: number;
84
+ issued_at: Date;
85
+ issued_local_date: string;
86
+ issued_local_hour: string | null;
87
+ /** Cumulative (order view) as of this compile. */
88
+ candidate_cumulative: number;
89
+ /** Event shell — `received_delta` 0 (resolved at close-plan time). */
90
+ event: {
91
+ event_local_date: string;
92
+ event_local_hour: string | null;
93
+ received_delta: number;
94
+ event_type: MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM;
95
+ credit_note?: string | null;
96
+ settled_at?: Date | null;
97
+ };
98
+ source_watermark: Date;
99
+ }
100
+ export declare function buildCreditBillEventCandidatesFromOrder(order: IOrder, eventLocalDate: string, options: IBuildCreditBillCandidatesOptions): ICreditBillEventCandidate[] | null;
101
+ /** Resolved ISSUE — today's issued entry with stored anchors carried forward. */
102
+ export interface IResolvedCreditBillIssued {
103
+ key: string;
104
+ entry: IMaterializedCreditBillIssuedEntry;
105
+ source_watermark: Date;
106
+ }
107
+ /** Resolved RECEIPT — today's collection event with its delta resolved. */
108
+ export interface IResolvedCreditBillEvent {
109
+ key: string;
110
+ entry: IMaterializedCreditBillReceivedEntry;
111
+ received_at: Date | null;
112
+ credit_note: string | null;
113
+ settled: boolean;
114
+ settled_at: Date | null;
115
+ settled_local_date: string;
116
+ source_watermark: Date;
117
+ }
118
+ /** A bill that fully settled on the compiled day — the close must patch its issue scopes. */
119
+ export interface IResolvedCreditBillSettlement {
120
+ key: string;
121
+ order_id: string;
122
+ payment_id: string;
123
+ amount: number;
124
+ /** Cumulative after this collection (the patched `received_amount`). */
125
+ received_amount: number;
126
+ settled_at: Date;
127
+ settled_local_date: string;
128
+ credit_note: string | null;
129
+ issued_local_date: string;
130
+ /** Punch-hour label of the issue day (null when unknown) — patch target ref. */
131
+ issued_local_hour: string | null;
132
+ }
133
+ export interface ICreditBillDayResolution {
134
+ issued: IResolvedCreditBillIssued[];
135
+ received_events: IResolvedCreditBillEvent[];
136
+ /**
137
+ * Bills settled on the compiled day whose ISSUE day is EARLIER — only
138
+ * these need issue-scope patches (same-day settlements are part of the
139
+ * issued payload itself).
140
+ */
141
+ settled_bills: IResolvedCreditBillSettlement[];
142
+ }
143
+ export interface IResolveCreditBillDayInput {
144
+ tenantId: string;
145
+ /** The compiled business day (tenant-local `'YYYY-MM-DD'`). */
146
+ localDate: string;
147
+ issued: ICreditBillIssuedCandidate[] | null | undefined;
148
+ events: ICreditBillEventCandidate[] | null | undefined;
149
+ /** Stored documents the close fetched (day scopes + issue scopes of `events`). */
150
+ stored: IMaterializedTenantCreditBillsReport[] | null | undefined;
151
+ computedAt: Date;
152
+ }
153
+ /**
154
+ * Resolves one compiled day against the stored ledger documents — NEVER
155
+ * throws (`null` on inconsistent input):
156
+ * - EVENT deltas: a stored receipt entry for the same `(bill, event day)`
157
+ * keeps its own delta and cumulative (idempotent re-closes); a first-seen
158
+ * event's delta resolves as `candidate_cumulative − stored issued
159
+ * received_amount` (the stored cumulative is the pre-event total; 0 when the
160
+ * bill was never materialized), clamped ≥ 0;
161
+ * - ISSUE anchors: `received_at_issue` / settlement fields carry forward from
162
+ * the stored issued entry — a re-close after collection never re-anchors
163
+ * them;
164
+ * - SETTLEMENTS: a resolved event whose cumulative now covers the amount
165
+ * emits a settlement (patched onto the issue scopes) exactly once — only
166
+ * for issue days EARLIER than the compiled day and only when the stored
167
+ * entry is not settled yet.
168
+ */
169
+ export declare function resolveCreditBillDay(input: IResolveCreditBillDayInput | null | undefined): ICreditBillDayResolution | null;
170
+ export interface IBuildMaterializedCreditBillDayReportsInput {
171
+ tenantId: string;
172
+ brandId: string;
173
+ /** The compiled business day (tenant-local `'YYYY-MM-DD'`). */
174
+ localDate: string;
175
+ resolution: ICreditBillDayResolution;
176
+ computedAt: Date;
177
+ }
178
+ /**
179
+ * Materializes ONE day's credit documents from its resolution — the
180
+ * month-capped scope set (`MATERIALIZED_CREDIT_BILLS_SCOPES`): one document per
181
+ * active hour, plus date, week, ISO week-of-year and month. Returns `[]` when
182
+ * the day has no credit activity; `null` on malformed input (never throws).
183
+ */
184
+ export declare function buildMaterializedCreditBillDayReports(input: IBuildMaterializedCreditBillDayReportsInput | null | undefined): IMaterializedTenantCreditBillsReport[] | null;
185
+ export interface IUpdateMaterializedCreditBillsReportInput {
186
+ /** Day/hour write: swap the payload wholesale. */
187
+ replacement?: IMaterializedTenantCreditBillsReport;
188
+ /** Period writes: remove the stored day's entries first. */
189
+ subtract?: IMaterializedTenantCreditBillsReport[];
190
+ /** Period writes: then fold the recompiled day's entries in. */
191
+ additions?: IMaterializedTenantCreditBillsReport[];
192
+ /** Settlement patches: update issue-scope `issued[]` entries exactly once. */
193
+ settled_bills?: IResolvedCreditBillSettlement[];
194
+ }
195
+ /**
196
+ * Applies one write to a stored credit document — NEVER throws (`null` on
197
+ * inconsistent input). Mirrors `updateMaterializedTenantSalesOverviewReport`:
198
+ * replacement swaps the payload; `subtract` removes the identity-matched
199
+ * entries a re-close must drop; `additions` folds the recompiled day's entries
200
+ * back in; `settled_bills` patches issue-scope `issued[]` entries (received
201
+ * cumulative + settlement anchors + note) exactly once. Versioned writes: the
202
+ * iteration bumps when the payload or the ledger state actually changed.
203
+ */
204
+ export declare function updateMaterializedCreditBillsReport(existing: IMaterializedTenantCreditBillsReport | null | undefined, updates: IUpdateMaterializedCreditBillsReportInput | null | undefined, options?: {
205
+ computedAt?: Date;
206
+ }): IMaterializedTenantCreditBillsReport | null;
207
+ export interface IMaterializedCreditBillScopeRef {
208
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
209
+ scope_field: string;
210
+ }
211
+ /** `Writes the watermarks / schema / key-filter grammar allow a write?` (mirrors the sales-report guard). */
212
+ export declare const needsMaterializedCreditBillsReportWrite: (existing: IMaterializedTenantCreditBillsReport | null | undefined, incoming: IMaterializedTenantCreditBillsReport) => boolean;
213
+ /**
214
+ * The day-close fetch plan: every scope document one compiled day may touch —
215
+ * date + 3 period scopes + all 24 hour buckets (28 refs). Returns `null` for
216
+ * a malformed local date.
217
+ */
218
+ export declare function getMaterializedCreditBillScopeRefsForDay(localDate: string): IMaterializedCreditBillScopeRef[] | null;
219
+ /**
220
+ * Issue-scope refs of a bill — the documents a SETTLEMENT patch must target:
221
+ * date + 3 period scopes, plus the punch-hour document when the hour is known.
222
+ * Returns `null` for a malformed date (the hour label is used as provided).
223
+ */
224
+ export declare function getMaterializedCreditBillScopeRefsForIssue(issuedLocalDate: string, issuedLocalHour: string | null): IMaterializedCreditBillScopeRef[] | null;
225
+ /** Selection view of one read — exact tenant-local labels (day or hour granularity). */
226
+ export interface IMaterializedCreditBillSelection {
227
+ /** `day` compares `'YYYY-MM-DD'`; `hour` compares `'YYYY-MM-DD HH'` labels. */
228
+ granularity: 'day' | 'hour';
229
+ /** Exact labels the selection covers (document `scope_field` values). */
230
+ labels: Set<string>;
231
+ /**
232
+ * Inclusive as-of-end boundary. For `day` reads: the last covered DAY
233
+ * (`'YYYY-MM-DD'` — a whole-month read passes `'2026-10-31'`). For `hour`
234
+ * reads: the last covered hour label (`'YYYY-MM-DD HH'`). Coarser period
235
+ * labels are expanded defensively (`'2026-10'` → `'2026-10-31'`,
236
+ * `'2026-Q3'` → `'2026-09-30'`, …) because a raw month/quarter string is
237
+ * lexicographically GREATER than every day string inside it — comparing it
238
+ * directly would zero the as-of-end counters (audit R5-1).
239
+ */
240
+ end_label: string;
241
+ }
242
+ /** Range-pure credit-bill counters (single source for reads). */
243
+ export interface IMaterializedCreditBillTotals {
244
+ issued: {
245
+ count: number;
246
+ amount: number;
247
+ settled_count: number;
248
+ settled_amount: number;
249
+ outstanding_count: number;
250
+ outstanding_amount: number;
251
+ outstanding_now_count: number;
252
+ outstanding_now_amount: number;
253
+ };
254
+ received: {
255
+ /**
256
+ * IN-SELECTION receipt entries — every collection event counts once (a
257
+ * bill collected in two installments counts twice). Identical semantics
258
+ * to the report documents' `received.count` and to the RECEIVED
259
+ * drill-down list (audit R5-2).
260
+ */
261
+ count: number;
262
+ amount: number;
263
+ };
264
+ /** Money in hand AT ISSUE (Σ `received_at_issue`): same-day settled + prepaid. */
265
+ collected_at_issue_count: number;
266
+ collected_at_issue_amount: number;
267
+ }
268
+ export declare function computeMaterializedCreditBillTotalsFromReports(reports: IMaterializedTenantCreditBillsReport[] | null | undefined, selection: IMaterializedCreditBillSelection): IMaterializedCreditBillTotals;
269
+ /**
270
+ * Per-key variant of `computeMaterializedCreditBillTotalsFromReports` — the
271
+ * SAME spec and math, one totals object per sale-type key (ordered by key).
272
+ * Used by the ops aggregation to splice the range-pure extras
273
+ * (`settled*` / `outstanding*` / `collected_at_issue*`) per key; summing the
274
+ * per-key values across keys equals the aggregate result.
275
+ */
276
+ export declare function computeMaterializedCreditBillTotalsFromReportsByKey(reports: IMaterializedTenantCreditBillsReport[] | null | undefined, selection: IMaterializedCreditBillSelection): Record<string, IMaterializedCreditBillTotals>;
277
+ /** One read's credit-side plan: fetch groups + range-pure selection. */
278
+ export interface IMaterializedCreditBillScopeSelection {
279
+ /**
280
+ * Fetch groups for `materialized_tenant_credit_bills` — the decoded read
281
+ * groups mirrored onto the credit contexts (`scope_context` present on
282
+ * every group, values deduped + sorted): quarter / semester / year expand
283
+ * to months, every other context keeps its exact values.
284
+ */
285
+ credit_groups: IGetMaterializedReportScopeGroup[];
286
+ /**
287
+ * Exact `scope_field` values of the FETCHED documents — the `labels` set
288
+ * every `computeMaterializedCreditBillTotalsFromReports*` call filters by
289
+ * (the same set is on `selection.labels`, one shared instance).
290
+ */
291
+ labels: Set<string>;
292
+ /** Granularity + inclusive as-of-end boundary for the range-pure math. */
293
+ selection: IMaterializedCreditBillSelection;
294
+ }
295
+ /**
296
+ * Maps ONE read's decoded overview scope groups onto the credit-side read:
297
+ * the fetch groups for `materialized_tenant_credit_bills` (quarter/semester/
298
+ * year → their months; month-capped mirror), the exact fetched-`scope_field`
299
+ * label set, and the `IMaterializedCreditBillSelection` for the range-pure
300
+ * counters — `granularity` `hour` iff the read carries `localHour` labels,
301
+ * `end_label` the LAST covered hour (hour reads) or DAY (day reads), where a
302
+ * Sunday-based week ends at start + 6 and an ISO week on its Sunday.
303
+ *
304
+ * Returns `null` for malformed input — callers fall back to the pipeline's
305
+ * NOW-basis counters instead of splicing partial math.
306
+ */
307
+ export declare function buildMaterializedCreditBillSelectionFromScopeGroups(groups: IGetMaterializedReportScopeGroup[] | null | undefined): IMaterializedCreditBillScopeSelection | null;