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
py 401 lines 14.3 KB
Raw
1 """HTTP API for the Pilot workbench (in-memory, audit-friendly, fail-closed)."""
2
3 from __future__ import annotations
4
5 import re
6 from io import BytesIO
7
8 from fastapi import APIRouter, File, HTTPException, Query, UploadFile
9 from fastapi.responses import StreamingResponse
10 from pydantic import BaseModel, Field
11
12 from aram_backend.pilot_demo import build_demo_workbook
13 from aram_backend.pilot_editing import (
14 DuplicateAccountError,
15 DuplicateNoteError,
16 EditingError,
17 InvalidCompanyError,
18 NoteInUseError,
19 UnknownNoteError,
20 make_company,
21 make_note,
22 )
23 from aram_backend.pilot_engine import (
24 DEFERRED_STATEMENTS,
25 RENDERED_STATEMENTS,
26 SECTION_LABELS_FA,
27 SECTION_POLICY,
28 STATEMENT_LABELS_FA,
29 PilotModelError,
30 accounts_table,
31 build_report,
32 export_report_workbook,
33 export_working_workbook,
34 notes_table,
35 parse_pilot_model,
36 )
37 from aram_backend.pilot_store import (
38 InvalidApprovalError,
39 UnknownAccountError,
40 UnknownSessionError,
41 UnknownTargetError,
42 store,
43 )
44
45 router = APIRouter(prefix="/api/v1/pilot", tags=["pilot-workbench"])
46
47 MAX_UPLOAD_BYTES = 25 * 1024 * 1024
48 XLSX_MEDIA_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
49
50 Amount = str | int | float
51
52
53 class MappingUpdate(BaseModel):
54 statement: str = Field(min_length=1)
55 section: str = Field(min_length=1)
56 note_number: str = Field(min_length=1)
57 subnote_code: str = ""
58 approval_status: str = "Draft"
59 reviewer: str = ""
60 actor: str = ""
61
62
63 class AccountCreate(BaseModel):
64 full_code: str = Field(min_length=1)
65 name: str = Field(min_length=1)
66 general_code: str = Field(min_length=1)
67 general_name: str = Field(min_length=1)
68 opening: Amount = "0"
69 debit: Amount = "0"
70 credit: Amount = "0"
71 source_row: int | None = None
72 row_status: str = "Draft"
73 subsidiary_code: str = ""
74 subsidiary_name: str = ""
75 actor: str = ""
76
77
78 class AccountUpdate(BaseModel):
79 name: str = Field(min_length=1)
80 general_code: str = Field(min_length=1)
81 general_name: str = Field(min_length=1)
82 opening: Amount = "0"
83 debit: Amount = "0"
84 credit: Amount = "0"
85 row_status: str = "Draft"
86 subsidiary_code: str = ""
87 subsidiary_name: str = ""
88 actor: str = ""
89
90
91 class AccountRename(BaseModel):
92 new_code: str = Field(min_length=1)
93 actor: str = ""
94
95
96 class NoteCreate(BaseModel):
97 statement: str = Field(min_length=1)
98 section: str = Field(min_length=1)
99 note_number: str = Field(min_length=1)
100 note_title: str = Field(min_length=1)
101 subnote_code: str = ""
102 subnote_title: str = ""
103 actor: str = ""
104
105
106 class NoteUpdate(BaseModel):
107 statement: str = Field(min_length=1)
108 section: str = Field(min_length=1)
109 note_number: str = Field(min_length=1)
110 subnote_code: str = ""
111 note_title: str = Field(min_length=1)
112 subnote_title: str = ""
113 actor: str = ""
114
115
116 class CompanyUpdate(BaseModel):
117 code: str = Field(min_length=1)
118 name: str = Field(min_length=1)
119 fiscal_year: int
120 currency: str = ""
121 unit: str = ""
122 prepared_by: str = ""
123 status: str = "Draft"
124 actor: str = ""
125
126
127 def _issues_payload(exc: PilotModelError) -> list[dict]:
128 return [
129 {
130 "severity": issue.severity, "code": issue.code, "sheet": issue.sheet,
131 "row": issue.row, "field": issue.field, "message": issue.message,
132 }
133 for issue in exc.issues
134 ]
135
136
137 def _session_payload(session_id: str) -> dict:
138 session, working, trail = store.snapshot(session_id)
139 report = build_report(working, working.mappings)
140 return {
141 "session": {
142 "id": session.id, "created_at": session.created_at,
143 "source": session.source, "filename": session.filename,
144 },
145 "report": report,
146 "accounts": accounts_table(working, working.mappings),
147 "notes": notes_table(working),
148 "audit_trail": trail,
149 }
150
151
152 def _create_session(data: bytes, source: str, filename: str) -> dict:
153 try:
154 model = parse_pilot_model(data)
155 except PilotModelError as exc:
156 raise HTTPException(
157 status_code=422,
158 detail={
159 "message": "فایل با قرارداد پایلوت v0.1 سازگار نیست؛ خطاهای زیر را رفع کنید.",
160 "issues": _issues_payload(exc),
161 },
162 ) from exc
163 session = store.create(model, source=source, filename=filename)
164 return _session_payload(session.id)
165
166
167 def _get_session_or_404(session_id: str):
168 try:
169 return store.get(session_id)
170 except UnknownSessionError as exc:
171 raise HTTPException(404, detail={"message": "جلسه یافت نشد؛ دوباره فایل را وارد کنید."}) from exc
172
173
174 def _editing_http_error(exc: Exception) -> HTTPException:
175 if isinstance(exc, (UnknownAccountError, UnknownNoteError)):
176 return HTTPException(404, detail={"message": str(exc) or "مورد یافت نشد."})
177 if isinstance(exc, NoteInUseError):
178 return HTTPException(409, detail={"message": str(exc)})
179 if isinstance(exc, (DuplicateAccountError, DuplicateNoteError)):
180 return HTTPException(409, detail={"message": str(exc)})
181 if isinstance(exc, (EditingError, InvalidApprovalError, UnknownTargetError, InvalidCompanyError)):
182 return HTTPException(422, detail={"message": str(exc)})
183 raise exc
184
185
186 @router.get("/meta")
187 def pilot_meta() -> dict:
188 return {
189 "rendered_statements": list(RENDERED_STATEMENTS),
190 "deferred_statements": list(DEFERRED_STATEMENTS),
191 "statement_labels_fa": STATEMENT_LABELS_FA,
192 "section_policy": SECTION_POLICY,
193 "section_labels_fa": SECTION_LABELS_FA,
194 "contract": "Pilot workbook v0.1",
195 "disclaimer_fa": "خروجی این ابزار پیش‌نویس کاری برای بررسی است، نه صورت مالی رسمی.",
196 }
197
198
199 @router.post("/sessions")
200 async def create_session_from_upload(file: UploadFile = File(...)) -> dict:
201 filename = file.filename or "upload.xlsx"
202 if not filename.lower().endswith(".xlsx"):
203 raise HTTPException(422, detail={"message": "فقط فایل .xlsx پذیرفته می‌شود."})
204 data = await file.read()
205 if not data:
206 raise HTTPException(422, detail={"message": "فایل خالی است."})
207 if len(data) > MAX_UPLOAD_BYTES:
208 raise HTTPException(413, detail={"message": "حداکثر حجم مجاز ۲۵ مگابایت است."})
209 return _create_session(data, source="upload", filename=filename)
210
211
212 @router.post("/demo")
213 def create_demo_session() -> dict:
214 return _create_session(
215 build_demo_workbook(), source="demo", filename="aram-synthetic-demo.xlsx"
216 )
217
218
219 @router.get("/sessions/{session_id}")
220 def get_session(session_id: str) -> dict:
221 _get_session_or_404(session_id)
222 return _session_payload(session_id)
223
224
225 @router.delete("/sessions/{session_id}")
226 def delete_session(session_id: str) -> dict:
227 _get_session_or_404(session_id)
228 store.delete(session_id)
229 return {"deleted": session_id}
230
231
232 # ------------------------------------------------------------------ mappings
233 @router.put("/sessions/{session_id}/mappings/{account_code}")
234 def set_mapping(session_id: str, account_code: str, update: MappingUpdate) -> dict:
235 _get_session_or_404(session_id)
236 try:
237 store.set_mapping(
238 session_id, account_code,
239 statement=update.statement.strip(), section=update.section.strip(),
240 note_number=update.note_number.strip(), subnote_code=update.subnote_code.strip(),
241 approval_status=update.approval_status, reviewer=update.reviewer, actor=update.actor,
242 )
243 except (UnknownAccountError, UnknownTargetError, InvalidApprovalError) as exc:
244 raise _editing_http_error(exc) from exc
245 return _session_payload(session_id)
246
247
248 @router.delete("/sessions/{session_id}/mappings/{account_code}")
249 def clear_mapping(session_id: str, account_code: str, actor: str = Query(default="")) -> dict:
250 _get_session_or_404(session_id)
251 try:
252 store.clear_mapping(session_id, account_code, actor=actor)
253 except UnknownAccountError as exc:
254 raise _editing_http_error(exc) from exc
255 return _session_payload(session_id)
256
257
258 # ------------------------------------------------------------------ accounts
259 @router.post("/sessions/{session_id}/accounts")
260 def add_account(session_id: str, body: AccountCreate) -> dict:
261 _get_session_or_404(session_id)
262 try:
263 store.add_account(
264 session_id, full_code=body.full_code, name=body.name,
265 general_code=body.general_code, general_name=body.general_name,
266 opening=body.opening, debit=body.debit, credit=body.credit,
267 source_row=body.source_row, row_status=body.row_status,
268 subsidiary_code=body.subsidiary_code, subsidiary_name=body.subsidiary_name,
269 actor=body.actor,
270 )
271 except (EditingError, UnknownAccountError) as exc:
272 raise _editing_http_error(exc) from exc
273 return _session_payload(session_id)
274
275
276 @router.put("/sessions/{session_id}/accounts/{account_code}")
277 def update_account(session_id: str, account_code: str, body: AccountUpdate) -> dict:
278 _get_session_or_404(session_id)
279 try:
280 store.update_account(
281 session_id, account_code, name=body.name,
282 general_code=body.general_code, general_name=body.general_name,
283 opening=body.opening, debit=body.debit, credit=body.credit,
284 row_status=body.row_status, subsidiary_code=body.subsidiary_code,
285 subsidiary_name=body.subsidiary_name, actor=body.actor,
286 )
287 except (EditingError, UnknownAccountError) as exc:
288 raise _editing_http_error(exc) from exc
289 return _session_payload(session_id)
290
291
292 @router.post("/sessions/{session_id}/accounts/{account_code}/rename")
293 def rename_account(session_id: str, account_code: str, body: AccountRename) -> dict:
294 _get_session_or_404(session_id)
295 try:
296 store.rename_account(session_id, account_code, body.new_code, actor=body.actor)
297 except (EditingError, UnknownAccountError) as exc:
298 raise _editing_http_error(exc) from exc
299 return _session_payload(session_id)
300
301
302 @router.delete("/sessions/{session_id}/accounts/{account_code}")
303 def delete_account(session_id: str, account_code: str, actor: str = Query(default="")) -> dict:
304 _get_session_or_404(session_id)
305 try:
306 store.delete_account(session_id, account_code, actor=actor)
307 except UnknownAccountError as exc:
308 raise _editing_http_error(exc) from exc
309 return _session_payload(session_id)
310
311
312 # --------------------------------------------------------------------- notes
313 @router.post("/sessions/{session_id}/notes")
314 def add_note(session_id: str, body: NoteCreate) -> dict:
315 _get_session_or_404(session_id)
316 try:
317 note = make_note(
318 statement=body.statement, section=body.section, note_number=body.note_number,
319 note_title=body.note_title, subnote_code=body.subnote_code,
320 subnote_title=body.subnote_title,
321 )
322 store.add_note(session_id, note, actor=body.actor)
323 except EditingError as exc:
324 raise _editing_http_error(exc) from exc
325 return _session_payload(session_id)
326
327
328 @router.put("/sessions/{session_id}/notes")
329 def update_note(session_id: str, body: NoteUpdate) -> dict:
330 _get_session_or_404(session_id)
331 try:
332 key = (body.statement.strip(), body.section.strip(),
333 body.note_number.strip(), body.subnote_code.strip())
334 note = make_note(
335 statement=body.statement, section=body.section, note_number=body.note_number,
336 note_title=body.note_title, subnote_code=body.subnote_code,
337 subnote_title=body.subnote_title,
338 )
339 store.update_note(session_id, key, note, actor=body.actor)
340 except EditingError as exc:
341 raise _editing_http_error(exc) from exc
342 return _session_payload(session_id)
343
344
345 @router.delete("/sessions/{session_id}/notes")
346 def delete_note(
347 session_id: str, statement: str = Query(...), section: str = Query(...),
348 note_number: str = Query(...), subnote_code: str = Query(default=""),
349 actor: str = Query(default=""),
350 ) -> dict:
351 _get_session_or_404(session_id)
352 key = (statement.strip(), section.strip(), note_number.strip(), subnote_code.strip())
353 try:
354 store.delete_note(session_id, key, actor=actor)
355 except EditingError as exc:
356 raise _editing_http_error(exc) from exc
357 return _session_payload(session_id)
358
359
360 # ------------------------------------------------------------------- company
361 @router.put("/sessions/{session_id}/company")
362 def update_company(session_id: str, body: CompanyUpdate) -> dict:
363 _get_session_or_404(session_id)
364 try:
365 company = make_company(
366 code=body.code, name=body.name, fiscal_year=body.fiscal_year,
367 currency=body.currency, unit=body.unit, prepared_by=body.prepared_by,
368 status=body.status,
369 )
370 store.update_company(session_id, company, actor=body.actor)
371 except EditingError as exc:
372 raise _editing_http_error(exc) from exc
373 return _session_payload(session_id)
374
375
376 # ------------------------------------------------------------------- exports
377 @router.get("/sessions/{session_id}/export.xlsx")
378 def export_session(session_id: str) -> StreamingResponse:
379 session = _get_session_or_404(session_id)
380 _, working, trail = store.snapshot(session_id)
381 report = build_report(working, working.mappings)
382 data = export_report_workbook(working, working.mappings, report, trail, session.source)
383 safe_code = re.sub(r"[^A-Za-z0-9_-]", "", working.company.code) or "session"
384 filename = f"aram-pilot-{safe_code}-{working.company.fiscal_year}.xlsx"
385 return StreamingResponse(
386 BytesIO(data), media_type=XLSX_MEDIA_TYPE,
387 headers={"Content-Disposition": f'attachment; filename="{filename}"'},
388 )
389
390
391 @router.get("/sessions/{session_id}/workspace.xlsx")
392 def export_workspace(session_id: str) -> StreamingResponse:
393 _get_session_or_404(session_id)
394 _, working, _ = store.snapshot(session_id)
395 data = export_working_workbook(working)
396 safe_code = re.sub(r"[^A-Za-z0-9_-]", "", working.company.code) or "session"
397 filename = f"aram-workspace-{safe_code}-{working.company.fiscal_year}.xlsx"
398 return StreamingResponse(
399 BytesIO(data), media_type=XLSX_MEDIA_TYPE,
400 headers={"Content-Disposition": f'attachment; filename="{filename}"'},
401 )