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
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
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:
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)
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:
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}