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

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

Synced Dec 4, 05:30 UTC

arena/094f314c-aram
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 162 lines 5.54 KB
Raw
1 """Comprehensive mapping Excel import/export (Phase 2, booklet §15).
2
3 Round-trips account->note mappings through a governed workbook. Codes are text
4 (leading zeros preserved). Import is fail-closed: invalid rows are reported and
5 nothing partial is committed for them. Export joins mappings with note metadata
6 and the imported account names.
7 """
8
9 from __future__ import annotations
10
11 from dataclasses import dataclass, field
12 from io import BytesIO
13
14 from openpyxl import Workbook, load_workbook
15 from sqlalchemy import select
16 from sqlalchemy.orm import Session
17
18 from aram_backend.domain.normalization import normalize_code
19 from aram_backend.models import LedgerBalance, MappingRule, NoteDefinition
20
21 _HEADERS = (
22 "account_code",
23 "account_name",
24 "target_note_number",
25 "statement",
26 "section",
27 "mapping_type",
28 )
29 _VALID_STATEMENTS = {"BS", "IS", "CF", "EQ"}
30
31
32 class MappingImportError(ValueError):
33 """Raised when a mapping workbook cannot be imported safely."""
34
35
36 @dataclass
37 class MappingImportResult:
38 created: int = 0
39 notes_created: int = 0
40 errors: list[str] = field(default_factory=list)
41
42
43 def _latest_note(session: Session, year_id: int, note_number: str) -> NoteDefinition | None:
44 return session.scalar(
45 select(NoteDefinition)
46 .where(NoteDefinition.year_id == year_id, NoteDefinition.note_number == note_number)
47 .order_by(NoteDefinition.version.desc())
48 .limit(1)
49 )
50
51
52 def export_mappings_workbook(session: Session, year_id: int) -> bytes:
53 rules = session.scalars(
54 select(MappingRule).where(MappingRule.year_id == year_id).order_by(MappingRule.account_code)
55 ).all()
56 names: dict[str, str] = {}
57 for balance in session.scalars(
58 select(LedgerBalance).where(LedgerBalance.year_id == year_id)
59 ).all():
60 names.setdefault(balance.account_full_code, balance.account_name)
61
62 wb = Workbook()
63 ws = wb.active
64 ws.title = "Mappings"
65 ws.append(list(_HEADERS))
66 for rule in rules:
67 note = rule.target_note
68 config = note.configuration_json if note else {}
69 ws.append(
70 [
71 rule.account_code,
72 names.get(rule.account_code, ""),
73 note.note_number if note else "",
74 config.get("statement", ""),
75 config.get("section", ""),
76 rule.mapping_type,
77 ]
78 )
79 buf = BytesIO()
80 wb.save(buf)
81 wb.close()
82 return buf.getvalue()
83
84
85 def import_mappings_workbook(session: Session, year_id: int, content: bytes) -> MappingImportResult:
86 wb = load_workbook(BytesIO(content), read_only=True, data_only=True, keep_links=False)
87 try:
88 ws = wb["Mappings"] if "Mappings" in wb.sheetnames else wb.active
89 rows = ws.iter_rows(values_only=True)
90 header = next(rows, None)
91 if header is None:
92 raise MappingImportError("mapping workbook is empty")
93 idx = {str(v).strip(): i for i, v in enumerate(header) if v is not None}
94 missing = [h for h in _HEADERS if h not in idx and h != "account_name"]
95 if missing:
96 raise MappingImportError(f"mapping workbook missing columns: {missing}")
97
98 result = MappingImportResult()
99 for row_number, vals in enumerate(rows, start=2):
100 if vals is None or not any(v is not None and str(v).strip() for v in vals):
101 continue
102 try:
103 code = normalize_code(
104 vals[idx["account_code"]], row=row_number, field="account_code"
105 )
106 note_number = str(vals[idx["target_note_number"]]).strip()
107 statement = str(vals[idx["statement"]]).strip().upper()
108 section = str(vals[idx["section"]]).strip()
109 mapping_type = str(vals[idx["mapping_type"]]).strip() or "closing"
110 if not note_number:
111 raise ValueError("target_note_number is required")
112 if statement not in _VALID_STATEMENTS:
113 raise ValueError(f"invalid statement '{statement}'")
114 if not section:
115 raise ValueError("section is required")
116 except (ValueError, KeyError) as exc:
117 result.errors.append(f"row {row_number}: {exc}")
118 continue
119
120 note = _latest_note(session, year_id, note_number)
121 if note is None:
122 note = NoteDefinition(
123 year_id=year_id,
124 note_number=note_number,
125 title=note_number,
126 configuration_json={"statement": statement, "section": section},
127 )
128 session.add(note)
129 session.flush()
130 result.notes_created += 1
131
132 existing = session.scalar(
133 select(MappingRule).where(
134 MappingRule.year_id == year_id,
135 MappingRule.account_code == code,
136 MappingRule.target_note_id == note.id,
137 )
138 )
139 if existing is not None:
140 continue
141 session.add(
142 MappingRule(
143 year_id=year_id,
144 rule_key=f"{code}->{note.id}",
145 account_code=code,
146 target_note_id=note.id,
147 mapping_type=mapping_type,
148 )
149 )
150 result.created += 1
151 session.flush()
152 return result
153 finally:
154 wb.close()
155
156
157 __all__ = [
158 "export_mappings_workbook",
159 "import_mappings_workbook",
160 "MappingImportResult",
161 "MappingImportError",
162 ]