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

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

Synced Dec 4, 10:30 UTC

arena/2d4eda07-aram
add-index-html-10623938925177053894 arena/094f314c-aram arena/2d4eda07-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 177 lines 6.18 KB
Raw
1 """Note engine (Phase 3, ADR-020): evaluate disclosure-row formulas safely.
2
3 Computes note row values on demand from the latest ledger import using the safe
4 formula grammar (no eval). Rows may reference earlier rows and other notes; cross
5 note references are cycle-detected. Each row reports the accounts it references
6 for drill-down.
7 """
8
9 from __future__ import annotations
10
11 from decimal import Decimal
12 from typing import Any, cast
13
14 from sqlalchemy import func, select
15 from sqlalchemy.orm import Session
16
17 from aram_backend.domain.formula import (
18 Binary,
19 Call,
20 FormulaError,
21 Str,
22 Unary,
23 eval_formula,
24 parse_formula,
25 )
26 from aram_backend.models import LedgerBalance, NoteDefinition
27
28 _ZERO = Decimal(0)
29 _FIELDS = {"opening", "debit", "credit", "closing"}
30
31
32 class NoteEngineError(ValueError):
33 """Raised when a note cannot be evaluated."""
34
35
36 def _balances(session: Session, year_id: int) -> dict[str, LedgerBalance]:
37 version = session.scalar(
38 select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
39 )
40 if version is None:
41 return {}
42 rows = session.scalars(
43 select(LedgerBalance).where(
44 LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
45 )
46 ).all()
47 return {b.account_full_code: b for b in rows}
48
49
50 def _referenced_accounts(node: object) -> set[str]:
51 found: set[str] = set()
52 if isinstance(node, Call):
53 if node.name == "acct" and node.args and isinstance(node.args[0], Str):
54 found.add(node.args[0].value)
55 for arg in node.args:
56 found |= _referenced_accounts(arg)
57 elif isinstance(node, Binary):
58 found |= _referenced_accounts(node.left) | _referenced_accounts(node.right)
59 elif isinstance(node, Unary):
60 found |= _referenced_accounts(node.operand)
61 return found
62
63
64 def evaluate_note(
65 session: Session,
66 note_id: int,
67 *,
68 _stack: tuple[int, ...] = (),
69 _cache: dict[int, dict[str, object]] | None = None,
70 ) -> dict[str, object]:
71 if _cache is not None and note_id in _cache:
72 return _cache[note_id]
73 if note_id in _stack:
74 raise NoteEngineError(f"circular note reference involving note {note_id}")
75 note = session.get(NoteDefinition, note_id)
76 if note is None:
77 raise NoteEngineError(f"note {note_id} does not exist")
78
79 balances = _balances(session, note.year_id)
80 rows = sorted(note.rows, key=lambda r: r.row_order)
81 values: dict[int, Decimal] = {}
82 stack = _stack + (note_id,)
83 cache: dict[int, dict[str, object]] = _cache if _cache is not None else {}
84
85 def _other_note_row(note_number: str, row_order: int) -> Decimal:
86 other = session.scalar(
87 select(NoteDefinition)
88 .where(
89 NoteDefinition.year_id == note.year_id, NoteDefinition.note_number == note_number
90 )
91 .order_by(NoteDefinition.version.desc())
92 .limit(1)
93 )
94 if other is None:
95 raise FormulaError(f"note '{note_number}' not found")
96 result = evaluate_note(session, other.id, _stack=stack, _cache=cache)
97 for row in cast(list[dict[str, object]], result["rows"]):
98 if row["row_order"] == row_order:
99 return Decimal(str(row["value"]))
100 raise FormulaError(f"note '{note_number}' has no row {row_order}")
101
102 def resolver(name: str, args: tuple[Any, ...]) -> Decimal:
103 if name == "acct":
104 if not args or not isinstance(args[0], str):
105 raise FormulaError("acct() requires an account code string")
106 field = args[1] if len(args) > 1 else "closing"
107 if field not in _FIELDS:
108 raise FormulaError(f"unknown account field '{field}'")
109 balance = balances.get(args[0])
110 if balance is None:
111 raise FormulaError(f"account '{args[0]}' not found in the latest import")
112 return cast(Decimal, getattr(balance, field))
113 if name == "row":
114 if not args:
115 raise FormulaError("row() requires a row order")
116 order = int(args[0])
117 if order not in values:
118 raise FormulaError(f"row {order} is not an earlier computed row")
119 return values[order]
120 if name == "note":
121 if len(args) < 2 or not isinstance(args[0], str):
122 raise FormulaError("note() requires a note number and row order")
123 return _other_note_row(args[0], int(args[1]))
124 if name == "sum":
125 return sum((Decimal(a) for a in args), _ZERO)
126 if name == "abs":
127 if len(args) != 1:
128 raise FormulaError("abs() requires one argument")
129 return abs(Decimal(args[0]))
130 raise FormulaError(f"unknown function '{name}'")
131
132 out_rows = []
133 for row in rows:
134 referenced: set[str] = set()
135 if row.formula_logic:
136 try:
137 ast = parse_formula(row.formula_logic)
138 referenced = _referenced_accounts(ast)
139 value = eval_formula(row.formula_logic, resolver)
140 except FormulaError as exc:
141 raise NoteEngineError(
142 f"note {note.note_number} row {row.row_order}: {exc}"
143 ) from exc
144 else:
145 value = _ZERO
146 values[row.row_order] = value
147 out_rows.append(
148 {
149 "row_order": row.row_order,
150 "label": row.label,
151 "formula": row.formula_logic,
152 "value": str(value),
153 "accounts_referenced": sorted(referenced),
154 }
155 )
156
157 result = {
158 "note_id": note.id,
159 "note_number": note.note_number,
160 "title": note.title,
161 "rows": out_rows,
162 }
163 cache[note_id] = result
164 return result
165
166
167 def evaluate_year_notes(session: Session, year_id: int) -> list[dict[str, object]]:
168 notes = session.scalars(
169 select(NoteDefinition)
170 .where(NoteDefinition.year_id == year_id)
171 .order_by(NoteDefinition.note_number)
172 ).all()
173 cache: dict[int, dict[str, object]] = {}
174 return [evaluate_note(session, note.id, _cache=cache) for note in notes]
175
176
177 __all__ = ["evaluate_note", "evaluate_year_notes", "NoteEngineError"]