Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 13:00 UTC
fix(services): mypy-clean services + generic golden columns + negative tests (audit #4)
- Type-annotate all services so mypy passes (dict/tuple generics, cast, isinstance AST walks, typed sort key, renamed shadowed variable). - golden: resolve note/year/statement-balance columns BY HEADER NAME (1403 and 1404 ledgers have different layouts); fixes 1403 comparison, keeps it generic. - mapping_workflow negative tests: nonexistent carry-forward target, inactive accounts excluded, raw-row aggregation in queue, empty mapping workbook rejected. mypy services+domain clean; golden 1403+1404 real-data tests pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
davoodmehraban89 committed
Dec 3, 2026 at 10:35 UTC
225a38c0b15c7187d036261081941662dc73d1ab
6 files changed
+106
-45
backend/src/aram_backend/services/audit.py
+2
-2
@@ -19,7 +19,7 @@ from aram_backend.models import AuditEntry
19
GENESIS_HASH = "0" * 64
20
21
22
-def _payload_hash(action: str, actor: str, year_id: int | None, payload: dict) -> str:
22
+def _payload_hash(action: str, actor: str, year_id: int | None, payload: dict[str, object]) -> str:
23
canonical = json.dumps(
24
{"action": action, "actor": actor, "year_id": year_id, "payload": payload},
25
sort_keys=True,
@@ -39,7 +39,7 @@ def append_entry(
39
action: str,
40
actor: str = "",
41
year_id: int | None = None,
42
- payload: dict | None = None,
42
+ payload: dict[str, object] | None = None,
43
) -> AuditEntry:
44
"""Append a new audit entry, chaining from the current head."""
45
payload = payload or {}
backend/src/aram_backend/services/golden.py
+32
-17
@@ -42,23 +42,34 @@ class NoteComparison:
42
43
44
def aggregate_source_by_note(source_path: str | Path, year: int) -> dict[str, Decimal]:
45
- """Sum the source statement balance (column 25) by note number (column 0)."""
45
+ """Sum the source statement balance by note number, locating columns by header.
46
+
47
+ Column positions differ between ledger vintages (e.g. 1403 vs 1404), so the
48
+ note / year / statement-balance columns are resolved by header name, never by
49
+ a fixed index. This keeps the comparison generic across source layouts.
50
+ """
51
wb = load_workbook(source_path, read_only=True, data_only=True, keep_links=False)
52
try:
53
ws = wb["Source"]
54
rows = ws.iter_rows(values_only=True)
50
- next(rows)
51
- next(rows)
55
+ next(rows) # title row
56
+ header = next(rows)
57
+ idx = {str(h).strip(): i for i, h in enumerate(header) if h is not None}
58
+ note_i = idx.get("یادداشت کل")
59
+ year_i = idx.get("year")
60
+ balance_i = idx.get("مانده صورت مالی")
61
+ if note_i is None or year_i is None or balance_i is None:
62
+ raise ValueError("source ledger missing note/year/statement-balance headers")
63
sums: dict[str, Decimal] = defaultdict(lambda: Decimal(0))
64
for vals in rows:
65
if not any(v is not None for v in vals):
66
continue
56
- if str(vals[6]) != str(year):
67
+ if str(vals[year_i]) != str(year):
68
continue
58
- note = str(vals[0]).strip() if vals[0] is not None else ""
69
+ note = str(vals[note_i]).strip() if vals[note_i] is not None else ""
70
if note in _UNMAPPED:
71
continue
61
- balance = vals[25]
72
+ balance = vals[balance_i]
73
if balance is None:
74
continue
75
sums[note] += Decimal(str(balance))
@@ -87,14 +98,20 @@ def read_official_notes(official_path: str | Path, sheet: str, year: int) -> dic
98
if i < len(row) and row[i] is not None and _NOTE_RE.fullmatch(str(row[i]).strip()):
99
note = str(row[i]).strip()
100
break
90
- if note is not None and amount_col < len(row) and isinstance(row[amount_col], (int, float)):
101
+ if (
102
+ note is not None
103
+ and amount_col < len(row)
104
+ and isinstance(row[amount_col], (int, float))
105
+ ):
106
notes[note] = int(row[amount_col])
107
return notes
108
finally:
109
wb.close()
110
111
97
-def compare_year(source_path: str | Path, official_path: str | Path, year: int) -> list[NoteComparison]:
112
+def compare_year(
113
+ source_path: str | Path, official_path: str | Path, year: int
114
+) -> list[NoteComparison]:
115
source = aggregate_source_by_note(source_path, year)
116
comparisons: list[NoteComparison] = []
117
for statement, sheet in STATEMENT_SHEETS.items():
@@ -117,19 +134,17 @@ def compare_year(source_path: str | Path, official_path: str | Path, year: int)
134
return comparisons
135
136
120
-def write_discrepancies(comparisons: list[NoteComparison], out_path: str | Path) -> dict:
137
+def write_discrepancies(comparisons: list[NoteComparison], out_path: str | Path) -> dict[str, int]:
138
discrepancies = [asdict(c) for c in comparisons if not c.match]
139
matched = sum(1 for c in comparisons if c.match)
123
- payload = {
124
- "summary": {
125
- "total": len(comparisons),
126
- "matched": matched,
127
- "discrepancies": len(discrepancies),
128
- },
129
- "discrepancies": discrepancies,
140
+ summary: dict[str, int] = {
141
+ "total": len(comparisons),
142
+ "matched": matched,
143
+ "discrepancies": len(discrepancies),
144
}
145
+ payload: dict[str, object] = {"summary": summary, "discrepancies": discrepancies}
146
Path(out_path).write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
132
- return payload["summary"]
147
+ return summary
148
149
150
__all__ = [
backend/src/aram_backend/services/mapping_workflow.py
+4
-4
@@ -28,7 +28,7 @@ class CarryForwardError(ValueError):
28
"""Raised when carry-forward is attempted on an invalid state."""
29
30
31
-def unknown_accounts(session: Session, year_id: int) -> list[dict]:
31
+def unknown_accounts(session: Session, year_id: int) -> list[dict[str, object]]:
32
"""Active accounts with no mapping, aggregated from raw rows (compute layer)."""
33
mapped = {
34
r.account_code
@@ -48,7 +48,7 @@ def unknown_accounts(session: Session, year_id: int) -> list[dict]:
48
"row_count": total.row_count,
49
}
50
)
51
- queue.sort(key=lambda item: item["account_full_code"])
51
+ queue.sort(key=lambda item: str(item["account_full_code"]))
52
return queue
53
54
@@ -101,14 +101,14 @@ def carry_forward_mappings(
101
target_note_id = note_map.get(rule.target_note_id)
102
if target_note_id is None:
103
continue
104
- existing = session.scalar(
104
+ existing_rule = session.scalar(
105
select(MappingRule).where(
106
MappingRule.year_id == to_year_id,
107
MappingRule.account_code == rule.account_code,
108
MappingRule.target_note_id == target_note_id,
109
)
110
)
111
- if existing is not None:
111
+ if existing_rule is not None:
112
continue
113
session.add(
114
MappingRule(
backend/src/aram_backend/services/note_engine.py
+22
-13
@@ -9,11 +9,20 @@ for drill-down.
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
16
-from aram_backend.domain.formula import Call, FormulaError, eval_formula, parse_formula
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)
@@ -41,13 +50,13 @@ def _balances(session: Session, year_id: int) -> dict[str, LedgerBalance]:
50
def _referenced_accounts(node: object) -> set[str]:
51
found: set[str] = set()
52
if isinstance(node, Call):
44
- if node.name == "acct" and node.args and hasattr(node.args[0], "value"):
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)
48
- elif hasattr(node, "left"):
57
+ elif isinstance(node, Binary):
58
found |= _referenced_accounts(node.left) | _referenced_accounts(node.right)
50
- elif hasattr(node, "operand"):
59
+ elif isinstance(node, Unary):
60
found |= _referenced_accounts(node.operand)
61
return found
62
@@ -57,8 +66,8 @@ def evaluate_note(
66
note_id: int,
67
*,
68
_stack: tuple[int, ...] = (),
60
- _cache: dict[int, dict] | None = None,
61
-) -> dict:
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:
@@ -71,7 +80,7 @@ def evaluate_note(
80
rows = sorted(note.rows, key=lambda r: r.row_order)
81
values: dict[int, Decimal] = {}
82
stack = _stack + (note_id,)
74
- cache = _cache if _cache is not None else {}
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(
@@ -85,12 +94,12 @@ def evaluate_note(
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)
88
- for row in result["rows"]:
97
+ for row in cast(list[dict[str, object]], result["rows"]):
98
if row["row_order"] == row_order:
90
- return Decimal(row["value"])
99
+ return Decimal(str(row["value"]))
100
raise FormulaError(f"note '{note_number}' has no row {row_order}")
101
93
- def resolver(name: str, args: tuple) -> Decimal:
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")
@@ -100,7 +109,7 @@ def evaluate_note(
109
balance = balances.get(args[0])
110
if balance is None:
111
raise FormulaError(f"account '{args[0]}' not found in the latest import")
103
- return getattr(balance, field)
112
+ return cast(Decimal, getattr(balance, field))
113
if name == "row":
114
if not args:
115
raise FormulaError("row() requires a row order")
@@ -155,13 +164,13 @@ def evaluate_note(
164
return result
165
166
158
-def evaluate_year_notes(session: Session, year_id: int) -> list[dict]:
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()
164
- cache: dict[int, dict] = {}
173
+ cache: dict[int, dict[str, object]] = {}
174
return [evaluate_note(session, note.id, _cache=cache) for note in notes]
175
176
backend/src/aram_backend/services/statement_build.py
+7
-9
@@ -151,14 +151,12 @@ def build_statements(
151
member_notes = [
152
n for n in notes.values() if n.configuration_json.get("statement") == stype_code
153
]
154
- member_notes.sort(
155
- key=lambda n: (
156
- order.index(n.configuration_json.get("section"))
157
- if n.configuration_json.get("section") in order
158
- else len(order),
159
- n.note_number,
160
- )
161
- )
154
+
155
+ def _sort_key(n: NoteDefinition, order: list[str] = order) -> tuple[int, str]:
156
+ section = str(n.configuration_json.get("section") or "")
157
+ return (order.index(section) if section in order else len(order), n.note_number)
158
+
159
+ member_notes.sort(key=_sort_key)
160
161
statement = FinancialStatement(
162
year_id=year_id,
@@ -191,7 +189,7 @@ def build_statements(
189
return BuildResult(statements=tuple(built), unmapped_accounts=tuple(sorted(set(unmapped))))
190
191
194
-def drill_down(session: Session, statement_line_id: int) -> dict:
192
+def drill_down(session: Session, statement_line_id: int) -> dict[str, object]:
193
"""Return the full lineage of a statement line to source file/sheet/row."""
194
line = session.get(StatementLine, statement_line_id)
195
if line is None:
backend/tests/test_mapping_workflow.py
+39
@@ -250,3 +250,42 @@ class TestPhase2Api:
250
# Now approval succeeds.
251
ok = c.post(f"/api/v1/years/{year_id}/approve", json={"actor": "r"}).json()
252
assert ok["approved"] is True
253
+
254
+
255
+class TestMappingWorkflowNegative:
256
+ def test_carry_forward_nonexistent_target_raises(self, session):
257
+ source_year = _balanced_mapped(session)
258
+ with pytest.raises(CarryForwardError):
259
+ carry_forward_mappings(session, source_year.id, 999999)
260
+
261
+ def test_unknown_queue_excludes_inactive_accounts(self, session):
262
+ year, source = _setup(session)
263
+ _balance(session, year, source, "148348", 0, 3) # all-zero -> inactive
264
+ session.flush()
265
+ assert unknown_accounts(session, year.id) == []
266
+
267
+ def test_unknown_queue_aggregates_raw_rows(self, session):
268
+ year, source = _setup(session)
269
+ _balance(session, year, source, "148348", 100, 3)
270
+ _balance(session, year, source, "148348", 200, 4) # same account, second raw row
271
+ session.flush()
272
+ queue = unknown_accounts(session, year.id)
273
+ assert len(queue) == 1 # deduped by account
274
+ assert queue[0]["account_full_code"] == "148348"
275
+ assert queue[0]["closing"] == "300" # aggregated in compute layer
276
+ assert queue[0]["row_count"] == 2
277
+
278
+ def test_mapping_import_empty_workbook_raises(self, session):
279
+ from io import BytesIO
280
+
281
+ from openpyxl import Workbook
282
+
283
+ from aram_backend.services.mapping_io import MappingImportError
284
+
285
+ year, _ = _setup(session)
286
+ wb = Workbook()
287
+ wb.active.title = "Mappings" # header-less
288
+ buf = BytesIO()
289
+ wb.save(buf)
290
+ with pytest.raises(MappingImportError):
291
+ import_mappings_workbook(session, year.id, buf.getvalue())