@davoodmehraban89 / Aram / commits / fe2cd36
Fork 0

feat(finance): add read-only explicit-scope trial balance arithmetic diagnostic

davoodmehraban89 committed Oct 31, 2026 at 06:50 UTC fe2cd36eca15e303d5a98755a201f190714af590
1 file changed +205
backend/src/aram_backend/trial_balance_diagnostic.py new
+205
@@ -0,0 +1,205 @@
1 +"""Read-only trial balance diagnostic for an authorized Pilot XLSX snapshot.
2 +
3 +This checks source account arithmetic and debit/credit equality within an
4 +explicit company-year scope. It does not perform financial postings, issue
5 +audited statements, or assert that the provided ledger is complete.
6 +"""
7 +from __future__ import annotations
8 +
9 +from dataclasses import asdict, dataclass
10 +from hashlib import sha256
11 +from io import BytesIO
12 +from typing import Any
13 +
14 +from openpyxl import load_workbook
15 +
16 +from aram_backend.coverage_preview import (
17 + CoverageError, MAX_INPUT_BYTES, _assert_visible, _guard_archive,
18 +)
19 +from aram_backend.pilot_workbook import SHEET_HEADERS, preflight_pilot_workbook
20 +from aram_backend.reconciliation_review import _money, _sum_exact
21 +
22 +
23 +@dataclass(frozen=True)
24 +class TrialBalanceAccount:
25 + account_code: str
26 + account_name: str
27 + excel_row: int
28 + source_row: int
29 + opening: str
30 + debit: str
31 + credit: str
32 + closing: str
33 + debit_net_movement: str
34 +
35 +
36 +@dataclass(frozen=True)
37 +class TrialBalanceDiagnostic:
38 + company_code: str
39 + fiscal_year: int
40 + source_sha256: str
41 + account_count: int
42 + opening_debit_net_total: str
43 + debit_turnover_total: str
44 + credit_turnover_total: str
45 + closing_debit_net_total: str
46 + movement_difference: str
47 + opening_to_closing_difference: str
48 + findings: tuple[str, ...]
49 + accounts: tuple[TrialBalanceAccount, ...]
50 + balanced_for_analyst_review: bool
51 + kind: str = "UNAPPROVED_TRIAL_BALANCE_DIAGNOSTIC"
52 + source_ledger_completeness_verified: bool = False
53 + accounting_policies_verified: bool = False
54 + official_financial_statement: bool = False
55 + independently_reviewed: bool = False
56 + releasable: bool = False
57 +
58 + def to_dict(self) -> dict[str, Any]:
59 + return asdict(self)
60 +
61 +
62 +def _scoped(row: dict[str, Any], *, company: str, fiscal_year: int) -> bool:
63 + return (
64 + isinstance(row.get("company_code"), str)
65 + and row["company_code"].strip() == company
66 + and type(row.get("fiscal_year")) is int
67 + and row["fiscal_year"] == fiscal_year
68 + )
69 +
70 +
71 +def _read_records(sheet: Any, columns: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]:
72 + records: list[tuple[int, dict[str, Any]]] = []
73 + for row_number, values in enumerate(
74 + sheet.iter_rows(min_row=2, values_only=True), 2
75 + ):
76 + row = dict(zip(columns, values))
77 + if any(cell is not None and str(cell).strip() for cell in row.values()):
78 + records.append((row_number, row))
79 + return records
80 +
81 +
82 +def analyze_trial_balance(
83 + workbook_bytes: bytes, *, company_code: str, fiscal_year: int,
84 +) -> TrialBalanceDiagnostic:
85 + """Reconcile row and column totals without claiming source completeness.
86 +
87 + The check assumes opening and closing figures are *debit-net*, meaning a
88 + credit-net account has a negative balance. It does not infer the sign from
89 + an account label. Incorrectly signed input can appear balanced, so the
90 + result is NEVER sufficient for financial authorization or release.
91 + """
92 + if (not isinstance(company_code, str) or not company_code.strip()
93 + or len(company_code) > 64):
94 + raise CoverageError("TRIAL_BALANCE_COMPANY_SCOPE_INVALID")
95 + if type(fiscal_year) is not int or fiscal_year <= 0:
96 + raise CoverageError("TRIAL_BALANCE_YEAR_SCOPE_INVALID")
97 + if (not isinstance(workbook_bytes, bytes)
98 + or not 0 < len(workbook_bytes) <= MAX_INPUT_BYTES):
99 + raise CoverageError("TRIAL_BALANCE_SIZE_INVALID")
100 + _guard_archive(workbook_bytes)
101 + try:
102 + preflight = preflight_pilot_workbook(workbook_bytes)
103 + except Exception as exc:
104 + raise CoverageError("TRIAL_BALANCE_WORKBOOK_INVALID") from exc
105 + if not preflight.valid:
106 + raise CoverageError("TRIAL_BALANCE_WORKBOOK_INVALID")
107 +
108 + try:
109 + book = load_workbook(
110 + BytesIO(workbook_bytes), read_only=False,
111 + data_only=False, keep_links=False,
112 + )
113 + except Exception as exc:
114 + raise CoverageError("TRIAL_BALANCE_WORKBOOK_INVALID") from exc
115 + try:
116 + for sheet in book.worksheets:
117 + _assert_visible(sheet)
118 + for name, expected in SHEET_HEADERS.items():
119 + if name not in book or tuple(cell.value for cell in book[name][1]) != expected:
120 + raise CoverageError("TRIAL_BALANCE_WORKBOOK_INVALID")
121 +
122 + company = company_code.strip()
123 + scope = {"company": company, "fiscal_year": fiscal_year}
124 + companies = [
125 + row for _, row in _read_records(book["Company"], SHEET_HEADERS["Company"])
126 + if _scoped(row, **scope)
127 + ]
128 + if len(companies) != 1:
129 + raise CoverageError("TRIAL_BALANCE_COMPANY_NOT_FOUND")
130 +
131 + accounts: list[TrialBalanceAccount] = []
132 + openings = []
133 + debits = []
134 + credits = []
135 + closings = []
136 + net_movements = []
137 + codes: set[str] = set()
138 +
139 + for row_number, row in _read_records(book["Accounts"], SHEET_HEADERS["Accounts"]):
140 + if not _scoped(row, **scope):
141 + continue
142 + code = row.get("account_full_code")
143 + if not isinstance(code, str) or not code.strip():
144 + raise CoverageError("TRIAL_BALANCE_ACCOUNT_CODE_INVALID")
145 + code = code.strip()
146 + if code in codes:
147 + raise CoverageError("TRIAL_BALANCE_DUPLICATE_ACCOUNT")
148 + codes.add(code)
149 + opening, debit, credit, closing = (
150 + _money(str(row[key])) for key in ("opening", "debit", "credit", "closing")
151 + )
152 + movement = _sum_exact([debit, -credit])
153 + if opening + movement != closing:
154 + raise CoverageError("TRIAL_BALANCE_ROW_DELTA_INVALID")
155 + if debit < 0 or credit < 0:
156 + raise CoverageError("TRIAL_BALANCE_NEGATIVE_TURNOVER")
157 + if row.get("source_row") is None or type(row["source_row"]) is not int:
158 + raise CoverageError("TRIAL_BALANCE_SOURCE_ROW_INVALID")
159 + accounts.append(TrialBalanceAccount(
160 + account_code=code, account_name=str(row["account_name"]),
161 + excel_row=row_number, source_row=row["source_row"],
162 + opening=str(opening), debit=str(debit), credit=str(credit),
163 + closing=str(closing), debit_net_movement=str(movement),
164 + ))
165 + openings.append(opening)
166 + debits.append(debit)
167 + credits.append(credit)
168 + closings.append(closing)
169 + net_movements.append(movement)
170 +
171 + if not accounts:
172 + raise CoverageError("TRIAL_BALANCE_NO_ACCOUNTS")
173 + opening_total = _sum_exact(openings)
174 + debit_total = _sum_exact(debits)
175 + credit_total = _sum_exact(credits)
176 + closing_total = _sum_exact(closings)
177 + net_total = _sum_exact(net_movements)
178 + movement_diff = _sum_exact([debit_total, -credit_total])
179 + rolling_diff = _sum_exact([opening_total, net_total, -closing_total])
180 + findings: list[str] = []
181 + if opening_total != 0:
182 + findings.append("OPENING_DEBIT_NET_UNBALANCED")
183 + if movement_diff != 0:
184 + findings.append("DEBIT_CREDIT_TURNOVER_UNBALANCED")
185 + if closing_total != 0:
186 + findings.append("CLOSING_DEBIT_NET_UNBALANCED")
187 + if rolling_diff != 0:
188 + findings.append("ROLL_FORWARD_INCONSISTENT")
189 +
190 + return TrialBalanceDiagnostic(
191 + company_code=company, fiscal_year=fiscal_year,
192 + source_sha256=sha256(workbook_bytes).hexdigest(),
193 + account_count=len(accounts),
194 + opening_debit_net_total=str(opening_total),
195 + debit_turnover_total=str(debit_total),
196 + credit_turnover_total=str(credit_total),
197 + closing_debit_net_total=str(closing_total),
198 + movement_difference=str(movement_diff),
199 + opening_to_closing_difference=str(rolling_diff),
200 + findings=tuple(findings),
201 + accounts=tuple(sorted(accounts, key=lambda acc: acc.account_code)),
202 + balanced_for_analyst_review=not findings,
203 + )
204 + finally:
205 + book.close()