@managesome/eposmatic-toolkit 0.3.11 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/constants/MATERIALIZED_REPORTS.js +105 -0
- package/esm/helpers/materialized-reports/index.js +5 -0
- package/esm/helpers/materialized-reports/key-helpers.js +59 -0
- package/esm/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +60 -0
- package/esm/helpers/materialized-reports/scope-helpers.js +107 -0
- package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +251 -0
- package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +860 -0
- package/esm/schemas/models/materialized_tenant_reports_iterations.js +82 -0
- package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +399 -0
- package/esm/schemas/types/materialized_tenant_reports_iterations.js +1 -0
- package/esm/schemas/types/materialized_tenant_sales_overview_reports.js +1 -0
- package/lib/constants/MATERIALIZED_REPORTS.d.ts +96 -0
- package/lib/constants/MATERIALIZED_REPORTS.js +108 -0
- package/lib/helpers/materialized-reports/index.d.ts +5 -0
- package/lib/helpers/materialized-reports/index.js +21 -0
- package/lib/helpers/materialized-reports/key-helpers.d.ts +35 -0
- package/lib/helpers/materialized-reports/key-helpers.js +64 -0
- package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.d.ts +66 -0
- package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +63 -0
- package/lib/helpers/materialized-reports/scope-helpers.d.ts +57 -0
- package/lib/helpers/materialized-reports/scope-helpers.js +114 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +125 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +256 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +223 -0
- package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +875 -0
- package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +80 -0
- package/lib/schemas/models/materialized_tenant_reports_iterations.js +85 -0
- package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +569 -0
- package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +402 -0
- package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +62 -0
- package/lib/schemas/types/materialized_tenant_reports_iterations.js +2 -0
- package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +242 -0
- package/lib/schemas/types/materialized_tenant_sales_overview_reports.js +3 -0
- package/lib/tests/materialized-reports/fixtures.d.ts +81 -0
- package/lib/tests/materialized-reports/fixtures.js +87 -0
- package/lib/tests/materialized-reports/fixtures.test.d.ts +1 -0
- package/lib/tests/materialized-reports/fixtures.test.js +123 -0
- package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.js +75 -0
- package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +73 -0
- package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +207 -0
- package/lib/tests/materialized-reports/sales-overview-baseline.test.d.ts +1 -0
- package/lib/tests/materialized-reports/sales-overview-baseline.test.js +326 -0
- package/lib/tests/materialized-reports/sales-overview-reference.d.ts +63 -0
- package/lib/tests/materialized-reports/sales-overview-reference.js +131 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.d.ts +1 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +335 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.d.ts +1 -0
- package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +885 -0
- package/package.json +5 -2
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Constants for the `materialized_*` report collections (see
|
|
3
|
+
* `MATERIALIZED_REPORTS.md`).
|
|
4
|
+
*
|
|
5
|
+
* NOTE: during the current development phase the materialized-report files
|
|
6
|
+
* stay self-contained — this file is NOT (yet) re-exported from
|
|
7
|
+
* `src/constants/index.ts`; the report schema/type files import it via
|
|
8
|
+
* relative paths. Wiring re-exports into the barrels is a separate,
|
|
9
|
+
* explicitly-enabled step.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Time-scope of a materialized report document. Every document covers exactly
|
|
13
|
+
* one tenant × one scope context × one scope value (`scope_field`), and the
|
|
14
|
+
* same scope set is shared by every materialized report collection.
|
|
15
|
+
*
|
|
16
|
+
* `scope_field` formats (all strings), derived from the existing toolkit time
|
|
17
|
+
* helpers (`getLocalDocumentFields`, `getIsoWeekOfYear`, `getCalendarWeekStart`)
|
|
18
|
+
* for the order's business day (`order.localDate`) — hours use the PUNCH hour
|
|
19
|
+
* for sales and the SETTLEMENT hour for credit-bill collections:
|
|
20
|
+
* - `LOCAL_HOUR`: 'YYYY-MM-DD HH' — e.g. '2026-09-15 18' (one hour of one day)
|
|
21
|
+
* - `LOCAL_DATE`: 'YYYY-MM-DD' — e.g. '2026-09-15'
|
|
22
|
+
* - `LOCAL_WEEK`: 'YYYY-MM-DD' — week start (Sun–Sat, the calendar UI's
|
|
23
|
+
* convention: `getCalendarWeekStart(date, 0)`)
|
|
24
|
+
* - `LOCAL_WEEK_OF_YEAR`: 'YYYY-Wnn' — ISO week (`getIsoWeekOfYear`); `YYYY` is the
|
|
25
|
+
* ISO week-year for boundary weeks
|
|
26
|
+
* - `LOCAL_MONTH`: 'YYYY-MM' — e.g. '2026-09'
|
|
27
|
+
* - `LOCAL_QUARTER`: 'YYYY-Qn' — e.g. '2026-Q3'
|
|
28
|
+
* - `LOCAL_SEMESTER`: 'YYYY-Sn' — e.g. '2026-S2'
|
|
29
|
+
* - `LOCAL_YEAR`: 'YYYY' — e.g. '2026'
|
|
30
|
+
*
|
|
31
|
+
* `DAY_INDEX` is intentionally NOT a scope: a weekday accumulator has no time
|
|
32
|
+
* anchor — it cannot honor date-range filters and would grow forever. Instead,
|
|
33
|
+
* `LOCAL_HOUR` and `LOCAL_DATE` documents carry a denormalized `day_index`
|
|
34
|
+
* field (`DAY_INDEX_ENUM`) so weekday filtering/grouping is a plain query over
|
|
35
|
+
* the date/hour slices (see `MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX`).
|
|
36
|
+
*
|
|
37
|
+
* The day-end materialization job compiles the tenant's day into the report
|
|
38
|
+
* collections: up to 24 `LOCAL_HOUR` documents plus one document for each
|
|
39
|
+
* other scope (31 per tenant-day; the longer-period documents accumulate until
|
|
40
|
+
* their period ends). Changing scope values or their formats requires a
|
|
41
|
+
* `schema_version` bump and re-materialization of history.
|
|
42
|
+
*/
|
|
43
|
+
export var MATERIALIZED_REPORT_SCOPE_ENUM;
|
|
44
|
+
(function (MATERIALIZED_REPORT_SCOPE_ENUM) {
|
|
45
|
+
MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_HOUR"] = "localHour";
|
|
46
|
+
MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_DATE"] = "localDate";
|
|
47
|
+
MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_WEEK"] = "localWeek";
|
|
48
|
+
MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_WEEK_OF_YEAR"] = "localWeekOfYear";
|
|
49
|
+
MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_MONTH"] = "localMonth";
|
|
50
|
+
MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_QUARTER"] = "localQuarter";
|
|
51
|
+
MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_SEMESTER"] = "localSemester";
|
|
52
|
+
MATERIALIZED_REPORT_SCOPE_ENUM["LOCAL_YEAR"] = "localYear";
|
|
53
|
+
})(MATERIALIZED_REPORT_SCOPE_ENUM || (MATERIALIZED_REPORT_SCOPE_ENUM = {}));
|
|
54
|
+
export const ALL_MATERIALIZED_REPORT_SCOPES = Object.values(MATERIALIZED_REPORT_SCOPE_ENUM);
|
|
55
|
+
/**
|
|
56
|
+
* Scopes whose documents carry the denormalized `day_index` weekday field
|
|
57
|
+
* (derived from `scope_field` by the materializer, `DAY_INDEX_ENUM`). All
|
|
58
|
+
* other scopes must leave it `null` — weekday analysis reads date/hour slices
|
|
59
|
+
* (`LOCAL_HOUR` / `LOCAL_DATE`) instead of an all-time accumulator document.
|
|
60
|
+
*/
|
|
61
|
+
export const MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX = [
|
|
62
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
|
|
63
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
64
|
+
];
|
|
65
|
+
/**
|
|
66
|
+
* Filter dimensions that can be encoded into the metric keys of a materialized
|
|
67
|
+
* report document (`sale_type_metrics`). The declaration order defines the key
|
|
68
|
+
* grammar: `<DIM_1>:<DIM_2>:...` built from raw enum/live string values
|
|
69
|
+
* (e.g. `PLACED:POS_WALK-IN`). Changing the dimensions or their order requires
|
|
70
|
+
* a `schema_version` bump and re-materialization of historical documents.
|
|
71
|
+
*/
|
|
72
|
+
export var MATERIALIZED_REPORT_KEY_FILTER_ENUM;
|
|
73
|
+
(function (MATERIALIZED_REPORT_KEY_FILTER_ENUM) {
|
|
74
|
+
MATERIALIZED_REPORT_KEY_FILTER_ENUM["ORDER_STATUS"] = "ORDER_STATUS";
|
|
75
|
+
MATERIALIZED_REPORT_KEY_FILTER_ENUM["PLATFORM"] = "PLATFORM";
|
|
76
|
+
})(MATERIALIZED_REPORT_KEY_FILTER_ENUM || (MATERIALIZED_REPORT_KEY_FILTER_ENUM = {}));
|
|
77
|
+
export const ALL_MATERIALIZED_REPORT_KEY_FILTERS = Object.values(MATERIALIZED_REPORT_KEY_FILTER_ENUM);
|
|
78
|
+
/** Ordered key filters of the tenant sales overview report (`PLACED:POS_WALK-IN`). */
|
|
79
|
+
export const SALES_OVERVIEW_KEY_FILTERS = [
|
|
80
|
+
MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS,
|
|
81
|
+
MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM,
|
|
82
|
+
];
|
|
83
|
+
/**
|
|
84
|
+
* Payment-type label used by the frontend report formatter for the derived
|
|
85
|
+
* credit-settlement line in a collection day's payments breakdown (a
|
|
86
|
+
* `PAY_LATER` bill collected on a later day). NOT stored in materialized docs —
|
|
87
|
+
* the formatter composes the line from the `CREDIT_BILLS` ledger's `received`
|
|
88
|
+
* bucket. The line is excluded from method buckets (CASH/CARD/…) and never
|
|
89
|
+
* feeds gross: gross stays sales-only, so cross-day gross sums stay equal to
|
|
90
|
+
* total sales.
|
|
91
|
+
*/
|
|
92
|
+
export const MATERIALIZED_CREDIT_SETTLEMENT_PAYMENT_TYPE = 'CREDIT_SETTLEMENT';
|
|
93
|
+
/**
|
|
94
|
+
* Materialized report kinds — the discriminator stored on
|
|
95
|
+
* `materialized_tenant_reports_iterations` rows. A single shared history collection records
|
|
96
|
+
* the structural iterations of EVERY materialized report, so each row must
|
|
97
|
+
* declare which report collection its `report_id` belongs to. Add one member
|
|
98
|
+
* per new report collection (Summary / X / Z / Riders / Items / Void Items …)
|
|
99
|
+
* as it lands.
|
|
100
|
+
*/
|
|
101
|
+
export var MATERIALIZED_REPORT_TYPE_ENUM;
|
|
102
|
+
(function (MATERIALIZED_REPORT_TYPE_ENUM) {
|
|
103
|
+
MATERIALIZED_REPORT_TYPE_ENUM["TENANT_SALES_OVERVIEW"] = "TENANT_SALES_OVERVIEW";
|
|
104
|
+
})(MATERIALIZED_REPORT_TYPE_ENUM || (MATERIALIZED_REPORT_TYPE_ENUM = {}));
|
|
105
|
+
export const ALL_MATERIALIZED_REPORT_TYPES = Object.values(MATERIALIZED_REPORT_TYPE_ENUM);
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared key grammar for materialized-report documents (see
|
|
3
|
+
* `MATERIALIZED_REPORTS.md`).
|
|
4
|
+
*
|
|
5
|
+
* Every `sale_type_metrics` key is the ordered join of the document's
|
|
6
|
+
* `sale_type_key_filters` values (the key dimensions), e.g.
|
|
7
|
+
* `"COMPLETED:POS_TAKE-AWAY"` for `[ORDER_STATUS, PLATFORM]`. The grammar must
|
|
8
|
+
* live in exactly one place — readers and writers must never build or parse
|
|
9
|
+
* keys ad hoc.
|
|
10
|
+
*
|
|
11
|
+
* Reserved characters: the separator `":"` plus Mongo field-name hazards
|
|
12
|
+
* (`"."`, `"$"`) — map keys are stored as document field names, so components
|
|
13
|
+
* containing them are rejected at build time.
|
|
14
|
+
*/
|
|
15
|
+
/** Delimiter between key components. */
|
|
16
|
+
export const MATERIALIZED_REPORT_KEY_SEPARATOR = ':';
|
|
17
|
+
// The separator itself plus Mongo field-name hazards (map keys are document field names).
|
|
18
|
+
const RESERVED_KEY_CHARACTERS = /[:.$]/;
|
|
19
|
+
/**
|
|
20
|
+
* Builds a `sale_type_metrics` key from its ordered components
|
|
21
|
+
* (`buildMaterializedReportKey(['COMPLETED', 'POS_TAKE-AWAY'])` →
|
|
22
|
+
* `"COMPLETED:POS_TAKE-AWAY"`).
|
|
23
|
+
*
|
|
24
|
+
* Returns `null` (never throws) when a component is missing, non-string or
|
|
25
|
+
* contains a reserved character — `null` means the source data is invalid and
|
|
26
|
+
* the caller must treat it as a data issue.
|
|
27
|
+
*/
|
|
28
|
+
export function buildMaterializedReportKey(components) {
|
|
29
|
+
if (!Array.isArray(components) || components.length === 0) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
for (const component of components) {
|
|
33
|
+
if (typeof component !== 'string' || component.length === 0) {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
if (RESERVED_KEY_CHARACTERS.test(component)) {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return components.join(MATERIALIZED_REPORT_KEY_SEPARATOR);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Parses a `sale_type_metrics` key back into its ordered components —
|
|
44
|
+
* `"COMPLETED:POS_TAKE-AWAY"` → `['COMPLETED', 'POS_TAKE-AWAY']`.
|
|
45
|
+
*
|
|
46
|
+
* The caller maps components to dimensions using the document's
|
|
47
|
+
* `sale_type_key_filters` order. Returns `null` (never throws) for empty or
|
|
48
|
+
* malformed keys — `null` means the stored data / input is corrupt.
|
|
49
|
+
*/
|
|
50
|
+
export function parseMaterializedReportKey(key) {
|
|
51
|
+
if (typeof key !== 'string' || key.length === 0) {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
const components = key.split(MATERIALIZED_REPORT_KEY_SEPARATOR);
|
|
55
|
+
if (components.some((component) => component.length === 0)) {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
return components;
|
|
59
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { ALL_MATERIALIZED_REPORT_TYPES } from '../../constants/MATERIALIZED_REPORTS';
|
|
2
|
+
/**
|
|
3
|
+
* `_id` as the report id string: plain strings pass through; a mongoose
|
|
4
|
+
* `ObjectId` (hydrated documents) stringifies via `toHexString()`.
|
|
5
|
+
*/
|
|
6
|
+
const normalizeMaterializedReportId = (value) => {
|
|
7
|
+
if (typeof value === 'string')
|
|
8
|
+
return value.length > 0 ? value : null;
|
|
9
|
+
if (value != null && typeof value.toHexString === 'function') {
|
|
10
|
+
const hex = value.toHexString();
|
|
11
|
+
return typeof hex === 'string' && hex.length > 0 ? hex : null;
|
|
12
|
+
}
|
|
13
|
+
return null;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Builds the `materialized_tenant_reports_iterations` row for a report document's current
|
|
17
|
+
* structural iteration — plain JSON, ready to upsert with
|
|
18
|
+
* `replaceOne({ report_id, iteration }, row, { upsert: true })` (`_id` is
|
|
19
|
+
* assigned by MongoDB; replays rewrite the same row idempotently).
|
|
20
|
+
*
|
|
21
|
+
* Documents that never went through an update (no explicit `iteration`, e.g.
|
|
22
|
+
* raw `convertOrdersToMaterializedTenantSalesOverviewReports` output) default
|
|
23
|
+
* to `iteration: 1` — matching the report schema's first-materialization
|
|
24
|
+
* default.
|
|
25
|
+
*
|
|
26
|
+
* `_id` may be a plain string (`.lean()` / JSON) or a mongoose `ObjectId`
|
|
27
|
+
* (hydrated documents) — the row's `report_id` is always the string form.
|
|
28
|
+
*
|
|
29
|
+
* Returns `null` (never throws) when the snapshot lacks `_id` /
|
|
30
|
+
* `schema_version`, carries an invalid `iteration`, or `reportType` is not a
|
|
31
|
+
* known report type.
|
|
32
|
+
*/
|
|
33
|
+
export function buildMaterializedTenantReportIteration(snapshot, options) {
|
|
34
|
+
if (snapshot == null || options == null)
|
|
35
|
+
return null;
|
|
36
|
+
if (!ALL_MATERIALIZED_REPORT_TYPES.includes(options.reportType))
|
|
37
|
+
return null;
|
|
38
|
+
if (typeof options.reason !== 'string' || options.reason.length === 0)
|
|
39
|
+
return null;
|
|
40
|
+
const { _id, schema_version } = snapshot;
|
|
41
|
+
const reportId = normalizeMaterializedReportId(_id);
|
|
42
|
+
if (reportId == null)
|
|
43
|
+
return null;
|
|
44
|
+
if (typeof schema_version !== 'number' || !Number.isFinite(schema_version))
|
|
45
|
+
return null;
|
|
46
|
+
const iteration = snapshot.iteration ?? 1;
|
|
47
|
+
if (!Number.isInteger(iteration) || iteration < 1)
|
|
48
|
+
return null;
|
|
49
|
+
const computedAt = options.computedAt ?? new Date();
|
|
50
|
+
return {
|
|
51
|
+
report_type: options.reportType,
|
|
52
|
+
report_id: reportId,
|
|
53
|
+
iteration,
|
|
54
|
+
schema_version,
|
|
55
|
+
reason: options.reason,
|
|
56
|
+
snapshot,
|
|
57
|
+
createdAt: computedAt,
|
|
58
|
+
updatedAt: computedAt,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { ALL_DAY_INDEX } from '../../constants/ENUMS';
|
|
2
|
+
import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
|
|
3
|
+
import { getCalendarWeekStart, getIsoWeekOfYear } from '../utils/time-helpers';
|
|
4
|
+
/**
|
|
5
|
+
* Scope-field builders for materialized-report documents (see
|
|
6
|
+
* `MATERIALIZED_REPORTS.md` "Time scopes"). Given the tenant-local business
|
|
7
|
+
* date (`YYYY-MM-DD`) of a compiled day, these derive the `scope_field` value
|
|
8
|
+
* of every period scope plus the denormalized weekday.
|
|
9
|
+
*
|
|
10
|
+
* All math is pure UTC calendar arithmetic on the date string — independent of
|
|
11
|
+
* the server timezone. The hour scope (`'YYYY-MM-DD HH'`) is built per bucket
|
|
12
|
+
* via `getMaterializedHourScopeField`.
|
|
13
|
+
*
|
|
14
|
+
* Validation convention: builders return `null` instead of throwing — a `null`
|
|
15
|
+
* result means the caller passed invalid data.
|
|
16
|
+
*/
|
|
17
|
+
const LOCAL_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
18
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
19
|
+
/**
|
|
20
|
+
* Parses + validates a `'YYYY-MM-DD'` local date into its numeric parts.
|
|
21
|
+
* Returns `null` (never throws) for malformed dates — `null` means the caller
|
|
22
|
+
* passed invalid data.
|
|
23
|
+
*/
|
|
24
|
+
export function parseMaterializedLocalDate(localDate) {
|
|
25
|
+
if (typeof localDate !== 'string' || !LOCAL_DATE_PATTERN.test(localDate)) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
const [year, month, day] = localDate.split('-').map(Number);
|
|
29
|
+
if (month < 1 || month > 12 || day < 1 || day > 31) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
// Real-calendar check: impossible dates (e.g. '2026-02-31') must never slip
|
|
33
|
+
// through — `Date.UTC` rollover would silently derive WRONG scope fields
|
|
34
|
+
// (week/day_index pointing into the next month).
|
|
35
|
+
const utc = new Date(Date.UTC(year, month - 1, day));
|
|
36
|
+
if (utc.getUTCFullYear() !== year || utc.getUTCMonth() !== month - 1 || utc.getUTCDate() !== day) {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
return { year, month, day };
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* ISO 8601 week-year of a local date — the year of the Thursday of that date's
|
|
43
|
+
* ISO week. Differs from the calendar year for boundary weeks (e.g.
|
|
44
|
+
* `'2027-01-01'` is `2026-W53`), which is exactly why `'YYYY-Wnn'` scope
|
|
45
|
+
* fields need it. Returns `null` for malformed dates.
|
|
46
|
+
*/
|
|
47
|
+
export function getIsoWeekYear(localDate) {
|
|
48
|
+
const parts = parseMaterializedLocalDate(localDate);
|
|
49
|
+
return parts != null ? getIsoWeekYearFromParts(parts) : null;
|
|
50
|
+
}
|
|
51
|
+
function getIsoWeekYearFromParts({ year, month, day }) {
|
|
52
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
53
|
+
const isoWeekday = date.getUTCDay() || 7; // Monday = 1 … Sunday = 7
|
|
54
|
+
date.setUTCDate(date.getUTCDate() + 4 - isoWeekday); // move to the ISO week's Thursday
|
|
55
|
+
return date.getUTCFullYear();
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Denormalized weekday (`DAY_INDEX_ENUM`) of a local date. Returns `null`
|
|
59
|
+
* (never throws) for malformed dates.
|
|
60
|
+
*/
|
|
61
|
+
export function getDayIndexFromLocalDate(localDate) {
|
|
62
|
+
const parts = parseMaterializedLocalDate(localDate);
|
|
63
|
+
if (parts == null)
|
|
64
|
+
return null;
|
|
65
|
+
return ALL_DAY_INDEX[new Date(Date.UTC(parts.year, parts.month - 1, parts.day)).getUTCDay()];
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Builds the `scope_field` of every period scope for a compiled local date:
|
|
69
|
+
*
|
|
70
|
+
* - `localDate`: `'2026-09-30'`
|
|
71
|
+
* - `localWeek`: Sun–Sat week start (the calendar UI convention —
|
|
72
|
+
* `getCalendarWeekStart(date, 0)`) → `'2026-09-27'`
|
|
73
|
+
* - `localWeekOfYear`: ISO week `'YYYY-Wnn'` where `YYYY` is the ISO week-year
|
|
74
|
+
* - `localMonth`: `'2026-09'`
|
|
75
|
+
* - `localQuarter`: `'2026-Q3'`
|
|
76
|
+
* - `localSemester`: `'2026-S2'`
|
|
77
|
+
* - `localYear`: `'2026'`
|
|
78
|
+
*
|
|
79
|
+
* Returns `null` (never throws) for malformed dates.
|
|
80
|
+
*/
|
|
81
|
+
export function getMaterializedPeriodScopeFields(localDate) {
|
|
82
|
+
const parts = parseMaterializedLocalDate(localDate);
|
|
83
|
+
if (parts == null)
|
|
84
|
+
return null;
|
|
85
|
+
const { year, month, day } = parts;
|
|
86
|
+
return {
|
|
87
|
+
[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE]: localDate,
|
|
88
|
+
[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK]: getCalendarWeekStart(localDate, 0),
|
|
89
|
+
[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR]: `${getIsoWeekYearFromParts(parts)}-W${pad(getIsoWeekOfYear(year, month, day))}`,
|
|
90
|
+
[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH]: `${year}-${pad(month)}`,
|
|
91
|
+
[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER]: `${year}-Q${Math.ceil(month / 3)}`,
|
|
92
|
+
[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER]: `${year}-S${month <= 6 ? 1 : 2}`,
|
|
93
|
+
[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR]: `${year}`,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* `scope_field` of a `localHour` bucket — `'2026-09-30 18'` (zero-padded).
|
|
98
|
+
* Returns `null` (never throws) for a malformed local date or an out-of-range
|
|
99
|
+
* hour.
|
|
100
|
+
*/
|
|
101
|
+
export function getMaterializedHourScopeField(localDate, hour) {
|
|
102
|
+
if (parseMaterializedLocalDate(localDate) == null)
|
|
103
|
+
return null;
|
|
104
|
+
if (!Number.isInteger(hour) || hour < 0 || hour > 23)
|
|
105
|
+
return null;
|
|
106
|
+
return `${localDate} ${pad(hour)}`;
|
|
107
|
+
}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { REPORT_SALE_TYPE_ENUM } from '../../constants';
|
|
2
|
+
import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
|
|
3
|
+
import { buildMaterializedTenantReportIteration } from './materialized-tenant-reports-iterations-helpers';
|
|
4
|
+
import { getMaterializedHourScopeField, getMaterializedPeriodScopeFields } from './scope-helpers';
|
|
5
|
+
import { normalizeMaterializedSaleTypeMetrics, updateMaterializedTenantSalesOverviewReport, } from './tenant-sales-overview-helpers';
|
|
6
|
+
/** Scopes written wholesale for the compiled day (replacement semantics). */
|
|
7
|
+
const CLOSE_DAY_DAY_SCOPES = [
|
|
8
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
|
|
9
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
10
|
+
];
|
|
11
|
+
/** Scopes that accumulate day deltas (subtract the stored delta, add the fresh one). */
|
|
12
|
+
const CLOSE_DAY_ACCUMULATED_SCOPES = [
|
|
13
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
|
|
14
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
|
|
15
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
|
|
16
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
|
|
17
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
|
|
18
|
+
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
|
|
19
|
+
];
|
|
20
|
+
const materializedScopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
|
|
21
|
+
const materializedCreditBillKey = (orderId, paymentId) => `${orderId}|${paymentId}`;
|
|
22
|
+
const hasMaterializedMetrics = (doc) => Object.keys(normalizeMaterializedSaleTypeMetrics(doc.sale_type_metrics)).length > 0;
|
|
23
|
+
/**
|
|
24
|
+
* Every stored scope the fan-out of one local day needs: the six period
|
|
25
|
+
* scopes + `localDate` of that day and all 24 `localHour` buckets (`null` for
|
|
26
|
+
* a malformed date). A bill's hour is unknowable from the received entry
|
|
27
|
+
* alone, so settlement patches always consider the whole day.
|
|
28
|
+
*/
|
|
29
|
+
export function getMaterializedTenantSalesOverviewScopeRefsForDay(localDate) {
|
|
30
|
+
const periodFields = getMaterializedPeriodScopeFields(localDate);
|
|
31
|
+
if (periodFields == null)
|
|
32
|
+
return null;
|
|
33
|
+
const refs = [];
|
|
34
|
+
for (const scopeContext of Object.keys(periodFields)) {
|
|
35
|
+
refs.push({
|
|
36
|
+
scope_context: scopeContext,
|
|
37
|
+
scope_field: periodFields[scopeContext],
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
for (let hour = 0; hour < 24; hour++) {
|
|
41
|
+
const scopeField = getMaterializedHourScopeField(localDate, hour);
|
|
42
|
+
if (scopeField == null)
|
|
43
|
+
return null;
|
|
44
|
+
refs.push({ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: scopeField });
|
|
45
|
+
}
|
|
46
|
+
return refs;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Watermark guard of the write path: does the stored document need a
|
|
50
|
+
* structural write for the incoming compiled version?
|
|
51
|
+
*
|
|
52
|
+
* `false` (skip) when the incoming `source_watermark` is not newer than the
|
|
53
|
+
* stored one and the schema version + key-filter grammar match. Watermarks are
|
|
54
|
+
* monotonic (`updateMaterializedTenantSalesOverviewReport` never regresses
|
|
55
|
+
* them). A missing stored document always needs a write.
|
|
56
|
+
*/
|
|
57
|
+
export function needsMaterializedTenantSalesOverviewReportWrite(existing, incoming) {
|
|
58
|
+
if (existing == null || incoming == null)
|
|
59
|
+
return true;
|
|
60
|
+
if (existing.schema_version !== incoming.schema_version)
|
|
61
|
+
return true;
|
|
62
|
+
if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
const existingTime = new Date(existing.source_watermark ?? 0).getTime();
|
|
66
|
+
const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
|
|
67
|
+
if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
|
|
68
|
+
return true;
|
|
69
|
+
return incomingTime > existingTime;
|
|
70
|
+
}
|
|
71
|
+
/** Would a received-payment patch change the stored bill? (settlement/note/received) */
|
|
72
|
+
const creditBillWouldChange = (bill, collected) => {
|
|
73
|
+
const received = Math.max(bill.received_amount ?? 0, collected.received_amount ?? 0);
|
|
74
|
+
if (received !== (bill.received_amount ?? 0))
|
|
75
|
+
return true;
|
|
76
|
+
const note = bill.credit_note ?? collected.credit_note;
|
|
77
|
+
if ((note ?? null) !== (bill.credit_note ?? null))
|
|
78
|
+
return true;
|
|
79
|
+
return bill.settled_at == null && received >= (bill.amount ?? 0);
|
|
80
|
+
};
|
|
81
|
+
/** Does the document hold an issued bill that one of the collected payments would change? */
|
|
82
|
+
const documentHoldsUnpatchedCreditBill = (doc, collectedByBill) => {
|
|
83
|
+
for (const keyMetrics of Object.values(normalizeMaterializedSaleTypeMetrics(doc.sale_type_metrics))) {
|
|
84
|
+
for (const bill of keyMetrics?.[REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]?.issued?.bills ?? []) {
|
|
85
|
+
const collected = collectedByBill.get(materializedCreditBillKey(bill.order_id, bill.payment_id));
|
|
86
|
+
if (collected != null && creditBillWouldChange(bill, collected))
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return false;
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Builds the close-day write plan for ONE tenant-day (see the module docs).
|
|
94
|
+
* Returns `null` (never throws) when the input is inconsistent — compiled
|
|
95
|
+
* docs of another tenant, duplicate compiled scope documents, a malformed
|
|
96
|
+
* `localDate`, duplicate STORED rows for one scope key (missing unique index
|
|
97
|
+
* — a data issue to fix, never silently deduplicated), or a merge conflict
|
|
98
|
+
* with a stored document (schema / brand).
|
|
99
|
+
*/
|
|
100
|
+
export function buildTenantSalesOverviewCloseDayPlan(input) {
|
|
101
|
+
if (input == null)
|
|
102
|
+
return null;
|
|
103
|
+
const { tenantId, compile, reason } = input;
|
|
104
|
+
if (typeof tenantId !== 'string' || tenantId.length === 0)
|
|
105
|
+
return null;
|
|
106
|
+
if (compile == null)
|
|
107
|
+
return null;
|
|
108
|
+
if (typeof reason !== 'string' || reason.length === 0)
|
|
109
|
+
return null;
|
|
110
|
+
const compiledReports = compile.materializedReports ?? [];
|
|
111
|
+
if (compiledReports.some((doc) => doc == null || doc.tenant_id !== tenantId))
|
|
112
|
+
return null;
|
|
113
|
+
const computedAt = input.computedAt ?? new Date();
|
|
114
|
+
const force = input.force === true;
|
|
115
|
+
const compiledByScope = new Map();
|
|
116
|
+
for (const doc of compiledReports) {
|
|
117
|
+
const key = materializedScopeKey(doc);
|
|
118
|
+
if (compiledByScope.has(key))
|
|
119
|
+
return null; // duplicate scope doc — data issue
|
|
120
|
+
compiledByScope.set(key, doc);
|
|
121
|
+
}
|
|
122
|
+
const compiledDateDoc = compiledReports.find((doc) => doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE) ?? null;
|
|
123
|
+
if (compiledDateDoc == null)
|
|
124
|
+
return null;
|
|
125
|
+
const localDate = compiledDateDoc.scope_field;
|
|
126
|
+
if (getMaterializedTenantSalesOverviewScopeRefsForDay(localDate) == null)
|
|
127
|
+
return null;
|
|
128
|
+
const existingByScope = new Map();
|
|
129
|
+
for (const doc of input.existing ?? []) {
|
|
130
|
+
if (doc == null || doc.tenant_id !== tenantId)
|
|
131
|
+
continue;
|
|
132
|
+
const key = materializedScopeKey(doc);
|
|
133
|
+
const prior = existingByScope.get(key);
|
|
134
|
+
if (prior == null) {
|
|
135
|
+
existingByScope.set(key, doc);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
// Repeating the SAME document (overlapping fetch refs) is fine; two
|
|
139
|
+
// different rows for one scope key mean the unique index is missing.
|
|
140
|
+
// String comparison keeps hydrated ObjectId `_id`s compatible with plain ids.
|
|
141
|
+
if (String(prior._id) !== String(doc._id))
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
const storedDateDoc = existingByScope.get(materializedScopeKey(compiledDateDoc)) ?? null;
|
|
145
|
+
const dayChanged = force || needsMaterializedTenantSalesOverviewReportWrite(storedDateDoc, compiledDateDoc);
|
|
146
|
+
const dayDeltaEmpty = !hasMaterializedMetrics(compiledDateDoc);
|
|
147
|
+
const writes = [];
|
|
148
|
+
const skippedDocuments = [];
|
|
149
|
+
const createdPeriodDocuments = [];
|
|
150
|
+
const addStructuralWrite = (report) => {
|
|
151
|
+
const iteration = buildMaterializedTenantReportIteration(report, {
|
|
152
|
+
reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
|
|
153
|
+
reason,
|
|
154
|
+
computedAt,
|
|
155
|
+
});
|
|
156
|
+
if (iteration == null)
|
|
157
|
+
return false;
|
|
158
|
+
writes.push({ report, iteration });
|
|
159
|
+
return true;
|
|
160
|
+
};
|
|
161
|
+
for (const compiledDoc of compiledReports) {
|
|
162
|
+
const existing = existingByScope.get(materializedScopeKey(compiledDoc)) ?? null;
|
|
163
|
+
if (CLOSE_DAY_DAY_SCOPES.includes(compiledDoc.scope_context)) {
|
|
164
|
+
if (!dayChanged) {
|
|
165
|
+
if (existing != null)
|
|
166
|
+
skippedDocuments.push(existing);
|
|
167
|
+
// Partial-failure repair: the day is up to date but this scope doc was never persisted.
|
|
168
|
+
else if (!addStructuralWrite(compiledDoc))
|
|
169
|
+
return null;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (existing == null) {
|
|
173
|
+
if (!addStructuralWrite(compiledDoc))
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
const updated = updateMaterializedTenantSalesOverviewReport(existing, { replacement: compiledDoc }, { computedAt });
|
|
178
|
+
if (updated == null || !addStructuralWrite(updated))
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (!CLOSE_DAY_ACCUMULATED_SCOPES.includes(compiledDoc.scope_context))
|
|
184
|
+
return null; // unknown scope — data issue
|
|
185
|
+
if (existing == null) {
|
|
186
|
+
if (dayDeltaEmpty)
|
|
187
|
+
continue; // nothing to fold into a (new) period document
|
|
188
|
+
if (!addStructuralWrite(compiledDoc))
|
|
189
|
+
return null;
|
|
190
|
+
createdPeriodDocuments.push({
|
|
191
|
+
scope_context: compiledDoc.scope_context,
|
|
192
|
+
scope_field: compiledDoc.scope_field,
|
|
193
|
+
});
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
if (!dayChanged) {
|
|
197
|
+
skippedDocuments.push(existing);
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (dayDeltaEmpty && storedDateDoc == null) {
|
|
201
|
+
skippedDocuments.push(existing); // first close of an order-less day — nothing to fold
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
const updated = updateMaterializedTenantSalesOverviewReport(existing, { subtract: storedDateDoc != null ? [storedDateDoc] : [], additions: [compiledDoc] }, { computedAt });
|
|
205
|
+
if (updated == null || !addStructuralWrite(updated))
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
// Orders deleted / moved shrank the day's active hours — drop the stale docs.
|
|
209
|
+
const staleHourDocuments = dayChanged
|
|
210
|
+
? Array.from(existingByScope.values()).filter((doc) => doc.scope_context === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
|
|
211
|
+
typeof doc.scope_field === 'string' &&
|
|
212
|
+
doc.scope_field.startsWith(`${localDate} `) &&
|
|
213
|
+
!compiledByScope.has(materializedScopeKey(doc)))
|
|
214
|
+
: [];
|
|
215
|
+
// Collected bills patch the ISSUE-day docs that still hold the issued
|
|
216
|
+
// ledger. Compute the patches against the POST-write documents — a period
|
|
217
|
+
// doc that both accumulates the day and holds an earlier issued bill must
|
|
218
|
+
// keep the accumulation in its patched version (persist patches AFTER
|
|
219
|
+
// writes).
|
|
220
|
+
const postWriteByScope = new Map();
|
|
221
|
+
for (const doc of existingByScope.values())
|
|
222
|
+
postWriteByScope.set(materializedScopeKey(doc), doc);
|
|
223
|
+
for (const write of writes)
|
|
224
|
+
postWriteByScope.set(materializedScopeKey(write.report), write.report);
|
|
225
|
+
for (const stale of staleHourDocuments)
|
|
226
|
+
postWriteByScope.delete(materializedScopeKey(stale));
|
|
227
|
+
const receivedPatches = [];
|
|
228
|
+
const receivedPayments = compile.received_payments ?? [];
|
|
229
|
+
if (receivedPayments.length > 0) {
|
|
230
|
+
const collectedByBill = new Map();
|
|
231
|
+
for (const collected of receivedPayments) {
|
|
232
|
+
collectedByBill.set(materializedCreditBillKey(collected.order_id, collected.payment_id), collected);
|
|
233
|
+
}
|
|
234
|
+
for (const doc of postWriteByScope.values()) {
|
|
235
|
+
if (!documentHoldsUnpatchedCreditBill(doc, collectedByBill))
|
|
236
|
+
continue;
|
|
237
|
+
const patched = updateMaterializedTenantSalesOverviewReport(doc, { received_payments: receivedPayments }, { computedAt });
|
|
238
|
+
if (patched == null)
|
|
239
|
+
return null;
|
|
240
|
+
const iteration = buildMaterializedTenantReportIteration(patched, {
|
|
241
|
+
reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
|
|
242
|
+
reason,
|
|
243
|
+
computedAt,
|
|
244
|
+
});
|
|
245
|
+
if (iteration == null)
|
|
246
|
+
return null;
|
|
247
|
+
receivedPatches.push({ report: patched, iteration });
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return { writes, staleHourDocuments, receivedPatches, skippedDocuments, createdPeriodDocuments };
|
|
251
|
+
}
|