@managesome/eposmatic-toolkit 0.4.2 → 0.4.4

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 (20) hide show
  1. package/esm/helpers/materialized-reports/index.js +2 -0
  2. package/esm/helpers/materialized-reports/materialized-reports-read-helpers.js +152 -0
  3. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +379 -0
  4. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +16 -2
  5. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +20 -26
  6. package/lib/helpers/materialized-reports/index.d.ts +2 -0
  7. package/lib/helpers/materialized-reports/index.js +2 -0
  8. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.d.ts +79 -0
  9. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.js +159 -0
  10. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +136 -0
  11. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +382 -0
  12. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +4 -1
  13. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +16 -2
  14. package/lib/helpers/types/materialized-reports-apis.d.ts +3 -3
  15. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +17 -25
  16. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +20 -26
  17. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +11 -0
  18. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.d.ts +1 -0
  19. package/lib/tests/materialized-reports/tenant-sales-overview-formatter.test.js +352 -0
  20. package/package.json +1 -1
@@ -0,0 +1,79 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
3
+ /**
4
+ * Read-side helpers for materialized-report documents — the frontend-facing
5
+ * half of the query story (see `MATERIALIZED_REPORTS.md` "Time scopes").
6
+ *
7
+ * The ops-service read API takes `{ scope_context, scope_field | from/to }`:
8
+ * - contiguous selections go through `from`/`to` directly (callers can use
9
+ * `getMaterializedScopeSpan` / `getMaterializedHourScopeSpan` to derive the
10
+ * span of a set of keys);
11
+ * - discrete selections fetch the min..max SPAN and keep the exact keys with
12
+ * `filterMaterializedTenantSalesOverviewReportsByScopeFields`;
13
+ * - recurring hour windows (e.g. 6–8pm on every day of a range) expand to the
14
+ * exact hour labels with `getMaterializedHourWindowScopeFields` (span-fetch
15
+ * the full days first, then filter to the labels).
16
+ *
17
+ * Validation convention: helpers return `null` instead of throwing — `null`
18
+ * means the caller passed invalid data.
19
+ */
20
+ /**
21
+ * Chronological business-hour index of an hour bucket: a business day's hour
22
+ * sequence is `06…23, 00…05`, so index = `(hour + 18) % 24` (06 → 0 … 05 →
23
+ * 23). NEVER order hour buckets lexicographically — `'D 00'` sorts before
24
+ * `'D 06'` yet happens ~18 hours later.
25
+ *
26
+ * Returns `null` (never throws) for a non-integer / out-of-range hour.
27
+ */
28
+ export declare function getMaterializedBusinessHourIndex(hour: number): number | null;
29
+ /**
30
+ * Expands a RECURRING daily hour window into the exact `localHour` scope
31
+ * labels (`$in`-style reads): the same business hours on every day of the
32
+ * list, e.g. `4pm–8pm` on June 1–2 →
33
+ * `['2026-06-01 16', '2026-06-01 17', '2026-06-01 18', '2026-06-01 19', …]`.
34
+ *
35
+ * Semantics (see `MATERIALIZED_REPORTS.md`): whole-hour buckets, the window
36
+ * END is the exclusive hour boundary — `16 → 20` = buckets `16, 17, 18, 19`;
37
+ * windows may cross midnight WITHIN one business day — `22 → 2` = buckets
38
+ * `22, 23` (evening) plus `00, 01` (post-midnight), all labelled with the SAME
39
+ * business day. Windows must stay inside one business day: a walk crossing the
40
+ * 06:00 business-morning boundary (e.g. `4 → 8`) is rejected (`null`) rather
41
+ * than silently spanning two label days. `0 → 24` requests the full business
42
+ * day (buckets `00`–`23` of the label day).
43
+ *
44
+ * Returns `null` (never throws) for malformed days or hours; the result is
45
+ * ordered by day, then by the window's own hour order.
46
+ */
47
+ export declare function getMaterializedHourWindowScopeFields(businessDays: string[], fromHour: number, toHour: number): string[] | null;
48
+ /**
49
+ * Full-day span of a list of business days for `localHour` reads: the
50
+ * inclusive `{ from: '<first> 00', to: '<last> 23' }` range covers ALL 24
51
+ * hour buckets of every label day in between (a label day's buckets are
52
+ * `'D 00'`…`'D 23'`, spanning the post-midnight hours too). Filter the
53
+ * fetched documents afterwards with `getMaterializedHourWindowScopeFields` /
54
+ * `filterMaterializedTenantSalesOverviewReportsByScopeFields`.
55
+ *
56
+ * Returns `null` (never throws) for a malformed list.
57
+ */
58
+ export declare function getMaterializedHourScopeSpan(businessDays: string[]): {
59
+ from: string;
60
+ to: string;
61
+ } | null;
62
+ /**
63
+ * Inclusive min..max span of exact non-hour scope values — the fetch range
64
+ * for discrete selections (all non-hour scope fields are fixed-width, so
65
+ * lexicographic order equals chronological order). Returns `null` (never
66
+ * throws) for the hour scope (use `getMaterializedHourScopeSpan`) or a
67
+ * malformed list.
68
+ */
69
+ export declare function getMaterializedScopeSpan(scope_context: MATERIALIZED_REPORT_SCOPE_ENUM, scopeFields: string[]): {
70
+ from: string;
71
+ to: string;
72
+ } | null;
73
+ /**
74
+ * Keeps only the documents whose `scope_field` is one of the requested keys —
75
+ * the client-side refinement for discrete selections fetched as a span.
76
+ * Returns `null` (never throws) for malformed input; unknown keys simply match
77
+ * nothing (absence = zero).
78
+ */
79
+ export declare function filterMaterializedTenantSalesOverviewReportsByScopeFields(docs: IMaterializedTenantSalesOverviewReport[], scopeFields: string[]): IMaterializedTenantSalesOverviewReport[] | null;
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMaterializedBusinessHourIndex = getMaterializedBusinessHourIndex;
4
+ exports.getMaterializedHourWindowScopeFields = getMaterializedHourWindowScopeFields;
5
+ exports.getMaterializedHourScopeSpan = getMaterializedHourScopeSpan;
6
+ exports.getMaterializedScopeSpan = getMaterializedScopeSpan;
7
+ exports.filterMaterializedTenantSalesOverviewReportsByScopeFields = filterMaterializedTenantSalesOverviewReportsByScopeFields;
8
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
9
+ const scope_helpers_1 = require("./scope-helpers");
10
+ /**
11
+ * Read-side helpers for materialized-report documents — the frontend-facing
12
+ * half of the query story (see `MATERIALIZED_REPORTS.md` "Time scopes").
13
+ *
14
+ * The ops-service read API takes `{ scope_context, scope_field | from/to }`:
15
+ * - contiguous selections go through `from`/`to` directly (callers can use
16
+ * `getMaterializedScopeSpan` / `getMaterializedHourScopeSpan` to derive the
17
+ * span of a set of keys);
18
+ * - discrete selections fetch the min..max SPAN and keep the exact keys with
19
+ * `filterMaterializedTenantSalesOverviewReportsByScopeFields`;
20
+ * - recurring hour windows (e.g. 6–8pm on every day of a range) expand to the
21
+ * exact hour labels with `getMaterializedHourWindowScopeFields` (span-fetch
22
+ * the full days first, then filter to the labels).
23
+ *
24
+ * Validation convention: helpers return `null` instead of throwing — `null`
25
+ * means the caller passed invalid data.
26
+ */
27
+ /**
28
+ * Chronological business-hour index of an hour bucket: a business day's hour
29
+ * sequence is `06…23, 00…05`, so index = `(hour + 18) % 24` (06 → 0 … 05 →
30
+ * 23). NEVER order hour buckets lexicographically — `'D 00'` sorts before
31
+ * `'D 06'` yet happens ~18 hours later.
32
+ *
33
+ * Returns `null` (never throws) for a non-integer / out-of-range hour.
34
+ */
35
+ function getMaterializedBusinessHourIndex(hour) {
36
+ if (!Number.isInteger(hour) || hour < 0 || hour > 23) {
37
+ return null;
38
+ }
39
+ return (hour + 18) % 24;
40
+ }
41
+ /**
42
+ * Expands a RECURRING daily hour window into the exact `localHour` scope
43
+ * labels (`$in`-style reads): the same business hours on every day of the
44
+ * list, e.g. `4pm–8pm` on June 1–2 →
45
+ * `['2026-06-01 16', '2026-06-01 17', '2026-06-01 18', '2026-06-01 19', …]`.
46
+ *
47
+ * Semantics (see `MATERIALIZED_REPORTS.md`): whole-hour buckets, the window
48
+ * END is the exclusive hour boundary — `16 → 20` = buckets `16, 17, 18, 19`;
49
+ * windows may cross midnight WITHIN one business day — `22 → 2` = buckets
50
+ * `22, 23` (evening) plus `00, 01` (post-midnight), all labelled with the SAME
51
+ * business day. Windows must stay inside one business day: a walk crossing the
52
+ * 06:00 business-morning boundary (e.g. `4 → 8`) is rejected (`null`) rather
53
+ * than silently spanning two label days. `0 → 24` requests the full business
54
+ * day (buckets `00`–`23` of the label day).
55
+ *
56
+ * Returns `null` (never throws) for malformed days or hours; the result is
57
+ * ordered by day, then by the window's own hour order.
58
+ */
59
+ function getMaterializedHourWindowScopeFields(businessDays, fromHour, toHour) {
60
+ if (!Array.isArray(businessDays) || businessDays.length === 0) {
61
+ return null;
62
+ }
63
+ if (!Number.isInteger(fromHour) || fromHour < 0 || fromHour > 23) {
64
+ return null;
65
+ }
66
+ if (!Number.isInteger(toHour) || toHour < 0 || toHour > 24) {
67
+ return null;
68
+ }
69
+ let hourCount;
70
+ if (toHour === 24) {
71
+ if (fromHour !== 0)
72
+ return null;
73
+ hourCount = 24;
74
+ }
75
+ else {
76
+ hourCount = (((toHour - fromHour) % 24) + 24) % 24;
77
+ if (hourCount === 0)
78
+ return null; // ambiguous empty window — caller must be explicit
79
+ }
80
+ // Reject walks crossing the 06:00 business-morning boundary — those span two
81
+ // label days and cannot be expressed with same-day labels.
82
+ if (hourCount < 24) {
83
+ const startPosition = getMaterializedBusinessHourIndex(fromHour);
84
+ if (startPosition == null || startPosition + hourCount > 24) {
85
+ return null;
86
+ }
87
+ }
88
+ const hours = Array.from({ length: hourCount }, (_, index) => (fromHour + index) % 24);
89
+ const labels = [];
90
+ for (const businessDay of businessDays) {
91
+ if ((0, scope_helpers_1.parseMaterializedLocalDate)(businessDay) == null) {
92
+ return null;
93
+ }
94
+ for (const hour of hours) {
95
+ const label = (0, scope_helpers_1.getMaterializedHourScopeField)(businessDay, hour);
96
+ if (label == null)
97
+ return null;
98
+ labels.push(label);
99
+ }
100
+ }
101
+ return labels;
102
+ }
103
+ /**
104
+ * Full-day span of a list of business days for `localHour` reads: the
105
+ * inclusive `{ from: '<first> 00', to: '<last> 23' }` range covers ALL 24
106
+ * hour buckets of every label day in between (a label day's buckets are
107
+ * `'D 00'`…`'D 23'`, spanning the post-midnight hours too). Filter the
108
+ * fetched documents afterwards with `getMaterializedHourWindowScopeFields` /
109
+ * `filterMaterializedTenantSalesOverviewReportsByScopeFields`.
110
+ *
111
+ * Returns `null` (never throws) for a malformed list.
112
+ */
113
+ function getMaterializedHourScopeSpan(businessDays) {
114
+ if (!Array.isArray(businessDays) || businessDays.length === 0) {
115
+ return null;
116
+ }
117
+ for (const businessDay of businessDays) {
118
+ if ((0, scope_helpers_1.parseMaterializedLocalDate)(businessDay) == null) {
119
+ return null;
120
+ }
121
+ }
122
+ const sorted = [...businessDays].sort();
123
+ return { from: `${sorted[0]} 00`, to: `${sorted[sorted.length - 1]} 23` };
124
+ }
125
+ /**
126
+ * Inclusive min..max span of exact non-hour scope values — the fetch range
127
+ * for discrete selections (all non-hour scope fields are fixed-width, so
128
+ * lexicographic order equals chronological order). Returns `null` (never
129
+ * throws) for the hour scope (use `getMaterializedHourScopeSpan`) or a
130
+ * malformed list.
131
+ */
132
+ function getMaterializedScopeSpan(scope_context, scopeFields) {
133
+ if (scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR) {
134
+ return null;
135
+ }
136
+ if (!Array.isArray(scopeFields) || scopeFields.length === 0) {
137
+ return null;
138
+ }
139
+ for (const scopeField of scopeFields) {
140
+ if (typeof scopeField !== 'string' || scopeField.length === 0) {
141
+ return null;
142
+ }
143
+ }
144
+ const sorted = [...scopeFields].sort();
145
+ return { from: sorted[0], to: sorted[sorted.length - 1] };
146
+ }
147
+ /**
148
+ * Keeps only the documents whose `scope_field` is one of the requested keys —
149
+ * the client-side refinement for discrete selections fetched as a span.
150
+ * Returns `null` (never throws) for malformed input; unknown keys simply match
151
+ * nothing (absence = zero).
152
+ */
153
+ function filterMaterializedTenantSalesOverviewReportsByScopeFields(docs, scopeFields) {
154
+ if (!Array.isArray(docs) || !Array.isArray(scopeFields)) {
155
+ return null;
156
+ }
157
+ const wanted = new Set(scopeFields);
158
+ return docs.filter((doc) => doc != null && wanted.has(doc.scope_field));
159
+ }
@@ -0,0 +1,136 @@
1
+ import { DAY_INDEX_ENUM } from '../../constants/ENUMS';
2
+ import { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
3
+ /**
4
+ * Frontend formatter for `materialized_tenant_sales_overview_reports` (see
5
+ * `MATERIALIZED_REPORTS.md` "Frontend consumption").
6
+ *
7
+ * The backend returns raw documents unchanged; this formatter derives all
8
+ * view shaping:
9
+ * - money is converted from CENTS to decimals (`/100`), counts stay integers;
10
+ * - platform / order-status filters are applied to the key map (zero
11
+ * re-fetches — the documents already carry every dimension);
12
+ * - the cancelled facet is split out of the `CANCELLED:*` keys;
13
+ * - payments merge by `payment_type` with the read-time `PAY_LATER → UNPAID`
14
+ * remap, and the dedicated `CREDIT_SETTLEMENT` line is DERIVED from the
15
+ * `CREDIT_BILLS.received` ledger (never from the stored payments);
16
+ * - weekday views group on the denormalized `day_index` field (date/hour
17
+ * scopes only) and hour series are ordered by business-hour index
18
+ * (`06…23, 00…05`) — never lexicographically;
19
+ * - the brand-level combined view sums across tenants (`allowTenantMismatch`
20
+ * on the sum helper; bills stay de-duplicated by `(order_id, payment_id)`).
21
+ *
22
+ * Validation convention: returns `null` instead of throwing when the input
23
+ * cannot be formatted (non-array, mixed scopes / key filters / schema
24
+ * versions, unresolved merges) — `null` means a data issue the caller must
25
+ * surface. An EMPTY document list is valid and yields a zero-filled page.
26
+ */
27
+ /** Filters applied to the metric key map client-side (empty = no constraint). */
28
+ export interface IFormattedSalesOverviewFilters {
29
+ /** Platform component values (e.g. `POS_WALK-IN`); empty or omitted = all. */
30
+ platforms?: string[] | null;
31
+ /** Order-status component values (e.g. `COMPLETED`); empty or omitted = all. */
32
+ order_statuses?: string[] | null;
33
+ /**
34
+ * Weekday filter for date/hour scopes — documents without a `day_index`
35
+ * are dropped when a non-empty list is given.
36
+ */
37
+ day_indexes?: DAY_INDEX_ENUM[] | null;
38
+ }
39
+ /** One order metric after cents → decimals conversion. */
40
+ export interface IFormattedSalesOverviewOrderMetric {
41
+ count: number;
42
+ gross_amount: number;
43
+ discount_amount: number;
44
+ discount_by_type: {
45
+ special_discount: number;
46
+ loyalty_discount: number;
47
+ voucher_discount: number;
48
+ };
49
+ gst_amount: number;
50
+ tax_amount: number;
51
+ tip_amount: number;
52
+ tax_invoice_provider_charges: number;
53
+ delivery_charges: number;
54
+ }
55
+ /** One payment-type line after cents → decimals conversion. */
56
+ export interface IFormattedSalesOverviewPayment {
57
+ /** Raw / UNPAID-normalized payment type, or `CREDIT_SETTLEMENT`. */
58
+ payment_type: string;
59
+ count: number;
60
+ gross_amount: number;
61
+ amount_due: number;
62
+ amount_paid: number;
63
+ amount_refunded: number;
64
+ card_charges: number;
65
+ /** `true` for the derived `CREDIT_SETTLEMENT` line. */
66
+ derived: boolean;
67
+ }
68
+ /** One platform's share (channel / collection split source). */
69
+ export interface IFormattedSalesOverviewChannel {
70
+ /** Platform value (e.g. `POS_WALK-IN`). */
71
+ platform: string;
72
+ /** `PLATFORM_NAMES` split — e.g. `'Pos'`. */
73
+ order_from: string;
74
+ /** `PLATFORM_NAMES` split — e.g. `'Walk-in'`. */
75
+ order_type: string;
76
+ count: number;
77
+ gross_amount: number;
78
+ }
79
+ /** Credit-bill ledger view (`CREDIT_BILLS` sale-type numbers). */
80
+ export interface IFormattedSalesOverviewCreditBills {
81
+ issued: {
82
+ count: number;
83
+ amount: number;
84
+ settled_count: number;
85
+ settled_amount: number;
86
+ };
87
+ received: {
88
+ count: number;
89
+ amount: number;
90
+ };
91
+ /** `issued.amount − issued.settled_amount` — still outstanding. */
92
+ outstanding_amount: number;
93
+ }
94
+ /** Weekday grouping (date/hour scopes only). */
95
+ export interface IFormattedSalesOverviewWeekday {
96
+ day_index: DAY_INDEX_ENUM;
97
+ metric: IFormattedSalesOverviewOrderMetric;
98
+ }
99
+ /** One hour bucket point (hour scope only), business-hour ordered. */
100
+ export interface IFormattedSalesOverviewHourPoint {
101
+ /** Business-day label (`YYYY-MM-DD`) — hours `00`–`05` are the next morning. */
102
+ local_date: string;
103
+ hour: number;
104
+ /** `(hour + 18) % 24` — chronological position within the business day. */
105
+ business_hour_index: number;
106
+ metric: IFormattedSalesOverviewOrderMetric;
107
+ }
108
+ /** One formatted page result (combined view: a single entry). */
109
+ export interface IFormattedSalesOverviewPageData {
110
+ /** All tenants folded into this result (`[tenant]` in single-tenant reads). */
111
+ tenant_ids: string[];
112
+ /** Non-cancelled sales (filtered) — the headline numbers. */
113
+ summary: IFormattedSalesOverviewOrderMetric;
114
+ /** `AMOUNT_COLLECTED` slot of the same filters. */
115
+ amount_collected: IFormattedSalesOverviewOrderMetric;
116
+ /** Orders materialized under `CANCELLED:*` keys. */
117
+ cancelled: IFormattedSalesOverviewOrderMetric;
118
+ /** Payments: UNPAID first, then COMPLIMENTARY, then the rest; settlement appended. */
119
+ payments: IFormattedSalesOverviewPayment[];
120
+ /** Per-platform breakdown, `count` desc. */
121
+ channels: IFormattedSalesOverviewChannel[];
122
+ credit_bills: IFormattedSalesOverviewCreditBills;
123
+ /** Date/hour scopes only (`null` for period scopes); ordered SUN…SAT. */
124
+ weekday: IFormattedSalesOverviewWeekday[] | null;
125
+ /** Hour scope only (`null` otherwise); ordered by business-hour index. */
126
+ hourly: IFormattedSalesOverviewHourPoint[] | null;
127
+ }
128
+ /**
129
+ * Formats materialized overview documents into page-ready data (see the
130
+ * module docblock for the full contract). Returns
131
+ * `[formattedPageData[], null]` — with `separate_view_per_tenant: true` one
132
+ * entry per tenant (comparative view seam; the analysis result is TBD), the
133
+ * default mode returns a single combined entry. Returns `null` (never throws)
134
+ * when the documents cannot be formatted together.
135
+ */
136
+ export declare function getFormattedTenantSalesOverviewReporting(docs: IMaterializedTenantSalesOverviewReport[], filters?: IFormattedSalesOverviewFilters | null, separate_view_per_tenant?: boolean): [IFormattedSalesOverviewPageData[], null] | null;