Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 22:00 UTC
codex/gate3-signed-year-scope-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
| 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 | allow_unchanged: bool = False, |
| 86 | ) -> MappingChangePreview: |
| 87 | """Describe a proposed NEXT version without writing or accepting it. |
| 88 | |
| 89 | expected_base_version=0 means no MappingRule exists for this rule_key/year. |
| 90 | Otherwise it must equal the latest persisted rule version. An old version, |
| 91 | non-current note, cross-year target or unchanged proposal is rejected. |
| 92 | """ |
| 93 | if type(allow_unchanged) is not bool: |
| 94 | raise MappingValidationError("allow_unchanged must be Boolean") |
| 95 | _validate_inputs( |
| 96 | year_id, rule_key, account_code, target_note_id, mapping_type, |
| 97 | expected_base_version, |
| 98 | ) |
| 99 | with session.no_autoflush: |
| 100 | _require_clean_mapping_state(session) |
| 101 | year = session.get(FiscalYear, year_id, populate_existing=True) |
| 102 | if year is None or year.status is not FiscalYearStatus.DRAFT: |
| 103 | raise MappingValidationError("fiscal year must exist and be Draft") |
| 104 | |
| 105 | previous_rule = session.scalar( |
| 106 | select(MappingRule) |
| 107 | .where(MappingRule.year_id == year_id, MappingRule.rule_key == rule_key) |
| 108 | .order_by(MappingRule.version.desc(), MappingRule.id.desc()) |
| 109 | .limit(1) |
| 110 | .execution_options(populate_existing=True) |
| 111 | ) |
| 112 | prior_version = previous_rule.version if previous_rule is not None else 0 |
| 113 | if expected_base_version != prior_version: |
| 114 | raise MappingValidationError("stale base mapping version; regenerate review preview") |
| 115 | |
| 116 | target = session.get(NoteDefinition, target_note_id, populate_existing=True) |
| 117 | if target is None or target.year_id != year_id: |
| 118 | raise MappingValidationError("target note must belong to the same fiscal year") |
| 119 | latest_note = session.scalar( |
| 120 | select(NoteDefinition).where( |
| 121 | NoteDefinition.year_id == year_id, |
| 122 | NoteDefinition.note_number == target.note_number, |
| 123 | ).order_by(NoteDefinition.version.desc(), NoteDefinition.id.desc()).limit(1) |
| 124 | .execution_options(populate_existing=True) |
| 125 | ) |
| 126 | if latest_note is None or latest_note.id != target_note_id: |
| 127 | raise MappingValidationError("target must reference latest note version") |
| 128 | |
| 129 | account = session.scalar( |
| 130 | select(AccountVersion).where( |
| 131 | AccountVersion.year_id == year_id, AccountVersion.account_code == account_code, |
| 132 | ).order_by(AccountVersion.version.desc(), AccountVersion.id.desc()).limit(1) |
| 133 | .execution_options(populate_existing=True) |
| 134 | ) |
| 135 | if account is None: |
| 136 | raise MappingValidationError("account code must exist in the same fiscal year") |
| 137 | |
| 138 | before = ( |
| 139 | RuleValues( |
| 140 | previous_rule.id, previous_rule.version, previous_rule.account_code, |
| 141 | previous_rule.target_note_id, previous_rule.mapping_type, |
| 142 | ) |
| 143 | if previous_rule is not None else None |
| 144 | ) |
| 145 | proposed = RuleValues( |
| 146 | id=None, version=prior_version + 1, account_code=account_code, |
| 147 | target_note_id=target_note_id, mapping_type=mapping_type, |
| 148 | ) |
| 149 | is_unchanged = before is not None and ( |
| 150 | before.account_code, before.target_note_id, before.mapping_type |
| 151 | ) == ( |
| 152 | proposed.account_code, proposed.target_note_id, proposed.mapping_type |
| 153 | ) |
| 154 | |
| 155 | data = { |
| 156 | "year_id": year_id, |
| 157 | "company_id": year.company_id, |
| 158 | "fiscal_year_number": year.year, |
| 159 | "rule_key": rule_key, |
| 160 | "expected_base_version": expected_base_version, |
| 161 | "before": asdict(before) if before is not None else None, |
| 162 | "proposed": asdict(proposed), |
| 163 | "target_note_number": target.note_number, |
| 164 | "target_note_version": target.version, |
| 165 | "account_version_id": account.id, |
| 166 | "account_version": account.version, |
| 167 | } |
| 168 | fingerprint = sha256( |
| 169 | json.dumps(data, sort_keys=True, ensure_ascii=True, separators=(",", ":")).encode("utf-8") |
| 170 | ).hexdigest() |
| 171 | preview = MappingChangePreview( |
| 172 | year_id=year_id, company_id=year.company_id, fiscal_year_number=year.year, |
| 173 | rule_key=rule_key, expected_base_version=expected_base_version, |
| 174 | before=before, proposed=proposed, |
| 175 | target_note_number=target.note_number, |
| 176 | target_note_version=target.version, |
| 177 | account_version_id=account.id, account_version=account.version, |
| 178 | fingerprint=fingerprint, |
| 179 | ) |
| 180 | if is_unchanged and not allow_unchanged: |
| 181 | raise MappingNoChange("no mapping change to review") |
| 182 | return preview |
| 183 | |
| 184 | |
| 185 | def verify_mapping_change_preview_current( |
| 186 | session: Session, preview: MappingChangePreview, |
| 187 | ) -> None: |
| 188 | """Recheck a previously observed snapshot; this never saves or approves. |
| 189 | |
| 190 | A successful recheck is NOT a transaction lock, authenticated approval or |
| 191 | authorization to skip version, audit and database-level race protections. |
| 192 | """ |
| 193 | if not isinstance(preview, MappingChangePreview): |
| 194 | raise MappingValidationError("invalid mapping preview") |
| 195 | try: |
| 196 | current = preview_mapping_change( |
| 197 | session, year_id=preview.year_id, rule_key=preview.rule_key, |
| 198 | account_code=preview.proposed.account_code, |
| 199 | target_note_id=preview.proposed.target_note_id, |
| 200 | mapping_type=preview.proposed.mapping_type, |
| 201 | expected_base_version=preview.expected_base_version, |
| 202 | ) |
| 203 | except MappingValidationError as exc: |
| 204 | raise MappingValidationError("mapping review preview is stale or invalid") from exc |
| 205 | if current != preview: |
| 206 | raise MappingValidationError("mapping review preview is stale or altered") |