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