@davoodmehraban89 / Aram-1 / commits / 91b050c
Fork 0

feat(pilot): working end-to-end Pilot Workbench (Excel in -> draft BS/IS out)

Atomic V1 vertical slice on top of the accepted audit-safe foundation: - pilot_engine: deterministic in-memory BS/IS engine with explicit sign policy, fail-closed exceptions (unmapped/conflict/unsupported/CF-EQ), exact Decimal totals, trial-balance + accounting-equation checks, and reviewable 7-sheet Excel export with source-row drill-down. - pilot_store: bounded thread-safe in-memory sessions with audit trail; Reviewed/Approved mappings require reviewer evidence (contract parity). - pilot_api: /api/v1/pilot endpoints (upload, synthetic demo, mapping edits, export); preflight rejections return exact sheet/row/field issues. - Persian RTL workbench UI at /pilot/ (no external dependencies), root redirects to it; replaces nothing, quarantined prototype untouched. - 25 new tests; full suite 92 passed; migration round-trip unaffected. No canonical data/, samples/, models, or migrations changed. Demo data is synthetic and labelled everywhere. Output is a working draft, never an official financial statement. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 07:16 UTC 91b050c1328897af0b1fda7d42de17a7513554f2
13 files changed +2520
backend/.gitignore
+1
@@ -1,6 +1,7 @@
1 .venv/
2 __pycache__/
3 .pytest_cache/
4 +*.egg-info/
5 *.py[cod]
6 *.db
7 *.sqlite
backend/README.md
+35
@@ -1,5 +1,40 @@
1 # Aram backend
2
3 +## Pilot Workbench (working V1 slice)
4 +
5 +A runnable, end-to-end pilot application lives at `/pilot/` (the root URL
6 +redirects there). It takes a Pilot workbook v0.1 `.xlsx`, runs the accepted
7 +read-only preflight, lets a reviewer resolve the mapping exception queue,
8 +and produces draft Balance Sheet and Income Statement output with full
9 +account-to-source-row drill-down, explicit checks, an audit trail, and a
10 +reviewable Excel export.
11 +
12 +```bash
13 +cd backend
14 +python -m pip install -e '.[test]'
15 +uvicorn aram_backend.main:app --host 0.0.0.0 --port 8000
16 +# open http://localhost:8000/pilot/
17 +```
18 +
19 +- `POST /api/v1/pilot/demo` starts a clearly-labelled **synthetic** demo with
20 + two unmapped suspense accounts so the full workflow can be exercised.
21 +- `POST /api/v1/pilot/sessions` (multipart `file`) uploads a real workbook.
22 +- `PUT/DELETE /api/v1/pilot/sessions/{id}/mappings/{account}` edit mappings;
23 + every change is recorded in the session audit trail. Reviewed/Approved
24 + statuses require a reviewer name, mirroring the workbook contract.
25 +- `GET /api/v1/pilot/sessions/{id}/export.xlsx` downloads the reviewable
26 + output (Info, Checks, BalanceSheet, IncomeStatement, Coverage, Exceptions,
27 + AuditTrail).
28 +
29 +Safety boundary: sessions are strictly in memory (bounded, thread-safe) and
30 +disappear on restart; the durable artifact is the exported Excel file. No
31 +canonical file, database row, or source value is read or modified. Closing
32 +balances are debit-positive; display signs come only from the explicit
33 +`SECTION_POLICY` in `pilot_engine.py` (BS: Assets +, Liabilities −, Equity −;
34 +IS: Revenue −, Expenses +). Unknown sections, conflicting mappings, unmapped
35 +accounts, and CF/EQ targets fail closed into the exception queue — nothing is
36 +guessed. Output is always a working draft, never an official statement.
37 +
38 ## Pilot workbook preflight
39
40 Gate 2A adds a strictly in-memory validator for the governed Pilot workbook.
backend/pyproject.toml
+1
@@ -14,6 +14,7 @@ dependencies = [
14 "sqlalchemy>=2.0,<3",
15 "uvicorn[standard]>=0.34,<1",
16 "openpyxl>=3.1,<4",
17 + "python-multipart>=0.0.18,<1",
18 ]
19
20 [project.optional-dependencies]
backend/src/aram_backend/main.py
+16
@@ -1,12 +1,28 @@
1 +from pathlib import Path
2 +
3 from fastapi import FastAPI
4 +from fastapi.responses import RedirectResponse
5 +from fastapi.staticfiles import StaticFiles
6
7 from aram_backend import __version__
8 from aram_backend.config import get_settings
9 from aram_backend.models import FiscalYearStatus, StatementType
10 +from aram_backend.pilot_api import router as pilot_router
11 from aram_backend.schemas import EntityDescriptor, EnumCatalog, HealthResponse, SchemaCatalog
12
13 settings = get_settings()
14 app = FastAPI(title=settings.app_name, version=__version__)
15 +app.include_router(pilot_router)
16 +app.mount(
17 + "/pilot",
18 + StaticFiles(directory=Path(__file__).parent / "static" / "pilot", html=True),
19 + name="pilot-workbench",
20 +)
21 +
22 +
23 +@app.get("/", include_in_schema=False)
24 +def root() -> RedirectResponse:
25 + return RedirectResponse(url="/pilot/")
26
27
28 @app.get("/api/v1/health", response_model=HealthResponse, tags=["system"])
backend/src/aram_backend/pilot_api.py new
+197
@@ -0,0 +1,197 @@
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_engine import (
14 + DEFERRED_STATEMENTS,
15 + RENDERED_STATEMENTS,
16 + SECTION_LABELS_FA,
17 + SECTION_POLICY,
18 + STATEMENT_LABELS_FA,
19 + PilotModelError,
20 + accounts_table,
21 + build_report,
22 + export_report_workbook,
23 + notes_table,
24 + parse_pilot_model,
25 +)
26 +from aram_backend.pilot_store import (
27 + InvalidApprovalError,
28 + UnknownAccountError,
29 + UnknownSessionError,
30 + UnknownTargetError,
31 + store,
32 +)
33 +
34 +router = APIRouter(prefix="/api/v1/pilot", tags=["pilot-workbench"])
35 +
36 +MAX_UPLOAD_BYTES = 25 * 1024 * 1024
37 +XLSX_MEDIA_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
38 +
39 +
40 +class MappingUpdate(BaseModel):
41 + statement: str = Field(min_length=1)
42 + section: str = Field(min_length=1)
43 + note_number: str = Field(min_length=1)
44 + subnote_code: str = ""
45 + approval_status: str = "Draft"
46 + reviewer: str = ""
47 + actor: str = ""
48 +
49 +
50 +def _issues_payload(exc: PilotModelError) -> list[dict]:
51 + return [
52 + {
53 + "severity": issue.severity,
54 + "code": issue.code,
55 + "sheet": issue.sheet,
56 + "row": issue.row,
57 + "field": issue.field,
58 + "message": issue.message,
59 + }
60 + for issue in exc.issues
61 + ]
62 +
63 +
64 +def _session_payload(session_id: str) -> dict:
65 + session, mappings, trail = store.snapshot(session_id)
66 + report = build_report(session.model, mappings)
67 + return {
68 + "session": {
69 + "id": session.id,
70 + "created_at": session.created_at,
71 + "source": session.source,
72 + "filename": session.filename,
73 + },
74 + "report": report,
75 + "accounts": accounts_table(session.model, mappings),
76 + "notes": notes_table(session.model),
77 + "audit_trail": trail,
78 + }
79 +
80 +
81 +def _create_session(data: bytes, source: str, filename: str) -> dict:
82 + try:
83 + model = parse_pilot_model(data)
84 + except PilotModelError as exc:
85 + raise HTTPException(
86 + status_code=422,
87 + detail={
88 + "message": "فایل با قرارداد پایلوت v0.1 سازگار نیست؛ خطاهای زیر را رفع کنید.",
89 + "issues": _issues_payload(exc),
90 + },
91 + ) from exc
92 + session = store.create(model, source=source, filename=filename)
93 + return _session_payload(session.id)
94 +
95 +
96 +@router.get("/meta")
97 +def pilot_meta() -> dict:
98 + return {
99 + "rendered_statements": list(RENDERED_STATEMENTS),
100 + "deferred_statements": list(DEFERRED_STATEMENTS),
101 + "statement_labels_fa": STATEMENT_LABELS_FA,
102 + "section_policy": SECTION_POLICY,
103 + "section_labels_fa": SECTION_LABELS_FA,
104 + "contract": "Pilot workbook v0.1",
105 + "disclaimer_fa": "خروجی این ابزار پیش‌نویس کاری برای بررسی است، نه صورت مالی رسمی.",
106 + }
107 +
108 +
109 +@router.post("/sessions")
110 +async def create_session_from_upload(file: UploadFile = File(...)) -> dict:
111 + filename = file.filename or "upload.xlsx"
112 + if not filename.lower().endswith(".xlsx"):
113 + raise HTTPException(422, detail={"message": "فقط فایل .xlsx پذیرفته می‌شود."})
114 + data = await file.read()
115 + if not data:
116 + raise HTTPException(422, detail={"message": "فایل خالی است."})
117 + if len(data) > MAX_UPLOAD_BYTES:
118 + raise HTTPException(413, detail={"message": "حداکثر حجم مجاز ۲۵ مگابایت است."})
119 + return _create_session(data, source="upload", filename=filename)
120 +
121 +
122 +@router.post("/demo")
123 +def create_demo_session() -> dict:
124 + return _create_session(
125 + build_demo_workbook(), source="demo", filename="aram-synthetic-demo.xlsx"
126 + )
127 +
128 +
129 +def _get_session_or_404(session_id: str):
130 + try:
131 + return store.get(session_id)
132 + except UnknownSessionError as exc:
133 + raise HTTPException(404, detail={"message": "جلسه یافت نشد؛ دوباره فایل را وارد کنید."}) from exc
134 +
135 +
136 +@router.get("/sessions/{session_id}")
137 +def get_session(session_id: str) -> dict:
138 + _get_session_or_404(session_id)
139 + return _session_payload(session_id)
140 +
141 +
142 +@router.put("/sessions/{session_id}/mappings/{account_code}")
143 +def set_mapping(session_id: str, account_code: str, update: MappingUpdate) -> dict:
144 + _get_session_or_404(session_id)
145 + try:
146 + session = store.set_mapping(
147 + session_id,
148 + account_code,
149 + statement=update.statement.strip(),
150 + section=update.section.strip(),
151 + note_number=update.note_number.strip(),
152 + subnote_code=update.subnote_code.strip(),
153 + approval_status=update.approval_status,
154 + reviewer=update.reviewer,
155 + actor=update.actor,
156 + )
157 + except UnknownAccountError as exc:
158 + raise HTTPException(404, detail={"message": "حساب در این جلسه وجود ندارد."}) from exc
159 + except (UnknownTargetError, InvalidApprovalError) as exc:
160 + raise HTTPException(422, detail={"message": str(exc)}) from exc
161 + return _session_payload(session.id)
162 +
163 +
164 +@router.delete("/sessions/{session_id}/mappings/{account_code}")
165 +def clear_mapping(
166 + session_id: str, account_code: str, actor: str = Query(default="")
167 +) -> dict:
168 + _get_session_or_404(session_id)
169 + try:
170 + session = store.clear_mapping(session_id, account_code, actor=actor)
171 + except UnknownAccountError as exc:
172 + raise HTTPException(404, detail={"message": "حساب در این جلسه وجود ندارد."}) from exc
173 + return _session_payload(session.id)
174 +
175 +
176 +@router.delete("/sessions/{session_id}")
177 +def delete_session(session_id: str) -> dict:
178 + _get_session_or_404(session_id)
179 + store.delete(session_id)
180 + return {"deleted": session_id}
181 +
182 +
183 +@router.get("/sessions/{session_id}/export.xlsx")
184 +def export_session(session_id: str) -> StreamingResponse:
185 + _get_session_or_404(session_id)
186 + session, mappings, trail = store.snapshot(session_id)
187 + report = build_report(session.model, mappings)
188 + data = export_report_workbook(
189 + session.model, mappings, report, trail, session.source
190 + )
191 + safe_code = re.sub(r"[^A-Za-z0-9_-]", "", session.model.company.code) or "session"
192 + filename = f"aram-pilot-{safe_code}-{session.model.company.fiscal_year}.xlsx"
193 + return StreamingResponse(
194 + BytesIO(data),
195 + media_type=XLSX_MEDIA_TYPE,
196 + headers={"Content-Disposition": f'attachment; filename="{filename}"'},
197 + )
backend/src/aram_backend/pilot_demo.py new
+161
@@ -0,0 +1,161 @@
1 +"""Synthetic demo workbook for the Pilot workbench.
2 +
3 +Every value here is fabricated for demonstration and is clearly labelled as
4 +such in the company name, the workbook itself, the API and the UI. It never
5 +touches canonical data and must never be used for real financial reporting.
6 +The trial balance is balanced; two suspense accounts are intentionally left
7 +unmapped so the exception-queue workflow can be exercised end to end.
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +from datetime import UTC, datetime
13 +from io import BytesIO
14 +
15 +from openpyxl import Workbook
16 +
17 +from aram_backend.pilot_workbook import SHEET_HEADERS
18 +
19 +DEMO_COMPANY_CODE = "DEMO"
20 +DEMO_COMPANY_NAME = "شرکت ساختگی دمو (دادهٔ کاملاً غیرواقعی)"
21 +DEMO_YEAR = 1404
22 +DEMO_REVIEWER = "بازبین دمو (ساختگی)"
23 +DEMO_REVIEW_DATE = "2026-12-03"
24 +
25 +# (full_code, name, general_code, general_name, subsidiary_code,
26 +# closing, debit, credit, statement, section, note_number, approval)
27 +_DEMO_ACCOUNTS = [
28 + ("1001", "نقد و بانک", "10", "دارایی‌های جاری", "01", 12_500_000_000, 7_500_000_000, 5_000_000_000, "BS", "Assets", "01", "Approved"),
29 + ("1002", "دریافتنی‌های تجاری", "10", "دارایی‌های جاری", "02", 8_300_000_000, 6_100_000_000, 4_300_000_000, "BS", "Assets", "02", "Approved"),
30 + ("1003", "موجودی کالا", "10", "دارایی‌های جاری", "03", 15_200_000_000, 9_400_000_000, 7_100_000_000, "BS", "Assets", "03", "Approved"),
31 + ("1004", "پیش‌پرداخت‌ها", "10", "دارایی‌های جاری", "04", 1_100_000_000, 800_000_000, 500_000_000, "BS", "Assets", "04", "Draft"),
32 + ("1101", "دارایی‌های ثابت مشهود", "11", "دارایی‌های غیرجاری", "01", 22_000_000_000, 4_000_000_000, 0, "BS", "Assets", "05", "Approved"),
33 + ("1102", "استهلاک انباشته", "11", "دارایی‌های غیرجاری", "02", -3_600_000_000, 0, 900_000_000, "BS", "Assets", "05", "Approved"),
34 + ("2001", "پرداختنی‌های تجاری", "20", "بدهی‌های جاری", "01", -6_400_000_000, 3_200_000_000, 4_100_000_000, "BS", "Liabilities", "06", "Approved"),
35 + ("2003", "ذخیره مالیات", "20", "بدهی‌های جاری", "03", -1_900_000_000, 0, 1_900_000_000, "BS", "Liabilities", "08", "Approved"),
36 + ("2101", "تسهیلات مالی", "21", "بدهی‌های غیرجاری", "01", -14_000_000_000, 2_000_000_000, 5_000_000_000, "BS", "Liabilities", "07", "Approved"),
37 + ("3001", "سرمایه", "30", "حقوق مالکانه", "01", -20_000_000_000, 0, 0, "BS", "Equity", "09", "Approved"),
38 + ("3002", "سود انباشته", "30", "حقوق مالکانه", "02", -13_000_000_000, 0, 0, "BS", "Equity", "10", "Approved"),
39 + ("4001", "فروش", "40", "درآمدها", "01", -18_700_000_000, 0, 18_700_000_000, "IS", "Revenue", "11", "Approved"),
40 + ("4002", "سایر درآمدها", "40", "درآمدها", "02", -400_000_000, 0, 400_000_000, "IS", "Revenue", "12", "Approved"),
41 + ("5001", "بهای تمام‌شده کالای فروش‌رفته", "50", "هزینه‌ها", "01", 9_800_000_000, 9_800_000_000, 0, "IS", "Expenses", "13", "Approved"),
42 + ("5002", "حقوق و دستمزد", "50", "هزینه‌ها", "02", 3_900_000_000, 3_900_000_000, 0, "IS", "Expenses", "14", "Approved"),
43 + ("5003", "اجاره و اداری", "50", "هزینه‌ها", "03", 1_250_000_000, 1_250_000_000, 0, "IS", "Expenses", "15", "Approved"),
44 + ("5004", "هزینه استهلاک", "50", "هزینه‌ها", "04", 900_000_000, 900_000_000, 0, "IS", "Expenses", "16", "Approved"),
45 + ("5005", "هزینه‌های مالی", "50", "هزینه‌ها", "05", 1_150_000_000, 1_150_000_000, 0, "IS", "Expenses", "17", "Approved"),
46 + ("5006", "مالیات بر درآمد", "50", "هزینه‌ها", "06", 1_900_000_000, 1_900_000_000, 0, "IS", "Expenses", "18", "Approved"),
47 + # Intentionally unmapped suspense pair: balanced, but incomplete coverage.
48 + ("9001", "حساب موقت — قلم شناسایی‌نشده بدهکار", "90", "حساب‌های موقت", "01", 500_000_000, 500_000_000, 0, None, None, None, None),
49 + ("9002", "حساب موقت — قلم شناسایی‌نشده بستانکار", "90", "حساب‌های موقت", "02", -500_000_000, 0, 500_000_000, None, None, None, None),
50 +]
51 +
52 +_DEMO_NOTES = [
53 + ("BS", "Assets", "01", "نقد و بانک"),
54 + ("BS", "Assets", "02", "دریافتنی‌های تجاری"),
55 + ("BS", "Assets", "03", "موجودی‌ها"),
56 + ("BS", "Assets", "04", "پیش‌پرداخت‌ها"),
57 + ("BS", "Assets", "05", "دارایی‌های ثابت مشهود"),
58 + ("BS", "Liabilities", "06", "پرداختنی‌های تجاری"),
59 + ("BS", "Liabilities", "07", "تسهیلات مالی"),
60 + ("BS", "Liabilities", "08", "ذخیره مالیات"),
61 + ("BS", "Equity", "09", "سرمایه"),
62 + ("BS", "Equity", "10", "سود انباشته"),
63 + ("IS", "Revenue", "11", "درآمد عملیاتی"),
64 + ("IS", "Revenue", "12", "سایر درآمدها"),
65 + ("IS", "Expenses", "13", "بهای تمام‌شده"),
66 + ("IS", "Expenses", "14", "حقوق و دستمزد"),
67 + ("IS", "Expenses", "15", "هزینه‌های اداری و تشکیلاتی"),
68 + ("IS", "Expenses", "16", "استهلاک"),
69 + ("IS", "Expenses", "17", "هزینه‌های مالی"),
70 + ("IS", "Expenses", "18", "مالیات بر درآمد"),
71 +]
72 +
73 +
74 +def _row(sheet: str, values: dict) -> tuple:
75 + return tuple(values.get(header) for header in SHEET_HEADERS[sheet])
76 +
77 +
78 +def build_demo_workbook() -> bytes:
79 + """Build the synthetic, balanced demo workbook fully in memory."""
80 + workbook = Workbook()
81 + workbook.remove(workbook.active)
82 + workbook.properties.creator = "Aram Pilot Workbench (synthetic demo)"
83 + workbook.properties.title = "SYNTHETIC DEMO — NOT REAL FINANCIAL DATA"
84 + fixed = datetime(2026, 12, 3, tzinfo=UTC)
85 + workbook.properties.created = fixed
86 + workbook.properties.modified = fixed
87 + for name, headers in SHEET_HEADERS.items():
88 + workbook.create_sheet(name).append(headers)
89 +
90 + company = {
91 + "company_code": DEMO_COMPANY_CODE,
92 + "company_name": DEMO_COMPANY_NAME,
93 + "fiscal_year": DEMO_YEAR,
94 + "currency": "IRR",
95 + "unit": "ریال (ساختگی)",
96 + "prepared_by": "Aram Demo",
97 + "status": "Draft",
98 + }
99 + workbook["Company"].append(_row("Company", company))
100 +
101 + mapping_index = 0
102 + for (code, name, general, general_name, subsidiary, closing, debit, credit,
103 + statement, section, note_number, approval) in _DEMO_ACCOUNTS:
104 + opening = closing - debit + credit
105 + source_row = 100 + int(code)
106 + workbook["Accounts"].append(_row("Accounts", {
107 + "company_code": DEMO_COMPANY_CODE,
108 + "fiscal_year": DEMO_YEAR,
109 + "general_code": general,
110 + "general_name": general_name,
111 + "subsidiary_code": subsidiary,
112 + "subsidiary_name": name,
113 + "account_full_code": code,
114 + "account_name": name,
115 + "opening": opening,
116 + "debit": debit,
117 + "credit": credit,
118 + "closing": closing,
119 + "source_row": source_row,
120 + "row_status": "Reviewed",
121 + "closing_delta": 0,
122 + }))
123 + if statement is None:
124 + continue
125 + mapping_index += 1
126 + reviewed = approval in {"Reviewed", "Approved"}
127 + workbook["Mapping"].append(_row("Mapping", {
128 + "mapping_id": f"DM{mapping_index:03d}",
129 + "company_code": DEMO_COMPANY_CODE,
130 + "fiscal_year": DEMO_YEAR,
131 + "account_full_code": code,
132 + "account_level": "Subsidiary",
133 + "general_code": general,
134 + "subsidiary_code": subsidiary,
135 + "target_statement": statement,
136 + "statement_section": section,
137 + "note_number": note_number,
138 + "mapping_version": 1,
139 + "approval_status": approval,
140 + "reviewer": DEMO_REVIEWER if reviewed else None,
141 + "review_date": DEMO_REVIEW_DATE if reviewed else None,
142 + "source": "synthetic-demo",
143 + "validation_status": "Valid" if approval == "Approved" else "Pending",
144 + }))
145 +
146 + for statement, section, note_number, title in _DEMO_NOTES:
147 + workbook["Notes"].append(_row("Notes", {
148 + "company_code": DEMO_COMPANY_CODE,
149 + "fiscal_year": DEMO_YEAR,
150 + "statement": statement,
151 + "statement_section": section,
152 + "note_number": note_number,
153 + "note_title": title,
154 + }))
155 +
156 + workbook["Guide_FA"].append(("هشدار", "همهٔ ارقام این فایل ساختگی و غیرواقعی هستند."))
157 + workbook["Lists"].append(("demo", "SYNTHETIC"))
158 +
159 + stream = BytesIO()
160 + workbook.save(stream)
161 + return stream.getvalue()
backend/src/aram_backend/pilot_engine.py new
+592
@@ -0,0 +1,592 @@
1 +"""Deterministic, in-memory Pilot statement engine (V1 workbench slice).
2 +
3 +Scope and safety boundary
4 +-------------------------
5 +- Input is a Pilot workbook v0.1 that has passed ``preflight_pilot_workbook``.
6 +- Everything is computed in memory. No source bytes, parsed rows, or reports
7 + are persisted, and no financial value is ever guessed or plugged.
8 +- Closing balances are debit-positive (``opening + debit - credit = closing``
9 + is enforced by preflight). Display signs come from the explicit
10 + ``SECTION_POLICY`` below; unknown sections fail closed as exceptions.
11 +- Only BS and IS are rendered in this slice. Mappings targeting CF/EQ are
12 + accepted by the contract but reported as deferred, never silently rendered.
13 +- Output is always a working draft for review, never an official statement.
14 +"""
15 +
16 +from __future__ import annotations
17 +
18 +import hashlib
19 +from dataclasses import dataclass
20 +from datetime import UTC, datetime
21 +from decimal import Decimal
22 +from io import BytesIO
23 +from typing import Any
24 +
25 +from openpyxl import Workbook, load_workbook
26 +from openpyxl.styles import Alignment, Font, PatternFill
27 +
28 +from aram_backend.pilot_workbook import (
29 + SHEET_HEADERS,
30 + PilotIssue,
31 + preflight_pilot_workbook,
32 +)
33 +
34 +ENGINE_VERSION = "1.0.0"
35 +
36 +# Explicit sign policy: display = sign * closing (closing is debit-positive).
37 +SECTION_POLICY: dict[str, dict[str, int]] = {
38 + "BS": {"Assets": 1, "Liabilities": -1, "Equity": -1},
39 + "IS": {"Revenue": -1, "Expenses": 1},
40 +}
41 +RENDERED_STATEMENTS = ("BS", "IS")
42 +DEFERRED_STATEMENTS = ("CF", "EQ")
43 +STATEMENT_LABELS_FA = {
44 + "BS": "ترازنامه",
45 + "IS": "صورت سود و زیان",
46 + "CF": "صورت جریان‌های نقدی",
47 + "EQ": "صورت تغییرات در حقوق مالکانه",
48 +}
49 +SECTION_LABELS_FA = {
50 + "Assets": "دارایی‌ها",
51 + "Liabilities": "بدهی‌ها",
52 + "Equity": "حقوق مالکانه",
53 + "Revenue": "درآمدها",
54 + "Expenses": "هزینه‌ها",
55 +}
56 +
57 +_ZERO = Decimal("0")
58 +
59 +
60 +class PilotModelError(ValueError):
61 + """Raised when a workbook cannot be represented as a Pilot model."""
62 +
63 + def __init__(self, issues: list[PilotIssue]) -> None:
64 + self.issues = tuple(issues)
65 + super().__init__("; ".join(f"{i.code}@{i.sheet}:{i.row}" for i in issues))
66 +
67 +
68 +@dataclass(frozen=True)
69 +class PilotCompany:
70 + code: str
71 + name: str
72 + fiscal_year: int
73 + currency: str
74 + unit: str
75 + prepared_by: str
76 + status: str
77 +
78 +
79 +@dataclass(frozen=True)
80 +class PilotAccount:
81 + full_code: str
82 + name: str
83 + general_code: str
84 + general_name: str
85 + opening: Decimal
86 + debit: Decimal
87 + credit: Decimal
88 + closing: Decimal
89 + source_row: int
90 + row_status: str
91 +
92 +
93 +@dataclass(frozen=True)
94 +class NoteTarget:
95 + statement: str
96 + section: str
97 + note_number: str
98 + note_title: str
99 + subnote_code: str
100 + subnote_title: str
101 +
102 + @property
103 + def key(self) -> tuple[str, str, str, str]:
104 + return (self.statement, self.section, self.note_number, self.subnote_code)
105 +
106 +
107 +@dataclass(frozen=True)
108 +class MappingEntry:
109 + account_code: str
110 + statement: str
111 + section: str
112 + note_number: str
113 + subnote_code: str
114 + approval_status: str
115 + reviewer: str
116 + source: str
117 + mapping_id: str
118 +
119 + @property
120 + def target_key(self) -> tuple[str, str, str, str]:
121 + return (self.statement, self.section, self.note_number, self.subnote_code)
122 +
123 +
124 +@dataclass(frozen=True)
125 +class PilotModel:
126 + company: PilotCompany
127 + accounts: dict[str, PilotAccount]
128 + notes: dict[tuple[str, str, str, str], NoteTarget]
129 + mappings: dict[str, MappingEntry]
130 + conflicts: dict[str, tuple[MappingEntry, ...]]
131 + source_sha256: str
132 +
133 +
134 +def _rows(sheet: Any, headers: tuple[str, ...]) -> list[dict[str, Any]]:
135 + result = []
136 + for values in sheet.iter_rows(min_row=2, values_only=True):
137 + row = dict(zip(headers, values))
138 + if any(v is not None and not (isinstance(v, str) and not v.strip()) for v in row.values()):
139 + result.append(row)
140 + return result
141 +
142 +
143 +def _text(value: Any) -> str:
144 + return value.strip() if isinstance(value, str) else ""
145 +
146 +
147 +def _decimal(value: Any) -> Decimal:
148 + return Decimal(str(value).strip())
149 +
150 +
151 +def parse_pilot_model(workbook_bytes: bytes) -> PilotModel:
152 + """Parse a preflight-valid workbook into a typed, immutable model."""
153 + preflight = preflight_pilot_workbook(workbook_bytes)
154 + if not preflight.valid:
155 + raise PilotModelError(list(preflight.issues))
156 +
157 + workbook = load_workbook(BytesIO(workbook_bytes), read_only=True, data_only=True)
158 + parsed = {
159 + name: _rows(workbook[name], headers) for name, headers in SHEET_HEADERS.items()
160 + }
161 + workbook.close()
162 +
163 + company_rows = parsed["Company"]
164 + if len(company_rows) != 1:
165 + raise PilotModelError([PilotIssue(
166 + "ERROR", "WORKBENCH_SINGLE_COMPANY_REQUIRED", "Company", 0, "__sheet__",
167 + "The workbench renders exactly one company/fiscal year per workbook; "
168 + f"found {len(company_rows)} company rows.",
169 + )])
170 + crow = company_rows[0]
171 + company = PilotCompany(
172 + code=_text(crow["company_code"]),
173 + name=_text(crow["company_name"]),
174 + fiscal_year=int(crow["fiscal_year"]),
175 + currency=_text(crow["currency"]),
176 + unit=_text(crow["unit"]),
177 + prepared_by=_text(crow["prepared_by"]),
178 + status=_text(crow["status"]),
179 + )
180 +
181 + accounts: dict[str, PilotAccount] = {}
182 + for row in parsed["Accounts"]:
183 + account = PilotAccount(
184 + full_code=_text(row["account_full_code"]),
185 + name=_text(row["account_name"]),
186 + general_code=_text(row["general_code"]),
187 + general_name=_text(row["general_name"]),
188 + opening=_decimal(row["opening"]),
189 + debit=_decimal(row["debit"]),
190 + credit=_decimal(row["credit"]),
191 + closing=_decimal(row["closing"]),
192 + source_row=int(row["source_row"]),
193 + row_status=_text(row["row_status"]),
194 + )
195 + accounts[account.full_code] = account
196 + accounts = dict(sorted(accounts.items()))
197 +
198 + notes: dict[tuple[str, str, str, str], NoteTarget] = {}
199 + for row in parsed["Notes"]:
200 + note = NoteTarget(
201 + statement=_text(row["statement"]),
202 + section=_text(row["statement_section"]),
203 + note_number=_text(row["note_number"]),
204 + note_title=_text(row["note_title"]),
205 + subnote_code=_text(row["subnote_code"]),
206 + subnote_title=_text(row["subnote_title"]),
207 + )
208 + notes[note.key] = note
209 +
210 + mappings: dict[str, MappingEntry] = {}
211 + conflicts: dict[str, tuple[MappingEntry, ...]] = {}
212 + for row in parsed["Mapping"]:
213 + entry = MappingEntry(
214 + account_code=_text(row["account_full_code"]),
215 + statement=_text(row["target_statement"]),
216 + section=_text(row["statement_section"]),
217 + note_number=_text(row["note_number"]),
218 + subnote_code=_text(row["subnote_code"]),
219 + approval_status=_text(row["approval_status"]),
220 + reviewer=_text(row["reviewer"]),
221 + source=_text(row["source"]),
222 + mapping_id=_text(row["mapping_id"]),
223 + )
224 + existing = mappings.get(entry.account_code)
225 + if entry.account_code in conflicts:
226 + conflicts[entry.account_code] += (entry,)
227 + elif existing is None:
228 + mappings[entry.account_code] = entry
229 + elif existing.target_key != entry.target_key:
230 + conflicts[entry.account_code] = (existing, entry)
231 + del mappings[entry.account_code]
232 + # Identical duplicate targets are deduplicated deterministically.
233 +
234 + return PilotModel(
235 + company=company,
236 + accounts=accounts,
237 + notes=notes,
238 + mappings=mappings,
239 + conflicts=conflicts,
240 + source_sha256=hashlib.sha256(workbook_bytes).hexdigest(),
241 + )
242 +
243 +
244 +def _amount(value: Decimal) -> str:
245 + """Exact decimal as string; JSON never loses precision through floats."""
246 + return format(value, "f")
247 +
248 +
249 +def _account_json(account: PilotAccount, mapping: MappingEntry | None, sign: int | None) -> dict:
250 + payload = {
251 + "code": account.full_code,
252 + "name": account.name,
253 + "closing": _amount(account.closing),
254 + "source_row": account.source_row,
255 + "row_status": account.row_status,
256 + }
257 + if sign is not None:
258 + payload["display"] = _amount(sign * account.closing)
259 + if mapping is not None:
260 + payload["approval_status"] = mapping.approval_status
261 + return payload
262 +
263 +
264 +def build_report(model: PilotModel, mappings: dict[str, MappingEntry]) -> dict:
265 + """Compute coverage, exceptions, checks and BS/IS drafts deterministically."""
266 + exceptions: list[dict] = []
267 + buckets: dict[tuple[str, str, str, str], list[tuple[PilotAccount, MappingEntry]]] = {}
268 + mapped_count = 0
269 +
270 + for code, account in model.accounts.items():
271 + resolved = mappings.get(code)
272 + if code in model.conflicts and not (resolved and resolved.source == "workbench"):
273 + exceptions.append({
274 + "code": "MAPPING_CONFLICT",
275 + "account_code": code,
276 + "account_name": account.name,
277 + "closing": _amount(account.closing),
278 + "source_row": account.source_row,
279 + "details": "چند نگاشت با مقصدهای متفاوت برای این حساب وجود دارد؛ "
280 + "تا رفع تعارض، حساب در صورت‌ها منظور نمی‌شود.",
281 + })
282 + continue
283 + mapping = mappings.get(code)
284 + if mapping is None:
285 + exceptions.append({
286 + "code": "UNMAPPED_ACCOUNT",
287 + "account_code": code,
288 + "account_name": account.name,
289 + "closing": _amount(account.closing),
290 + "source_row": account.source_row,
291 + "details": "حساب نگاشت نشده است؛ مقصد آن را در زبانهٔ نگاشت تعیین کنید.",
292 + })
293 + continue
294 + mapped_count += 1
295 + if mapping.statement in DEFERRED_STATEMENTS:
296 + exceptions.append({
297 + "code": "DEFERRED_STATEMENT",
298 + "account_code": code,
299 + "account_name": account.name,
300 + "closing": _amount(account.closing),
301 + "source_row": account.source_row,
302 + "details": f"مقصد {mapping.statement} در این نسخه رندر نمی‌شود؛ "
303 + "موتور جریان نقدی/تغییرات حقوق مالکانه در گام بعدی است.",
304 + })
305 + continue
306 + policy = SECTION_POLICY.get(mapping.statement, {})
307 + if mapping.section not in policy:
308 + exceptions.append({
309 + "code": "UNSUPPORTED_SECTION",
310 + "account_code": code,
311 + "account_name": account.name,
312 + "closing": _amount(account.closing),
313 + "source_row": account.source_row,
314 + "details": f"بخش «{mapping.section}» در سیاست علامت صریح تعریف نشده است؛ "
315 + "حدس زدن ممنوع است.",
316 + })
317 + continue
318 + buckets.setdefault(mapping.target_key, []).append((account, mapping))
319 +
320 + statements: dict[str, dict] = {}
321 + section_totals: dict[tuple[str, str], Decimal] = {}
322 + for statement in RENDERED_STATEMENTS:
323 + sections = []
324 + for section, sign in SECTION_POLICY[statement].items():
325 + lines = []
326 + for key in sorted(k for k in buckets if k[0] == statement and k[1] == section):
327 + members = buckets[key]
328 + note = model.notes.get(key)
329 + line_total = sum((sign * a.closing for a, _ in members), _ZERO)
330 + lines.append({
331 + "note_number": key[2],
332 + "note_title": note.note_title if note else "",
333 + "subnote_code": key[3],
334 + "subnote_title": note.subnote_title if note else "",
335 + "total": _amount(line_total),
336 + "accounts": [
337 + _account_json(a, m, sign)
338 + for a, m in sorted(members, key=lambda item: item[0].full_code)
339 + ],
340 + })
341 + total = sum((Decimal(line["total"]) for line in lines), _ZERO)
342 + section_totals[(statement, section)] = total
343 + sections.append({
344 + "name": section,
345 + "label_fa": SECTION_LABELS_FA.get(section, section),
346 + "total": _amount(total),
347 + "lines": lines,
348 + })
349 + statements[statement] = {"label_fa": STATEMENT_LABELS_FA[statement], "sections": sections}
350 +
351 + assets = section_totals[("BS", "Assets")]
352 + liabilities = section_totals[("BS", "Liabilities")]
353 + equity = section_totals[("BS", "Equity")]
354 + revenue = section_totals[("IS", "Revenue")]
355 + expenses = section_totals[("IS", "Expenses")]
356 + profit = revenue - expenses
357 + trial_balance_sum = sum((a.closing for a in model.accounts.values()), _ZERO)
358 + equation_residual = assets - liabilities - equity - profit
359 + all_approved = bool(mappings) and all(
360 + m.approval_status == "Approved" for m in mappings.values()
361 + )
362 +
363 + checks = [
364 + {
365 + "code": "NON_EMPTY_ACCOUNTS",
366 + "name_fa": "وجود حساب‌های منبع",
367 + "passed": bool(model.accounts),
368 + "amount": None,
369 + "details": f"{len(model.accounts)} حساب در فایل ورودی ثبت شده است.",
370 + },
371 + {
372 + "code": "TRIAL_BALANCE_CLOSED",
373 + "name_fa": "تراز بودن مانده‌های دفتر کل",
374 + "passed": trial_balance_sum == _ZERO,
375 + "amount": _amount(trial_balance_sum),
376 + "details": "جمع مانده‌های پایان دوره (بدهکار مثبت) باید صفر باشد.",
377 + },
378 + {
379 + "code": "FULL_COVERAGE",
380 + "name_fa": "پوشش کامل نگاشت",
381 + "passed": not exceptions,
382 + "amount": None,
383 + "details": f"{len(exceptions)} استثنا باقی مانده است." if exceptions
384 + else "همهٔ حساب‌ها نگاشت معتبر دارند.",
385 + },
386 + {
387 + "code": "ACCOUNTING_EQUATION",
388 + "name_fa": "معادلهٔ حسابداری",
389 + "passed": equation_residual == _ZERO,
390 + "amount": _amount(equation_residual),
391 + "details": "دارایی‌ها − بدهی‌ها − حقوق مالکانه − سود دوره باید صفر باشد.",
392 + },
393 + {
394 + "code": "MAPPINGS_APPROVED",
395 + "name_fa": "تأیید همهٔ نگاشت‌ها",
396 + "passed": all_approved,
397 + "amount": None,
398 + "details": "همهٔ نگاشت‌های مؤثر وضعیت Approved دارند." if all_approved
399 + else "برخی نگاشت‌ها هنوز Approved نیستند؛ خروجی پیش‌نویس می‌ماند.",
400 + },
401 + ]
402 + complete = all(c["passed"] for c in checks if c["code"] != "MAPPINGS_APPROVED")
403 + label = (
404 + "COMPLETE_APPROVED" if complete and all_approved
405 + else "COMPLETE_DRAFT" if complete
406 + else "INCOMPLETE"
407 + )
408 +
409 + return {
410 + "engine_version": ENGINE_VERSION,
411 + "company": {
412 + "code": model.company.code,
413 + "name": model.company.name,
414 + "fiscal_year": model.company.fiscal_year,
415 + "currency": model.company.currency,
416 + "unit": model.company.unit,
417 + "prepared_by": model.company.prepared_by,
418 + "status": model.company.status,
419 + },
420 + "source_sha256": model.source_sha256,
421 + "status": {"label": label, "complete": complete, "all_mappings_approved": all_approved},
422 + "coverage": {
423 + "total_accounts": len(model.accounts),
424 + "mapped_accounts": mapped_count,
425 + "exception_count": len(exceptions),
426 + },
427 + "totals": {
428 + "assets": _amount(assets),
429 + "liabilities": _amount(liabilities),
430 + "equity": _amount(equity),
431 + "liabilities_and_equity": _amount(liabilities + equity),
432 + "revenue": _amount(revenue),
433 + "expenses": _amount(expenses),
434 + "profit": _amount(profit),
435 + },
436 + "checks": checks,
437 + "statements": statements,
438 + "exceptions": exceptions,
439 + }
440 +
441 +
442 +def accounts_table(model: PilotModel, mappings: dict[str, MappingEntry]) -> list[dict]:
443 + rows = []
444 + for code, account in model.accounts.items():
445 + mapping = mappings.get(code)
446 + rows.append({
447 + **_account_json(account, mapping, None),
448 + "general_code": account.general_code,
449 + "general_name": account.general_name,
450 + "conflict": code in model.conflicts
451 + and not (mapping and mapping.source == "workbench"),
452 + "mapping": None if mapping is None else {
453 + "statement": mapping.statement,
454 + "section": mapping.section,
455 + "note_number": mapping.note_number,
456 + "subnote_code": mapping.subnote_code,
457 + "approval_status": mapping.approval_status,
458 + "reviewer": mapping.reviewer,
459 + "source": mapping.source,
460 + "mapping_id": mapping.mapping_id,
461 + },
462 + })
463 + return rows
464 +
465 +
466 +def notes_table(model: PilotModel) -> list[dict]:
467 + return [
468 + {
469 + "statement": note.statement,
470 + "section": note.section,
471 + "note_number": note.note_number,
472 + "note_title": note.note_title,
473 + "subnote_code": note.subnote_code,
474 + "subnote_title": note.subnote_title,
475 + }
476 + for note in sorted(model.notes.values(), key=lambda n: n.key)
477 + ]
478 +
479 +
480 +def export_report_workbook(
481 + model: PilotModel,
482 + mappings: dict[str, MappingEntry],
483 + report: dict,
484 + audit_trail: list[dict],
485 + source_label: str,
486 +) -> bytes:
487 + """Render the reviewable Excel output. Values are derived, never invented."""
488 + workbook = Workbook()
489 + workbook.remove(workbook.active)
490 + header_font = Font(bold=True, color="FFFFFF")
491 + header_fill = PatternFill("solid", fgColor="1F4E78")
492 + title_font = Font(bold=True, size=13)
493 +
494 + def sheet(name: str, headers: tuple[str, ...]) -> Any:
495 + ws = workbook.create_sheet(name)
496 + ws.append(headers)
497 + for cell in ws[1]:
498 + cell.font = header_font
499 + cell.fill = header_fill
500 + ws.freeze_panes = "A2"
501 + ws.sheet_view.rightToLeft = True
502 + for column in range(1, len(headers) + 1):
503 + ws.column_dimensions[ws.cell(1, column).column_letter].width = 22
504 + return ws
505 +
506 + info = sheet("Info", ("field", "value"))
507 + company = report["company"]
508 + for field_name, value in (
509 + ("company_code", company["code"]),
510 + ("company_name", company["name"]),
511 + ("fiscal_year", company["fiscal_year"]),
512 + ("unit", company["unit"]),
513 + ("source", source_label),
514 + ("source_sha256", report["source_sha256"]),
515 + ("engine_version", ENGINE_VERSION),
516 + ("generated_at_utc", datetime.now(UTC).isoformat(timespec="seconds")),
517 + ("status", report["status"]["label"]),
518 + ("disclaimer", "خروجی پیش‌نویس کاری برای بررسی است؛ صورت مالی رسمی نیست. "
519 + "هیچ مبلغی حدس زده یا جایگزین نشده است."),
520 + ):
521 + info.append((field_name, value))
522 + if source_label == "demo":
523 + info.append(("synthetic_data", "TRUE — داده‌های دمو کاملاً ساختگی و غیرواقعی هستند."))
524 + info.column_dimensions["B"].width = 80
525 +
526 + checks = sheet("Checks", ("check_code", "name_fa", "passed", "amount", "details"))
527 + for check in report["checks"]:
528 + checks.append((
529 + check["code"], check["name_fa"], "PASS" if check["passed"] else "FAIL",
530 + float(check["amount"]) if check["amount"] is not None else None,
531 + check["details"],
532 + ))
533 +
534 + for statement in RENDERED_STATEMENTS:
535 + data = report["statements"][statement]
536 + ws = sheet(
537 + "BalanceSheet" if statement == "BS" else "IncomeStatement",
538 + ("level", "section", "note", "title", "amount", "account_code", "source_row"),
539 + )
540 + ws.append(("title", "", "", f"{data['label_fa']} — {company['name']} — {company['fiscal_year']}", None, "", None))
541 + ws.cell(ws.max_row, 4).font = title_font
542 + for section in data["sections"]:
543 + ws.append(("section", section["name"], "", section["label_fa"], float(section["total"]), "", None))
544 + ws.cell(ws.max_row, 5).font = Font(bold=True)
545 + for line in section["lines"]:
546 + title = line["note_title"]
547 + if line["subnote_code"]:
548 + title += f" / {line['subnote_code']} {line['subnote_title']}".rstrip()
549 + ws.append(("note", section["name"], line["note_number"], title, float(line["total"]), "", None))
550 + for account in line["accounts"]:
551 + ws.append((
552 + "account", section["name"], line["note_number"], account["name"],
553 + float(account["display"]), account["code"], account["source_row"],
554 + ))
555 + ws.cell(ws.max_row, 4).alignment = Alignment(indent=1)
556 + if statement == "IS":
557 + ws.append(("total", "", "", "سود (زیان) دوره", float(report["totals"]["profit"]), "", None))
558 + ws.cell(ws.max_row, 5).font = Font(bold=True)
559 + ws.column_dimensions["D"].width = 48
560 +
561 + coverage = sheet("Coverage", (
562 + "account_code", "account_name", "closing", "source_row", "statement",
563 + "section", "note_number", "subnote_code", "approval_status", "mapping_source",
564 + ))
565 + for row in accounts_table(model, mappings):
566 + mapping = row["mapping"] or {}
567 + coverage.append((
568 + row["code"], row["name"], float(row["closing"]), row["source_row"],
569 + mapping.get("statement"), mapping.get("section"), mapping.get("note_number"),
570 + mapping.get("subnote_code"), mapping.get("approval_status"), mapping.get("source"),
571 + ))
572 +
573 + exceptions = sheet("Exceptions", ("code", "account_code", "account_name", "closing", "source_row", "details"))
574 + for item in report["exceptions"]:
575 + exceptions.append((
576 + item["code"], item["account_code"], item["account_name"],
577 + float(item["closing"]), item["source_row"], item["details"],
578 + ))
579 + exceptions.column_dimensions["F"].width = 70
580 +
581 + trail = sheet("AuditTrail", ("at_utc", "actor", "account_code", "action", "before", "after"))
582 + for entry in audit_trail:
583 + trail.append((
584 + entry["at"], entry["actor"], entry["account_code"], entry["action"],
585 + entry["before"], entry["after"],
586 + ))
587 + trail.column_dimensions["E"].width = 46
588 + trail.column_dimensions["F"].width = 46
589 +
590 + stream = BytesIO()
591 + workbook.save(stream)
592 + return stream.getvalue()
backend/src/aram_backend/pilot_store.py new
+175
@@ -0,0 +1,175 @@
1 +"""Bounded, thread-safe in-memory session store for the Pilot workbench.
2 +
3 +Sessions hold only the typed model and effective mappings — never the source
4 +workbook bytes. Everything disappears on restart by design; the durable,
5 +reviewable artifact is the exported Excel report.
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +import threading
11 +import uuid
12 +from dataclasses import dataclass, field
13 +from datetime import UTC, datetime
14 +
15 +from aram_backend.pilot_engine import MappingEntry, PilotModel
16 +
17 +MAX_SESSIONS = 32
18 +
19 +
20 +def _now() -> str:
21 + return datetime.now(UTC).isoformat(timespec="seconds")
22 +
23 +
24 +def _mapping_summary(entry: MappingEntry | None) -> str:
25 + if entry is None:
26 + return "(بدون نگاشت)"
27 + return (
28 + f"{entry.statement}/{entry.section}/{entry.note_number}"
29 + + (f"/{entry.subnote_code}" if entry.subnote_code else "")
30 + + f" [{entry.approval_status}]"
31 + )
32 +
33 +
34 +@dataclass
35 +class PilotSession:
36 + id: str
37 + model: PilotModel
38 + mappings: dict[str, MappingEntry]
39 + source: str
40 + filename: str
41 + created_at: str = field(default_factory=_now)
42 + audit_trail: list[dict] = field(default_factory=list)
43 +
44 +
45 +class UnknownSessionError(KeyError):
46 + pass
47 +
48 +
49 +class UnknownAccountError(KeyError):
50 + pass
51 +
52 +
53 +class UnknownTargetError(ValueError):
54 + pass
55 +
56 +
57 +class InvalidApprovalError(ValueError):
58 + pass
59 +
60 +
61 +class PilotSessionStore:
62 + def __init__(self, max_sessions: int = MAX_SESSIONS) -> None:
63 + self._sessions: dict[str, PilotSession] = {}
64 + self._order: list[str] = []
65 + self._lock = threading.RLock()
66 + self._max = max_sessions
67 +
68 + def create(self, model: PilotModel, source: str, filename: str) -> PilotSession:
69 + session = PilotSession(
70 + id=uuid.uuid4().hex,
71 + model=model,
72 + mappings=dict(model.mappings),
73 + source=source,
74 + filename=filename,
75 + )
76 + with self._lock:
77 + self._sessions[session.id] = session
78 + self._order.append(session.id)
79 + while len(self._order) > self._max:
80 + oldest = self._order.pop(0)
81 + self._sessions.pop(oldest, None)
82 + return session
83 +
84 + def get(self, session_id: str) -> PilotSession:
85 + with self._lock:
86 + session = self._sessions.get(session_id)
87 + if session is None:
88 + raise UnknownSessionError(session_id)
89 + return session
90 +
91 + def snapshot(self, session_id: str) -> tuple[PilotSession, dict, list]:
92 + """Consistent copy of mappings and trail for lock-free report building."""
93 + session = self.get(session_id)
94 + with self._lock:
95 + return session, dict(session.mappings), list(session.audit_trail)
96 +
97 + def delete(self, session_id: str) -> None:
98 + with self._lock:
99 + if session_id not in self._sessions:
100 + raise UnknownSessionError(session_id)
101 + del self._sessions[session_id]
102 + self._order.remove(session_id)
103 +
104 + def set_mapping(
105 + self,
106 + session_id: str,
107 + account_code: str,
108 + *,
109 + statement: str,
110 + section: str,
111 + note_number: str,
112 + subnote_code: str = "",
113 + approval_status: str = "Draft",
114 + reviewer: str = "",
115 + actor: str = "workbench-user",
116 + ) -> PilotSession:
117 + session = self.get(session_id)
118 + with self._lock:
119 + if account_code not in session.model.accounts:
120 + raise UnknownAccountError(account_code)
121 + key = (statement, section, note_number, subnote_code)
122 + if key not in session.model.notes:
123 + raise UnknownTargetError(
124 + "Target statement/section/note/sub-note does not exist in Notes."
125 + )
126 + if approval_status not in {"Draft", "Reviewed", "Approved"}:
127 + raise InvalidApprovalError("Allowed approval statuses: Draft, Reviewed, Approved.")
128 + if approval_status in {"Reviewed", "Approved"} and not reviewer.strip():
129 + raise InvalidApprovalError(
130 + "Reviewed/Approved mappings require a reviewer name as evidence."
131 + )
132 + before = session.mappings.get(account_code)
133 + entry = MappingEntry(
134 + account_code=account_code,
135 + statement=statement,
136 + section=section,
137 + note_number=note_number,
138 + subnote_code=subnote_code,
139 + approval_status=approval_status,
140 + reviewer=reviewer.strip(),
141 + source="workbench",
142 + mapping_id=f"WB-{uuid.uuid4().hex[:10]}",
143 + )
144 + session.mappings[account_code] = entry
145 + session.audit_trail.append({
146 + "at": _now(),
147 + "actor": actor.strip() or "workbench-user",
148 + "account_code": account_code,
149 + "action": "set_mapping",
150 + "before": _mapping_summary(before),
151 + "after": _mapping_summary(entry)
152 + + (f" بازبین: {entry.reviewer}" if entry.reviewer else ""),
153 + })
154 + return session
155 +
156 + def clear_mapping(
157 + self, session_id: str, account_code: str, actor: str = "workbench-user"
158 + ) -> PilotSession:
159 + session = self.get(session_id)
160 + with self._lock:
161 + if account_code not in session.model.accounts:
162 + raise UnknownAccountError(account_code)
163 + before = session.mappings.pop(account_code, None)
164 + session.audit_trail.append({
165 + "at": _now(),
166 + "actor": actor.strip() or "workbench-user",
167 + "account_code": account_code,
168 + "action": "clear_mapping",
169 + "before": _mapping_summary(before),
170 + "after": "(بدون نگاشت)",
171 + })
172 + return session
173 +
174 +
175 +store = PilotSessionStore()
backend/src/aram_backend/static/pilot/app.js new
+518
@@ -0,0 +1,518 @@
1 +/* Aram Pilot Workbench — vanilla JS, RTL, no external dependencies. */
2 +"use strict";
3 +
4 +const API = "/api/v1/pilot";
5 +const S = {
6 + meta: null,
7 + data: null,
8 + tab: "dashboard",
9 + filter: "all",
10 + search: "",
11 + editing: null,
12 + expanded: new Set(),
13 +};
14 +
15 +const $ = (sel) => document.querySelector(sel);
16 +const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => (
17 + { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]
18 +));
19 +
20 +function fmt(v) {
21 + if (v === null || v === undefined || v === "") return "—";
22 + let s = String(v);
23 + const neg = s.startsWith("-");
24 + if (neg) s = s.slice(1);
25 + let [i, d] = s.split(".");
26 + i = i.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
27 + if (d) d = d.replace(/0+$/, "");
28 + return (neg ? "−" : "") + i + (d ? "." + d : "");
29 +}
30 +const isNeg = (v) => String(v ?? "").startsWith("-");
31 +const numCell = (v) => `<td class="num${isNeg(v) ? " neg" : ""}">${fmt(v)}</td>`;
32 +
33 +const STATUS_FA = {
34 + INCOMPLETE: "ناقص — پیش‌نویس کاری",
35 + COMPLETE_DRAFT: "کامل — نگاشت‌ها در انتظار تأیید",
36 + COMPLETE_APPROVED: "کامل — همهٔ نگاشت‌ها تأییدشده",
37 +};
38 +
39 +let toastTimer = null;
40 +function toast(msg, kind = "") {
41 + const el = $("#toast");
42 + el.textContent = msg;
43 + el.className = `toast ${kind}`;
44 + clearTimeout(toastTimer);
45 + toastTimer = setTimeout(() => el.classList.add("hidden"), 4200);
46 +}
47 +
48 +async function api(path, opts = {}) {
49 + const res = await fetch(API + path, opts);
50 + let body = null;
51 + try { body = await res.json(); } catch { /* non-JSON */ }
52 + if (!res.ok) {
53 + const detail = body?.detail;
54 + const err = new Error(
55 + typeof detail === "string" ? detail : detail?.message || `خطای سرور (${res.status})`
56 + );
57 + err.issues = detail?.issues;
58 + throw err;
59 + }
60 + return body;
61 +}
62 +
63 +const actor = () => ($("#actor-input").value || "").trim();
64 +
65 +/* ---------------- landing ---------------- */
66 +
67 +function renderPolicy() {
68 + const m = S.meta;
69 + const grid = $("#policy-grid");
70 + const items = [];
71 + for (const st of m.rendered_statements) {
72 + for (const [sec, sign] of Object.entries(m.section_policy[st])) {
73 + items.push(`<div class="policy-item"><b>${esc(m.statement_labels_fa[st])}</b> / ${esc(m.section_labels_fa[sec] || sec)} <span class="mono">${sign > 0 ? "+" : "−"}</span></div>`);
74 + }
75 + }
76 + for (const st of m.deferred_statements) {
77 + items.push(`<div class="policy-item muted">${esc(m.statement_labels_fa[st])} — در نسخهٔ بعدی</div>`);
78 + }
79 + grid.innerHTML = items.join("");
80 +}
81 +
82 +function showIssues(err) {
83 + const panel = $("#issues-panel");
84 + if (!err.issues?.length) { toast(err.message, "error"); return; }
85 + $("#issues-message").textContent = err.message;
86 + $("#issues-table tbody").innerHTML = err.issues.map((i) =>
87 + `<tr><td>${esc(i.sheet)}</td><td class="num">${i.row}</td><td class="mono">${esc(i.field)}</td><td class="mono">${esc(i.code)}</td><td>${esc(i.message)}</td></tr>`
88 + ).join("");
89 + panel.classList.remove("hidden");
90 + panel.scrollIntoView({ behavior: "smooth", block: "start" });
91 +}
92 +
93 +async function uploadFile(file) {
94 + $("#issues-panel").classList.add("hidden");
95 + $("#upload-progress").classList.remove("hidden");
96 + $("#upload-btn").disabled = true;
97 + try {
98 + const form = new FormData();
99 + form.append("file", file);
100 + const payload = await api("/sessions", { method: "POST", body: form });
101 + enterWorkspace(payload);
102 + toast("فایل پذیرفته شد؛ پیش‌بررسی بدون خطا بود.", "success");
103 + } catch (err) { showIssues(err); }
104 + finally {
105 + $("#upload-progress").classList.add("hidden");
106 + $("#upload-btn").disabled = false;
107 + $("#file-input").value = "";
108 + }
109 +}
110 +
111 +async function startDemo() {
112 + $("#issues-panel").classList.add("hidden");
113 + $("#demo-btn").disabled = true;
114 + try {
115 + const payload = await api("/demo", { method: "POST" });
116 + enterWorkspace(payload);
117 + toast("دموی ساختگی آماده شد؛ دو حساب نگاشت‌نشده منتظر شما هستند.", "success");
118 + } catch (err) { toast(err.message, "error"); }
119 + finally { $("#demo-btn").disabled = false; }
120 +}
121 +
122 +/* ---------------- workspace ---------------- */
123 +
124 +function enterWorkspace(payload) {
125 + S.data = payload;
126 + S.tab = "dashboard";
127 + S.filter = "all";
128 + S.search = "";
129 + S.editing = null;
130 + S.expanded = new Set();
131 + $("#view-landing").classList.add("hidden");
132 + $("#view-workspace").classList.remove("hidden");
133 + $("#new-session-btn").classList.remove("hidden");
134 + $("#engine-version").textContent = payload.report.engine_version;
135 + renderAll();
136 + window.scrollTo({ top: 0 });
137 +}
138 +
139 +function leaveWorkspace() {
140 + S.data = null;
141 + $("#view-workspace").classList.add("hidden");
142 + $("#view-landing").classList.remove("hidden");
143 + $("#new-session-btn").classList.add("hidden");
144 +}
145 +
146 +function renderAll() {
147 + const { report, session } = S.data;
148 + const c = report.company;
149 + const sourceChip = session.source === "demo"
150 + ? `<span class="chip demo">دموی ساختگی — غیرواقعی</span>`
151 + : `<span class="chip mono">${esc(session.filename)}</span>`;
152 + $("#session-info").innerHTML = `
153 + <div class="session-meta">
154 + <span class="company-name">${esc(c.name)}</span>
155 + <span class="chip">کد ${esc(c.code)}</span>
156 + <span class="chip">سال مالی ${c.fiscal_year}</span>
157 + <span class="chip">${esc(c.unit || "واحد نامشخص")}</span>
158 + ${sourceChip}
159 + </div>`;
160 + $("#status-chip").innerHTML =
161 + `<span class="status-chip status-${report.status.label}">${STATUS_FA[report.status.label]}</span>`;
162 +
163 + const badge = $("#mapping-badge");
164 + const ex = report.coverage.exception_count;
165 + badge.textContent = ex;
166 + badge.className = `badge${ex === 0 ? " zero" : ""}`;
167 +
168 + document.querySelectorAll(".tab").forEach((t) =>
169 + t.classList.toggle("active", t.dataset.tab === S.tab));
170 + document.querySelectorAll(".tab-panel").forEach((p) => p.classList.add("hidden"));
171 + const panel = $(`#tab-${S.tab}`);
172 + panel.classList.remove("hidden");
173 + ({ dashboard: renderDashboard, mapping: renderMapping, BS: renderBS, IS: renderIS, audit: renderAudit })[S.tab]();
174 +}
175 +
176 +/* ---------------- dashboard ---------------- */
177 +
178 +function renderDashboard() {
179 + const { report } = S.data;
180 + const t = report.totals;
181 + const cov = report.coverage;
182 + const pct = cov.total_accounts ? Math.round((cov.mapped_accounts / cov.total_accounts) * 100) : 0;
183 + const totalCard = (label, value, hl = false) =>
184 + `<div class="total-card${hl ? " highlight" : ""}"><div class="label">${label}</div><div class="value${isNeg(value) ? " neg" : ""}">${fmt(value)}</div></div>`;
185 +
186 + const exceptions = report.exceptions.length ? `
187 + <div class="card" style="margin-top:16px">
188 + <h3 style="margin-top:0">صف استثنا (${report.exceptions.length})</h3>
189 + <div class="table-wrap"><table>
190 + <thead><tr><th>حساب</th><th>نام</th><th class="num">مانده پایان دوره</th><th>سطر منبع</th><th>علت</th><th></th></tr></thead>
191 + <tbody>${report.exceptions.map((e) => `
192 + <tr>
193 + <td class="mono">${esc(e.account_code)}</td><td>${esc(e.account_name)}</td>
194 + ${numCell(e.closing)}<td class="num">${e.source_row}</td>
195 + <td><span class="approval-chip approval-none">${esc(e.code)}</span> ${esc(e.details)}</td>
196 + <td><button class="btn small" data-action="goto-mapping" data-code="${esc(e.account_code)}">رسیدگی</button></td>
197 + </tr>`).join("")}
198 + </tbody></table></div>
199 + </div>` : `<div class="card" style="margin-top:16px"><b style="color:var(--green)">✓ هیچ استثنایی باقی نمانده است.</b></div>`;
200 +
201 + $("#tab-dashboard").innerHTML = `
202 + <div class="grid checks-grid">
203 + ${report.checks.map((ch) => `
204 + <div class="check-card ${ch.passed ? "pass" : "fail"}">
205 + <div class="check-name">${esc(ch.name_fa)}</div>
206 + <div class="check-state">${ch.passed ? "✓ قبول" : "✗ رد"}</div>
207 + ${ch.amount !== null ? `<div class="check-amount">${fmt(ch.amount)}</div>` : ""}
208 + <div class="check-details">${esc(ch.details)}</div>
209 + </div>`).join("")}
210 + </div>
211 + <div class="card">
212 + <b>پوشش نگاشت:</b> ${cov.mapped_accounts} از ${cov.total_accounts} حساب (${pct}٪)
213 + <div class="coverage-bar-wrap" style="margin-top:8px"><div class="coverage-bar" style="width:${pct}%"></div></div>
214 + </div>
215 + <div class="grid totals-grid">
216 + ${totalCard("جمع دارایی‌ها", t.assets)}
217 + ${totalCard("جمع بدهی‌ها", t.liabilities)}
218 + ${totalCard("حقوق مالکانه", t.equity)}
219 + ${totalCard("درآمدها", t.revenue)}
220 + ${totalCard("هزینه‌ها", t.expenses)}
221 + ${totalCard("سود (زیان) دوره", t.profit, true)}
222 + </div>
223 + ${exceptions}`;
224 +}
225 +
226 +/* ---------------- mapping ---------------- */
227 +
228 +function filteredAccounts() {
229 + const q = S.search.trim();
230 + return S.data.accounts.filter((a) => {
231 + if (S.filter === "unmapped" && a.mapping) return false;
232 + if (S.filter === "unapproved" && a.mapping?.approval_status === "Approved") return false;
233 + if (S.filter === "conflict" && !a.conflict) return false;
234 + if (q && !(a.code.includes(q) || a.name.includes(q))) return false;
235 + return true;
236 + });
237 +}
238 +
239 +function mappingSummary(a) {
240 + if (a.conflict) return `<span class="approval-chip approval-none">تعارض نگاشت</span>`;
241 + if (!a.mapping) return `<span class="approval-chip approval-none">بدون نگاشت</span>`;
242 + const m = a.mapping;
243 + const note = S.data.notes.find((n) =>
244 + n.statement === m.statement && n.section === m.section &&
245 + n.note_number === m.note_number && n.subnote_code === m.subnote_code);
246 + const label = note ? `${note.note_number} — ${note.note_title}` : m.note_number;
247 + return `<span class="mono">${esc(m.statement)}/${esc(m.section)}</span> · ${esc(label)}
248 + <span class="approval-chip approval-${esc(m.approval_status)}">${esc(m.approval_status)}</span>`;
249 +}
250 +
251 +function editorHtml(a) {
252 + const m = a.mapping || {};
253 + return `<tr class="editor-row"><td colspan="6">
254 + <div class="editor-grid">
255 + <label>صورت مالی<select id="ed-statement"></select></label>
256 + <label>بخش<select id="ed-section"></select></label>
257 + <label>یادداشت / زیریادداشت<select id="ed-note" style="min-width:230px"></select></label>
258 + <label>وضعیت تأیید<select id="ed-approval">
259 + <option value="Draft">Draft</option><option value="Reviewed">Reviewed</option><option value="Approved">Approved</option>
260 + </select></label>
261 + <label>نام بازبین<input id="ed-reviewer" type="text" value="${esc(m.reviewer || actor())}" placeholder="برای Reviewed/Approved الزامی"></label>
262 + <div class="editor-actions">
263 + <button class="btn primary small" data-action="save-mapping" data-code="${esc(a.code)}">ثبت نگاشت</button>
264 + ${a.mapping ? `<button class="btn danger small" data-action="clear-mapping" data-code="${esc(a.code)}">حذف نگاشت</button>` : ""}
265 + <button class="btn ghost small" data-action="cancel-edit">انصراف</button>
266 + </div>
267 + </div>
268 + </td></tr>`;
269 +}
270 +
271 +function fillEditorSelects(a) {
272 + const m = a.mapping || {};
273 + const stSel = $("#ed-statement"), secSel = $("#ed-section"), noteSel = $("#ed-note");
274 + const statements = [...S.meta.rendered_statements, ...S.meta.deferred_statements];
275 + stSel.innerHTML = statements.map((st) =>
276 + `<option value="${st}"${st === (m.statement || "BS") ? " selected" : ""}>${esc(S.meta.statement_labels_fa[st])} (${st})</option>`).join("");
277 + const fillSections = () => {
278 + const st = stSel.value;
279 + const sections = S.meta.section_policy[st]
280 + ? Object.keys(S.meta.section_policy[st])
281 + : [...new Set(S.data.notes.filter((n) => n.statement === st).map((n) => n.section))];
282 + secSel.innerHTML = sections.map((sec) =>
283 + `<option value="${esc(sec)}"${sec === m.section ? " selected" : ""}>${esc(S.meta.section_labels_fa[sec] || sec)}</option>`).join("");
284 + fillNotes();
285 + };
286 + const fillNotes = () => {
287 + const options = S.data.notes.filter((n) => n.statement === stSel.value && n.section === secSel.value);
288 + noteSel.innerHTML = options.length
289 + ? options.map((n) => {
290 + const val = `${n.note_number}|${n.subnote_code}`;
291 + const sel = n.note_number === m.note_number && n.subnote_code === (m.subnote_code || "") ? " selected" : "";
292 + const label = `${n.note_number} — ${n.note_title}${n.subnote_code ? ` / ${n.subnote_code} ${n.subnote_title}` : ""}`;
293 + return `<option value="${esc(val)}"${sel}>${esc(label)}</option>`;
294 + }).join("")
295 + : `<option value="">— یادداشتی برای این بخش تعریف نشده —</option>`;
296 + };
297 + stSel.onchange = fillSections;
298 + secSel.onchange = fillNotes;
299 + fillSections();
300 + $("#ed-approval").value = m.approval_status || "Draft";
301 +}
302 +
303 +function updateMappingRows() {
304 + const tbody = $("#mapping-tbody");
305 + if (!tbody) return;
306 + const rows = [];
307 + for (const a of filteredAccounts()) {
308 + rows.push(`<tr>
309 + <td class="mono">${esc(a.code)}</td>
310 + <td>${esc(a.name)}</td>
311 + ${numCell(a.closing)}
312 + <td class="num">${a.source_row}</td>
313 + <td>${mappingSummary(a)}</td>
314 + <td><button class="btn small" data-action="edit-mapping" data-code="${esc(a.code)}">${a.mapping ? "ویرایش" : "تعیین مقصد"}</button></td>
315 + </tr>`);
316 + if (S.editing === a.code) rows.push(editorHtml(a));
317 + }
318 + tbody.innerHTML = rows.join("") || `<tr><td colspan="6" class="muted">حسابی با این فیلتر یافت نشد.</td></tr>`;
319 + if (S.editing) {
320 + const a = S.data.accounts.find((x) => x.code === S.editing);
321 + if (a) fillEditorSelects(a);
322 + }
323 +}
324 +
325 +function renderMapping() {
326 + $("#tab-mapping").innerHTML = `
327 + <div class="table-toolbar">
328 + <input type="search" id="map-search" placeholder="جستجوی کد یا نام حساب…" value="${esc(S.search)}">
329 + <select id="map-filter">
330 + <option value="all">همهٔ حساب‌ها</option>
331 + <option value="unmapped">بدون نگاشت</option>
332 + <option value="unapproved">تأییدنشده</option>
333 + <option value="conflict">دارای تعارض</option>
334 + </select>
335 + <span class="muted">${S.data.accounts.length} حساب · مانده‌ها بدهکار-مثبت · هر تغییر در ردّ ممیزی ثبت می‌شود</span>
336 + </div>
337 + <div class="table-wrap"><table>
338 + <thead><tr><th>کد حساب</th><th>نام حساب</th><th class="num">مانده پایان دوره</th><th>سطر منبع</th><th>مقصد نگاشت</th><th></th></tr></thead>
339 + <tbody id="mapping-tbody"></tbody>
340 + </table></div>`;
341 + $("#map-filter").value = S.filter;
342 + $("#map-search").oninput = (e) => { S.search = e.target.value; updateMappingRows(); };
343 + $("#map-filter").onchange = (e) => { S.filter = e.target.value; updateMappingRows(); };
344 + updateMappingRows();
345 +}
346 +
347 +async function saveMapping(code) {
348 + const noteVal = $("#ed-note").value;
349 + if (!noteVal) { toast("برای این بخش یادداشتی تعریف نشده است؛ مقصد دیگری انتخاب کنید.", "error"); return; }
350 + const [noteNumber, subnote] = noteVal.split("|");
351 + const approval = $("#ed-approval").value;
352 + const reviewer = $("#ed-reviewer").value.trim();
353 + if (approval !== "Draft" && !reviewer) {
354 + toast("برای وضعیت Reviewed/Approved نام بازبین الزامی است.", "error");
355 + return;
356 + }
357 + try {
358 + const payload = await api(`/sessions/${S.data.session.id}/mappings/${encodeURIComponent(code)}`, {
359 + method: "PUT",
360 + headers: { "Content-Type": "application/json" },
361 + body: JSON.stringify({
362 + statement: $("#ed-statement").value,
363 + section: $("#ed-section").value,
364 + note_number: noteNumber,
365 + subnote_code: subnote || "",
366 + approval_status: approval,
367 + reviewer,
368 + actor: actor(),
369 + }),
370 + });
371 + S.data = payload;
372 + S.editing = null;
373 + renderAll();
374 + toast(`نگاشت حساب ${code} ثبت شد.`, "success");
375 + } catch (err) { toast(err.message, "error"); }
376 +}
377 +
378 +async function clearMapping(code) {
379 + try {
380 + const payload = await api(
381 + `/sessions/${S.data.session.id}/mappings/${encodeURIComponent(code)}?actor=${encodeURIComponent(actor())}`,
382 + { method: "DELETE" });
383 + S.data = payload;
384 + S.editing = null;
385 + renderAll();
386 + toast(`نگاشت حساب ${code} حذف شد.`, "success");
387 + } catch (err) { toast(err.message, "error"); }
388 +}
389 +
390 +/* ---------------- statements ---------------- */
391 +
392 +function renderStatement(code) {
393 + const { report } = S.data;
394 + const st = report.statements[code];
395 + const c = report.company;
396 + const sections = st.sections.map((sec) => `
397 + <div class="statement-section">
398 + <div class="section-head"><span>${esc(sec.label_fa)}</span><span class="note-total${isNeg(sec.total) ? " neg" : ""}">${fmt(sec.total)}</span></div>
399 + ${sec.lines.map((line) => {
400 + const key = `${code}|${sec.name}|${line.note_number}|${line.subnote_code}`;
401 + const open = S.expanded.has(key);
402 + const title = `${line.note_title}${line.subnote_code ? ` / ${line.subnote_code} ${line.subnote_title}` : ""}`;
403 + return `
404 + <div class="note-line" data-action="toggle-line" data-key="${esc(key)}">
405 + <span class="note-title"><span class="note-number">${esc(line.note_number)}</span>${esc(title)}
406 + <span class="muted">${open ? "▾" : "◂"} ${line.accounts.length} حساب</span></span>
407 + <span class="note-total${isNeg(line.total) ? " neg" : ""}">${fmt(line.total)}</span>
408 + </div>
409 + ${open ? `<div class="drill"><div class="table-wrap"><table>
410 + <thead><tr><th>کد</th><th>حساب</th><th class="num">مانده دفتر (بدهکار+)</th><th class="num">مبلغ نمایشی</th><th>سطر منبع</th><th>تأیید نگاشت</th></tr></thead>
411 + <tbody>${line.accounts.map((a) => `<tr>
412 + <td class="mono">${esc(a.code)}</td><td>${esc(a.name)}</td>
413 + ${numCell(a.closing)}${numCell(a.display)}<td class="num">${a.source_row}</td>
414 + <td><span class="approval-chip approval-${esc(a.approval_status)}">${esc(a.approval_status)}</span></td>
415 + </tr>`).join("")}</tbody></table></div></div>` : ""}`;
416 + }).join("") || `<div class="note-line muted">رقمی در این بخش منظور نشده است.</div>`}
417 + </div>`).join("");
418 +
419 + const grand = code === "BS"
420 + ? `<div class="statement-total"><span>جمع دارایی‌ها</span><span class="note-total">${fmt(report.totals.assets)}</span></div>
421 + <div class="statement-total"><span>جمع بدهی‌ها و حقوق مالکانه</span><span class="note-total">${fmt(report.totals.liabilities_and_equity)}</span></div>`
422 + : `<div class="statement-total"><span>سود (زیان) دوره</span><span class="note-total${isNeg(report.totals.profit) ? " neg" : ""}">${fmt(report.totals.profit)}</span></div>`;
423 +
424 + $(`#tab-${code}`).innerHTML = `
425 + <div class="statement-tools">
426 + <button class="btn small ghost" data-action="print">🖨 چاپ</button>
427 + </div>
428 + <div class="statement-paper">
429 + <div class="statement-head">
430 + <h2>${esc(st.label_fa)}</h2>
431 + <div class="sub">${esc(c.name)} — سال مالی ${c.fiscal_year} — به ${esc(c.unit || "واحد نامشخص")}</div>
432 + <span class="draft-watermark">${STATUS_FA[report.status.label]} · پیش‌نویس کاری، نه صورت مالی رسمی</span>
433 + </div>
434 + ${sections}
435 + ${grand}
436 + ${code === "BS" ? `<p class="muted">سود دوره (${fmt(report.totals.profit)}) در حقوق مالکانه از طریق معادلهٔ حسابداری کنترل می‌شود؛ کنترل کامل در داشبورد نمایش داده شده است.</p>` : ""}
437 + </div>`;
438 +}
439 +const renderBS = () => renderStatement("BS");
440 +const renderIS = () => renderStatement("IS");
441 +
442 +/* ---------------- audit & export ---------------- */
443 +
444 +function renderAudit() {
445 + const { report, session, audit_trail: trail } = S.data;
446 + const prov = (k, v, mono = false) =>
447 + `<div class="prov-item"><div class="k">${k}</div><div class="v${mono ? " mono" : ""}">${esc(v)}</div></div>`;
448 + $("#tab-audit").innerHTML = `
449 + <div class="card" style="margin-bottom:16px">
450 + <h3 style="margin-top:0">شناسنامه و شواهد</h3>
451 + <div class="provenance-grid">
452 + ${prov("SHA-256 فایل ورودی", report.source_sha256, true)}
453 + ${prov("زمان ایجاد جلسه (UTC)", session.created_at, true)}
454 + ${prov("منبع", session.source === "demo" ? "دموی ساختگی (غیرواقعی)" : `فایل ${session.filename}`)}
455 + ${prov("نسخهٔ موتور", report.engine_version, true)}
456 + </div>
457 + <div style="display:flex;gap:10px;flex-wrap:wrap">
458 + <a class="btn primary" href="${API}/sessions/${session.id}/export.xlsx" download>⬇ دانلود خروجی اکسل (صورت‌ها + پوشش + کنترل‌ها + ردّ ممیزی)</a>
459 + <button class="btn danger" data-action="delete-session">حذف جلسه از حافظه</button>
460 + </div>
461 + <p class="muted">جلسه‌ها فقط در حافظهٔ سرور هستند و با راه‌اندازی مجدد پاک می‌شوند؛ سند ماندگار، همین خروجی اکسل است.</p>
462 + </div>
463 + <div class="card">
464 + <h3 style="margin-top:0">ردّ ممیزی تغییرات نگاشت (${trail.length})</h3>
465 + ${trail.length ? `<div class="table-wrap"><table>
466 + <thead><tr><th>زمان (UTC)</th><th>کاربر</th><th>حساب</th><th>اقدام</th><th>قبل</th><th>بعد</th></tr></thead>
467 + <tbody>${trail.map((e) => `<tr>
468 + <td class="mono">${esc(e.at)}</td><td>${esc(e.actor)}</td><td class="mono">${esc(e.account_code)}</td>
469 + <td>${esc(e.action)}</td><td class="mono">${esc(e.before)}</td><td class="mono">${esc(e.after)}</td>
470 + </tr>`).join("")}</tbody></table></div>`
471 + : `<p class="muted">هنوز تغییری در نگاشت‌ها ثبت نشده است.</p>`}
472 + </div>`;
473 +}
474 +
475 +async function deleteSession() {
476 + if (!confirm("جلسه از حافظهٔ سرور حذف شود؟ خروجی اکسلِ دانلودشده باقی می‌ماند.")) return;
477 + try {
478 + await api(`/sessions/${S.data.session.id}`, { method: "DELETE" });
479 + leaveWorkspace();
480 + toast("جلسه حذف شد.", "success");
481 + } catch (err) { toast(err.message, "error"); }
482 +}
483 +
484 +/* ---------------- events ---------------- */
485 +
486 +document.addEventListener("click", (e) => {
487 + const el = e.target.closest("[data-action]");
488 + if (!el) return;
489 + const { action, code, key } = el.dataset;
490 + if (action === "edit-mapping") { S.editing = code; updateMappingRows(); }
491 + else if (action === "cancel-edit") { S.editing = null; updateMappingRows(); }
492 + else if (action === "save-mapping") saveMapping(code);
493 + else if (action === "clear-mapping") clearMapping(code);
494 + else if (action === "goto-mapping") { S.tab = "mapping"; S.filter = "all"; S.search = code; S.editing = code; renderAll(); }
495 + else if (action === "toggle-line") { S.expanded.has(key) ? S.expanded.delete(key) : S.expanded.add(key); renderStatement(S.tab); }
496 + else if (action === "print") window.print();
497 + else if (action === "delete-session") deleteSession();
498 +});
499 +
500 +document.addEventListener("DOMContentLoaded", async () => {
501 + $("#actor-input").value = localStorage.getItem("aram-actor") || "";
502 + $("#actor-input").addEventListener("input", (e) => localStorage.setItem("aram-actor", e.target.value));
503 + $("#upload-btn").addEventListener("click", () => $("#file-input").click());
504 + $("#file-input").addEventListener("change", (e) => { if (e.target.files[0]) uploadFile(e.target.files[0]); });
505 + $("#demo-btn").addEventListener("click", startDemo);
506 + $("#new-session-btn").addEventListener("click", leaveWorkspace);
507 + $("#tabs").addEventListener("click", (e) => {
508 + const tab = e.target.closest(".tab");
509 + if (!tab || !S.data) return;
510 + S.tab = tab.dataset.tab;
511 + S.editing = null;
512 + renderAll();
513 + });
514 + try {
515 + S.meta = await api("/meta");
516 + renderPolicy();
517 + } catch (err) { toast("بارگذاری اطلاعات موتور ناموفق بود: " + err.message, "error"); }
518 +});
backend/src/aram_backend/static/pilot/index.html new
+116
@@ -0,0 +1,116 @@
1 +<!doctype html>
2 +<html lang="fa" dir="rtl">
3 +<head>
4 + <meta charset="utf-8">
5 + <meta name="viewport" content="width=device-width, initial-scale=1">
6 + <title>آرام — میز کار پایلوت</title>
7 + <link rel="stylesheet" href="styles.css">
8 + <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='80' font-size='80'>📊</text></svg>">
9 +</head>
10 +<body>
11 + <header class="topbar">
12 + <div class="brand">
13 + <span class="brand-mark">آ</span>
14 + <div>
15 + <h1>آرام — میز کار پایلوت</h1>
16 + <p class="tagline">از اکسل منبع تا پیش‌نویس صورت‌های مالی، با ردیابی کامل</p>
17 + </div>
18 + </div>
19 + <div class="topbar-actions">
20 + <label class="actor-field" title="نام شما در ردّ ممیزی ثبت می‌شود">
21 + <span>نام کاربر:</span>
22 + <input id="actor-input" type="text" placeholder="نام بازبین" autocomplete="name">
23 + </label>
24 + <button id="new-session-btn" class="btn ghost hidden">جلسهٔ جدید</button>
25 + </div>
26 + </header>
27 +
28 + <main id="main">
29 + <!-- Landing -->
30 + <section id="view-landing">
31 + <div class="hero">
32 + <h2>صورت‌های مالیِ قابل‌ردیابی، از فایل اکسل شما</h2>
33 + <p>
34 + فایل پایلوت (قرارداد v0.1) را وارد کنید؛ پیش‌بررسی کامل اجرا می‌شود،
35 + نگاشت حساب‌ها را بررسی و اصلاح می‌کنید، و ترازنامه و صورت سود و زیان
36 + با کنترل‌های تراز و معادلهٔ حسابداری ساخته می‌شود — هر رقم تا سطر منبع قابل ردیابی است.
37 + </p>
38 + <p class="safety-note">
39 + هیچ مبلغی حدس زده نمی‌شود · دادهٔ منبع تغییر نمی‌کند · خروجی «پیش‌نویس کاری» است، نه صورت مالی رسمی
40 + </p>
41 + </div>
42 +
43 + <div class="action-cards">
44 + <div class="card action-card">
45 + <div class="action-icon">📥</div>
46 + <h3>ورود فایل پایلوت</h3>
47 + <p>فایل <span class="mono">.xlsx</span> مطابق قالب تأییدشدهٔ v0.1 (حداکثر ۲۵ مگابایت)</p>
48 + <input id="file-input" type="file" accept=".xlsx" class="hidden">
49 + <button id="upload-btn" class="btn primary">انتخاب و بررسی فایل</button>
50 + </div>
51 + <div class="card action-card">
52 + <div class="action-icon">🧪</div>
53 + <h3>دموی ساختگی</h3>
54 + <p>دادهٔ کاملاً غیرواقعی و تراز، با دو حساب نگاشت‌نشده برای تجربهٔ گردش کار کامل</p>
55 + <button id="demo-btn" class="btn accent">اجرای دمو</button>
56 + </div>
57 + </div>
58 +
59 + <div id="upload-progress" class="card progress-card hidden">
60 + <span class="spinner"></span> در حال پیش‌بررسی فایل…
61 + </div>
62 +
63 + <div id="issues-panel" class="card issues-card hidden">
64 + <h3>❌ فایل رد شد — خطاهای پیش‌بررسی</h3>
65 + <p id="issues-message"></p>
66 + <div class="table-wrap">
67 + <table id="issues-table">
68 + <thead><tr><th>برگه</th><th>سطر</th><th>فیلد</th><th>کد خطا</th><th>شرح</th></tr></thead>
69 + <tbody></tbody>
70 + </table>
71 + </div>
72 + </div>
73 +
74 + <div class="card info-card">
75 + <h3>سیاست صریح علامت‌ها (بدون حدس)</h3>
76 + <div class="policy-grid" id="policy-grid"></div>
77 + <p class="muted">
78 + مانده‌ها بدهکار-مثبت هستند؛ نمایش = علامت × مانده. بخش‌های ناشناخته به‌جای حدس، به صف استثنا می‌روند.
79 + مقصدهای CF و EQ در این نسخه رندر نمی‌شوند و شفاف گزارش می‌شوند.
80 + </p>
81 + </div>
82 + </section>
83 +
84 + <!-- Workspace -->
85 + <section id="view-workspace" class="hidden">
86 + <div class="session-bar card">
87 + <div id="session-info"></div>
88 + <div id="status-chip"></div>
89 + </div>
90 +
91 + <nav class="tabs" id="tabs">
92 + <button data-tab="dashboard" class="tab active">داشبورد و کنترل‌ها</button>
93 + <button data-tab="mapping" class="tab">نگاشت حساب‌ها <span id="mapping-badge" class="badge"></span></button>
94 + <button data-tab="BS" class="tab">ترازنامه</button>
95 + <button data-tab="IS" class="tab">سود و زیان</button>
96 + <button data-tab="audit" class="tab">ممیزی و خروجی</button>
97 + </nav>
98 +
99 + <div id="tab-dashboard" class="tab-panel"></div>
100 + <div id="tab-mapping" class="tab-panel hidden"></div>
101 + <div id="tab-BS" class="tab-panel hidden"></div>
102 + <div id="tab-IS" class="tab-panel hidden"></div>
103 + <div id="tab-audit" class="tab-panel hidden"></div>
104 + </section>
105 + </main>
106 +
107 + <div id="toast" class="toast hidden"></div>
108 +
109 + <footer class="footer">
110 + Aram Pilot Workbench · نسخهٔ موتور <span id="engine-version"></span> ·
111 + خروجی پیش‌نویس کاری است؛ برای گزارشگری رسمی استفاده نکنید.
112 + </footer>
113 +
114 + <script src="app.js"></script>
115 +</body>
116 +</html>
backend/src/aram_backend/static/pilot/styles.css new
+278
@@ -0,0 +1,278 @@
1 +:root {
2 + --bg: #0a1220;
3 + --bg-soft: #0f1a2e;
4 + --card: #13203a;
5 + --card-2: #182848;
6 + --line: #24365c;
7 + --text: #e8eefb;
8 + --muted: #93a4c7;
9 + --primary: #4f8cff;
10 + --accent: #f59e0b;
11 + --green: #34d399;
12 + --red: #f87171;
13 + --blue: #60a5fa;
14 + --radius: 14px;
15 + color-scheme: dark;
16 +}
17 +
18 +* { box-sizing: border-box; }
19 +
20 +body {
21 + margin: 0;
22 + font-family: Vazirmatn, "Segoe UI", Tahoma, Arial, sans-serif;
23 + background:
24 + radial-gradient(1100px 500px at 85% -10%, #14264a 0%, transparent 60%),
25 + var(--bg);
26 + color: var(--text);
27 + min-height: 100vh;
28 + line-height: 1.8;
29 +}
30 +
31 +.hidden { display: none !important; }
32 +.muted { color: var(--muted); font-size: 13px; }
33 +.mono { font-family: Consolas, Menlo, monospace; direction: ltr; unicode-bidi: embed; }
34 +
35 +/* ---------- top bar ---------- */
36 +.topbar {
37 + display: flex; align-items: center; justify-content: space-between;
38 + gap: 16px; flex-wrap: wrap;
39 + padding: 18px 28px;
40 + border-bottom: 1px solid var(--line);
41 + background: rgb(10 18 32 / 80%);
42 + backdrop-filter: blur(6px);
43 + position: sticky; top: 0; z-index: 20;
44 +}
45 +.brand { display: flex; align-items: center; gap: 14px; }
46 +.brand-mark {
47 + width: 46px; height: 46px; border-radius: 12px;
48 + display: grid; place-items: center;
49 + background: linear-gradient(135deg, var(--primary), #7c5cff);
50 + font-size: 24px; font-weight: 800; color: #fff;
51 +}
52 +.topbar h1 { margin: 0; font-size: 18px; }
53 +.tagline { margin: 0; font-size: 12px; color: var(--muted); }
54 +.topbar-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
55 +.actor-field { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--muted); }
56 +.actor-field input {
57 + background: var(--bg-soft); border: 1px solid var(--line); color: var(--text);
58 + border-radius: 8px; padding: 7px 10px; width: 160px; font-family: inherit;
59 +}
60 +
61 +main { max-width: 1200px; margin: 0 auto; padding: 26px 22px 60px; }
62 +
63 +/* ---------- cards / buttons ---------- */
64 +.card {
65 + background: var(--card);
66 + border: 1px solid var(--line);
67 + border-radius: var(--radius);
68 + padding: 20px;
69 +}
70 +.btn {
71 + border: 1px solid var(--line); border-radius: 10px;
72 + background: var(--card-2); color: var(--text);
73 + padding: 10px 18px; font-family: inherit; font-size: 14px;
74 + cursor: pointer; transition: filter .15s, transform .05s;
75 +}
76 +.btn:hover { filter: brightness(1.15); }
77 +.btn:active { transform: translateY(1px); }
78 +.btn:disabled { opacity: .5; cursor: wait; }
79 +.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; font-weight: 700; }
80 +.btn.accent { background: var(--accent); border-color: var(--accent); color: #201400; font-weight: 700; }
81 +.btn.ghost { background: transparent; }
82 +.btn.small { padding: 5px 12px; font-size: 12px; border-radius: 8px; }
83 +.btn.danger { background: #3a1420; border-color: #7f1d1d; color: #fca5a5; }
84 +
85 +/* ---------- landing ---------- */
86 +.hero { text-align: center; padding: 26px 10px 10px; }
87 +.hero h2 { font-size: 26px; margin: 0 0 10px; }
88 +.hero p { max-width: 760px; margin: 0 auto 8px; color: var(--muted); }
89 +.safety-note {
90 + display: inline-block; margin-top: 10px; padding: 6px 16px;
91 + border: 1px dashed var(--accent); border-radius: 999px;
92 + color: var(--accent); font-size: 12.5px;
93 +}
94 +.action-cards {
95 + display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
96 + gap: 18px; margin: 26px 0;
97 +}
98 +.action-card { text-align: center; padding: 28px 22px; }
99 +.action-icon { font-size: 38px; }
100 +.action-card h3 { margin: 10px 0 6px; }
101 +.action-card p { color: var(--muted); font-size: 13.5px; min-height: 48px; }
102 +.progress-card { display: flex; align-items: center; gap: 12px; margin-bottom: 18px; }
103 +.spinner {
104 + width: 18px; height: 18px; border-radius: 50%;
105 + border: 3px solid var(--line); border-top-color: var(--primary);
106 + animation: spin 0.9s linear infinite; display: inline-block;
107 +}
108 +@keyframes spin { to { transform: rotate(360deg); } }
109 +
110 +.issues-card { border-color: #7f1d1d; margin-bottom: 18px; }
111 +.issues-card h3 { color: var(--red); margin-top: 0; }
112 +.info-card h3 { margin-top: 0; }
113 +.policy-grid { display: flex; gap: 12px; flex-wrap: wrap; margin: 10px 0; }
114 +.policy-item {
115 + background: var(--bg-soft); border: 1px solid var(--line); border-radius: 10px;
116 + padding: 8px 14px; font-size: 13px;
117 +}
118 +.policy-item b { color: var(--blue); }
119 +
120 +/* ---------- session bar / tabs ---------- */
121 +.session-bar {
122 + display: flex; justify-content: space-between; align-items: center;
123 + gap: 14px; flex-wrap: wrap; margin-bottom: 16px;
124 +}
125 +.session-meta { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
126 +.session-meta .company-name { font-weight: 800; font-size: 16px; }
127 +.chip {
128 + padding: 3px 12px; border-radius: 999px; font-size: 12px;
129 + border: 1px solid var(--line); background: var(--bg-soft); color: var(--muted);
130 +}
131 +.chip.demo { border-color: var(--accent); color: var(--accent); }
132 +.status-chip { padding: 8px 18px; border-radius: 12px; font-weight: 800; font-size: 14px; }
133 +.status-INCOMPLETE { background: #3a2a10; color: #fbbf24; border: 1px solid #92600a; }
134 +.status-COMPLETE_DRAFT { background: #122a4a; color: #93c5fd; border: 1px solid #1d4ed8; }
135 +.status-COMPLETE_APPROVED { background: #0c2f24; color: #6ee7b7; border: 1px solid #047857; }
136 +
137 +.tabs { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 18px; }
138 +.tab {
139 + background: transparent; border: 1px solid transparent; color: var(--muted);
140 + padding: 9px 16px; border-radius: 10px; cursor: pointer;
141 + font-family: inherit; font-size: 14px;
142 +}
143 +.tab:hover { color: var(--text); background: var(--bg-soft); }
144 +.tab.active { background: var(--card); border-color: var(--line); color: var(--text); font-weight: 700; }
145 +.badge {
146 + background: var(--accent); color: #201400; border-radius: 999px;
147 + font-size: 11px; padding: 1px 8px; font-weight: 800; margin-inline-start: 4px;
148 +}
149 +.badge.zero { background: var(--green); }
150 +
151 +/* ---------- dashboard ---------- */
152 +.grid { display: grid; gap: 14px; }
153 +.checks-grid { grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); margin-bottom: 16px; }
154 +.check-card { padding: 14px 16px; border-radius: 12px; border: 1px solid var(--line); background: var(--card); }
155 +.check-card .check-name { font-size: 13px; color: var(--muted); }
156 +.check-card .check-state { font-size: 16px; font-weight: 800; margin: 4px 0; }
157 +.check-card.pass .check-state { color: var(--green); }
158 +.check-card.fail .check-state { color: var(--red); }
159 +.check-card .check-details { font-size: 12px; color: var(--muted); }
160 +.check-amount { direction: ltr; font-family: Consolas, monospace; font-size: 12.5px; }
161 +
162 +.totals-grid { grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); margin: 16px 0; }
163 +.total-card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; }
164 +.total-card .label { font-size: 12.5px; color: var(--muted); }
165 +.total-card .value { font-size: 17px; font-weight: 800; direction: ltr; text-align: right; font-family: Consolas, monospace; }
166 +.total-card.highlight { border-color: var(--primary); }
167 +.total-card .value.neg { color: var(--red); }
168 +
169 +.coverage-bar-wrap { background: var(--bg-soft); border-radius: 999px; height: 14px; overflow: hidden; border: 1px solid var(--line); }
170 +.coverage-bar { height: 100%; background: linear-gradient(90deg, var(--primary), var(--green)); transition: width .4s; }
171 +
172 +/* ---------- tables ---------- */
173 +.table-wrap { overflow-x: auto; border-radius: 12px; border: 1px solid var(--line); }
174 +table { width: 100%; border-collapse: collapse; font-size: 13.5px; background: var(--card); }
175 +th, td { padding: 9px 12px; border-bottom: 1px solid var(--line); text-align: right; vertical-align: middle; }
176 +thead th { background: var(--card-2); color: var(--muted); font-size: 12.5px; white-space: nowrap; }
177 +tbody tr:hover { background: rgb(79 140 255 / 6%); }
178 +td.num, th.num { direction: ltr; text-align: left; font-family: Consolas, monospace; white-space: nowrap; }
179 +td.num.neg { color: var(--red); }
180 +.table-toolbar { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-bottom: 12px; }
181 +.table-toolbar input[type="search"], .table-toolbar select {
182 + background: var(--bg-soft); border: 1px solid var(--line); color: var(--text);
183 + border-radius: 9px; padding: 8px 12px; font-family: inherit; font-size: 13px;
184 +}
185 +.table-toolbar input[type="search"] { width: 240px; }
186 +
187 +.approval-chip { font-size: 11.5px; padding: 2px 10px; border-radius: 999px; border: 1px solid var(--line); }
188 +.approval-Approved { background: #0c2f24; color: #6ee7b7; border-color: #047857; }
189 +.approval-Reviewed { background: #122a4a; color: #93c5fd; border-color: #1d4ed8; }
190 +.approval-Draft { background: #3a2a10; color: #fbbf24; border-color: #92600a; }
191 +.approval-none { background: #3a1420; color: #fca5a5; border-color: #7f1d1d; }
192 +
193 +/* ---------- mapping editor ---------- */
194 +.editor-row td { background: var(--bg-soft); padding: 16px; }
195 +.editor-grid { display: flex; gap: 12px; flex-wrap: wrap; align-items: flex-end; }
196 +.editor-grid label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--muted); }
197 +.editor-grid select, .editor-grid input {
198 + background: var(--card); border: 1px solid var(--line); color: var(--text);
199 + border-radius: 8px; padding: 8px 10px; font-family: inherit; min-width: 130px;
200 +}
201 +.editor-actions { display: flex; gap: 8px; }
202 +
203 +/* ---------- statements ---------- */
204 +.statement-paper {
205 + background: var(--card); border: 1px solid var(--line); border-radius: var(--radius);
206 + padding: 26px 30px;
207 +}
208 +.statement-head { text-align: center; margin-bottom: 18px; }
209 +.statement-head h2 { margin: 0; font-size: 20px; }
210 +.statement-head .sub { color: var(--muted); font-size: 13px; }
211 +.draft-watermark {
212 + display: inline-block; margin-top: 8px; padding: 3px 14px; border-radius: 999px;
213 + border: 1px dashed var(--accent); color: var(--accent); font-size: 12px;
214 +}
215 +.statement-section { margin: 18px 0; }
216 +.statement-section > .section-head {
217 + display: flex; justify-content: space-between; align-items: center;
218 + background: var(--card-2); padding: 9px 16px; border-radius: 10px;
219 + font-weight: 800; border: 1px solid var(--line);
220 +}
221 +.note-line {
222 + display: flex; justify-content: space-between; align-items: center;
223 + padding: 9px 18px; border-bottom: 1px solid var(--line); cursor: pointer;
224 +}
225 +.note-line:hover { background: rgb(79 140 255 / 6%); }
226 +.note-line .note-title { display: flex; gap: 10px; align-items: center; }
227 +.note-number {
228 + background: var(--bg-soft); border: 1px solid var(--line); border-radius: 7px;
229 + min-width: 34px; text-align: center; font-size: 12px; padding: 1px 6px; color: var(--muted);
230 +}
231 +.note-total { direction: ltr; font-family: Consolas, monospace; font-weight: 700; }
232 +.note-total.neg { color: var(--red); }
233 +.drill { padding: 4px 26px 12px; }
234 +.drill table { font-size: 12.5px; background: var(--bg-soft); }
235 +.statement-total {
236 + display: flex; justify-content: space-between; padding: 12px 18px; margin-top: 14px;
237 + border-top: 2px solid var(--primary); font-weight: 900; font-size: 15px;
238 +}
239 +.statement-tools { display: flex; justify-content: flex-end; gap: 8px; margin-bottom: 10px; }
240 +
241 +/* ---------- audit ---------- */
242 +.provenance-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; margin-bottom: 16px; }
243 +.prov-item { background: var(--bg-soft); border: 1px solid var(--line); border-radius: 10px; padding: 10px 14px; font-size: 13px; }
244 +.prov-item .k { color: var(--muted); font-size: 11.5px; }
245 +.prov-item .v { word-break: break-all; }
246 +
247 +/* ---------- toast / footer ---------- */
248 +.toast {
249 + position: fixed; bottom: 24px; right: 50%; transform: translateX(50%);
250 + background: var(--card-2); border: 1px solid var(--line); color: var(--text);
251 + padding: 12px 22px; border-radius: 12px; z-index: 50; max-width: 90vw;
252 + box-shadow: 0 12px 40px rgb(0 0 0 / 45%); font-size: 14px;
253 +}
254 +.toast.error { border-color: #7f1d1d; color: #fca5a5; }
255 +.toast.success { border-color: #047857; color: #6ee7b7; }
256 +.footer {
257 + text-align: center; color: var(--muted); font-size: 12px;
258 + padding: 18px; border-top: 1px solid var(--line);
259 +}
260 +
261 +/* ---------- print ---------- */
262 +@media print {
263 + body { background: #fff; color: #111; }
264 + .topbar, .tabs, .session-bar, .footer, .statement-tools, .toast { display: none !important; }
265 + .statement-paper { border: none; background: #fff; }
266 + .statement-section > .section-head { background: #eef2f7; color: #111; }
267 + .note-line, th, td { border-color: #cbd5e1; }
268 + .note-number, .chip { color: #334155; background: #f1f5f9; }
269 + thead th { background: #eef2f7; color: #334155; }
270 + table { background: #fff; }
271 + .draft-watermark { color: #92400e; border-color: #92400e; }
272 +}
273 +
274 +@media (max-width: 720px) {
275 + main { padding: 16px 12px 50px; }
276 + .statement-paper { padding: 16px; }
277 + .actor-field input { width: 110px; }
278 +}
backend/tests/test_pilot_api.py new
+179
@@ -0,0 +1,179 @@
1 +from __future__ import annotations
2 +
3 +from io import BytesIO
4 +
5 +from openpyxl import load_workbook
6 +
7 +import aram_backend.pilot_api as pilot_api
8 +from test_pilot_engine import build_balanced_workbook
9 +
10 +
11 +def test_meta_exposes_explicit_sign_policy(client):
12 + response = client.get("/api/v1/pilot/meta")
13 + assert response.status_code == 200
14 + body = response.json()
15 + assert body["rendered_statements"] == ["BS", "IS"]
16 + assert body["deferred_statements"] == ["CF", "EQ"]
17 + assert body["section_policy"]["BS"] == {"Assets": 1, "Liabilities": -1, "Equity": -1}
18 + assert body["section_policy"]["IS"] == {"Revenue": -1, "Expenses": 1}
19 +
20 +
21 +def test_root_redirects_to_workbench_and_ui_is_served(client):
22 + response = client.get("/", follow_redirects=False)
23 + assert response.status_code in {302, 307}
24 + assert response.headers["location"] == "/pilot/"
25 + page = client.get("/pilot/")
26 + assert page.status_code == 200
27 + assert "میز کار پایلوت" in page.text
28 + assert client.get("/pilot/app.js").status_code == 200
29 + assert client.get("/pilot/styles.css").status_code == 200
30 +
31 +
32 +def test_demo_full_workflow_from_exceptions_to_approved_export(client):
33 + created = client.post("/api/v1/pilot/demo")
34 + assert created.status_code == 200
35 + body = created.json()
36 + sid = body["session"]["id"]
37 + assert body["session"]["source"] == "demo"
38 + assert body["report"]["status"]["label"] == "INCOMPLETE"
39 + assert {e["account_code"] for e in body["report"]["exceptions"]} == {"9001", "9002"}
40 + tb = next(c for c in body["report"]["checks"] if c["code"] == "TRIAL_BALANCE_CLOSED")
41 + assert tb["passed"] and tb["amount"] == "0"
42 +
43 + # Map the two suspense accounts; coverage and equation close, approval pending.
44 + for code, statement, section, note in (
45 + ("9001", "BS", "Assets", "04"),
46 + ("9002", "BS", "Liabilities", "06"),
47 + ):
48 + response = client.put(
49 + f"/api/v1/pilot/sessions/{sid}/mappings/{code}",
50 + json={"statement": statement, "section": section, "note_number": note,
51 + "actor": "آزمون"},
52 + )
53 + assert response.status_code == 200
54 + body = response.json()
55 + assert body["report"]["status"]["label"] == "COMPLETE_DRAFT"
56 + assert body["report"]["totals"]["assets"] == "56000000000"
57 + assert body["report"]["totals"]["liabilities"] == "22800000000"
58 + assert body["report"]["totals"]["equity"] == "33000000000"
59 + assert body["report"]["totals"]["profit"] == "200000000"
60 + assert all(c["passed"] for c in body["report"]["checks"] if c["code"] != "MAPPINGS_APPROVED")
61 +
62 + # Approve the remaining Draft mappings with reviewer evidence.
63 + for code, statement, section, note in (
64 + ("1004", "BS", "Assets", "04"),
65 + ("9001", "BS", "Assets", "04"),
66 + ("9002", "BS", "Liabilities", "06"),
67 + ):
68 + response = client.put(
69 + f"/api/v1/pilot/sessions/{sid}/mappings/{code}",
70 + json={"statement": statement, "section": section, "note_number": note,
71 + "approval_status": "Approved", "reviewer": "بازبین آزمون", "actor": "آزمون"},
72 + )
73 + assert response.status_code == 200
74 + body = response.json()
75 + assert body["report"]["status"]["label"] == "COMPLETE_APPROVED"
76 + assert len(body["audit_trail"]) == 5
77 + assert body["audit_trail"][0]["actor"] == "آزمون"
78 +
79 + export = client.get(f"/api/v1/pilot/sessions/{sid}/export.xlsx")
80 + assert export.status_code == 200
81 + assert "spreadsheetml" in export.headers["content-type"]
82 + book = load_workbook(BytesIO(export.content))
83 + assert "BalanceSheet" in book.sheetnames
84 + info = {row[0]: row[1] for row in book["Info"].iter_rows(min_row=2, values_only=True)}
85 + assert info["status"] == "COMPLETE_APPROVED"
86 + assert info["synthetic_data"].startswith("TRUE")
87 + assert book["AuditTrail"].max_row == 6
88 + book.close()
89 +
90 + assert client.delete(f"/api/v1/pilot/sessions/{sid}").status_code == 200
91 + assert client.get(f"/api/v1/pilot/sessions/{sid}").status_code == 404
92 +
93 +
94 +def test_upload_valid_workbook_creates_session(client):
95 + response = client.post(
96 + "/api/v1/pilot/sessions",
97 + files={"file": ("pilot.xlsx", build_balanced_workbook(),
98 + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
99 + )
100 + assert response.status_code == 200
101 + body = response.json()
102 + assert body["session"]["source"] == "upload"
103 + assert body["report"]["status"]["label"] == "COMPLETE_APPROVED"
104 + assert len(body["accounts"]) == 5
105 +
106 +
107 +def test_upload_invalid_workbook_returns_exact_preflight_issues(client):
108 + response = client.post(
109 + "/api/v1/pilot/sessions", files={"file": ("bad.xlsx", b"not an xlsx")}
110 + )
111 + assert response.status_code == 422
112 + detail = response.json()["detail"]
113 + assert detail["issues"][0]["code"] == "INVALID_WORKBOOK"
114 +
115 +
116 +def test_upload_rejects_wrong_extension_and_empty_file(client):
117 + response = client.post(
118 + "/api/v1/pilot/sessions", files={"file": ("data.csv", b"x,y\n1,2")}
119 + )
120 + assert response.status_code == 422
121 + response = client.post(
122 + "/api/v1/pilot/sessions", files={"file": ("empty.xlsx", b"")}
123 + )
124 + assert response.status_code == 422
125 +
126 +
127 +def test_upload_size_limit_is_enforced(client, monkeypatch):
128 + monkeypatch.setattr(pilot_api, "MAX_UPLOAD_BYTES", 8)
129 + response = client.post(
130 + "/api/v1/pilot/sessions", files={"file": ("big.xlsx", b"0123456789")}
131 + )
132 + assert response.status_code == 413
133 +
134 +
135 +def test_mapping_validation_is_fail_closed(client):
136 + sid = client.post("/api/v1/pilot/demo").json()["session"]["id"]
137 + base = f"/api/v1/pilot/sessions/{sid}/mappings"
138 + # Unknown account.
139 + assert client.put(f"{base}/9999", json={
140 + "statement": "BS", "section": "Assets", "note_number": "01",
141 + }).status_code == 404
142 + # Target that does not exist in Notes.
143 + assert client.put(f"{base}/9001", json={
144 + "statement": "BS", "section": "Assets", "note_number": "99",
145 + }).status_code == 422
146 + # Approved without reviewer evidence.
147 + assert client.put(f"{base}/9001", json={
148 + "statement": "BS", "section": "Assets", "note_number": "04",
149 + "approval_status": "Approved",
150 + }).status_code == 422
151 + # Invalid lifecycle value.
152 + assert client.put(f"{base}/9001", json={
153 + "statement": "BS", "section": "Assets", "note_number": "04",
154 + "approval_status": "Published",
155 + }).status_code == 422
156 +
157 +
158 +def test_clear_mapping_reopens_the_exception_queue(client):
159 + sid = client.post("/api/v1/pilot/demo").json()["session"]["id"]
160 + response = client.delete(f"/api/v1/pilot/sessions/{sid}/mappings/1001?actor=tester")
161 + assert response.status_code == 200
162 + body = response.json()
163 + assert body["report"]["status"]["label"] == "INCOMPLETE"
164 + assert "1001" in {e["account_code"] for e in body["report"]["exceptions"]}
165 + assert body["audit_trail"][-1]["action"] == "clear_mapping"
166 +
167 +
168 +def test_unknown_session_is_404_everywhere(client):
169 + assert client.get("/api/v1/pilot/sessions/nope").status_code == 404
170 + assert client.get("/api/v1/pilot/sessions/nope/export.xlsx").status_code == 404
171 + assert client.delete("/api/v1/pilot/sessions/nope").status_code == 404
172 + assert client.put("/api/v1/pilot/sessions/nope/mappings/10", json={
173 + "statement": "BS", "section": "Assets", "note_number": "01",
174 + }).status_code == 404
175 +
176 +
177 +def test_existing_api_surface_is_unchanged(client):
178 + assert client.get("/api/v1/health").json()["status"] == "ok"
179 + assert len(client.get("/api/v1/schema/entities").json()["entities"]) == 9
backend/tests/test_pilot_engine.py new
+251
@@ -0,0 +1,251 @@
1 +from __future__ import annotations
2 +
3 +from decimal import Decimal
4 +from io import BytesIO
5 +
6 +from openpyxl import load_workbook
7 +import pytest
8 +
9 +from aram_backend.pilot_engine import (
10 + PilotModelError,
11 + build_report,
12 + export_report_workbook,
13 + parse_pilot_model,
14 +)
15 +from test_pilot_workbook import workbook_bytes
16 +
17 +
18 +def account_row(code, name, closing, *, debit=0, credit=0, source_row=2):
19 + opening = closing - debit + credit
20 + return (
21 + "C1", 1404, code, "کل", None, None, None, None, None, None, None,
22 + None, None, None, code, name, opening, debit, credit, closing,
23 + source_row, "Draft", 0,
24 + )
25 +
26 +
27 +def note_row(statement, section, number, title):
28 + return ("C1", 1404, statement, section, number, title, None, None)
29 +
30 +
31 +def mapping_row(mid, code, statement, section, number, *, approval="Approved"):
32 + reviewed = approval in {"Reviewed", "Approved"}
33 + return (
34 + mid, "C1", 1404, code, "General", code, None, None, None, None, None,
35 + statement, section, number, None, 1, approval,
36 + "tester" if reviewed else None, "2026-12-03" if reviewed else None,
37 + "test", None, "Valid" if approval == "Approved" else "Pending",
38 + )
39 +
40 +
41 +BALANCED_NOTES = [
42 + note_row("BS", "Assets", "01", "نقد"),
43 + note_row("BS", "Liabilities", "02", "پرداختنی"),
44 + note_row("BS", "Equity", "03", "سرمایه"),
45 + note_row("IS", "Revenue", "04", "فروش"),
46 + note_row("IS", "Expenses", "05", "هزینه"),
47 +]
48 +BALANCED_ACCOUNTS = [
49 + account_row("10", "نقد", 100, debit=150, credit=50, source_row=10),
50 + account_row("20", "پرداختنی", -60, credit=60, source_row=11),
51 + account_row("30", "سرمایه", -30, credit=30, source_row=12),
52 + account_row("40", "فروش", -20, credit=20, source_row=13),
53 + account_row("50", "هزینه", 10, debit=10, source_row=14),
54 +]
55 +BALANCED_MAPPINGS = [
56 + mapping_row("M1", "10", "BS", "Assets", "01"),
57 + mapping_row("M2", "20", "BS", "Liabilities", "02"),
58 + mapping_row("M3", "30", "BS", "Equity", "03"),
59 + mapping_row("M4", "40", "IS", "Revenue", "04"),
60 + mapping_row("M5", "50", "IS", "Expenses", "05"),
61 +]
62 +
63 +
64 +def balanced_rows():
65 + return {
66 + "Company": [("C1", "شرکت آزمون", 1404, "IRR", "rial", "tester", "Draft")],
67 + "Accounts": list(BALANCED_ACCOUNTS),
68 + "Notes": list(BALANCED_NOTES),
69 + "Mapping": list(BALANCED_MAPPINGS),
70 + }
71 +
72 +
73 +def build_balanced_workbook() -> bytes:
74 + return workbook_bytes(balanced_rows())
75 +
76 +
77 +def test_balanced_workbook_produces_complete_approved_report():
78 + model = parse_pilot_model(build_balanced_workbook())
79 + report = build_report(model, model.mappings)
80 + assert report["status"] == {
81 + "label": "COMPLETE_APPROVED", "complete": True, "all_mappings_approved": True,
82 + }
83 + assert report["totals"]["assets"] == "100"
84 + assert report["totals"]["liabilities"] == "60"
85 + assert report["totals"]["equity"] == "30"
86 + assert report["totals"]["liabilities_and_equity"] == "90"
87 + assert report["totals"]["profit"] == "10"
88 + assert all(check["passed"] for check in report["checks"])
89 + assert report["exceptions"] == []
90 + assets = report["statements"]["BS"]["sections"][0]
91 + assert assets["total"] == "100"
92 + line = assets["lines"][0]
93 + assert line["accounts"][0]["source_row"] == 10
94 + assert line["accounts"][0]["display"] == "100"
95 +
96 +
97 +def test_unmapped_account_blocks_completeness_and_enters_queue():
98 + rows = balanced_rows()
99 + rows["Mapping"] = rows["Mapping"][:-1] # expense account unmapped
100 + model = parse_pilot_model(workbook_bytes(rows))
101 + report = build_report(model, model.mappings)
102 + assert report["status"]["label"] == "INCOMPLETE"
103 + assert [e["code"] for e in report["exceptions"]] == ["UNMAPPED_ACCOUNT"]
104 + assert report["exceptions"][0]["account_code"] == "50"
105 + failed = {c["code"] for c in report["checks"] if not c["passed"]}
106 + assert failed == {"FULL_COVERAGE", "ACCOUNTING_EQUATION"}
107 +
108 +
109 +def test_deferred_cf_and_eq_targets_are_reported_not_rendered():
110 + rows = balanced_rows()
111 + rows["Notes"].append(note_row("CF", "Operating", "06", "جریان نقدی"))
112 + rows["Mapping"][4] = mapping_row("M5", "50", "CF", "Operating", "06")
113 + model = parse_pilot_model(workbook_bytes(rows))
114 + report = build_report(model, model.mappings)
115 + assert report["status"]["label"] == "INCOMPLETE"
116 + assert report["exceptions"][0]["code"] == "DEFERRED_STATEMENT"
117 + assert set(report["statements"]) == {"BS", "IS"}
118 +
119 +
120 +def test_unknown_section_fails_closed_instead_of_guessing():
121 + rows = balanced_rows()
122 + rows["Notes"].append(note_row("BS", "Mystery", "06", "بخش ناشناخته"))
123 + rows["Mapping"][0] = mapping_row("M1", "10", "BS", "Mystery", "06")
124 + model = parse_pilot_model(workbook_bytes(rows))
125 + report = build_report(model, model.mappings)
126 + assert report["exceptions"][0]["code"] == "UNSUPPORTED_SECTION"
127 + assert report["statements"]["BS"]["sections"][0]["total"] == "0"
128 +
129 +
130 +def test_conflicting_mappings_are_excluded_until_explicit_resolution():
131 + rows = balanced_rows()
132 + rows["Notes"].append(note_row("BS", "Assets", "06", "مقصد دوم"))
133 + rows["Mapping"].append(mapping_row("M6", "10", "BS", "Assets", "06"))
134 + model = parse_pilot_model(workbook_bytes(rows))
135 + assert "10" in model.conflicts and "10" not in model.mappings
136 + report = build_report(model, model.mappings)
137 + assert report["exceptions"][0]["code"] == "MAPPING_CONFLICT"
138 +
139 + # An explicit workbench mapping resolves the conflict, with provenance.
140 + from aram_backend.pilot_engine import MappingEntry
141 + resolved = dict(model.mappings)
142 + resolved["10"] = MappingEntry(
143 + "10", "BS", "Assets", "01", "", "Draft", "", "workbench", "WB-1"
144 + )
145 + report = build_report(model, resolved)
146 + assert all(e["code"] != "MAPPING_CONFLICT" for e in report["exceptions"])
147 + assert report["statements"]["BS"]["sections"][0]["total"] == "100"
148 +
149 +
150 +def test_identical_duplicate_mappings_are_deduplicated():
151 + rows = balanced_rows()
152 + rows["Mapping"].append(mapping_row("M6", "10", "BS", "Assets", "01"))
153 + model = parse_pilot_model(workbook_bytes(rows))
154 + assert not model.conflicts
155 + report = build_report(model, model.mappings)
156 + assert report["coverage"]["mapped_accounts"] == 5
157 + assert report["status"]["complete"]
158 +
159 +
160 +def test_draft_mappings_keep_output_in_draft_state():
161 + rows = balanced_rows()
162 + rows["Mapping"][0] = mapping_row("M1", "10", "BS", "Assets", "01", approval="Draft")
163 + model = parse_pilot_model(workbook_bytes(rows))
164 + report = build_report(model, model.mappings)
165 + assert report["status"] == {
166 + "label": "COMPLETE_DRAFT", "complete": True, "all_mappings_approved": False,
167 + }
168 +
169 +
170 +def test_decimal_precision_is_preserved_as_exact_strings():
171 + rows = balanced_rows()
172 + rows["Accounts"] = [
173 + account_row("10", "نقد", Decimal("10.10")),
174 + account_row("20", "پرداختنی", Decimal("-6.06")),
175 + account_row("30", "سرمایه", Decimal("-3.03")),
176 + account_row("40", "فروش", Decimal("-2.02")),
177 + account_row("50", "هزینه", Decimal("1.01")),
178 + ]
179 + model = parse_pilot_model(workbook_bytes(rows))
180 + report = build_report(model, model.mappings)
181 + # Excel numeric storage drops trailing zeros (10.10 -> 10.1) but the
182 + # decimal value itself must survive exactly, with no float drift.
183 + assert report["totals"]["assets"] == "10.1"
184 + assert report["totals"]["profit"] == "1.01"
185 + assert report["totals"]["liabilities_and_equity"] == "9.09"
186 + assert report["status"]["complete"]
187 +
188 +
189 +def test_invalid_workbook_raises_typed_error_with_issues():
190 + rows = balanced_rows()
191 + broken = list(rows["Accounts"][0])
192 + broken[19] = 999 # closing no longer ties
193 + rows["Accounts"][0] = tuple(broken)
194 + with pytest.raises(PilotModelError) as exc:
195 + parse_pilot_model(workbook_bytes(rows))
196 + assert any(i.code == "NON_ZERO_CLOSING_DELTA" for i in exc.value.issues)
197 +
198 +
199 +def test_multiple_companies_are_rejected_explicitly():
200 + rows = balanced_rows()
201 + rows["Company"].append(("C2", "شرکت دوم", 1404, "IRR", "rial", "t", "Draft"))
202 + with pytest.raises(PilotModelError) as exc:
203 + parse_pilot_model(workbook_bytes(rows))
204 + assert exc.value.issues[0].code == "WORKBENCH_SINGLE_COMPANY_REQUIRED"
205 +
206 +
207 +def test_empty_accounts_never_report_complete():
208 + rows = balanced_rows()
209 + rows["Accounts"] = []
210 + rows["Mapping"] = []
211 + model = parse_pilot_model(workbook_bytes(rows))
212 + report = build_report(model, model.mappings)
213 + assert report["status"]["label"] == "INCOMPLETE"
214 + assert not report["checks"][0]["passed"]
215 +
216 +
217 +def test_report_is_deterministic():
218 + data = build_balanced_workbook()
219 + first = build_report(parse_pilot_model(data), parse_pilot_model(data).mappings)
220 + second = build_report(parse_pilot_model(data), parse_pilot_model(data).mappings)
221 + assert first == second
222 +
223 +
224 +def test_export_contains_all_sheets_and_exact_provenance():
225 + model = parse_pilot_model(build_balanced_workbook())
226 + report = build_report(model, model.mappings)
227 + trail = [{"at": "2026-12-03T00:00:00+00:00", "actor": "tester", "account_code": "10",
228 + "action": "set_mapping", "before": "(بدون نگاشت)", "after": "BS/Assets/01"}]
229 + data = export_report_workbook(model, model.mappings, report, trail, "upload")
230 + book = load_workbook(BytesIO(data))
231 + assert book.sheetnames == [
232 + "Info", "Checks", "BalanceSheet", "IncomeStatement",
233 + "Coverage", "Exceptions", "AuditTrail",
234 + ]
235 + info = {row[0]: row[1] for row in book["Info"].iter_rows(min_row=2, values_only=True)}
236 + assert info["source_sha256"] == model.source_sha256
237 + assert info["status"] == "COMPLETE_APPROVED"
238 + amounts = [row[4] for row in book["BalanceSheet"].iter_rows(min_row=2, values_only=True)
239 + if row[0] == "note"]
240 + assert 100.0 in amounts
241 + assert book["Coverage"].max_row == 6 # header + 5 accounts
242 + assert book["AuditTrail"].max_row == 2
243 + book.close()
244 +
245 +
246 +def test_engine_never_writes_files(tmp_path, monkeypatch):
247 + monkeypatch.chdir(tmp_path)
248 + model = parse_pilot_model(build_balanced_workbook())
249 + report = build_report(model, model.mappings)
250 + export_report_workbook(model, model.mappings, report, [], "demo")
251 + assert list(tmp_path.iterdir()) == []