Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 03:00 UTC
arena/094f314c-aram
add-index-html-10623938925177053894
arena/094f314c-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
| 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.config import get_settings |
| 17 | from aram_backend.database import get_session |
| 18 | from aram_backend.domain.controls import BalanceRow, run_controls |
| 19 | from aram_backend.ingestion import SourceRegistrationError, register_source_document |
| 20 | from aram_backend.ledger_parser import LedgerParseError, SkippedRow, parse_ledger |
| 21 | from aram_backend.models import ( |
| 22 | Company, |
| 23 | FinancialStatement, |
| 24 | FiscalYear, |
| 25 | LedgerBalance, |
| 26 | MappingRule, |
| 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 |
| 34 | from aram_backend.services.mapping_io import ( |
| 35 | MappingImportError, |
| 36 | export_mappings_workbook, |
| 37 | import_mappings_workbook, |
| 38 | ) |
| 39 | from aram_backend.services.mapping_workflow import ( |
| 40 | CarryForwardError, |
| 41 | carry_forward_mappings, |
| 42 | unknown_accounts, |
| 43 | ) |
| 44 | from aram_backend.services.note_engine import NoteEngineError, evaluate_note |
| 45 | from aram_backend.services.source_store import SourceStore, SourceStoreError |
| 46 | from aram_backend.services.statement_build import ( |
| 47 | SECTION_LABELS_FA, |
| 48 | STATEMENT_LABELS_FA, |
| 49 | StatementBuildError, |
| 50 | build_statements, |
| 51 | drill_down, |
| 52 | ) |
| 53 | from aram_backend.services.statement_export import ( |
| 54 | StatementExportError, |
| 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 | |
| 62 | |
| 63 | class CompanyIn(BaseModel): |
| 64 | code: str = Field(min_length=1, max_length=64) |
| 65 | name: str = Field(min_length=1, max_length=256) |
| 66 | year: int = Field(gt=0) |
| 67 | |
| 68 | |
| 69 | class NoteIn(BaseModel): |
| 70 | note_number: str = Field(min_length=1, max_length=32) |
| 71 | title: str = Field(min_length=1, max_length=512) |
| 72 | statement: str = Field(pattern="^(BS|IS|CF|EQ)$") |
| 73 | section: str = Field(min_length=1, max_length=64) |
| 74 | |
| 75 | |
| 76 | class MappingIn(BaseModel): |
| 77 | account_code: str = Field(min_length=1, max_length=64) |
| 78 | target_note_id: int |
| 79 | mapping_type: str = Field(default="closing", max_length=32) |
| 80 | |
| 81 | |
| 82 | def _year_or_404(session: Session, year_id: int) -> FiscalYear: |
| 83 | year = session.get(FiscalYear, year_id) |
| 84 | if year is None: |
| 85 | raise HTTPException(status_code=404, detail="fiscal year not found") |
| 86 | return year |
| 87 | |
| 88 | |
| 89 | @router.post("/companies") |
| 90 | def create_company(body: CompanyIn, session: Session = Depends(get_session)) -> dict: |
| 91 | company = Company(code=body.code, name=body.name) |
| 92 | session.add(company) |
| 93 | session.flush() |
| 94 | year = FiscalYear(company_id=company.id, year=body.year) |
| 95 | session.add(year) |
| 96 | session.commit() |
| 97 | return { |
| 98 | "company_id": company.id, |
| 99 | "year_id": year.id, |
| 100 | "year": year.year, |
| 101 | "status": year.status.value, |
| 102 | } |
| 103 | |
| 104 | |
| 105 | @router.post("/years/{year_id}/ledger") |
| 106 | def upload_ledger( |
| 107 | year_id: int, |
| 108 | file: UploadFile = File(...), |
| 109 | session: Session = Depends(get_session), |
| 110 | ) -> dict: |
| 111 | year = _year_or_404(session, year_id) |
| 112 | content = file.file.read() |
| 113 | store = SourceStore(get_settings().source_store_root) |
| 114 | try: |
| 115 | source = register_source_document( |
| 116 | session, |
| 117 | year_id=year_id, |
| 118 | filename=file.filename or "ledger.xlsx", |
| 119 | document_type="general_ledger", |
| 120 | content=content, |
| 121 | store=store, |
| 122 | ) |
| 123 | except (SourceRegistrationError, SourceStoreError) as exc: |
| 124 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 125 | |
| 126 | skipped: list[SkippedRow] = [] |
| 127 | try: |
| 128 | records = [ |
| 129 | rec |
| 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: |
| 136 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 137 | |
| 138 | next_version = ( |
| 139 | session.scalar( |
| 140 | select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id) |
| 141 | ) |
| 142 | or 0 |
| 143 | ) + 1 |
| 144 | try: |
| 145 | count = import_ledger_balances( |
| 146 | session, |
| 147 | year_id=year_id, |
| 148 | source_document_id=source.id, |
| 149 | records=records, |
| 150 | import_version=next_version, |
| 151 | ) |
| 152 | except ValueError as exc: |
| 153 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 154 | session.commit() |
| 155 | return { |
| 156 | "source_document_id": source.id, |
| 157 | "file_hash": source.file_hash, |
| 158 | "import_version": next_version, |
| 159 | "accounts_imported": count, |
| 160 | "rows_for_year": len(records), |
| 161 | "skipped_rows": [{"row": s.row_number, "reason": s.reason} for s in skipped], |
| 162 | } |
| 163 | |
| 164 | |
| 165 | @router.post("/years/{year_id}/notes") |
| 166 | def create_note(year_id: int, body: NoteIn, session: Session = Depends(get_session)) -> dict: |
| 167 | _year_or_404(session, year_id) |
| 168 | note = NoteDefinition( |
| 169 | year_id=year_id, |
| 170 | note_number=body.note_number, |
| 171 | title=body.title, |
| 172 | configuration_json={"statement": body.statement, "section": body.section}, |
| 173 | ) |
| 174 | session.add(note) |
| 175 | session.commit() |
| 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) |
| 223 | note = session.get(NoteDefinition, body.target_note_id) |
| 224 | if note is None or note.year_id != year_id: |
| 225 | raise HTTPException(status_code=422, detail="target note not found in this year") |
| 226 | rule = MappingRule( |
| 227 | year_id=year_id, |
| 228 | rule_key=f"{body.account_code}->{body.target_note_id}", |
| 229 | account_code=body.account_code, |
| 230 | target_note_id=body.target_note_id, |
| 231 | mapping_type=body.mapping_type, |
| 232 | ) |
| 233 | session.add(rule) |
| 234 | session.commit() |
| 235 | return {"mapping_id": rule.id, "account_code": rule.account_code} |
| 236 | |
| 237 | |
| 238 | @router.post("/years/{year_id}/statements/build") |
| 239 | def build(year_id: int, session: Session = Depends(get_session)) -> dict: |
| 240 | _year_or_404(session, year_id) |
| 241 | try: |
| 242 | result = build_statements(session, year_id) |
| 243 | except StatementBuildError as exc: |
| 244 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 245 | session.commit() |
| 246 | return { |
| 247 | "statements": [ |
| 248 | {"id": s.id, "type": s.statement_type.value, "version": s.version} |
| 249 | for s in result.statements |
| 250 | ], |
| 251 | "unmapped_accounts": list(result.unmapped_accounts), |
| 252 | } |
| 253 | |
| 254 | |
| 255 | @router.get("/years/{year_id}/statements") |
| 256 | def list_statements(year_id: int, session: Session = Depends(get_session)) -> dict: |
| 257 | _year_or_404(session, year_id) |
| 258 | statements = session.scalars( |
| 259 | select(FinancialStatement) |
| 260 | .where(FinancialStatement.year_id == year_id) |
| 261 | .order_by(FinancialStatement.statement_type, FinancialStatement.version) |
| 262 | ).all() |
| 263 | payload = [] |
| 264 | for statement in statements: |
| 265 | lines = session.scalars( |
| 266 | select(StatementLine) |
| 267 | .where(StatementLine.statement_id == statement.id) |
| 268 | .order_by(StatementLine.line_order) |
| 269 | ).all() |
| 270 | payload.append( |
| 271 | { |
| 272 | "id": statement.id, |
| 273 | "type": statement.statement_type.value, |
| 274 | "label_fa": STATEMENT_LABELS_FA.get(statement.statement_type.value, ""), |
| 275 | "version": statement.version, |
| 276 | "lines": [ |
| 277 | { |
| 278 | "id": ln.id, |
| 279 | "line_order": ln.line_order, |
| 280 | "label": ln.line_label, |
| 281 | "mapped_total": str(ln.mapped_total) |
| 282 | if ln.mapped_total is not None |
| 283 | else None, |
| 284 | "target_note_id": ln.target_note_id, |
| 285 | } |
| 286 | for ln in lines |
| 287 | ], |
| 288 | } |
| 289 | ) |
| 290 | return {"statements": payload, "section_labels_fa": SECTION_LABELS_FA} |
| 291 | |
| 292 | |
| 293 | @router.get("/years/{year_id}/statements/export") |
| 294 | def export_statements( |
| 295 | year_id: int, format: str = "xlsx", session: Session = Depends(get_session) |
| 296 | ) -> StreamingResponse: |
| 297 | _year_or_404(session, year_id) |
| 298 | try: |
| 299 | if format == "json": |
| 300 | data = export_statements_json_bytes(session, year_id) |
| 301 | media = "application/json" |
| 302 | ext = "json" |
| 303 | elif format == "xlsx": |
| 304 | data = export_statements_workbook(session, year_id) |
| 305 | media = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" |
| 306 | ext = "xlsx" |
| 307 | else: |
| 308 | raise HTTPException(status_code=422, detail="format must be 'xlsx' or 'json'") |
| 309 | except StatementExportError as exc: |
| 310 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 311 | return StreamingResponse( |
| 312 | iter([data]), |
| 313 | media_type=media, |
| 314 | headers={"Content-Disposition": f'attachment; filename="aram-statements-{year_id}.{ext}"'}, |
| 315 | ) |
| 316 | |
| 317 | |
| 318 | @router.get("/statement-lines/{line_id}/drilldown") |
| 319 | def line_drilldown(line_id: int, session: Session = Depends(get_session)) -> dict: |
| 320 | try: |
| 321 | return drill_down(session, line_id) |
| 322 | except StatementBuildError as exc: |
| 323 | raise HTTPException(status_code=404, detail=str(exc)) from exc |
| 324 | |
| 325 | |
| 326 | @router.get("/years/{year_id}/preflight") |
| 327 | def preflight(year_id: int, session: Session = Depends(get_session)) -> dict: |
| 328 | year = _year_or_404(session, year_id) |
| 329 | version = session.scalar( |
| 330 | select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id) |
| 331 | ) |
| 332 | balances = ( |
| 333 | session.scalars( |
| 334 | select(LedgerBalance).where( |
| 335 | LedgerBalance.year_id == year_id, LedgerBalance.import_version == version |
| 336 | ) |
| 337 | ).all() |
| 338 | if version is not None |
| 339 | else [] |
| 340 | ) |
| 341 | rows = [ |
| 342 | BalanceRow( |
| 343 | row_number=b.source_row, |
| 344 | account_code=b.account_full_code, |
| 345 | opening=b.opening, |
| 346 | debit=b.debit, |
| 347 | credit=b.credit, |
| 348 | closing=b.closing, |
| 349 | ) |
| 350 | for b in balances |
| 351 | ] |
| 352 | rules = session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all() |
| 353 | from aram_backend.domain.controls import MappingTarget |
| 354 | |
| 355 | mappings: dict[str, list[MappingTarget]] = {} |
| 356 | for rule in rules: |
| 357 | mappings.setdefault(rule.account_code, []).append( |
| 358 | MappingTarget(target=str(rule.target_note_id)) |
| 359 | ) |
| 360 | results = run_controls(rows, mappings) |
| 361 | return { |
| 362 | "year": year.year, |
| 363 | "can_approve": all(r.passed for r in results if r.severity == "ERROR"), |
| 364 | "controls": [ |
| 365 | {"code": r.code, "severity": r.severity, "passed": r.passed, "message_fa": r.message_fa} |
| 366 | for r in results |
| 367 | ], |
| 368 | } |
| 369 | |
| 370 | |
| 371 | # ----------------------------------------------------------- Phase 2: mapping I/O |
| 372 | @router.get("/years/{year_id}/mappings/export") |
| 373 | def export_mappings(year_id: int, session: Session = Depends(get_session)) -> StreamingResponse: |
| 374 | _year_or_404(session, year_id) |
| 375 | data = export_mappings_workbook(session, year_id) |
| 376 | return StreamingResponse( |
| 377 | iter([data]), |
| 378 | media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", |
| 379 | headers={"Content-Disposition": f'attachment; filename="aram-mappings-{year_id}.xlsx"'}, |
| 380 | ) |
| 381 | |
| 382 | |
| 383 | @router.post("/years/{year_id}/mappings/import") |
| 384 | def import_mappings( |
| 385 | year_id: int, |
| 386 | file: UploadFile = File(...), |
| 387 | session: Session = Depends(get_session), |
| 388 | ) -> dict: |
| 389 | _year_or_404(session, year_id) |
| 390 | content = file.file.read() |
| 391 | try: |
| 392 | result = import_mappings_workbook(session, year_id, content) |
| 393 | except MappingImportError as exc: |
| 394 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 395 | session.commit() |
| 396 | return { |
| 397 | "created": result.created, |
| 398 | "notes_created": result.notes_created, |
| 399 | "errors": result.errors, |
| 400 | } |
| 401 | |
| 402 | |
| 403 | @router.get("/years/{year_id}/unknown-accounts") |
| 404 | def unknown_queue(year_id: int, session: Session = Depends(get_session)) -> dict: |
| 405 | _year_or_404(session, year_id) |
| 406 | queue = unknown_accounts(session, year_id) |
| 407 | return {"count": len(queue), "accounts": queue} |
| 408 | |
| 409 | |
| 410 | class CarryForwardIn(BaseModel): |
| 411 | from_year_id: int |
| 412 | |
| 413 | |
| 414 | @router.post("/years/{year_id}/mappings/carry-forward") |
| 415 | def carry_forward( |
| 416 | year_id: int, body: CarryForwardIn, session: Session = Depends(get_session) |
| 417 | ) -> dict: |
| 418 | _year_or_404(session, year_id) |
| 419 | try: |
| 420 | result = carry_forward_mappings(session, body.from_year_id, year_id) |
| 421 | except CarryForwardError as exc: |
| 422 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 423 | session.commit() |
| 424 | return {"notes_created": result.notes_created, "mappings_created": result.mappings_created} |
| 425 | |
| 426 | |
| 427 | class ApproveIn(BaseModel): |
| 428 | actor: str = Field(default="", max_length=128) |
| 429 | |
| 430 | |
| 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: |
| 445 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 446 | if not result.approved: |
| 447 | return { |
| 448 | "approved": False, |
| 449 | "blocking": [{"code": r.code, "message_fa": r.message_fa} for r in result.blocking], |
| 450 | } |
| 451 | session.commit() |
| 452 | return {"approved": True, "status": "Approved"} |
| 453 | |
| 454 | |
| 455 | # ----------------------------------------------------------- Phase 3: note engine |
| 456 | class NoteRowIn(BaseModel): |
| 457 | row_order: int = Field(ge=0) |
| 458 | label: str = Field(min_length=1, max_length=512) |
| 459 | formula_logic: str | None = Field(default=None, max_length=2000) |
| 460 | |
| 461 | |
| 462 | @router.post("/years/{year_id}/notes/{note_id}/rows") |
| 463 | def create_note_row( |
| 464 | year_id: int, note_id: int, body: NoteRowIn, session: Session = Depends(get_session) |
| 465 | ) -> dict: |
| 466 | _year_or_404(session, year_id) |
| 467 | note = session.get(NoteDefinition, note_id) |
| 468 | if note is None or note.year_id != year_id: |
| 469 | raise HTTPException(status_code=404, detail="note not found in this year") |
| 470 | if body.formula_logic: |
| 471 | from aram_backend.domain.formula import FormulaError, parse_formula |
| 472 | |
| 473 | try: |
| 474 | parse_formula(body.formula_logic) |
| 475 | except FormulaError as exc: |
| 476 | raise HTTPException(status_code=422, detail=f"invalid formula: {exc}") from exc |
| 477 | row = NoteRow( |
| 478 | note_id=note_id, |
| 479 | row_order=body.row_order, |
| 480 | label=body.label, |
| 481 | formula_logic=body.formula_logic, |
| 482 | ) |
| 483 | session.add(row) |
| 484 | session.commit() |
| 485 | return {"row_id": row.id, "row_order": row.row_order} |
| 486 | |
| 487 | |
| 488 | @router.get("/notes/{note_id}/rows") |
| 489 | def list_note_rows(note_id: int, session: Session = Depends(get_session)) -> dict: |
| 490 | note = session.get(NoteDefinition, note_id) |
| 491 | if note is None: |
| 492 | raise HTTPException(status_code=404, detail="note not found") |
| 493 | rows = sorted(note.rows, key=lambda r: r.row_order) |
| 494 | return { |
| 495 | "note_id": note.id, |
| 496 | "rows": [ |
| 497 | {"row_order": r.row_order, "label": r.label, "formula_logic": r.formula_logic} |
| 498 | for r in rows |
| 499 | ], |
| 500 | } |
| 501 | |
| 502 | |
| 503 | @router.get("/notes/{note_id}/evaluate") |
| 504 | def evaluate_note_endpoint(note_id: int, session: Session = Depends(get_session)) -> dict: |
| 505 | try: |
| 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} |