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

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

Synced Dec 4, 10:30 UTC

arena/2d4eda07-aram
add-index-html-10623938925177053894 arena/094f314c-aram arena/2d4eda07-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 660 lines 23.2 KB
Raw
1 """HTTP API for the persistent, audited vertical slice (Phase 1, ADR-018).
2
3 Company/year setup -> source upload + year-filtered import -> notes + mappings ->
4 statement build -> drill-down to source file/sheet/row. All mutations are
5 year-isolated and subject to the D-07 immutability guards.
6 """
7
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
15
16 from aram_backend.auth import current_user, require_launch
17 from aram_backend.config import get_settings
18 from aram_backend.database import get_session
19 from aram_backend.domain.controls import BalanceRow, run_controls
20 from aram_backend.ingestion import SourceRegistrationError, register_source_document
21 from aram_backend.ledger_parser import LedgerParseError, SkippedRow, parse_ledger
22 from aram_backend.models import (
23 Company,
24 FinancialStatement,
25 FiscalYear,
26 LedgerBalance,
27 MappingRule,
28 NoteDefinition,
29 NoteRow,
30 StatementLine,
31 User,
32 UserRole,
33 )
34 from aram_backend.services.approval import ApprovalError, approve_year
35 from aram_backend.services.ledger_import import import_ledger_balances
36 from aram_backend.services.mapping_io import (
37 MappingImportError,
38 export_mappings_workbook,
39 import_mappings_workbook,
40 )
41 from aram_backend.services.mapping_workflow import (
42 CarryForwardError,
43 carry_forward_mappings,
44 unknown_accounts,
45 )
46 from aram_backend.services.note_engine import NoteEngineError, evaluate_note
47 from aram_backend.services.source_store import SourceStore, SourceStoreError
48 from aram_backend.services.statement_build import (
49 SECTION_LABELS_FA,
50 STATEMENT_LABELS_FA,
51 StatementBuildError,
52 build_statements,
53 drill_down,
54 )
55 from aram_backend.services.statement_export import (
56 StatementExportError,
57 export_statements_json_bytes,
58 export_statements_workbook,
59 )
60 from aram_backend.services.users import AuthorizationError, ensure_role
61
62 # R1 (booklet 2.1): every statement route requires a server-side session; reads
63 # included. The only unauthenticated routes in the app are /health, /auth/login,
64 # /auth/launch and the one-time first-admin bootstrap.
65 router = APIRouter(
66 prefix="/api/v1", tags=["statements"], dependencies=[Depends(require_launch), Depends(current_user)]
67 )
68
69
70 class CompanyIn(BaseModel):
71 code: str = Field(min_length=1, max_length=64)
72 name: str = Field(min_length=1, max_length=256)
73 year: int = Field(gt=0)
74
75
76 class NoteIn(BaseModel):
77 note_number: str = Field(min_length=1, max_length=32)
78 title: str = Field(min_length=1, max_length=512)
79 statement: str = Field(pattern="^(BS|IS|CF|EQ)$")
80 section: str = Field(min_length=1, max_length=64)
81
82
83 class MappingIn(BaseModel):
84 account_code: str = Field(min_length=1, max_length=64)
85 target_note_id: int
86 mapping_type: str = Field(default="closing", max_length=32)
87
88
89 def _year_or_404(session: Session, year_id: int) -> FiscalYear:
90 year = session.get(FiscalYear, year_id)
91 if year is None:
92 raise HTTPException(status_code=404, detail="fiscal year not found")
93 return year
94
95
96 @router.post("/companies")
97 def create_company(body: CompanyIn, session: Session = Depends(get_session)) -> dict:
98 company = Company(code=body.code, name=body.name)
99 session.add(company)
100 session.flush()
101 year = FiscalYear(company_id=company.id, year=body.year)
102 session.add(year)
103 session.commit()
104 return {
105 "company_id": company.id,
106 "year_id": year.id,
107 "year": year.year,
108 "status": year.status.value,
109 }
110
111
112 @router.post("/years/{year_id}/ledger")
113 def upload_ledger(
114 year_id: int,
115 file: UploadFile = File(...),
116 session: Session = Depends(get_session),
117 ) -> dict:
118 year = _year_or_404(session, year_id)
119 content = file.file.read()
120 store = SourceStore(get_settings().source_store_root)
121 try:
122 source = register_source_document(
123 session,
124 year_id=year_id,
125 filename=file.filename or "ledger.xlsx",
126 document_type="general_ledger",
127 content=content,
128 store=store,
129 )
130 except (SourceRegistrationError, SourceStoreError) as exc:
131 raise HTTPException(status_code=422, detail=str(exc)) from exc
132
133 skipped: list[SkippedRow] = []
134 try:
135 records = [
136 rec
137 for rec in parse_ledger(
138 content, file.filename or "ledger.xlsx", tolerant=True, skipped=skipped
139 )
140 if rec.source_year == year.year
141 ]
142 except LedgerParseError as exc:
143 raise HTTPException(status_code=422, detail=str(exc)) from exc
144
145 next_version = (
146 session.scalar(
147 select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
148 )
149 or 0
150 ) + 1
151 try:
152 count = import_ledger_balances(
153 session,
154 year_id=year_id,
155 source_document_id=source.id,
156 records=records,
157 import_version=next_version,
158 )
159 except ValueError as exc:
160 raise HTTPException(status_code=422, detail=str(exc)) from exc
161 session.commit()
162 return {
163 "source_document_id": source.id,
164 "file_hash": source.file_hash,
165 "import_version": next_version,
166 "accounts_imported": count,
167 "rows_for_year": len(records),
168 "skipped_rows": [{"row": s.row_number, "reason": s.reason} for s in skipped],
169 }
170
171
172 @router.post("/years/{year_id}/notes")
173 def create_note(year_id: int, body: NoteIn, session: Session = Depends(get_session)) -> dict:
174 _year_or_404(session, year_id)
175 note = NoteDefinition(
176 year_id=year_id,
177 note_number=body.note_number,
178 title=body.title,
179 configuration_json={"statement": body.statement, "section": body.section},
180 )
181 session.add(note)
182 session.commit()
183 return {"note_id": note.id, "note_number": note.note_number}
184
185
186 @router.get("/years/{year_id}/notes")
187 def list_notes(year_id: int, session: Session = Depends(get_session)) -> dict:
188 _year_or_404(session, year_id)
189 notes = session.scalars(
190 select(NoteDefinition)
191 .where(NoteDefinition.year_id == year_id)
192 .order_by(NoteDefinition.note_number)
193 ).all()
194 return {
195 "notes": [
196 {
197 "note_id": n.id,
198 "note_number": n.note_number,
199 "title": n.title,
200 "statement": (n.configuration_json or {}).get("statement", ""),
201 "section": (n.configuration_json or {}).get("section", ""),
202 }
203 for n in notes
204 ]
205 }
206
207
208 @router.get("/years/{year_id}/mappings")
209 def list_mappings(year_id: int, session: Session = Depends(get_session)) -> dict:
210 _year_or_404(session, year_id)
211 rules = session.scalars(
212 select(MappingRule).where(MappingRule.year_id == year_id).order_by(MappingRule.account_code)
213 ).all()
214 return {
215 "mappings": [
216 {
217 "mapping_id": r.id,
218 "account_code": r.account_code,
219 "target_note_id": r.target_note_id,
220 "mapping_type": r.mapping_type,
221 }
222 for r in rules
223 ]
224 }
225
226
227 @router.post("/years/{year_id}/mappings")
228 def create_mapping(year_id: int, body: MappingIn, session: Session = Depends(get_session)) -> dict:
229 _year_or_404(session, year_id)
230 note = session.get(NoteDefinition, body.target_note_id)
231 if note is None or note.year_id != year_id:
232 raise HTTPException(status_code=422, detail="target note not found in this year")
233 rule = MappingRule(
234 year_id=year_id,
235 rule_key=f"{body.account_code}->{body.target_note_id}",
236 account_code=body.account_code,
237 target_note_id=body.target_note_id,
238 mapping_type=body.mapping_type,
239 )
240 session.add(rule)
241 session.commit()
242 return {"mapping_id": rule.id, "account_code": rule.account_code}
243
244
245 @router.post("/years/{year_id}/statements/build")
246 def build(year_id: int, session: Session = Depends(get_session)) -> dict:
247 _year_or_404(session, year_id)
248 try:
249 result = build_statements(session, year_id)
250 except StatementBuildError as exc:
251 raise HTTPException(status_code=422, detail=str(exc)) from exc
252 session.commit()
253 return {
254 "statements": [
255 {"id": s.id, "type": s.statement_type.value, "version": s.version}
256 for s in result.statements
257 ],
258 "unmapped_accounts": list(result.unmapped_accounts),
259 }
260
261
262 @router.get("/years/{year_id}/statements")
263 def list_statements(year_id: int, session: Session = Depends(get_session)) -> dict:
264 _year_or_404(session, year_id)
265 statements = session.scalars(
266 select(FinancialStatement)
267 .where(FinancialStatement.year_id == year_id)
268 .order_by(FinancialStatement.statement_type, FinancialStatement.version)
269 ).all()
270 payload = []
271 for statement in statements:
272 lines = session.scalars(
273 select(StatementLine)
274 .where(StatementLine.statement_id == statement.id)
275 .order_by(StatementLine.line_order)
276 ).all()
277 payload.append(
278 {
279 "id": statement.id,
280 "type": statement.statement_type.value,
281 "label_fa": STATEMENT_LABELS_FA.get(statement.statement_type.value, ""),
282 "version": statement.version,
283 "lines": [
284 {
285 "id": ln.id,
286 "line_order": ln.line_order,
287 "label": ln.line_label,
288 "mapped_total": str(ln.mapped_total)
289 if ln.mapped_total is not None
290 else None,
291 "target_note_id": ln.target_note_id,
292 }
293 for ln in lines
294 ],
295 }
296 )
297 return {"statements": payload, "section_labels_fa": SECTION_LABELS_FA}
298
299
300 @router.get("/years/{year_id}/statements/export")
301 def export_statements(
302 year_id: int, format: str = "xlsx", session: Session = Depends(get_session)
303 ) -> StreamingResponse:
304 _year_or_404(session, year_id)
305 try:
306 if format == "json":
307 data = export_statements_json_bytes(session, year_id)
308 media = "application/json"
309 ext = "json"
310 elif format == "xlsx":
311 data = export_statements_workbook(session, year_id)
312 media = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
313 ext = "xlsx"
314 else:
315 raise HTTPException(status_code=422, detail="format must be 'xlsx' or 'json'")
316 except StatementExportError as exc:
317 raise HTTPException(status_code=422, detail=str(exc)) from exc
318 return StreamingResponse(
319 iter([data]),
320 media_type=media,
321 headers={"Content-Disposition": f'attachment; filename="aram-statements-{year_id}.{ext}"'},
322 )
323
324
325 @router.get("/statement-lines/{line_id}/drilldown")
326 def line_drilldown(line_id: int, session: Session = Depends(get_session)) -> dict:
327 try:
328 return drill_down(session, line_id)
329 except StatementBuildError as exc:
330 raise HTTPException(status_code=404, detail=str(exc)) from exc
331
332
333 @router.get("/years/{year_id}/preflight")
334 def preflight(year_id: int, session: Session = Depends(get_session)) -> dict:
335 year = _year_or_404(session, year_id)
336 version = session.scalar(
337 select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
338 )
339 balances = (
340 session.scalars(
341 select(LedgerBalance).where(
342 LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
343 )
344 ).all()
345 if version is not None
346 else []
347 )
348 rows = [
349 BalanceRow(
350 row_number=b.source_row,
351 account_code=b.account_full_code,
352 opening=b.opening,
353 debit=b.debit,
354 credit=b.credit,
355 closing=b.closing,
356 )
357 for b in balances
358 ]
359 rules = session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all()
360 from aram_backend.domain.controls import MappingTarget
361
362 mappings: dict[str, list[MappingTarget]] = {}
363 for rule in rules:
364 mappings.setdefault(rule.account_code, []).append(
365 MappingTarget(target=str(rule.target_note_id))
366 )
367 results = run_controls(rows, mappings)
368 return {
369 "year": year.year,
370 "can_approve": all(r.passed for r in results if r.severity == "ERROR"),
371 "controls": [
372 {"code": r.code, "severity": r.severity, "passed": r.passed, "message_fa": r.message_fa}
373 for r in results
374 ],
375 }
376
377
378 # ----------------------------------------------------------- Phase 2: mapping I/O
379 @router.get("/years/{year_id}/mappings/export")
380 def export_mappings(year_id: int, session: Session = Depends(get_session)) -> StreamingResponse:
381 _year_or_404(session, year_id)
382 data = export_mappings_workbook(session, year_id)
383 return StreamingResponse(
384 iter([data]),
385 media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
386 headers={"Content-Disposition": f'attachment; filename="aram-mappings-{year_id}.xlsx"'},
387 )
388
389
390 @router.post("/years/{year_id}/mappings/import")
391 def import_mappings(
392 year_id: int,
393 file: UploadFile = File(...),
394 session: Session = Depends(get_session),
395 ) -> dict:
396 _year_or_404(session, year_id)
397 content = file.file.read()
398 try:
399 result = import_mappings_workbook(session, year_id, content)
400 except MappingImportError as exc:
401 raise HTTPException(status_code=422, detail=str(exc)) from exc
402 session.commit()
403 return {
404 "created": result.created,
405 "notes_created": result.notes_created,
406 "errors": result.errors,
407 }
408
409
410 @router.get("/years/{year_id}/unknown-accounts")
411 def unknown_queue(year_id: int, session: Session = Depends(get_session)) -> dict:
412 _year_or_404(session, year_id)
413 queue = unknown_accounts(session, year_id)
414 return {"count": len(queue), "accounts": queue}
415
416
417 class CarryForwardIn(BaseModel):
418 from_year_id: int
419
420
421 @router.post("/years/{year_id}/mappings/carry-forward")
422 def carry_forward(
423 year_id: int, body: CarryForwardIn, session: Session = Depends(get_session)
424 ) -> dict:
425 _year_or_404(session, year_id)
426 try:
427 result = carry_forward_mappings(session, body.from_year_id, year_id)
428 except CarryForwardError as exc:
429 raise HTTPException(status_code=422, detail=str(exc)) from exc
430 session.commit()
431 return {"notes_created": result.notes_created, "mappings_created": result.mappings_created}
432
433
434 @router.post("/years/{year_id}/approve")
435 def approve(
436 year_id: int, session: Session = Depends(get_session), user: User = Depends(current_user)
437 ) -> dict:
438 # R1 (booklet 2.1): approval always requires an authenticated reviewer/admin.
439 # The former "no users yet -> allowed" shortcut is removed: with zero users
440 # there is no identity, so approval is impossible (401 from current_user).
441 # The role gate runs before the existence check so it can never be skipped.
442 try:
443 ensure_role(user, {UserRole.ADMIN, UserRole.REVIEWER})
444 except AuthorizationError as exc:
445 raise HTTPException(status_code=403, detail=str(exc)) from exc
446 _year_or_404(session, year_id)
447 try:
448 result = approve_year(session, year_id, actor=user.username)
449 except ApprovalError as exc:
450 raise HTTPException(status_code=422, detail=str(exc)) from exc
451 if not result.approved:
452 return {
453 "approved": False,
454 "blocking": [{"code": r.code, "message_fa": r.message_fa} for r in result.blocking],
455 }
456 session.commit()
457 return {"approved": True, "status": "Approved"}
458
459
460 # ----------------------------------------------------------- Phase 3: note engine
461 class NoteRowIn(BaseModel):
462 row_order: int = Field(ge=0)
463 label: str = Field(min_length=1, max_length=512)
464 formula_logic: str | None = Field(default=None, max_length=2000)
465
466
467 @router.post("/years/{year_id}/notes/{note_id}/rows")
468 def create_note_row(
469 year_id: int, note_id: int, body: NoteRowIn, session: Session = Depends(get_session)
470 ) -> dict:
471 _year_or_404(session, year_id)
472 note = session.get(NoteDefinition, note_id)
473 if note is None or note.year_id != year_id:
474 raise HTTPException(status_code=404, detail="note not found in this year")
475 if body.formula_logic:
476 from aram_backend.domain.formula import FormulaError, parse_formula
477
478 try:
479 parse_formula(body.formula_logic)
480 except FormulaError as exc:
481 raise HTTPException(status_code=422, detail=f"invalid formula: {exc}") from exc
482 row = NoteRow(
483 note_id=note_id,
484 row_order=body.row_order,
485 label=body.label,
486 formula_logic=body.formula_logic,
487 )
488 session.add(row)
489 session.commit()
490 return {"row_id": row.id, "row_order": row.row_order}
491
492
493 @router.get("/notes/{note_id}/rows")
494 def list_note_rows(note_id: int, session: Session = Depends(get_session)) -> dict:
495 note = session.get(NoteDefinition, note_id)
496 if note is None:
497 raise HTTPException(status_code=404, detail="note not found")
498 rows = sorted(note.rows, key=lambda r: r.row_order)
499 return {
500 "note_id": note.id,
501 "rows": [
502 {"row_order": r.row_order, "label": r.label, "formula_logic": r.formula_logic}
503 for r in rows
504 ],
505 }
506
507
508 @router.get("/notes/{note_id}/evaluate")
509 def evaluate_note_endpoint(note_id: int, session: Session = Depends(get_session)) -> dict:
510 try:
511 return evaluate_note(session, note_id)
512 except NoteEngineError as exc:
513 raise HTTPException(status_code=422, detail=str(exc)) from exc
514
515
516 # ------------------------------------------------- Phase 5: editable notes/mappings
517 def _commit_guarded(session: Session) -> None:
518 """Commit, translating the D-07 immutability guard into HTTP 409."""
519 try:
520 session.commit()
521 except ValueError as exc:
522 session.rollback()
523 raise HTTPException(status_code=409, detail=str(exc)) from exc
524
525
526 def _note_in_year(session: Session, year_id: int, note_id: int) -> NoteDefinition:
527 note = session.get(NoteDefinition, note_id)
528 if note is None or note.year_id != year_id:
529 raise HTTPException(status_code=404, detail="note not found in this year")
530 return note
531
532
533 class NoteUpdate(BaseModel):
534 note_number: str | None = Field(default=None, min_length=1, max_length=32)
535 title: str | None = Field(default=None, min_length=1, max_length=512)
536 statement: str | None = Field(default=None, pattern="^(BS|IS|CF|EQ)$")
537 section: str | None = Field(default=None, min_length=1, max_length=64)
538
539
540 @router.put("/years/{year_id}/notes/{note_id}")
541 def update_note(
542 year_id: int, note_id: int, body: NoteUpdate, session: Session = Depends(get_session)
543 ) -> dict:
544 _year_or_404(session, year_id)
545 note = _note_in_year(session, year_id, note_id)
546 if body.note_number is not None:
547 note.note_number = body.note_number
548 if body.title is not None:
549 note.title = body.title
550 config = dict(note.configuration_json or {})
551 if body.statement is not None:
552 config["statement"] = body.statement
553 if body.section is not None:
554 config["section"] = body.section
555 note.configuration_json = config
556 _commit_guarded(session)
557 return {"note_id": note.id, "note_number": note.note_number, "title": note.title}
558
559
560 @router.delete("/years/{year_id}/notes/{note_id}")
561 def delete_note(year_id: int, note_id: int, session: Session = Depends(get_session)) -> dict:
562 _year_or_404(session, year_id)
563 note = _note_in_year(session, year_id, note_id)
564 referencing_mappings = session.scalar(
565 select(func.count(MappingRule.id)).where(MappingRule.target_note_id == note_id)
566 )
567 referencing_lines = session.scalar(
568 select(func.count(StatementLine.id)).where(StatementLine.target_note_id == note_id)
569 )
570 if referencing_mappings or referencing_lines:
571 raise HTTPException(
572 status_code=409,
573 detail="note is referenced by mappings or statement lines; remove those first",
574 )
575 session.delete(note) # NoteRow rows cascade
576 _commit_guarded(session)
577 return {"deleted": note_id}
578
579
580 class MappingUpdate(BaseModel):
581 target_note_id: int | None = None
582 mapping_type: str | None = Field(default=None, max_length=32)
583
584
585 @router.put("/years/{year_id}/mappings/{mapping_id}")
586 def update_mapping(
587 year_id: int, mapping_id: int, body: MappingUpdate, session: Session = Depends(get_session)
588 ) -> dict:
589 _year_or_404(session, year_id)
590 rule = session.get(MappingRule, mapping_id)
591 if rule is None or rule.year_id != year_id:
592 raise HTTPException(status_code=404, detail="mapping not found in this year")
593 if body.target_note_id is not None:
594 _note_in_year(session, year_id, body.target_note_id)
595 rule.target_note_id = body.target_note_id
596 if body.mapping_type is not None:
597 rule.mapping_type = body.mapping_type
598 _commit_guarded(session)
599 return {"mapping_id": rule.id, "account_code": rule.account_code}
600
601
602 @router.delete("/years/{year_id}/mappings/{mapping_id}")
603 def delete_mapping(year_id: int, mapping_id: int, session: Session = Depends(get_session)) -> dict:
604 _year_or_404(session, year_id)
605 rule = session.get(MappingRule, mapping_id)
606 if rule is None or rule.year_id != year_id:
607 raise HTTPException(status_code=404, detail="mapping not found in this year")
608 session.delete(rule)
609 _commit_guarded(session)
610 return {"deleted": mapping_id}
611
612
613 class NoteRowUpdate(BaseModel):
614 row_order: int | None = Field(default=None, ge=0)
615 label: str | None = Field(default=None, min_length=1, max_length=512)
616 formula_logic: str | None = Field(default=None, max_length=2000)
617
618
619 @router.put("/years/{year_id}/notes/{note_id}/rows/{row_id}")
620 def update_note_row(
621 year_id: int,
622 note_id: int,
623 row_id: int,
624 body: NoteRowUpdate,
625 session: Session = Depends(get_session),
626 ) -> dict:
627 _year_or_404(session, year_id)
628 _note_in_year(session, year_id, note_id)
629 row = session.get(NoteRow, row_id)
630 if row is None or row.note_id != note_id:
631 raise HTTPException(status_code=404, detail="note row not found")
632 if body.formula_logic:
633 from aram_backend.domain.formula import FormulaError, parse_formula
634
635 try:
636 parse_formula(body.formula_logic)
637 except FormulaError as exc:
638 raise HTTPException(status_code=422, detail=f"invalid formula: {exc}") from exc
639 if body.row_order is not None:
640 row.row_order = body.row_order
641 if body.label is not None:
642 row.label = body.label
643 if body.formula_logic is not None:
644 row.formula_logic = body.formula_logic
645 _commit_guarded(session)
646 return {"row_id": row.id, "row_order": row.row_order}
647
648
649 @router.delete("/years/{year_id}/notes/{note_id}/rows/{row_id}")
650 def delete_note_row(
651 year_id: int, note_id: int, row_id: int, session: Session = Depends(get_session)
652 ) -> dict:
653 _year_or_404(session, year_id)
654 _note_in_year(session, year_id, note_id)
655 row = session.get(NoteRow, row_id)
656 if row is None or row.note_id != note_id:
657 raise HTTPException(status_code=404, detail="note row not found")
658 session.delete(row)
659 _commit_guarded(session)
660 return {"deleted": row_id}