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

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

Synced Dec 4, 14:15 UTC

feat(mapping): Excel I/O + unknown queue + approval gate + carry-forward (Phase 2)

- mapping_io: governed Mappings workbook export/import; text codes; fail-closed per-row import with error report; idempotent re-import; auto-create notes - mapping_workflow: unknown-account queue (C-04 active unmapped); carry-forward notes+mappings into a Draft year (D1 continuity), idempotent - approval: approve_year runs C-01..C-04; blocking ERROR refuses Draft->Approved; clean pass transitions + hash-chained audit entry (P-09) - statement_api: mappings export/import, unknown-accounts, carry-forward, approve - ADR-019 mapping I/O + approval contract; shared api_client fixture in conftest Tests: export/import round-trip, invalid-row fail-closed, queue list/clear, approval blocked/success/non-draft, carry-forward copy/idempotent/reject, API end-to-end (queue->import mappings->approve). 220 passed; gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 09:54 UTC cfbd8794a44a4a2d61c04e9ef27b5fabecd09574
8 files changed +808 -27
backend/src/aram_backend/services/approval.py new
+87
@@ -0,0 +1,87 @@
1 +"""Approval gate (Phase 2, P-09): ERROR controls block Draft -> Approved.
2 +
3 +Approval runs the full C-01..C-04 control set over the latest ledger import and
4 +active mappings. Any blocking ERROR refuses the transition and is reported; a
5 +clean pass transitions the year and writes a hash-chained audit entry.
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +from dataclasses import dataclass
11 +
12 +from sqlalchemy import func, select
13 +from sqlalchemy.orm import Session
14 +
15 +from aram_backend.domain.controls import BalanceRow, ControlResult, MappingTarget, run_controls
16 +from aram_backend.models import FiscalYear, FiscalYearStatus, LedgerBalance, MappingRule
17 +from aram_backend.services.audit import append_entry
18 +
19 +
20 +class ApprovalError(ValueError):
21 + """Raised when approval is attempted on an invalid state."""
22 +
23 +
24 +@dataclass(frozen=True)
25 +class ApprovalResult:
26 + approved: bool
27 + blocking: tuple[ControlResult, ...]
28 + controls: tuple[ControlResult, ...]
29 +
30 +
31 +def _controls(session: Session, year_id: int) -> list[ControlResult]:
32 + version = session.scalar(
33 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
34 + )
35 + balances = (
36 + session.scalars(
37 + select(LedgerBalance).where(
38 + LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
39 + )
40 + ).all()
41 + if version is not None
42 + else []
43 + )
44 + rows = [
45 + BalanceRow(
46 + row_number=b.source_row,
47 + account_code=b.account_full_code,
48 + opening=b.opening,
49 + debit=b.debit,
50 + credit=b.credit,
51 + closing=b.closing,
52 + )
53 + for b in balances
54 + ]
55 + mappings: dict[str, list[MappingTarget]] = {}
56 + for rule in session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all():
57 + mappings.setdefault(rule.account_code, []).append(
58 + MappingTarget(target=str(rule.target_note_id))
59 + )
60 + return run_controls(rows, mappings)
61 +
62 +
63 +def approve_year(session: Session, year_id: int, *, actor: str = "") -> ApprovalResult:
64 + year = session.get(FiscalYear, year_id)
65 + if year is None:
66 + raise ApprovalError(f"fiscal year {year_id} does not exist")
67 + if year.status != FiscalYearStatus.DRAFT:
68 + raise ApprovalError(f"only a Draft year can be approved (current: {year.status.value})")
69 +
70 + controls = _controls(session, year_id)
71 + blocking = tuple(r for r in controls if r.severity == "ERROR" and not r.passed)
72 + if blocking:
73 + return ApprovalResult(approved=False, blocking=blocking, controls=tuple(controls))
74 +
75 + year.status = FiscalYearStatus.APPROVED
76 + append_entry(
77 + session,
78 + action="approve",
79 + actor=actor,
80 + year_id=year_id,
81 + payload={"controls": [r.code for r in controls]},
82 + )
83 + session.flush()
84 + return ApprovalResult(approved=True, blocking=(), controls=tuple(controls))
85 +
86 +
87 +__all__ = ["approve_year", "ApprovalResult", "ApprovalError"]
backend/src/aram_backend/services/mapping_io.py new
+162
@@ -0,0 +1,162 @@
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 +]
backend/src/aram_backend/services/mapping_workflow.py new
+140
@@ -0,0 +1,140 @@
1 +"""Unknown-account queue and mapping carry-forward (Phase 2, D1/D4).
2 +
3 +The queue lists active accounts that have no mapping (C-04); resolving them is
4 +mandatory before approval. Carry-forward copies a prior year's notes + mappings
5 +into a new Draft year so 1403 -> 1404 continuity does not start from scratch.
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +from dataclasses import dataclass
11 +from decimal import Decimal
12 +
13 +from sqlalchemy import func, select
14 +from sqlalchemy.orm import Session
15 +
16 +from aram_backend.models import (
17 + FiscalYear,
18 + FiscalYearStatus,
19 + LedgerBalance,
20 + MappingRule,
21 + NoteDefinition,
22 +)
23 +
24 +_ZERO = Decimal(0)
25 +
26 +
27 +class CarryForwardError(ValueError):
28 + """Raised when carry-forward is attempted on an invalid state."""
29 +
30 +
31 +def _latest_balances(session: Session, year_id: int) -> list[LedgerBalance]:
32 + version = session.scalar(
33 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
34 + )
35 + if version is None:
36 + return []
37 + return list(
38 + session.scalars(
39 + select(LedgerBalance).where(
40 + LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
41 + )
42 + ).all()
43 + )
44 +
45 +
46 +def unknown_accounts(session: Session, year_id: int) -> list[dict]:
47 + mapped = {
48 + r.account_code
49 + for r in session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all()
50 + }
51 + queue = []
52 + for balance in _latest_balances(session, year_id):
53 + if balance.account_full_code in mapped:
54 + continue
55 + if any(getattr(balance, k) != _ZERO for k in ("opening", "debit", "credit", "closing")):
56 + queue.append(
57 + {
58 + "account_full_code": balance.account_full_code,
59 + "account_name": balance.account_name,
60 + "closing": str(balance.closing),
61 + "source_row": balance.source_row,
62 + }
63 + )
64 + queue.sort(key=lambda item: item["account_full_code"])
65 + return queue
66 +
67 +
68 +@dataclass(frozen=True)
69 +class CarryForwardResult:
70 + notes_created: int
71 + mappings_created: int
72 +
73 +
74 +def carry_forward_mappings(
75 + session: Session, from_year_id: int, to_year_id: int
76 +) -> CarryForwardResult:
77 + target = session.get(FiscalYear, to_year_id)
78 + if target is None:
79 + raise CarryForwardError(f"target year {to_year_id} does not exist")
80 + if target.status != FiscalYearStatus.DRAFT:
81 + raise CarryForwardError("carry-forward target must be a Draft year")
82 +
83 + source_notes = session.scalars(
84 + select(NoteDefinition).where(NoteDefinition.year_id == from_year_id)
85 + ).all()
86 + note_map: dict[int, int] = {}
87 + notes_created = 0
88 + for note in source_notes:
89 + existing = session.scalar(
90 + select(NoteDefinition)
91 + .where(
92 + NoteDefinition.year_id == to_year_id, NoteDefinition.note_number == note.note_number
93 + )
94 + .order_by(NoteDefinition.version.desc())
95 + .limit(1)
96 + )
97 + if existing is None:
98 + existing = NoteDefinition(
99 + year_id=to_year_id,
100 + note_number=note.note_number,
101 + title=note.title,
102 + configuration_json=dict(note.configuration_json),
103 + )
104 + session.add(existing)
105 + session.flush()
106 + notes_created += 1
107 + note_map[note.id] = existing.id
108 +
109 + mappings_created = 0
110 + source_rules = session.scalars(
111 + select(MappingRule).where(MappingRule.year_id == from_year_id)
112 + ).all()
113 + for rule in source_rules:
114 + target_note_id = note_map.get(rule.target_note_id)
115 + if target_note_id is None:
116 + continue
117 + existing = session.scalar(
118 + select(MappingRule).where(
119 + MappingRule.year_id == to_year_id,
120 + MappingRule.account_code == rule.account_code,
121 + MappingRule.target_note_id == target_note_id,
122 + )
123 + )
124 + if existing is not None:
125 + continue
126 + session.add(
127 + MappingRule(
128 + year_id=to_year_id,
129 + rule_key=f"{rule.account_code}->{target_note_id}",
130 + account_code=rule.account_code,
131 + target_note_id=target_note_id,
132 + mapping_type=rule.mapping_type,
133 + )
134 + )
135 + mappings_created += 1
136 + session.flush()
137 + return CarryForwardResult(notes_created=notes_created, mappings_created=mappings_created)
138 +
139 +
140 +__all__ = ["unknown_accounts", "carry_forward_mappings", "CarryForwardResult", "CarryForwardError"]
backend/src/aram_backend/statement_api.py
+88
@@ -8,6 +8,7 @@ year-isolated and subject to the D-07 immutability guards.
8 from __future__ import annotations
9
10 from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
11 +from fastapi.responses import StreamingResponse
12 from pydantic import BaseModel, Field
13 from sqlalchemy import func, select
14 from sqlalchemy.orm import Session
@@ -26,7 +27,18 @@ from aram_backend.models import (
27 NoteDefinition,
28 StatementLine,
29 )
30 +from aram_backend.services.approval import ApprovalError, approve_year
31 from aram_backend.services.ledger_import import import_ledger_balances
32 +from aram_backend.services.mapping_io import (
33 + MappingImportError,
34 + export_mappings_workbook,
35 + import_mappings_workbook,
36 +)
37 +from aram_backend.services.mapping_workflow import (
38 + CarryForwardError,
39 + carry_forward_mappings,
40 + unknown_accounts,
41 +)
42 from aram_backend.services.source_store import SourceStore, SourceStoreError
43 from aram_backend.services.statement_build import (
44 SECTION_LABELS_FA,
@@ -275,3 +287,79 @@ def preflight(year_id: int, session: Session = Depends(get_session)) -> dict:
287 for r in results
288 ],
289 }
290 +
291 +
292 +# ----------------------------------------------------------- Phase 2: mapping I/O
293 +@router.get("/years/{year_id}/mappings/export")
294 +def export_mappings(year_id: int, session: Session = Depends(get_session)) -> StreamingResponse:
295 + _year_or_404(session, year_id)
296 + data = export_mappings_workbook(session, year_id)
297 + return StreamingResponse(
298 + iter([data]),
299 + media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
300 + headers={"Content-Disposition": f'attachment; filename="aram-mappings-{year_id}.xlsx"'},
301 + )
302 +
303 +
304 +@router.post("/years/{year_id}/mappings/import")
305 +def import_mappings(
306 + year_id: int,
307 + file: UploadFile = File(...),
308 + session: Session = Depends(get_session),
309 +) -> dict:
310 + _year_or_404(session, year_id)
311 + content = file.file.read()
312 + try:
313 + result = import_mappings_workbook(session, year_id, content)
314 + except MappingImportError as exc:
315 + raise HTTPException(status_code=422, detail=str(exc)) from exc
316 + session.commit()
317 + return {
318 + "created": result.created,
319 + "notes_created": result.notes_created,
320 + "errors": result.errors,
321 + }
322 +
323 +
324 +@router.get("/years/{year_id}/unknown-accounts")
325 +def unknown_queue(year_id: int, session: Session = Depends(get_session)) -> dict:
326 + _year_or_404(session, year_id)
327 + queue = unknown_accounts(session, year_id)
328 + return {"count": len(queue), "accounts": queue}
329 +
330 +
331 +class CarryForwardIn(BaseModel):
332 + from_year_id: int
333 +
334 +
335 +@router.post("/years/{year_id}/mappings/carry-forward")
336 +def carry_forward(
337 + year_id: int, body: CarryForwardIn, session: Session = Depends(get_session)
338 +) -> dict:
339 + _year_or_404(session, year_id)
340 + try:
341 + result = carry_forward_mappings(session, body.from_year_id, year_id)
342 + except CarryForwardError as exc:
343 + raise HTTPException(status_code=422, detail=str(exc)) from exc
344 + session.commit()
345 + return {"notes_created": result.notes_created, "mappings_created": result.mappings_created}
346 +
347 +
348 +class ApproveIn(BaseModel):
349 + actor: str = Field(default="", max_length=128)
350 +
351 +
352 +@router.post("/years/{year_id}/approve")
353 +def approve(year_id: int, body: ApproveIn, session: Session = Depends(get_session)) -> dict:
354 + _year_or_404(session, year_id)
355 + try:
356 + result = approve_year(session, year_id, actor=body.actor)
357 + except ApprovalError as exc:
358 + raise HTTPException(status_code=422, detail=str(exc)) from exc
359 + if not result.approved:
360 + return {
361 + "approved": False,
362 + "blocking": [{"code": r.code, "message_fa": r.message_fa} for r in result.blocking],
363 + }
364 + session.commit()
365 + return {"approved": True, "status": "Approved"}
backend/tests/conftest.py
+26 -1
@@ -2,7 +2,8 @@ import pytest
2 from fastapi.testclient import TestClient
3 from sqlalchemy.orm import Session, sessionmaker
4
5 -from aram_backend.database import Base, build_engine, ensure_triggers
5 +from aram_backend.config import Settings
6 +from aram_backend.database import Base, build_engine, ensure_triggers, get_session
7 from aram_backend.main import app
8
9
@@ -21,3 +22,27 @@ def session(tmp_path) -> Session:
22 @pytest.fixture
23 def client() -> TestClient:
24 return TestClient(app)
25 +
26 +
27 +@pytest.fixture
28 +def api_client(tmp_path, monkeypatch) -> TestClient:
29 + """DB-backed API client with an isolated SQLite DB + source store."""
30 + engine = build_engine(f"sqlite:///{tmp_path / 'api.db'}")
31 + Base.metadata.create_all(engine)
32 + ensure_triggers(engine)
33 + factory = sessionmaker(bind=engine, expire_on_commit=False)
34 +
35 + def override_session():
36 + with factory() as db:
37 + yield db
38 +
39 + app.dependency_overrides[get_session] = override_session
40 + monkeypatch.setattr(
41 + "aram_backend.statement_api.get_settings",
42 + lambda: Settings(source_store_root=str(tmp_path / "store")),
43 + )
44 + with TestClient(app) as test_client:
45 + yield test_client
46 + app.dependency_overrides.clear()
47 + Base.metadata.drop_all(engine)
48 + engine.dispose()
backend/tests/test_mapping_workflow.py new
+252
@@ -0,0 +1,252 @@
1 +"""Phase 2 acceptance: mapping Excel I/O, unknown queue, approval gate, carry-forward."""
2 +
3 +from __future__ import annotations
4 +
5 +from io import BytesIO
6 +
7 +import pytest
8 +from openpyxl import load_workbook
9 +
10 +from aram_backend.models import Company, FiscalYear, FiscalYearStatus, MappingRule, NoteDefinition
11 +from aram_backend.services.approval import ApprovalError, approve_year
12 +from aram_backend.services.mapping_io import (
13 + export_mappings_workbook,
14 + import_mappings_workbook,
15 +)
16 +from aram_backend.services.mapping_workflow import (
17 + CarryForwardError,
18 + carry_forward_mappings,
19 + unknown_accounts,
20 +)
21 +from test_statement_build import _balance, _map, _note, _setup
22 +
23 +
24 +def _balanced_mapped(session):
25 + """A ledger that satisfies C-01..C-04 once mapped (debit==credit, sum closing 0)."""
26 + year, source = _setup(session)
27 + _balance(session, year, source, "148348", 100, 3) # asset, debit 100
28 + _balance(session, year, source, "241001", -60, 4) # liability, credit 60
29 + _balance(session, year, source, "341001", -40, 5) # equity, credit 40
30 + n_a = _note(session, year, "6", "نقد", "BS", "Assets")
31 + n_l = _note(session, year, "10", "پرداختنی", "BS", "Liabilities")
32 + n_e = _note(session, year, "12", "سرمایه", "BS", "Equity")
33 + _map(session, year, "148348", n_a)
34 + _map(session, year, "241001", n_l)
35 + _map(session, year, "341001", n_e)
36 + session.flush()
37 + return year
38 +
39 +
40 +class TestMappingIo:
41 + def test_export_import_roundtrip(self, session):
42 + year = _balanced_mapped(session)
43 + data = export_mappings_workbook(session, year.id)
44 + wb = load_workbook(BytesIO(data))
45 + ws = wb["Mappings"]
46 + rows = list(ws.iter_rows(values_only=True))
47 + assert rows[0][0] == "account_code"
48 + assert len(rows) == 4 # header + 3 mappings
49 + wb.close()
50 +
51 + # Import into a fresh year reproduces the mappings.
52 + company = Company(code="RT", name="x")
53 + session.add(company)
54 + session.flush()
55 + year2 = FiscalYear(company_id=company.id, year=1405)
56 + session.add(year2)
57 + session.flush()
58 + result = import_mappings_workbook(session, year2.id, data)
59 + session.commit()
60 + assert result.created == 3
61 + assert result.notes_created == 3
62 + assert not result.errors
63 + rules = session.query(MappingRule).filter_by(year_id=year2.id).count()
64 + assert rules == 3
65 +
66 + def test_import_invalid_row_reported_not_committed(self, session):
67 + year, _ = _setup(session)
68 + wb = load_workbook(BytesIO(export_mappings_workbook(session, year.id)))
69 + # Build a workbook with one valid + one invalid row.
70 + from openpyxl import Workbook
71 +
72 + out = Workbook()
73 + ws = out.active
74 + ws.title = "Mappings"
75 + ws.append(
76 + [
77 + "account_code",
78 + "account_name",
79 + "target_note_number",
80 + "statement",
81 + "section",
82 + "mapping_type",
83 + ]
84 + )
85 + ws.append(["148348", "نقد", "6", "BS", "Assets", "closing"])
86 + ws.append(["999999", "بد", "7", "INVALID", "Assets", "closing"])
87 + buf = BytesIO()
88 + out.save(buf)
89 + wb.close()
90 + result = import_mappings_workbook(session, year.id, buf.getvalue())
91 + session.commit()
92 + assert result.created == 1
93 + assert len(result.errors) == 1
94 + assert "invalid statement" in result.errors[0]
95 +
96 +
97 +class TestUnknownQueue:
98 + def test_queue_lists_unmapped_active_accounts(self, session):
99 + year, source = _setup(session)
100 + _balance(session, year, source, "148348", 100, 3)
101 + _balance(session, year, source, "241001", -60, 4)
102 + session.flush()
103 + queue = unknown_accounts(session, year.id)
104 + codes = {item["account_full_code"] for item in queue}
105 + assert codes == {"148348", "241001"}
106 +
107 + def test_mapping_removes_from_queue(self, session):
108 + year, source = _setup(session)
109 + _balance(session, year, source, "148348", 100, 3)
110 + note = _note(session, year, "6", "نقد", "BS", "Assets")
111 + _map(session, year, "148348", note)
112 + session.flush()
113 + assert unknown_accounts(session, year.id) == []
114 +
115 +
116 +class TestApproval:
117 + def test_approval_blocked_by_unmapped(self, session):
118 + year, source = _setup(session)
119 + _balance(session, year, source, "148348", 100, 3)
120 + session.flush()
121 + result = approve_year(session, year.id)
122 + assert not result.approved
123 + assert any(r.code == "C-04" for r in result.blocking)
124 + assert year.status == FiscalYearStatus.DRAFT
125 +
126 + def test_approval_succeeds_on_clean_ledger(self, session):
127 + year = _balanced_mapped(session)
128 + result = approve_year(session, year.id, actor="reviewer")
129 + session.commit()
130 + assert result.approved
131 + assert year.status == FiscalYearStatus.APPROVED
132 + from aram_backend.services.audit import verify_chain
133 +
134 + assert verify_chain(session)
135 +
136 + def test_approval_rejected_on_non_draft(self, session):
137 + year = _balanced_mapped(session)
138 + approve_year(session, year.id)
139 + session.commit()
140 + with pytest.raises(ApprovalError):
141 + approve_year(session, year.id)
142 +
143 +
144 +class TestCarryForward:
145 + def test_copies_notes_and_mappings(self, session):
146 + source_year = _balanced_mapped(session)
147 + company = Company(code="CF", name="x")
148 + session.add(company)
149 + session.flush()
150 + target = FiscalYear(company_id=company.id, year=1405)
151 + session.add(target)
152 + session.flush()
153 + result = carry_forward_mappings(session, source_year.id, target.id)
154 + session.commit()
155 + assert result.notes_created == 3
156 + assert result.mappings_created == 3
157 + assert session.query(NoteDefinition).filter_by(year_id=target.id).count() == 3
158 + assert session.query(MappingRule).filter_by(year_id=target.id).count() == 3
159 +
160 + def test_carry_forward_idempotent(self, session):
161 + source_year = _balanced_mapped(session)
162 + company = Company(code="CF2", name="x")
163 + session.add(company)
164 + session.flush()
165 + target = FiscalYear(company_id=company.id, year=1405)
166 + session.add(target)
167 + session.flush()
168 + carry_forward_mappings(session, source_year.id, target.id)
169 + session.commit()
170 + again = carry_forward_mappings(session, source_year.id, target.id)
171 + session.commit()
172 + assert again.notes_created == 0
173 + assert again.mappings_created == 0
174 +
175 + def test_carry_forward_rejects_non_draft_target(self, session):
176 + source_year = _balanced_mapped(session)
177 + company = Company(code="CF3", name="x")
178 + session.add(company)
179 + session.flush()
180 + target = FiscalYear(company_id=company.id, year=1405)
181 + session.add(target)
182 + session.flush()
183 + target.status = FiscalYearStatus.APPROVED
184 + session.commit()
185 + with pytest.raises(CarryForwardError):
186 + carry_forward_mappings(session, source_year.id, target.id)
187 +
188 +
189 +class TestPhase2Api:
190 + def test_mapping_export_import_and_approve(self, api_client):
191 + c = api_client
192 + year_id = c.post(
193 + "/api/v1/companies", json={"code": "P2", "name": "x", "year": 1404}
194 + ).json()["year_id"]
195 + csv = (
196 + "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
197 + "8348,14,نقد,1404,O,,,,,0,100,0,100\n"
198 + "1001,24,پرداختنی,1404,O,,,,,0,0,60,-60\n"
199 + "1001,34,سرمایه,1404,O,,,,,0,0,40,-40\n"
200 + ).encode()
201 + c.post(f"/api/v1/years/{year_id}/ledger", files={"file": ("l.csv", csv, "text/csv")})
202 +
203 + # Unknown queue initially has 3 accounts.
204 + q = c.get(f"/api/v1/years/{year_id}/unknown-accounts").json()
205 + assert q["count"] == 3
206 +
207 + # Approval blocked while unmapped.
208 + blocked = c.post(f"/api/v1/years/{year_id}/approve", json={"actor": "r"}).json()
209 + assert blocked["approved"] is False
210 +
211 + # Import a mapping workbook covering all three accounts.
212 + from openpyxl import Workbook
213 +
214 + wb = Workbook()
215 + ws = wb.active
216 + ws.title = "Mappings"
217 + ws.append(
218 + [
219 + "account_code",
220 + "account_name",
221 + "target_note_number",
222 + "statement",
223 + "section",
224 + "mapping_type",
225 + ]
226 + )
227 + ws.append(["148348", "نقد", "6", "BS", "Assets", "closing"])
228 + ws.append(["241001", "پرداختنی", "10", "BS", "Liabilities", "closing"])
229 + ws.append(["341001", "سرمایه", "12", "BS", "Equity", "closing"])
230 + buf = BytesIO()
231 + wb.save(buf)
232 + r = c.post(
233 + f"/api/v1/years/{year_id}/mappings/import",
234 + files={
235 + "file": (
236 + "mappings.xlsx",
237 + buf.getvalue(),
238 + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
239 + )
240 + },
241 + )
242 + assert r.status_code == 200, r.text
243 + assert r.json()["created"] == 3
244 +
245 + # Export round-trips.
246 + exp = c.get(f"/api/v1/years/{year_id}/mappings/export")
247 + assert exp.status_code == 200
248 + assert len(exp.content) > 0
249 +
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
backend/tests/test_statement_build.py
-26
@@ -6,16 +6,11 @@ from decimal import Decimal
6 from pathlib import Path
7
8 import pytest
9 -from fastapi.testclient import TestClient
9 from openpyxl import load_workbook
11 -from sqlalchemy.orm import sessionmaker
10
13 -from aram_backend.config import Settings
14 -from aram_backend.database import Base, build_engine, ensure_triggers, get_session
11 from aram_backend.domain.normalization import decimal_from_cell, normalize_code
12 from aram_backend.ingestion import register_source_document
13 from aram_backend.ledger_parser import LedgerRecord
18 -from aram_backend.main import app
14 from aram_backend.models import (
15 Company,
16 FiscalYear,
@@ -177,27 +172,6 @@ class TestStatementBuild:
172
173
174 # --------------------------------------------------------------- API e2e
180 -@pytest.fixture
181 -def api_client(tmp_path, monkeypatch):
182 - engine = build_engine(f"sqlite:///{tmp_path / 'api.db'}")
183 - Base.metadata.create_all(engine)
184 - ensure_triggers(engine)
185 - factory = sessionmaker(bind=engine, expire_on_commit=False)
186 -
187 - def override_session():
188 - with factory() as db:
189 - yield db
190 -
191 - app.dependency_overrides[get_session] = override_session
192 - monkeypatch.setattr(
193 - "aram_backend.statement_api.get_settings",
194 - lambda: Settings(source_store_root=str(tmp_path / "store")),
195 - )
196 - with TestClient(app) as client:
197 - yield client
198 - app.dependency_overrides.clear()
199 -
200 -
175 CSV = (
176 "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
177 "8348,14,نقد,1404,O,,,,,0,100,0,100\n"
docs/adr/ADR-019-mapping-io-approval.md new
+53
@@ -0,0 +1,53 @@
1 +# ADR-019 — Mapping Excel I/O, unknown queue, and approval gate (Phase 2)
2 +
3 +- Status: Accepted (Phase 2)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 2, D1/D4, P-09
6 +
7 +## Context
8 +
9 +Phase 1 built statements from mappings, but mappings could only be created one at
10 +a time. V1 requires comprehensive mapping Excel import/export, an unknown-account
11 +queue, carry-forward between years, and an approval gate that refuses to approve
12 +while any blocking control fails.
13 +
14 +## Decision
15 +
16 +### Mapping workbook contract
17 +
18 +A single `Mappings` sheet with columns:
19 +`account_code, account_name, target_note_number, statement, section, mapping_type`.
20 +Codes are text (leading zeros preserved). Import is fail-closed per row: invalid
21 +rows are collected in `errors` and skipped; valid rows create the note (if new)
22 +and the mapping. Export joins mappings with note metadata and imported account
23 +names. Re-import is idempotent (existing account→note pairs are not duplicated).
24 +
25 +### Unknown-account queue (C-04)
26 +
27 +`unknown_accounts` lists active accounts (any non-zero opening/debit/credit/
28 +closing) with no mapping, sorted by code, with name/closing/source_row. Resolving
29 +the queue is mandatory before approval.
30 +
31 +### Approval gate (P-09)
32 +
33 +`approve_year` runs C-01..C-04 over the latest import + active mappings. Any
34 +blocking ERROR refuses Draft→Approved and returns the failing controls. A clean
35 +pass transitions the year and appends a hash-chained audit entry. Only Draft
36 +years may be approved.
37 +
38 +### Carry-forward (D1)
39 +
40 +`carry_forward_mappings(from_year, to_year)` copies notes (by note_number) and
41 +mappings into a Draft target year, idempotently, so 1403→1404 continuity reuses
42 +prior mappings instead of starting from scratch.
43 +
44 +## Consequences
45 +
46 +- Mappings are portable through a governed, auditable workbook.
47 +- Approval is impossible while controls fail; the audit chain records each pass.
48 +- Year continuity is supported without re-keying mappings.
49 +
50 +## Rejected alternatives
51 +
52 +- Auto-creating mappings for unmapped accounts: would invent financial mappings
53 + (forbidden by §19); the queue forces explicit human resolution.