@managesome/eposmatic-toolkit 0.4.61 → 0.4.62

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 (38) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +77 -0
  2. package/esm/constants/TENANT_ENUMS.js +15 -0
  3. package/esm/constants/WORKER_ENDPOINTS.js +12 -0
  4. package/esm/helpers/materialized-reports/index.js +1 -0
  5. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +3 -1
  6. package/esm/helpers/materialized-reports/materialized-report-runs.js +143 -0
  7. package/esm/schemas/models/index.js +1 -0
  8. package/esm/schemas/models/materialized_tenant_report_runs.js +105 -0
  9. package/esm/schemas/models/tenant_active_jobs.js +19 -1
  10. package/esm/schemas/types/index.js +1 -0
  11. package/esm/schemas/types/materialized_tenant_report_runs.js +1 -0
  12. package/lib/constants/MATERIALIZED_REPORTS.d.ts +69 -0
  13. package/lib/constants/MATERIALIZED_REPORTS.js +78 -1
  14. package/lib/constants/TENANT_ENUMS.d.ts +14 -0
  15. package/lib/constants/TENANT_ENUMS.js +16 -1
  16. package/lib/constants/WORKER_ENDPOINTS.d.ts +12 -0
  17. package/lib/constants/WORKER_ENDPOINTS.js +12 -0
  18. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  19. package/lib/helpers/materialized-reports/index.js +1 -0
  20. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +2 -0
  21. package/lib/helpers/materialized-reports/materialized-report-runs.d.ts +105 -0
  22. package/lib/helpers/materialized-reports/materialized-report-runs.js +156 -0
  23. package/lib/helpers/types/workers.d.ts +65 -0
  24. package/lib/schemas/models/index.d.ts +1 -0
  25. package/lib/schemas/models/index.js +1 -0
  26. package/lib/schemas/models/materialized_tenant_report_runs.d.ts +97 -0
  27. package/lib/schemas/models/materialized_tenant_report_runs.js +108 -0
  28. package/lib/schemas/models/tenant_active_jobs.d.ts +12 -3
  29. package/lib/schemas/models/tenant_active_jobs.js +18 -0
  30. package/lib/schemas/types/index.d.ts +1 -0
  31. package/lib/schemas/types/index.js +1 -0
  32. package/lib/schemas/types/materialized_tenant_report_runs.d.ts +55 -0
  33. package/lib/schemas/types/materialized_tenant_report_runs.js +2 -0
  34. package/lib/schemas/types/tenant_active_jobs.d.ts +15 -1
  35. package/lib/tests/materialized-reports/materialized-report-runs.test.d.ts +1 -0
  36. package/lib/tests/materialized-reports/materialized-report-runs.test.js +116 -0
  37. package/lib/tests/materialized-reports/tenant-dinein-formatter.test.js +159 -0
  38. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ALL_TENANT_ACTIVE_JOBS_NAMES = exports.TENANT_ACTIVE_JOBS_ENUM = exports.ALL_TENANT_ACTIVITY_LOG_SEVERITY_NAMES = exports.TENANT_ACTIVITY_LOG_SEVERITY_ENUM = exports.ALL_TENANT_ACTIVITY_LOG_ACTION_NAMES = exports.TENANT_ACTIVITY_LOG_ACTION_ENUM = exports.ALL_TENANT_ACTIVITY_LOG_ENTITY_TYPE_NAMES = exports.TENANT_ACTIVITY_LOG_ENTITY_TYPE_ENUM = exports.ALL_TENANT_PURCHASE_ORDER_VENDOR_RETURN_STATUS_NAMES = exports.TENANT_PURCHASE_ORDER_VENDOR_RETURN_STATUS_ENUM = exports.ALL_TENANT_PURCHASE_ORDER_STATUS_NAMES = exports.TENANT_PURCHASE_ORDER_STATUS_ENUM = void 0;
3
+ exports.ALL_TENANT_DAY_JOB_OUTCOMES = exports.TENANT_DAY_JOB_OUTCOME_ENUM = exports.ALL_TENANT_ACTIVE_JOBS_NAMES = exports.TENANT_ACTIVE_JOBS_ENUM = exports.ALL_TENANT_ACTIVITY_LOG_SEVERITY_NAMES = exports.TENANT_ACTIVITY_LOG_SEVERITY_ENUM = exports.ALL_TENANT_ACTIVITY_LOG_ACTION_NAMES = exports.TENANT_ACTIVITY_LOG_ACTION_ENUM = exports.ALL_TENANT_ACTIVITY_LOG_ENTITY_TYPE_NAMES = exports.TENANT_ACTIVITY_LOG_ENTITY_TYPE_ENUM = exports.ALL_TENANT_PURCHASE_ORDER_VENDOR_RETURN_STATUS_NAMES = exports.TENANT_PURCHASE_ORDER_VENDOR_RETURN_STATUS_ENUM = exports.ALL_TENANT_PURCHASE_ORDER_STATUS_NAMES = exports.TENANT_PURCHASE_ORDER_STATUS_ENUM = void 0;
4
4
  // ======================>> TENANT PURCHASE ORDER <<====================== //
