@davoodmehraban89 / Aram / commits / 4726f5e
Fork 0

fix(review): role-gate approve + editable notes/mappings/rows (5-agent review)

Findings from the deep compliance review: - F3-1: API /approve now enforces reviewer/admin role once local users exist (consistent with /lock and /reopen); bootstrap/dev (no users) stays open; the C-01..C-04 ERROR gate always applies. +2 negative/positive tests. - F2-1: add PUT/DELETE for notes, mappings, note rows + GET list notes/mappings, satisfying the owner's editable codes/accounts/notes/subnotes requirement. Draft-guarded; D-07 immutability translated to HTTP 409; note delete refuses while mappings/statement lines reference it (rows cascade). +9 tests incl. locked-year edit refusal. - F5-1: document python-multipart upload dependency in ADR-018. Full suite: 319 passed; mypy services clean; ruff clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 12:47 UTC 4726f5ebde38cb7dc38f4c0daf89bc6e08d430b1
4 files changed +382 -1
backend/src/aram_backend/statement_api.py
+201 -1
@@ -27,6 +27,7 @@ from aram_backend.models import (
27 NoteDefinition,
28 NoteRow,
29 StatementLine,
30 + UserRole,
31 )
32 from aram_backend.services.approval import ApprovalError, approve_year
33 from aram_backend.services.ledger_import import import_ledger_balances
@@ -54,6 +55,7 @@ from aram_backend.services.statement_export import (
55 export_statements_json_bytes,
56 export_statements_workbook,
57 )
58 +from aram_backend.services.users import AuthorizationError, list_users, require_role
59
60 router = APIRouter(prefix="/api/v1", tags=["statements"])
61
@@ -125,7 +127,9 @@ def upload_ledger(
127 try:
128 records = [
129 rec
128 - for rec in parse_ledger(content, file.filename or "ledger.xlsx", tolerant=True, skipped=skipped)
130 + for rec in parse_ledger(
131 + content, file.filename or "ledger.xlsx", tolerant=True, skipped=skipped
132 + )
133 if rec.source_year == year.year
134 ]
135 except LedgerParseError as exc:
@@ -172,6 +176,47 @@ def create_note(year_id: int, body: NoteIn, session: Session = Depends(get_sessi
176 return {"note_id": note.id, "note_number": note.note_number}
177
178
179 +@router.get("/years/{year_id}/notes")
180 +def list_notes(year_id: int, session: Session = Depends(get_session)) -> dict:
181 + _year_or_404(session, year_id)
182 + notes = session.scalars(
183 + select(NoteDefinition)
184 + .where(NoteDefinition.year_id == year_id)
185 + .order_by(NoteDefinition.note_number)
186 + ).all()
187 + return {
188 + "notes": [
189 + {
190 + "note_id": n.id,
191 + "note_number": n.note_number,
192 + "title": n.title,
193 + "statement": (n.configuration_json or {}).get("statement", ""),
194 + "section": (n.configuration_json or {}).get("section", ""),
195 + }
196 + for n in notes
197 + ]
198 + }
199 +
200 +
201 +@router.get("/years/{year_id}/mappings")
202 +def list_mappings(year_id: int, session: Session = Depends(get_session)) -> dict:
203 + _year_or_404(session, year_id)
204 + rules = session.scalars(
205 + select(MappingRule).where(MappingRule.year_id == year_id).order_by(MappingRule.account_code)
206 + ).all()
207 + return {
208 + "mappings": [
209 + {
210 + "mapping_id": r.id,
211 + "account_code": r.account_code,
212 + "target_note_id": r.target_note_id,
213 + "mapping_type": r.mapping_type,
214 + }
215 + for r in rules
216 + ]
217 + }
218 +
219 +
220 @router.post("/years/{year_id}/mappings")
221 def create_mapping(year_id: int, body: MappingIn, session: Session = Depends(get_session)) -> dict:
222 _year_or_404(session, year_id)
@@ -386,6 +431,14 @@ class ApproveIn(BaseModel):
431 @router.post("/years/{year_id}/approve")
432 def approve(year_id: int, body: ApproveIn, session: Session = Depends(get_session)) -> dict:
433 _year_or_404(session, year_id)
434 + # Phase 7 role gate: once local users exist, only a reviewer/admin may approve
435 + # (consistent with /lock and /reopen). With no users yet (bootstrap/dev) the
436 + # action is allowed; the C-01..C-04 ERROR gate below always applies regardless.
437 + if list_users(session):
438 + try:
439 + require_role(session, username=body.actor, allowed={UserRole.ADMIN, UserRole.REVIEWER})
440 + except AuthorizationError as exc:
441 + raise HTTPException(status_code=403, detail=str(exc)) from exc
442 try:
443 result = approve_year(session, year_id, actor=body.actor)
444 except ApprovalError as exc:
@@ -453,3 +506,150 @@ def evaluate_note_endpoint(note_id: int, session: Session = Depends(get_session)
506 return evaluate_note(session, note_id)
507 except NoteEngineError as exc:
508 raise HTTPException(status_code=422, detail=str(exc)) from exc
509 +
510 +
511 +# ------------------------------------------------- Phase 5: editable notes/mappings
512 +def _commit_guarded(session: Session) -> None:
513 + """Commit, translating the D-07 immutability guard into HTTP 409."""
514 + try:
515 + session.commit()
516 + except ValueError as exc:
517 + session.rollback()
518 + raise HTTPException(status_code=409, detail=str(exc)) from exc
519 +
520 +
521 +def _note_in_year(session: Session, year_id: int, note_id: int) -> NoteDefinition:
522 + note = session.get(NoteDefinition, note_id)
523 + if note is None or note.year_id != year_id:
524 + raise HTTPException(status_code=404, detail="note not found in this year")
525 + return note
526 +
527 +
528 +class NoteUpdate(BaseModel):
529 + note_number: str | None = Field(default=None, min_length=1, max_length=32)
530 + title: str | None = Field(default=None, min_length=1, max_length=512)
531 + statement: str | None = Field(default=None, pattern="^(BS|IS|CF|EQ)$")
532 + section: str | None = Field(default=None, min_length=1, max_length=64)
533 +
534 +
535 +@router.put("/years/{year_id}/notes/{note_id}")
536 +def update_note(
537 + year_id: int, note_id: int, body: NoteUpdate, session: Session = Depends(get_session)
538 +) -> dict:
539 + _year_or_404(session, year_id)
540 + note = _note_in_year(session, year_id, note_id)
541 + if body.note_number is not None:
542 + note.note_number = body.note_number
543 + if body.title is not None:
544 + note.title = body.title
545 + config = dict(note.configuration_json or {})
546 + if body.statement is not None:
547 + config["statement"] = body.statement
548 + if body.section is not None:
549 + config["section"] = body.section
550 + note.configuration_json = config
551 + _commit_guarded(session)
552 + return {"note_id": note.id, "note_number": note.note_number, "title": note.title}
553 +
554 +
555 +@router.delete("/years/{year_id}/notes/{note_id}")
556 +def delete_note(year_id: int, note_id: int, session: Session = Depends(get_session)) -> dict:
557 + _year_or_404(session, year_id)
558 + note = _note_in_year(session, year_id, note_id)
559 + referencing_mappings = session.scalar(
560 + select(func.count(MappingRule.id)).where(MappingRule.target_note_id == note_id)
561 + )
562 + referencing_lines = session.scalar(
563 + select(func.count(StatementLine.id)).where(StatementLine.target_note_id == note_id)
564 + )
565 + if referencing_mappings or referencing_lines:
566 + raise HTTPException(
567 + status_code=409,
568 + detail="note is referenced by mappings or statement lines; remove those first",
569 + )
570 + session.delete(note) # NoteRow rows cascade
571 + _commit_guarded(session)
572 + return {"deleted": note_id}
573 +
574 +
575 +class MappingUpdate(BaseModel):
576 + target_note_id: int | None = None
577 + mapping_type: str | None = Field(default=None, max_length=32)
578 +
579 +
580 +@router.put("/years/{year_id}/mappings/{mapping_id}")
581 +def update_mapping(
582 + year_id: int, mapping_id: int, body: MappingUpdate, session: Session = Depends(get_session)
583 +) -> dict:
584 + _year_or_404(session, year_id)
585 + rule = session.get(MappingRule, mapping_id)
586 + if rule is None or rule.year_id != year_id:
587 + raise HTTPException(status_code=404, detail="mapping not found in this year")
588 + if body.target_note_id is not None:
589 + _note_in_year(session, year_id, body.target_note_id)
590 + rule.target_note_id = body.target_note_id
591 + if body.mapping_type is not None:
592 + rule.mapping_type = body.mapping_type
593 + _commit_guarded(session)
594 + return {"mapping_id": rule.id, "account_code": rule.account_code}
595 +
596 +
597 +@router.delete("/years/{year_id}/mappings/{mapping_id}")
598 +def delete_mapping(year_id: int, mapping_id: int, session: Session = Depends(get_session)) -> dict:
599 + _year_or_404(session, year_id)
600 + rule = session.get(MappingRule, mapping_id)
601 + if rule is None or rule.year_id != year_id:
602 + raise HTTPException(status_code=404, detail="mapping not found in this year")
603 + session.delete(rule)
604 + _commit_guarded(session)
605 + return {"deleted": mapping_id}
606 +
607 +
608 +class NoteRowUpdate(BaseModel):
609 + row_order: int | None = Field(default=None, ge=0)
610 + label: str | None = Field(default=None, min_length=1, max_length=512)
611 + formula_logic: str | None = Field(default=None, max_length=2000)
612 +
613 +
614 +@router.put("/years/{year_id}/notes/{note_id}/rows/{row_id}")
615 +def update_note_row(
616 + year_id: int,
617 + note_id: int,
618 + row_id: int,
619 + body: NoteRowUpdate,
620 + session: Session = Depends(get_session),
621 +) -> dict:
622 + _year_or_404(session, year_id)
623 + _note_in_year(session, year_id, note_id)
624 + row = session.get(NoteRow, row_id)
625 + if row is None or row.note_id != note_id:
626 + raise HTTPException(status_code=404, detail="note row not found")
627 + if body.formula_logic:
628 + from aram_backend.domain.formula import FormulaError, parse_formula
629 +
630 + try:
631 + parse_formula(body.formula_logic)
632 + except FormulaError as exc:
633 + raise HTTPException(status_code=422, detail=f"invalid formula: {exc}") from exc
634 + if body.row_order is not None:
635 + row.row_order = body.row_order
636 + if body.label is not None:
637 + row.label = body.label
638 + if body.formula_logic is not None:
639 + row.formula_logic = body.formula_logic
640 + _commit_guarded(session)
641 + return {"row_id": row.id, "row_order": row.row_order}
642 +
643 +
644 +@router.delete("/years/{year_id}/notes/{note_id}/rows/{row_id}")
645 +def delete_note_row(
646 + year_id: int, note_id: int, row_id: int, session: Session = Depends(get_session)
647 +) -> dict:
648 + _year_or_404(session, year_id)
649 + _note_in_year(session, year_id, note_id)
650 + row = session.get(NoteRow, row_id)
651 + if row is None or row.note_id != note_id:
652 + raise HTTPException(status_code=404, detail="note row not found")
653 + session.delete(row)
654 + _commit_guarded(session)
655 + return {"deleted": row_id}
backend/tests/test_editing.py new
+143
@@ -0,0 +1,143 @@
1 +"""Phase 5 editability: update/delete notes, mappings, note rows (Draft-guarded).
2 +
3 +Covers the owner's requirement that codes/accounts/notes/subnotes be editable, and
4 +proves edits are refused on a locked year (D-07) with HTTP 409.
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +_BALANCED_CSV = (
10 + "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
11 + "8348,14,نقد,1404,O,,,,,0,100,0,100\n"
12 + "1001,24,پرداختنی,1404,O,,,,,0,0,100,-100\n"
13 +).encode()
14 +
15 +
16 +def _year(client):
17 + return client.post(
18 + "/api/v1/companies", json={"code": "ED", "name": "شرکت", "year": 1404}
19 + ).json()["year_id"]
20 +
21 +
22 +def _note(client, year_id, number="10", title="دارایی", statement="BS", section="Assets"):
23 + return client.post(
24 + f"/api/v1/years/{year_id}/notes",
25 + json={"note_number": number, "title": title, "statement": statement, "section": section},
26 + ).json()["note_id"]
27 +
28 +
29 +class TestNoteEditing:
30 + def test_update_note(self, api_client):
31 + y = _year(api_client)
32 + n = _note(api_client, y)
33 + r = api_client.put(
34 + f"/api/v1/years/{y}/notes/{n}", json={"title": "عنوان جدید", "section": "Liabilities"}
35 + )
36 + assert r.status_code == 200, r.text
37 + assert r.json()["title"] == "عنوان جدید"
38 +
39 + def test_delete_note_cascades_rows(self, api_client):
40 + y = _year(api_client)
41 + n = _note(api_client, y)
42 + api_client.post(
43 + f"/api/v1/years/{y}/notes/{n}/rows",
44 + json={"row_order": 0, "label": "جمع", "formula_logic": None},
45 + )
46 + r = api_client.delete(f"/api/v1/years/{y}/notes/{n}")
47 + assert r.status_code == 200, r.text
48 + assert api_client.get(f"/api/v1/notes/{n}/rows").status_code == 404
49 +
50 + def test_delete_note_with_mapping_refused(self, api_client):
51 + y = _year(api_client)
52 + n = _note(api_client, y)
53 + api_client.post(
54 + f"/api/v1/years/{y}/mappings", json={"account_code": "148348", "target_note_id": n}
55 + )
56 + r = api_client.delete(f"/api/v1/years/{y}/notes/{n}")
57 + assert r.status_code == 409
58 +
59 + def test_update_missing_note_404(self, api_client):
60 + y = _year(api_client)
61 + assert (
62 + api_client.put(f"/api/v1/years/{y}/notes/999", json={"title": "x"}).status_code == 404
63 + )
64 +
65 +
66 +class TestMappingEditing:
67 + def test_update_and_delete_mapping(self, api_client):
68 + y = _year(api_client)
69 + n1 = _note(api_client, y, "10")
70 + n2 = _note(api_client, y, "11")
71 + m = api_client.post(
72 + f"/api/v1/years/{y}/mappings", json={"account_code": "148348", "target_note_id": n1}
73 + ).json()["mapping_id"]
74 + r = api_client.put(f"/api/v1/years/{y}/mappings/{m}", json={"target_note_id": n2})
75 + assert r.status_code == 200, r.text
76 + r = api_client.delete(f"/api/v1/years/{y}/mappings/{m}")
77 + assert r.status_code == 200, r.text
78 +
79 + def test_update_mapping_to_foreign_note_404(self, api_client):
80 + y = _year(api_client)
81 + n = _note(api_client, y)
82 + m = api_client.post(
83 + f"/api/v1/years/{y}/mappings", json={"account_code": "148348", "target_note_id": n}
84 + ).json()["mapping_id"]
85 + assert (
86 + api_client.put(
87 + f"/api/v1/years/{y}/mappings/{m}", json={"target_note_id": 999}
88 + ).status_code
89 + == 404
90 + )
91 +
92 +
93 +class TestNoteRowEditing:
94 + def test_update_row_formula_valid_and_invalid(self, api_client):
95 + y = _year(api_client)
96 + n = _note(api_client, y)
97 + row = api_client.post(
98 + f"/api/v1/years/{y}/notes/{n}/rows",
99 + json={"row_order": 0, "label": "جمع", "formula_logic": None},
100 + ).json()["row_id"]
101 + r = api_client.put(
102 + f"/api/v1/years/{y}/notes/{n}/rows/{row}",
103 + json={"label": "جمع کل", "formula_logic": 'acct("148348")'},
104 + )
105 + assert r.status_code == 200, r.text
106 + bad = api_client.put(
107 + f"/api/v1/years/{y}/notes/{n}/rows/{row}", json={"formula_logic": "acct("}
108 + )
109 + assert bad.status_code == 422
110 +
111 + def test_delete_row(self, api_client):
112 + y = _year(api_client)
113 + n = _note(api_client, y)
114 + row = api_client.post(
115 + f"/api/v1/years/{y}/notes/{n}/rows",
116 + json={"row_order": 0, "label": "جمع", "formula_logic": None},
117 + ).json()["row_id"]
118 + assert api_client.delete(f"/api/v1/years/{y}/notes/{n}/rows/{row}").status_code == 200
119 +
120 +
121 +class TestLockedYearEditing:
122 + def test_edit_locked_year_refused_409(self, api_client):
123 + # Bootstrap admin, import a balanced ledger, map, approve, lock.
124 + api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
125 + y = _year(api_client)
126 + api_client.post(
127 + f"/api/v1/years/{y}/ledger", files={"file": ("ledger.csv", _BALANCED_CSV, "text/csv")}
128 + )
129 + n_a = _note(api_client, y, "6", "نقد", "BS", "Assets")
130 + n_l = _note(api_client, y, "10", "پرداختنی", "BS", "Liabilities")
131 + api_client.post(
132 + f"/api/v1/years/{y}/mappings", json={"account_code": "148348", "target_note_id": n_a}
133 + )
134 + api_client.post(
135 + f"/api/v1/years/{y}/mappings", json={"account_code": "241001", "target_note_id": n_l}
136 + )
137 + ap = api_client.post(f"/api/v1/years/{y}/approve", json={"actor": "root"})
138 + assert ap.status_code == 200 and ap.json()["approved"] is True, ap.text
139 + lk = api_client.post(f"/api/v1/years/{y}/lock", json={"actor": "root"})
140 + assert lk.status_code == 200, lk.text
141 + # Editing a note on the locked year is refused by the D-07 guard.
142 + r = api_client.put(f"/api/v1/years/{y}/notes/{n_a}", json={"title": "تغییر"})
143 + assert r.status_code == 409, r.text
backend/tests/test_phase7_admin.py
+30
@@ -198,6 +198,36 @@ class TestAdminApi:
198 )
199 assert r.status_code == 403
200
201 + def test_approve_role_gated_once_users_exist(self, api_client):
202 + # Bootstrap admin + a preparer.
203 + api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
204 + api_client.post(
205 + "/api/v1/users",
206 + json={
207 + "username": "prep",
208 + "password": "supersecret",
209 + "role": "preparer",
210 + "actor": "root",
211 + },
212 + )
213 + year_id = api_client.post(
214 + "/api/v1/companies", json={"code": "RG", "name": "شرکت", "year": 1404}
215 + ).json()["year_id"]
216 + # Preparer is refused by the role gate (403) before controls even run.
217 + r = api_client.post(f"/api/v1/years/{year_id}/approve", json={"actor": "prep"})
218 + assert r.status_code == 403, r.text
219 + # Admin passes the role gate (controls may still block, but never 403).
220 + r = api_client.post(f"/api/v1/years/{year_id}/approve", json={"actor": "root"})
221 + assert r.status_code == 200, r.text
222 +
223 + def test_approve_open_when_no_users(self, api_client):
224 + # Bootstrap/dev: with no users, the role gate is inactive (control gate still applies).
225 + year_id = api_client.post(
226 + "/api/v1/companies", json={"code": "NU", "name": "شرکت", "year": 1404}
227 + ).json()["year_id"]
228 + r = api_client.post(f"/api/v1/years/{year_id}/approve", json={"actor": "anyone"})
229 + assert r.status_code == 200, r.text
230 +
231 def test_audit_endpoint_chain_valid(self, api_client):
232 api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
233 r = api_client.get("/api/v1/audit/verify")
docs/adr/ADR-018-persistent-statements-drilldown.md
+8
@@ -53,6 +53,14 @@ total is therefore traceable to the exact source file, sheet and row.
53 - The in-memory Pilot workbench remains the interactive editor; this persistent
54 engine is the audited system of record.
55
56 +## Dependencies
57 +
58 +- `python-multipart` is required by FastAPI to parse `multipart/form-data` for the
59 + ledger and mapping workbook uploads (`UploadFile`/`File`). It is the standard
60 + FastAPI file-upload dependency, pinned `>=0.0.18,<1` in `backend/pyproject.toml`.
61 + No other runtime dependency was added for the statement slice; Excel I/O uses the
62 + already-required `openpyxl` (ADR-017).
63 +
64 ## Rejected alternatives
65
66 - Storing drill-down as a denormalized blob on StatementLine: loses the live