@davoodmehraban89 / Aram-2 Mirror · read-only
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 3, 22:00 UTC

codex/gate3-mapping-batch-review-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 201 lines 8.24 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
17
18 class MappingNoChange(MappingValidationError):
19 """Preview is valid, but proposed Mapping content is unchanged."""
20 from aram_backend.models import (
21 AccountVersion, FiscalYear, FiscalYearStatus, MappingRule, NoteDefinition,
22 )
23
24
25 @dataclass(frozen=True)
26 class RuleValues:
27 id: int | None
28 version: int
29 account_code: str
30 target_note_id: int
31 mapping_type: str
32
33
34 @dataclass(frozen=True)
35 class MappingChangePreview:
36 year_id: int
37 company_id: int
38 fiscal_year_number: int
39 rule_key: str
40 expected_base_version: int
41 before: RuleValues | None
42 proposed: RuleValues
43 target_note_number: str
44 target_note_version: int
45 account_version_id: int
46 account_version: int
47 fingerprint: str
48
49
50 def _require_clean_mapping_state(session: Session) -> None:
51 # A read-only DB snapshot cannot faithfully describe unflushed ORM edits.
52 # Conservatively reject pending related edits (even to another year)
53 # rather than use a misleading snapshot or trigger an implicit flush.
54 touched = session.new | session.dirty | session.deleted
55 if any(isinstance(item, (
56 FiscalYear, MappingRule, NoteDefinition, AccountVersion
57 )) for item in touched):
58 raise MappingValidationError(
59 "mapping preview requires a clean Session; flush or rollback pending edits first"
60 )
61
62
63 def _validate_inputs(
64 year_id: int, rule_key: str, account_code: str,
65 target_note_id: int, mapping_type: str, expected_base_version: int,
66 ) -> None:
67 if type(year_id) is not int or year_id <= 0:
68 raise MappingValidationError("year_id must be a positive integer")
69 if type(target_note_id) is not int or target_note_id <= 0:
70 raise MappingValidationError("target_note_id must be a positive integer")
71 if type(expected_base_version) is not int or expected_base_version < 0:
72 raise MappingValidationError("expected_base_version must be a nonnegative integer")
73 for name, value, limit in (
74 ("rule_key", rule_key, 128),
75 ("account_code", account_code, 64),
76 ("mapping_type", mapping_type, 32),
77 ):
78 if not isinstance(value, str) or not value or value.strip() != value or len(value) > limit:
79 raise MappingValidationError(f"invalid {name}")
80
81
82 def preview_mapping_change(
83 session: Session, *, year_id: int, rule_key: str, account_code: str,
84 target_note_id: int, mapping_type: str, expected_base_version: int,
85 ) -> MappingChangePreview:
86 """Describe a proposed NEXT version without writing or accepting it.
87
88 expected_base_version=0 means no MappingRule exists for this rule_key/year.
89 Otherwise it must equal the latest persisted rule version. An old version,
90 non-current note, cross-year target or unchanged proposal is rejected.
91 """
92 _validate_inputs(
93 year_id, rule_key, account_code, target_note_id, mapping_type,
94 expected_base_version,
95 )
96 with session.no_autoflush:
97 _require_clean_mapping_state(session)
98 year = session.get(FiscalYear, year_id, populate_existing=True)
99 if year is None or year.status is not FiscalYearStatus.DRAFT:
100 raise MappingValidationError("fiscal year must exist and be Draft")
101
102 previous_rule = session.scalar(
103 select(MappingRule)
104 .where(MappingRule.year_id == year_id, MappingRule.rule_key == rule_key)
105 .order_by(MappingRule.version.desc(), MappingRule.id.desc())
106 .limit(1)
107 .execution_options(populate_existing=True)
108 )
109 prior_version = previous_rule.version if previous_rule is not None else 0
110 if expected_base_version != prior_version:
111 raise MappingValidationError("stale base mapping version; regenerate review preview")
112
113 target = session.get(NoteDefinition, target_note_id, populate_existing=True)
114 if target is None or target.year_id != year_id:
115 raise MappingValidationError("target note must belong to the same fiscal year")
116 latest_note = session.scalar(
117 select(NoteDefinition).where(
118 NoteDefinition.year_id == year_id,
119 NoteDefinition.note_number == target.note_number,
120 ).order_by(NoteDefinition.version.desc(), NoteDefinition.id.desc()).limit(1)
121 .execution_options(populate_existing=True)
122 )
123 if latest_note is None or latest_note.id != target_note_id:
124 raise MappingValidationError("target must reference latest note version")
125
126 account = session.scalar(
127 select(AccountVersion).where(
128 AccountVersion.year_id == year_id, AccountVersion.account_code == account_code,
129 ).order_by(AccountVersion.version.desc(), AccountVersion.id.desc()).limit(1)
130 .execution_options(populate_existing=True)
131 )
132 if account is None:
133 raise MappingValidationError("account code must exist in the same fiscal year")
134
135 before = (
136 RuleValues(
137 previous_rule.id, previous_rule.version, previous_rule.account_code,
138 previous_rule.target_note_id, previous_rule.mapping_type,
139 )
140 if previous_rule is not None else None
141 )
142 proposed = RuleValues(
143 id=None, version=prior_version + 1, account_code=account_code,
144 target_note_id=target_note_id, mapping_type=mapping_type,
145 )
146 if before is not None and (
147 before.account_code, before.target_note_id, before.mapping_type
148 ) == (
149 proposed.account_code, proposed.target_note_id, proposed.mapping_type
150 ):
151 raise MappingNoChange("no mapping change to review")
152
153 data = {
154 "year_id": year_id,
155 "company_id": year.company_id,
156 "fiscal_year_number": year.year,
157 "rule_key": rule_key,
158 "expected_base_version": expected_base_version,
159 "before": asdict(before) if before is not None else None,
160 "proposed": asdict(proposed),
161 "target_note_number": target.note_number,
162 "target_note_version": target.version,
163 "account_version_id": account.id,
164 "account_version": account.version,
165 }
166 fingerprint = sha256(
167 json.dumps(data, sort_keys=True, ensure_ascii=True, separators=(",", ":")).encode("utf-8")
168 ).hexdigest()
169 return MappingChangePreview(
170 year_id=year_id, company_id=year.company_id, fiscal_year_number=year.year,
171 rule_key=rule_key, expected_base_version=expected_base_version,
172 before=before, proposed=proposed,
173 target_note_number=target.note_number,
174 target_note_version=target.version,
175 account_version_id=account.id, account_version=account.version,
176 fingerprint=fingerprint,
177 )
178
179
180 def verify_mapping_change_preview_current(
181 session: Session, preview: MappingChangePreview,
182 ) -> None:
183 """Recheck a previously observed snapshot; this never saves or approves.
184
185 A successful recheck is NOT a transaction lock, authenticated approval or
186 authorization to skip version, audit and database-level race protections.
187 """
188 if not isinstance(preview, MappingChangePreview):
189 raise MappingValidationError("invalid mapping preview")
190 try:
191 current = preview_mapping_change(
192 session, year_id=preview.year_id, rule_key=preview.rule_key,
193 account_code=preview.proposed.account_code,
194 target_note_id=preview.proposed.target_note_id,
195 mapping_type=preview.proposed.mapping_type,
196 expected_base_version=preview.expected_base_version,
197 )
198 except MappingValidationError as exc:
199 raise MappingValidationError("mapping review preview is stale or invalid") from exc
200 if current != preview:
201 raise MappingValidationError("mapping review preview is stale or altered")