5
5
  var TENANT_PURCHASE_ORDER_STATUS_ENUM;
6
6
  (function (TENANT_PURCHASE_ORDER_STATUS_ENUM) {
@@ -91,3 +91,18 @@ var TENANT_ACTIVE_JOBS_ENUM;
91
91
  TENANT_ACTIVE_JOBS_ENUM["Z_REPORT"] = "Z_REPORT";
92
92
  })(TENANT_ACTIVE_JOBS_ENUM || (exports.TENANT_ACTIVE_JOBS_ENUM = TENANT_ACTIVE_JOBS_ENUM = {}));
93
93
  exports.ALL_TENANT_ACTIVE_JOBS_NAMES = Object.values(TENANT_ACTIVE_JOBS_ENUM);
94
+ /**
95
+ * Terminal outcome of ONE close/retry run that owned the tenant's CALENDAR job.
96
+ *
97
+ * `PARTIAL` is the per-report model's outcome: at least one report FAILED while
98
+ * others committed. It is NEVER a readiness status - readiness keeps only
99
+ * COMMITTED / NEEDS_RECONCILIATION; the failed report lives in the operational
100
+ * run ledger (`materialized_tenant_report_runs`).
101
+ */
102
+ var TENANT_DAY_JOB_OUTCOME_ENUM;
103
+ (function (TENANT_DAY_JOB_OUTCOME_ENUM) {
104
+ TENANT_DAY_JOB_OUTCOME_ENUM["COMPLETED"] = "COMPLETED";
105
+ TENANT_DAY_JOB_OUTCOME_ENUM["PARTIAL"] = "PARTIAL";
106
+ TENANT_DAY_JOB_OUTCOME_ENUM["FAILED"] = "FAILED";
107
+ })(TENANT_DAY_JOB_OUTCOME_ENUM || (exports.TENANT_DAY_JOB_OUTCOME_ENUM = TENANT_DAY_JOB_OUTCOME_ENUM = {}));
108
+ exports.ALL_TENANT_DAY_JOB_OUTCOMES = Object.values(TENANT_DAY_JOB_OUTCOME_ENUM);
@@ -65,4 +65,16 @@ export declare const WORKER_ENDPOINTS: {
65
65
  readonly POST_WAREHOUSE_ACTIVITY_LOGS: "/post-warehouse-activity-logs";
66
66
  readonly END_INSTORE_SHIFT: "/end-instore-shift";
67
67
  readonly END_TENANT_DAY: "/end-tenant-day";
68
+ /**
69
+ * INTERNAL, report-scoped retry of ONE failed END_TENANT_DAY report.
70
+ * Operations-service is the only caller (POST /materialization/reports/retry).
71
+ * Never a whole-day retry.
72
+ */
73
+ readonly RETRY_MATERIALIZED_REPORT: "/internal/materialization/reports/retry";
74
+ /**
75
+ * INTERNAL, worker-owned recovery of INTERRUPTED report runs (RUNNING /
76
+ * RETRYING). Called before the retry API rejects a RUNNING report and before
77
+ * listing runs for the admin page. Never fabricates readiness.
78
+ */
79
+ readonly RECONCILE_MATERIALIZED_REPORT_RUNS: "/internal/materialization/reports/reconcile";
68
80
  };
@@ -80,4 +80,16 @@ exports.WORKER_ENDPOINTS = {
80
80
  // ========================>> Shift / Business Day / Cash Drawer (compile) <<======================= //
81
81
  END_INSTORE_SHIFT: '/end-instore-shift',
82
82
  END_TENANT_DAY: '/end-tenant-day',
83
+ /**
84
+ * INTERNAL, report-scoped retry of ONE failed END_TENANT_DAY report.
85
+ * Operations-service is the only caller (POST /materialization/reports/retry).
86
+ * Never a whole-day retry.
87
+ */
88
+ RETRY_MATERIALIZED_REPORT: '/internal/materialization/reports/retry',
89
+ /**
90
+ * INTERNAL, worker-owned recovery of INTERRUPTED report runs (RUNNING /
91
+ * RETRYING). Called before the retry API rejects a RUNNING report and before
92
+ * listing runs for the admin page. Never fabricates readiness.
93
+ */
94
+ RECONCILE_MATERIALIZED_REPORT_RUNS: '/internal/materialization/reports/reconcile',
83
95
  };
@@ -1,6 +1,7 @@
1
1
  export * from './key-helpers';
2
2
  export * from './materialized-credit-bills-helpers';
3
3
  export * from './materialized-day-readiness';
4
+ export * from './materialized-report-runs';
4
5
  export * from './materialized-index-bootstrap';
5
6
  export * from './materialized-integer-contract';
6
7
  export * from './materialized-discount-accumulator-helpers';
@@ -17,6 +17,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./key-helpers"), exports);
18
18
  __exportStar(require("./materialized-credit-bills-helpers"), exports);
