codex/aram-gate3-integration-validation-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 120 lines 5.42 KB
Raw
1 """Read-only, explicit-review preview for carrying mapping decisions into a new year.
2
3 Never infers target notes or writes rules. The caller must explicitly review and
4 save each proposed mapping using the governed mapping service.
5 """
6 from __future__ import annotations
7
8 from dataclasses import dataclass
9
10 from sqlalchemy import select
11 from sqlalchemy.orm import Session
12
13 from aram_backend.mapping_service import MappingValidationError
14 from aram_backend.models import AccountVersion, FiscalYear, FiscalYearStatus, MappingRule, NoteDefinition
15
16
17 @dataclass(frozen=True)
18 class CarryForwardCandidate:
19 rule_key: str
20 account_code: str
21 source_note_number: str
22 target_note_id: int
23 mapping_type: str
24 source_version: int
25
26
27 @dataclass(frozen=True)
28 class CarryForwardPreview:
29 source_year_id: int
30 target_year_id: int
31 candidates: tuple[CarryForwardCandidate, ...]
32 skipped: tuple[tuple[str, str], ...]
33
34
35 def preview_mapping_carry_forward(
36 session: Session, *, source_year_id: int, target_year_id: int,
37 ) -> CarryForwardPreview:
38 """Preview mapping candidates for the same company's later Draft year.
39
40 Match target notes by *exact* note_number only when unique at their latest
41 version. Missing accounts/notes and existing target rules are skipped with
42 reasons, never auto-created. No changes are flushed or committed.
43 """
44 for label, value in (("source_year_id", source_year_id), ("target_year_id", target_year_id)):
45 if type(value) is not int or value <= 0:
46 raise MappingValidationError(f"{label} must be a positive integer")
47 if source_year_id == target_year_id:
48 raise MappingValidationError("source and target fiscal years must differ")
49
50 with session.no_autoflush:
51 source = session.get(FiscalYear, source_year_id)
52 target = session.get(FiscalYear, target_year_id)
53 if source is None or target is None:
54 raise MappingValidationError("both fiscal years must exist")
55 if source.company_id != target.company_id:
56 raise MappingValidationError("fiscal years must belong to the same company")
57 if source.year >= target.year:
58 raise MappingValidationError("target fiscal year must be later than source")
59 if target.status is not FiscalYearStatus.DRAFT:
60 raise MappingValidationError("target fiscal year must be Draft")
61
62 source_rules = session.scalars(
63 select(MappingRule).where(MappingRule.year_id == source_year_id)
64 .order_by(MappingRule.rule_key, MappingRule.version.desc(), MappingRule.id.desc())
65 ).all()
66 latest_rules: dict[str, MappingRule] = {}
67 for rule in source_rules:
68 latest_rules.setdefault(rule.rule_key, rule)
69
70 # Only the latest version of a source note number can authorize
71 # carry-forward. An old MappingRule target is not the current note,
72 # even when the note number happens to remain unchanged.
73 source_note_rows = session.scalars(
74 select(NoteDefinition).where(NoteDefinition.year_id == source_year_id)
75 .order_by(NoteDefinition.note_number, NoteDefinition.version.desc(), NoteDefinition.id.desc())
76 ).all()
77 source_notes = {note.id: note for note in source_note_rows}
78 latest_source_notes: dict[str, NoteDefinition] = {}
79 for note in source_note_rows:
80 latest_source_notes.setdefault(note.note_number, note)
81 target_notes = session.scalars(
82 select(NoteDefinition).where(NoteDefinition.year_id == target_year_id)
83 .order_by(NoteDefinition.note_number, NoteDefinition.version.desc(), NoteDefinition.id.desc())
84 ).all()
85 latest_target_notes: dict[str, NoteDefinition] = {}
86 for note in target_notes:
87 latest_target_notes.setdefault(note.note_number, note)
88
89 target_accounts = set(session.scalars(
90 select(AccountVersion.account_code).where(AccountVersion.year_id == target_year_id)
91 ))
92 target_rule_keys = set(session.scalars(
93 select(MappingRule.rule_key).where(MappingRule.year_id == target_year_id)
94 ))
95
96 candidates: list[CarryForwardCandidate] = []
97 skipped: list[tuple[str, str]] = []
98 for key, rule in sorted(latest_rules.items()):
99 source_note = source_notes.get(rule.target_note_id)
100 if source_note is None:
101 skipped.append((key, "source_note_missing"))
102 elif latest_source_notes[source_note.note_number].id != source_note.id:
103 skipped.append((key, "source_note_stale"))
104 elif rule.account_code not in target_accounts:
105 skipped.append((key, "target_account_missing"))
106 elif source_note.note_number not in latest_target_notes:
107 skipped.append((key, "target_note_missing"))
108 elif key in target_rule_keys:
109 skipped.append((key, "target_rule_exists"))
110 else:
111 candidates.append(CarryForwardCandidate(
112 rule_key=key, account_code=rule.account_code,
113 source_note_number=source_note.note_number,
114 target_note_id=latest_target_notes[source_note.note_number].id,
115 mapping_type=rule.mapping_type, source_version=rule.version,
116 ))
117 return CarryForwardPreview(
118 source_year_id=source_year_id, target_year_id=target_year_id,
119 candidates=tuple(candidates), skipped=tuple(skipped),
120 )