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

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

Synced Dec 4, 14:15 UTC

dependabot/github_actions/actions/upload-artifact-7
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 dependabot/github_actions/actions/checkout-7 dependabot/github_actions/actions/setup-node-6 dependabot/github_actions/actions/setup-python-7 dependabot/github_actions/actions/upload-artifact-7 dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1 dependabot/npm_and_yarn/frontend/globals-17.15.0 dependabot/npm_and_yarn/frontend/vite-8.4.0 dependabot/npm_and_yarn/frontend/vitest-5.1.2 dependabot/npm_and_yarn/frontend/vitest/coverage-v8-5.1.2 dependabot/pip/backend/mypy-gte-1.13-and-lt-3 dependabot/pip/backend/pytest-cov-gte-6.0-and-lt-8 dependabot/pip/backend/setuptools-gte-75-and-lt-85 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 723 lines 25.7 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 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.control_context import build_control_context, load_mappings, load_rows
36 from aram_backend.services.ledger_import import import_ledger_balances
37 from aram_backend.services.mapping_io import (
38 MappingImportError,
39 export_mappings_workbook,
40 import_mappings_workbook,
41 )
42 from aram_backend.services.mapping_workflow import (
43 CarryForwardError,
44 carry_forward_mappings,
45 unknown_accounts,
46 )
47 from aram_backend.services.note_engine import NoteEngineError, evaluate_note
48 from aram_backend.services.source_store import SourceStore, SourceStoreError
49 from aram_backend.services.statement_build import (
50 SECTION_LABELS_FA,
51 STATEMENT_LABELS_FA,
52 StatementBuildError,
53 build_statements,
54 drill_down,
55 )
56 from aram_backend.services.statement_compare import compare_built_statements
57 from aram_backend.services.statement_export import (
58 StatementExportError,
59 export_statements_json_bytes,
60 export_statements_workbook,
61 )
62 from aram_backend.services.users import AuthorizationError, ensure_role
63
64 # R1 (booklet 2.1): every statement route requires a server-side session; reads
65 # included. The only unauthenticated routes in the app are /health, /auth/login,
66 # /auth/launch and the one-time first-admin bootstrap.
67 router = APIRouter(
68 prefix="/api/v1",
69 tags=["statements"],
70 dependencies=[Depends(require_launch), Depends(current_user)],
71 )
72
73
74 class CompanyIn(BaseModel):
75 code: str = Field(min_length=1, max_length=64)
76 name: str = Field(min_length=1, max_length=256)
77 year: int = Field(gt=0)
78
79
80 class NoteIn(BaseModel):
81 note_number: str = Field(min_length=1, max_length=32)
82 title: str = Field(min_length=1, max_length=512)
83 statement: str = Field(pattern="^(BS|IS|CF|EQ)$")
84 section: str = Field(min_length=1, max_length=64)
85 # R2: explicit control role. C-08 needs a retained-earnings note and C-10 a
86 # cash note; neither is ever inferred from a title or note number.
87 role: str | None = Field(default=None, pattern="^(retained_earnings|cash)$")
88
89
90 class MappingIn(BaseModel):
91 account_code: str = Field(min_length=1, max_length=64)
92 target_note_id: int
93 mapping_type: str = Field(default="closing", max_length=32)
94
95
96 def _year_or_404(session: Session, year_id: int) -> FiscalYear:
97 year = session.get(FiscalYear, year_id)
98 if year is None:
99 raise HTTPException(status_code=404, detail="fiscal year not found")
100 return year
101
102
103 def _note_config(statement: str, section: str, role: str | None) -> dict:
104 config = {"statement": statement, "section": section}
105 if role:
106 config["role"] = role
107 return config
108
109
110 class YearIn(BaseModel):
111 year: int = Field(ge=1300, le=1600)
112
113
114 @router.post("/companies/{company_id}/years")
115 def create_year(company_id: int, body: YearIn, session: Session = Depends(get_session)) -> dict:
116 """Add another fiscal year to a company (R2: C-05/C-14 need the prior year)."""
117 if session.get(Company, company_id) is None:
118 raise HTTPException(status_code=422, detail="شرکت یافت نشد")
119 existing = session.scalar(
120 select(FiscalYear).where(FiscalYear.company_id == company_id, FiscalYear.year == body.year)
121 )
122 if existing is not None:
123 raise HTTPException(status_code=422, detail="این سال مالی قبلاً ثبت شده است")
124 year = FiscalYear(company_id=company_id, year=body.year)
125 session.add(year)
126 session.commit()
127 return {"year_id": year.id, "year": year.year, "status": year.status.value}
128
129
130 @router.post("/companies")
131 def create_company(body: CompanyIn, session: Session = Depends(get_session)) -> dict:
132 company = Company(code=body.code, name=body.name)
133 session.add(company)
134 session.flush()
135 year = FiscalYear(company_id=company.id, year=body.year)
136 session.add(year)
137 session.commit()
138 return {
139 "company_id": company.id,
140 "year_id": year.id,
141 "year": year.year,
142 "status": year.status.value,
143 }
144
145
146 @router.post("/years/{year_id}/ledger")
147 def upload_ledger(
148 year_id: int,
149 file: UploadFile = File(...),
150 session: Session = Depends(get_session),
151 ) -> dict:
152 year = _year_or_404(session, year_id)
153 content = file.file.read()
154 store = SourceStore(get_settings().source_store_root)
155 try:
156 source = register_source_document(
157 session,
158 year_id=year_id,
159 filename=file.filename or "ledger.xlsx",
160 document_type="general_ledger",
161 content=content,
162 store=store,
163 )
164 except (SourceRegistrationError, SourceStoreError) as exc:
165 raise HTTPException(status_code=422, detail=str(exc)) from exc
166
167 skipped: list[SkippedRow] = []
168 try:
169 records = [
170 rec
171 for rec in parse_ledger(
172 content, file.filename or "ledger.xlsx", tolerant=True, skipped=skipped
173 )
174 if rec.source_year == year.year
175 ]
176 except LedgerParseError as exc:
177 raise HTTPException(status_code=422, detail=str(exc)) from exc
178
179 next_version = (
180 session.scalar(
181 select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
182 )
183 or 0
184 ) + 1
185 try:
186 count = import_ledger_balances(
187 session,
188 year_id=year_id,
189 source_document_id=source.id,
190 records=records,
191 import_version=next_version,
192 )
193 except ValueError as exc:
194 raise HTTPException(status_code=422, detail=str(exc)) from exc
195 session.commit()
196 return {
197 "source_document_id": source.id,
198 "file_hash": source.file_hash,
199 "import_version": next_version,
200 "accounts_imported": count,
201 "rows_for_year": len(records),
202 "skipped_rows": [{"row": s.row_number, "reason": s.reason} for s in skipped],
203 }
204
205
206 @router.post("/years/{year_id}/notes")
207 def create_note(year_id: int, body: NoteIn, session: Session = Depends(get_session)) -> dict:
208 _year_or_404(session, year_id)
209 note = NoteDefinition(
210 year_id=year_id,
211 note_number=body.note_number,
212 title=body.title,
213 configuration_json=_note_config(body.statement, body.section, body.role),
214 )
215 session.add(note)
216 session.commit()
217 return {"note_id": note.id, "note_number": note.note_number}
218
219
220 @router.get("/years/{year_id}/notes")
221 def list_notes(year_id: int, session: Session = Depends(get_session)) -> dict:
222 _year_or_404(session, year_id)
223 notes = session.scalars(
224 select(NoteDefinition)
225 .where(NoteDefinition.year_id == year_id)
226 .order_by(NoteDefinition.note_number)
227 ).all()
228 return {
229 "notes": [
230 {
231 "note_id": n.id,
232 "note_number": n.note_number,
233 "title": n.title,
234 "statement": (n.configuration_json or {}).get("statement", ""),
235 "section": (n.configuration_json or {}).get("section", ""),
236 "role": (n.configuration_json or {}).get("role"),
237 }
238 for n in notes
239 ]
240 }
241
242
243 @router.get("/years/{year_id}/mappings")
244 def list_mappings(year_id: int, session: Session = Depends(get_session)) -> dict:
245 _year_or_404(session, year_id)
246 rules = session.scalars(
247 select(MappingRule).where(MappingRule.year_id == year_id).order_by(MappingRule.account_code)
248 ).all()
249 return {
250 "mappings": [
251 {
252 "mapping_id": r.id,
253 "account_code": r.account_code,
254 "target_note_id": r.target_note_id,
255 "mapping_type": r.mapping_type,
256 }
257 for r in rules
258 ]
259 }
260
261
262 @router.post("/years/{year_id}/mappings")
263 def create_mapping(year_id: int, body: MappingIn, session: Session = Depends(get_session)) -> dict:
264 _year_or_404(session, year_id)
265 note = session.get(NoteDefinition, body.target_note_id)
266 if note is None or note.year_id != year_id:
267 raise HTTPException(status_code=422, detail="target note not found in this year")
268 rule = MappingRule(
269 year_id=year_id,
270 rule_key=f"{body.account_code}->{body.target_note_id}",
271 account_code=body.account_code,
272 target_note_id=body.target_note_id,
273 mapping_type=body.mapping_type,
274 )
275 session.add(rule)
276 session.commit()
277 return {"mapping_id": rule.id, "account_code": rule.account_code}
278
279
280 @router.post("/years/{year_id}/statements/build")
281 def build(year_id: int, session: Session = Depends(get_session)) -> dict:
282 _year_or_404(session, year_id)
283 try:
284 result = build_statements(session, year_id)
285 except StatementBuildError as exc:
286 raise HTTPException(status_code=422, detail=str(exc)) from exc
287 session.commit()
288 return {
289 "statements": [
290 {"id": s.id, "type": s.statement_type.value, "version": s.version}
291 for s in result.statements
292 ],
293 "unmapped_accounts": list(result.unmapped_accounts),
294 }
295
296
297 @router.get("/years/{year_id}/statements")
298 def list_statements(year_id: int, session: Session = Depends(get_session)) -> dict:
299 _year_or_404(session, year_id)
300 statements = session.scalars(
301 select(FinancialStatement)
302 .where(FinancialStatement.year_id == year_id)
303 .order_by(FinancialStatement.statement_type, FinancialStatement.version)
304 ).all()
305 payload = []
306 for statement in statements:
307 lines = session.scalars(
308 select(StatementLine)
309 .where(StatementLine.statement_id == statement.id)
310 .order_by(StatementLine.line_order)
311 ).all()
312 payload.append(
313 {
314 "id": statement.id,
315 "type": statement.statement_type.value,
316 "label_fa": STATEMENT_LABELS_FA.get(statement.statement_type.value, ""),
317 "version": statement.version,
318 "lines": [
319 {
320 "id": ln.id,
321 "line_order": ln.line_order,
322 "label": ln.line_label,
323 "mapped_total": str(ln.mapped_total)
324 if ln.mapped_total is not None
325 else None,
326 "target_note_id": ln.target_note_id,
327 }
328 for ln in lines
329 ],
330 }
331 )
332 return {"statements": payload, "section_labels_fa": SECTION_LABELS_FA}
333
334
335 @router.get("/years/{year_id}/statements/export")
336 def export_statements(
337 year_id: int, format: str = "xlsx", session: Session = Depends(get_session)
338 ) -> StreamingResponse:
339 _year_or_404(session, year_id)
340 try:
341 if format == "json":
342 data = export_statements_json_bytes(session, year_id)
343 media = "application/json"
344 ext = "json"
345 elif format == "xlsx":
346 data = export_statements_workbook(session, year_id)
347 media = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
348 ext = "xlsx"
349 else:
350 raise HTTPException(status_code=422, detail="format must be 'xlsx' or 'json'")
351 except StatementExportError as exc:
352 raise HTTPException(status_code=422, detail=str(exc)) from exc
353 return StreamingResponse(
354 iter([data]),
355 media_type=media,
356 headers={"Content-Disposition": f'attachment; filename="aram-statements-{year_id}.{ext}"'},
357 )
358
359
360 @router.get("/statement-lines/{line_id}/drilldown")
361 def line_drilldown(line_id: int, session: Session = Depends(get_session)) -> dict:
362 try:
363 return drill_down(session, line_id)
364 except StatementBuildError as exc:
365 raise HTTPException(status_code=404, detail=str(exc)) from exc
366
367
368 @router.get("/years/{year_id}/preflight")
369 def preflight(year_id: int, session: Session = Depends(get_session)) -> dict:
370 """All 15 controls (R2). An unrun ERROR control blocks approval and says why."""
371 year = _year_or_404(session, year_id)
372 results = run_controls(
373 load_rows(session, year_id),
374 load_mappings(session, year_id),
375 build_control_context(session, year_id),
376 )
377 return {
378 "year": year.year,
379 "can_approve": all(r.passed for r in results if r.severity == "ERROR"),
380 "controls": [
381 {
382 "code": r.code,
383 "severity": r.severity,
384 "passed": r.passed,
385 "ran": r.ran,
386 "message_fa": r.message_fa,
387 }
388 for r in results
389 ],
390 }
391
392
393 # ----------------------------------------------------------- Phase 2: mapping I/O
394 @router.post("/years/{year_id}/official-comparison")
395 def official_comparison(
396 year_id: int,
397 file: UploadFile = File(...),
398 session: Session = Depends(get_session),
399 ) -> dict:
400 """Compare the **built** statements with an uploaded official workbook (R3).
401
402 The workbook is parsed in memory; nothing is written to the source store and
403 no stored figure is changed. The result also feeds control C-13.
404 """
405 year = _year_or_404(session, year_id)
406 report = compare_built_statements(session, year_id, file.file.read(), year.year)
407 return {
408 "year": year.year,
409 "counts": report.counts(),
410 "deltas": [
411 {
412 "statement": d.statement,
413 "note": d.note,
414 "built_million": d.built_million,
415 "official_million": d.official_million,
416 "delta": d.delta,
417 "match": d.match,
418 "status": d.status,
419 "official_cell": d.official_cell,
420 "accounts": [
421 {
422 "account_code": a.account_code,
423 "account_name": a.account_name,
424 "million_rounded": a.million_rounded,
425 "source_rows": a.source_rows,
426 }
427 for a in d.accounts
428 ],
429 }
430 for d in report.deltas
431 ],
432 }
433
434
435 @router.get("/years/{year_id}/mappings/export")
436 def export_mappings(year_id: int, session: Session = Depends(get_session)) -> StreamingResponse:
437 _year_or_404(session, year_id)
438 data = export_mappings_workbook(session, year_id)
439 return StreamingResponse(
440 iter([data]),
441 media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
442 headers={"Content-Disposition": f'attachment; filename="aram-mappings-{year_id}.xlsx"'},
443 )
444
445
446 @router.post("/years/{year_id}/mappings/import")
447 def import_mappings(
448 year_id: int,
449 file: UploadFile = File(...),
450 session: Session = Depends(get_session),
451 ) -> dict:
452 _year_or_404(session, year_id)
453 content = file.file.read()
454 try:
455 result = import_mappings_workbook(session, year_id, content)
456 except MappingImportError as exc:
457 raise HTTPException(status_code=422, detail=str(exc)) from exc
458 session.commit()
459 return {
460 "created": result.created,
461 "notes_created": result.notes_created,
462 "errors": result.errors,
463 }
464
465
466 @router.get("/years/{year_id}/unknown-accounts")
467 def unknown_queue(year_id: int, session: Session = Depends(get_session)) -> dict:
468 _year_or_404(session, year_id)
469 queue = unknown_accounts(session, year_id)
470 return {"count": len(queue), "accounts": queue}
471
472
473 class CarryForwardIn(BaseModel):
474 from_year_id: int
475
476
477 @router.post("/years/{year_id}/mappings/carry-forward")
478 def carry_forward(
479 year_id: int, body: CarryForwardIn, session: Session = Depends(get_session)
480 ) -> dict:
481 _year_or_404(session, year_id)
482 try:
483 result = carry_forward_mappings(session, body.from_year_id, year_id)
484 except CarryForwardError as exc:
485 raise HTTPException(status_code=422, detail=str(exc)) from exc
486 session.commit()
487 return {"notes_created": result.notes_created, "mappings_created": result.mappings_created}
488
489
490 @router.post("/years/{year_id}/approve")
491 def approve(
492 year_id: int, session: Session = Depends(get_session), user: User = Depends(current_user)
493 ) -> dict:
494 # R1 (booklet 2.1): approval always requires an authenticated reviewer/admin.
495 # The former "no users yet -> allowed" shortcut is removed: with zero users
496 # there is no identity, so approval is impossible (401 from current_user).
497 # The role gate runs before the existence check so it can never be skipped.
498 try:
499 ensure_role(user, {UserRole.ADMIN, UserRole.REVIEWER})
500 except AuthorizationError as exc:
501 raise HTTPException(status_code=403, detail=str(exc)) from exc
502 _year_or_404(session, year_id)
503 try:
504 result = approve_year(session, year_id, actor=user.username)
505 except ApprovalError as exc:
506 raise HTTPException(status_code=422, detail=str(exc)) from exc
507 if not result.approved:
508 # The refused decision is itself audited (R2), so it must be committed.
509 session.commit()
510 return {
511 "approved": False,
512 "blocking": [
513 {"code": r.code, "message_fa": r.message_fa, "ran": r.ran} for r in result.blocking
514 ],
515 }
516 session.commit()
517 return {"approved": True, "status": "Approved"}
518
519
520 # ----------------------------------------------------------- Phase 3: note engine
521 class NoteRowIn(BaseModel):
522 row_order: int = Field(ge=0)
523 label: str = Field(min_length=1, max_length=512)
524 formula_logic: str | None = Field(default=None, max_length=2000)
525
526
527 @router.post("/years/{year_id}/notes/{note_id}/rows")
528 def create_note_row(
529 year_id: int, note_id: int, body: NoteRowIn, session: Session = Depends(get_session)
530 ) -> dict:
531 _year_or_404(session, year_id)
532 note = session.get(NoteDefinition, note_id)
533 if note is None or note.year_id != year_id:
534 raise HTTPException(status_code=404, detail="note not found in this year")
535 if body.formula_logic:
536 from aram_backend.domain.formula import FormulaError, parse_formula
537
538 try:
539 parse_formula(body.formula_logic)
540 except FormulaError as exc:
541 raise HTTPException(status_code=422, detail=f"invalid formula: {exc}") from exc
542 row = NoteRow(
543 note_id=note_id,
544 row_order=body.row_order,
545 label=body.label,
546 formula_logic=body.formula_logic,
547 )
548 session.add(row)
549 session.commit()
550 return {"row_id": row.id, "row_order": row.row_order}
551
552
553 @router.get("/notes/{note_id}/rows")
554 def list_note_rows(note_id: int, session: Session = Depends(get_session)) -> dict:
555 note = session.get(NoteDefinition, note_id)
556 if note is None:
557 raise HTTPException(status_code=404, detail="note not found")
558 rows = sorted(note.rows, key=lambda r: r.row_order)
559 return {
560 "note_id": note.id,
561 "rows": [
562 {"row_order": r.row_order, "label": r.label, "formula_logic": r.formula_logic}
563 for r in rows
564 ],
565 }
566
567
568 @router.get("/notes/{note_id}/evaluate")
569 def evaluate_note_endpoint(note_id: int, session: Session = Depends(get_session)) -> dict:
570 try:
571 return evaluate_note(session, note_id)
572 except NoteEngineError as exc:
573 raise HTTPException(status_code=422, detail=str(exc)) from exc
574
575
576 # ------------------------------------------------- Phase 5: editable notes/mappings
577 def _commit_guarded(session: Session) -> None:
578 """Commit, translating the D-07 immutability guard into HTTP 409."""
579 try:
580 session.commit()
581 except ValueError as exc:
582 session.rollback()
583 raise HTTPException(status_code=409, detail=str(exc)) from exc
584
585
586 def _note_in_year(session: Session, year_id: int, note_id: int) -> NoteDefinition:
587 note = session.get(NoteDefinition, note_id)
588 if note is None or note.year_id != year_id:
589 raise HTTPException(status_code=404, detail="note not found in this year")
590 return note
591
592
593 class NoteUpdate(BaseModel):
594 note_number: str | None = Field(default=None, min_length=1, max_length=32)
595 title: str | None = Field(default=None, min_length=1, max_length=512)
596 statement: str | None = Field(default=None, pattern="^(BS|IS|CF|EQ)$")
597 section: str | None = Field(default=None, min_length=1, max_length=64)
598 role: str | None = Field(default=None, pattern="^(retained_earnings|cash)$")
599
600
601 @router.put("/years/{year_id}/notes/{note_id}")
602 def update_note(
603 year_id: int, note_id: int, body: NoteUpdate, session: Session = Depends(get_session)
604 ) -> dict:
605 _year_or_404(session, year_id)
606 note = _note_in_year(session, year_id, note_id)
607 if body.note_number is not None:
608 note.note_number = body.note_number
609 if body.title is not None:
610 note.title = body.title
611 config = dict(note.configuration_json or {})
612 if body.statement is not None:
613 config["statement"] = body.statement
614 if body.section is not None:
615 config["section"] = body.section
616 if body.role is not None:
617 config["role"] = body.role
618 note.configuration_json = config
619 _commit_guarded(session)
620 return {"note_id": note.id, "note_number": note.note_number, "title": note.title}
621
622
623 @router.delete("/years/{year_id}/notes/{note_id}")
624 def delete_note(year_id: int, note_id: int, session: Session = Depends(get_session)) -> dict:
625 _year_or_404(session, year_id)
626 note = _note_in_year(session, year_id, note_id)
627 referencing_mappings = session.scalar(
628 select(func.count(MappingRule.id)).where(MappingRule.target_note_id == note_id)
629 )
630 referencing_lines = session.scalar(
631 select(func.count(StatementLine.id)).where(StatementLine.target_note_id == note_id)
632 )
633 if referencing_mappings or referencing_lines:
634 raise HTTPException(
635 status_code=409,
636 detail="note is referenced by mappings or statement lines; remove those first",
637 )
638 session.delete(note) # NoteRow rows cascade
639 _commit_guarded(session)
640 return {"deleted": note_id}
641
642
643 class MappingUpdate(BaseModel):
644 target_note_id: int | None = None
645 mapping_type: str | None = Field(default=None, max_length=32)
646
647
648 @router.put("/years/{year_id}/mappings/{mapping_id}")
649 def update_mapping(
650 year_id: int, mapping_id: int, body: MappingUpdate, session: Session = Depends(get_session)
651 ) -> dict:
652 _year_or_404(session, year_id)
653 rule = session.get(MappingRule, mapping_id)
654 if rule is None or rule.year_id != year_id:
655 raise HTTPException(status_code=404, detail="mapping not found in this year")
656 if body.target_note_id is not None:
657 _note_in_year(session, year_id, body.target_note_id)
658 rule.target_note_id = body.target_note_id
659 if body.mapping_type is not None:
660 rule.mapping_type = body.mapping_type
661 _commit_guarded(session)
662 return {"mapping_id": rule.id, "account_code": rule.account_code}
663
664
665 @router.delete("/years/{year_id}/mappings/{mapping_id}")
666 def delete_mapping(year_id: int, mapping_id: int, session: Session = Depends(get_session)) -> dict:
667 _year_or_404(session, year_id)
668 rule = session.get(MappingRule, mapping_id)
669 if rule is None or rule.year_id != year_id:
670 raise HTTPException(status_code=404, detail="mapping not found in this year")
671 session.delete(rule)
672 _commit_guarded(session)
673 return {"deleted": mapping_id}
674
675
676 class NoteRowUpdate(BaseModel):
677 row_order: int | None = Field(default=None, ge=0)
678 label: str | None = Field(default=None, min_length=1, max_length=512)
679 formula_logic: str | None = Field(default=None, max_length=2000)
680
681
682 @router.put("/years/{year_id}/notes/{note_id}/rows/{row_id}")
683 def update_note_row(
684 year_id: int,
685 note_id: int,
686 row_id: int,
687 body: NoteRowUpdate,
688 session: Session = Depends(get_session),
689 ) -> dict:
690 _year_or_404(session, year_id)
691 _note_in_year(session, year_id, note_id)
692 row = session.get(NoteRow, row_id)
693 if row is None or row.note_id != note_id:
694 raise HTTPException(status_code=404, detail="note row not found")
695 if body.formula_logic:
696 from aram_backend.domain.formula import FormulaError, parse_formula
697
698 try:
699 parse_formula(body.formula_logic)
700 except FormulaError as exc:
701 raise HTTPException(status_code=422, detail=f"invalid formula: {exc}") from exc
702 if body.row_order is not None:
703 row.row_order = body.row_order
704 if body.label is not None:
705 row.label = body.label
706 if body.formula_logic is not None:
707 row.formula_logic = body.formula_logic
708 _commit_guarded(session)
709 return {"row_id": row.id, "row_order": row.row_order}
710
711
712 @router.delete("/years/{year_id}/notes/{note_id}/rows/{row_id}")
713 def delete_note_row(
714 year_id: int, note_id: int, row_id: int, session: Session = Depends(get_session)
715 ) -> dict:
716 _year_or_404(session, year_id)
717 _note_in_year(session, year_id, note_id)
718 row = session.get(NoteRow, row_id)
719 if row is None or row.note_id != note_id:
720 raise HTTPException(status_code=404, detail="note row not found")
721 session.delete(row)
722 _commit_guarded(session)
723 return {"deleted": row_id}