codex/aram-gate3-mapping-change-preview-20261030
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 197 lines 8.13 KB
Raw
1 """Read-only change preview for explicit, human-reviewed Mapping decisions.
2
3 A preview and its fingerprint are NOT an approval, an authenticated identity,
4 a persisted audit event, or a race-free database write authorization.
5 """
6 from __future__ import annotations
7
8 from dataclasses import asdict, dataclass
9 from hashlib import sha256
10 import json
11
12 from sqlalchemy import select
13 from sqlalchemy.orm import Session
14
15 from aram_backend.mapping_service import MappingValidationError
16 from aram_backend.models import (
17 AccountVersion, FiscalYear, FiscalYearStatus, MappingRule, NoteDefinition,
18 )
19
20
21 @dataclass(frozen=True)
22 class RuleValues:
23 id: int | None
24 version: int
25 account_code: str
26 target_note_id: int
27 mapping_type: str
28
29
30 @dataclass(frozen=True)
31 class MappingChangePreview:
32 year_id: int
33 company_id: int
34 fiscal_year_number: int
35 rule_key: str
36 expected_base_version: int
37 before: RuleValues | None
38 proposed: RuleValues
39 target_note_number: str
40 target_note_version: int
41 account_version_id: int
42 account_version: int
43 fingerprint: str
44
45
46 def _require_clean_mapping_state(session: Session) -> None:
47 # A read-only DB snapshot cannot faithfully describe unflushed ORM edits.
48 # Conservatively reject pending related edits (even to another year)
49 # rather than use a misleading snapshot or trigger an implicit flush.
50 touched = session.new | session.dirty | session.deleted
51 if any(isinstance(item, (
52 FiscalYear, MappingRule, NoteDefinition, AccountVersion
53 )) for item in touched):
54 raise MappingValidationError(
55 "mapping preview requires a clean Session; flush or rollback pending edits first"
56 )
57
58
59 def _validate_inputs(
60 year_id: int, rule_key: str, account_code: str,
61 target_note_id: int, mapping_type: str, expected_base_version: int,
62 ) -> None:
63 if type(year_id) is not int or year_id <= 0:
64 raise MappingValidationError("year_id must be a positive integer")
65 if type(target_note_id) is not int or target_note_id <= 0:
66 raise MappingValidationError("target_note_id must be a positive integer")
67 if type(expected_base_version) is not int or expected_base_version < 0:
68 raise MappingValidationError("expected_base_version must be a nonnegative integer")
69 for name, value, limit in (
70 ("rule_key", rule_key, 128),
71 ("account_code", account_code, 64),
72 ("mapping_type", mapping_type, 32),
73 ):
74 if not isinstance(value, str) or not value or value.strip() != value or len(value) > limit:
75 raise MappingValidationError(f"invalid {name}")
76
77
78 def preview_mapping_change(
79 session: Session, *, year_id: int, rule_key: str, account_code: str,
80 target_note_id: int, mapping_type: str, expected_base_version: int,
81 ) -> MappingChangePreview:
82 """Describe a proposed NEXT version without writing or accepting it.
83
84 expected_base_version=0 means no MappingRule exists for this rule_key/year.
85 Otherwise it must equal the latest persisted rule version. An old version,
86 non-current note, cross-year target or unchanged proposal is rejected.
87 """
88 _validate_inputs(
89 year_id, rule_key, account_code, target_note_id, mapping_type,
90 expected_base_version,
91 )
92 with session.no_autoflush:
93 _require_clean_mapping_state(session)
94 year = session.get(FiscalYear, year_id, populate_existing=True)
95 if year is None or year.status is not FiscalYearStatus.DRAFT:
96 raise MappingValidationError("fiscal year must exist and be Draft")
97
98 previous_rule = session.scalar(
99 select(MappingRule)
100 .where(MappingRule.year_id == year_id, MappingRule.rule_key == rule_key)
101 .order_by(MappingRule.version.desc(), MappingRule.id.desc())
102 .limit(1)
103 .execution_options(populate_existing=True)
104 )
105 prior_version = previous_rule.version if previous_rule is not None else 0
106 if expected_base_version != prior_version:
107 raise MappingValidationError("stale base mapping version; regenerate review preview")
108
109 target = session.get(NoteDefinition, target_note_id, populate_existing=True)
110 if target is None or target.year_id != year_id:
111 raise MappingValidationError("target note must belong to the same fiscal year")
112 latest_note = session.scalar(
113 select(NoteDefinition).where(
114 NoteDefinition.year_id == year_id,
115 NoteDefinition.note_number == target.note_number,
116 ).order_by(NoteDefinition.version.desc(), NoteDefinition.id.desc()).limit(1)
117 .execution_options(populate_existing=True)
118 )
119 if latest_note is None or latest_note.id != target_note_id:
120 raise MappingValidationError("target must reference latest note version")
121
122 account = session.scalar(
123 select(AccountVersion).where(
124 AccountVersion.year_id == year_id, AccountVersion.account_code == account_code,
125 ).order_by(AccountVersion.version.desc(), AccountVersion.id.desc()).limit(1)
126 .execution_options(populate_existing=True)
127 )
128 if account is None:
129 raise MappingValidationError("account code must exist in the same fiscal year")
130
131 before = (
132 RuleValues(
133 previous_rule.id, previous_rule.version, previous_rule.account_code,
134 previous_rule.target_note_id, previous_rule.mapping_type,
135 )
136 if previous_rule is not None else None
137 )
138 proposed = RuleValues(
139 id=None, version=prior_version + 1, account_code=account_code,
140 target_note_id=target_note_id, mapping_type=mapping_type,
141 )
142 if before is not None and (
143 before.account_code, before.target_note_id, before.mapping_type
144 ) == (
145 proposed.account_code, proposed.target_note_id, proposed.mapping_type
146 ):
147 raise MappingValidationError("no mapping change to review")
148
149 data = {
150 "year_id": year_id,
151 "company_id": year.company_id,
152 "fiscal_year_number": year.year,
153 "rule_key": rule_key,
154 "expected_base_version": expected_base_version,
155 "before": asdict(before) if before is not None else None,
156 "proposed": asdict(proposed),
157 "target_note_number": target.note_number,
158 "target_note_version": target.version,
159 "account_version_id": account.id,
160 "account_version": account.version,
161 }
162 fingerprint = sha256(
163 json.dumps(data, sort_keys=True, ensure_ascii=True, separators=(",", ":")).encode("utf-8")
164 ).hexdigest()
165 return MappingChangePreview(
166 year_id=year_id, company_id=year.company_id, fiscal_year_number=year.year,
167 rule_key=rule_key, expected_base_version=expected_base_version,
168 before=before, proposed=proposed,
169 target_note_number=target.note_number,
170 target_note_version=target.version,
171 account_version_id=account.id, account_version=account.version,
172 fingerprint=fingerprint,
173 )
174
175
176 def verify_mapping_change_preview_current(
177 session: Session, preview: MappingChangePreview,
178 ) -> None:
179 """Recheck a previously observed snapshot; this never saves or approves.
180
181 A successful recheck is NOT a transaction lock, authenticated approval or
182 authorization to skip version, audit and database-level race protections.
183 """
184 if not isinstance(preview, MappingChangePreview):
185 raise MappingValidationError("invalid mapping preview")
186 try:
187 current = preview_mapping_change(
188 session, year_id=preview.year_id, rule_key=preview.rule_key,
189 account_code=preview.proposed.account_code,
190 target_note_id=preview.proposed.target_note_id,
191 mapping_type=preview.proposed.mapping_type,
192 expected_base_version=preview.expected_base_version,
193 )
194 except MappingValidationError as exc:
195 raise MappingValidationError("mapping review preview is stale or invalid") from exc
196 if current != preview:
197 raise MappingValidationError("mapping review preview is stale or altered")