@managesome/eposmatic-toolkit 0.3.10 → 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.
Files changed (145) hide show
  1. package/esm/constants/ENUMS.js +17 -1988
  2. package/esm/constants/MATERIALIZED_REPORTS.js +105 -0
  3. package/esm/constants/enums/cash.js +45 -0
  4. package/esm/constants/enums/communications.js +329 -0
  5. package/esm/constants/enums/delivery.js +35 -0
  6. package/esm/constants/enums/geo.js +150 -0
  7. package/esm/constants/enums/hr.js +130 -0
  8. package/esm/constants/enums/internal.js +132 -0
  9. package/esm/constants/enums/items.js +126 -0
  10. package/esm/constants/enums/misc.js +35 -0
  11. package/esm/constants/enums/offers.js +102 -0
  12. package/esm/constants/enums/order.js +135 -0
  13. package/esm/constants/enums/payments.js +186 -0
  14. package/esm/constants/enums/platform.js +215 -0
  15. package/esm/constants/enums/printing.js +107 -0
  16. package/esm/constants/enums/users.js +245 -0
  17. package/esm/constants/enums/wallet.js +32 -0
  18. package/esm/helpers/materialized-reports/index.js +5 -0
  19. package/esm/helpers/materialized-reports/key-helpers.js +59 -0
  20. package/esm/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +60 -0
  21. package/esm/helpers/materialized-reports/scope-helpers.js +107 -0
  22. package/esm/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +251 -0
  23. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +860 -0
  24. package/esm/helpers/store/cart-actions.js +1 -1
  25. package/esm/helpers/store/common-tenant-purchase-order-actions.js +7 -7
  26. package/esm/helpers/store/common-warehouse-purchase-order-actions.js +1 -1
  27. package/esm/helpers/store/common-warehouse-purchase-order-rfq-actions.js +1 -1
  28. package/esm/helpers/store/common-warehouse-sale-order-actions.js +1 -1
  29. package/esm/helpers/store/common-warehouse-sale-order-rfq-actions.js +1 -1
  30. package/esm/helpers/store/offline-ordering.js +1 -1
  31. package/esm/helpers/store/tenant-purchase-orders-cart-actions.js +1 -1
  32. package/esm/helpers/store/warehouse-purchase-order-rfq-cart-actions.js +1 -1
  33. package/esm/helpers/store/warehouse-purchase-orders-cart-actions.js +1 -1
  34. package/esm/helpers/store/warehouse-sale-order-rfq-cart-actions.js +1 -1
  35. package/esm/helpers/store/warehouse-sale-orders-cart-actions.js +1 -1
  36. package/esm/helpers/utils/cancellation-helpers.js +7 -0
  37. package/esm/helpers/utils/common.js +0 -46
  38. package/esm/helpers/utils/getFormFieldsDiff.js +1 -1
  39. package/esm/helpers/utils/index.js +2 -0
  40. package/esm/helpers/utils/phone-helpers.js +40 -0
  41. package/esm/helpers/utils/receipt-engine.js +3 -1
  42. package/esm/helpers/utils/specials-helpers.js +1 -1
  43. package/esm/helpers/utils/void-items-report-helpers.js +2 -1
  44. package/esm/schemas/models/materialized_tenant_reports_iterations.js +82 -0
  45. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +399 -0
  46. package/esm/schemas/types/materialized_tenant_reports_iterations.js +1 -0
  47. package/esm/schemas/types/materialized_tenant_sales_overview_reports.js +1 -0
  48. package/lib/constants/ENUMS.d.ts +15 -1275
  49. package/lib/constants/ENUMS.js +31 -1994
  50. package/lib/constants/MATERIALIZED_REPORTS.d.ts +96 -0
  51. package/lib/constants/MATERIALIZED_REPORTS.js +108 -0
  52. package/lib/constants/enums/cash.d.ts +35 -0
  53. package/lib/constants/enums/cash.js +48 -0
  54. package/lib/constants/enums/communications.d.ts +79 -0
  55. package/lib/constants/enums/communications.js +332 -0
  56. package/lib/constants/enums/delivery.d.ts +26 -0
  57. package/lib/constants/enums/delivery.js +38 -0
  58. package/lib/constants/enums/geo.d.ts +133 -0
  59. package/lib/constants/enums/geo.js +153 -0
  60. package/lib/constants/enums/hr.d.ts +105 -0
  61. package/lib/constants/enums/hr.js +133 -0
  62. package/lib/constants/enums/internal.d.ts +104 -0
  63. package/lib/constants/enums/internal.js +135 -0
  64. package/lib/constants/enums/items.d.ts +94 -0
  65. package/lib/constants/enums/items.js +129 -0
  66. package/lib/constants/enums/misc.d.ts +25 -0
  67. package/lib/constants/enums/misc.js +38 -0
  68. package/lib/constants/enums/offers.d.ts +80 -0
  69. package/lib/constants/enums/offers.js +105 -0
  70. package/lib/constants/enums/order.d.ts +108 -0
  71. package/lib/constants/enums/order.js +138 -0
  72. package/lib/constants/enums/payments.d.ts +129 -0
  73. package/lib/constants/enums/payments.js +189 -0
  74. package/lib/constants/enums/platform.d.ts +100 -0
  75. package/lib/constants/enums/platform.js +218 -0
  76. package/lib/constants/enums/printing.d.ts +89 -0
  77. package/lib/constants/enums/printing.js +110 -0
  78. package/lib/constants/enums/users.d.ts +142 -0
  79. package/lib/constants/enums/users.js +248 -0
  80. package/lib/constants/enums/wallet.d.ts +26 -0
  81. package/lib/constants/enums/wallet.js +35 -0
  82. package/lib/helpers/materialized-reports/index.d.ts +5 -0
  83. package/lib/helpers/materialized-reports/index.js +21 -0
  84. package/lib/helpers/materialized-reports/key-helpers.d.ts +35 -0
  85. package/lib/helpers/materialized-reports/key-helpers.js +64 -0
  86. package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.d.ts +66 -0
  87. package/lib/helpers/materialized-reports/materialized-tenant-reports-iterations-helpers.js +63 -0
  88. package/lib/helpers/materialized-reports/scope-helpers.d.ts +57 -0
  89. package/lib/helpers/materialized-reports/scope-helpers.js +114 -0
  90. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.d.ts +125 -0
  91. package/lib/helpers/materialized-reports/tenant-sales-overview-close-day-helpers.js +256 -0
  92. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +223 -0
  93. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +875 -0
  94. package/lib/helpers/store/cart-actions.js +6 -6
  95. package/lib/helpers/store/common-tenant-purchase-order-actions.d.ts +2 -2
  96. package/lib/helpers/store/common-tenant-purchase-order-actions.js +10 -10
  97. package/lib/helpers/store/common-warehouse-purchase-order-actions.js +4 -4
  98. package/lib/helpers/store/common-warehouse-purchase-order-rfq-actions.js +4 -4
  99. package/lib/helpers/store/common-warehouse-sale-order-actions.js +4 -4
  100. package/lib/helpers/store/common-warehouse-sale-order-rfq-actions.js +4 -4
  101. package/lib/helpers/store/offline-ordering.js +2 -2
  102. package/lib/helpers/store/tenant-purchase-orders-cart-actions.js +2 -2
  103. package/lib/helpers/store/warehouse-purchase-order-rfq-cart-actions.js +2 -2
  104. package/lib/helpers/store/warehouse-purchase-orders-cart-actions.js +2 -2
  105. package/lib/helpers/store/warehouse-sale-order-rfq-cart-actions.js +2 -2
  106. package/lib/helpers/store/warehouse-sale-orders-cart-actions.js +2 -2
  107. package/lib/helpers/utils/cancellation-helpers.d.ts +1 -0
  108. package/lib/helpers/utils/cancellation-helpers.js +13 -0
  109. package/lib/helpers/utils/common.d.ts +0 -6
  110. package/lib/helpers/utils/common.js +1 -54
  111. package/lib/helpers/utils/getFormFieldsDiff.js +5 -2
  112. package/lib/helpers/utils/index.d.ts +2 -0
  113. package/lib/helpers/utils/index.js +2 -0
  114. package/lib/helpers/utils/phone-helpers.d.ts +5 -0
  115. package/lib/helpers/utils/phone-helpers.js +46 -0
  116. package/lib/helpers/utils/receipt-engine.js +4 -2
  117. package/lib/helpers/utils/specials-helpers.js +2 -2
  118. package/lib/helpers/utils/void-items-report-helpers.js +3 -2
  119. package/lib/schemas/models/materialized_tenant_reports_iterations.d.ts +80 -0
  120. package/lib/schemas/models/materialized_tenant_reports_iterations.js +85 -0
  121. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +569 -0
  122. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +402 -0
  123. package/lib/schemas/types/materialized_tenant_reports_iterations.d.ts +62 -0
  124. package/lib/schemas/types/materialized_tenant_reports_iterations.js +2 -0
  125. package/lib/schemas/types/materialized_tenant_sales_overview_reports.d.ts +242 -0
  126. package/lib/schemas/types/materialized_tenant_sales_overview_reports.js +3 -0
  127. package/lib/tests/materialized-reports/fixtures.d.ts +81 -0
  128. package/lib/tests/materialized-reports/fixtures.js +87 -0
  129. package/lib/tests/materialized-reports/fixtures.test.d.ts +1 -0
  130. package/lib/tests/materialized-reports/fixtures.test.js +123 -0
  131. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.d.ts +1 -0
  132. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-helpers.test.js +75 -0
  133. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.d.ts +1 -0
  134. package/lib/tests/materialized-reports/materialized-tenant-reports-iterations-schema.test.js +73 -0
  135. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.d.ts +1 -0
  136. package/lib/tests/materialized-reports/materialized-tenant-sales-overview-reports-schema.test.js +207 -0
  137. package/lib/tests/materialized-reports/sales-overview-baseline.test.d.ts +1 -0
  138. package/lib/tests/materialized-reports/sales-overview-baseline.test.js +326 -0
  139. package/lib/tests/materialized-reports/sales-overview-reference.d.ts +63 -0
  140. package/lib/tests/materialized-reports/sales-overview-reference.js +131 -0
  141. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.d.ts +1 -0
  142. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +335 -0
  143. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.d.ts +1 -0
  144. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +885 -0
  145. package/package.json +5 -2
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseMaterializedLocalDate = parseMaterializedLocalDate;
4
+ exports.getIsoWeekYear = getIsoWeekYear;
5
+ exports.getDayIndexFromLocalDate = getDayIndexFromLocalDate;
6
+ exports.getMaterializedPeriodScopeFields = getMaterializedPeriodScopeFields;
7
+ exports.getMaterializedHourScopeField = getMaterializedHourScopeField;
8
+ const ENUMS_1 = require("../../constants/ENUMS");
9
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
10
+ const time_helpers_1 = require("../utils/time-helpers");
11
+ /**
12
+ * Scope-field builders for materialized-report documents (see
13
+ * `MATERIALIZED_REPORTS.md` "Time scopes"). Given the tenant-local business
14
+ * date (`YYYY-MM-DD`) of a compiled day, these derive the `scope_field` value
15
+ * of every period scope plus the denormalized weekday.
16
+ *
17
+ * All math is pure UTC calendar arithmetic on the date string — independent of
18
+ * the server timezone. The hour scope (`'YYYY-MM-DD HH'`) is built per bucket
19
+ * via `getMaterializedHourScopeField`.
20
+ *
21
+ * Validation convention: builders return `null` instead of throwing — a `null`
22
+ * result means the caller passed invalid data.
23
+ */
24
+ const LOCAL_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
25
+ const pad = (value) => String(value).padStart(2, '0');
26
+ /**
27
+ * Parses + validates a `'YYYY-MM-DD'` local date into its numeric parts.
28
+ * Returns `null` (never throws) for malformed dates — `null` means the caller
29
+ * passed invalid data.
30
+ */
31
+ function parseMaterializedLocalDate(localDate) {
32
+ if (typeof localDate !== 'string' || !LOCAL_DATE_PATTERN.test(localDate)) {
33
+ return null;
34
+ }
35
+ const [year, month, day] = localDate.split('-').map(Number);
36
+ if (month < 1 || month > 12 || day < 1 || day > 31) {
37
+ return null;
38
+ }
39
+ // Real-calendar check: impossible dates (e.g. '2026-02-31') must never slip
40
+ // through — `Date.UTC` rollover would silently derive WRONG scope fields
41
+ // (week/day_index pointing into the next month).
42
+ const utc = new Date(Date.UTC(year, month - 1, day));
43
+ if (utc.getUTCFullYear() !== year || utc.getUTCMonth() !== month - 1 || utc.getUTCDate() !== day) {
44
+ return null;
45
+ }
46
+ return { year, month, day };
47
+ }
48
+ /**
49
+ * ISO 8601 week-year of a local date — the year of the Thursday of that date's
50
+ * ISO week. Differs from the calendar year for boundary weeks (e.g.
51
+ * `'2027-01-01'` is `2026-W53`), which is exactly why `'YYYY-Wnn'` scope
52
+ * fields need it. Returns `null` for malformed dates.
53
+ */
54
+ function getIsoWeekYear(localDate) {
55
+ const parts = parseMaterializedLocalDate(localDate);
56
+ return parts != null ? getIsoWeekYearFromParts(parts) : null;
57
+ }
58
+ function getIsoWeekYearFromParts({ year, month, day }) {
59
+ const date = new Date(Date.UTC(year, month - 1, day));
60
+ const isoWeekday = date.getUTCDay() || 7; // Monday = 1 … Sunday = 7
61
+ date.setUTCDate(date.getUTCDate() + 4 - isoWeekday); // move to the ISO week's Thursday
62
+ return date.getUTCFullYear();
63
+ }
64
+ /**
65
+ * Denormalized weekday (`DAY_INDEX_ENUM`) of a local date. Returns `null`
66
+ * (never throws) for malformed dates.
67
+ */
68
+ function getDayIndexFromLocalDate(localDate) {
69
+ const parts = parseMaterializedLocalDate(localDate);
70
+ if (parts == null)
71
+ return null;
72
+ return ENUMS_1.ALL_DAY_INDEX[new Date(Date.UTC(parts.year, parts.month - 1, parts.day)).getUTCDay()];
73
+ }
74
+ /**
75
+ * Builds the `scope_field` of every period scope for a compiled local date:
76
+ *
77
+ * - `localDate`: `'2026-09-30'`
78
+ * - `localWeek`: Sun–Sat week start (the calendar UI convention —
79
+ * `getCalendarWeekStart(date, 0)`) → `'2026-09-27'`
80
+ * - `localWeekOfYear`: ISO week `'YYYY-Wnn'` where `YYYY` is the ISO week-year
81
+ * - `localMonth`: `'2026-09'`
82
+ * - `localQuarter`: `'2026-Q3'`
83
+ * - `localSemester`: `'2026-S2'`
84
+ * - `localYear`: `'2026'`
85
+ *
86
+ * Returns `null` (never throws) for malformed dates.
87
+ */
88
+ function getMaterializedPeriodScopeFields(localDate) {
89
+ const parts = parseMaterializedLocalDate(localDate);
90
+ if (parts == null)
91
+ return null;
92
+ const { year, month, day } = parts;
93
+ return {
94
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE]: localDate,
95
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK]: (0, time_helpers_1.getCalendarWeekStart)(localDate, 0),
96
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR]: `${getIsoWeekYearFromParts(parts)}-W${pad((0, time_helpers_1.getIsoWeekOfYear)(year, month, day))}`,
97
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH]: `${year}-${pad(month)}`,
98
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER]: `${year}-Q${Math.ceil(month / 3)}`,
99
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER]: `${year}-S${month <= 6 ? 1 : 2}`,
100
+ [MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR]: `${year}`,
101
+ };
102
+ }
103
+ /**
104
+ * `scope_field` of a `localHour` bucket — `'2026-09-30 18'` (zero-padded).
105
+ * Returns `null` (never throws) for a malformed local date or an out-of-range
106
+ * hour.
107
+ */
108
+ function getMaterializedHourScopeField(localDate, hour) {
109
+ if (parseMaterializedLocalDate(localDate) == null)
110
+ return null;
111
+ if (!Number.isInteger(hour) || hour < 0 || hour > 23)
112
+ return null;
113
+ return `${localDate} ${pad(hour)}`;
114
+ }
@@ -0,0 +1,125 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { IMaterializedTenantReportIterationInput } from '../../schemas/types/materialized_tenant_reports_iterations';
3
+ import { IMaterializedTenantSalesOverviewReport } from '../../schemas/types/materialized_tenant_sales_overview_reports';
4
+ import { IConvertOrdersToMaterializedReportsResult } from './tenant-sales-overview-helpers';
5
+ /**
6
+ * Close-day planning for `materialized_tenant_sales_overview_reports` (see
7
+ * `MATERIALIZED_REPORTS.md` “Backend materialization cycle”).
8
+ *
9
+ * The day-close job compiles one tenant-day (`convertOrdersTo…`), fetches the
10
+ * stored documents the plan needs (`getMaterializedTenantSalesOverviewScopeRefsForDay`
11
+ * + the issue-day docs of collected bills), and asks this module for the
12
+ * complete write plan:
13
+ *
14
+ * - **`writes`** — hour + date documents (insert, or `replacement` when stored
15
+ * so `iteration` bumps without `_id` churn) and the six accumulated period
16
+ * documents (`additions`, or — when the day was previously folded —
17
+ * `subtract` the stored day delta first). Each write carries its
18
+ * `materialized_tenant_reports_iterations` history row; persist both.
19
+ * - **`staleHourDocuments`** — stored `localHour` docs of the day with no
20
+ * activity anymore (orders deleted / moved) — delete by `_id`.
21
+ * - **`receivedPatches`** — issue-day docs holding bills collected on the
22
+ * compiled day, patched through `update(…, { received_payments })`. A
23
+ * ledger-changing patch is a versioned write, so each patched document
24
+ * comes with its history row; computed against the POST-write documents,
25
+ * so a period doc that both accumulates the day and holds an earlier bill
26
+ * keeps the accumulation — persist them AFTER `writes`.
27
+ * - **`skippedDocuments`** — already up to date (see
28
+ * `needsMaterializedTenantSalesOverviewReportWrite`).
29
+ * - **`createdPeriodDocuments`** — period docs that were absent from
30
+ * `existing` and are created by this close (also present in `writes`): a
31
+ * first materialized close of the period, an order-less prefix, or a
32
+ * genuinely missing document — in the last case the caller must alert and
33
+ * run the documented period backfill (a deleted doc cannot be reconstructed
34
+ * from one day's delta alone).
35
+ *
36
+ * The watermark guard skips nothing when `force` is set (repairs / schema
37
+ * rollouts). Helpers never throw — invalid input returns `null`.
38
+ */
39
+ /** Options of `buildTenantSalesOverviewCloseDayPlan`. */
40
+ export interface IBuildTenantSalesOverviewCloseDayPlanInput {
41
+ /** Tenant the compile belongs to (one plan = one tenant-day). */
42
+ tenantId: string;
43
+ /** The tenant-day compile (`convertOrdersToMaterializedTenantSalesOverviewReports`). */
44
+ compile: IConvertOrdersToMaterializedReportsResult;
45
+ /**
46
+ * Why this close is applied — stored as the `reason` of every history row
47
+ * the plan produces (`NEW_DAY`, `RECLOSE`, `RECONCILE`, …). Required: the
48
+ * iteration history must always explain itself.
49
+ */
50
+ reason: string;
51
+ /**
52
+ * Stored documents the job fetched: the compiled scopes that already exist
53
+ * plus, for every collected bill's `issued_local_date`, that day's stored
54
+ * documents (`getMaterializedTenantSalesOverviewScopeRefsForDay`). Pass
55
+ * plain JSON (`.lean()` recommended — a hydrated document's map-cast
56
+ * `sale_type_metrics` is normalized defensively, but its other mongoose
57
+ * internals are not supported). Repeating the SAME document (overlapping
58
+ * fetch refs) is fine; two different rows for one scope key → `null`.
59
+ */
60
+ existing?: IMaterializedTenantSalesOverviewReport[];
61
+ /** Force structural writes even when the watermarks are up to date. */
62
+ force?: boolean;
63
+ /** Override for write timestamps (tests, replays). */
64
+ computedAt?: Date;
65
+ }
66
+ /** One versioned write (structural write or ledger-changing patch): persist `report` + upsert its history row. */
67
+ export interface ITenantSalesOverviewCloseDayWrite {
68
+ /** Post-write document (stored `_id` kept for replacements). */
69
+ report: IMaterializedTenantSalesOverviewReport;
70
+ /** `materialized_tenant_reports_iterations` row — upsert by `(report_id, iteration)`. */
71
+ iteration: IMaterializedTenantReportIterationInput;
72
+ }
73
+ /** The complete close-day write plan (see the module docs). */
74
+ export interface ITenantSalesOverviewCloseDayPlan {
75
+ /** Structural writes (report + history row) — persist in any order. */
76
+ writes: ITenantSalesOverviewCloseDayWrite[];
77
+ /** Stored hour docs of the compiled day no longer backed by activity — delete by `_id`. */
78
+ staleHourDocuments: IMaterializedTenantSalesOverviewReport[];
79
+ /** Issued-ledger patches (versioned writes) — persist AFTER `writes`. */
80
+ receivedPatches: ITenantSalesOverviewCloseDayWrite[];
81
+ /** Stored docs that were already up to date (job logging). */
82
+ skippedDocuments: IMaterializedTenantSalesOverviewReport[];
83
+ /**
84
+ * Period-scope documents this close CREATED because they were absent from
85
+ * `existing` — a first materialized close of the period (including when
86
+ * earlier days of the period were order-less), or a document that is simply
87
+ * missing. A missing document folds only the closing day's delta: if
88
+ * earlier days of the period were already materialized, run the documented
89
+ * period backfill — a deleted document cannot be reconstructed from one
90
+ * day. These writes are also present in `writes`; alert on a non-empty list
91
+ * when the day is not the period's first materialized close.
92
+ */
93
+ createdPeriodDocuments: IMaterializedReportScopeRef[];
94
+ }
95
+ /** `(scope_context, scope_field)` pair of a stored / compiled document. */
96
+ export interface IMaterializedReportScopeRef {
97
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
98
+ scope_field: string;
99
+ }
100
+ /**
101
+ * Every stored scope the fan-out of one local day needs: the six period
102
+ * scopes + `localDate` of that day and all 24 `localHour` buckets (`null` for
103
+ * a malformed date). A bill's hour is unknowable from the received entry
104
+ * alone, so settlement patches always consider the whole day.
105
+ */
106
+ export declare function getMaterializedTenantSalesOverviewScopeRefsForDay(localDate: string): IMaterializedReportScopeRef[] | null;
107
+ /**
108
+ * Watermark guard of the write path: does the stored document need a
109
+ * structural write for the incoming compiled version?
110
+ *
111
+ * `false` (skip) when the incoming `source_watermark` is not newer than the
112
+ * stored one and the schema version + key-filter grammar match. Watermarks are
113
+ * monotonic (`updateMaterializedTenantSalesOverviewReport` never regresses
114
+ * them). A missing stored document always needs a write.
115
+ */
116
+ export declare function needsMaterializedTenantSalesOverviewReportWrite(existing: IMaterializedTenantSalesOverviewReport | null | undefined, incoming: IMaterializedTenantSalesOverviewReport | null | undefined): boolean;
117
+ /**
118
+ * Builds the close-day write plan for ONE tenant-day (see the module docs).
119
+ * Returns `null` (never throws) when the input is inconsistent — compiled
120
+ * docs of another tenant, duplicate compiled scope documents, a malformed
121
+ * `localDate`, duplicate STORED rows for one scope key (missing unique index
122
+ * — a data issue to fix, never silently deduplicated), or a merge conflict
123
+ * with a stored document (schema / brand).
124
+ */
125
+ export declare function buildTenantSalesOverviewCloseDayPlan(input: IBuildTenantSalesOverviewCloseDayPlanInput | null | undefined): ITenantSalesOverviewCloseDayPlan | null;
@@ -0,0 +1,256 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMaterializedTenantSalesOverviewScopeRefsForDay = getMaterializedTenantSalesOverviewScopeRefsForDay;
4
+ exports.needsMaterializedTenantSalesOverviewReportWrite = needsMaterializedTenantSalesOverviewReportWrite;
5
+ exports.buildTenantSalesOverviewCloseDayPlan = buildTenantSalesOverviewCloseDayPlan;
6
+ const constants_1 = require("../../constants");
7
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
8
+ const materialized_tenant_reports_iterations_helpers_1 = require("./materialized-tenant-reports-iterations-helpers");
9
+ const scope_helpers_1 = require("./scope-helpers");
10
+ const tenant_sales_overview_helpers_1 = require("./tenant-sales-overview-helpers");
11
+ /** Scopes written wholesale for the compiled day (replacement semantics). */
12
+ const CLOSE_DAY_DAY_SCOPES = [
13
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR,
14
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
15
+ ];
16
+ /** Scopes that accumulate day deltas (subtract the stored delta, add the fresh one). */
17
+ const CLOSE_DAY_ACCUMULATED_SCOPES = [
18
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
19
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
20
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
21
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
22
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
23
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
24
+ ];
25
+ const materializedScopeKey = (doc) => `${doc.scope_context}|${doc.scope_field}`;
26
+ const materializedCreditBillKey = (orderId, paymentId) => `${orderId}|${paymentId}`;
27
+ const hasMaterializedMetrics = (doc) => Object.keys((0, tenant_sales_overview_helpers_1.normalizeMaterializedSaleTypeMetrics)(doc.sale_type_metrics)).length > 0;
28
+ /**
29
+ * Every stored scope the fan-out of one local day needs: the six period
30
+ * scopes + `localDate` of that day and all 24 `localHour` buckets (`null` for
31
+ * a malformed date). A bill's hour is unknowable from the received entry
32
+ * alone, so settlement patches always consider the whole day.
33
+ */
34
+ function getMaterializedTenantSalesOverviewScopeRefsForDay(localDate) {
35
+ const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
36
+ if (periodFields == null)
37
+ return null;
38
+ const refs = [];
39
+ for (const scopeContext of Object.keys(periodFields)) {
40
+ refs.push({
41
+ scope_context: scopeContext,
42
+ scope_field: periodFields[scopeContext],
43
+ });
44
+ }
45
+ for (let hour = 0; hour < 24; hour++) {
46
+ const scopeField = (0, scope_helpers_1.getMaterializedHourScopeField)(localDate, hour);
47
+ if (scopeField == null)
48
+ return null;
49
+ refs.push({ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR, scope_field: scopeField });
50
+ }
51
+ return refs;
52
+ }
53
+ /**
54
+ * Watermark guard of the write path: does the stored document need a
55
+ * structural write for the incoming compiled version?
56
+ *
57
+ * `false` (skip) when the incoming `source_watermark` is not newer than the
58
+ * stored one and the schema version + key-filter grammar match. Watermarks are
59
+ * monotonic (`updateMaterializedTenantSalesOverviewReport` never regresses
60
+ * them). A missing stored document always needs a write.
61
+ */
62
+ function needsMaterializedTenantSalesOverviewReportWrite(existing, incoming) {
63
+ if (existing == null || incoming == null)
64
+ return true;
65
+ if (existing.schema_version !== incoming.schema_version)
66
+ return true;
67
+ if ((existing.sale_type_key_filters ?? []).join(':') !== (incoming.sale_type_key_filters ?? []).join(':')) {
68
+ return true;
69
+ }
70
+ const existingTime = new Date(existing.source_watermark ?? 0).getTime();
71
+ const incomingTime = new Date(incoming.source_watermark ?? 0).getTime();
72
+ if (Number.isNaN(existingTime) || Number.isNaN(incomingTime))
73
+ return true;
74
+ return incomingTime > existingTime;
75
+ }
76
+ /** Would a received-payment patch change the stored bill? (settlement/note/received) */
77
+ const creditBillWouldChange = (bill, collected) => {
78
+ const received = Math.max(bill.received_amount ?? 0, collected.received_amount ?? 0);
79
+ if (received !== (bill.received_amount ?? 0))
80
+ return true;
81
+ const note = bill.credit_note ?? collected.credit_note;
82
+ if ((note ?? null) !== (bill.credit_note ?? null))
83
+ return true;
84
+ return bill.settled_at == null && received >= (bill.amount ?? 0);
85
+ };
86
+ /** Does the document hold an issued bill that one of the collected payments would change? */
87
+ const documentHoldsUnpatchedCreditBill = (doc, collectedByBill) => {
88
+ for (const keyMetrics of Object.values((0, tenant_sales_overview_helpers_1.normalizeMaterializedSaleTypeMetrics)(doc.sale_type_metrics))) {
89
+ for (const bill of keyMetrics?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]?.issued?.bills ?? []) {
90
+ const collected = collectedByBill.get(materializedCreditBillKey(bill.order_id, bill.payment_id));
91
+ if (collected != null && creditBillWouldChange(bill, collected))
92
+ return true;
93
+ }
94
+ }
95
+ return false;
96
+ };
97
+ /**
98
+ * Builds the close-day write plan for ONE tenant-day (see the module docs).
99
+ * Returns `null` (never throws) when the input is inconsistent — compiled
100
+ * docs of another tenant, duplicate compiled scope documents, a malformed
101
+ * `localDate`, duplicate STORED rows for one scope key (missing unique index
102
+ * — a data issue to fix, never silently deduplicated), or a merge conflict
103
+ * with a stored document (schema / brand).
104
+ */
105
+ function buildTenantSalesOverviewCloseDayPlan(input) {
106
+ if (input == null)
107
+ return null;
108
+ const { tenantId, compile, reason } = input;
109
+ if (typeof tenantId !== 'string' || tenantId.length === 0)
110
+ return null;
111
+ if (compile == null)
112
+ return null;
113
+ if (typeof reason !== 'string' || reason.length === 0)
114
+ return null;
115
+ const compiledReports = compile.materializedReports ?? [];
116
+ if (compiledReports.some((doc) => doc == null || doc.tenant_id !== tenantId))
117
+ return null;
118
+ const computedAt = input.computedAt ?? new Date();
119
+ const force = input.force === true;
120
+ const compiledByScope = new Map();
121
+ for (const doc of compiledReports) {
122
+ const key = materializedScopeKey(doc);
123
+ if (compiledByScope.has(key))
124
+ return null; // duplicate scope doc — data issue
125
+ compiledByScope.set(key, doc);
126
+ }
127
+ const compiledDateDoc = compiledReports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE) ?? null;
128
+ if (compiledDateDoc == null)
129
+ return null;
130
+ const localDate = compiledDateDoc.scope_field;
131
+ if (getMaterializedTenantSalesOverviewScopeRefsForDay(localDate) == null)
132
+ return null;
133
+ const existingByScope = new Map();
134
+ for (const doc of input.existing ?? []) {
135
+ if (doc == null || doc.tenant_id !== tenantId)
136
+ continue;
137
+ const key = materializedScopeKey(doc);
138
+ const prior = existingByScope.get(key);
139
+ if (prior == null) {
140
+ existingByScope.set(key, doc);
141
+ continue;
142
+ }
143
+ // Repeating the SAME document (overlapping fetch refs) is fine; two
144
+ // different rows for one scope key mean the unique index is missing.
145
+ // String comparison keeps hydrated ObjectId `_id`s compatible with plain ids.
146
+ if (String(prior._id) !== String(doc._id))
147
+ return null;
148
+ }
149
+ const storedDateDoc = existingByScope.get(materializedScopeKey(compiledDateDoc)) ?? null;
150
+ const dayChanged = force || needsMaterializedTenantSalesOverviewReportWrite(storedDateDoc, compiledDateDoc);
151
+ const dayDeltaEmpty = !hasMaterializedMetrics(compiledDateDoc);
152
+ const writes = [];
153
+ const skippedDocuments = [];
154
+ const createdPeriodDocuments = [];
155
+ const addStructuralWrite = (report) => {
156
+ const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(report, {
157
+ reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
158
+ reason,
159
+ computedAt,
160
+ });
161
+ if (iteration == null)
162
+ return false;
163
+ writes.push({ report, iteration });
164
+ return true;
165
+ };
166
+ for (const compiledDoc of compiledReports) {
167
+ const existing = existingByScope.get(materializedScopeKey(compiledDoc)) ?? null;
168
+ if (CLOSE_DAY_DAY_SCOPES.includes(compiledDoc.scope_context)) {
169
+ if (!dayChanged) {
170
+ if (existing != null)
171
+ skippedDocuments.push(existing);
172
+ // Partial-failure repair: the day is up to date but this scope doc was never persisted.
173
+ else if (!addStructuralWrite(compiledDoc))
174
+ return null;
175
+ continue;
176
+ }
177
+ if (existing == null) {
178
+ if (!addStructuralWrite(compiledDoc))
179
+ return null;
180
+ }
181
+ else {
182
+ const updated = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(existing, { replacement: compiledDoc }, { computedAt });
183
+ if (updated == null || !addStructuralWrite(updated))
184
+ return null;
185
+ }
186
+ continue;
187
+ }
188
+ if (!CLOSE_DAY_ACCUMULATED_SCOPES.includes(compiledDoc.scope_context))
189
+ return null; // unknown scope — data issue
190
+ if (existing == null) {
191
+ if (dayDeltaEmpty)
192
+ continue; // nothing to fold into a (new) period document
193
+ if (!addStructuralWrite(compiledDoc))
194
+ return null;
195
+ createdPeriodDocuments.push({
196
+ scope_context: compiledDoc.scope_context,
197
+ scope_field: compiledDoc.scope_field,
198
+ });
199
+ continue;
200
+ }
201
+ if (!dayChanged) {
202
+ skippedDocuments.push(existing);
203
+ continue;
204
+ }
205
+ if (dayDeltaEmpty && storedDateDoc == null) {
206
+ skippedDocuments.push(existing); // first close of an order-less day — nothing to fold
207
+ continue;
208
+ }
209
+ const updated = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(existing, { subtract: storedDateDoc != null ? [storedDateDoc] : [], additions: [compiledDoc] }, { computedAt });
210
+ if (updated == null || !addStructuralWrite(updated))
211
+ return null;
212
+ }
213
+ // Orders deleted / moved shrank the day's active hours — drop the stale docs.
214
+ const staleHourDocuments = dayChanged
215
+ ? Array.from(existingByScope.values()).filter((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR &&
216
+ typeof doc.scope_field === 'string' &&
217
+ doc.scope_field.startsWith(`${localDate} `) &&
218
+ !compiledByScope.has(materializedScopeKey(doc)))
219
+ : [];
220
+ // Collected bills patch the ISSUE-day docs that still hold the issued
221
+ // ledger. Compute the patches against the POST-write documents — a period
222
+ // doc that both accumulates the day and holds an earlier issued bill must
223
+ // keep the accumulation in its patched version (persist patches AFTER
224
+ // writes).
225
+ const postWriteByScope = new Map();
226
+ for (const doc of existingByScope.values())
227
+ postWriteByScope.set(materializedScopeKey(doc), doc);
228
+ for (const write of writes)
229
+ postWriteByScope.set(materializedScopeKey(write.report), write.report);
230
+ for (const stale of staleHourDocuments)
231
+ postWriteByScope.delete(materializedScopeKey(stale));
232
+ const receivedPatches = [];
233
+ const receivedPayments = compile.received_payments ?? [];
234
+ if (receivedPayments.length > 0) {
235
+ const collectedByBill = new Map();
236
+ for (const collected of receivedPayments) {
237
+ collectedByBill.set(materializedCreditBillKey(collected.order_id, collected.payment_id), collected);
238
+ }
239
+ for (const doc of postWriteByScope.values()) {
240
+ if (!documentHoldsUnpatchedCreditBill(doc, collectedByBill))
241
+ continue;
242
+ const patched = (0, tenant_sales_overview_helpers_1.updateMaterializedTenantSalesOverviewReport)(doc, { received_payments: receivedPayments }, { computedAt });
243
+ if (patched == null)
244
+ return null;
245
+ const iteration = (0, materialized_tenant_reports_iterations_helpers_1.buildMaterializedTenantReportIteration)(patched, {
246
+ reportType: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_SALES_OVERVIEW,
247
+ reason,
248
+ computedAt,
249
+ });
250
+ if (iteration == null)
251
+ return null;
252
+ receivedPatches.push({ report: patched, iteration });
253
+ }
254
+ }
255
+ return { writes, staleHourDocuments, receivedPatches, skippedDocuments, createdPeriodDocuments };
256
+ }