19
19
  __exportStar(require("./materialized-day-readiness"), exports);
20
+ __exportStar(require("./materialized-report-runs"), exports);
20
21
  __exportStar(require("./materialized-index-bootstrap"), exports);
21
22
  __exportStar(require("./materialized-integer-contract"), exports);
22
23
  __exportStar(require("./materialized-discount-accumulator-helpers"), exports);
@@ -20,6 +20,7 @@ const materialized_tenant_discount_reports_1 = require("../../schemas/models/mat
20
20
  const materialized_tenant_discount_sources_1 = require("../../schemas/models/materialized_tenant_discount_sources");
21
21
  const materialized_tenant_prep_time_entries_1 = require("../../schemas/models/materialized_tenant_prep_time_entries");
22
22
  const materialized_tenant_prep_time_reports_1 = require("../../schemas/models/materialized_tenant_prep_time_reports");
23
+ const materialized_tenant_report_runs_1 = require("../../schemas/models/materialized_tenant_report_runs");
23
24
  const materialized_tenant_reports_iterations_1 = require("../../schemas/models/materialized_tenant_reports_iterations");
24
25
  const materialized_tenant_sales_overview_reports_1 = require("../../schemas/models/materialized_tenant_sales_overview_reports");
25
26
  const tenant_active_jobs_1 = require("../../schemas/models/tenant_active_jobs");
@@ -47,6 +48,7 @@ const INDEXES = {
47
48
  [materialized_tenant_discount_sources_1.MATERIALIZED_TENANT_DISCOUNT_SOURCES_COLLECTION_NAME]: materialized_tenant_discount_sources_1.MATERIALIZED_TENANT_DISCOUNT_SOURCES_INDEX_OPTIONS,
48
49
  [materialized_tenant_prep_time_reports_1.MATERIALIZED_TENANT_PREP_TIME_REPORTS_COLLECTION_NAME]: materialized_tenant_prep_time_reports_1.MATERIALIZED_TENANT_PREP_TIME_REPORTS_INDEX_OPTIONS,
49
50
  [materialized_tenant_prep_time_entries_1.MATERIALIZED_TENANT_PREP_TIME_ENTRIES_COLLECTION_NAME]: materialized_tenant_prep_time_entries_1.MATERIALIZED_TENANT_PREP_TIME_ENTRIES_INDEX_OPTIONS,
51
+ [MATERIALIZED_REPORTS_2.MATERIALIZED_TENANT_REPORT_RUNS_COLLECTION_NAME]: materialized_tenant_report_runs_1.MATERIALIZED_TENANT_REPORT_RUNS_INDEX_OPTIONS,
50
52
  [materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME]: materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_INDEX_OPTIONS,
51
53
  [materialized_tenant_delivery_geo_cells_1.MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_COLLECTION_NAME]: materialized_tenant_delivery_geo_cells_1.MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_INDEX_OPTIONS,
52
54
  [MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_COLLECTION_NAME]: materialized_tenant_delivery_geo_scopes_1.MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_INDEX_OPTIONS,
@@ -0,0 +1,105 @@
1
+ import { MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM, type TMaterializedReadinessReportKey } from '../../constants/MATERIALIZED_REPORTS';
2
+ /**
3
+ * PURE report-run-ledger helpers shared by the writer (workers-service) and the
4
+ * admin/retry API (operations-service).
5
+ *
6
+ * The ledger row identity is `(tenant_id, localDate, report_key,
7
+ * schema_version)` — the SAME identity as the readiness row, but a DIFFERENT
8
+ * collection with a DIFFERENT lifecycle:
9
+ *
10
+ * - readiness (COMMITTED / NEEDS_RECONCILIATION) is written INSIDE the report
11
+ * transaction, so it can never exist for a failed report;
12
+ * - the run row (PENDING / RUNNING / RETRYING / COMMITTED / FAILED) is written
13
+ * OUTSIDE the transaction, so a rollback cannot hide the attempt.
14
+ */
15
+ export interface IMaterializedReportRunIdentity {
16
+ tenantId: string;
17
+ localDate: string;
18
+ reportKey: TMaterializedReadinessReportKey | string;
19
+ schemaVersion?: number;
20
+ }
21
+ /** Stable string key of one run row (Map keys / log correlation). */
22
+ export declare function materializedReportRunKey(parts: IMaterializedReportRunIdentity): string;
23
+ /** The Mongo filter of the ONE run row of a report. */
24
+ export declare function buildMaterializedReportRunFilter(parts: IMaterializedReportRunIdentity): {
25
+ tenant_id: string;
26
+ localDate: string;
27
+ report_key: string;
28
+ schema_version: number;
29
+ };
30
+ export declare function isMaterializedReportRunStatus(value: unknown): value is MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM;
31
+ /**
32
+ * Is the report CURRENTLY being executed?
33
+ *
34
+ * Only a run that owns the report may be in this state; the retry API refuses
35
+ * it (409) instead of racing the executor.
36
+ */
37
+ export declare function isMaterializedReportRunInFlight(status: unknown): boolean;
38
+ /**
39
+ * Does this run carry the UNKNOWN-COMMIT marker?
40
+ *
41
+ * Such a run MUST stay non-terminal until recovery settles it from
42
+ * ownership-checked readiness (a ledger error alone must never decide it).
43
+ */
44
+ export declare function isMaterializedReportRunCommitOutcomeUnknown(run: {
45
+ last_error?: string | null;
46
+ } | null | undefined): boolean;
47
+ /**
48
+ * Proves that a readiness row belongs to the run that owns this report.
49
+ *
50
+ * The row identity is the tenant/day/report/schema; ownership is the RUN
51
+ * identity. A row written by an OLDER close/re-close carries a DIFFERENT
52
+ * `run_id` and therefore proves nothing about the current run: it must keep the
53
+ * old report readable while the current run is recorded as FAILED
54
+ * (`INTERRUPTED_RUN`) and stays retryable. Never delete that older row.
55
+ */
56
+ export declare function isMaterializedReadinessOwnedByRun(args: {
57
+ readiness: {
58
+ run_id?: string | null;
59
+ } | null | undefined;
60
+ run: {
61
+ run_id?: string | null;
62
+ } | null | undefined;
63
+ }): boolean;
64
+ /** COMMITTED / FAILED: the execution reached a terminal state. */
65
+ export declare function isMaterializedReportRunTerminal(status: unknown): boolean;
66
+ /**
67
+ * The instant a run started (its `started_at`, or `updatedAt` when a legacy /
68
+ * partial row has none).
69
+ */
70
+ export declare function materializedReportRunStartedAt(run: {
71
+ started_at?: Date | string | null;
72
+ updatedAt?: Date | string | null;
73
+ }): Date | null;
74
+ /**
75
+ * Is an IN-FLIGHT run old enough that an interruption is plausible?
76
+ *
77
+ * AGE ALONE IS NEVER ENOUGH: recovery must also observe a STALE
78
+ * `tenant_active_jobs` heartbeat, otherwise a healthy long-running report would
79
+ * be taken over. This helper only answers the age question.
80
+ */
81
+ export declare function isMaterializedReportRunStale(args: {
82
+ run: {
83
+ status?: unknown;
84
+ started_at?: Date | string | null;
85
+ updatedAt?: Date | string | null;
86
+ };
87
+ now?: Date;
88
+ staleAfterMs?: number;
89
+ }): boolean;
90
+ /**
91
+ * May this report be retried?
92
+ *
93
+ * A MISSING row is retryable (the report never ran: a failed day, a crash
94
+ * before the first attempt, or a pre-ledger day). A FAILED row is retryable.
95
+ * A COMMITTED row is NOT (the retry would be a no-op), and an in-flight row is
96
+ * NOT (the executor owns it).
97
+ */
98
+ export declare function canRetryMaterializedReportRun(status: unknown): boolean;
99
+ /**
100
+ * Sanitizes an execution error for durable storage / API output.
101
+ *
102
+ * Deliberately conservative: the message is single-lined, PII-redacted and
103
+ * bounded. The ERROR STACK and raw driver payload are never stored.
104
+ */
105
+ export declare function sanitizeMaterializedReportRunError(error: unknown): string | null;
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.materializedReportRunKey = materializedReportRunKey;
4
+ exports.buildMaterializedReportRunFilter = buildMaterializedReportRunFilter;
5
+ exports.isMaterializedReportRunStatus = isMaterializedReportRunStatus;
6
+ exports.isMaterializedReportRunInFlight = isMaterializedReportRunInFlight;
7
+ exports.isMaterializedReportRunCommitOutcomeUnknown = isMaterializedReportRunCommitOutcomeUnknown;
8
+ exports.isMaterializedReadinessOwnedByRun = isMaterializedReadinessOwnedByRun;
9
+ exports.isMaterializedReportRunTerminal = isMaterializedReportRunTerminal;
10
+ exports.materializedReportRunStartedAt = materializedReportRunStartedAt;
11
+ exports.isMaterializedReportRunStale = isMaterializedReportRunStale;
12
+ exports.canRetryMaterializedReportRun = canRetryMaterializedReportRun;
13
+ exports.sanitizeMaterializedReportRunError = sanitizeMaterializedReportRunError;
14
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
15
+ /** Stable string key of one run row (Map keys / log correlation). */
16
+ function materializedReportRunKey(parts) {
17
+ return [
18
+ String(parts.tenantId),
19
+ String(parts.localDate),
20
+ String(parts.reportKey),
21
+ String(parts.schemaVersion ?? MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUNS_SCHEMA_VERSION),
22
+ ].join('|');
23
+ }
24
+ /** The Mongo filter of the ONE run row of a report. */
25
+ function buildMaterializedReportRunFilter(parts) {
26
+ return {
27
+ tenant_id: String(parts.tenantId),
28
+ localDate: String(parts.localDate),
29
+ report_key: String(parts.reportKey),
30
+ schema_version: parts.schemaVersion ?? MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUNS_SCHEMA_VERSION,
31
+ };
32
+ }
33
+ function isMaterializedReportRunStatus(value) {
34
+ return Object.values(MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM).includes(value);
35
+ }
36
+ /**
37
+ * Is the report CURRENTLY being executed?
38
+ *
39
+ * Only a run that owns the report may be in this state; the retry API refuses
40
+ * it (409) instead of racing the executor.
41
+ */
42
+ function isMaterializedReportRunInFlight(status) {
43
+ return (status === MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM.PENDING ||
44
+ status === MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM.RUNNING ||
45
+ status === MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM.RETRYING);
46
+ }
47
+ /**
48
+ * Does this run carry the UNKNOWN-COMMIT marker?
49
+ *
50
+ * Such a run MUST stay non-terminal until recovery settles it from
51
+ * ownership-checked readiness (a ledger error alone must never decide it).
52
+ */
53
+ function isMaterializedReportRunCommitOutcomeUnknown(run) {
54
+ return String(run?.last_error ?? '') === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_RUN_COMMIT_OUTCOME_UNKNOWN_ERROR;
55
+ }
56
+ /**
57
+ * Proves that a readiness row belongs to the run that owns this report.
58
+ *
59
+ * The row identity is the tenant/day/report/schema; ownership is the RUN
60
+ * identity. A row written by an OLDER close/re-close carries a DIFFERENT
61
+ * `run_id` and therefore proves nothing about the current run: it must keep the
62
+ * old report readable while the current run is recorded as FAILED
63
+ * (`INTERRUPTED_RUN`) and stays retryable. Never delete that older row.
64
+ */
65
+ function isMaterializedReadinessOwnedByRun(args) {
66
+ const readinessRun = args.readiness?.run_id;
67
+ const currentRun = args.run?.run_id;
68
+ return readinessRun != null && currentRun != null && String(readinessRun) === String(currentRun);
69
+ }
70
+ /** COMMITTED / FAILED: the execution reached a terminal state. */
71
+ function isMaterializedReportRunTerminal(status) {
72
+ return (status === MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM.COMMITTED ||
73
+ status === MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM.FAILED);
74
+ }
75
+ /**
76
+ * The instant a run started (its `started_at`, or `updatedAt` when a legacy /
77
+ * partial row has none).
78
+ */
79
+ function materializedReportRunStartedAt(run) {
80
+ const candidate = run.started_at ?? run.updatedAt ?? null;
81
+ if (candidate == null)
82
+ return null;
83
+ const date = candidate instanceof Date ? candidate : new Date(candidate);
84
+ return Number.isNaN(date.getTime()) ? null : date;
85
+ }
86
+ /**
87
+ * Is an IN-FLIGHT run old enough that an interruption is plausible?
88
+ *
89
+ * AGE ALONE IS NEVER ENOUGH: recovery must also observe a STALE
90
+ * `tenant_active_jobs` heartbeat, otherwise a healthy long-running report would
91
+ * be taken over. This helper only answers the age question.
92
+ */
93
+ function isMaterializedReportRunStale(args) {
94
+ if (!isMaterializedReportRunInFlight(args.run?.status))
95
+ return false;
96
+ const startedAt = materializedReportRunStartedAt(args.run);
97
+ if (startedAt == null)
98
+ return false;
99
+ const now = args.now ?? new Date();
100
+ const staleAfterMs = Number.isFinite(args.staleAfterMs) && args.staleAfterMs > 0
101
+ ? args.staleAfterMs
102
+ : MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_STALE_MS;
103
+ return now.getTime() - startedAt.getTime() >= staleAfterMs;
104
+ }
105
+ /**
106
+ * May this report be retried?
107
+ *
108
+ * A MISSING row is retryable (the report never ran: a failed day, a crash
109
+ * before the first attempt, or a pre-ledger day). A FAILED row is retryable.
110
+ * A COMMITTED row is NOT (the retry would be a no-op), and an in-flight row is
111
+ * NOT (the executor owns it).
112
+ */
113
+ function canRetryMaterializedReportRun(status) {
114
+ if (status == null)
115
+ return true;
116
+ return status === MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM.FAILED;
117
+ }
118
+ /* ------------------------------ PII safety ------------------------------ */
119
+ /**
120
+ * Patterns that must NEVER reach `last_error` (operator-visible, may be logged
121
+ * or exported): e-mail addresses, long digit runs (phone numbers / card-like
122
+ * values) and bearer/basic credentials.
123
+ */
124
+ const PII_PATTERNS = [
125
+ [/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, '[redacted-email]'],
126
+ // 7+ digits with common separators (phone numbers, card fragments).
127
+ [/(?:\+?\d[\s().-]?){7,}\d/g, '[redacted-number]'],
128
+ [/\b(?:bearer|basic)\s+[A-Za-z0-9._~+/-]+=*/gi, '[redacted-credential]'],
129
+ [/\b(?:password|secret|token|api[_-]?key)\s*[:=]\s*\S+/gi, '[redacted-credential]'],
130
+ ];
131
+ /**
132
+ * Sanitizes an execution error for durable storage / API output.
133
+ *
134
+ * Deliberately conservative: the message is single-lined, PII-redacted and
135
+ * bounded. The ERROR STACK and raw driver payload are never stored.
136
+ */
137
+ function sanitizeMaterializedReportRunError(error) {
138
+ if (error == null)
139
+ return null;
140
+ const raw = typeof error === 'string'
141
+ ? error
142
+ : typeof error.message === 'string'
143
+ ? String(error.message)
144
+ : '';
145
+ let message = raw.replace(/\s+/g, ' ').trim();
146
+ if (message === '') {
147
+ message =
148
+ typeof error.name === 'string'
149
+ ? String(error.name)
150
+ : 'UNKNOWN_ERROR';
151
+ }
152
+ for (const [pattern, replacement] of PII_PATTERNS) {
153
+ message = message.replace(pattern, replacement);
154
+ }
155
+ return message.slice(0, MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_ERROR_MAX_LENGTH);
156
+ }
@@ -491,3 +491,68 @@ export interface IWorker_EndTenantDay {
491
491
  /** The business day being closed (tenant_day_sessions doc id). */
492
492
  day_session_id: string;
493
493
  }
494
+ /**
495
+ * INTERNAL report-scoped retry (one report of one tenant-day).
496
+ *
497
+ * The retry re-runs ONLY `report_key`: it writes that report's documents and
498
+ * that report's readiness, never any other report and never the calendar.
499
+ */
500
+ export interface IWorker_RetryMaterializedReport {
501
+ tenant_id: string;
502
+ /** Tenant-local business day, `YYYY-MM-DD` of an EXISTING CLOSED session. */
503
+ localDate: string;
504
+ report_key: string;
505
+ }
506
+ /**
507
+ * Answer of the internal retry endpoint (report-scoped, no PII).
508
+ *
509
+ * ASYNC contract: the endpoint validates + acquires the report lease
510
+ * synchronously and starts the retry in the background, so it answers
511
+ * `accepted: true` with `status: RUNNING` (operations maps it to HTTP 202).
512
+ * The terminal outcome lands in the run ledger and is read by polling.
513
+ */
514
+ export interface IWorker_RetryMaterializedReportResult {
515
+ tenant_id: string;
516
+ localDate: string;
517
+ report_key: string;
518
+ /** Identity of the retry run (its own report-scoped lease token). */
519
+ run_id: string;
520
+ /** `RUNNING` when the retry was accepted. */
521
+ status: string;
522
+ /** True when the retry was accepted and is executing in the background. */
523
+ accepted: boolean;
524
+ /** Latest execution attempts (present once the execution has started). */
525
+ attempts?: number;
526
+ /** Whether readiness was written (only known once the retry finished). */
527
+ readiness_written?: boolean;
528
+ /** Sanitized failure reason; `null` while running / on success. */
529
+ last_error?: string | null;
530
+ }
531
+ /**
532
+ * INTERNAL stale-run reconciliation (workers-owned).
533
+ *
534
+ * Operations calls it before listing runs / before rejecting a RUNNING retry so
535
+ * a crash-interrupted execution converges instead of looking running forever.
536
+ */
537
+ export interface IWorker_ReconcileMaterializedReportRuns {
538
+ tenant_id: string;
539
+ /** `YYYY-MM-DD`; omitted = every day of the tenant (bounded by the worker). */
540
+ localDate?: string;
541
+ /** Omitted = every in-flight report of the tenant/day. */
542
+ report_key?: string;
543
+ }
544
+ export interface IWorker_ReconciledMaterializedReportRun {
545
+ localDate: string;
546
+ report_key: string;
547
+ /** What recovery decided: COMMITTED / FAILED (or a no-op reason). */
548
+ status: string;
549
+ from_status: string;
550
+ reason: string;
551
+ }
552
+ export interface IWorker_ReconcileMaterializedReportRunsResult {
553
+ tenant_id: string;
554
+ /** Ordered decisions (empty = nothing to reconcile). */
555
+ reconciled: IWorker_ReconciledMaterializedReportRun[];
556
+ /** Rows inspected but deliberately left untouched (active/fresh/terminal). */
557
+ skipped: IWorker_ReconciledMaterializedReportRun[];
558
+ }
@@ -49,6 +49,7 @@ export * from './materialized_tenant_payments_comparison_entries';
49
49
  export * from './materialized_tenant_payments_comparison_reports';
50
50
  export * from './materialized_tenant_prep_time_entries';
51
51
  export * from './materialized_tenant_prep_time_reports';
52
+ export * from './materialized_tenant_report_runs';
52
53
  export * from './materialized_tenant_reports_iterations';
53
54
  export * from './materialized_tenant_sales_comparison_entries';
54
55
  export * from './materialized_tenant_sales_comparison_reports';
@@ -65,6 +65,7 @@ __exportStar(require("./materialized_tenant_payments_comparison_entries"), expor
65
65
  __exportStar(require("./materialized_tenant_payments_comparison_reports"), exports);
66
66
  __exportStar(require("./materialized_tenant_prep_time_entries"), exports);
67
67
  __exportStar(require("./materialized_tenant_prep_time_reports"), exports);
68
+ __exportStar(require("./materialized_tenant_report_runs"), exports);
68
69
  __exportStar(require("./materialized_tenant_reports_iterations"), exports);
69
70
  __exportStar(require("./materialized_tenant_sales_comparison_entries"), exports);
70
71
  __exportStar(require("./materialized_tenant_sales_comparison_reports"), exports);
@@ -0,0 +1,97 @@
1
+ import { Schema } from 'mongoose';
2
+ import { MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM } from '../../constants/MATERIALIZED_REPORTS';
3
+ /**
4
+ * Mongoose schema for `materialized_tenant_report_runs` — the OPERATIONAL
5
+ * per-report execution ledger (PENDING / RUNNING / RETRYING / COMMITTED /
6
+ * FAILED).
7
+ *
8
+ * It is deliberately SEPARATE from `materialized_tenant_day_readiness`:
9
+ * readiness is the historical read gate and only ever carries COMMITTED /
10
+ * NEEDS_RECONCILIATION. A failed report must never look materialized, so its
11
+ * failure is recorded here, together with `attempts` and the redacted
12
+ * `last_error`.
13
+ *
14
+ * The row is written OUTSIDE the report transaction (a rollback must not erase
15
+ * the attempt), keyed by the unique compound
16
+ * `(tenant_id, localDate, report_key, schema_version)`.
17
+ */
18
+ export declare const MaterializedTenantReportRunSchema: Schema<any, import("mongoose").Model<any, any, any, any, any, any>, {}, {}, {}, {}, {
19
+ timestamps: true;
20
+ versionKey: false;
21
+ minimize: false;
22
+ }, {
23
+ createdAt: NativeDate;
24
+ updatedAt: NativeDate;
25
+ } & {
26
+ localDate: string;
27
+ createdAt: NativeDate;
28
+ updatedAt: NativeDate;
29
+ tenant_id: string;
30
+ status: MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM;
31
+ schema_version: number;
32
+ report_key: "DELIVERY" | "DISCOUNTS" | "OVERVIEW" | "PREP_TIME" | "DIALER" | "DINEIN";
33
+ attempts: number;
34
+ total_attempts: number;
35
+ run_id?: string | null | undefined;
36
+ last_error?: string | null | undefined;
37
+ started_at?: NativeDate | null | undefined;
38
+ finished_at?: NativeDate | null | undefined;
39
+ }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
40
+ createdAt: NativeDate;
41
+ updatedAt: NativeDate;
42
+ } & {
43
+ localDate: string;
44
+ createdAt: NativeDate;
45
+ updatedAt: NativeDate;
46
+ tenant_id: string;
47
+ status: MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM;
48
+ schema_version: number;
49
+ report_key: "DELIVERY" | "DISCOUNTS" | "OVERVIEW" | "PREP_TIME" | "DIALER" | "DINEIN";
50
+ attempts: number;
51
+ total_attempts: number;
52
+ run_id?: string | null | undefined;
53
+ last_error?: string | null | undefined;
54
+ started_at?: NativeDate | null | undefined;
55
+ finished_at?: NativeDate | null | undefined;
56
+ }>> & import("mongoose").FlatRecord<{
57
+ createdAt: NativeDate;
58
+ updatedAt: NativeDate;
59
+ } & {
60
+ localDate: string;
61
+ createdAt: NativeDate;
62
+ updatedAt: NativeDate;
63
+ tenant_id: string;
64
+ status: MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM;
65
+ schema_version: number;
66
+ report_key: "DELIVERY" | "DISCOUNTS" | "OVERVIEW" | "PREP_TIME" | "DIALER" | "DINEIN";
67
+ attempts: number;
68
+ total_attempts: number;
69
+ run_id?: string | null | undefined;
70
+ last_error?: string | null | undefined;
71
+ started_at?: NativeDate | null | undefined;
72
+ finished_at?: NativeDate | null | undefined;
73
+ }> & {
74
+ _id: import("mongoose").Types.ObjectId;
75
+ } & {
76
+ __v: number;
77
+ }>;
78
+ export declare const MATERIALIZED_TENANT_REPORT_RUNS_COLLECTION_INDEXES: {
79
+ _id: {
80
+ _id: number;
81
+ };
82
+ tenant_id__localDate__report_key__schema_version: {
83
+ tenant_id: number;
84
+ localDate: number;
85
+ report_key: number;
86
+ schema_version: number;
87
+ };
88
+ };
89
+ /**
90
+ * Index OPTIONS the owner must CREATE (declared here, applied by a separate
91
+ * migration/deploy step — never by a read, a close or a retry at runtime).
92
+ */
93
+ export declare const MATERIALIZED_TENANT_REPORT_RUNS_INDEX_OPTIONS: readonly {
94
+ key: Record<string, 1 | -1>;
95
+ name: string;
96
+ unique?: boolean;
97
+ }[];
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MATERIALIZED_TENANT_REPORT_RUNS_INDEX_OPTIONS = exports.MATERIALIZED_TENANT_REPORT_RUNS_COLLECTION_INDEXES = exports.MaterializedTenantReportRunSchema = void 0;
4
+ const mongoose_1 = require("mongoose");
5
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
6
+ /**
7
+ * Mongoose schema for `materialized_tenant_report_runs` — the OPERATIONAL
8
+ * per-report execution ledger (PENDING / RUNNING / RETRYING / COMMITTED /
9
+ * FAILED).
10
+ *
11
+ * It is deliberately SEPARATE from `materialized_tenant_day_readiness`:
12
+ * readiness is the historical read gate and only ever carries COMMITTED /
13
+ * NEEDS_RECONCILIATION. A failed report must never look materialized, so its
14
+ * failure is recorded here, together with `attempts` and the redacted
15
+ * `last_error`.
16
+ *
17
+ * The row is written OUTSIDE the report transaction (a rollback must not erase
18
+ * the attempt), keyed by the unique compound
19
+ * `(tenant_id, localDate, report_key, schema_version)`.
20
+ */
21
+ exports.MaterializedTenantReportRunSchema = new mongoose_1.Schema({
22
+ tenant_id: { type: String, required: true },
23
+ localDate: { type: String, required: true },
24
+ report_key: {
25
+ type: String,
26
+ required: true,
27
+ enum: [...MATERIALIZED_REPORTS_1.MATERIALIZED_READINESS_REPORT_KEYS],
28
+ },
29
+ schema_version: {
30
+ type: Number,
31
+ required: true,
32
+ immutable: true,
33
+ default: MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUNS_SCHEMA_VERSION,
34
+ },
35
+ status: {
36
+ type: String,
37
+ required: true,
38
+ enum: MATERIALIZED_REPORTS_1.ALL_MATERIALIZED_TENANT_REPORT_RUN_STATUSES,
39
+ default: MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM.PENDING,
40
+ },
41
+ attempts: {
42
+ type: Number,
43
+ required: true,
44
+ default: 0,
45
+ // Stored counters remain integers.
46
+ validate: {
47
+ validator: (value) => Number.isInteger(value) && value >= 0,
48
+ message: 'attempts must be a non-negative integer',
49
+ },
50
+ },
51
+ total_attempts: {
52
+ type: Number,
53
+ required: true,
54
+ default: 0,
55
+ // Stored counters remain integers.
56
+ validate: {
57
+ validator: (value) => Number.isInteger(value) && value >= 0,
58
+ message: 'total_attempts must be a non-negative integer',
59
+ },
60
+ },
61
+ last_error: { type: String, required: false, default: null },
62
+ run_id: { type: String, required: false, default: null },
63
+ started_at: { type: mongoose_1.Schema.Types.Date, required: false, default: null },
64
+ finished_at: { type: mongoose_1.Schema.Types.Date, required: false, default: null },
65
+ createdAt: {
66
+ type: mongoose_1.Schema.Types.Date,
67
+ required: true,
68
+ default: () => new Date(),
69
+ immutable: true,
70
+ },
71
+ updatedAt: {
72
+ type: mongoose_1.Schema.Types.Date,
73
+ required: true,
74
+ default: () => new Date(),
75
+ },
76
+ }, { timestamps: true, versionKey: false, minimize: false });
77
+ exports.MATERIALIZED_TENANT_REPORT_RUNS_COLLECTION_INDEXES = {
78
+ _id: { _id: 1 },
79
+ tenant_id__localDate__report_key__schema_version: {
80
+ tenant_id: 1,
81
+ localDate: 1,
82
+ report_key: 1,
83
+ schema_version: 1,
84
+ },
85
+ };
86
+ /**
87
+ * Index OPTIONS the owner must CREATE (declared here, applied by a separate
88
+ * migration/deploy step — never by a read, a close or a retry at runtime).
89
+ */
90
+ exports.MATERIALIZED_TENANT_REPORT_RUNS_INDEX_OPTIONS = [
91
+ {
92
+ key: { tenant_id: 1, localDate: 1, report_key: 1, schema_version: 1 },
93
+ name: 'tenant_id__localDate__report_key__schema_version',
94
+ unique: true,
95
+ },
96
+ // Admin materialization page: one tenant-day's reports, newest first.
97
+ {
98
+ key: { tenant_id: 1, localDate: 1, report_key: 1 },
99
+ name: 'tenant_id__localDate__report_key',
100
+ unique: false,
101
+ },
102
+ // Admin materialization page: the failed/running filters across tenants.
103
+ {
104
+ key: { status: 1, updatedAt: -1 },
105
+ name: 'status__updatedAt',
106
+ unique: false,
107
+ },
108
+ ];