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

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

Synced Dec 4, 10:30 UTC

C0: course correction (booklet 2) — browser-edition removal, PR triage, booklet references, process rules (#97)

* 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> * feat(pilot): generic company-agnostic editing + mobile-first UI + save/resume Make the workbench a complete, reusable tool for any company, fully usable on a phone: - Full account CRUD: add/edit/rename/delete. Rename carries the mapping forward automatically. Manually added accounts derive closing from opening+debit-credit (never invented); duplicates/non-finite rejected. - Full note & sub-note CRUD: add/edit-title/delete. Deleting a note that is a mapping target is blocked (409) until mappings move. - Company edit: name/code/fiscal-year/unit/currency -> not tied to any entity. - Save/resume: GET workspace.xlsx serializes the working state to a valid Pilot v0.1 workbook; re-upload rebuilds it losslessly (verified round-trip). - Mutable WorkingModel + typed editing validators (pilot_editing.py); every change append-only audited; thread-safe snapshots. - Mobile-first UI: bottom navigation, bottom-sheet forms, card layouts, numeric keyboards, safe-area insets; partial list updates keep search focus. - Engine 1.1.0; PilotAccount now carries full hierarchy for lossless export. Tests: 107 passed (15 new editing/round-trip/API tests). No canonical data, samples, models or migrations changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(pilot): serve workbench directly at root (no redirect) for proxy safety The preview proxy can mishandle the / -> /pilot/ redirect hop. Serve the workbench HTML directly at / with absolute asset paths so the app loads in one request at both / and /pilot/. Update the root test accordingly. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(pilot): permanent browser edition (Pyodide) deployed via GitHub Pages - webapp/: mobile-first RTL UI shell + bridge.py (JSON dispatcher mirroring pilot_api.py, no FastAPI) running the exact tested engine in-browser - scripts/build_webapp.py: assembles docs/ from UI + unmodified engine copies - docs/: Pages source (app at site root, .nojekyll, engine under py/aram_backend) - Verified under Node+Pyodide 0.26.4: demo, CRUD, rename-with-mapping, company edit, lossless workspace round-trip, report export, preflight/duplicate errors, balance fail-closed semantics, COMPLETE_APPROVED end state Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci(pilot): deploy browser edition to GitHub Pages (auto-enable) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(pilot): vendor Excel wheels + dual-CDN boot; permanent commit-pinned links - boot() installs vendored openpyxl/et_xmlfile wheels directly into site-packages (no PyPI/micropip at runtime) and falls back jsDelivr->unpkg - docs/vendor/ carries the two pure-Python wheels (268KB) - Pages workflow is dispatch-only (site creation requires owner action); app is served permanently via rawcdn.githack.com / cdn.jsdelivr.net gh - Final Node+Pyodide test of deployed bundle: full journey to COMPLETE_APPROVED, lossless workspace round-trip, 12 audit entries Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(domain): pure financial domain layer + parser/inspection fixes (Phase 0) Evidence-based ADRs from read-only probe of canonical 1404 ledger (252898 rows): - ADR-012 money: integer-rial BIGINT storage (Rial TypeDecorator), Decimal in Python, half-up + largest-remainder rounding only in output (P-02, D-03, OD-03) - ADR-013 sign: debit-positive confirmed (C-01 252892/252898 vs 37% credit-pos) - ADR-014 hierarchy: OD-01 default refuted (T1..T4 concat == حساب for 0 rows); kol->general, حساب->subsidiary, T1..T4->detail1..4; full code = kol+حساب (D-10) Domain (no I/O): normalize_fa/normalize_code/decimal_from_cell (P-03/P-04, D-04), Rial money, ledger<->Pilot hierarchy, blocking controls C-01..C-04 (D-02). ledger_parser delegates to domain (text codes keep leading zeros, exact float repr); workbook_inspection normalizes sheets/headers (D-05) and guards max_column=None (D-11). hypothesis added to test extra (ADR-012). Tests: 47 domain + 9 Phase-0 acceptance incl. bounded real-data evidence. Full suite 163 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(db): LedgerBalance model + exact-rial money column (D-01, D-03) - LedgerBalance: year-isolated, source-linked, text hierarchy codes, opening/ debit/credit/closing as Rial BIGINT; unique (year_id, account_full_code, import_version); new import version per Draft re-import (booklet §5) - StatementLine.mapped_total Numeric(24,4) -> Rial() (no float on SQLite, P-02) - ledger_parser extracts optional kol (general_code); hierarchy mapper accepts absent kol; services/ledger_import aggregates parsed rows by canonical account with exact Decimal summation - Migration 20261203_02 (guarded create + batch alter) runs on SQLite/PostgreSQL; up/down round-trip verified Tests: small-sample exact round-trip, large-rial BIGINT storage (>2^53) via ORM, duplicate-account aggregation, uniqueness, migration upgrade/downgrade. Full suite 168 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(source): content-addressed byte store + full CSV support (D-06) - SourceFile model (sha256 PK, size, content_type, stored_path) + SourceDocument FK; SourceStore writes immutable bytes atomically, re-verifies hash on read (corruption/tamper fails loudly); registration accepts optional store, keeps metadata-only model contract (accepted tests unchanged) - CSV ledger parser: UTF-8/UTF-8-BOM/Windows-1256, delimiter sniffing, same Persian normalization + exact-money rules as XLSX; parse_ledger routes by extension; streaming reader - Migration 20261203_03 (guarded create + batch add column) Tests: store round-trip/idempotency/corruption, registration+re-import hash match, CSV encodings/delimiters/leading-zeros/missing-header/empty/routing. 185 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(db): locked-year immutability triggers + hash-chained audit + reopen (D-07) - DB triggers (SQLite + PostgreSQL) block INSERT/UPDATE/DELETE on year-owned tables when the year is LOCKED, enforced even via raw SQL (P-08, D3) - Lifecycle trigger: Draft->Approved->Locked; Locked->Approved only with an approved ReopenRequest; protected years cannot be deleted - AuditEntry append-only (trigger) + hash chain (verify_chain detects tampering independently of the trigger); ReopenRequest model + ORM guard exemption - ADR-016 reopen/immutability model; migration 20261203_04 installs tables+triggers - ensure_triggers() helper; conftest installs triggers for all tests Tests: raw-SQL insert/update/delete blocked on locked year, draft writes allowed, reopen with/without approved request (ORM + raw SQL), audit chain build/verify/ tamper-detection/append-only. 195 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ingestion): wire C-01..C-04 controls into preflight (D-02) - services/preflight.run_preflight evaluates the blocking control set over parsed ledger rows + active mappings; PreflightReport exposes blocking results, can_approve, and the unknown-account queue (C-04) - Mappings loaded from the year's MappingRule rows or supplied directly (pure path) - ERROR results block approval (P-09); unmapped active accounts surface in the unknown queue for Phase 2 resolution Tests: clean ledger passes C-01/C-02, C-01 violation blocks, unmapped accounts queued, mapping clears queue, all four controls present, inactive accounts not queued. 201 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci: quality gates — ruff, mypy strict (domain), coverage, pip-audit, PG matrix (D-12) - pyproject: ruff/mypy/coverage/pytest-cov/pip-audit in test extra; psycopg in ci extra; ruff/mypy/coverage config (domain strict, total>=80%, domain>=90%) - CI: quality job (whitespace, ruff lint+format, mypy domain strict, coverage gates, pip-audit) + migration matrix job (SQLite + PostgreSQL service container, up/down/up round-trip) - ADR-017 documents the dev/CI-only dependencies (no runtime impact, P-10) - Lint fixes across backend (zip strict, StrEnum, specific test exceptions, unused vars); format applied to Phase-0 layers (domain/services/migrations) - pytest>=9.0.3 + pip/setuptools upgraded to clear pip-audit CVEs Gates verified locally: ruff clean, format clean, mypy domain strict clean, coverage total 92% / domain 97%, pip-audit no known vulnerabilities, 201 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs: refresh PROJECT_STATUS + PROJECT_LOG for Phase 0 debts (D-08) Record D-01..D-12 states with commit evidence, real-data proof, ADRs 012/013/ 014/016/017, and local gate results (201 tests, coverage 92%/97%, pip-audit clean). D-09 marked BLOCKED (owner-only). No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * style: ruff format migration files (Phase-0 format gate) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(statements): persistent audited vertical slice + drill-down (Phase 1) - services/statement_build: build versioned BS/IS from latest LedgerBalance import + mappings/notes; exact integer-rial totals; display sign policy (ADR-013/018); unmapped active accounts surfaced; new version per build (never mutates snapshot) - drill_down: StatementLine -> Note -> MappingRule -> LedgerBalance -> SourceDocument (filename + SHA-256) + sheet + row (D2 full traceability) - statement_api: company/year setup, year-filtered ledger upload+import, notes, mappings, statement build/list, drill-down, preflight controls endpoint - ADR-018 persistent statements + drill-down contract Tests: BS/IS totals+signs, drill-down to source row, version increment, unmapped surfacing, API end-to-end (CSV->import->map->build->drilldown), preflight controls, bounded real-data smoke (3000 real 1404 rows -> import -> build -> drill-down). 209 passed; ruff/mypy/coverage gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(mapping): Excel I/O + unknown queue + approval gate + carry-forward (Phase 2) - mapping_io: governed Mappings workbook export/import; text codes; fail-closed per-row import with error report; idempotent re-import; auto-create notes - mapping_workflow: unknown-account queue (C-04 active unmapped); carry-forward notes+mappings into a Draft year (D1 continuity), idempotent - approval: approve_year runs C-01..C-04; blocking ERROR refuses Draft->Approved; clean pass transitions + hash-chained audit entry (P-09) - statement_api: mappings export/import, unknown-accounts, carry-forward, approve - ADR-019 mapping I/O + approval contract; shared api_client fixture in conftest Tests: export/import round-trip, invalid-row fail-closed, queue list/clear, approval blocked/success/non-draft, carry-forward copy/idempotent/reject, API end-to-end (queue->import mappings->approve). 220 passed; gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(notes): safe formula grammar + note engine (Phase 3) - domain/formula: hand-written tokenizer + recursive-descent parser -> whitelisted AST, exact Decimal evaluation; NO eval/exec (P-05); unknown tokens/functions fail closed; division-by-zero rejected; mypy --strict clean - services/note_engine: evaluate disclosure rows from latest ledger import; acct/ row/note/sum/abs functions; earlier-row + cross-note references with cycle detection; per-row referenced accounts for drill-down - statement_api: note-row create (formula validated on create), list, evaluate - ADR-020 formula grammar (mandatory pre-code ADR) Tests: 22 formula parse/eval/safety cases (injection rejected), note engine account/subtotal/cross-note/circular/forward-ref/unknown-account, API create+ evaluate+invalid-formula rejection. 250 passed; gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * WIP: Phase 4 golden comparison (partial, interrupted) - services/golden: data-derived note aggregation (source col0/col25) vs official sheets, half-up million-rial rounding, discrepancies writer (ADR-021) - statement_build: ALL_STATEMENTS constant (BS/IS/CF/EQ) - test_golden: real-data BS match + all-4 build (test run interrupted, unverified) Saved as WIP per owner instruction before priority architecture fixes. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(money): prove P-02 no-silent-rounding with exhaustive evidence (audit #1) - ADR-012 revised: exhaustive probe of BOTH ledgers (457,074 rows, 6 money columns) confirms zero fractional rial; scale-0 is lossless. Clarifies .to_integral_value() is a DETECTOR (raises on fractional), never a rounder; round_half_up is display-only. - 7 regression tests: fractional text/boundary rejected (not rounded), fractional through ORM and CSV import fail loudly (StatementError wrapping ValueError). No storage behavior change needed — the fail-loud design already satisfies P-02. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(ledger): store RAW rows for drill-down, aggregate in compute layer (audit #2, D3/P-01) - ledger_import: one LedgerBalance per source row (no import-time aggregation); source_row preserved so every figure traces to file/sheet/row (D3) - LedgerBalance uniqueness -> (year_id, source_document_id, source_row, import_version) - NEW services/ledger_aggregate: account-level totals via exact Decimal summation in the compute layer (latest import version) - unknown_accounts now aggregates raw rows by account (dedupe + row_count) - Migration 20261203_05 swaps the constraint on existing DBs + reinstalls triggers; fresh DBs get it from the live model. Round-trip verified, triggers preserved. - Test updated: duplicate accounts stored as 2 raw rows, aggregated in service. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(approval): make C-03 enforcement explicit + hard ERROR gate (audit #3, D5) - approve_year loads rows AND mappings, passes both to evaluate_controls -> run_controls; C-03 (double mapping) and C-04 (unknown queue) always evaluated. Even one ERROR blocks Draft->Approved; no bypass path. - 13 negative/positive tests: double-mapping blocks via C-03, C-01/C-02/C-04 block, blocked approval writes no audit + stays Draft, non-draft/nonexistent rejected, clean ledger approves + audit chain valid, locked year immutable after approval, evaluate_controls proves mappings drive C-03/C-04 (incl. valid 100% split). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(services): mypy-clean services + generic golden columns + negative tests (audit #4) - Type-annotate all services so mypy passes (dict/tuple generics, cast, isinstance AST walks, typed sort key, renamed shadowed variable). - golden: resolve note/year/statement-balance columns BY HEADER NAME (1403 and 1404 ledgers have different layouts); fixes 1403 comparison, keeps it generic. - mapping_workflow negative tests: nonexistent carry-forward target, inactive accounts excluded, raw-row aggregation in queue, empty mapping workbook rejected. mypy services+domain clean; golden 1403+1404 real-data tests pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci: frontend gates (eslint/tsc/vitest/Playwright) + mypy services (audit #4, §14) - backend-ci: add 'Mypy (services)' gate (services now type-clean). - frontend-ci: eslint, tsc --noEmit, vitest, vite build, and Playwright e2e (chromium) with report artifact. - frontend/: Vite+React+TS RTL scaffold (Phase 5 foundation) with unit test (App.test.tsx), e2e specs (e2e/app.spec.ts), eslint flat config, tsconfig, playwright.config.ts, package-lock.json. Local: lint/tsc/vitest/build pass; playwright --list validates 2 specs. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * chore: drop unused import in approval gate test (ruff F401) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs: record Phases 1-4 + owner priority fixes in status/log (§0) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(import): tolerant real-ledger import + statement-balance capture (Phase 4/5) - Tolerant parse path (XLSX+CSV): reclassified rows with empty OPENING/Debit/ Credit/CLOSING are kept with exact zero; signed مانده صورت مالی stored as LedgerBalance.statement_balance (nullable Rial BIGINT, migration 20261203_06). Non-numeric money cells are skipped + reported (fail-loud, never invented); identity fields stay strictly required. Strict mode unchanged. - statement_build uses the effective balance: statement_balance rows contribute their pre-signed figure directly (reproduces Phase-4 golden); ordinary closing rows get the ADR-013 section sign. drill_down exposes effective/statement balance. - API upload uses tolerant import and returns skipped_rows for transparency. - 4 new tests (reclassified kept, anomaly skipped+reported, strict fails loud, statement_balance drives build + raw-row drill-down). Full suite: 285 passed. Real-data proof: source_1404.xlsx -> 131,280 raw rows imported, 4 anomalies reported; note->map->build->drill-down traced to exact source rows. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): Phase 5 RTL workbench — setup/import/mapping/statements/drill-down/approval - Vite dev proxy forwards relative /api to FastAPI (no browser localhost calls); allowedHosts for the Arena live preview. - Typed API client + types; Persian-locale rial formatting. - Components: CompanySetup, LedgerUpload, MappingPanel (unknown-account queue, note creation, mapping import/export), StatementView (BS/IS/CF/EQ tabs, build, per-line drill-down), DrillDown (source file/sheet/row lineage), ApprovalPanel (controls + hard approval gate). - Unit tests (11): format, api client, CompanySetup, DrillDown, App shell. Playwright e2e: app smoke + full workflow (backend-gated via ARAM_E2E_BACKEND). - Gates: eslint/tsc/vitest/build pass; mypy services clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(output): Phase 6 reviewable statement outputs (XLSX + JSON) with lineage - statement_export: latest-version BS/IS/CF/EQ + evaluated notes + full source lineage (file/SHA-256/sheet/row) as RTL XLSX (Summary/per-statement/Note/Lineage) and structured JSON. Exact integer-rial preserved; million-rial display-only (half-up, ADR-012). No new dependency (openpyxl). ADR-022. - API GET /years/{id}/statements/export?format=xlsx|json; workbench download buttons. - 3 tests (JSON exact rial + lineage, XLSX sheets/values, JSON serializable). Real-data proof: year 1404 export -> BS/IS, 340 lineage rows, Note 10; XLSX sheets Summary/BS/IS/Note 10/Lineage. Full suite: 288 passed; mypy services clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(admin): Phase 7 users/roles, controlled reopen/lock, verifiable backup - User model + roles (admin/reviewer/preparer); PBKDF2-HMAC-SHA256 + per-user salt (stdlib, no plaintext, no network); require_role gate; first-user bootstrap. - Reopen/lock service: request->approve->reopen (LOCKED->APPROVED only with an approved request; ORM guard + DB trigger re-check, no bypass); lock APPROVED-> LOCKED; every step hash-chained audited. Migration 20261203_07 (round-trip OK). - Backup: consistent SQLite online-backup snapshot + source-store copy + SHA-256 manifest + audit-chain verification; verify_backup recomputes hashes + chain; tamper/non-empty-dest/broken-chain refused. ADR-023. - admin_api /api/v1: users, auth/login, audit(+verify), reopen/lock, backup(+verify) with 403 role gates. - 17 tests (users/auth/roles, reopen workflow + immutability, backup integrity + tamper, admin API bootstrap/login/gate/audit). Full suite: 305 passed. Live proof: bootstrap->admin, login, audit chain valid, backup+verify (1 source file), preparer backup -> 403. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): admin panel — login, audit verify, lock/reopen, backup/verify Phase 7 workbench surface: role-gated login, audit-chain check, year lock, reopen request->approve->reopen, and backup create/verify against the admin API. Gates: eslint/tsc/vitest/build pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(desktop): Phase 8 offline desktop entrypoint + reproducible PyInstaller recipe - desktop.py: per-user data dir, idempotent SQLite schema + D-07 triggers, FastAPI + bundled React workbench served on 127.0.0.1 only (zero network). database.reconfigure rebinds the shared engine to the local file at launch. - packaging/aram.spec (one-folder Aram.exe) + build_desktop.py (npm build -> PyInstaller) + README. Binary is a build artifact, never committed (§19). ADR-024. - 3 tests: DB init creates schema+triggers (idempotent), desktop app serves health + API end-to-end, data-dir override. Full suite: 308 passed; mypy clean. Live proof: desktop app serves bundled RTL workbench at / (200) + health ok. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(e2e): update smoke spec to the workbench (company setup form, not counter) The Phase 5 workbench replaced the demo counter; the Playwright smoke test now asserts the RTL heading + company setup form (frontend-only, no backend needed). Fixes the Frontend CI e2e job. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs+uat: Phase 9 real-data UAT script + status/log for Phases 5-9 (§0/§18) scripts/uat_real_data.py exercises the full persistent pipeline on source_1404 (read-only): import->auto-map->build->golden reconcile->approval gate->export-> backup->audit. Records reviewable evidence; report is not a committed artifact. PROJECT_STATUS + PROJECT_LOG updated with Phases 5-9 and UAT results. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(review): role-gate approve + editable notes/mappings/rows (5-agent review) Findings from the deep compliance review: - F3-1: API /approve now enforces reviewer/admin role once local users exist (consistent with /lock and /reopen); bootstrap/dev (no users) stays open; the C-01..C-04 ERROR gate always applies. +2 negative/positive tests. - F2-1: add PUT/DELETE for notes, mappings, note rows + GET list notes/mappings, satisfying the owner's editable codes/accounts/notes/subnotes requirement. Draft-guarded; D-07 immutability translated to HTTP 409; note delete refuses while mappings/statement lines reference it (rows cascade). +9 tests incl. locked-year edit refusal. - F5-1: document python-multipart upload dependency in ADR-018. Full suite: 319 passed; mypy services clean; ruff clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): notes/mappings manager (edit/delete) wired to the editing API NotesManager lists notes (inline title edit + delete) and mappings (delete), refreshing after each change. eslint/tsc/vitest/build pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs(review): 5-pass booklet compliance review report + log (§0) Records the five reviewer mandates, evidence, findings (F2-1/F3-1/F5-1 fixed, O5-1 noted) and per-agent verdicts. All passes PASS after fixes; 319 tests green. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * B0: booklet reference + lightweight-process reconciliation - docs/booklet/BOOKLET_v1.0.md + MANIFEST.json (original PDF SHA-256 anchor; ADR-025) - PROJECT_STATUS.md rewritten to GitHub reality (Phases 0-9 MERGED @46253c9, 319 tests, post-merge CI; stale V1-01/unmerged rows removed; D-08 closed) - 14 root analytical docs git mv -> docs/archive/ (+ index); no new root analytical doc (booklet §0.5) - AGENTS.md <-> §0.5 conflict resolved: handoff cadence per-category, lightweight-process bullets (ADR-026) - docs/discrepancies.json skeleton {row,our_amount,official_amount,cause,evidence,year} (OD-08; B8 populates) - docs/PROJECT_LOG.md + LATEST_HANDOFF.md refreshed (end-of-category) - data/ + samples/ tree hashes unchanged (docs/process only) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0: booklet 2 course correction (بخش الف) - الف‌1: remove Pyodide/Pages/CDN browser edition (webapp/, docs built output, docs/vendor wheels, scripts/build_webapp.py, pilot-pages.yml); recoverable from history @46253c9; ADR-028 - booklet 2 v2.0 verbatim -> docs/booklet/BOOKLET_v2.0.md + MANIFEST.json (SHA-256 anchor); ADR-027 (C0..C10 supersedes B framing; OD-09..14; generality rule; databansoft not reachable) - الف‌6: docs/PR_TRIAGE.md (ADOPT #81/#89/#92; CLOSE NO-GO #82/#88; SUPERSEDED #90/#91 + #22-#80) - الف‌4/5 + ب‌1 + §16: PR honesty/size, generality grep, offline/read-only/no-plaintext rules in AGENTS.md - الف‌2/3 verified: persistent core (domain+statement_api/admin_api on LedgerBalance) is main path; phase 0/1 + golden merged @46253c9 - PROJECT_STATUS.md -> C0..C10 roadmap + C0 progress + الف‌7; PROJECT_LOG + handoff refreshed - data/ + samples/ tree hashes unchanged; backend 319 passed, frontend lint/tsc/vitest(11)/build green (no regression) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0 addendum: booklet 2 appendix revision (owner) + ADR-029 - appendix replaced verbatim: Databan catalog studied by owner (marketing, unverified); positioning = independent pluggable product + Host Integration API; accepted elements 1-10; rejected scope; legal restriction - OD-09 REVISED: pyodbc-first (existing ODBC driver, Windows+SQL Server), python-tds fallback (ADR-027 updated, ADR-029) - ADR-029: positioning, OD-14 capability comparison, element->phase mapping (C4-C9/C11), C11 AI constraints (never generates numbers) - PROJECT_STATUS: C5/C7/C8/C9 scope notes + C11 row + positioning; PROJECT_LOG + handoff updated - BOOKLET_v2.0.md re-anchored: SHA-256 79618ddd...; MANIFEST.json revision history kept - docs-only addendum; code identical to tested C0 tree (backend 319 passed, frontend green); data/ + samples/ unchanged Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0 remediation: populate discrepancies.json (الف‌7) + record review findings - الف‌7 met: golden.compare_year(1404) re-run -> 28/9 matched/19 diffs; docs/discrepancies.json populated one-by-one with cause + reproducible evidence + source/official SHA-256 (16 caused: 8 exact-magnitude sign flips ADR-013, CF note reuse, absent/underived notes; 3 under_investigation: IS 6/8/9 = bugs until proven D1); EQ official parsing gap recorded - ADR-028: owner's explicit experiment/browser-edition instruction recorded; Arena single-branch block reported; preservation guaranteed via tag v1.0.0 -> 46253c9 - PROJECT_STATUS: review deviations tracked (forgeable actor auth C8, 4/15 controls C3, desktop create_all bypasses Alembic C9, PR #96 discipline violation historical, booklet-1 extraction artifacts disclosed); الف‌7 marked MET - Fresh evidence: backend 319 tests exit 0; D-04/D-05 normalization 17 passed - docs-only; data/ + samples/ trees unchanged; no second PR (owner directive) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --------- Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 4, 2026 at 10:55 UTC f2e6da5e7ade3c851584008d590c588894d4c9c3
50 files changed +1823 -4892
.github/workflows/pilot-pages.yml deleted
-44
@@ -1,44 +0,0 @@
1 -name: Deploy Pilot Workbench (browser edition) to Pages
2 -
3 -# Manual trigger only: GitHub allows enabling a Pages site solely by the repo
4 -# owner (Settings -> Pages -> Source: GitHub Actions). Once enabled, dispatch
5 -# this workflow to publish docs/. The app is meanwhile served permanently via
6 -# commit-pinned CDN URLs (see webapp/README.md).
7 -on:
8 - workflow_dispatch:
9 -
10 -permissions:
11 - contents: read
12 - pages: write
13 - id-token: write
14 -
15 -concurrency:
16 - group: pilot-pages
17 - cancel-in-progress: true
18 -
19 -jobs:
20 - deploy:
21 - runs-on: ubuntu-latest
22 - environment:
23 - name: github-pages
24 - url: ${{ steps.deployment.outputs.page_url }}
25 - steps:
26 - - name: Checkout
27 - uses: actions/checkout@v4
28 -
29 - - name: Rebuild browser bundle from engine sources
30 - run: python scripts/build_webapp.py
31 -
32 - - name: Configure Pages (auto-enable if needed)
33 - uses: actions/configure-pages@v5
34 - with:
35 - enablement: true
36 -
37 - - name: Upload site artifact
38 - uses: actions/upload-pages-artifact@v3
39 - with:
40 - path: docs
41 -
42 - - name: Deploy to GitHub Pages
43 - id: deployment
44 - uses: actions/deploy-pages@v4
AGENTS.md
+8 -3
@@ -15,9 +15,13 @@ Never treat a local file, task summary, or agent report as proof that a branch,
15
16 ## Work rules
17
18 -- Use one dedicated branch and one focused PR per task.
18 +- Use one dedicated branch and one focused PR per task (one phase task per PR).
19 +- Keep each PR to at most ~1,500 changed lines, excluding tests and generated data; do not combine multiple phases in one PR (booklet 2 الف‌5).
20 +- Make every PR body match `git diff --stat` and the real head exactly (file count, lines, tests, SHA); a PR whose description does not match reality is not reviewable (booklet 2 الف‌4).
21 - Modify only explicitly allowed paths.
22 - Do not merge your own PR.
23 +- Keep the product general: no company name, account code, heading, or industry constant in source code; company/industry-specific content lives only in `packs/` and the database, enforced by an automated grep test (booklet 2 ب‌1).
24 +- No runtime network dependency; the tool runs fully offline (booklet 2 §16). Source-database connectors are read-only; never write to a source database; never store secrets in plaintext; never run a custom query without parse-validation (booklet 2 ب‌5/§16).
25 - Do not incorporate work from closed PR #7 except when a task explicitly identifies the exact feature and files to recover.
26 - Do not modify canonical XLSX/PDF, `data/`, databases, or financial source values unless the task is an approved data-change task with hashes and recovery steps.
27 - Do not commit ZIP, EXE, build output, secrets, credentials, caches, or local databases unless explicitly required by an approved artifact task.
@@ -38,11 +42,12 @@ Never treat a local file, task summary, or agent report as proof that a branch,
42 Every meaningful PR must:
43
44 - update `PROJECT_STATUS.md` when current state changes;
41 -- append a complete entry to `docs/PROJECT_LOG.md`;
45 +- append a short entry to `docs/PROJECT_LOG.md` (lightweight process, booklet §0.5: code and tests grow, not documentation);
46 +- create no new root-level analytical document; historical root analytical docs live in `docs/archive/` (booklet §0.5; see ADR-026);
47 - add a new ADR instead of silently rewriting an accepted decision;
48 - satisfy `docs/ACCEPTANCE_POLICY.md`;
49 - use `.github/pull_request_template.md`;
45 -- update `docs/handoff/LATEST_HANDOFF.md` after every meaningful completed or rejected step so a successor can resume without chat history;
50 +- update `docs/handoff/LATEST_HANDOFF.md` at the end of each B-category (B0…B12), and on any governance change, so a successor can resume without chat history — not after every commit/step (booklet §0.5 lightweight process; see ADR-026);
51 - keep `docs/handoff/MASTER_RECOVERY_PROMPT.md` stable unless the governance process itself changes;
52 - keep `docs/handoff/CHATGPT_BOOTSTRAP_PROMPT.txt` as the saveable entry point for a successor chat.
53
PROJECT_STATUS.md
+78 -114
@@ -5,154 +5,118 @@
5 ## Repository baseline
6
7 - Repository: [davoodmehraban89/Aram](https://github.com/davoodmehraban89/Aram)
8 -- Accepted branch: source-data-cleanup
9 -- Recorded accepted control event: [PR #18](https://github.com/davoodmehraban89/Aram/pull/18), reviewed head `fcbeb7387218e9ab294318ae462ed59de717fc95`, squash merge [f213d321ff4cd7d3d6fa65ba78dc48f090ee846b](https://github.com/davoodmehraban89/Aram/commit/f213d321ff4cd7d3d6fa65ba78dc48f090ee846b)
10 -- Durable post-merge acceptance record: [PR #19](https://github.com/davoodmehraban89/Aram/pull/19), reviewed head `b9059592409606a0a4f11a71c30778cff158b6b6`, squash merge [77f9f595ccfe67a87b11024ff0f6143629dba438](https://github.com/davoodmehraban89/Aram/commit/77f9f595ccfe67a87b11024ff0f6143629dba438)
11 -- Before starting new work, fetch the live `source-data-cleanup` head; this record intentionally avoids a self-referential current-head claim
8 +- Accepted branch: `source-data-cleanup`
9 +- **Live accepted head: `46253c94405abd065dfc5e8cf080b295cb83cde4`** — squash merge of [PR #96](https://github.com/davoodmehraban89/Aram/pull/96), merged 2026-12-03T15:22:02Z (owner final acceptance).
10 +- **Release tag `v1.0.0`** points to `46253c94405abd065dfc5e8cf080b295cb83cde4` (owner-authorized, created pre-mission). The implementation author does not tag (§19); no further tagging without owner directive.
11 +- Post-merge CI on the accepted head: [Backend CI #47137691800](https://github.com/davoodmehraban89/Aram/actions/runs/47137691800) ✅ and [Frontend CI #47137691857](https://github.com/davoodmehraban89/Aram/actions/runs/47137691857) ✅.
12 - Product objective: a controlled, auditable accounting and financial-statement workflow that preserves canonical source data.
13 +- Authoritative work orders: booklet 1 v1.0 ([`docs/booklet/BOOKLET_v1.0.md`](docs/booklet/BOOKLET_v1.0.md), ADR-025) and **booklet 2 v2.0** ([`docs/booklet/BOOKLET_v2.0.md`](docs/booklet/BOOKLET_v2.0.md), ADR-027 — course correction + general-platform architecture; supersedes conflicting parts of booklet 1). Integrity anchored by SHA-256 in [`docs/booklet/MANIFEST.json`](docs/booklet/MANIFEST.json).
14
15 ## Status vocabulary
16
17 | State | Meaning |
18 |---|---|
19 | VERIFIED_AND_MERGED | Present on the accepted branch with Git evidence. |
19 -| VERIFIED_BUT_UNMERGED | Present in a remote commit or PR, but not accepted. |
20 -| PRESENT_BUT_UNVERIFIED | Present, but required tests or evidence are missing. |
21 -| CLAIMED_BUT_NOT_PROVEN | Reported by an actor, with no sufficient GitHub evidence. |
22 -| NOT_IMPLEMENTED | Required capability is absent. |
20 | IN_PROGRESS | Work is in an open PR and is not accepted. |
21 +| NOT_IMPLEMENTED | Required capability is absent. |
22 | BLOCKED | Work cannot proceed until the recorded blocker is resolved. |
23
26 -## Verified state
24 +## Accepted state — booklet Phases 0–9 (all MERGED via PR #96)
25
28 -| Area | State | Evidence / note |
29 -|---|---|---|
30 -| Phase 1B-1 source inventory | VERIFIED_AND_MERGED | [PR #1](https://github.com/davoodmehraban89/Aram/pull/1) |
31 -| Phase 1B-2 audit corrections | VERIFIED_AND_MERGED | [PR #4](https://github.com/davoodmehraban89/Aram/pull/4) |
32 -| Phase 2A backend foundation | VERIFIED_AND_MERGED | [PR #6](https://github.com/davoodmehraban89/Aram/pull/6) |
33 -| One-file model refactor | VERIFIED_AND_MERGED | [PR #8](https://github.com/davoodmehraban89/Aram/pull/8) |
34 -| Project-control foundation | VERIFIED_AND_MERGED | [PR #10](https://github.com/davoodmehraban89/Aram/pull/10) |
35 -| Phase 2B ingestion foundation | VERIFIED_AND_MERGED | [PR #12](https://github.com/davoodmehraban89/Aram/pull/12), squash merge 7b5bd79b760d534dad34b3162f770e838616ebe9 |
36 -| Phase 2B control reconciliation | VERIFIED_AND_MERGED | [PR #13](https://github.com/davoodmehraban89/Aram/pull/13), squash merge 7c7533ee87146dc8fc78b46ebf423be55532c7eb |
37 -| Gate 2A Pilot workbook contract/preflight | VERIFIED_AND_MERGED | [PR #15](https://github.com/davoodmehraban89/Aram/pull/15), reviewed head 74b6a6397a2a2c9199a5c7bcf818bb661b2ebe06, squash merge 4ab54f4a3cf666827fa1ed30c4e43259ea79f2d4, [Backend CI #24](https://github.com/davoodmehraban89/Aram/actions/runs/32712900800) |
38 -| V1-01 safety-gate hardening | IN_PROGRESS | Draft [PR #21](https://github.com/davoodmehraban89/Aram/pull/21) from exact base `b1ddee87d31ee73b3a5aeac8f9953d0a604c206a`; independently reviewed implementation head `700d800dbd9c657f6bd510faafedcbde4847fafd`; CI-verified stabilized candidate `b3dc8b3a18934ffe63f615e4f650248be21a5f9c`; [Backend CI #39](https://github.com/davoodmehraban89/Aram/actions/runs/33015277194) succeeded with 67 tests, migration round-trip, and compile after broadening one reparent-rejection assertion to accept either valid protection message; code, scope, and protected-data boundary remain unchanged; final independent acceptance is pending this durable-document reconciliation |
39 -| Post-Gate-2A control reconciliation | VERIFIED_AND_MERGED | [PR #18](https://github.com/davoodmehraban89/Aram/pull/18), reviewed head `fcbeb7387218e9ab294318ae462ed59de717fc95`, squash merge `f213d321ff4cd7d3d6fa65ba78dc48f090ee846b`; documentation only |
40 -| Durable post-merge acceptance record | VERIFIED_AND_MERGED | [PR #19](https://github.com/davoodmehraban89/Aram/pull/19), reviewed head `b9059592409606a0a4f11a71c30778cff158b6b6`, squash merge `77f9f595ccfe67a87b11024ff0f6143629dba438`; documentation only |
41 -| Role-based project operating model | VERIFIED_AND_MERGED | Permanent responsibilities and current assignments are defined in `docs/handoff/MASTER_RECOVERY_PROMPT.md` and ADR-011; introduced through [PR #20](https://github.com/davoodmehraban89/Aram/pull/20) |
42 -| Parallel V1 prototype | VERIFIED_BUT_UNMERGED | Closed, unmerged [PR #7](https://github.com/davoodmehraban89/Aram/pull/7); reference/recovery source only |
43 -| Superseded Phase 2B candidate | VERIFIED_BUT_UNMERGED | Closed, unmerged [PR #9](https://github.com/davoodmehraban89/Aram/pull/9) |
44 -| Duplicate Gate 2A candidate | VERIFIED_BUT_UNMERGED | [PR #16](https://github.com/davoodmehraban89/Aram/pull/16) closed without merge on 2026-08-25; no content accepted |
45 -| Gate 2B Mapping foundation candidate | VERIFIED_BUT_UNMERGED | [PR #17](https://github.com/davoodmehraban89/Aram/pull/17) closed without merge on 2026-08-25; stale-base reference only; no content accepted |
46 -| Official V1 release | NOT_IMPLEMENTED | No accepted tag, release, retained release artifact, ZIP, or EXE |
47 -| Comprehensive Mapping Excel import/export | NOT_IMPLEMENTED | Mandatory before V1 acceptance |
48 -| Unknown-account queue and mapping carry-forward | NOT_IMPLEMENTED | Mandatory before V1 acceptance |
49 -| Note and sub-note mapping workflow/UI | NOT_IMPLEMENTED | Mandatory before V1 acceptance |
50 -| Minimal Pilot application and reviewable output | NOT_IMPLEMENTED | Required before packaging |
51 -| Reproducible Windows package and clean-environment test | NOT_IMPLEMENTED | Required before V1 acceptance |
52 -
53 -## Accepted product capabilities
54 -
55 -- Read-only source inventory and workbook audit evidence.
56 -- Persistent backend/data-model foundation with fiscal-year mutation controls.
57 -- Metadata-only source registration, structural XLSX inspection, and typed in-memory ledger parsing.
58 -- Governed Pilot workbook v0.1 contract, reproducible blank template generator, and deterministic read-only preflight.
59 -- Approved Pilot template path: samples/Aram_Pilot_Input_and_Mapping_Template_v0.1.xlsx.
60 -- Independently verified template SHA-256: e14a7feb80a216d79ed9cb6dde2b0df3e55317f3da6b26efc77f7118f4702b6f.
61 -
62 -The accepted branch does not include PR #7 desktop/release work, PR #16 alternate Pilot implementation, or PR #17 Mapping implementation. Green CI on an unmerged stale-base PR is not acceptance evidence.
63 -
64 -## Current risks and blockers
65 -
66 -- The accepted branch is not protected by GitHub branch protection.
67 -- The accepted branch still permits direct identity mutation/deletion of approved or locked fiscal years and parent-company deletion; the V1-01 candidate fixes this but is not accepted yet.
68 -- The accepted Pilot preflight can still accept targetless or structurally invalid mappings and can ignore a declared closing-delta mismatch; the V1-01 candidate fixes this but is not accepted yet.
69 -- The accepted root `index.html` is still a disconnected hard-coded prototype; the V1-01 candidate replaces it with an explicit quarantine page.
70 -- PR #17 was closed without merge; its stale-base 12-file diff is reference material only, and its narrative listed only 9 files.
71 -- PR #17 CI was green on its own stale head, but compatibility with accepted Gate 2A was never proven.
72 -- Binary execution, release provenance, and clean Windows verification do not exist.
73 -- Mapping, notes/sub-notes, Pilot UI, and end-to-end user acceptance remain incomplete.
74 -
75 -## Next approved action
76 -
77 -1. Publish this two-file durable-document reconciliation on Draft PR #21; [Backend CI #39](https://github.com/davoodmehraban89/Aram/actions/runs/33015277194) succeeded on stabilized candidate `b3dc8b3a18934ffe63f615e4f650248be21a5f9c` with 67 tests, migration round-trip, and compile.
78 -2. The independent reviewer re-fetches the resulting documentation-only head, confirms that its comparison with `b3dc8b3a18934ffe63f615e4f650248be21a5f9c` changes only `PROJECT_STATUS.md` and `docs/handoff/LATEST_HANDOFF.md`, verifies the final workflow result, then marks the PR ready and squash-merges it.
79 -3. Only after V1-01 is accepted, start the first focused Gate 3 Mapping import/persistence task from the new accepted head.
80 -
81 -## Booklet v1.0 — Phase 0 (execution work order)
82 -
83 -Authoritative work order: «کتابچهٔ اجرایی تکمیل Aram» v1.0 (base head `7dc864fd032f0c4ae4d650d89304a01286a6d914`, PR #21 merge). Branch `arena/094f314c-aram`. Per §17 the agent resolves ambiguities by default + real-data proof + ADR and never queries the owner; the owner's sole role is Phase-9 final acceptance.
84 -
85 -| Debt | State | Evidence |
26 +All Phase 0–9 work below is **VERIFIED_AND_MERGED** on `source-data-cleanup` at head `46253c9` (squash of PR #96). Evidence is the merged head plus post-merge CI; per-commit references are the pre-squash implementation history on `arena/094f314c-aram`.
27 +
28 +| Phase / capability | State | Evidence |
29 |---|---|---|
87 -| D-01 LedgerBalance model | VERIFIED_BUT_UNMERGED | commit `a3c330b`; exact-rial round-trip + aggregation tests |
88 -| D-02 controls in preflight | VERIFIED_BUT_UNMERGED | commit `8f2f902`; C-01..C-04 preflight tests |
89 -| D-03 Rial money column | VERIFIED_BUT_UNMERGED | commit `a3c330b`; BIGINT storage >2^53 via ORM; ADR-012 |
90 -| D-04 numeric code normalization | VERIFIED_BUT_UNMERGED | commit `ac565e9`; integral-numeric exact, leading zeros preserved |
91 -| D-05 Persian header matching | VERIFIED_BUT_UNMERGED | commit `ac565e9`; normalize_fa header matching |
92 -| D-06 source bytes + CSV | VERIFIED_BUT_UNMERGED | commit `a661423`; content-addressed store + CSV encodings/delimiters |
93 -| D-07 immutability + audit + reopen | VERIFIED_BUT_UNMERGED | commit `00ca58e`; raw-SQL locked-year guards, hash chain, ADR-016 |
94 -| D-08 status/log refresh | IN_PROGRESS | this entry |
95 -| D-09 git-history rewrite | BLOCKED | owner-only; requires explicit owner approval (§19) |
96 -| D-10 hierarchy mapping | VERIFIED_BUT_UNMERGED | commit `ac565e9`; ADR-014 (general=kol, subsidiary=حساب) |
97 -| D-11 inspection guards | VERIFIED_BUT_UNMERGED | commit `ac565e9`; max_column None guard |
98 -| D-12 CI quality gates | VERIFIED_BUT_UNMERGED | commit `8412c56`; ruff/mypy/coverage/pip-audit/PG matrix; ADR-017 |
30 +| Phase 0 debts D-01..D-07, D-10..D-12 (LedgerBalance, controls C-01..04, rial money, code/header normalization, source store, immutability+audit+reopen, hierarchy, inspection guards, CI gates) | VERIFIED_AND_MERGED | head `46253c9`; ADR-012/013/014/016/017 |
31 +| Phase 1 statements + drill-down | VERIFIED_AND_MERGED | head `46253c9`; ADR-018 |
32 +| Phase 2 mapping import/export | VERIFIED_AND_MERGED | head `46253c9`; ADR-019 |
33 +| Phase 3 note formula engine (AST, no eval) | VERIFIED_AND_MERGED | head `46253c9`; ADR-020 |
34 +| Phase 4 golden comparison (1403+1404) | VERIFIED_AND_MERGED | head `46253c9`; ADR-021 |
35 +| Phase 5 RTL React workbench + Playwright | VERIFIED_AND_MERGED | head `46253c9`; Frontend CI #47137691857 |
36 +| Phase 6 reviewable outputs (XLSX+JSON, exact rial + lineage) | VERIFIED_AND_MERGED | head `46253c9`; ADR-022 |
37 +| Phase 7 users/audit/reopen/backup (roles, PBKDF2, migration 07) | VERIFIED_AND_MERGED | head `46253c9`; ADR-023 |
38 +| Phase 8 offline desktop packaging (loopback entrypoint + PyInstaller recipe) | VERIFIED_AND_MERGED | head `46253c9`; ADR-024; no binary committed (§19) |
39 +| Phase 9 UAT + release prep (`scripts/uat_real_data.py`) | VERIFIED_AND_MERGED | head `46253c9`; UAT evidence below |
40 +| Review fixes: approve role gate, note/mapping edit/delete endpoints, NotesManager UI, python-multipart ADR | VERIFIED_AND_MERGED | head `46253c9`; `docs/reviews/BOOKLET_COMPLIANCE_REVIEW.md` |
41 +| D-08 status/log refresh | VERIFIED_AND_MERGED (this B0 PR) | this entry |
42 +| D-09 git-history rewrite | BLOCKED | owner-only; requires explicit owner directive (§19); tracked in B12 |
43 +
44 +**Test/quality evidence at the accepted head:** backend **319 tests passed** (full local suite); Backend CI #47137691800 green (SQLite + PostgreSQL migration round-trips, ruff, mypy domain-strict + services, coverage, pip-audit); Frontend CI #47137691857 green (eslint, tsc, vitest, build, Playwright). No canonical `data/` or `samples/` file changed.
45
100 -Phase-0 local evidence: 201 tests passed; ruff clean; mypy domain strict clean; coverage total 92% / domain 97%; pip-audit no known vulnerabilities; SQLite migration up/down/up clean. PostgreSQL migration path is exercised by the CI matrix (no local PG). Real-data evidence (source_1404.xlsx, 252,898 rows): debit-positive C-01 holds 252,892/252,898; Σdebit=Σcredit=10,823,163,409,740,108; OD-01 refuted (T1..T4 concat ≠ حساب), ADR-014 adopted. No canonical `data/` or `samples/` file changed.
46 +### Historical control events (reference)
47
102 -ADRs added: 012 (money scale/rounding), 013 (sign contract), 014 (T1..T4 hierarchy), 016 (reopen/immutability), 017 (CI gates/tooling).
48 +Earlier accepted control events remain part of history: PR #1/#4/#6/#8/#10/#12/#13/#15/#18/#19/#20/#21 (see `docs/PROJECT_LOG.md`). Closed-unmerged candidates PR #7/#9/#16/#17 were never accepted and are reference only. The stale "V1-01 IN_PROGRESS" and "VERIFIED_BUT_UNMERGED" phase rows from prior snapshots are superseded: that work is now merged in PR #96.
49
104 -## Booklet v1.0 — Phases 1–4 + owner priority fixes (execution work order)
50 +## Active mission — booklet 2 course correction + C0…C10 roadmap
51
106 -Continuation on branch `arena/094f314c-aram` (base `7dc864fd`). Per §17 the agent resolves by default + real-data proof + ADR and never queries the owner.
52 +Booklet 2 v2.0 («اصلاح مسیر و معماری نهایی Aram», [`docs/booklet/BOOKLET_v2.0.md`](docs/booklet/BOOKLET_v2.0.md), ADR-027; appendix revised by owner 2026-12-03 — positioning + Host Integration API + accepted elements, ADR-029) **supersedes** the conflicting parts of booklet 1 and the earlier B0…B12 framing; it defines the governing roadmap **C0…C10 + optional C11** below. Positioning: Aram is an independent, pluggable financial-statement preparation/control/audit engine with a Host Integration API (REST + permissions) for future embedding; government systems (مودیان/IMED/trade), bank-invoice processing, form builder/cartable are rejected scope; messenger bots for financial data prohibited (ADR-029). One focused PR per phase task, ≤ ~1,500 changed lines excluding tests/generated data (الف‌5); PR body must match `git diff --stat` + real head (الف‌4). Executor only; independent reviewer separate; no "done" without evidence (§19). Ambiguities closed via booklet 2 §14 (default + proof + ADR, OD-01..OD-14), never by querying the owner. `data/` + `samples/` read-only with before/after tree-hash evidence per PR. No merge, no tag, no runtime network, no company-specific code (§16).
53
108 -| Phase / item | State | Evidence |
54 +| Phase | Scope (summary) | State |
55 |---|---|---|
110 -| Phase 1 statements + drill-down | VERIFIED_BUT_UNMERGED | commit `9c33586`; build_statements BS/IS, drill_down source{filename,file_hash,sheet,row} |
111 -| Phase 2 mapping import/export | VERIFIED_BUT_UNMERGED | commit `cfbd879`; mapping_io Mappings sheet, fail-closed, idempotent |
112 -| Phase 3 note formula engine | VERIFIED_BUT_UNMERGED | commit `9fba3c6`; AST formula (no eval), acct/row/note/sum/abs, cycle detection |
113 -| Phase 4 golden comparison | VERIFIED_BUT_UNMERGED | commit `225a38c`; golden.py header-name columns; 1403+1404 real-data tests pass |
114 -| Fix 1 money/P-02 (ADR-012) | VERIFIED_BUT_UNMERGED | commit `a00b0dc`; 457,074 rows, 0 fractional rial; 7 guard tests |
115 -| Fix 2 raw-row drill-down (D3/P-01) | VERIFIED_BUT_UNMERGED | commit `f7c3b4a`; one LedgerBalance per source row; ledger_aggregate service; migration 20261203_05 round-trip |
116 -| Fix 3 approval gate (D5/C-03) | VERIFIED_BUT_UNMERGED | commit `1844a62`; evaluate_controls explicit; hard ERROR gate; 13 tests |
117 -| Fix 4 tests + CI (D-12/§14) | VERIFIED_BUT_UNMERGED | commits `225a38c`,`be08192`; mypy services gate; frontend eslint/tsc/vitest/Playwright |
118 -| Phase 5 UI + Playwright | VERIFIED_BUT_UNMERGED | commits `fa64baf`,`77fbe70`; RTL workbench (setup/import/mapping/statements/drill-down/approval/admin); eslint/tsc/vitest/build + Playwright gates |
119 -| Phase 6 reviewable outputs | VERIFIED_BUT_UNMERGED | commit `c4c37c0`; statement_export XLSX+JSON with exact rial + lineage; ADR-022 |
120 -| Phase 7 users/audit/reopen/backup | VERIFIED_BUT_UNMERGED | commit `e20572d`; roles+PBKDF2, controlled reopen/lock, verifiable backup; migration 20261203_07; ADR-023 |
121 -| Phase 8 desktop packaging | VERIFIED_BUT_UNMERGED | commit `ffc9888`; desktop entrypoint (127.0.0.1) + PyInstaller recipe; ADR-024; no binary committed (§19) |
122 -| Phase 9 UAT + release prep | VERIFIED_BUT_UNMERGED | `scripts/uat_real_data.py`; real-1404 UAT evidence below; tag v1.0.0 is the owner's post-acceptance action |
123 -
124 -Local evidence at head `dafb559`: backend **308 tests passed**; ruff clean; mypy domain strict + services clean; frontend lint/tsc/vitest/build pass; Playwright smoke + workflow specs valid. Migrations 20261203_05/06/07 up/down/up verified (SQLite). No canonical `data/` or `samples/` file changed.
125 -
126 -### Phase 9 UAT evidence (real source_1404.xlsx, read-only)
56 +| C0 | Course correction (بخش الف): browser-edition removal (الف‌1, ADR-028); persistent core is main path (الف‌2); phase 0/1 + golden 1404 verified (الف‌3); PR honesty/size rules (الف‌4/5); `docs/PR_TRIAGE.md` (الف‌6); exit criteria (الف‌7); booklet 1+2 references | IN_PROGRESS (this PR) |
57 +| C1 | Real vertical slice: 1404 ledger → LedgerBalance → C-01/C-02 → mapping → BS/IS → official reconciliation; golden green or diffs documented | NOT_IMPLEMENTED (core largely merged; re-verify on new model) |
58 +| C2 | Mapping + notes (booklet 1 phases 2–3) | NOT_IMPLEMENTED |
59 +| C3 | Four statements BS/IS/EQ/CF + all controls C-01..C-15 + two-year comparison + 1403 | NOT_IMPLEMENTED |
60 +| C4 | Connector framework + FileConnector: plugin model, manifest, Conformance Suite, Adapter, snapshot + reconciliation | NOT_IMPLEMENTED |
61 +| C5 | DB Connector: SQLite/PostgreSQL then SQL Server (**OD-09 revised: pyodbc-first**, python-tds fallback — ADR-029), test DB in CI, read-only source user | NOT_IMPLEMENTED |
62 +| C6 | Data packs + generalization: template/mapping packs; "second synthetic company" CI proof (ب‌1/ب‌8); document level only after C6 (OD-12) | NOT_IMPLEMENTED |
63 +| C7 | Full UI + outputs (booklet 1 phases 5–6 on new model): exact-rial Persian UI, PDF/XLSX; work center; print templates w/ letterhead + statutory ledgers (روزنامه/کل); Ctrl+K search; group dashboard; Host Integration API surface (ADR-029) | NOT_IMPLEMENTED |
64 +| C8 | Security + audit (booklet 1 phase 7 + ب‌10): pilot API auth, Argon2id, DPAPI vault, encrypted backup, plugin allowlist; multi-layer access (module←company←year←row/field); source-drift detection → «نیازمند بازبینی»; dry-run; nightly document audit C-16+ (optional, post-C6) | NOT_IMPLEMENTED |
65 +| C9 | Packaging + deployment (booklet 1 phase 8 + SBOM/signing): offline Windows, CI gates, large-file manifest; signed updates w/ auto-rollback + in-app backup/restore; Windows drift service | NOT_IMPLEMENTED |
66 +| C10 | Acceptance: Shadow Run on a real period of two companies + owner signature | NOT_IMPLEMENTED |
67 +| C11 | AI assistant (optional, OFF by default): understands questions only, **never generates numbers** — figures only from engine + approved CalculationRun with lineage; read-only, local/anonymized, audited (ADR-029) | NOT_IMPLEMENTED (optional) |
68 +
69 +### C0 progress (بخش الف)
70 +
71 +- **الف‌1 (browser removal):** DONE — `webapp/`, `docs/{app.js,index.html,bridge.py,styles.css,py,vendor}`, `scripts/build_webapp.py`, `.github/workflows/pilot-pages.yml` removed (ADR-028). Recoverable from history at `46253c9`; the named `experiment/browser-edition` branch is an owner action (Arena single-branch constraint).
72 +- **الف‌2 (persistent core main):** VERIFIED — `domain/{controls,money,hierarchy,formula,normalization}` + `statement_api`/`admin_api` on stored `LedgerBalance` is the product path; legacy in-memory pilot (`pilot_engine/store/api/editing`, `static/pilot`) retained as logic reference, secured in C8 then retired; exception-queue persistence tracked in C4.
73 +- **الف‌3 (phase 0/1 + golden 1404):** VERIFIED merged at `46253c9` — D-01..D-12, `test_golden.py`/`test_domain_controls.py`/`test_approval_gate.py`; real-1404 UAT evidence below.
74 +- **الف‌4/الف‌5 (PR honesty/size):** rules added to `AGENTS.md`; this PR body matches the diff.
75 +- **الف‌6 (PR triage):** DONE — `docs/PR_TRIAGE.md` (ADOPT #81/#89/#92; CLOSE NO-GO #82/#88; SUPERSEDED #90/#91 + #22–#80 backlog).
76 +- **الف‌7 (exit criteria):** MET — CI green at accepted head; `PROJECT_STATUS.md` consistent with head; golden 1404 freshly re-run (`golden.compare_year`): **28 comparisons, 9 matched, 19 differences** (BS 9/16, IS 0/6, EQ 0/0, CF 0/6), **all 19 recorded one-by-one in [`docs/discrepancies.json`](docs/discrepancies.json) with cause + reproducible evidence** (16 caused: 8 presentation-sign flips with exact magnitude, note-number reuse, absent/undderived CF notes; 3 under investigation = IS notes 6/8/9, treated as bugs until proven, D1). EQ official sheet yields 0 extractable note rows (C3 parsing gap, recorded). Real-1404 approval remains blocked by C-01/C-03/C-04 (fail-loud, correct).
77 +- **Appendix revision (owner, 2026-12-03 second message):** Databan catalog studied by owner (marketing, unverified; agent has no site access); positioning + Host Integration API recorded (ADR-029); **OD-09 revised to pyodbc-first** (python-tds fallback); accepted elements mapped to C4–C9/C11; C11 added (optional AI assistant, OFF by default, never generates numbers); rejected scope binding; booklet 2 markdown re-anchored (revision history in `MANIFEST.json`).
78 +
79 +## Phase 9 UAT evidence (real source_1404.xlsx, read-only)
80
81 `python scripts/uat_real_data.py --year 1404` on a fresh local DB:
82 - Import: **131,280 raw rows** preserved (4 anomalous rows skipped + reported).
83 - Auto-mapping from embedded note numbers: 22 notes, 244 mappings.
84 - Build: BS/IS/CF/EQ persisted; 1 unmapped ordinary account surfaced.
132 -- Golden reconciliation: core balance-sheet notes match official **rial-for-rial**
133 - (÷10⁶ half-up): 10→673,740,637 · 11→242,194 · 12-1→13,386,398 · 12-2→8,310,168 ·
134 - 13→6,839,535 · 14→11,273,650 · 15→19,951,136 (plus zero notes 17-1/17-2). Remaining
135 - BS/IS differences are surfaced as discrepancies (OD-08), never silently corrected.
136 -- Approval gate: correctly **blocks** on real-data control failures (C-01/C-03/C-04) —
137 - fail-loud, no bypass.
85 +- Golden reconciliation: core balance-sheet notes match official **rial-for-rial** (÷10⁶ half-up): 10→673,740,637 · 11→242,194 · 12-1→13,386,398 · 12-2→8,310,168 · 13→6,839,535 · 14→11,273,650 · 15→19,951,136 (plus zero notes 17-1/17-2). Remaining BS/IS differences are surfaced as discrepancies (OD-08), never silently corrected; B8 records them one-by-one in `docs/discrepancies.json`.
86 +- Approval gate: correctly **blocks** on real-data control failures (C-01/C-03/C-04) — fail-loud, no bypass.
87 - Export: XLSX (6.27 MB) + JSON with **158,050 lineage rows** (file/SHA-256/sheet/row).
88 - Backup: created + verified (hashes + audit chain); audit chain valid.
89
141 -ADRs added in this stretch: 021 (golden scale/columns), 022 (outputs), 023 (users/reopen/backup), 024 (desktop packaging).
90 +## Known gaps feeding the C-phases (honest residual risks)
91 +
92 +- **Authorization is forgeable (independent review, 2026-12-03):** roles derive from a client-supplied `actor` string in the request body, not a token/session; `"actor":"admin"` grants admin to anyone who reaches the API. Most endpoints (company create, ledger upload, mapping, export) are unguarded; with no users seeded, year approval is open to all. Loopback-only binding limits exposure on a single-user machine but this is serious on a server/shared machine and contradicts booklet 1 §13. `pilot_api.py` also exposes 17 unauthenticated routes. → **C8** (token/session auth + role guards + audit on every write; fail-closed).
93 +- `frontend/src/lib/format.ts` uses `Number(value)` (float risk) (C7).
94 +- **Only 4 of 15 controls implemented** (`domain/controls.py` = C-01..C-04); approval depends only on these, so a year with an unbalanced BS or note/statement mismatch can be approved. C-05..C-15 absent → **C3** (wire all controls into `run_controls` + approval gate; ERROR year unapprovable).
95 +- **Desktop install bypasses Alembic** (`desktop.py:62` `Base.metadata.create_all`); existing user DBs will not migrate on update → **C9** (replace with `alembic upgrade head` + migration round-trip test on an existing DB).
96 +- ImportRun/CalculationRun/LineageEdge/Adjustment/UnknownAccountQueue/carried_from_year_id/calculation_run_id refs absent; pilot exception queue not persisted in `domain/` (C1/C4).
97 +- `note_engine.acct()` is closing-only; statement_balance-only rows evaluate 0 in notes (C1/C3).
98 +- No connector framework / Source Adapter / snapshot reconciliation / packs yet; generality grep test pending (C4/C5/C6).
99 +- CI: `npm ci --no-audit`, coverage gate not 80/90, services mypy non-strict (C9).
100 +- Backup unencrypted; no DPAPI vault / plugin allowlist / SBOM yet (C8/C9).
101 +- Browser edition removed (C0); single reference UI = React workbench, developed in C7. Backend `static/pilot` legacy retained until C8.
102 +- Windows EXE not built; clean-machine install log + Shadow Run two-company + owner signature pending (C9/C10).
103 +- `docs/discrepancies.json` now records all 19 golden-1404 differences with cause+evidence (الف‌7 met); 3 IS magnitude mismatches remain under investigation (bugs until proven, D1) and build-vs-official comparison is added in C3.
104 +- **PR-discipline violation recorded (independent review):** merged PR #96 bundled all 10 phases in one PR (154 files, +24,327 lines ≈ 16× the الف‌5 cap), its body cited a stale head (`969f608` vs merged `babe829`), and it merged without independent review under a one-time owner waiver. Historical; cannot be un-merged. Booklet 2 الف‌4/الف‌5 now enforced in `AGENTS.md` for all future PRs.
105 +- Booklet 1 markdown is a token-reversal PDF extraction (ADR-025): RTL/English-code artifacts possible; the original PDF SHA-256 is the authoritative anchor. A faithful re-extraction awaits a docx original or a better bidi method (owner option).
106
143 -### Release procedure (owner, after independent review)
107 +## Release procedure (owner)
108
145 -The implementation author does **not** merge or tag (§19). After independent GitHub
146 -review approves PR #96 and it is merged into `source-data-cleanup`, the owner creates
147 -the release tag `v1.0.0` on the accepted head and builds the Windows package from
148 -`packaging/build_desktop.py` (artifact retained in the release, not committed).
109 +The implementation author does **not** merge or tag (§19 / booklet 2 §16). Tag `v1.0.0` already exists on `46253c9` (owner-authorized pre-mission). After C0…C9 acceptance, prepare the release checklist here (owner tags, retained artifact, clean-machine offline install log, SBOM/signing); final acceptance is **C10**: Shadow Run on a real period of two companies + owner signature (booklet 2 §15). Do not tag. Git-history rewrite / large-file external migration stays BLOCKED absent an explicit owner directive (C9).
110
111 ## Control documents
112
113 - [Project log](docs/PROJECT_LOG.md)
114 - [Decision log](docs/DECISION_LOG.md)
115 - [Acceptance policy](docs/ACCEPTANCE_POLICY.md)
155 -- [Jules task template](docs/JULES_TASK_TEMPLATE.md)
116 +- [Booklet v1.0 (reference)](docs/booklet/BOOKLET_v1.0.md) · [Booklet v2.0 (course correction)](docs/booklet/BOOKLET_v2.0.md) · [manifest](docs/booklet/MANIFEST.json)
117 +- [PR triage (الف‌6)](docs/PR_TRIAGE.md)
118 +- [Discrepancy registry (skeleton)](docs/discrepancies.json)
119 +- [Archived analytical documents](docs/archive/README.md)
120 - [Master recovery prompt](docs/handoff/MASTER_RECOVERY_PROMPT.md)
121 - [Latest handoff snapshot](docs/handoff/LATEST_HANDOFF.md)
122 - [Saveable ChatGPT bootstrap prompt](docs/handoff/CHATGPT_BOOTSTRAP_PROMPT.txt)
docs/PROJECT_LOG.md
+66
@@ -354,3 +354,69 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
354 - Acceptance: IN_PROGRESS; author does not merge or tag
355 - Reviewer: independent reviewer pending
356 - Next action: independent GitHub review of PR #96; owner acceptance, merge, tag v1.0.0, build Windows package
357 +
358 +### 2026-12-03T15:22:02Z — PR #96 merged + tag v1.0.0 (owner acceptance)
359 +
360 +- Actor: owner (final acceptance via one-time waiver of independent review); Arena agent executed merge+tag under that authorization only
361 +- PR #96 MERGED (squash) into `source-data-cleanup` -> head `46253c94405abd065dfc5e8cf080b295cb83cde4`
362 +- Tag `v1.0.0` created on `46253c9` (remote tag object `a17da671ce1fef2415ce56ebec87b69da6ebb603`)
363 +- Post-merge CI: Backend #47137691800 ✅, Frontend #47137691857 ✅ (both on `46253c9`)
364 +- Transfer verified: `git diff --exit-code` working tree vs `origin/source-data-cleanup` = 0 (199 files identical)
365 +- New mission B0…B12 reinstates no-merge/no-tag for the implementation author
366 +
367 +### 2026-12-03T15:45:00Z — B0: booklet reference + lightweight-process reconciliation
368 +
369 +- Actor: Arena agent (implementation); independent reviewer separate
370 +- Mission: booklet-compliance remediation B0…B12, one focused PR per category, sequential
371 +- Base: live `source-data-cleanup@46253c94405abd065dfc5e8cf080b295cb83cde4` (BASE MATCH verified, §0.2); working branch `arena/094f314c-aram` aligned to accepted base via merge (no force-push)
372 +- B0.1 booklet: `docs/booklet/BOOKLET_v1.0.md` (pymupdf extraction, visual-RTL -> logical reorder) + `docs/booklet/MANIFEST.json` (original PDF SHA-256 `7dd508274babd604f74d10b692464ce42f26a88c4a7116cfd861188abd4a2baf`, 745,088 bytes, 14 pages). Original is PDF not docx; binary not committed (§19); ADR-025
373 +- B0.2 status: `PROJECT_STATUS.md` rewritten to GitHub reality (Phases 0–9 VERIFIED_AND_MERGED at `46253c9`, 319 backend tests, post-merge CI links, stale V1-01 IN_PROGRESS / VERIFIED_BUT_UNMERGED rows removed, D-08 closed)
374 +- B0.3 archive: 14 root analytical docs `git mv` -> `docs/archive/` (+ index README); root retains only AGENTS.md + PROJECT_STATUS.md; no new root analytical doc (§0.5)
375 +- B0.4 process: AGENTS.md ↔ §0.5 conflict reported + resolved; handoff cadence changed to per-category (not per-step); lightweight-process bullets added; ADR-026
376 +- B0.5 registry: `docs/discrepancies.json` skeleton `{row, our_amount, official_amount, cause, evidence, year}` (OD-08; populated in B8)
377 +- Protected data: `data/` tree `2ef8a512523f62f0cf84c5009f141be2f8a9cb5f`, `samples/` tree `00aba54b1dc30485ba9b164c8036a7b4bbe9020e` — unchanged before/after (B0 touches docs only)
378 +- Tests: B0 is documentation/process only; no code changed; backend/frontend suites unaffected (319 backend / 11 frontend at accepted head)
379 +- Artifacts/releases: NONE committed
380 +- Acceptance: IN_PROGRESS; author does not merge or tag
381 +- Next action: independent GitHub review of B0 PR; B1 starts only after B0 acceptance
382 +
383 +### 2026-12-03T16:10:00Z — C0: booklet 2 course correction (بخش الف)
384 +
385 +- Actor: Arena agent (implementation); independent reviewer separate
386 +- Trigger: owner delivered booklet 2 v2.0 (course correction + general-platform architecture); supersedes conflicting parts of booklet 1 and the B0…B12 framing with roadmap C0…C10 (ADR-027). No owner questions (§14).
387 +- Base: live `source-data-cleanup@46253c94405abd065dfc5e8cf080b295cb83cde4` (BASE MATCH, §0.2). Booklet 2 cited PR #96 head 2fce09d (pilot/browser); actual merged head 46253c9 — browser files present in both, course correction applies (reconciliation recorded in ADR-027, الف‌4 honesty).
388 +- الف‌1 browser removal: `git rm` webapp/, docs/{app.js,index.html,bridge.py,styles.css,py,vendor}, scripts/build_webapp.py, .github/workflows/pilot-pages.yml (ADR-028). No backend/frontend code refs (verified). Recoverable from history @46253c9; experiment/browser-edition branch = owner action (Arena single-branch constraint).
389 +- الف‌2 persistent core: VERIFIED main path = domain/{controls,money,hierarchy,formula,normalization} + statement_api/admin_api on stored LedgerBalance; legacy in-memory pilot retained as logic reference (secure C8, retire later; exception-queue persistence C4).
390 +- الف‌3 phase 0/1 + golden: VERIFIED merged @46253c9 (D-01..D-12; test_golden/test_domain_controls/test_approval_gate; real-1404 UAT).
391 +- الف‌4/الف‌5: PR honesty + ≤~1500-line/one-phase rules added to AGENTS.md; generality rule (ب‌1) + no-runtime-network/read-only-source/no-plaintext-secrets (§16) added.
392 +- الف‌6 triage: docs/PR_TRIAGE.md — ADOPT #81(C6/C4)/#89(C8)/#92(C8); CLOSE NO-GO #82/#88; SUPERSEDED #90/#91 + #22–#80 backlog. Closes recommended, executed after triage acceptance (conservative §14); author merges nothing.
393 +- Booklet 2 verbatim: docs/booklet/BOOKLET_v2.0.md (SHA-256 9738f8049703ca63ea6eae471538cdadc6328e4f15efaaf87a250315e516e2fc) + MANIFEST.json updated (both booklets).
394 +- OD-09..OD-14 adopted (ADR-027); databansoft.ir not reachable from sandbox allowlist — no capability claims (OD-14).
395 +- Protected data: data/ tree 2ef8a512523f62f0cf84c5009f141be2f8a9cb5f, samples/ tree 00aba54b1dc30485ba9b164c8036a7b4bbe9020e — unchanged before/after.
396 +- Tests: removal touches no backend/frontend code; suites unaffected (319 backend / 11 frontend at accepted head); local re-run recorded in PR.
397 +- Artifacts/releases: NONE committed. Acceptance: IN_PROGRESS; author does not merge or tag.
398 +- Next: independent review of C0 (PR #97, re-scoped from B0); C1 starts only after C0 acceptance with evidence in PROJECT_STATUS.
399 +
400 +### 2026-12-03T20:20:00Z — C0 addendum: booklet 2 appendix revision (owner) + ADR-029
401 +
402 +- Actor: Arena agent (implementation); trigger: owner re-sent booklet 2 with a rewritten appendix ("این کتابچه اصلاحی رو پیش ببر")
403 +- Appendix now records: Databan catalog (fall 1405) studied by owner — marketing claims, unverified, inspiration only; Databan does NOT prepare financial statements (Aram's gap); positioning = independent pluggable product + Host Integration API (REST + permissions); commercial cooperation out of agent scope
404 +- OD-09 REVISED per owner directive: pyodbc with existing ODBC driver preferred (Windows + SQL Server target); python-tds fallback; 100k-row proof gate unchanged (ADR-027 updated, ADR-029)
405 +- Accepted elements mapped: multi-layer access control (C8), source-drift nightly detection → «نیازمند بازبینی» (C8/C9), nightly document audit C-16+ (optional post-C6, OD-12), work center (C7), dry-run (C4/C8), signed updates + auto-rollback + in-app backup/restore (C9), letterhead print templates + statutory ledgers + Ctrl+K (C7), AI assistant C11 (optional, OFF by default, never generates numbers, engine+CalculationRun lineage only, read-only, local/anonymized, audited), multi-company group dashboard (C6/C7; consolidation next version)
406 +- Rejected scope binding: مودیان/IMED/trade system/bank-invoice+document reader/form builder/cartable; messenger bots for financial data prohibited (notifications without figures only)
407 +- Agent has no access to databansoft.ir (sandbox allowlist); no independent capability claims made; no Databan code/text/design/name/brand copied
408 +- docs/booklet/BOOKLET_v2.0.md appendix replaced verbatim (list numbering normalized, disclosed in header); new SHA-256 79618dddb3de9bde195b8253880593b2900389369150c917d81b97006762823a; MANIFEST.json keeps revision history (initial 9738f804…)
409 +- ADR-029 added (positioning, OD-14 comparison table, element→phase mapping, OD-09 revision, C11 constraints); PROJECT_STATUS roadmap updated (C5/C7/C8/C9 notes + C11 row)
410 +- Protected data: data/ + samples/ trees unchanged (docs-only addendum). Code state identical to C0 commit 6e3fe70 (backend 319 passed / frontend green run on that tree)
411 +- Acceptance: IN_PROGRESS; author does not merge or tag. Next: push C0 (both commits), update PR #97 body to match diff (الف‌4), independent review
412 +
413 +### 2026-12-03T21:00:00Z — C0 remediation after independent review of PR #97
414 +
415 +- Actor: Arena agent (implementation); trigger: owner/independent-reviewer verdict on PR #97 (report accurate; repo-vs-booklet-2 gaps mostly from merged PR #96) + explicit instruction to create experiment/browser-edition branch
416 +- Branch instruction: BLOCKED by Arena single-branch session constraint (system-level; cannot create/push any branch but arena/094f314c-aram). Reported per booklet 2 §14; exact owner command + GitHub-UI alternative recorded in ADR-028. Preservation already guaranteed: tag v1.0.0 -> 46253c9 contains the full browser edition (recoverable after #97 merges). No second PR created (owner: "Create PR را نزن").
417 +- الف‌7 REMEDIATED (was the real C0 exit gap): re-ran golden.compare_year(1404) fresh -> 28 comparisons / 9 matched / 19 diffs (BS 9/16, IS 0/6, EQ 0/0, CF 0/6). Populated docs/discrepancies.json one-by-one with cause + reproducible evidence + source/official SHA-256: 16 caused (8 exact-magnitude presentation-sign flips per ADR-013; CF note-number reuse 10/15; absent notes IS 20-3/7, CF 20-1; CF not yet derived 23/24; official CF account-code row 46268), 3 under_investigation (IS 6/8/9 magnitude mismatches = bugs until proven, D1). EQ official sheet yields 0 note rows (C3 parsing gap, recorded). Real-1404 approval still blocked by C-01/C-03/C-04 (correct fail-loud).
418 +- Fresh verification evidence for reviewer's "not verified" items: backend full suite exit 0, collect-only = 319 tests; D-04/D-05 test_domain_normalization.py = 17 passed (numeric-code exactness, leading zeros, Persian/Arabic digit + letter normalization, ZWNJ preserved); golden numbers freshly reproduced above.
419 +- Reviewer deviations recorded as tracked gaps in PROJECT_STATUS: forgeable actor-string auth + unguarded endpoints + open approval when no users (C8); only 4/15 controls (C3); desktop.py create_all bypasses Alembic (C9); PR #96 discipline violation (154 files/+24,327, stale head 969f608 vs babe829, merged without independent review under one-time waiver) recorded as historical, الف‌4/5 enforced going forward; booklet-1 extraction artifacts disclosed (ADR-025).
420 +- Screenshot +21065/−242 explained: Arena patchset view diffs vs session base 7dc864f (cumulative with phases 0–9), not PR base 46253c9; actual PR #97 diff = 50 files/+1490/−4892 (reviewer-confirmed).
421 +- Protected data: data/ + samples/ trees unchanged (docs-only remediation). No code changed; backend/frontend suites unaffected.
422 +- Acceptance: IN_PROGRESS; author does not merge or tag. Next: independent re-review of updated PR #97; C1 only after C0 acceptance.
docs/PR_TRIAGE.md new
+69
@@ -0,0 +1,69 @@
1 +# PR Triage (booklet 2 · الف‌6)
2 +
3 +Disposition of every open PR against booklets 1 + 2. Three verdicts only:
4 +
5 +- **ADOPT** — aligned with the booklets **and** has tests; cherry-pick the useful,
6 + tested code into a new small focused PR (≤ ~1,500 lines, booklet 2 الف‌5). The
7 + original PR is **not** merged as-is.
8 +- **SUPERSEDED** — replaced by merged work (PR #96, head `46253c9`) or by the
9 + booklet-2 architecture/roadmap; close.
10 +- **CLOSE** — NO-GO or otherwise not acceptable; close. **No NO-GO PR is ever merged.**
11 +
12 +Evidence base: live `gh pr list/view` on 2026-12-03; accepted head
13 +`46253c94405abd065dfc5e8cf080b295cb83cde4`. PR #83–#87 do not exist (already closed).
14 +
15 +> Execution note (§14 conservative default): this file **records** the verdicts
16 +> required by الف‌6. Bulk-closing ~50 PRs is an irreversible action; the closes for
17 +> SUPERSEDED/CLOSE verdicts are recommended here and are executed by the
18 +> owner/independent reviewer after this triage is accepted (or on explicit request).
19 +> ADOPT items are cherry-picked into the named C-phase PRs, never merged from the
20 +> source PR. The author merges nothing (§19 / booklet 2 §16).
21 +
22 +## Named backlog #81–#92 (owner-specified)
23 +
24 +| PR | Title (short) | Evidence | Verdict | Target / rationale |
25 +|---|---|---|---|---|
26 +| #81 | read-only mapping source parser | +931/−1, 11 files; tests: `test_mapping_matcher`, `test_mapping_parser_limits`, `test_mapping_precision`, `test_mapping_source_parser` | **ADOPT** | Cherry-pick `mapping_matcher.py` + `mapping_source_parser.py` + tests into **C6** (MappingPack suggestions, ب‌8) / **C4** (adapter parsing). Drop the extra analytical docs (§0.5); ignore the Windows-pilot test touch. |
27 +| #82 | Gate 3 — FINAL NO-GO | +1903/−1, 22 files; title **NO-GO**; > 1,500 lines | **CLOSE** | NO-GO; superseded by merged phases 0–9 + booklet-2 architecture. Never merge. |
28 +| #88 | isolated local hardening (NO-GO) | +914/−48, 34 files; title **NO-GO** | **CLOSE** | NO-GO. Hardening re-implemented cleanly in **C8** (ب‌10) rather than cherry-picking a NO-GO candidate. |
29 +| #89 | Argon2id + DPAPI vault + recovery (partial, NO-GO) | +757/−24, 15 files; tests: `test_password_security`, `test_windows_credential_vault`, `test_credential_recovery`, `test_local_auth`, `test_auth_api`; title **NO-GO / partial** | **ADOPT** | Strongly aligned with **C8** (Argon2id, B1) + ب‌10 (DPAPI vault, credential recovery). Cherry-pick tested logic into focused C8 security PRs with a dependency ADR (argon2-cffi). Do **not** merge #89 (NO-GO/partial). |
30 +| #90 | docs: reconcile FS 1402–1404 | +1691/−102, 9 files; **no tests**; re-adds root `NOTE_CATALOG.md`/`NOTE_TO_SHEET_MATRIX.md` (archived in B0) | **SUPERSEDED** | Doc-heavy; conflicts with §0.5 and re-introduces archived catalogs. Reconciliation evidence is **re-derived with proof** into `docs/discrepancies.json` in **C3/B8** (not copied from unverified docs). Close. |
31 +| #91 | docs: mandatory master control plan | +3071/−3, 13 files; **no tests**; 3,071-line new plan | **SUPERSEDED** | Governance is now booklet 1 + 2 + `AGENTS.md` + `ACCEPTANCE_POLICY.md` + `PROJECT_STATUS.md`. A new master plan conflicts with §0.5 lightweight process. Close. |
32 +| #92 | fail closed on malformed Unicode passwords | +123/−5, 6 files; test: `test_password_security` | **ADOPT** | Small, focused, aligned with **C8** (B1 security). Cherry-pick `password_security.py` + test into the C8 password PR (folds into #89's Argon2id work). |
33 +
34 +## Older backlog #22–#80 (pre-PR #96 candidates)
35 +
36 +All are draft candidates from 2026-10-23…31 built on the **old** Gate-3 / Windows-
37 +native-pilot / five-statement-CLI architecture. They predate the merged persistent
38 +core (PR #96) and the booklet-2 connector/pack architecture. Per §14 (conservative
39 +default) and الف‌6 (aligned **and** tested), reusable domain logic is **re-derived and
40 +verified on the new model** in C1–C3 (golden + dual-path + metamorphic), not blindly
41 +cherry-picked from old-architecture code. Verdict for the group: **SUPERSEDED — close.**
42 +
43 +| PRs | Subject cluster | Verdict | Note |
44 +|---|---|---|---|
45 +| #62, #63, #64, #65, #66 | BS/IS/TB/EQ/CF explicit-policy candidates | SUPERSEDED | Re-derive on persistent model in **C3** (four statements + C-01..C-15). Reference for formula/sign logic only. |
46 +| #67, #68, #69, #70 | cross-statement controls / multistatement mapping / pipeline | SUPERSEDED | Controls re-derived in **C3**; mapping in **C2/C6**; pipeline replaced by connector+snapshot (**C4**). |
47 +| #71, #72, #73 | five-statement CLI / manifest schema / referential integrity | SUPERSEDED | CLI pipeline replaced by API+engine on snapshots (**C4/C7**). |
48 +| #74 | CI Node24 actions migration | SUPERSEDED | CI gates already merged (ADR-017); revisit in **C9/B9** if needed. |
49 +| #75, #76, #77, #78, #79, #80 | Windows native pilot / demo / drill-down / background search | SUPERSEDED | Old Windows-pilot path; packaging re-done on new model in **C9**; drill-down already merged (ADR-018). |
50 +| #59 | native Windows pilot shell + EXE candidate | SUPERSEDED | Replaced by desktop entrypoint (ADR-024) + **C9**. |
51 +| #50, #51, #52, #53, #54, #55, #56, #57 | Gate-3 mapping batch/auth/draft-staging | SUPERSEDED | Mapping/auth merged (phases 2–3, 7) + **C2/C8**; old RS256/grant model not adopted. |
52 +| #45, #46, #47 | stale-note / hidden-XLSX / coverage-target guards | SUPERSEDED | Import hardening re-derived in **C4/B5** with destructive tests. |
53 +| #44, #34, #33 | roadmap dashboard / governance 5+1+3 / Peyvast docs | SUPERSEDED | Governance = booklets 1+2; connector architecture = booklet 2 ب‌2..ب‌6 (ADR-027). |
54 +| #35, #32 | same-flush fiscal lock / year isolation | SUPERSEDED | Equivalent immutability/isolation merged (D-07, ADR-016). |
55 +| #26, #27, #28, #29, #30, #31 | Gate-3 mapping core/exchange/coverage/carry-forward/review; connector ADR | SUPERSEDED | Mapping merged (phase 2–3) + **C2/C6**; #29 connector-reservation realized by booklet 2 (its "ADR-012" number also collides with merged ADR-012 money). |
56 +| #22, #23, #24, #25 | repo hygiene / CI audit / diagnostics / explicit migrations | SUPERSEDED | Merged: README/status, CI audit (ADR-017), diagnostics, Alembic migrations. |
57 +
58 +## Active PR (not triaged)
59 +
60 +- **#97** — this branch's open PR; re-scoped to **C0 course correction** (booklet
61 + references + browser-edition removal + this triage + process rules). It is the
62 + vehicle for C0, not a backlog candidate.
63 +
64 +## Summary
65 +
66 +- **ADOPT (cherry-pick into focused C-phase PRs):** #81 → C6/C4; #89 → C8; #92 → C8.
67 +- **CLOSE (NO-GO):** #82, #88.
68 +- **SUPERSEDED (close):** #90, #91, and the entire #22–#80 backlog.
69 +- No NO-GO PR is merged. No PR is merged by the author. Closes executed after triage acceptance.
docs/adr/ADR-025-booklet-reference-artifact.md new
+52
@@ -0,0 +1,52 @@
1 +# ADR-025 — Booklet reference artifact (source format + integrity anchor)
2 +
3 +- Status: Accepted (B0)
4 +- Date: 2026-12-03
5 +- Booklet: §0 (this booklet is the product work order), §17 (default + proof + ADR,
6 + never query the owner), §19 (no committed binaries)
7 +
8 +## Context
9 +
10 +Mission item B0.1 asks for the booklet verbatim in `docs/booklet/BOOKLET_v1.0.md`
11 +plus the SHA-256 of the original **docx** in a manifest. The actual source delivered
12 +to the workspace is a **PDF**, not a docx:
13 +
14 +- Original file: «کتابچهٔ اجرایی تکمیل Aram» (PDF, 14 pages).
15 +- SHA-256: `7dd508274babd604f74d10b692464ce42f26a88c4a7116cfd861188abd4a2baf`
16 +- Size: 745,088 bytes.
17 +
18 +No `.docx` exists anywhere in the repository or the workspace. Committing the
19 +original binary is prohibited by §19 (no binaries in Git).
20 +
21 +A first-pass PDF text extraction was RTL-scrambled (Arabic presentation forms in
22 +visual order). Committing that as "verbatim" would misrepresent the source.
23 +
24 +## Decision (§17 default + proof)
25 +
26 +1. **Anchor integrity on the original PDF's SHA-256**, recorded in
27 + `docs/booklet/MANIFEST.json`. The original binary is **not** committed (§19);
28 + the hash is the durable, verifiable reference. The manifest records that the
29 + real source is PDF and that B0.1's docx wording did not match the delivered
30 + artifact.
31 +2. **Provide a readable, version-controlled derived text** in
32 + `docs/booklet/BOOKLET_v1.0.md`, extracted with `pymupdf` and re-ordered per line
33 + from visual RTL to logical reading order (whitespace-token reversal, NFC
34 + normalization). This is a **reading aid**, explicitly labelled as derived; minor
35 + hamza/punctuation artifacts may remain. The authoritative source is the original
36 + file identified by the hash above.
37 +3. **No content is invented or "corrected"** (§19). The derived text is a faithful
38 + extraction, not a paraphrase or reconstruction.
39 +
40 +## Proof
41 +
42 +- `sha256sum` of the original PDF = the hash above (reproducible by any reviewer
43 + who has the original upload).
44 +- `docs/booklet/MANIFEST.json` records format, size, page count, tool, and method.
45 +- Page count 14 matches the original's `Page N of 14` footers.
46 +
47 +## Consequences
48 +
49 +- Reviewers verify the booklet against the original PDF by hash, not by trusting
50 + the derived Markdown byte-for-byte.
51 +- If a docx original is later supplied, add its hash to the manifest as an
52 + additional anchor; do not silently replace the PDF anchor.
docs/adr/ADR-026-lightweight-process-handoff-cadence.md new
+55
@@ -0,0 +1,55 @@
1 +# ADR-026 — Lightweight process & handoff cadence (AGENTS.md ↔ booklet §0.5)
2 +
3 +- Status: Accepted (B0)
4 +- Date: 2026-12-03
5 +- Booklet: §0.5 (lightweight process), §0.1 (booklet is the product work order;
6 + AGENTS.md is process rules; report conflicts), §17 (default + proof + ADR)
7 +
8 +## Context — the conflict (reported, not guessed)
9 +
10 +Booklet §0.5 (verbatim, logical order):
11 +
12 +> «سازی‌سبک فرایند (الزامی): سند تحلیلی جدید در ریشهٔ مخزن ساخته نشود. فایل‌های تحلیلی
13 +> تاریخی ریشه (کاتالوگ‌ها و ماتریس‌ها) در یک PR جداگانه به docs/archive/ منتقل شوند. هر PR
14 +> فقط PROJECT_STATUS.md و یک ورودی کوتاه docs/PROJECT_LOG.md را روزبه‌روز کند. هدف: کد و
15 +> تست رشد کند، نه مستندات.»
16 +
17 +`AGENTS.md` ("Project records") currently requires:
18 +
19 +> "update `docs/handoff/LATEST_HANDOFF.md` after **every meaningful completed or
20 +> rejected step** so a successor can resume without chat history"
21 +
22 +These conflict: §0.5 mandates a lightweight per-PR record (status + a short log
23 +entry only, "code and tests grow, not documentation"), while AGENTS.md mandates a
24 +handoff rewrite after every step. The mission's owner decision resolves it
25 +explicitly: **handoff is updated only at the end of each category (B0…B12), not
26 +after every commit/step.**
27 +
28 +## Decision (§17 default + owner decision embedded in the mission)
29 +
30 +1. Amend `AGENTS.md` so the handoff cadence is **per category**, not per step:
31 + `docs/handoff/LATEST_HANDOFF.md` is refreshed at the **end of each B-category**
32 + (and on any governance change), not after every commit.
33 +2. Keep the lightweight per-PR record required by §0.5: every PR updates
34 + `PROJECT_STATUS.md` and appends a **short** `docs/PROJECT_LOG.md` entry; add an
35 + ADR only when a decision is made. No new root-level analytical documents.
36 +3. Historical root analytical docs are moved to `docs/archive/` (done in this B0
37 + PR via `git mv`, preserving history).
38 +4. `MASTER_RECOVERY_PROMPT.md` and `CHATGPT_BOOTSTRAP_PROMPT.txt` stay stable unless
39 + the governance process itself changes (unchanged rule).
40 +
41 +## Proof
42 +
43 +- §0.5 text quoted above from `docs/booklet/BOOKLET_v1.0.md` (integrity anchored by
44 + ADR-025).
45 +- The owner decision is stated in the mission's B0 item 4 ("handoff update only at
46 + end of each category, not every commit").
47 +- This PR moves 14 root analytical docs to `docs/archive/` and adds no new root
48 + analytical document; root retains only `AGENTS.md` and `PROJECT_STATUS.md`.
49 +
50 +## Consequences
51 +
52 +- Successors resume from the per-category handoff plus `PROJECT_STATUS.md` and the
53 + short log, without a handoff rewrite on every commit.
54 +- The conflict is resolved in the process file itself (AGENTS.md), so future agents
55 + read a consistent rule rather than re-discovering the conflict.
docs/adr/ADR-027-booklet-v2-course-correction.md new
+86
@@ -0,0 +1,86 @@
1 +# ADR-027 — Booklet 2 adoption: course correction + general-platform architecture
2 +
3 +- Status: Accepted (C0)
4 +- Date: 2026-12-03
5 +- Booklet: booklet 2 (all sections); booklet 1 §17 (OD-01..OD-08 remain valid), §18, §19
6 +
7 +## Context
8 +
9 +The owner delivered booklet 2 v2.0 («اصلاح مسیر و معماری نهایی Aram»), verbatim at
10 +`docs/booklet/BOOKLET_v2.0.md` (SHA-256 anchor in `MANIFEST.json`). It supersedes the
11 +conflicting parts of booklet 1 and supplements the rest, and asks the agent to never
12 +query the owner (ambiguities closed via booklet 2 §14).
13 +
14 +**Base reconciliation (honesty, الف‌4):** booklet 2 cites "PR #96 (head 2fce09d)" — the
15 +pilot/browser-edition head. The live accepted head is `46253c94405abd065dfc5e8cf080b295cb83cde4`
16 +(squash merge of PR #96, phases 0–9). The browser-edition files booklet 2 targets are
17 +present in **both** heads, so the course correction applies to the current tree. The
18 +§0.2 base check passes (live head = `46253c9`). The stale head label is recorded here;
19 +GitHub reality is authoritative (AGENTS.md).
20 +
21 +## Decision
22 +
23 +### Roadmap: C0…C10 (+ optional C11) supersedes the B0…B12 framing
24 +
25 +Booklet 2 §13 defines the governing roadmap **C0…C10**; the revised appendix adds
26 +**C11** (optional AI assistant, off by default, never generates numbers — ADR-029). The earlier B0…B12 categories
27 +are folded into it (B0 groundwork → C0; B1 security → C8; B2 money/UI → C7; B3 controls
28 +→ C3; B4 data model → C1/C4; B5 import → C4; B6 mapping → C2/C6; B7 outputs → C7;
29 +B8 golden/registry → C1/C3; B9 CI → C9; B10 backup → C8; B11 drift/layout → C0/C4;
30 +B12 large files → C9). B0's deliverables (booklet reference, archive, status rewrite,
31 +discrepancy skeleton, process ADRs) are C0-compatible and retained. One focused PR per
32 +phase task, ≤ ~1,500 changed lines excluding tests/generated data (الف‌5); PR body must
33 +match `git diff --stat` and the real head (الف‌4).
34 +
35 +### Automatic decisions OD-09…OD-14 (booklet 2 §14) adopted
36 +
37 +- **OD-09** SQL Server driver: **REVISED by the owner's appendix (2026-12-03):
38 + `pyodbc` with the existing ODBC driver is preferred** (target environment is
39 + Windows + SQL Server); `python-tds` (pure-Python) is the fallback for offline
40 + packaging where no ODBC driver exists. Proof gate unchanged: connection +
41 + 100k-row extraction in C5; switch if unstable. See ADR-029.
42 +- **OD-10** adapter language: YAML validated by JSON Schema; round-trip test + precise
43 + Persian error messages (C4).
44 +- **OD-11** plugin execution: separate process for Connectors; if it blocks Windows
45 + packaging, same-process with restricted permissions + a new ADR (C4/C9).
46 +- **OD-12** data level: trial-balance default; document-level optional, only after C6 and
47 + only if a note cannot be computed without document detail.
48 +- **OD-13** concurrency: single local install for V1; multi-user server out of scope;
49 + PostgreSQL exercised in CI for the future path.
50 +- **OD-14** similar tools: inspiration only; no code/brand/content copied; capability
51 + comparison recorded in an ADR.
52 +- Other ambiguities: most conservative option (the one that blocks approval) + ADR with
53 + rejected options.
54 +
55 +### Generality rule (ب‌1, non-negotiable)
56 +
57 +No company name, account code, heading, or industry constant in source code; these live
58 +only in `packs/` and the database. An automated grep test enforces this (added with the
59 +packs work in C6; the rule is recorded now and in `AGENTS.md`). Company/industry-specific
60 +content (including the current transmission-company pack) is **data**, never a code default.
61 +
62 +### databansoft.ir appendix — owner-studied catalog (revised 2026-12-03)
63 +
64 +The agent cannot reach `databansoft.ir` from this sandbox (allowlist: github.com /
65 +npmjs / pypi hosts). The **owner** studied the official Databan catalog (fall 1405
66 +edition) and revised the appendix in a second message: it is a marketing document,
67 +its claims are unverified, and it is inspiration only. The positioning decision
68 +(independent product + Host Integration API), the OD-14 capability comparison, the
69 +accepted elements (priority order), the OD-09 revision, phase C11 (optional AI
70 +assistant), and the rejected scope are recorded in **ADR-029**. No Databan
71 +code/text/design/name/brand is copied.
72 +
73 +## Proof
74 +
75 +- Booklet 2 verbatim in `MANIFEST.json` with revision history: initial SHA-256
76 + `9738f8049703ca63ea6eae471538cdadc6328e4f15efaaf87a250315e516e2fc`; current (revised
77 + appendix) SHA-256 `79618dddb3de9bde195b8253880593b2900389369150c917d81b97006762823a`.
78 +- Live head verified `46253c9`; browser files present (`webapp/`, `docs/{app.js,index.html,bridge.py,styles.css,py,vendor}`, `scripts/build_webapp.py`, `.github/workflows/pilot-pages.yml`).
79 +- Persistent core is the main path: `domain/{controls,money,hierarchy,formula,normalization}.py` + `statement_api`/`admin_api` on `LedgerBalance`; golden tests `test_golden.py`, `test_domain_controls.py`, `test_approval_gate.py` present (الف‌2/الف‌3).
80 +
81 +## Consequences
82 +
83 +- C0 (this PR) executes الف‌1 (browser removal, ADR-028), الف‌6 (`docs/PR_TRIAGE.md`),
84 + الف‌4/الف‌5 (process rules in `AGENTS.md`), and records الف‌2/الف‌3/الف‌7 status.
85 +- Subsequent phases follow C1…C10 with evidence recorded in `PROJECT_STATUS.md` before
86 + advancing. No merge, no tag, no runtime network, no company-specific code (§16).
docs/adr/ADR-028-remove-browser-edition.md new
+71
@@ -0,0 +1,71 @@
1 +# ADR-028 — Remove the Pyodide / Pages / CDN browser edition (الف‌1)
2 +
3 +- Status: Accepted (C0)
4 +- Date: 2026-12-03
5 +- Booklet: booklet 2 الف‌1, §16 (no runtime network); booklet 1 §19 (no committed binaries)
6 +
7 +## Context
8 +
9 +PR #96 carried a browser edition of the pilot: a Pyodide/WebAssembly UI served via
10 +GitHub Pages and commit-pinned CDN URLs. For an offline financial tool this is a
11 +runtime-network dependency (booklet 2 الف‌1 / §16) and it placed built output inside
12 +`docs/`, colliding with governance documents. It also committed binary wheels
13 +(`openpyxl`, `et_xmlfile`) under `webapp/vendor/` and `docs/vendor/` (§19).
14 +
15 +Files removed in this PR:
16 +
17 +- `webapp/` (UI shell + `vendor/` wheels)
18 +- `docs/app.js`, `docs/index.html`, `docs/bridge.py`, `docs/styles.css`
19 +- `docs/py/` (Pyodide copy of the engine), `docs/vendor/` (wheels)
20 +- `scripts/build_webapp.py`
21 +- `.github/workflows/pilot-pages.yml`
22 +
23 +Governance content in `docs/` is kept (`ACCEPTANCE_POLICY.md`, `DECISION_LOG.md`,
24 +`PROJECT_LOG.md`, `adr/`, `archive/`, `booklet/`, `handoff/`, `reviews/`,
25 +`discrepancies.json`, etc.).
26 +
27 +## Decision (§14 default + proof)
28 +
29 +1. **Remove** the browser edition from the accepted path (this PR). Verified safe: no
30 + `backend/src` or `frontend/src` code references `webapp/`, `docs/py`, `docs/vendor`,
31 + `build_webapp`, or `pilot-pages`; the only references were inside the removed files
32 + themselves. Backend/Frontend CI are path-filtered to `backend/**` / `frontend/**`,
33 + so removal does not affect them.
34 +2. **Preserve the work in Git history.** Booklet 2 الف‌1 asks to keep the browser edition
35 + on a separate unmergeable branch `experiment/browser-edition`. This Arena session is
36 + constrained to a **single branch** (`arena/094f314c-aram`) and must not create, switch
37 + to, or push any other branch. Creating `experiment/browser-edition` is therefore an
38 + **owner / non-Arena action**. The intent (do not lose the work) is satisfied because the
39 + full browser edition remains recoverable from Git history at head `46253c9` and the
40 + earlier pilot commits; `git rm` here removes it from the working tree only, not history.
41 + Recommended owner command (outside Arena):
42 + `git branch experiment/browser-edition 46253c94405abd065dfc5e8cf080b295cb83cde4 && git push origin experiment/browser-edition`.
43 + **Owner explicitly requested this command on 2026-12-03 review.** The Arena
44 + single-branch session constraint still blocks the agent from creating/pushing any
45 + branch other than `arena/094f314c-aram` (system-level, not overridable by task
46 + instructions), so the agent reports the block and continues independent work
47 + (booklet 2 §14). Preservation is already guaranteed without the named branch: tag
48 + **`v1.0.0` points to `46253c9`**, whose tree contains the full browser edition, so
49 + `git show v1.0.0:webapp/app.js` (etc.) recovers every removed file permanently, even
50 + after #97 merges. The owner can create the named branch via the one-liner above or
51 + GitHub UI (Branches → New branch → source `46253c9`).
52 +3. The backend in-memory pilot subsystem (`pilot_engine.py`, `pilot_store.py`,
53 + `pilot_api.py`, `pilot_editing.py`, `static/pilot`) is **not** removed here. It is legacy
54 + (الف‌2): the persistent core is the main product path. It is secured in **C8** (B1) and
55 + retired/relocated per the target layout afterwards; `pilot_engine.py` is retained as a
56 + logic reference until its exception-queue logic is persisted in `domain/` (C4/B4).
57 +
58 +## Proof
59 +
60 +- `grep -rnE "webapp|docs/py|docs/vendor|build_webapp|pilot-pages" backend/src frontend/src`
61 + → no code references (only the removed `build_webapp.py` / `pilot-pages.yml` self-refs).
62 +- `main.py` mounts `statement_router` + `admin_router` (persistent) alongside the legacy
63 + `pilot_router`; `domain/controls.py` + `domain/money.py` run on stored `LedgerBalance`.
64 +- Removed wheels are binary artifacts (§19); their removal reduces committed binaries.
65 +
66 +## Consequences
67 +
68 +- The accepted path is offline-only (no Pages/CDN/Pyodide). The single reference UI is the
69 + React workbench (`frontend/`), developed further in C7.
70 +- The browser edition is recoverable from history; the named experiment branch is an owner
71 + action recorded here, not performed in this single-branch session.
docs/adr/ADR-029-positioning-host-integration.md new
+101
@@ -0,0 +1,101 @@
1 +# ADR-029 — Positioning vs Databan: Host Integration API, accepted elements, OD-09 revision
2 +
3 +- Status: Accepted (C0)
4 +- Date: 2026-12-03
5 +- Booklet: booklet 2 revised appendix (owner message 2026-12-03, second), ب‌3..ب‌6,
6 + ب‌10, §14 (OD-09, OD-12, OD-14), §16
7 +
8 +## Context
9 +
10 +The owner studied the official Databan catalog (fall 1405 edition) and revised the
11 +booklet-2 appendix. Per the owner: Databan is a smart layer on top of existing
12 +accounting-software ledgers — it reads ledgers directly, runs on the company's own
13 +server (Windows + SQL Server), brings multiple companies into one template, and its
14 +domain is reports, dashboards, alerts, automation, and government systems. **It does
15 +not prepare financial statements.** These are marketing claims from a promotional
16 +document; the agent has not verified them (`databansoft.ir` is unreachable from this
17 +sandbox's network allowlist) and makes no independent capability claims. Inspiration
18 +only; no Databan code, text, design, name, or brand is copied (OD-14, §16, appendix
19 +legal restriction).
20 +
21 +## Decision
22 +
23 +### Positioning (owner decision, recorded)
24 +
25 +Aram is an **independent product with a pluggable core** and a **Host Integration
26 +API** (REST contract + permissions) so it can later be embedded as a module inside a
27 +data platform. Any commercial cooperation with Databan or similar vendors is outside
28 +the agent's scope. The gap Aram fills: the **preparation, control, and audit engine
29 +for financial statements** — which the catalog says Databan does not provide.
30 +
31 +Implementation note: the Host Integration API contract is designed alongside the
32 +plugin API (C4) and exposed with the API surface (C7); it reuses the single
33 +authorization policy (below), never a parallel permission model.
34 +
35 +### OD-14 capability comparison (owner-provided catalog description, unverified)
36 +
37 +| Capability | Databan (per catalog, unverified) | Aram (booklet 2) |
38 +|---|---|---|
39 +| Read accounting-software ledgers directly, no source mutation | Yes | Yes — Connectors + read-only safety (ب‌4/ب‌5, C4/C5) |
40 +| Runs on the company's own server (Windows + SQL Server) | Yes | Yes — offline Windows default; SQL Server source via pyodbc (C5/C9) |
41 +| Multi-company in one template | Yes | Yes — packs + group dashboard (ب‌8, C6/C7); consolidation next version |
42 +| Reports / dashboards / alerts / automation | Yes | Statements, work center, drift alerts, nightly jobs (C7/C8) |
43 +| Government systems (مودیان/IMED/trade) | Yes | **Rejected — out of scope** (appendix) |
44 +| **Financial-statement preparation + controls + audit** | **No** | **Yes — the core product** (C1–C3) |
45 +
46 +### OD-09 revision (owner directive supersedes the §14 default)
47 +
48 +Target environment is Windows + SQL Server with an existing ODBC driver, so
49 +**`pyodbc` is preferred**; `python-tds` (pure-Python) is the fallback for offline
50 +packaging where no ODBC driver exists. Proof gate unchanged: connection test +
51 +100k-row extraction in C5; switch if unstable. (Evidence/directive over default, §14.)
52 +
53 +### Accepted elements → phase mapping (appendix priority order)
54 +
55 +1. **Direct ledger reads without source mutation** → confirms ب‌4/ب‌5 (C4/C5); OD-09 revised above.
56 +2. **Multi-layer access control** (module ← company ← fiscal year ← row/field), one
57 + policy across API, UI, exports, and any AI module → extends ب‌10 (C8).
58 +3. **Source-drift detection**: nightly Windows-service job re-measures source sums +
59 + hash after snapshot approval; added/modified/deleted documents dated in an approved
60 + year ⇒ alert + audit record + year moved to «نیازمند بازبینی» (needs-review);
61 + approved output never changes automatically → C8 (detection) + C9 (Windows service).
62 +4. **Nightly document-level audit** (optional, only with a document-level connector):
63 + unbalanced, probable-duplicate, large-amount, modified/deleted documents; feeds new
64 + controls **C-16+** → after C6 per OD-12; control catalog extension registered in C3.
65 +5. **Work center**: one page for everything awaiting the user (unknown accounts, failed
66 + controls, approval/reopen requests, source drift) → C7.
67 +6. **Dry-run** for every extraction and automated job (result shown, zero effect) → C4/C8.
68 +7. **Signed updates with automatic rollback + in-app backup/restore** → C9 (+ C8 backup).
69 +8. **Print templates with company letterhead** for statements, statutory ledger exports
70 + (روزنامه/کل), supporting tables; global **Ctrl+K** search → C7.
71 +9. **AI assistant — phase C11, optional, OFF by default**: understands questions only,
72 + **never generates numbers**; figures come only from the engine and an approved
73 + CalculationRun with lineage; read-only; local model or anonymization of person/company
74 + names before any external service; every query audited; AI mapping suggestions remain
75 + suggestions with mandatory human approval (ب‌8 unchanged) → C11.
76 +10. **Multi-company** with one template + group dashboard; consolidated statements in a
77 + later version → C6/C7 (consolidation out of V1).
78 +
79 +### Rejected scope (appendix, binding)
80 +
81 +مودیان, IMED, comprehensive trade system, bank-invoice processing and document reading,
82 +generic form builder and cartable. Messenger bots for financial data are **prohibited by
83 +default**; if ever needed, notifications only, **without figures**.
84 +
85 +## Proof
86 +
87 +- Revised appendix verbatim in `docs/booklet/BOOKLET_v2.0.md`, SHA-256
88 + `79618dddb3de9bde195b8253880593b2900389369150c917d81b97006762823a` (revision history in
89 + `MANIFEST.json`).
90 +- Owner directive is the evidence source for the catalog description; agent network
91 + allowlist excludes `databansoft.ir` (no independent verification claimed).
92 +- Roadmap updated in `PROJECT_STATUS.md` (C5/C7/C8/C9 scope notes + C11 row).
93 +
94 +## Consequences
95 +
96 +- C5 connector work starts from pyodbc; the pure-Python fallback stays available for
97 + driverless offline machines (ADR required if the proof gate fails).
98 +- The needs-review year status and C-16+ controls enter the data-model/control design
99 + in C3/C8; no approved output is ever mutated automatically (P-01/D-07 preserved).
100 +- C11 is optional and gated: no number ever originates from an AI model; lineage and
101 + audit are mandatory; default OFF.
docs/app.js deleted
-692
@@ -1,692 +0,0 @@
1 -/* Aram Pilot Workbench — browser edition.
2 - Runs the exact, tested Python engine client-side via Pyodide. No server. */
3 -"use strict";
4 -
5 -const S = {
6 - meta: null, data: null, tab: "dashboard",
7 - filter: "all", search: "", noteSearch: "",
8 - statementView: "BS", expanded: new Set(),
9 - ready: false,
10 -};
11 -let PY = null, BRIDGE = null;
12 -
13 -const $ = (s) => document.querySelector(s);
14 -const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => (
15 - { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]
16 -));
17 -function fmt(v) {
18 - if (v === null || v === undefined || v === "") return "—";
19 - let s = String(v); const neg = s.startsWith("-"); if (neg) s = s.slice(1);
20 - let [i, d] = s.split("."); i = i.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
21 - if (d) d = d.replace(/0+$/, "");
22 - return (neg ? "−" : "") + i + (d ? "." + d : "");
23 -}
24 -const isNeg = (v) => String(v ?? "").startsWith("-");
25 -const numCell = (v) => `<td class="num${isNeg(v) ? " neg" : ""}">${fmt(v)}</td>`;
26 -const STATUS_FA = {
27 - INCOMPLETE: "ناقص — پیش‌نویس کاری",
28 - COMPLETE_DRAFT: "کامل — نگاشت‌ها در انتظار تأیید",
29 - COMPLETE_APPROVED: "کامل — همهٔ نگاشت‌ها تأییدشده",
30 -};
31 -const APPROVAL_FA = { Draft: "پیش‌نویس", Reviewed: "بررسی‌شده", Approved: "تأییدشده" };
32 -
33 -let toastTimer = null;
34 -function toast(msg, kind = "") {
35 - const el = $("#toast"); el.textContent = msg; el.className = `toast ${kind}`;
36 - clearTimeout(toastTimer); toastTimer = setTimeout(() => el.classList.add("hidden"), 4200);
37 -}
38 -
39 -/* ---------------- engine bridge ---------------- */
40 -function call(action, data = {}) {
41 - const resJson = BRIDGE.handle(action, JSON.stringify(data));
42 - const r = JSON.parse(resJson);
43 - if (!r.ok) { const e = new Error(r.error || "خطا"); e.issues = r.issues; e.status = r.status; throw e; }
44 - return r.data;
45 -}
46 -const actor = () => ($("#actor-input").value || "").trim();
47 -const sid = () => S.data.session.id;
48 -function applyPayload(p) { S.data = p; renderAll(); }
49 -
50 -function bufToB64(buf) {
51 - const bytes = new Uint8Array(buf); let bin = ""; const CH = 0x8000;
52 - for (let i = 0; i < bytes.length; i += CH) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CH));
53 - return btoa(bin);
54 -}
55 -function downloadB64(b64, filename) {
56 - const bin = atob(b64); const arr = new Uint8Array(bin.length);
57 - for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
58 - const blob = new Blob([arr], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
59 - const url = URL.createObjectURL(blob);
60 - const a = document.createElement("a"); a.href = url; a.download = filename;
61 - document.body.appendChild(a); a.click(); a.remove();
62 - setTimeout(() => URL.revokeObjectURL(url), 2000);
63 -}
64 -
65 -/* ---------------- boot ---------------- */
66 -const PYODIDE_VERSION = "0.26.4";
67 -const PYODIDE_BASES = [
68 - `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`,
69 - `https://unpkg.com/pyodide@${PYODIDE_VERSION}/`,
70 -];
71 -const VENDOR_WHEELS = ["et_xmlfile-2.0.0-py3-none-any.whl", "openpyxl-3.1.5-py2.py3-none-any.whl"];
72 -
73 -function bootProgress(pct, msg) {
74 - $("#boot-progress").style.width = pct + "%";
75 - if (msg) $("#boot-status").textContent = msg;
76 -}
77 -function loadScript(src) {
78 - return new Promise((resolve, reject) => {
79 - const s = document.createElement("script");
80 - s.src = src;
81 - s.onload = resolve;
82 - s.onerror = () => reject(new Error("بارگذاری اسکریپت ناموفق: " + src));
83 - document.head.appendChild(s);
84 - });
85 -}
86 -async function loadPyodideRuntime() {
87 - let lastErr = null;
88 - for (const base of PYODIDE_BASES) {
89 - try {
90 - if (typeof globalThis.loadPyodide !== "function") await loadScript(base + "pyodide.js");
91 - return await loadPyodide({ indexURL: base });
92 - } catch (err) { lastErr = err; }
93 - }
94 - throw lastErr || new Error("بارگذاری پایتون ناموفق بود.");
95 -}
96 -async function boot() {
97 - try {
98 - bootProgress(10, "در حال بارگذاری پایتون در مرورگر…");
99 - PY = await loadPyodideRuntime();
100 - bootProgress(45, "در حال نصب کتابخانهٔ اکسل…");
101 - const site = PY.runPython("import site; site.getsitepackages()[0]");
102 - for (const w of VENDOR_WHEELS) {
103 - const resp = await fetch(`vendor/${w}`);
104 - if (!resp.ok) throw new Error("بارگذاری کتابخانه ناموفق: " + w);
105 - PY.FS.writeFile(`/tmp/${w}`, new Uint8Array(await resp.arrayBuffer()));
106 - PY.runPython(`import zipfile; zipfile.ZipFile('/tmp/${w}').extractall('${site}')`);
107 - }
108 - bootProgress(70, "در حال بارگذاری موتور آرام…");
109 - PY.FS.mkdirTree("/pkg/aram_backend");
110 - const files = ["__init__.py", "pilot_workbook.py", "pilot_engine.py", "pilot_editing.py", "pilot_demo.py", "pilot_store.py"];
111 - for (const f of files) {
112 - const text = await (await fetch(`py/aram_backend/${f}`)).text();
113 - PY.FS.writeFile(`/pkg/aram_backend/${f}`, text);
114 - }
115 - const bridgeText = await (await fetch("bridge.py")).text();
116 - PY.FS.writeFile("/pkg/bridge.py", bridgeText);
117 - PY.runPython("import sys; sys.path.insert(0, '/pkg')");
118 - BRIDGE = PY.pyimport("bridge");
119 - bootProgress(95, "آماده‌سازی…");
120 - S.meta = call("meta");
121 - renderPolicy();
122 - S.ready = true;
123 - $("#upload-btn").disabled = false;
124 - $("#demo-btn").disabled = false;
125 - bootProgress(100, "آماده است");
126 - setTimeout(() => $("#boot").classList.add("hidden"), 350);
127 - } catch (err) {
128 - const el = $("#boot-error");
129 - el.classList.remove("hidden");
130 - el.textContent = "بارگذاری موتور ناموفق بود: " + (err?.message || err) +
131 - " — اتصال اینترنت را بررسی کنید و صفحه را دوباره بارگذاری کنید.";
132 - $("#boot-status").textContent = "خطا در بارگذاری";
133 - }
134 -}
135 -
136 -/* ---------------- landing ---------------- */
137 -function renderPolicy() {
138 - const m = S.meta, items = [];
139 - for (const st of m.rendered_statements)
140 - for (const [sec, sign] of Object.entries(m.section_policy[st]))
141 - 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>`);
142 - for (const st of m.deferred_statements)
143 - items.push(`<div class="policy-item muted">${esc(m.statement_labels_fa[st])} — نسخهٔ بعدی</div>`);
144 - $("#policy-grid").innerHTML = items.join("");
145 -}
146 -function showIssues(err) {
147 - const panel = $("#issues-panel");
148 - if (!err.issues?.length) { toast(err.message, "error"); return; }
149 - $("#issues-message").textContent = err.message;
150 - $("#issues-table tbody").innerHTML = err.issues.map((i) =>
151 - `<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>`).join("");
152 - panel.classList.remove("hidden");
153 - panel.scrollIntoView({ behavior: "smooth", block: "start" });
154 -}
155 -async function uploadFile(file) {
156 - $("#issues-panel").classList.add("hidden");
157 - $("#upload-progress").classList.remove("hidden"); $("#upload-btn").disabled = true;
158 - try {
159 - if (!file.name.toLowerCase().endsWith(".xlsx")) throw new Error("فقط فایل .xlsx پذیرفته می‌شود.");
160 - if (file.size > 25 * 1024 * 1024) throw new Error("حداکثر حجم مجاز ۲۵ مگابایت است.");
161 - const b64 = bufToB64(await file.arrayBuffer());
162 - enterWorkspace(call("upload", { filename: file.name, bytes_b64: b64 }));
163 - toast("فایل پذیرفته شد؛ پیش‌بررسی بدون خطا بود.", "success");
164 - } catch (err) { showIssues(err); }
165 - finally { $("#upload-progress").classList.add("hidden"); $("#upload-btn").disabled = false; $("#file-input").value = ""; }
166 -}
167 -function startDemo() {
168 - $("#issues-panel").classList.add("hidden"); $("#demo-btn").disabled = true;
169 - try {
170 - enterWorkspace(call("demo"));
171 - toast("دموی ساختگی آماده شد؛ دو حساب نگاشت‌نشده منتظر شما هستند.", "success");
172 - } catch (err) { toast(err.message, "error"); }
173 - finally { $("#demo-btn").disabled = false; }
174 -}
175 -
176 -/* ---------------- workspace ---------------- */
177 -function enterWorkspace(payload) {
178 - S.data = payload; S.tab = "dashboard"; S.filter = "all"; S.search = "";
179 - S.noteSearch = ""; S.expanded = new Set();
180 - $("#view-landing").classList.add("hidden");
181 - $("#view-workspace").classList.remove("hidden");
182 - $("#tabbar").classList.remove("hidden");
183 - $("#new-session-btn").classList.remove("hidden");
184 - $("#engine-version").textContent = payload.report.engine_version;
185 - renderAll(); window.scrollTo({ top: 0 });
186 -}
187 -function leaveWorkspace() {
188 - S.data = null;
189 - $("#view-workspace").classList.add("hidden");
190 - $("#view-landing").classList.remove("hidden");
191 - $("#tabbar").classList.add("hidden");
192 - $("#new-session-btn").classList.add("hidden");
193 -}
194 -function renderAll() {
195 - const { report, session } = S.data, c = report.company;
196 - const sourceChip = session.source === "demo"
197 - ? `<span class="chip demo">دموی ساختگی</span>`
198 - : `<span class="chip mono">${esc(session.filename)}</span>`;
199 - $("#session-info").innerHTML = `<div class="session-meta">
200 - <span class="company-name">${esc(c.name)}</span>
201 - <span class="chip">کد ${esc(c.code)}</span>
202 - <span class="chip">سال ${c.fiscal_year}</span>
203 - <span class="chip">${esc(c.unit || "واحد نامشخص")}</span>${sourceChip}</div>`;
204 - $("#status-chip").innerHTML = `<span class="status-chip status-${report.status.label}">${STATUS_FA[report.status.label]}</span>`;
205 - const ex = report.coverage.exception_count, badge = $("#mapping-badge");
206 - badge.textContent = ex; badge.className = `badge${ex === 0 ? " zero" : ""}`;
207 - document.querySelectorAll(".tabbar .tab").forEach((t) => t.classList.toggle("active", t.dataset.tab === S.tab));
208 - document.querySelectorAll(".tab-panel").forEach((p) => p.classList.add("hidden"));
209 - $(`#tab-${S.tab}`).classList.remove("hidden");
210 - ({ dashboard: renderDashboard, accounts: renderAccounts, notes: renderNotes, statements: renderStatements, more: renderMore })[S.tab]();
211 -}
212 -
213 -/* ---------------- dashboard ---------------- */
214 -function renderDashboard() {
215 - const { report } = S.data, t = report.totals, cov = report.coverage;
216 - const pct = cov.total_accounts ? Math.round((cov.mapped_accounts / cov.total_accounts) * 100) : 0;
217 - const totalCard = (label, v, hl = false) =>
218 - `<div class="total-card${hl ? " highlight" : ""}"><div class="label">${label}</div><div class="value${isNeg(v) ? " neg" : ""}">${fmt(v)}</div></div>`;
219 - const exceptions = report.exceptions.length ? `
220 - <div class="card" style="margin-top:14px">
221 - <h3 style="margin-top:0">صف استثنا (${report.exceptions.length})</h3>
222 - <div class="item-list">${report.exceptions.map((e) => `
223 - <div class="item-card">
224 - <div class="item-top">
225 - <div><div class="item-title">${esc(e.account_name)}</div><div class="item-code mono">${esc(e.account_code)} · سطر منبع ${e.source_row}</div></div>
226 - <span class="item-amount${isNeg(e.closing) ? " neg" : ""}">${fmt(e.closing)}</span>
227 - </div>
228 - <div class="item-sub"><span class="approval-chip approval-none">${esc(e.code)}</span> ${esc(e.details)}</div>
229 - <div class="item-actions"><button class="btn small primary" data-action="resolve-exception" data-code="${esc(e.account_code)}">رسیدگی و نگاشت</button></div>
230 - </div>`).join("")}</div>
231 - </div>` : `<div class="card" style="margin-top:14px"><b style="color:var(--green)">✓ هیچ استثنایی باقی نمانده است.</b></div>`;
232 - $("#tab-dashboard").innerHTML = `
233 - <div class="grid checks-grid">${report.checks.map((ch) => `
234 - <div class="check-card ${ch.passed ? "pass" : "fail"}">
235 - <div class="check-name">${esc(ch.name_fa)}</div>
236 - <div class="check-state">${ch.passed ? "✓ قبول" : "✗ رد"}</div>
237 - ${ch.amount !== null ? `<div class="check-amount">${fmt(ch.amount)}</div>` : ""}
238 - <div class="check-details">${esc(ch.details)}</div>
239 - </div>`).join("")}</div>
240 - <div class="card"><b>پوشش نگاشت:</b> ${cov.mapped_accounts} از ${cov.total_accounts} حساب (${pct}٪)
241 - <div class="coverage-bar-wrap" style="margin-top:8px"><div class="coverage-bar" style="width:${pct}%"></div></div></div>
242 - <div class="grid totals-grid">
243 - ${totalCard("جمع دارایی‌ها", t.assets)}${totalCard("جمع بدهی‌ها", t.liabilities)}
244 - ${totalCard("حقوق مالکانه", t.equity)}${totalCard("درآمدها", t.revenue)}
245 - ${totalCard("هزینه‌ها", t.expenses)}${totalCard("سود (زیان) دوره", t.profit, true)}
246 - </div>${exceptions}`;
247 -}
248 -
249 -/* ---------------- accounts ---------------- */
250 -function mappingSummary(a) {
251 - if (a.conflict) return `<span class="approval-chip approval-none">تعارض نگاشت</span>`;
252 - if (!a.mapping) return `<span class="approval-chip approval-none">بدون نگاشت</span>`;
253 - const m = a.mapping;
254 - const note = S.data.notes.find((n) => n.statement === m.statement && n.section === m.section && n.note_number === m.note_number && n.subnote_code === m.subnote_code);
255 - const label = note ? `${note.note_number} — ${note.note_title}` : m.note_number;
256 - return `<span class="mono">${esc(m.statement)}/${esc(m.section)}</span> · ${esc(label)} <span class="approval-chip approval-${esc(m.approval_status)}">${APPROVAL_FA[m.approval_status] || m.approval_status}</span>`;
257 -}
258 -function filteredAccounts() {
259 - const q = S.search.trim();
260 - return S.data.accounts.filter((a) => {
261 - if (S.filter === "unmapped" && a.mapping) return false;
262 - if (S.filter === "unapproved" && a.mapping?.approval_status === "Approved") return false;
263 - if (S.filter === "conflict" && !a.conflict) return false;
264 - if (q && !(a.code.includes(q) || a.name.includes(q))) return false;
265 - return true;
266 - });
267 -}
268 -function accountCard(a) {
269 - return `<div class="item-card">
270 - <div class="item-top">
271 - <div><div class="item-title">${esc(a.name)}</div><div class="item-code mono">${esc(a.code)} · کل ${esc(a.general_code)} · سطر ${a.source_row}</div></div>
272 - <span class="item-amount${isNeg(a.closing) ? " neg" : ""}">${fmt(a.closing)}</span>
273 - </div>
274 - <div class="item-sub">${mappingSummary(a)}</div>
275 - <div class="item-actions">
276 - <button class="btn small primary" data-action="map-account" data-code="${esc(a.code)}">${a.mapping ? "ویرایش نگاشت" : "تعیین مقصد"}</button>
277 - <button class="btn small" data-action="edit-account" data-code="${esc(a.code)}">ویرایش حساب</button>
278 - <button class="btn small" data-action="rename-account" data-code="${esc(a.code)}">تغییر کد</button>
279 - <button class="btn small danger" data-action="delete-account" data-code="${esc(a.code)}">حذف</button>
280 - </div>
281 - </div>`;
282 -}
283 -function updateAccList() {
284 - const list = $("#acc-list"); if (!list) return;
285 - const rows = filteredAccounts().map(accountCard).join("");
286 - list.innerHTML = rows || `<div class="card muted">حسابی با این فیلتر یافت نشد.</div>`;
287 -}
288 -function renderAccounts() {
289 - $("#tab-accounts").innerHTML = `
290 - <div class="table-toolbar">
291 - <input type="search" id="acc-search" placeholder="جستجوی کد یا نام…" value="${esc(S.search)}">
292 - <select id="acc-filter">
293 - <option value="all">همه</option><option value="unmapped">بدون نگاشت</option>
294 - <option value="unapproved">تأییدنشده</option><option value="conflict">تعارض</option>
295 - </select>
296 - <button class="btn accent small" data-action="add-account">+ حساب جدید</button>
297 - </div>
298 - <p class="muted">${S.data.accounts.length} حساب · مانده بدهکار-مثبت · هر تغییر در ردّ ممیزی ثبت می‌شود</p>
299 - <div class="item-list" id="acc-list"></div>`;
300 - $("#acc-filter").value = S.filter;
301 - $("#acc-search").oninput = (e) => { S.search = e.target.value; updateAccList(); };
302 - $("#acc-filter").onchange = (e) => { S.filter = e.target.value; updateAccList(); };
303 - updateAccList();
304 -}
305 -
306 -/* ---------------- account forms ---------------- */
307 -function accountFormHtml(a) {
308 - const v = a || { full_code: "", name: "", general_code: "", general_name: "", opening: "0", debit: "0", credit: "0", subsidiary_code: "", subsidiary_name: "", row_status: "Draft" };
309 - const codeField = a
310 - ? `<div class="form-field full"><span>کد حساب (ثابت)</span><input value="${esc(v.full_code)}" disabled></div>`
311 - : `<div class="form-field full"><span>کد کامل حساب *</span><input id="f-code" value="${esc(v.full_code)}" placeholder="مثلاً 1201"></div>`;
312 - return `<div class="form-grid">
313 - ${codeField}
314 - <div class="form-field full"><span>نام حساب *</span><input id="f-name" value="${esc(v.name)}"></div>
315 - <div class="form-field"><span>کد حساب کل *</span><input id="f-gencode" value="${esc(v.general_code)}"></div>
316 - <div class="form-field"><span>نام حساب کل *</span><input id="f-genname" value="${esc(v.general_name)}"></div>
317 - <div class="form-field"><span>کد معین (اختیاری)</span><input id="f-subcode" value="${esc(v.subsidiary_code)}"></div>
318 - <div class="form-field"><span>نام معین (اختیاری)</span><input id="f-subname" value="${esc(v.subsidiary_name)}"></div>
319 - <div class="form-field"><span>مانده ابتدای دوره</span><input id="f-opening" inputmode="decimal" value="${esc(v.opening)}"></div>
320 - <div class="form-field"><span>گردش بدهکار</span><input id="f-debit" inputmode="decimal" value="${esc(v.debit)}"></div>
321 - <div class="form-field"><span>گردش بستانکار</span><input id="f-credit" inputmode="decimal" value="${esc(v.credit)}"></div>
322 - <div class="form-field"><span>وضعیت سطر</span><select id="f-rowstatus">
323 - <option value="Draft">Draft</option><option value="Reviewed">Reviewed</option><option value="Approved">Approved</option>
324 - </select></div>
325 - <div class="form-field full"><span>مانده پایان دوره (محاسبه‌شده)</span><div class="computed-box">بدهکار+ = <b id="f-closing">—</b></div></div>
326 - </div>
327 - <p class="form-hint">مانده پایان دوره از «ابتدای دوره + بدهکار − بستانکار» محاسبه می‌شود؛ هیچ مبلغی حدس زده نمی‌شود.</p>
328 - <div class="form-actions">
329 - <button class="btn primary" data-action="submit-account" data-code="${a ? esc(a.code) : ""}">${a ? "ذخیره تغییرات" : "افزودن حساب"}</button>
330 - <button class="btn ghost" data-action="close-sheet">انصراف</button>
331 - </div>`;
332 -}
333 -function wireAccountForm(a) {
334 - $("#f-rowstatus").value = a?.row_status || "Draft";
335 - const calc = () => {
336 - const o = parseFloat($("#f-opening").value) || 0, d = parseFloat($("#f-debit").value) || 0, c = parseFloat($("#f-credit").value) || 0;
337 - $("#f-closing").textContent = fmt(String(o + d - c));
338 - };
339 - ["f-opening", "f-debit", "f-credit"].forEach((id) => $("#" + id).addEventListener("input", calc));
340 - calc();
341 -}
342 -function submitAccount(code) {
343 - const body = {
344 - sid: sid(), name: $("#f-name").value, general_code: $("#f-gencode").value, general_name: $("#f-genname").value,
345 - opening: $("#f-opening").value || "0", debit: $("#f-debit").value || "0", credit: $("#f-credit").value || "0",
346 - row_status: $("#f-rowstatus").value, subsidiary_code: $("#f-subcode").value, subsidiary_name: $("#f-subname").value,
347 - actor: actor(),
348 - };
349 - try {
350 - if (code) applyPayload(call("update_account", { ...body, code }));
351 - else applyPayload(call("add_account", { ...body, full_code: $("#f-code").value }));
352 - closeSheet(); toast(code ? "حساب ویرایش شد." : "حساب جدید افزوده شد؛ اکنون مقصدش را تعیین کنید.", "success");
353 - } catch (err) { toast(err.message, "error"); }
354 -}
355 -function openRename(a) {
356 - openSheet("تغییر کد حساب", `<div class="form-grid">
357 - <div class="form-field full"><span>کد فعلی</span><input value="${esc(a.code)}" disabled></div>
358 - <div class="form-field full"><span>کد جدید *</span><input id="f-newcode" placeholder="کد جدید"></div>
359 - </div><p class="form-hint">نگاشت این حساب به‌صورت خودکار به کد جدید منتقل می‌شود.</p>
360 - <div class="form-actions"><button class="btn primary" data-action="submit-rename" data-code="${esc(a.code)}">تغییر کد</button>
361 - <button class="btn ghost" data-action="close-sheet">انصراف</button></div>`);
362 -}
363 -function submitRename(code) {
364 - try {
365 - applyPayload(call("rename_account", { sid: sid(), code, new_code: $("#f-newcode").value, actor: actor() }));
366 - closeSheet(); toast("کد حساب تغییر کرد و نگاشت منتقل شد.", "success");
367 - } catch (err) { toast(err.message, "error"); }
368 -}
369 -function deleteAccount(code) {
370 - if (!confirm(`حساب ${code} و نگاشت آن حذف شود؟`)) return;
371 - try { applyPayload(call("delete_account", { sid: sid(), code, actor: actor() })); toast("حساب حذف شد.", "success"); }
372 - catch (err) { toast(err.message, "error"); }
373 -}
374 -
375 -/* ---------------- mapping form ---------------- */
376 -function noteOptions(statement, section) {
377 - return S.data.notes.filter((n) => n.statement === statement && n.section === section);
378 -}
379 -function openMapping(a) {
380 - const m = a.mapping || {};
381 - const statements = [...S.meta.rendered_statements, ...S.meta.deferred_statements];
382 - openSheet(`نگاشت حساب ${a.code}`, `<div class="form-grid">
383 - <div class="form-field full"><span>حساب</span><input value="${esc(a.code)} — ${esc(a.name)}" disabled></div>
384 - <div class="form-field"><span>صورت مالی</span><select id="m-statement">${statements.map((st) => `<option value="${st}">${esc(S.meta.statement_labels_fa[st])} (${st})</option>`).join("")}</select></div>
385 - <div class="form-field"><span>بخش</span><select id="m-section"></select></div>
386 - <div class="form-field full"><span>یادداشت / زیریادداشت</span><select id="m-note"></select></div>
387 - <div class="form-field"><span>وضعیت تأیید</span><select id="m-approval">
388 - <option value="Draft">Draft</option><option value="Reviewed">Reviewed</option><option value="Approved">Approved</option>
389 - </select></div>
390 - <div class="form-field"><span>نام بازبین</span><input id="m-reviewer" value="${esc(m.reviewer || actor())}" placeholder="برای Reviewed/Approved الزامی"></div>
391 - </div>
392 - <div class="form-actions">
393 - <button class="btn primary" data-action="submit-mapping" data-code="${esc(a.code)}">ثبت نگاشت</button>
394 - ${a.mapping ? `<button class="btn danger" data-action="clear-mapping" data-code="${esc(a.code)}">حذف نگاشت</button>` : ""}
395 - <button class="btn ghost" data-action="close-sheet">انصراف</button>
396 - </div>`, () => {
397 - const stSel = $("#m-statement"), secSel = $("#m-section"), noteSel = $("#m-note");
398 - stSel.value = m.statement || "BS";
399 - const fillSections = () => {
400 - const st = stSel.value;
401 - const sections = S.meta.section_policy[st] ? Object.keys(S.meta.section_policy[st])
402 - : [...new Set(S.data.notes.filter((n) => n.statement === st).map((n) => n.section))];
403 - secSel.innerHTML = sections.map((sec) => `<option value="${esc(sec)}">${esc(S.meta.section_labels_fa[sec] || sec)}</option>`).join("");
404 - if (m.section && sections.includes(m.section)) secSel.value = m.section;
405 - fillNotes();
406 - };
407 - const fillNotes = () => {
408 - const opts = noteOptions(stSel.value, secSel.value);
409 - noteSel.innerHTML = opts.length ? opts.map((n) => {
410 - const val = `${n.note_number}|${n.subnote_code}`;
411 - const label = `${n.note_number} — ${n.note_title}${n.subnote_code ? ` / ${n.subnote_code} ${n.subnote_title}` : ""}`;
412 - return `<option value="${esc(val)}">${esc(label)}</option>`;
413 - }).join("") : `<option value="">— یادداشتی تعریف نشده؛ ابتدا از زبانهٔ یادداشت‌ها اضافه کنید —</option>`;
414 - const cur = `${m.note_number}|${m.subnote_code || ""}`;
415 - if ([...noteSel.options].some((o) => o.value === cur)) noteSel.value = cur;
416 - };
417 - stSel.onchange = fillSections; secSel.onchange = fillNotes; fillSections();
418 - $("#m-approval").value = m.approval_status || "Draft";
419 - });
420 -}
421 -function submitMapping(code) {
422 - const noteVal = $("#m-note").value;
423 - if (!noteVal) { toast("برای این بخش یادداشتی نیست؛ ابتدا یادداشت اضافه کنید.", "error"); return; }
424 - const [note_number, subnote_code] = noteVal.split("|");
425 - const approval_status = $("#m-approval").value, reviewer = $("#m-reviewer").value.trim();
426 - if (approval_status !== "Draft" && !reviewer) { toast("برای Reviewed/Approved نام بازبین الزامی است.", "error"); return; }
427 - try {
428 - applyPayload(call("set_mapping", { sid: sid(), code, statement: $("#m-statement").value, section: $("#m-section").value, note_number, subnote_code: subnote_code || "", approval_status, reviewer, actor: actor() }));
429 - closeSheet(); toast(`نگاشت حساب ${code} ثبت شد.`, "success");
430 - } catch (err) { toast(err.message, "error"); }
431 -}
432 -function clearMapping(code) {
433 - try { applyPayload(call("clear_mapping", { sid: sid(), code, actor: actor() })); closeSheet(); toast("نگاشت حذف شد.", "success"); }
434 - catch (err) { toast(err.message, "error"); }
435 -}
436 -
437 -/* ---------------- notes ---------------- */
438 -function updateNoteList() {
439 - const list = $("#note-list"); if (!list) return;
440 - const q = S.noteSearch.trim();
441 - const notes = S.data.notes.filter((n) => !q || n.note_number.includes(q) || n.note_title.includes(q) || n.section.includes(q));
442 - const groups = {};
443 - for (const n of notes) { const k = `${n.statement}|${n.section}`; (groups[k] = groups[k] || []).push(n); }
444 - const usedKeys = new Set(S.data.accounts.filter((a) => a.mapping).map((a) => `${a.mapping.statement}|${a.mapping.section}|${a.mapping.note_number}|${a.mapping.subnote_code}`));
445 - let html = "";
446 - const order = Object.keys(groups).sort();
447 - if (!order.length) html = `<div class="card muted">یادداشتی یافت نشد.</div>`;
448 - for (const k of order) {
449 - const [st, sec] = k.split("|");
450 - html += `<div class="section-label">${esc(S.meta.statement_labels_fa[st] || st)} / ${esc(S.meta.section_labels_fa[sec] || sec)}</div><div class="item-list">`;
451 - for (const n of groups[k].sort((a, b) => a.note_number.localeCompare(b.note_number) || a.subnote_code.localeCompare(b.subnote_code))) {
452 - const key = `${n.statement}|${n.section}|${n.note_number}|${n.subnote_code}`;
453 - const inUse = usedKeys.has(key);
454 - html += `<div class="item-card">
455 - <div class="item-top">
456 - <div><div class="item-title">${esc(n.note_title)}${n.subnote_code ? ` <span class="muted">/ ${esc(n.subnote_code)} ${esc(n.subnote_title)}</span>` : ""}</div>
457 - <div class="item-code mono">یادداشت ${esc(n.note_number)}${n.subnote_code ? ` · زیریادداشت ${esc(n.subnote_code)}` : ""}</div></div>
458 - ${inUse ? `<span class="approval-chip approval-Approved">در استفاده</span>` : `<span class="approval-chip">آزاد</span>`}
459 - </div>
460 - <div class="item-actions">
461 - <button class="btn small" data-action="edit-note" data-key="${esc(key)}">ویرایش عنوان</button>
462 - <button class="btn small danger" data-action="delete-note" data-key="${esc(key)}" ${inUse ? 'title="ابتدا نگاشت‌های متصل را جابه‌جا کنید"' : ""}>حذف</button>
463 - </div>
464 - </div>`;
465 - }
466 - html += `</div>`;
467 - }
468 - list.innerHTML = html;
469 -}
470 -function renderNotes() {
471 - $("#tab-notes").innerHTML = `<div class="table-toolbar">
472 - <input type="search" id="note-search" placeholder="جستجوی یادداشت…" value="${esc(S.noteSearch)}">
473 - <button class="btn accent small" data-action="add-note">+ یادداشت جدید</button>
474 - </div><p class="muted">${S.data.notes.length} یادداشت/زیریادداشت · مقصدهای نگاشت از اینجا تعریف می‌شوند</p>
475 - <div id="note-list"></div>`;
476 - $("#note-search").oninput = (e) => { S.noteSearch = e.target.value; updateNoteList(); };
477 - updateNoteList();
478 -}
479 -function noteFormHtml(n) {
480 - const statements = [...S.meta.rendered_statements, ...S.meta.deferred_statements];
481 - const v = n || { statement: "BS", section: "Assets", note_number: "", note_title: "", subnote_code: "", subnote_title: "" };
482 - const keyLocked = !!n;
483 - return `<div class="form-grid">
484 - <div class="form-field"><span>صورت مالی</span><select id="n-statement" ${keyLocked ? "disabled" : ""}>${statements.map((st) => `<option value="${st}">${esc(S.meta.statement_labels_fa[st])} (${st})</option>`).join("")}</select></div>
485 - <div class="form-field"><span>بخش *</span><input id="n-section" value="${esc(v.section)}" ${keyLocked ? "disabled" : ""} placeholder="Assets / Liabilities / …"></div>
486 - <div class="form-field"><span>شماره یادداشت *</span><input id="n-number" value="${esc(v.note_number)}" ${keyLocked ? "disabled" : ""}></div>
487 - <div class="form-field"><span>کد زیریادداشت (اختیاری)</span><input id="n-subcode" value="${esc(v.subnote_code)}" ${keyLocked ? "disabled" : ""}></div>
488 - <div class="form-field full"><span>عنوان یادداشت *</span><input id="n-title" value="${esc(v.note_title)}"></div>
489 - <div class="form-field full"><span>عنوان زیریادداشت</span><input id="n-subtitle" value="${esc(v.subnote_title)}"></div>
490 - </div>
491 - ${keyLocked ? `<p class="form-hint">کلید یادداشت ثابت است؛ فقط عنوان‌ها ویرایش می‌شوند.</p>` : `<p class="form-hint">برای زیریادداشت، کد و عنوان آن را پر کنید. بخش‌های استاندارد: Assets، Liabilities، Equity، Revenue، Expenses.</p>`}
492 - <div class="form-actions">
493 - <button class="btn primary" data-action="submit-note" data-key="${n ? esc(`${n.statement}|${n.section}|${n.note_number}|${n.subnote_code}`) : ""}">${n ? "ذخیره عنوان" : "افزودن یادداشت"}</button>
494 - <button class="btn ghost" data-action="close-sheet">انصراف</button>
495 - </div>`;
496 -}
497 -function submitNote(key) {
498 - const body = {
499 - sid: sid(), statement: $("#n-statement").value, section: $("#n-section").value,
500 - note_number: $("#n-number").value, note_title: $("#n-title").value,
501 - subnote_code: $("#n-subcode").value, subnote_title: $("#n-subtitle").value, actor: actor(),
502 - };
503 - try {
504 - if (key) { const [st, sec, num, sub] = key.split("|"); Object.assign(body, { statement: st, section: sec, note_number: num, subnote_code: sub }); }
505 - applyPayload(call(key ? "update_note" : "add_note", body));
506 - closeSheet(); toast(key ? "عنوان یادداشت ویرایش شد." : "یادداشت جدید افزوده شد.", "success");
507 - } catch (err) { toast(err.message, "error"); }
508 -}
509 -function deleteNote(key) {
510 - const [statement, section, note_number, subnote_code] = key.split("|");
511 - if (!confirm("این یادداشت حذف شود؟")) return;
512 - try {
513 - applyPayload(call("delete_note", { sid: sid(), statement, section, note_number, subnote_code, actor: actor() }));
514 - toast("یادداشت حذف شد.", "success");
515 - } catch (err) { toast(err.message, "error"); }
516 -}
517 -
518 -/* ---------------- statements ---------------- */
519 -function renderStatements() {
520 - const code = S.statementView;
521 - const { report } = S.data, st = report.statements[code], c = report.company;
522 - const sections = st.sections.map((sec) => `
523 - <div class="statement-section">
524 - <div class="section-head"><span>${esc(sec.label_fa)}</span><span class="note-total${isNeg(sec.total) ? " neg" : ""}">${fmt(sec.total)}</span></div>
525 - ${sec.lines.map((line) => {
526 - const key = `${code}|${sec.name}|${line.note_number}|${line.subnote_code}`;
527 - const open = S.expanded.has(key);
528 - const title = `${line.note_title}${line.subnote_code ? ` / ${line.subnote_code} ${line.subnote_title}` : ""}`;
529 - return `<div class="note-line" data-action="toggle-line" data-key="${esc(key)}">
530 - <span class="note-title"><span class="note-number">${esc(line.note_number)}</span>${esc(title)} <span class="muted">${open ? "▾" : "◂"} ${line.accounts.length} حساب</span></span>
531 - <span class="note-total${isNeg(line.total) ? " neg" : ""}">${fmt(line.total)}</span></div>
532 - ${open ? `<div class="drill"><div class="table-wrap"><table>
533 - <thead><tr><th>کد</th><th>حساب</th><th class="num">مانده دفتر</th><th class="num">نمایشی</th><th>سطر</th><th>تأیید</th></tr></thead>
534 - <tbody>${line.accounts.map((a) => `<tr><td class="mono">${esc(a.code)}</td><td>${esc(a.name)}</td>${numCell(a.closing)}${numCell(a.display)}<td class="num">${a.source_row}</td><td><span class="approval-chip approval-${esc(a.approval_status)}">${APPROVAL_FA[a.approval_status] || a.approval_status}</span></td></tr>`).join("")}</tbody>
535 - </table></div></div>` : ""}`;
536 - }).join("") || `<div class="note-line muted">رقمی در این بخش منظور نشده است.</div>`}
537 - </div>`).join("");
538 - const grand = code === "BS"
539 - ? `<div class="statement-total"><span>جمع دارایی‌ها</span><span class="note-total">${fmt(report.totals.assets)}</span></div>
540 - <div class="statement-total"><span>جمع بدهی‌ها و حقوق مالکانه</span><span class="note-total">${fmt(report.totals.liabilities_and_equity)}</span></div>`
541 - : `<div class="statement-total"><span>سود (زیان) دوره</span><span class="note-total${isNeg(report.totals.profit) ? " neg" : ""}">${fmt(report.totals.profit)}</span></div>`;
542 - $("#tab-statements").innerHTML = `
543 - <div class="statement-tools">
544 - <div class="segmented">
545 - <button data-action="view-statement" data-code="BS" class="${code === "BS" ? "active" : ""}">ترازنامه</button>
546 - <button data-action="view-statement" data-code="IS" class="${code === "IS" ? "active" : ""}">سود و زیان</button>
547 - </div>
548 - <button class="btn small ghost" data-action="print">🖨 چاپ</button>
549 - </div>
550 - <div class="statement-paper">
551 - <div class="statement-head"><h2>${esc(st.label_fa)}</h2>
552 - <div class="sub">${esc(c.name)} — سال مالی ${c.fiscal_year} — به ${esc(c.unit || "واحد نامشخص")}</div>
553 - <span class="draft-watermark">${STATUS_FA[report.status.label]} · پیش‌نویس کاری، نه صورت مالی رسمی</span></div>
554 - ${sections}${grand}
555 - ${code === "BS" ? `<p class="muted">سود دوره (${fmt(report.totals.profit)}) از طریق معادلهٔ حسابداری در حقوق مالکانه کنترل می‌شود.</p>` : ""}
556 - </div>`;
557 -}
558 -
559 -/* ---------------- more / audit / export ---------------- */
560 -function renderMore() {
561 - const { report, session, audit_trail: trail } = S.data, c = report.company;
562 - const prov = (k, v, mono = false) => `<div class="prov-item"><div class="k">${k}</div><div class="v${mono ? " mono" : ""}">${esc(v)}</div></div>`;
563 - $("#tab-more").innerHTML = `
564 - <div class="card" style="margin-bottom:14px">
565 - <h3 style="margin-top:0">شرکت و سال مالی</h3>
566 - <div class="provenance-grid">
567 - ${prov("نام", c.name)}${prov("کد", c.code, true)}${prov("سال مالی", c.fiscal_year)}
568 - ${prov("واحد", c.unit || "—")}${prov("ارز", c.currency || "—")}
569 - </div>
570 - <button class="btn block" data-action="edit-company">ویرایش اطلاعات شرکت</button>
571 - </div>
572 - <div class="card" style="margin-bottom:14px">
573 - <h3 style="margin-top:0">خروجی و ذخیره</h3>
574 - <div class="action-stack">
575 - <button class="btn primary block" data-action="export-report">⬇ دانلود گزارش اکسل (صورت‌ها + کنترل‌ها + ردّ ممیزی)</button>
576 - <button class="btn accent block" data-action="export-workspace">💾 ذخیرهٔ کارگاه (قابل آپلود مجدد برای ادامهٔ کار)</button>
577 - <button class="btn danger block" data-action="delete-session">حذف جلسه از حافظه</button>
578 - </div>
579 - <p class="muted">جلسه‌ها فقط در حافظهٔ مرورگر هستند؛ «ذخیرهٔ کارگاه» را دانلود کنید و بعداً دوباره آپلود کنید تا کار ادامه یابد.</p>
580 - </div>
581 - <div class="card" style="margin-bottom:14px">
582 - <h3 style="margin-top:0">شناسنامه</h3>
583 - <div class="provenance-grid">
584 - ${prov("SHA-256 فایل ورودی", report.source_sha256, true)}
585 - ${prov("زمان ایجاد (UTC)", session.created_at, true)}
586 - ${prov("منبع", session.source === "demo" ? "دموی ساختگی" : `فایل ${session.filename}`)}
587 - ${prov("نسخهٔ موتور", report.engine_version, true)}
588 - </div>
589 - </div>
590 - <div class="card">
591 - <h3 style="margin-top:0">ردّ ممیزی (${trail.length})</h3>
592 - ${trail.length ? `<div class="table-wrap"><table>
593 - <thead><tr><th>زمان</th><th>کاربر</th><th>حساب</th><th>اقدام</th><th>قبل</th><th>بعد</th></tr></thead>
594 - <tbody>${trail.map((e) => `<tr><td class="mono">${esc(e.at)}</td><td>${esc(e.actor)}</td><td class="mono">${esc(e.account_code)}</td><td>${esc(e.action)}</td><td class="mono">${esc(e.before)}</td><td class="mono">${esc(e.after)}</td></tr>`).join("")}</tbody>
595 - </table></div>` : `<p class="muted">هنوز تغییری ثبت نشده است.</p>`}
596 - </div>`;
597 -}
598 -function openCompany() {
599 - const c = S.data.report.company;
600 - openSheet("ویرایش شرکت", `<div class="form-grid">
601 - <div class="form-field full"><span>نام شرکت *</span><input id="c-name" value="${esc(c.name)}"></div>
602 - <div class="form-field"><span>کد شرکت *</span><input id="c-code" value="${esc(c.code)}"></div>
603 - <div class="form-field"><span>سال مالی *</span><input id="c-year" inputmode="numeric" value="${c.fiscal_year}"></div>
604 - <div class="form-field"><span>واحد پول</span><input id="c-unit" value="${esc(c.unit)}"></div>
605 - <div class="form-field"><span>ارز</span><input id="c-currency" value="${esc(c.currency)}"></div>
606 - <div class="form-field full"><span>تهیه‌کننده</span><input id="c-prepared" value="${esc(c.prepared_by)}"></div>
607 - </div>
608 - <div class="form-actions"><button class="btn primary" data-action="submit-company">ذخیره</button>
609 - <button class="btn ghost" data-action="close-sheet">انصراف</button></div>`);
610 -}
611 -function submitCompany() {
612 - try {
613 - applyPayload(call("update_company", { sid: sid(), name: $("#c-name").value, code: $("#c-code").value, fiscal_year: parseInt($("#c-year").value, 10), unit: $("#c-unit").value, currency: $("#c-currency").value, prepared_by: $("#c-prepared").value, actor: actor() }));
614 - closeSheet(); toast("اطلاعات شرکت ویرایش شد.", "success");
615 - } catch (err) { toast(err.message, "error"); }
616 -}
617 -function exportReport() {
618 - try { const r = call("export_report", { sid: sid() }); downloadB64(r.bytes_b64, r.filename); toast("گزارش اکسل دانلود شد.", "success"); }
619 - catch (err) { toast(err.message, "error"); }
620 -}
621 -function exportWorkspace() {
622 - try { const r = call("export_workspace", { sid: sid() }); downloadB64(r.bytes_b64, r.filename); toast("ذخیرهٔ کارگاه دانلود شد.", "success"); }
623 - catch (err) { toast(err.message, "error"); }
624 -}
625 -function deleteSession() {
626 - if (!confirm("جلسه از حافظهٔ مرورگر حذف شود؟ فایل‌های دانلودشده باقی می‌مانند.")) return;
627 - try { call("delete_session", { sid: sid() }); leaveWorkspace(); toast("جلسه حذف شد.", "success"); }
628 - catch (err) { toast(err.message, "error"); }
629 -}
630 -
631 -/* ---------------- bottom sheet ---------------- */
632 -function openSheet(title, html, onMount) {
633 - $("#sheet-title").textContent = title;
634 - $("#sheet-body").innerHTML = html;
635 - $("#sheet").classList.remove("hidden");
636 - $("#sheet-backdrop").classList.remove("hidden");
637 - document.body.style.overflow = "hidden";
638 - if (onMount) onMount();
639 -}
640 -function closeSheet() {
641 - $("#sheet").classList.add("hidden");
642 - $("#sheet-backdrop").classList.add("hidden");
643 - document.body.style.overflow = "";
644 -}
645 -
646 -/* ---------------- events ---------------- */
647 -document.addEventListener("click", (e) => {
648 - const el = e.target.closest("[data-action]");
649 - if (!el) return;
650 - const { action, code, key } = el.dataset;
651 - const findAcc = (c) => S.data.accounts.find((a) => a.code === c);
652 - if (action === "close-sheet") closeSheet();
653 - else if (action === "add-account") openSheet("افزودن حساب جدید", accountFormHtml(null), () => wireAccountForm(null));
654 - else if (action === "edit-account") { const a = findAcc(code); openSheet(`ویرایش حساب ${code}`, accountFormHtml(a), () => wireAccountForm(a)); }
655 - else if (action === "submit-account") submitAccount(code);
656 - else if (action === "rename-account") openRename(findAcc(code));
657 - else if (action === "submit-rename") submitRename(code);
658 - else if (action === "delete-account") deleteAccount(code);
659 - else if (action === "map-account") openMapping(findAcc(code));
660 - else if (action === "submit-mapping") submitMapping(code);
661 - else if (action === "clear-mapping") clearMapping(code);
662 - else if (action === "resolve-exception") { S.tab = "accounts"; renderAll(); openMapping(findAcc(code)); }
663 - else if (action === "add-note") openSheet("افزودن یادداشت جدید", noteFormHtml(null), () => { $("#n-statement").value = "BS"; });
664 - else if (action === "edit-note") { const n = S.data.notes.find((x) => `${x.statement}|${x.section}|${x.note_number}|${x.subnote_code}` === key); openSheet("ویرایش یادداشت", noteFormHtml(n), () => { $("#n-statement").value = n.statement; }); }
665 - else if (action === "submit-note") submitNote(key);
666 - else if (action === "delete-note") deleteNote(key);
667 - else if (action === "view-statement") { S.statementView = code; renderStatements(); }
668 - else if (action === "toggle-line") { S.expanded.has(key) ? S.expanded.delete(key) : S.expanded.add(key); renderStatements(); }
669 - else if (action === "print") window.print();
670 - else if (action === "edit-company") openCompany();
671 - else if (action === "submit-company") submitCompany();
672 - else if (action === "export-report") exportReport();
673 - else if (action === "export-workspace") exportWorkspace();
674 - else if (action === "delete-session") deleteSession();
675 -});
676 -
677 -document.addEventListener("DOMContentLoaded", () => {
678 - $("#actor-input").value = localStorage.getItem("aram-actor") || "";
679 - $("#actor-input").addEventListener("input", (e) => localStorage.setItem("aram-actor", e.target.value));
680 - $("#upload-btn").addEventListener("click", () => $("#file-input").click());
681 - $("#file-input").addEventListener("change", (e) => { if (e.target.files[0]) uploadFile(e.target.files[0]); });
682 - $("#demo-btn").addEventListener("click", startDemo);
683 - $("#new-session-btn").addEventListener("click", leaveWorkspace);
684 - $("#sheet-close").addEventListener("click", closeSheet);
685 - $("#sheet-backdrop").addEventListener("click", closeSheet);
686 - $("#tabbar").addEventListener("click", (e) => {
687 - const tab = e.target.closest(".tab");
688 - if (!tab || !S.data) return;
689 - S.tab = tab.dataset.tab; renderAll(); window.scrollTo({ top: 0 });
690 - });
691 - boot();
692 -});
docs/archive/HISTORICAL_DISCREPANCIES.md renamed
docs/archive/MAPPING_ANALYSIS.md renamed
docs/archive/MIGRATION_PLAN.md renamed
docs/archive/NOTE_CATALOG.md renamed
docs/archive/NOTE_TO_SHEET_MATRIX.md renamed
docs/archive/NOTE_TO_STATEMENT_MATRIX.md renamed
docs/archive/PHASE_1B1_VALIDATION.md renamed
docs/archive/PHASE_1B2_VALIDATION.md renamed
docs/archive/PROJECT_AUDIT.md renamed
docs/archive/README.md new
+26
@@ -0,0 +1,26 @@
1 +# Archived analytical documents
2 +
3 +Historical root-level analytical documents (catalogs, matrices, audits, analyses)
4 +moved here in B0 per booklet §0.5 (lightweight process: no new root analytical
5 +documents; code and tests grow, not documentation). Moved with `git mv`, so file
6 +history is preserved. These are reference material, not the live status entry point.
7 +
8 +Live records: [`PROJECT_STATUS.md`](../../PROJECT_STATUS.md),
9 +[`docs/PROJECT_LOG.md`](../PROJECT_LOG.md), [`docs/adr/`](../adr/).
10 +
11 +| Document | Subject |
12 +|---|---|
13 +| HISTORICAL_DISCREPANCIES.md | Historical official-statement discrepancies (starting point for OD-08 / `docs/discrepancies.json`) |
14 +| MAPPING_ANALYSIS.md | Mapping analysis |
15 +| MIGRATION_PLAN.md | Migration plan |
16 +| NOTE_CATALOG.md | Note catalog |
17 +| NOTE_TO_SHEET_MATRIX.md | Note → workbook sheet matrix |
18 +| NOTE_TO_STATEMENT_MATRIX.md | Note → statement matrix |
19 +| PHASE_1B1_VALIDATION.md | Phase 1B-1 validation |
20 +| PHASE_1B2_VALIDATION.md | Phase 1B-2 validation |
21 +| PROJECT_AUDIT.md | Project audit |
22 +| SOURCE_INVENTORY.md | Source inventory |
23 +| SOURCE_LINEAGE_ANALYSIS.md | Source lineage analysis |
24 +| TARGET_ARCHITECTURE.md | Target architecture |
25 +| TARGET_DATA_MODEL.md | Target data model |
26 +| WORKBOOK_SHEET_CATALOG.md | Workbook sheet catalog |
docs/archive/SOURCE_INVENTORY.md renamed
docs/archive/SOURCE_LINEAGE_ANALYSIS.md renamed
docs/archive/TARGET_ARCHITECTURE.md renamed
docs/archive/TARGET_DATA_MODEL.md renamed
docs/archive/WORKBOOK_SHEET_CATALOG.md renamed
docs/booklet/BOOKLET_v1.0.md new
+641
@@ -0,0 +1,641 @@
1 +# کتابچهٔ اجرایی تکمیل Aram — نسخهٔ ۱٫۰ (سند مرجع)
2 +
3 +> **سند مرجعِ version-controlled.** این فایل متنِ استخراج‌شده از PDF اصلیِ کتابچه است
4 +> که به‌ترتیبِ منطقیِ خوانش (RTL) بازچینش شده تا در مخزن قابل‌بازبینی باشد.
5 +>
6 +> - **فایل اصلی:** «کتابچهٔ اجرایی تکمیل Aram» (PDF، 14 صفحه)
7 +> - **SHA-256 فایل اصلی:** `7dd508274babd604f74d10b692464ce42f26a88c4a7116cfd861188abd4a2baf`
8 +> - **روش استخراج:** `pymupdf` + بازچینش واژه‌ها در هر خط از ترتیب بصریِ RTL به منطقی.
9 +> - **لنگرِ یکپارچگی:** هشِ SHA-256 بالا در `MANIFEST.json`. متنِ زیر یک کمک‌خوانشِ
10 +> مشتق است؛ آرتیفکت‌های جزئیِ همزه/نشانه‌گذاری ممکن است وجود داشته باشد. مرجعِ
11 +> قطعی، فایلِ اصلی با هشِ بالاست. هیچ محتوایی جعل یا «اختراع» نشده (§19).
12 +> - فایل اصلی به‌صورت PDF ارسال شد (دستور B0.1 به docx اشاره داشت؛ منبعِ واقعیِ
13 +> موجود PDF است و هشِ همان ثبت شده). اصلِ باینری کامیت نشده (§19)؛ فقط هش.
14 +
15 +---
16 +
17 +## صفحهٔ 1
18 +
19 +ٔکتابچ اجرایی تکمیل Aram
20 +ٔنسخ ۱٫۰ — دستور کار کامل برای های‌ایجنت کدنویسی Code( Claude / Jules / .)Codex :مبنا بررسی
21 +مخزن davoodmehraban89/Aram ، ٔشاخ source-data-cleanup ، head برابر 7dc864fd…
22 +merge( ٔشد #21 .)PR
23 +.۰ ٔنحو استفاده از این کتابچه
24 +.1
25 +این کتابچه دستور کار محصول است و AGENTS.md قواعد .فرایندی در تضاد بین این :دو توقف ،کن
26 +تضاد را دقیق گزارش ،کن حدس .نزن
27 +.2
28 +پیش از هر :کار remote را fetch ،کن PROJECT_STATUS.md و docs/ACCEPTANCE_POLICY.md
29 +را ،بخوان SHA پایه را تأیید .کن اگر با وضعیت واقعی ،نخواند .توقف
30 +.3
31 +کارها فقط به ترتیب فازهای بخش ۱۵ انجام .شود‌می فاز n+1 قبل از پذیرش فاز n شروع .شود‌نمی
32 +.4
33 +هر مقدار ،مالی ٔقاعد ،نگاشت فرمول یا ٔنتیج تست که در دیتای واقعی مخزن نیست »اختراع«
34 +.شود‌نمی اگر چیزی مبهم ،است جای‌به ،حدس طبق بخش ۱۷ قواعد( تصمیم )خودکار تصمیم ،بگیر
35 +شواهدش را در ADR ثبت کن و ادامه بده؛ از مالک سؤال .نکن
36 +سازی‌سبک فرایند :)الزامی( سند تحلیلی جدید در ٔریش مخزن ساخته .نشود های‌فایل .5تحلیلی
37 +تاریخی ریشه ها‌کاتالوگ( و )ها‌ماتریس در یک PR جداگانه به docs/archive/ منتقل .شوند هر PR
38 +فقط PROJECT_STATUS.md و یک ورودی کوتاه docs/PROJECT_LOG.md را روز‌به .کند :هدف کد و
39 +تست رشد ،کند نه .مستندات
40 +.6
41 +پایان هر کار با قالب گزارش بخش ۱۸ و ٔجمل not« review; GitHub independent for Ready
42 +».merged تمام .شود‌می
43 +.۱ ،هدف دامنه و تعریف »شده‌تمام«
44 +:هدف افزار‌نرم لوکال/دسکتاپ برای ٔتهی ،کامل ردیابی‌قابل و ممیزی‌قابل های‌صورت مالی اساسی
45 +وضعیت( مالی ،BS سود و زیان ،IS جریان وجوه نقد ،CF تغییرات حقوق مالکانه )EQ و های‌یادداشت
46 +،توضیحی از روی تراز/لجر ،اصلی بر ٔپای استانداردهای حسابداری .ایران
47 +در :دامنه چند شرکت و چند سال مالی در یک نصب هر( سال ؛)ایزوله ورود لجر ؛xlsx نگاشت حساب به
48 +ردیف/یادداشت صورت؛ موتور ٔمحاسب ها‌یادداشت و ها؛‌صورت های‌کنترل مالی؛ drill-down از عدد نهایی
49 +تا ردیف منبع؛ گردش کار نویس‌پیش ← بازبینی ← تأیید ← قفل؛ خروجی ؛Excel/PDF رابط فارسی
50 +چپ؛‌به‌راست اجرای ًکام آفالین روی .Windows
51 +خارج از دامنه مگر( با تصمیم صریح :)مالک های‌صورت ،تلفیقی محاسبات ،مالیاتی SaaS و
52 +،چندمستأجری ثبت سند ،حسابداری ارتباط آنالین با هر سرویس .بیرونی
53 +تعریف »شده‌تمام« ٔهم( موارد با :)شواهد
54 +14 of 1 Page
55 +
56 +---
57 +
58 +## صفحهٔ 2
59 +
60 +تولیدشده با های‌صورت رسمی IS و BS لجر واقعی سال ۱۴۰۴ ورود شود‌می و های‌صورت D1:
61 +در ٔهم های‌ردیف دار‌جمع ریال به ریال برابرند یا( ها‌اختالف data/official_statements
62 +یک‌به‌یک. در گزارش توجیه )اند‌شده
63 +همین برای ،۱۴۰۳ و پیوستگی سال به سال مانده( پایان ۱۴۰۳ = ابتدای )۱۴۰۴ خودکار کنترل D2:
64 +شود‌می.
65 +drill-down هر عدد در هر صورت و یادداشت تا ردیف لجر منبع ،فایل( ،شیت ٔشمار )ردیف قابل D3:
66 +است.
67 +تواند‌نمی تغییر دهد؛ تست bulk) خام، SQL (API، سال شده‌قفل/تأییدشده را هیچ مسیری D4:
68 +خام. این را ثابت کند‌می SQL خودکار با
69 +ٔهم. های‌کنترل بخش ۷ پیاده و در گزارش خروجی دیده شوند؛‌می کنترل ناموفق مانع تأیید است D5:
70 +و) بدون اینترنت Python ماشین (بدون بازتولیدپذیر است و در محیط تمیز Windows ٔبست نصبی D6:
71 +بدون. خطا اجرا شود‌می
72 +و. ٔآستان پوشش pip-audit e2e، تست pytest، mypy، ruff، سبز با CI D7:
73 +توسط. مالک روی داده واقعی با سناریوهای بخش ۱۴ امضا شده است (UAT) پذیرش کاربری D8:
74 +.۲ وضعیت فعلی و های‌بدهی اجباری فاز( )۰
75 +پیش از هر قابلیت ،جدید موارد زیر باید رفع و با تست ثابت .شوند هر ردیف یک PR کوچک و متمرکز .است
76 +مشکل از( بررسی شناسه)مخزن
77 +الزام رفع
78 +تست پذیرش
79 +هیچ جدولی برای ٔماند D-01ها‌حساب
80 +)opening/debit/credit/closing( وجود
81 +ندارد؛ خروجی ledger_parser جایی
82 +ذخیره شود‌نمی
83 +مدل LedgerBalance
84 +بخش( )۵ و مهاجرت
85 +ورود ٔنمون کوچک و
86 +خواندن دقیق مقادیر
87 +D-02
88 +فقط یکتایی mapping_id را preflight
89 +:سنجد‌می یک حساب تواند‌می دو بار نگاشت
90 +شود شمارش( ؛)مضاعف حساب بدون
91 +نگاشت با مانده غیرصفر و تراز کل جمع(
92 +بدهکار = جمع )بستانکار کنترل شود‌نمی
93 +های‌کنترل C-03، C-02،
94 +C-04 بخش ۷
95 +های‌تست منفی برای
96 +هر سه
97 +Numeric(24,4) روی SQLite D-03فرض‌پیش(
98 +sqlite:/// ) به float ذخیره شود‌می و
99 +مبالغ بزرگ ریالی صدا‌بی گرد شوند‌می
100 +ٔذخیر مبلغ صورت‌به عدد
101 +صحیح دار‌مقیاس بخش(
102 +،۳ )P-02
103 +تست property-
104 +based با
105 +Hypothesis:
106 +round-trip دقیق تا
107 +۱۸ رقم
108 +14 of 2 Page
109 +
110 +---
111 +
112 +## صفحهٔ 3
113 +
114 +مشکل از( بررسی شناسه)مخزن
115 +الزام رفع
116 +تست پذیرش
117 +D-04
118 +ledger_parser کدهای عددی را به int
119 +تبدیل کند‌می و صفر ابتدایی پرد‌می
120 +( →0101 101 ،) در حالی که preflight
121 +همین را ممنوع کرده؛ ارقام عربی/فارسی
122 +پشتیبانی شوند؛‌نمی مقدار float اکسل از
123 +str(float) عبور کند‌می
124 +یک تابع واحد سازی‌نرمال
125 +بخش( ؛)۸ کد عددی خام
126 +→ خطای ،صریح نه تبدیل
127 +صدا‌بی
128 +تست با کد 0101 ،
129 +ارقام ،فارسی float
130 +مثل 0.1+0.2
131 +نام ها‌شیت با »ك/ي« عربی کد‌سخت شده D-05و
132 +سازی‌نرمال ندارد
133 +ٔمقایس هدر/شیت پس از
134 +سازی‌نرمال ،ک/ی
135 +NBSP ZWNJ،
136 +فایل با ک/ی فارسی
137 +پذیرفته شود‌می
138 +D-06
139 +بایت فایل منبع ذخیره ،شود‌نمی فقط SHA-
140 +؛256 .csv مجاز است ولی parser ندارد
141 +ٔذخیر content-
142 +addressed فایل منبع
143 +بخش( ؛)۵ یا CSV کامل
144 +پشتیبانی شود یا از
145 +مجازها حذف شود
146 +ورود دوباره از روی
147 +فایل شده‌ذخیره و
148 +تطابق hash
149 +D-07
150 +قفل سال فقط در before_flush ORM
151 +:است با update bulk و SQL خام دور زده
152 +شود؛‌می برای هر آبجکت کوئری زند‌می
153 +؛)N+1( کاربر و log audit ندارد؛ مسیر
154 +بازگشایی ٔشد‌کنترل سال تأییدشده نیست
155 +تریگرهای سطح ،دیتابیس
156 +log audit ،ای‌زنجیره
157 +گردش کار بازگشایی
158 +بخش( )۱۳
159 +تست با UPDATE
160 +خام که باید شکست
161 +بخورد
162 +PROJECT_STATUS.md گوید‌می V1-01 D-08در
163 +جریان ،است اما head همان #21 merge
164 +است
165 +سازی‌همگام و حذف
166 +های‌ریسک شده‌رفع
167 +بازبینی دستی در PR
168 +دو فایل xlsx حدود ۲۴ و ۳۲ مگابایت D-09در
169 +ٔتاریخچ اند‌گیت
170 +انتقال به LFS Git یا
171 +بیرون مخزن با ثبت hash
172 +در مانیفست؛ بازنویسی
173 +تاریخچه فقط با تأیید
174 +صریح مالک
175 +ٔانداز clone و
176 +مانیفست hash
177 +دو گذاری‌نام برای یک :مراتب‌سلسله D-10لجر
178 +T1..T4 و Pilot
179 +؛general/subsidiary/detail1..4
180 +نگاشت مستند بین ها‌آن نیست
181 +با نگاشت رسمی؛ ADR
182 +تصمیم (باز مالک تأیید کند
183 +OD-01)
184 +تست تبدیل دوطرفه
185 +D-11
186 +worksheet.max_column در حالت read-
187 +only ممکن است None باشد و min()
188 +خطا دهد
189 +محافظت صریح و تست
190 +با فایل بدون dimension
191 +فایل تولیدشده با
192 +ابزار دیگر
193 +14 of 3 Page
194 +
195 +---
196 +
197 +## صفحهٔ 4
198 +
199 +.۳ اصول مذاکره‌غیرقابل
200 +منبع :مقدس ٔداد منبع هرگز ویرایش .شود‌نمی هر تصحیحی ٔالی جدا اصالحیه( با دلیل و )کاربر P-01
201 +،است. نه تغییر مقدار
202 +(،ریال در .جا‌هیچ مبلغ در دیتابیس صورت‌به عدد صحیح دار‌مقیاس float دقت :مالی هیچ P-02
203 +Decimal ذخیره و در پایتون TypeDecorator با ثبت) شود ADR مقیاس از ٔداد واقعی تعیین و در
204 +.است. گرد کردن فقط در یک تابع مرکزی با ٔقاعد شده‌ثبت انجام شود‌می
205 +کدها. :اند‌متن کد یادداشت/حساب هرگز عدد نیست؛ صفر ابتدایی و طول حفظ شود‌می P-03
206 +عبور. کند‌می normalize_fa سازی‌نرمال :جا‌یک ٔهم ورودی متنی فارسی از یک تابع P-04
207 +:قطعیت با ورودی و پیکربندی ،یکسان خروجی بایت‌به‌بایت یکسان است ترتیب( ،پایدار بدون P-05
208 +ها‌ورودی. و ٔنسخ کد را ثبت کند‌می hash وابستگی به .)تصادف/زمان هر اجرای محاسبه
209 +:ردیابی. هر عدد خروجی فهرست های‌ردیف منبع ٔسازند خود را دارد P-06
210 +اجرا. شود‌نمی year_id ایزوالسیون :سال هیچ کوئری یا ای‌محاسبه بدون P-07
211 +اجرای اکسل ارزیابی شوند؛‌نمی فقط /با eval های‌فرمول یادداشت با دستور eval: بدون P-08
212 +گرامر. امن بخش ۶
213 +شکست :بلند کنترل ناموفق یا ورودی نامعتبر یعنی خطای صریح و ،کننده‌متوقف نه هشدار P-09
214 +،گرفتنی‌نادیده. مگر در جدول ها‌کنترل که ًصراحت »هشدار« تعریف شده
215 +:آفالین. هیچ درخواست ای‌شبکه در زمان اجرا؛ ها‌فونت و ٔهم ها‌دارایی داخل بسته P-10
216 +مهاجرت :امن هر مهاجرت رو به جلو و عقب تست شود‌می و روی کپی داده واقعی بدون تغییر P-11
217 +ها‌مجموع. اجرا گردد‌می
218 +تست. قبل از :ادعا کار« »کند‌می فقط با تست و خروجی واقعی اجرا معتبر است P-12
219 +.۴ معماری و های‌تصمیم فنی
220 +:ساختار اند‌بک Alembic + 2 SQLAlchemy + FastAPI + 3.12 ؛Python فرانت TypeScript + React
221 +Vite + با پشتیبانی کامل RTL و فونت Vazirmatn داخل بسته؛ سرویس اند‌بک های‌فایل ایستای فرانت را
222 +هم سرو کند‌می و برنامه با یک ٔاجراکنند (PyInstaller) Windows روی 127.0.0.1 ال ب آید‌می و مرورگر
223 +فرض‌پیش را باز .کند‌می
224 +مشکل از( بررسی شناسه)مخزن
225 +الزام رفع
226 +تست پذیرش
227 +D-12
228 +پوشش، type-check، lint، فاقد CI
229 +است lockfile و Postgres
230 +سبز با ٔهم ها‌گیت بخشCI ۱۴
231 +14 of 4 Page
232 +
233 +---
234 +
235 +## صفحهٔ 5
236 +
237 +:دیتابیس ) foreign_keys=ON (WAL، SQLite برای نصب کاربره؛‌تک مدل و ها‌مهاجرت طوری نوشته
238 +شوند که روی PostgreSQL هم در CI اجرا شوند تا مسیر چندکاربره بسته .نشود هر قابلیتی که فقط روی
239 +یکی کار کند ممنوع .است
240 +:ها‌الیه domain قواعد( خالص و بدون :I/O ،سازی‌نرمال ،پولی ،فرمول )ها‌کنترل ← services ،ورود(
241 +،نگاشت ،محاسبه گردش )کار ← api ← ui . ٔدامن خالص ٪۱۰۰ پذیر‌تست بدون دیتابیس .است
242 +چیدمان مخزن :هدف backend/src/aram_backend/{domain,services,api,db} ،
243 +frontend/ ، packaging/windows/ ، docs/{adr,archive} ، data/ فقط مانیفست و های‌فایل
244 +کوچک؛ های‌فایل بزرگ بیرون مخزن یا .LFS
245 +های اجباری قبل از کدنویسی فاز :مربوط مقیاس و گرد کردن پول؛ قرارداد عالمت ADR/بدهکار(
246 +؛ دستور زبان general..detail4فرمول؛ به T1..T4 ؛ نگاشت closingمراتب‌سلسله )بستانکار و معنای
247 +مدل. بازگشایی سال؛ روش بندی‌بسته
248 +.۵ مدل ٔداد هدف
249 +های‌جدول موجود حفظ .شوند‌می اضافه یا :اصالح
250 +های‌بایت فایل در مخزن پذیر‌آدرس-محتوا روی ،دیسک ،اندازه ،نوع (کلید)، sha256 SourceFile:
251 +به. آن ارجاع دهد‌می SourceDocument زمان.
252 +، source_row ، source_sheet ، source_document_id ، year_id LedgerBalance:
253 +، opening ، account_name (متن)، general…detail4 سطوح ، account_full_code
254 +یکتایی: . entry_type P-02)، (پول closing ، credit ، debit
255 +برای. هر ٔنسخ .ورود تغییر‌غیرقابل پس از ورود ) account_full_code , year_id (
256 +،فایل. تعداد ردیف ،ردشده/پذیرفته/خوانده گزارش ،خطا ،کاربر زمان hash هر: ورود ImportRun:
257 +هدف تواند‌می ردیف صورت یا زیریادداشت/یادداشت باشد؛ وضعیت (تکمیل): MappingRule
258 +:یکتایی برای هر . carried_from_year_id ،بازبین، تاریخ بازبینی Draft/Reviewed/Approved،
259 +فقط یک ٔقاعد فعال مگر تقسیم صریح مبلغی/درصدی که ) account_full_code , year_id (
260 +مجموعش. باید ٪۱۰۰ باشد
261 +های‌حساب. ورود شده که نگاشت ،ندارند با مانده و وضعیت رسیدگی UnknownAccountQueue:
262 +فهرست + calculation_run_id + مقدار شده‌محاسبه (تکمیل): StatementLine / NoteCell
263 +). LineageEdge جدول (ارتباطی LedgerBalance ارجاع به
264 +ها‌ورودی ،لجر( ،نگاشت ،)پیکربندی ٔنسخ ،کد ،زمان ٔنتیج ٔهم .ها‌کنترل hash CalculationRun:
265 +تأییدشده. run خروجی رسمی فقط از یک
266 +ٔاصالحی :ای‌الیه ،حساب ،مبلغ ،دلیل سند ،پشتیبان ،کاربر وضعیت بازبینی؛ هرگز مقدار Adjustment:
267 +منبع. را عوض کند‌نمی
268 +14 of 5 Page
269 +
270 +---
271 +
272 +## صفحهٔ 6
273 +
274 +اصل چهار :چشم Admin. Approver، Reviewer، Preparer، ها‌نقش: Session: Role, User,
275 +تأییدکننده. تواند‌نمی همان کننده‌تهیه باشد پیکربندی‌قابل( برای نصب نفره‌تک با هشدار )شده‌ثبت
276 +و prev_hash (hash)، ،موجودیت مقدار بعد/قبل UTC، ،رویداد ،کاربر زمان AuditLog:
277 +فقط. افزودنی؛ تریگر ویرایش/حذف را رد کند‌می ٔزنجیر). (هش entry_hash
278 +درخواست بازگشایی سال :تأییدشده ،دلیل ،دهنده‌درخواست ،تأییدکننده نتیجه؛ ReopenRequest:
279 +سال. شده‌بازگشایی ٔنسخ جدید سازد‌می و ٔنسخ ٔتأییدشد قبلی ًعین باقی ماند‌می
280 +.۶ موتور محاسبه
281 +خط ٔلول ثابت هر( مرحله تابع خالص و :)تست‌قابل
282 +.1
283 +ورود → LedgerBalance بخش( )۸
284 +.2
285 +سازی‌نرمال و اعتبارسنجی ساختاری )preflight(
286 +.3
287 +اعمال نگاشت :تأییدشده هر حساب ← هدف ردیف( صورت / یادداشت / )زیریادداشت
288 +.4
289 +ٔمحاسب های‌سلول یادداشت ها‌فرمول( + قواعد )سازی‌مرتب
290 +ٔمحاسب های‌ردیف صورت از ها‌یادداشت و های‌حساب .5مستقیم
291 +.6
292 +اجرای ٔهم ها‌کنترل بخش( )۷
293 +ثبت CalculationRun با hash .7ها‌ورودی
294 +های‌فرمول :یادداشت منبع قدیمی ( data/mappings ، های‌ستون فرمول« یادداشت )»فرعی/اصلی
295 +فرمول .دارد ٔوظیف فاز ۳ ابتدا کردن‌فهرست ٔهم الگوهای متمایز فرمول با اسکریپت خواندنی‌فقط و
296 +نوشتن گرامر در یک ADR .است سپس فقط یک زبان کوچک امن ،تفریق/جمع( ارجاع به /یادداشت/حساب
297 +،ردیف شرط ،ساده جمع بر اساس سطح )مراتب‌سلسله پیاده .شود‌می فرمول خارج از گرامر = خطای
298 +صریح با ٔشمار ،ردیف نه .گرفتن‌نادیده هیچ ایeval مجاز نیست .)P-08(
299 +قواعد مالی که باید قبل از کد در ADR نوشته و بر ٔپای شواهد داده طبق بخش ۱۷ نهایی
300 +:شوند
301 +معنی closing و عالمت های‌حساب ماهیت‌بستانکار در( داده ثابت ،شود حدس زده .)نشود
302 +مقیاس نمایش ریال( یا میلیون )ریال و گرد کردن فقط در ٔالی ،خروجی/نمایش با تضمین اینکه جمع
303 +های‌ردیف گردشده با جمع کل شده‌داده‌نمایش سازگار بماند روش( تخصیص اختالف گردکردن مستند
304 +.)شود
305 +ترتیب ها‌ردیف و قواعد سازی‌مرتب ( sorting_rule_id ) صورت‌به ،داده نه .کد
306 +ارقام ای‌مقایسه سال :قبل فقط از ٔنسخ ٔتأییدشد سال قبل خوانده .شود‌می
307 +اگر سال قبل در سامانه ،نیست ورود دستی ارقام« »ای‌مقایسه با منبع و برچسب مشخص نه( ارقام
308 +.)خالی
309 +14 of 6 Page
310 +
311 +---
312 +
313 +## صفحهٔ 7
314 +
315 +.۷ فهرست های‌کنترل مالی )مسدودسازی‌قابل(
316 +هر :کنترل ،کد شدت ( ERROR مانع تأیید / WARN نیازمند توضیح ،)شده‌ثبت ،ورودی ،خروجی پیام ،فارسی
317 +تست مثبت و .منفی
318 +کد
319 +کنترل
320 +شدت
321 +C-01
322 +هر :ردیف = closing − credit − debit + opening
323 +0 طبق( ADR )عالمت
324 +ERROR
325 +ترازERROR :کل جمع بدهکار = جمع ،بستانکار و جمع ها‌مانده C-02صفر
326 +هر حساب با گردش/مانده غیرصفر ًدقیق یک نگاشت C-03فعال
327 +دارد بدون( نگاشت = ،ERROR دو نگاشت = ERROR مگر
328 +تقسیم )٪۱۰۰
329 +ERROR
330 +حساب بدون نگاشت وارد صف های‌حساب ناشناخته C-04شود‌می
331 +و تا تعیین تکلیف مانع تأیید است
332 +ERROR
333 +مانده پایان سال قبل = مانده ابتدای سال C-05جاری
334 +)حساب‌به‌حساب(
335 +ERROR
336 +وضعیتERROR :مالی ها‌دارایی = ها‌بدهی + حقوق C-06مالکانه
337 +جمعERROR هر یادداشت = ردیف متناظر در C-07صورت
338 +سود و زیان خالص IS = تغییر زیان/سود ٔانباشت EQ C-08با(
339 +اصالحات )صریح
340 +ERROR
341 +C-09
342 +ماندهERROR ابتدا + تغییرات = مانده پایان EQ:
343 +C-10
344 +BS) (در خالص تغییر وجه نقد = مانده نقد پایان − ابتدا CF:
345 +ERROR
346 +:مراتب‌سلسله هر کد سطح تر‌پایین والد موجود دارد و C-11جمع
347 +فرزندان = والد اگر( لجر والد )دارد
348 +ERROR
349 +یادداشتERROR بدون نگاشت یا نگاشت به یادداشت C-12ناموجود
350 +تطابق با صورت رسمی ( official_statements ) C-13در
351 +حالت اعتبارسنجی/تست
352 +UI در INFO CI، در ERROR
353 +C-14
354 +تغییرWARN ناگهانی بیش از آستانه نسبت به سال قبل )تحلیلی(
355 +حسابWARN با مانده خالف C-15ماهیت
356 +14 of 7 Page
357 +
358 +---
359 +
360 +## صفحهٔ 8
361 +
362 +.۸ً ورود داده )Import(
363 +ورود :جریانی فایل ۳۰ مگابایتی نباید کل حافظه را .بگیرد خواندن ،read-only درج ای‌دسته مث(
364 +۵۰۰۰ )ردیفی در یک تراکنش با بازگشت کامل در .خطا هدف :عملکرد لجر ۳۲MB در کمتر از ۵ دقیقه
365 +روی ماشین متوسط و کمتر از ۱ گیگابایت RAM تنظیم‌قابل( و ثبت در .)تست
366 +​
367 +چیزی را دوباره سازد؛‌نمی فایل جدید برای همان hash) (همان ورود ٔدوبار همان فایل idempotent:
368 +است. Draft سال = ٔنسخ جدید ورود با( )مقایسه تا وقتی سال
369 +سازی‌نرمال فارسی ( normalize_fa :) ،»ی«←»ي« ،»ک«←»ك« ارقام التین←عربی/فارسی برای
370 +مقادیر ،عددی حذف NBSP و کاراکترهای ،کنترلی ،trim سازی‌یکسان ،فاصله‌نیم حذف .کشیده کد
371 +حساب هرگز سازی‌عددی .شود‌نمی ٔمقایس نام هدر/شیت بعد از .سازی‌نرمال
372 +مقدارٔ :سلول data_only=True فقط وقتی مجاز است که مقدار شده‌کش موجود باشد؛ سلول
373 +فرمولی بدون مقدار کش = خطای .صریح اعداد float اکسل با روش دقیق ( repr ترین‌کوتاه رشت
374 +)round-trip به Decimal روند‌می و اگر بیش از مقیاس مجاز رقم اعشار دارند هشدار/خطا ثبت
375 +.شود‌می
376 +گزارش :خطا خروجی Excel با ٔشمار ،ردیف ،ستون کد خطا و پیام فارسی؛ شمارش کل خطاها
377 +همیشه نمایش داده .شود
378 +​
379 +یا ،جداکننده) همان قواعد ال ب (UTF-8/UTF-8-BOM/Windows-1256، یا کامل پشتیبانی شود CSV:
380 +از. ها‌مجاز حذف .شود کاره‌نیمه ممنوع
381 +.۹ نگاشت Studio( )Mapping و صف های‌حساب ناشناخته
382 +خروج/ورود Excel جامع نگاشت قالب( v0.1 Pilot ،موجود با SHA ،)شده‌ثبت با گزارش تفاوت
383 +.)تغییر/حذف/افزوده(
384 +صف های‌حساب :ناشناخته هر حساب بدون نگاشت با اش؛‌مانده پیشنهاد نگاشت بر اساس پیشوند کد
385 +و نگاشت سال قبل فقط( ،پیشنهاد هرگز تأیید .)خودکار
386 +حمل نگاشت از سال قبل :)carry-forward( کپی صورت‌به Draft با ارجاع به ،منبع نیازمند بازبینی
387 +.دوباره
388 +گردش :کار Reviewed → Draft بازبین( مشخص + )تاریخ → Approved فقط( وقتی اعتبارسنجی
389 +.)Valid
390 +نگاشت تقسیمی یک( حساب به چند )هدف فقط با مجموع ٪۱۰۰ یا مبلغ مساوی با .مانده
391 +،جستجو ،فیلتر ویرایش گروهی با نمایش‌پیش اثر چه( ارقامی تغییر )کند‌می قبل از .اعمال
392 +API ۱۰.
393 +پایه /api/v1 ، خطاها ساختار یکسان ( code , message_fa , details ،) ٔهم ها‌نوشتن نیازمند احراز
394 +هویت و ثبت در .AuditLog
395 +14 of 8 Page
396 +
397 +---
398 +
399 +## صفحهٔ 9
400 +
401 +companies ، fiscal-years +( انتقال :وضعیت approve , lock , reopen-request )
402 +fiscal-years/{id}/sources ،آپلود( ،لیست دانلود با ،)hash imports ،شروع( ،وضعیت
403 +گزارش )خطا
404 +fiscal-years/{id}/ledger ،بندی‌صفحه/جستجو( )drill-down
405 +​
406 +، carry-forward ، unknown-accounts import/export، Draft، در (CRUD mappings
407 +) suggestions
408 +notes و statements خواندنی‌فقط( از آخرین run تأییدشده؛ calculate برای run )جدید
409 +checks ٔنتیج( های‌کنترل ،)run lineage/{cell} فهرست( رکوردهای )منبع
410 +​
411 +restore و backup ، audit-log json)، / pdf / (xlsx exports
412 +​
413 +عنوان‌به. قرارداد؛ تست قرارداد بین فرانت و اند‌بک OpenAPI
414 +.۱۱ٔ رابط کاربری
415 +:قواعد فارسی RTL ،کامل فونت Vazirmatn داخل ،بسته تاریخ شمسی ٔذخیر( ،)میالدی/UTC جداکنند
416 +،هزارگان ٔگزین ارقام ،التین/فارسی اعداد منفی داخل ،پرانتز ها‌حساب و ارقام با dir=ltr در های‌سلول
417 +،عددی کیبورد ،کامل حالت ،روشن/تیره هیچ اتکایی به .اینترنت
418 +:ها‌صفحه داشبورد سال/شرکت با وضعیت و ها؛‌کنترل ورود فایل و گزارش ؛preflight صف های‌حساب
419 +ناشناخته؛ استودیوی نگاشت؛ فهرست و جزئیات ها؛‌یادداشت چهار صورت اصلی با drill-down تا ردیف
420 +لجر؛ مرکز ها‌کنترل و تطبیق؛ ٔمقایس دو سال؛ ٔسابق تغییرات ؛)audit( ها؛‌خروجی تنظیمات و .کاربران
421 +ٔقاعد UX :مهم ٔدکم تأیید« »سال تا وقتی حتی یک کنترل ERROR باز است غیرفعال و علت نمایش داده
422 +شود؛‌می هیچ مسیر دورزدن در UI .نیست
423 +.۱۲ ها‌خروجی
424 +و یک RTL، هر، صورت و یادداشت در یک ،شیت مقادیر عددی واقعی نه( ،)متن فرمت هزارگان Excel:
425 +شیت »ردیابی« هر( سلول ← ٔشمار های‌ردیف لجر .)منبع شیت »ها‌کنترل« با ٔنتیج ٔهم ها‌کنترل و
426 +ها‌ورودی. hash
427 +:چاپ‌قابل فونت ،شده‌جاسازی شکستن صفحه ،درست سرصفحه با نام وضعیت/سال/شرکت PDF
428 +نویس‌پیش(. یا ،)تأییدشده شماره ،صفحه واترمارک »نویس‌پیش« تا قبل از تأیید
429 +کامل. برای بازیابی و تطبیق JSON
430 +تأییدشده run هر خروجی رسمی فقط از . run} نام_{ی‌شناسه :فایل }نوع{_}سال{_}شرکت{
431 +خودش. را در متادیتا دارد hash ساخته شود‌می و
432 +حداقل از نظر PDF (round-trip)؛ دوباره خوانده و با دیتابیس مقایسه شود‌می Excel :تست خروجی
433 +های‌متن. کلیدی و تعداد صفحه بررسی شود‌می
434 +14 of 9 Page
435 +
436 +---
437 +
438 +## صفحهٔ 10
439 +
440 +.۱۳ ،امنیت ممیزی و یکپارچگی
441 +احراز هویت :محلی گذرواژه/کاربر با ،Argon2 قفل بعد از تالش ،ناموفق ها‌نقش
442 +)Preparer/Reviewer/Approver/Admin( و بررسی مجوز در هر endpoint نه( فقط در .)UI سرور
443 +فقط روی 127.0.0.1 . CORS .بسته هیچ راز در .مخزن
444 +قفل سطح :دیتابیس تریگرهای SQLite/PostgreSQL که هر INSERT/UPDATE/DELETE روی
445 +های‌جدول وابسته به ِسا شده‌قفل/تأییدشده را رد ،کنند‌می مستقل از .ORM تست :اجباری UPDATE
446 +خام باید شکست .بخورد شنونده before_flush عنوان‌به ٔالی دوم ماند‌می ولی بدون N+1 وضعیت(
447 +سال بار‌یک کش در .)تراکنش
448 +​
449 +:ای‌زنجیره هر رویداد دارای prev_hash و ؛entry_hash ابزار verify-audit AuditLog
450 +سالمت. زنجیره را بررسی کند؛‌می دستکاری = شکست تأیید
451 +​
452 +تنها راه تغییر سال :تأییدشده درخواست با ،دلیل تأیید نقش التر ،ب ساخت ٔنسخ ReopenRequest:
453 +جدید؛. ٔنسخ قبلی نخورده‌دست
454 +:گیری‌پشتیبان پشتیبان شده‌رمزگذاری از دیتابیس + های‌فایل منبع + مانیفست ،hash با دستور
455 +بازیابی و تست بازیابی در .CI
456 +ٔزنجیر :تأمین lockfile با ،hash pip-audit و audit npm در ،CI های‌نسخه pin .شده
457 +:الگ بدون ثبت نام/مبالغ حساب در های‌الگ عادی؛ سطح debug فقط با ٔگزین .صریح
458 +.۱۴ راهبرد تست و های‌دروازه کیفیت
459 +هرم :تست واحد )دامنه( ← یکپارچگی )DB+سرویس( ← قرارداد e2e ← API Playwright( روی UI
460 +)واقعی ← .عملکرد
461 +های‌تست اجباری :ویژه
462 +طالیی :)Golden( لجر ۱۴۰۴ و ۱۴۰۳ ← ها‌صورت ← ٔمقایس ریال‌به‌ریال با
463 +official_statements . اختالف = ،شکست مگر شده‌ثبت در فهرست های‌اختالف« تاریخی
464 +»شده‌شناخته با دلیل و امضای مالک فایل( HISTORICAL_DISCREPANCIES.md موجود ٔنقط شروع
465 +.)است
466 +​
467 +جمع شده‌نگاشت = جمع منبع برای هر ورودی تصادفی معتبر؛ (Hypothesis): Property-based
468 +idempotent. پول؛ ترتیب ورودی تأثیری بر خروجی ندارد؛ سازی‌نرمال round-trip
469 +:تخریبی SQL خام روی سال ،شده‌قفل فایل فایل/بمب‌ZIP/خراب با ۱۰۰۰ ،شیت کدهای ،تکراری
470 +های‌عالمت ،وارونه سلول فرمول بدون ،کش فایل با »ك/ي« .عربی
471 +:عملکرد ورود لجر ۳۲MB زیر آستانه؛ ٔمحاسب کامل زیر آستانه؛ ٔبودج .حافظه
472 +:مهاجرت upgrade/downgrade و اجرا روی کپی داده واقعی بدون تغییر .ها‌مجموع
473 +قابلیت :بازتولید دو اجرای ،سرهم‌پشت خروجی بایت‌به‌بایت یکسان .)P-05(
474 +14 of 10 Page
475 +
476 +---
477 +
478 +## صفحهٔ 11
479 +
480 +های‌دروازه CI همه( باید سبز :)باشند check ruff ، --check format ruff ، -- mypy
481 +strict روی domain/services ، pytest با پوشش ≥ ٪۹۰ روی دامنه و ≥ ٪۸۰ ،کل مهاجرت روی
482 +SQLite و ،PostgreSQL eslint و --noEmit tsc و vitest برای ،فرانت ،Playwright pip-
483 +audit ، audit npm ، --check diff git ، و ساخت ٔبست Windows روی ٔشاخ .release
484 +.۱۵ ٔنقش راه اجرا به( ترتیب؛ هر فاز با معیار )پذیرش
485 +فاز ۰ — سازی‌پاک و :ها‌بدهی رفع D-01 تا D-12 جز‌به( آنچه مدل فاز ۱ الزم ،)دارد انتقال مستندات
486 +تاریخی به docs/archive/ ، هایADR بخش ۴ با تأیید .مالک :پذیرش CI جدید ،سبز
487 +PROJECT_STATUS.md با head واقعی .خوان‌هم
488 +فاز ۱ — برش عمودی ترین‌مهم( :)فاز یک ،شرکت یک سال :)۱۴۰۴( ورود لجر ← LedgerBalance
489 +← کنترل C-01/C-02 ← نگاشت حتی( )اولیه ← های‌جمع BS و IS ← مقایسه با صورت .رسمی بدون UI زیبا؛
490 +CLI و گزارش متنی کافی .است :پذیرش های‌جمع BS/IS برابر صورت رسمی یا ها‌اختالف کامل فهرست و
491 +توجیه .شده
492 +فاز ۲ — نگاشت :کامل خروج/ورود ،Excel صف ،ناشناخته حمل النه ،س گردش
493 +C-03/C-04/C-12 .Draft/Reviewed/Approved، :پذیرش ٪۱۰۰ های‌حساب لجر ۱۴۰۴ شده‌نگاشت یا در
494 +صف با .وضعیت
495 +فاز ۳ — موتور :ها‌یادداشت گرامر فرمول ،)ADR( های‌سلول ،یادداشت ،زیریادداشت ،سازی‌مرتب C-
496 +.07 :پذیرش هر یادداشت سال ۱۴۰۴ با یادداشت رسمی .برابر
497 +فاز ۴ — چهار صورت و :ها‌تطبیق BS/IS/EQ/CF ،کامل C-05 تا C-13 ،C-11، ٔمقایس دو ،سال سال
498 +.۱۴۰۳ :پذیرش ٔهم ها‌کنترل روی هر دو سال .سبز
499 +فاز ۵ — رابط :کاربری های‌صفحه بخش ۱۱ بر ٔپای drill-down ،API، اپراتور واقعی با .Playwright
500 +:پذیرش سناریوی کامل ورود« تا »تأیید بدون ابزار .جانبی
501 +فاز ۶ — :ها‌خروجی Excel/PDF/JSON بخش .۱۲
502 +فاز ۷ — امنیت و :ممیزی ،ها‌نقش/کاربران تریگرهای ،دیتابیس audit ،ای‌زنجیره ،reopen /پشتیبان
503 +بازیابی بخش( .)۱۳
504 +فاز ۸ — بندی‌بسته :Windows ٔاجراکنند ،مستقل ،نصاب بدون ،اینترنت/Python تست در ماشین
505 +،تمیز SHA-256 و مستند .نصب :پذیرش ثبت الگ/ویدئو نصب و اجرا روی ماشین .تمیز
506 +فاز ۹ — پذیرش کاربری و :انتشار مالک سناریوهای بخش ۱۴ را روی ٔداد واقعی اجرا و امضا کند؛‌می
507 +تگ v1.0.0 و artifact .شده‌داری‌نگه
508 +ٔقاعد ورود به فاز :بعد معیار پذیرش فاز قبل با شواهد CI( ،SHA، خروجی )تست در
509 +PROJECT_STATUS.md ثبت شده .باشد
510 +14 of 11 Page
511 +
512 +---
513 +
514 +## صفحهٔ 12
515 +
516 +.۱۶ ها‌ریسک و پاسخ
517 +.۱۷ قواعد تصمیم خودکار بدون( پرسش از )مالک
518 +مالک ًصریح خواسته ایجنت هیچ سؤالی .نپرسد پس هر ابهام زیر با یک تصمیم فرض‌پیش و یک روش
519 +اثبات بسته شده .است این بخش بر هر عبارت تأیید« »مالک یا تصمیم« »باز در های‌بخش دیگر مقدم .است
520 +روش کار برای هر :مورد )۱ فرض‌پیش را اعمال .کن )۲ با آزمون روی ٔداد واقعی و های‌صورت رسمی
521 +.بسنجش )۳ اگر شواهد با فرض‌پیش ،خواند‌نمی شواهد برنده .است )۴ ،تصمیم شواهد و های‌گزینه ردشده
522 +را در یک ADR ثبت .کن )۵ کار را متوقف .نکن ها‌فرض‌پیش ِحد اند؛‌تأییدنشده اعتبارشان فقط از آزمون
523 +.آید‌می
524 +ریسک
525 +پاسخ
526 +برداری‌فهرست کامل در فاز ؛۳ مورد ناپشتیبانی های‌فرمول= قدیمی خارج از گرامر
527 +تصمیم ،مالک نه حدس
528 +اختالف صورت رسمی با لجر به علت های‌اصالحیه
529 +دستی
530 +ثبت در Adjustment و فهرست های‌اختالف
531 +شده‌شناخته
532 +تست روی داده قبل از هر محاسبه + ابهامADR ماهیت/عالمت ها‌حساب
533 +،جریانی ،ای‌دسته ٔبودج عملکرد در حجمCI و سرعت ورود
534 +وابستگی به یک ابزار/ایجنت
535 +معماری ،استاندارد ،محور‌تست مستندسازی ها‌تصمیم
536 +در ADR
537 +گسترش دامنه
538 +هر مورد خارج از بخش ۱ فقط با ADR و تأیید مالک
539 +کد
540 +تصمیم فرض‌پیش
541 +روش اثبات یا اصالح
542 +سطوح OD-01
543 +T1..T4
544 +سطوح لجر به سطوح Pilot ( general…
545 +detail4 ) به ترتیب نگاشت شوند و
546 +سطوح اضافی تهی بمانند
547 +کد کامل شده‌بازسازی از سطوح باید
548 +برای ٪۱۰۰ ها‌ردیف ًدقیق برابر ستون
549 +»حساب« باشد؛ هر نگاشتی که این را
550 +برقرار کند پذیرفته است
551 +عالمت و OD-02
552 +closing
553 +بدهکار ،مثبت بستانکار ،منفی = closing
554 +credit − debit + opening
555 +هر دو قرارداد عالمت را روی داده بسنج؛
556 +آنی که C-01 را روی ٔهم ها‌ردیف و C-
557 +02 و C-06 را برقرار کند انتخاب
558 +شود‌می
559 +14 of 12 Page
560 +
561 +---
562 +
563 +## صفحهٔ 13
564 +
565 +تنها توقف :مجاز خطر تغییر یا از دست رفتن ٔداد ،منبع یا تضاد مستقیم با AGENTS.md . در این دو حالت
566 +وضعیت را گزارش کن و روی ٔبقی کارهای مستقل ادامه .بده
567 +نقش مالک در تمام این مسیر فقط یکی :است پذیرش نهایی فاز ۹ روی ٔداد .واقعی
568 +.۱۸ قالب گزارش پایان هر کار
569 +و ،لینک فهرست دقیق های‌فایل PR ٔشمار head، کامل SHA remote، ٔپای ،تأییدشده ٔشاخ SHA
570 +، NONE یا artifact/release شواهد Actions، GitHub ،یافته‌تغییر دستورهای تست و ،نتیجه لینک اجرای
571 +GitHub independent for Ready تأیید: عدم تغییر های‌داده ،منبع های‌ریسک ،مانده‌باقی و ٔجمل پایانی
572 +merged. not review;
573 +کد
574 +تصمیم فرض‌پیش
575 +روش اثبات یا اصالح
576 +مقیاس و OD-03
577 +گرد کردن
578 +ذخیره و محاسبه به ریال کامل بدون گرد
579 +کردن؛ نمایش در مقیاس همان صورت
580 +رسمی؛ گرد کردن half-up فقط در
581 +خروجی
582 +مقیاس را از ارقام
583 +official_statements تشخیص
584 +بده؛ اختالف گرد کردن بین ها‌ردیف و
585 +جمع با روش ترین‌بزرگ باقیمانده
586 +تخصیص و ثبت شود
587 +قالب OD-04
588 +ها‌صورتٔ
589 +ًعین ،ها‌سرفصل ترتیب و شمار
590 +های‌یادداشت صورت رسمی؛ استانداردهای
591 +حسابداری ایران
592 +هیچ ردیفی ساخته یا حذف نشود؛ هر
593 +مغایرت قالب با فایل رسمی باگ است
594 +جریان OD-05
595 +وجوه نقد
596 +همان روشی که در صورت رسمی به کار
597 +رفته؛ اگر از ساختار ها‌ردیف معلوم ،نشد
598 +غیرمستقیم
599 +ردیفی که از لجر اشتقاق‌قابل نیست
600 +فقط با Adjustment شده‌ثبت و منبع
601 +وارد شود؛ C-10 باید برقرار باشد
602 +صورت OD-06
603 +تلفیقی
604 +خارج از ؛V1 فقط معماری مانع آن نشود
605 +( company_id )جا‌همه
606 +هیچ قابلیت تلفیقی نساز
607 +OD-07
608 +چندکاربری
609 +نصب‌تک و ماشین‌تک با چند کاربر و نقش V1
610 +؛ دسترسی SQLiteزمان‌هم محلی روی
611 +V1 چندماشینی خارج از
612 +تست مهاجرت و مدل روی
613 +PostgreSQL در CI برای مسیر آینده
614 +اختالف OD-08
615 +تاریخی
616 +هر اختالف با صورت رسمی در
617 +docs/discrepancies.json ثبت شود
618 +،ردیف( مبلغ ،ما مبلغ ،رسمی ،علت )شواهد
619 +اختالف بدون ِعل مستند و بازتولیدپذیر
620 += باگ تا اثبات خالف؛ فهرست نهایی را
621 +مالک بار‌یک در پذیرش نهایی فاز( )۹
622 +امضا ،کند‌می نه حین کار
623 +سایر ها‌ابهام و
624 +Q1–Q7 قبلی
625 +ترین‌کارانه‌محافظه :گزینه آنی که تأیید را
626 +مسدود ،کند‌می نه آنی که اجازه دهد‌می
627 +با های‌گزینه ردشده؛ در صورت ADR
628 +جدید اصالح ADR شواهد ،بهتر تصمیم با
629 +شود
630 +14 of 13 Page
631 +
632 +---
633 +
634 +## صفحهٔ 14
635 +
636 +.۱۹ ها‌ممنوعیت
637 +اختراع مقدار ٔنتیج/فرمول/نگاشت/مالی تست؛ ویرایش های‌داده منبع؛ ادغام PR خود؛ دورزدن کنترل یا
638 +کردن‌غیرفعال تست برای سبزشدن؛ افزودن وابستگی بدون ؛ADR commit فایل باینری ،بزرگ ZIP/EXE
639 +یا رمز؛ استفاده از شبکه در زمان اجرا؛ بازگرداندن کد #7 PR بدون دستور صریح؛ افزودن مستند تحلیلی
640 +جدید در ریشه؛ ادعای تمام« »شد بدون شواهد .بررسی‌قابل
641 +14 of 14 Page
docs/booklet/BOOKLET_v2.0.md new
+191
@@ -0,0 +1,191 @@
1 +# کتابچهٔ ۲ — اصلاح مسیر و معماری نهایی Aram
2 +
3 +> **سند مرجعِ version-controlled (نسخهٔ ۲٫۰).** متنِ زیر عیناً دستور کارِ مالک است که
4 +> در پیام 2026-12-03 ارائه شد (پیوست در پیام دوم همان روز اصلاح شد: مطالعهٔ کاتالوگ
5 +> دیتابان، تصمیم موقعیت‌یابی، عناصر پذیرفته‌شده، اصلاح OD-09، فاز C11). شماره‌گذاری
6 +> فهرست‌ها برای مارک‌داون نرمال شده؛ محتوا بدون تغییر است. این کتابچه جایگزین بخش‌های متناقض کتابچهٔ ۱ و مکمل بقیهٔ
7 +> آن است. لنگر یکپارچگی: SHA-256 همین فایل در `MANIFEST.json` (منبع: پیام مالک، بدون فایل اصلی).
8 +> مبنا: بررسی PR #96 و مخزن davoodmehraban89/Aram. مالک خواسته است ایجنت **هیچ سؤالی نپرسد**؛
9 +> ابهام‌ها با قواعد بخش ۱۴ بسته می‌شوند.
10 +
11 +نسخهٔ ۲٫۰ — جایگزین بخش‌های متناقض کتابچهٔ ۱ و مکمل بقیهٔ آن. مخاطب: ایجنت کدنویسی. مبنا: بررسی PR #96 (head 2fce09d) و مخزن davoodmehraban89/Aram. مالک خواسته است ایجنت هیچ سؤالی نپرسد؛ ابهام‌ها با قواعد بخش ۱۴ بسته می‌شوند.
12 +
13 +## بخش الف — اصلاح مسیر فوری (قبل از هر قابلیت جدید)
14 +
15 +بررسی PR #96 نشان داد کار به سمت یک ابزار موقت درون‌حافظه‌ای و مرورگری رفته است. موارد زیر اجباری و به همین ترتیب‌اند:
16 +
17 +**الف‌۱. توقف انشعاب Pyodide / GitHub Pages / CDN.** فایل‌های `.github/workflows/pilot-pages.yml`، پوشهٔ `webapp/`، خروجی ساخته‌شده در `docs/` (که با مستندات حاکمیتی تداخل دارد)، `docs/vendor/` و `scripts/build_webapp.py` از PR #96 حذف و در شاخهٔ جدا `experiment/browser-edition` نگهداری شوند (ادغام‌نشدنی). دلیل: وابستگی به شبکه در زمان اجرا برای ابزار مالی نقض اصل آفلاین است.
18 +
19 +**الف‌۲. تکمیل هستهٔ ماندگار به‌جای حافظهٔ موقت.** `pilot_engine.py` فقط به‌عنوان مرجع منطق حفظ شود: سیاست علامت، صف استثنا و کنترل‌های آن به `domain/` منتقل و روی داده‌های ذخیره‌شده اجرا شوند. جلسهٔ درون‌حافظه‌ای (`pilot_store`) نباید مسیر اصلی محصول بماند. ورودی‌ها: لجر واقعی سال ۱۴۰۴ (`data/source_ledgers`) + نگاشت، نه فقط قالب Pilot.
20 +
21 +**الف‌۳. اجرای فاز ۰ و فاز ۱ کتابچه ۱ کامل:** بدهی‌های D-01 تا D-12 (به‌ویژه جدول LedgerBalance، ذخیرهٔ محتوا-آدرس‌پذیر فایل منبع، قفل سطح دیتابیس، audit زنجیره‌ای، Decimal دقیق روی SQLite) و سپس برش عمودی ۱۴۰۴ با تست طلایی تطبیق ریال‌به‌ریال با `official_statements`.
22 +
23 +**الف‌۴. صداقت PR.** متن هر PR باید دقیقاً با `git diff --stat` و head واقعی هم‌خوان باشد (تعداد فایل، خطوط، تست‌ها، SHA). PRای که مشخصاتش با واقعیت نمی‌خواند برای بازبینی پذیرفته نیست.
24 +
25 +**الف‌۵. اندازه PR.** هر PR یک وظیفهٔ فاز، حداکثر حدود ۱٬۵۰۰ خط تغییر (بدون تست و دادهٔ تولیدشده). ادغام چند فاز در یک PR ممنوع است.
26 +
27 +**الف‌۶. تعیین تکلیف PRهای انباشته (#81 تا #92، #88/#89 و بقیه).** در یک فایل `docs/PR_TRIAGE.md` برای هر PR باز یکی از سه حکم ثبت شود: اتخاذ (cherry-pick شود به PR جدید و کوچک)، جایگزین‌شده (بست)، بستن. هیچ PR با برچسب NO-GO ادغام نشود. معیار اتخاذ: با کتابچه‌ها هم‌خوان باشد و تست داشته باشد.
28 +
29 +**الف‌۷. معیار خروج از بخش الف:** CI سبز، `PROJECT_STATUS.md` هم‌خوان با head، تست طلایی ۱۴۰۴ سبز یا اختلاف‌ها در `docs/discrepancies.json` با علت ثبت شده باشند.
30 +
31 +## بخش ب — هدف نهایی: Aram به‌عنوان پلتفرم عمومی و دیتابیس‌محور
32 +
33 +### ب‌۱. چشم‌انداز
34 +
35 +Aram نباید ابزار یک شرکت (مثلاً انتقال گاز) باشد. باید برای هر شرکت صورت‌های مالی اساسی و یادداشت‌ها را از روی داده‌های حسابداری آن شرکت تهیه کند، با دو مسیر ورود: فایل (Excel/CSV) و اتصال مستقیم به بانک اطلاعاتی نرم‌افزار حسابداری/ERP. هرچه به یک شرکت یا صنعت خاص مربوط است باید داده باشد (بستهٔ قالب/نگاشت)، نه کد.
36 +
37 +**قاعدهٔ عمومی‌بودن (غیرقابل‌مذاکره):** هیچ نام شرکت، کد حساب، سرفصل یا ثابت صنعتی در کد منبع نباشد؛ این‌ها فقط در `packs/` و دیتابیس می‌آیند. تست خودکار با grep این را بررسی کند.
38 +
39 +### ب‌۲. معماری لایه‌ای
40 +
41 +1. **Connectors (افزونه‌های منبع داده):** استخراج فقط‌خواندنی از یک منبع.
42 +2. **Source Adapter (پروفایل منبع):** توصیف اعلانی (YAML/JSON) که ساختار جدول‌ها/ویوهای منبع را به مدل کانونی لجر ترجمه می‌کند.
43 +3. **Canonical Ledger:** مدل استاندارد داخلی (LedgerBalance و اختیاری JournalLine).
44 +4. **Snapshot:** هر استخراج یک عکس فوری تغییرناپذیر با hash است؛ محاسبه فقط روی snapshot انجام می‌شود، نه روی منبع زنده.
45 +5. **Engine:** نگاشت، یادداشت‌ها، صورت‌ها، کنترل‌ها (کتابچهٔ ۱ بخش‌های ۶ و ۷).
46 +6. **Packs:** قالب صورت‌ها، نگاشت‌ها و قواعد اعتبارسنجی به‌صورت داده نسخه‌دار.
47 +7. **API و UI** و **Exports**.
48 +
49 +### ب‌۳. مدل افزونه (Plugin)
50 +
51 +- انواع افزونه: SourceConnector، MappingPack (الگوی نگاشت سرفصل‌ها)، StatementTemplatePack (قالب صورت‌ها و یادداشت‌ها)، ValidationPack (کنترل‌های اضافه)، ExportRenderer.
52 +- رابط پایدار و نسخه‌دار `aram_plugin_api` v1؛ افزونه فقط از همین رابط استفاده کند و به ORM داخلی دست نزند.
53 +- مانیفست: نام، نسخه، نسخهٔ سازگار API، نوع، مجوزهای لازم (شبکهٔ محلی، فایل)، JSON Schema تنظیمات.
54 +- اجرا: افزونه‌های Connector در فرایند جدا با حداقل مجوز اجرا شوند؛ خروجی فقط از رابط ساخت‌یافته می‌آید.
55 +- امضا و فهرست مجاز: افزونه فقط با hash/امضای ثبت‌شده توسط Admin بار می‌شود. بارگذاری کد دلخواه از شبکه ممنوع است.
56 +- تست انطباق (Conformance Suite): هر Connector باید مجموعه‌تست مشترک را بگذراند (تست اتصال، شناسایی ساختار، استخراج صفحه‌ای، قطع ارتباط، timeout، دادهٔ ناقص، یونیکد فارسی).
57 +
58 +### ب‌۴. Connectorها (ترتیب پیاده‌سازی)
59 +
60 +1. **FileConnector** (Excel/CSV): پیاده‌سازی مرجع و پایهٔ تست انطباق.
61 +2. **SQL عمومی** بر پایهٔ SQLAlchemy Core برای PostgreSQL و SQLite، سپس **SQL Server** (پیش‌فرض: درایور خالص‌پایتون python-tds برای بسته‌بندی آفلاین؛ جایگزین: pyodbc در صورت نصب درایور ODBC).
62 +3. **ODBC عمومی** برای بقیهٔ سامانه‌ها (از جمله Oracle/MySQL) از راه افزونهٔ جدا.
63 +
64 +هر Connector این قرارداد را دارد: `test_connection()`، `discover_schema()`، `preview(table, n)`، `extract(adapter, period) → iterator`، `fingerprint()` (hash ساختار و مجموع‌ها).
65 +
66 +### ب‌۵. ایمنی اتصال به دیتابیس
67 +
68 +- فقط‌خواندنی: کاربر دیتابیس با دسترسی SELECT؛ برنامه در ثبت اتصال، نبود مجوز نوشتن را بررسی و در صورت وجود مجوز نوشتن هشدار مسدودکننده بدهد.
69 +- کوئری‌ها قالبی و پارامتری‌اند (بدون الحاق رشته). حالت «کوئری سفارشی» فقط برای Admin و پس از تجزیهٔ نحوی (مثلاً sqlglot) با اجازهٔ منحصراً SELECT، با timeout و سقف تعداد ردیف.
70 +- رمزها: در Windows با DPAPI و در بقیهٔ سامانه‌ها با keyring رمز شوند؛ هرگز در لاگ، فایل پیکربندی یا خروجی نیایند.
71 +- شبکه: فقط به میزبان/درگاه ثبت‌شدهٔ اتصال؛ بدون هیچ فراخوانی اینترنتی. TLS در صورت پشتیبانی دیتابیس فعال و وضعیتش نمایش داده شود.
72 +- تغییرنکردن منبع: استخراج در تراکنش با سطح ایزولاسیون snapshot/read-committed و بدون قفل طولانی.
73 +
74 +### ب‌۶. Source Adapter (پروفایل منبع)
75 +
76 +یک فایل اعلانی نسخه‌دار با این بخش‌ها: اتصال (ارجاع به رمز)، queries پارامتری برای سال/دوره، columns (نگاشت ستون‌های منبع به فیلدهای کانونی)، transforms (مثل normalize_fa، پر کردن صفر کد)، sign_convention، unit (ریال/میلیون ریال)، و expectations (انتظارات اعتبارسنجی مثل «جمع بدهکار برابر جمع بستانکار»). تغییر هر چیز در adapter = نسخهٔ جدید و ثبت در audit.
77 +
78 +**فیلدهای کانونی:** account_code (متن)، سطوح level_1..level_n، account_name، opening، debit، credit، closing، period، و در سطح سند (اختیاری): doc_no، doc_date_gregorian و doc_date_jalali، description، cost_center، counterparty.
79 +
80 +**ب‌۶‌-۱. جریان کاربر برای اتصال (ویزارد):** اتصال ← تست ← کشف ساختار ← انتخاب جدول/ویوی منبع ← نگاشت ستون‌ها با پیشنهاد خودکار ← پیش‌نمایش ۵۰ ردیف ← تطبیق خودکار با انتظارات ← ذخیره به‌عنوان adapter ← استخراج آزمایشی ← گزارش تطبیق (تعداد ردیف، مجموع‌ها، hash) ← تأیید و ساخت snapshot.
81 +
82 +### ب‌۷. Snapshot و تطبیق با منبع
83 +
84 +- هر استخراج: ExtractionRun با پارامترها، نسخهٔ adapter، زمان، تعداد ردیف، مجموع‌های کنترلی (جمع بدهکار، بستانکار، ماندهٔ ابتدا/پایان) و hash کل.
85 +- تطبیق دوطرفه: مجموع‌های محاسبه‌شده توسط خود دیتابیس مبدأ (با SUM در پرس‌وجوی جداگانه) باید دقیقاً با مجموع‌های snapshot برابر باشد؛ اختلاف = توقف.
86 +- استخراج دوباره برای همان دوره، snapshot جدید می‌سازد و تفاوت با قبلی را نشان می‌دهد (حساب‌های تغییرکرده). تا وقتی سال Draft است مجاز است، پس از تأیید فقط از مسیر Reopen.
87 +- پشتیبانی از استخراج افزایشی فقط وقتی منبع شناسهٔ تغییر قابل‌اتکا دارد؛ پیش‌فرض همیشه استخراج کامل دوره است (سادگی و صحت مقدم بر سرعت).
88 +
89 +### ب‌۸. بسته‌های داده (Packs) برای عمومی‌بودن
90 +
91 +- **StatementTemplatePack:** ردیف‌ها، ترتیب، شمارهٔ یادداشت، فرمول، قواعد مرتب‌سازی و عنوان‌ها به‌صورت داده؛ نسخه‌دار؛ هر صورت یک قالب و هر شرکت یک قالب انتخاب‌شده دارد.
92 +- **MappingPack:** الگوی نگاشت سرفصل‌ها به یادداشت‌ها برای یک نوع کسب‌وکار/استاندارد؛ هنگام راه‌اندازی شرکت جدید، موتور پیشنهاد نگاشت می‌دهد (بر پایهٔ پیشوند کد، شباهت نام فارسی نرمال‌شده و نگاشت شرکت‌های مشابه)، هرگز تأیید خودکار.
93 +- **Industry Profiles:** صنایع نمونه (تولیدی، بازرگانی، خدماتی، انرژی/انتقال) فقط به‌صورت بستهٔ داده؛ بستهٔ فعلی شرکت انتقال‌دهنده یکی از آن‌هاست، نه پیش‌فرض سامانه.
94 +- **قاعده:** افزودن شرکت یا صنعت جدید باید بدون تغییر کد و فقط با افزودن بسته ممکن باشد؛ این با تست «شرکت ساختگی دوم» در CI اثبات شود.
95 +
96 +### ب‌۹. هرم اعتماد («ضدگلوله» یعنی چه)
97 +
98 +ضدگلوله‌بودن با ادعا حاصل نمی‌شود، با لایه‌های قابل‌اندازه‌گیری حاصل می‌شود:
99 +
100 +1. **تست طلایی چندشرکتی:** حداقل سه مجموعه‌داده با ساختار متفاوت (شرکت فعلی + دو شرکت دیگر، واقعی یا ناشناس‌شده) که خروجی هرکدام با صورت رسمی/دستی همان شرکت ریال‌به‌ریال می‌خواند.
101 +2. **محاسبهٔ مستقل دوگانه (Dual-path):** جمع‌های هر ردیف صورت علاوه بر موتور اصلی، با یک مسیر مستقل (پرس‌وجوی SQL تجمیعی روی snapshot) محاسبه و برابری الزامی شود. نتیجهٔ ناهمخوان = باگ تا اثبات خلاف.
102 +3. **تست‌های متامورفیک:** جابه‌جایی ترتیب ردیف‌ها، تقسیم یک حساب به دو حساب با جمع برابر، یا اضافه‌کردن حساب با مانده صفر نباید جمع‌ها را عوض کند.
103 +4. **Property-based و تخریبی** (کتابچهٔ ۱ بخش ۱۴).
104 +5. **حالت اجرای موازی (Shadow Run):** برای یک دورهٔ واقعی، خروجی Aram کنار صورت دستی قرار می‌گیرد و گزارش اختلاف ردیف‌به‌ردیف تولید می‌شود؛ پذیرش نهایی بر پایهٔ همین گزارش است.
105 +6. **بازتولیدپذیری:** هر خروجی رسمی از CalculationRun با hash ورودی/کد/adapter/قالب؛ اجرای دوباره بایت‌به‌بایت یکسان.
106 +
107 +### ب‌۱۰. امنیت (افزون بر کتابچهٔ ۱ بخش ۱۳)
108 +
109 +- حداقل دسترسی برای کاربر دیتابیس منبع؛ ثبت اینکه کدام کاربر/ماشین چه استخراجی انجام داد.
110 +- فهرست مجاز افزونه‌ها با hash؛ افزونهٔ Connector بدون اجازهٔ صریح به فایل‌سیستم/شبکهٔ غیرمنبع دسترسی ندارد.
111 +- ناشناس‌سازی خروجی پشتیبانی (حذف نام شرکت/مبالغ) برای ارسال خطا.
112 +- SBOM و لاک‌فایل با hash برای وابستگی‌ها؛ بسته‌های نصب امضاشده؛ به‌روزرسانی آفلاین با بستهٔ امضاشده.
113 +- سیاست نگه‌داری: مدت نگه‌داری snapshotها و لاگ‌ها قابل‌تنظیم؛ حذف فقط با دو نقش و ثبت در audit.
114 +
115 +### ب‌۱۱. تجربهٔ کاربری
116 +
117 +وب‌اپ محلی فارسی RTL با پشتیبانی کامل موبایل در سطح مرورگر؛ کاربر اصلی مسیرهایی را بدون ابزار جانبی طی کند: راه‌اندازی شرکت ← اتصال/ورود داده ← نگاشت ← یادداشت‌ها ← صورت‌ها و کنترل‌ها ← تأیید ← خروجی. هر صفحه وضعیت واقعی سال (Draft/Reviewed/Approved/Locked) و علت غیرفعال‌بودن دکمه‌ها را نشان دهد. طرح صفحات در بوم طراحی ضمیمه به‌عنوان مرجع سبک است؛ مجاز به بهبود ولی نه حذف عناصر کنترلی (کنترل‌ها، ردیابی، وضعیت).
118 +
119 +### ب‌۱۲. استقرار
120 +
121 +پیش‌فرض: نصب محلی آفلاین Windows با SQLite. حالت سرور (چندکاربره هم‌زمان، PostgreSQL، TLS) در نسخهٔ بعد؛ از هم‌اکنون معماری، مدل داده و migrationها روی PostgreSQL در CI تست می‌شوند. هر دو حالت از یک کد با پیکربندی اجرا شوند.
122 +
123 +## بخش ۱۳ — نقشهٔ راه (به ترتیب؛ هر فاز با معیار پذیرش مبتنی بر شواهد)
124 +
125 +- **فاز C0 — اصلاح مسیر:** بخش الف کامل.
126 +- **فاز C1 — برش عمودی واقعی:** لجر ۱۴۰۴ ← LedgerBalance ← کنترل‌های C-01/C-02 ← نگاشت ← BS/IS ← تطبیق با صورت رسمی. پذیرش: تست طلایی سبز یا اختلاف‌ها مستند.
127 +- **فاز C2 — نگاشت و یادداشت‌ها:** کتابچهٔ ۱ فازهای ۲ و ۳.
128 +- **فاز C3 — چهار صورت و کنترل‌ها:** BS/IS/EQ/CF، همهٔ کنترل‌های C-01..C-15، مقایسهٔ دو سال، سال ۱۴۰۳.
129 +- **فاز C4 — چارچوب Connector و FileConnector:** مدل افزونه، مانیفست، Conformance Suite، Adapter، snapshot و تطبیق. پذیرش: ورود لجر فعلی از طریق FileConnector دقیقاً همان snapshot فاز C1 را بدهد.
130 +- **فاز C5 — Connector دیتابیس:** SQLite/PostgreSQL، سپس SQL Server، با دیتابیس آزمایشی در CI؛ وزارت/شرکت واقعی فقط با کاربر فقط‌خواندنی.
131 +- **فاز C6 — بسته‌های داده و عمومی‌سازی:** قالب و نگاشت به‌صورت بسته؛ اثبات با «شرکت ساختگی دوم» و سپس شرکت دوم واقعی.
132 +- **فاز C7 — UI کامل و خروجی‌ها:** کتابچهٔ ۱ فازهای ۵ و ۶ بر پایهٔ مدل جدید.
133 +- **فاز C8 — امنیت و ممیزی:** کتابچهٔ ۱ فاز ۷ + بخش ب‌۱۰.
134 +- **فاز C9 — بسته‌بندی و استقرار:** کتابچهٔ ۱ فاز ۸ + SBOM و امضا.
135 +- **فاز C10 — پذیرش:** Shadow Run روی دورهٔ واقعی دو شرکت و امضای مالک.
136 +
137 +قاعدهٔ ورود به فاز بعد: شواهد فاز قبل (SHA، CI، خروجی تست، گزارش تطبیق) در `PROJECT_STATUS.md` ثبت شده باشد.
138 +
139 +## بخش ۱۴ — قواعد تصمیم خودکار (بدون پرسش از مالک)
140 +
141 +برای هر ابهام: پیش‌فرض را اعمال کن، با داده بسنج، شواهد را در ADR ثبت کن، ادامه بده. شواهد بر پیش‌فرض مقدم است. تصمیم‌های کتابچهٔ ۱ بخش ۱۷ (OD-01 تا OD-08) معتبر و ادامه‌دارند. تصمیم‌های تازه:
142 +
143 +| کد | پیش‌فرض | اثبات یا اصلاح |
144 +|---|---|---|
145 +| OD-09 درایور SQL Server | python-tds (خالص‌پایتون)، با pyodbc به‌عنوان جایگزین | آزمون اتصال و استخراج ۱۰۰هزار ردیف؛ اگر ناپایدار بود pyodbc |
146 +| OD-10 زبان adapter | YAML با اعتبارسنجی JSON Schema | تست round-trip و پیام خطای فارسی دقیق |
147 +| OD-11 اجرای افزونه | فرایند جداگانه برای Connectorها | اگر مانع بسته‌بندی Windows شد، همان‌فرایند با مجوز محدود و ثبت ADR |
148 +| OD-12 سطح داده | پیش‌فرض تراز آزمایشی؛ سطح سند اختیاری و بعد از فاز C6 | فقط وقتی یادداشت خاصی بدون ریز سند قابل‌محاسبه نبود فعال شود |
149 +| OD-13 همزمانی | تک‌نصب محلی؛ سرور چندکاربره خارج از V1 | تست PostgreSQL در CI برای مسیر آینده |
150 +| OD-14 مقایسه با ابزارهای مشابه | از آن‌ها فقط الهام بگیر؛ کد، برند و محتوا کپی نشود | ردیف مقایسهٔ قابلیت‌ها در یک ADR |
151 +| سایر ابهام‌ها | محافظه‌کارانه‌ترین گزینه (آنی که تأیید را مسدود می‌کند) | ADR با گزینه‌های ردشده |
152 +
153 +**توقف مجاز فقط در دو حالت:** خطر تغییر یا نابودی داده/دیتابیس مبدأ، یا تضاد مستقیم با `AGENTS.md`. در این دو حالت وضعیت را گزارش و روی کارهای مستقل ادامه بده.
154 +
155 +## بخش ۱۵ — تعریف «تمام‌شده» نسخهٔ ۲
156 +
157 +1. تست طلایی سه شرکت سبز (یا اختلاف‌ها با علت و امضا در `docs/discrepancies.json`).
158 +2. ورود از FileConnector و حداقل دو Connector دیتابیس از مسیر Conformance Suite.
159 +3. شرکت دوم بدون تغییر کد فقط با افزودن بسته راه‌اندازی شد.
160 +4. محاسبهٔ مستقل دوگانه و تست‌های متامورفیک سبز.
161 +5. SQL خام روی سال قفل‌شده شکست می‌خورد و audit زنجیره‌ای تأیید می‌شود.
162 +6. بستهٔ Windows روی ماشین تمیز آفلاین نصب و اجرا می‌شود.
163 +7. Shadow Run دو شرکت و امضای مالک.
164 +8. گزارش پایان هر فاز با قالب کتابچهٔ ۱ بخش ۱۸ و جملهٔ `Ready for independent GitHub review; not merged.`
165 +
166 +## بخش ۱۶ — ممنوعیت‌ها
167 +
168 +همهٔ ممنوعیت‌های کتابچهٔ ۱ بخش ۱۹، و افزون بر آن: وابستگی به شبکه در زمان اجرا؛ هر نام/کد/سرفصل مختص یک شرکت در کد؛ نوشتن در دیتابیس مبدأ؛ ذخیرهٔ رمز در متن آشکار؛ کوئری سفارشی بدون تجزیهٔ نحوی؛ ادغام PR توسط خود ایجنت؛ ادعای تکمیل بدون شواهد؛ و افزودن مستند تحلیلی جدید در ریشهٔ مخزن.
169 +
170 +## پیوست — ایدهٔ مرجع: databansoft.ir
171 +
172 +کاتالوگ رسمی دیتابان (ویرایش پاییز ۱۴۰۵) مطالعه شد. این سند تبلیغاتی است؛ ادعاهایش راستی‌آزمایی نشده و فقط **الهام** است. دیتابان لایه‌ای هوشمند روی دفاتر نرم‌افزار حسابداری فعلی است: مستقیم از دفاتر می‌خواند، روی سرور خود شرکت (Windows و SQL Server) اجرا می‌شود، چند شرکت را در یک قالب می‌آورد و حوزه‌اش گزارش، داشبورد، هشدار، خودکارسازی و سامانه‌های دولتی است. **صورت مالی تهیه نمی‌کند.** پس Aram رقیب مستقیم آن نیست؛ جای خالی‌اش همین است: موتور تهیه، کنترل و ممیزی صورت‌های مالی.
173 +
174 +**تصمیم موقعیت‌یابی:** Aram محصول مستقل با هستهٔ افزونه‌پذیر است و یک **Host Integration API** (قرارداد REST + مجوزها) دارد تا بتواند در آینده به‌عنوان ماژول داخل یک پلتفرم داده جا بگیرد. هر همکاری تجاری با دیتابان یا مشابه آن خارج از دامنهٔ ایجنت است.
175 +
176 +**عناصر پذیرفته‌شده (به ترتیب اولویت):**
177 +
178 +1. **خواندن مستقیم از دفاتر نرم‌افزار حسابداری بدون تغییر در آن** (تأیید ب‌۴ و ب‌۵). چون محیط هدف Windows و SQL Server است، OD-09 اصلاح می‌شود: pyodbc با درایور ODBC موجود اولویت دارد و python-tds جایگزین است.
179 +2. **کنترل دسترسی چندلایه:** ماژول ← شرکت ← سال مالی ← ردیف/فیلد، با یک سیاست واحد در API، UI، خروجی‌ها و هر ماژول هوش مصنوعی (افزودن به ب‌۱۰).
180 +3. **تشخیص رانش منبع (Source Drift):** پس از تأیید snapshot، یک کار شبانه (سرویس Windows) مجموع‌ها و hash منبع را دوباره می‌سنجد. اگر سندی با تاریخ سال تأییدشده اضافه، اصلاح یا حذف شده بود: هشدار، ثبت در audit و انتقال سال به وضعیت «نیازمند بازبینی»؛ خروجی تأییدشده هرگز خودکار تغییر نمی‌کند.
181 +4. **حسابرسی شبانهٔ سطح سند** (اختیاری، فقط اگر Connector سطح سند دارد): سند ناتراز، تکراری احتمالی، مبلغ کلان، سند اصلاح/حذف‌شده؛ خروجی آن به کنترل‌های Aram وصل شود (C-16 به بعد).
182 +5. **مرکز کارها:** یک صفحه برای همهٔ موارد منتظر کاربر: حساب‌های ناشناخته، کنترل‌های ناموفق، درخواست‌های تأیید/بازگشایی، رانش منبع.
183 +6. **اجرای آزمایشی (Dry-run)** برای هر استخراج و کار خودکار: نتیجه بدون هیچ اثری نمایش داده شود.
184 +7. **به‌روزرسانی امضاشده با بازگشت خودکار** و پشتیبان/بازیابی داخل برنامه (کتابچهٔ ۱ بخش ۱۳ و فاز C9).
185 +8. **قالب چاپ با سربرگ شرکت** برای صورت‌ها، خروجی دفاتر قانونی (روزنامه و کل) و جدول‌های پشتیبان، و جستجوی سراسری Ctrl+K.
186 +9. **دستیار هوش مصنوعی (فاز C11، اختیاری، پیش‌فرض خاموش):** هوش مصنوعی فقط پرسش را می‌فهمد و **هیچ عددی را تولید نمی‌کند**؛ اعداد فقط از موتور و یک CalculationRun تأییدشده با منبع (lineage) می‌آیند. فقط‌خواندنی، با مدل محلی یا ناشناس‌سازی نام اشخاص و شرکت پیش از ارسال به هر سرویس بیرونی، و ثبت هر پرسش در audit. پیشنهاد نگاشت با هوش مصنوعی هم فقط «پیشنهاد» است و تأیید انسانی الزامی می‌ماند (بدون تغییر ب‌۸).
187 +10. **چندشرکتی** با یک قالب و داشبورد گروه؛ صورت تلفیقی در نسخهٔ بعد.
188 +
189 +**خارج از دامنه (رد شد):** سامانهٔ مودیان، IMED، سامانهٔ جامع تجارت، پردازش صورتحساب بانکی و سندخوان، فرمساز و کارتابل عمومی. بات پیامرسان برای داده مالی پیش‌فرض ممنوع است؛ در صورت نیاز فقط اعلان بدون ارقام.
190 +
191 +**محدودیت حقوقی:** کپی کد، متن، طراحی، نام و برند دیتابان ممنوع است؛ هر قابلیت باید مستقل طراحی و ثبت شود. در تضاد، ب‌۱ تا ب‌۱۲ و بخش ۱۴ مقدم‌اند مگر شواهد بهتری ارائه شود.
docs/booklet/MANIFEST.json new
+35
@@ -0,0 +1,35 @@
1 +{
2 + "booklets": [
3 + {
4 + "version": "1.0",
5 + "reference": "BOOKLET_v1.0.md",
6 + "original_filename": "کتابچهٔ اجرایی تکمیل Aram.pdf",
7 + "original_format": "PDF",
8 + "original_sha256": "7dd508274babd604f74d10b692464ce42f26a88c4a7116cfd861188abd4a2baf",
9 + "original_size_bytes": 745088,
10 + "page_count": 14,
11 + "extraction_tool": "pymupdf",
12 + "extraction_method": "per-line whitespace-token reversal (visual RTL -> logical reading order)",
13 + "note": "Original binary not committed (§19); SHA-256 is the integrity anchor. B0.1 referenced docx; the actual provided source is PDF. See ADR-025."
14 + },
15 + {
16 + "version": "2.0",
17 + "reference": "BOOKLET_v2.0.md",
18 + "source": "Owner message 2026-12-03 (chat text; no original file)",
19 + "original_format": "verbatim chat text",
20 + "markdown_sha256": "79618dddb3de9bde195b8253880593b2900389369150c917d81b97006762823a",
21 + "markdown_size_bytes": 28045,
22 + "note": "Verbatim owner work order (list numbering normalized for markdown; content unchanged). Supersedes conflicting sections of booklet 1 and supplements the rest. Integrity anchor is the SHA-256 of this markdown. See ADR-027 and ADR-029.",
23 + "revisions": [
24 + {
25 + "markdown_sha256": "9738f8049703ca63ea6eae471538cdadc6328e4f15efaaf87a250315e516e2fc",
26 + "note": "Initial owner message 2026-12-03; appendix: site not loaded by booklet author, no capability claims."
27 + },
28 + {
29 + "markdown_sha256": "79618dddb3de9bde195b8253880593b2900389369150c917d81b97006762823a",
30 + "note": "Owner revision 2026-12-03 (second message): Databan catalog (fall 1405) studied by owner; positioning decision + Host Integration API; accepted elements 1-10; OD-09 revised to pyodbc-first; phase C11 (optional AI assistant, off by default, never generates numbers); rejected-scope list; legal restriction."
31 + }
32 + ]
33 + }
34 + ]
35 +}
docs/bridge.py deleted
-207
@@ -1,207 +0,0 @@
1 -"""JSON-in / JSON-out bridge that runs the exact Aram engine in the browser.
2 -
3 -This mirrors backend/src/aram_backend/pilot_api.py but without FastAPI, so the
4 -identical, tested engine/store/editing code runs client-side under Pyodide.
5 -Everything stays in memory; the durable artifacts are the exported workbooks.
6 -"""
7 -
8 -from __future__ import annotations
9 -
10 -import base64
11 -import json
12 -import re
13 -
14 -from aram_backend.pilot_demo import build_demo_workbook
15 -from aram_backend.pilot_editing import (
16 - DuplicateAccountError,
17 - DuplicateNoteError,
18 - EditingError,
19 - NoteInUseError,
20 - UnknownNoteError,
21 - make_company,
22 - make_note,
23 -)
24 -from aram_backend.pilot_engine import (
25 - DEFERRED_STATEMENTS,
26 - RENDERED_STATEMENTS,
27 - SECTION_LABELS_FA,
28 - SECTION_POLICY,
29 - STATEMENT_LABELS_FA,
30 - PilotModelError,
31 - accounts_table,
32 - build_report,
33 - export_report_workbook,
34 - export_working_workbook,
35 - notes_table,
36 - parse_pilot_model,
37 -)
38 -from aram_backend.pilot_store import (
39 - InvalidApprovalError,
40 - PilotSessionStore,
41 - UnknownAccountError,
42 - UnknownSessionError,
43 - UnknownTargetError,
44 -)
45 -
46 -store = PilotSessionStore()
47 -
48 -
49 -def _payload(session_id: str) -> dict:
50 - session, working, trail = store.snapshot(session_id)
51 - report = build_report(working, working.mappings)
52 - return {
53 - "session": {
54 - "id": session.id, "created_at": session.created_at,
55 - "source": session.source, "filename": session.filename,
56 - },
57 - "report": report,
58 - "accounts": accounts_table(working, working.mappings),
59 - "notes": notes_table(working),
60 - "audit_trail": trail,
61 - }
62 -
63 -
64 -def _meta() -> dict:
65 - return {
66 - "rendered_statements": list(RENDERED_STATEMENTS),
67 - "deferred_statements": list(DEFERRED_STATEMENTS),
68 - "statement_labels_fa": STATEMENT_LABELS_FA,
69 - "section_policy": SECTION_POLICY,
70 - "section_labels_fa": SECTION_LABELS_FA,
71 - "contract": "Pilot workbook v0.1",
72 - "disclaimer_fa": "خروجی این ابزار پیش‌نویس کاری برای بررسی است، نه صورت مالی رسمی.",
73 - }
74 -
75 -
76 -def _create(data: bytes, source: str, filename: str) -> dict:
77 - model = parse_pilot_model(data)
78 - session = store.create(model, source=source, filename=filename)
79 - return _payload(session.id)
80 -
81 -
82 -def _export(session_id: str, kind: str) -> dict:
83 - session = store.get(session_id)
84 - _, working, trail = store.snapshot(session_id)
85 - safe = re.sub(r"[^A-Za-z0-9_-]", "", working.company.code) or "session"
86 - if kind == "workspace":
87 - data = export_working_workbook(working)
88 - name = f"aram-workspace-{safe}-{working.company.fiscal_year}.xlsx"
89 - else:
90 - report = build_report(working, working.mappings)
91 - data = export_report_workbook(working, working.mappings, report, trail, session.source)
92 - name = f"aram-pilot-{safe}-{working.company.fiscal_year}.xlsx"
93 - return {"filename": name, "bytes_b64": base64.b64encode(data).decode("ascii")}
94 -
95 -
96 -def _dispatch(action: str, d: dict):
97 - if action == "meta":
98 - return _meta()
99 - if action == "demo":
100 - return _create(build_demo_workbook(), "demo", "aram-synthetic-demo.xlsx")
101 - if action == "upload":
102 - raw = base64.b64decode(d["bytes_b64"])
103 - if not raw:
104 - raise EditingError("فایل خالی است.")
105 - return _create(raw, "upload", d.get("filename", "upload.xlsx"))
106 - if action == "get":
107 - return _payload(d["sid"])
108 - if action == "delete_session":
109 - store.delete(d["sid"])
110 - return {"deleted": d["sid"]}
111 - if action == "set_mapping":
112 - store.set_mapping(
113 - d["sid"], d["code"], statement=d["statement"].strip(), section=d["section"].strip(),
114 - note_number=d["note_number"].strip(), subnote_code=d.get("subnote_code", "").strip(),
115 - approval_status=d.get("approval_status", "Draft"), reviewer=d.get("reviewer", ""),
116 - actor=d.get("actor", ""),
117 - )
118 - return _payload(d["sid"])
119 - if action == "clear_mapping":
120 - store.clear_mapping(d["sid"], d["code"], actor=d.get("actor", ""))
121 - return _payload(d["sid"])
122 - if action == "add_account":
123 - store.add_account(
124 - d["sid"], full_code=d["full_code"], name=d["name"], general_code=d["general_code"],
125 - general_name=d["general_name"], opening=d.get("opening", "0"), debit=d.get("debit", "0"),
126 - credit=d.get("credit", "0"), source_row=d.get("source_row"), row_status=d.get("row_status", "Draft"),
127 - subsidiary_code=d.get("subsidiary_code", ""), subsidiary_name=d.get("subsidiary_name", ""),
128 - actor=d.get("actor", ""),
129 - )
130 - return _payload(d["sid"])
131 - if action == "update_account":
132 - store.update_account(
133 - d["sid"], d["code"], name=d["name"], general_code=d["general_code"],
134 - general_name=d["general_name"], opening=d.get("opening", "0"), debit=d.get("debit", "0"),
135 - credit=d.get("credit", "0"), row_status=d.get("row_status", "Draft"),
136 - subsidiary_code=d.get("subsidiary_code", ""), subsidiary_name=d.get("subsidiary_name", ""),
137 - actor=d.get("actor", ""),
138 - )
139 - return _payload(d["sid"])
140 - if action == "rename_account":
141 - store.rename_account(d["sid"], d["code"], d["new_code"], actor=d.get("actor", ""))
142 - return _payload(d["sid"])
143 - if action == "delete_account":
144 - store.delete_account(d["sid"], d["code"], actor=d.get("actor", ""))
145 - return _payload(d["sid"])
146 - if action == "add_note":
147 - note = make_note(
148 - statement=d["statement"], section=d["section"], note_number=d["note_number"],
149 - note_title=d["note_title"], subnote_code=d.get("subnote_code", ""),
150 - subnote_title=d.get("subnote_title", ""),
151 - )
152 - store.add_note(d["sid"], note, actor=d.get("actor", ""))
153 - return _payload(d["sid"])
154 - if action == "update_note":
155 - key = (d["statement"].strip(), d["section"].strip(), d["note_number"].strip(), d.get("subnote_code", "").strip())
156 - note = make_note(
157 - statement=d["statement"], section=d["section"], note_number=d["note_number"],
158 - note_title=d["note_title"], subnote_code=d.get("subnote_code", ""),
159 - subnote_title=d.get("subnote_title", ""),
160 - )
161 - store.update_note(d["sid"], key, note, actor=d.get("actor", ""))
162 - return _payload(d["sid"])
163 - if action == "delete_note":
164 - key = (d["statement"].strip(), d["section"].strip(), d["note_number"].strip(), d.get("subnote_code", "").strip())
165 - store.delete_note(d["sid"], key, actor=d.get("actor", ""))
166 - return _payload(d["sid"])
167 - if action == "update_company":
168 - company = make_company(
169 - code=d["code"], name=d["name"], fiscal_year=d["fiscal_year"],
170 - currency=d.get("currency", ""), unit=d.get("unit", ""),
171 - prepared_by=d.get("prepared_by", ""), status=d.get("status", "Draft"),
172 - )
173 - store.update_company(d["sid"], company, actor=d.get("actor", ""))
174 - return _payload(d["sid"])
175 - if action == "export_report":
176 - return _export(d["sid"], "report")
177 - if action == "export_workspace":
178 - return _export(d["sid"], "workspace")
179 - raise EditingError(f"اقدام ناشناخته: {action}")
180 -
181 -
182 -def handle(action: str, data_json: str = "") -> str:
183 - """Single entry point called from JavaScript. Always returns a JSON string."""
184 - try:
185 - data = json.loads(data_json) if data_json else {}
186 - except json.JSONDecodeError:
187 - data = {}
188 - try:
189 - return json.dumps({"ok": True, "data": _dispatch(action, data)}, ensure_ascii=False)
190 - except PilotModelError as exc:
191 - return json.dumps({
192 - "ok": False,
193 - "error": "فایل با قرارداد پایلوت v0.1 سازگار نیست؛ خطاهای زیر را رفع کنید.",
194 - "issues": [
195 - {"severity": i.severity, "code": i.code, "sheet": i.sheet,
196 - "row": i.row, "field": i.field, "message": i.message}
197 - for i in exc.issues
198 - ],
199 - }, ensure_ascii=False)
200 - except (UnknownSessionError, UnknownAccountError, UnknownNoteError) as exc:
201 - return json.dumps({"ok": False, "error": str(exc) or "مورد یافت نشد.", "status": 404}, ensure_ascii=False)
202 - except (DuplicateAccountError, DuplicateNoteError, NoteInUseError) as exc:
203 - return json.dumps({"ok": False, "error": str(exc), "status": 409}, ensure_ascii=False)
204 - except (EditingError, UnknownTargetError, InvalidApprovalError) as exc:
205 - return json.dumps({"ok": False, "error": str(exc), "status": 422}, ensure_ascii=False)
206 - except Exception as exc: # noqa: BLE001 - surface a safe message to the UI
207 - return json.dumps({"ok": False, "error": f"خطای غیرمنتظره: {exc}"}, ensure_ascii=False)
docs/discrepancies.json new
+323
@@ -0,0 +1,323 @@
1 +{
2 + "purpose": "OD-08 / D1 / الف‌7: one-by-one record of every golden-test difference (source-aggregated-by-note vs official statement) with cause and evidence. An uncaused difference is a bug until proven otherwise. Numbers are never 'corrected' here — only an Adjustment (C4) or a discrepancy record is permitted (booklet §6.7/§12.60, D1/D2).",
3 + "status": "POPULATED for 1404 golden (source-vs-official, ADR-021). 28 comparisons, 9 matched, 19 recorded. Resolution of causes tracked in C1/C3; build-vs-official comparison added when the engine builds all four statements (C3).",
4 + "scale_note": "Official statements are in million rial; source is exact rial. Comparison rounds source rial to million (half-up, ADR-012/021). our_amount/official_amount are exact rial strings; *_million fields are the comparison basis.",
5 + "record_schema": {
6 + "row": "statement + note identifier",
7 + "statement": "BS/IS/EQ/CF",
8 + "note": "note number as in official sheet",
9 + "our_amount": "source-aggregated exact rial (string)",
10 + "official_amount": "official million rial x 1e6 (string)",
11 + "our_million_rounded": "source rial rounded to million (half-up)",
12 + "official_million": "official million rial",
13 + "delta_million": "our_million_rounded - official_million",
14 + "cause": "root-cause explanation (Persian)",
15 + "cause_status": "caused | under_investigation (under_investigation = bug until proven, D1)",
16 + "evidence": "reproducible proof pointer",
17 + "year": "Jalali fiscal year"
18 + },
19 + "summary": {
20 + "total_comparisons": 28,
21 + "matched": 9,
22 + "recorded": 19,
23 + "by_statement": {
24 + "BS": {
25 + "total": 16,
26 + "matched": 9,
27 + "recorded": 7
28 + },
29 + "IS": {
30 + "total": 6,
31 + "matched": 0,
32 + "recorded": 6
33 + },
34 + "EQ": {
35 + "total": 0,
36 + "matched": 0,
37 + "recorded": 0
38 + },
39 + "CF": {
40 + "total": 6,
41 + "matched": 0,
42 + "recorded": 6
43 + }
44 + },
45 + "by_cause_status": {
46 + "caused": 16,
47 + "under_investigation": 3
48 + }
49 + },
50 + "coverage_notes": [
51 + "EQ: read_official_notes extracted 0 note rows from the official «حقوق مالكانه» sheet for 1404 (layout differs); EQ official parsing is a C3 coverage gap, not a zero discrepancy.",
52 + "This golden test is source-aggregated-vs-official (ADR-021). A build-vs-official comparison (engine output vs official) is added in C3 once BS/IS/EQ/CF are all built.",
53 + "Approval of the real 1404 year is currently BLOCKED by controls C-01/C-03/C-04 (UAT). Separately, ADR-013 records 6 residual C-01 rows in the 252,898-row source (252,892 satisfy debit-positive); these are source-data quirks to reconcile, not statement discrepancies, and are tracked under C-01/ADR-013."
54 + ],
55 + "records": [
56 + {
57 + "row": "BS note 16",
58 + "statement": "BS",
59 + "note": "16",
60 + "our_amount": "-20000000000000",
61 + "official_amount": "20000000000000",
62 + "our_million_rounded": -20000000,
63 + "official_million": 20000000,
64 + "delta_million": -40000000,
65 + "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
66 + "cause_status": "caused",
67 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 16 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
68 + "year": 1404
69 + },
70 + {
71 + "row": "BS note 18",
72 + "statement": "BS",
73 + "note": "18",
74 + "our_amount": "-1613615852",
75 + "official_amount": "1614000000",
76 + "our_million_rounded": -1614,
77 + "official_million": 1614,
78 + "delta_million": -3228,
79 + "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
80 + "cause_status": "caused",
81 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 18 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
82 + "year": 1404
83 + },
84 + {
85 + "row": "BS note 19-1",
86 + "statement": "BS",
87 + "note": "19-1",
88 + "our_amount": "-145241976038754",
89 + "official_amount": "145241976000000",
90 + "our_million_rounded": -145241976,
91 + "official_million": 145241976,
92 + "delta_million": -290483952,
93 + "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
94 + "cause_status": "caused",
95 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 19-1 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
96 + "year": 1404
97 + },
98 + {
99 + "row": "BS note 19-2",
100 + "statement": "BS",
101 + "note": "19-2",
102 + "our_amount": "-630414220070002",
103 + "official_amount": "630414220000000",
104 + "our_million_rounded": -630414220,
105 + "official_million": 630414220,
106 + "delta_million": -1260828440,
107 + "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
108 + "cause_status": "caused",
109 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 19-2 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
110 + "year": 1404
111 + },
112 + {
113 + "row": "BS note 20",
114 + "statement": "BS",
115 + "note": "20",
116 + "our_amount": "-133078120519345",
117 + "official_amount": "133078121000000",
118 + "our_million_rounded": -133078121,
119 + "official_million": 133078121,
120 + "delta_million": -266156242,
121 + "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
122 + "cause_status": "caused",
123 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 20 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
124 + "year": 1404
125 + },
126 + {
127 + "row": "BS note 21",
128 + "statement": "BS",
129 + "note": "21",
130 + "our_amount": "-8833412166636",
131 + "official_amount": "8833412000000",
132 + "our_million_rounded": -8833412,
133 + "official_million": 8833412,
134 + "delta_million": -17666824,
135 + "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
136 + "cause_status": "caused",
137 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 21 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
138 + "year": 1404
139 + },
140 + {
141 + "row": "BS note 22",
142 + "statement": "BS",
143 + "note": "22",
144 + "our_amount": "-61449318680",
145 + "official_amount": "61449000000",
146 + "our_million_rounded": -61449,
147 + "official_million": 61449,
148 + "delta_million": -122898,
149 + "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
150 + "cause_status": "caused",
151 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 22 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
152 + "year": 1404
153 + },
154 + {
155 + "row": "IS note 20-3",
156 + "statement": "IS",
157 + "note": "20-3",
158 + "our_amount": "0",
159 + "official_amount": "-4697329000000",
160 + "our_million_rounded": 0,
161 + "official_million": -4697329,
162 + "delta_million": 4697329,
163 + "cause": "یادداشت در ستون statement_balance منبع حضور ندارد (src_rial=0)؛ تعریف/نگاشت یادداشت یا استخراج آن هنوز انجام نشده (C2/C3)؛ مقدار رسمی غیرصفر است.",
164 + "cause_status": "caused",
165 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 20-3 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
166 + "year": 1404
167 + },
168 + {
169 + "row": "IS note 5",
170 + "statement": "IS",
171 + "note": "5",
172 + "our_amount": "-243097685650599",
173 + "official_amount": "243097686000000",
174 + "our_million_rounded": -243097686,
175 + "official_million": 243097686,
176 + "delta_million": -486195372,
177 + "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
178 + "cause_status": "caused",
179 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 5 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
180 + "year": 1404
181 + },
182 + {
183 + "row": "IS note 6",
184 + "statement": "IS",
185 + "note": "6",
186 + "our_amount": "308711587703360",
187 + "official_amount": "-245897444000000",
188 + "our_million_rounded": 308711588,
189 + "official_million": -245897444,
190 + "delta_million": 554609032,
191 + "cause": "اختلاف مقداری واقعی (قدرمطلق‌ها برابر نیستند)؛ علت دقیق هنوز تعیین نشده — احتمال تفاوت دامنهٔ حساب‌های تجمیع‌شده در یادداشت نسبت به رسمی. طبق D1 تا اثبات خلاف باگ تلقی می‌شود؛ بررسی در C3.",
192 + "cause_status": "under_investigation",
193 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 6 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
194 + "year": 1404
195 + },
196 + {
197 + "row": "IS note 7",
198 + "statement": "IS",
199 + "note": "7",
200 + "our_amount": "0",
201 + "official_amount": "-62814143000000",
202 + "our_million_rounded": 0,
203 + "official_million": -62814143,
204 + "delta_million": 62814143,
205 + "cause": "یادداشت در ستون statement_balance منبع حضور ندارد (src_rial=0)؛ تعریف/نگاشت یادداشت یا استخراج آن هنوز انجام نشده (C2/C3)؛ مقدار رسمی غیرصفر است.",
206 + "cause_status": "caused",
207 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 7 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
208 + "year": 1404
209 + },
210 + {
211 + "row": "IS note 8",
212 + "statement": "IS",
213 + "note": "8",
214 + "our_amount": "-431960487352",
215 + "official_amount": "1543514000000",
216 + "our_million_rounded": -431960,
217 + "official_million": 1543514,
218 + "delta_million": -1975474,
219 + "cause": "اختلاف مقداری واقعی (قدرمطلق‌ها برابر نیستند)؛ علت دقیق هنوز تعیین نشده — احتمال تفاوت دامنهٔ حساب‌های تجمیع‌شده در یادداشت نسبت به رسمی. طبق D1 تا اثبات خلاف باگ تلقی می‌شود؛ بررسی در C3.",
220 + "cause_status": "under_investigation",
221 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 8 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
222 + "year": 1404
223 + },
224 + {
225 + "row": "IS note 9",
226 + "statement": "IS",
227 + "note": "9",
228 + "our_amount": "9489628188720",
229 + "official_amount": "-10601182000000",
230 + "our_million_rounded": 9489628,
231 + "official_million": -10601182,
232 + "delta_million": 20090810,
233 + "cause": "اختلاف مقداری واقعی (قدرمطلق‌ها برابر نیستند)؛ علت دقیق هنوز تعیین نشده — احتمال تفاوت دامنهٔ حساب‌های تجمیع‌شده در یادداشت نسبت به رسمی. طبق D1 تا اثبات خلاف باگ تلقی می‌شود؛ بررسی در C3.",
234 + "cause_status": "under_investigation",
235 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 9 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
236 + "year": 1404
237 + },
238 + {
239 + "row": "CF note 10",
240 + "statement": "CF",
241 + "note": "10",
242 + "our_amount": "673740636579631",
243 + "official_amount": "0",
244 + "our_million_rounded": 673740637,
245 + "official_million": 0,
246 + "delta_million": 673740637,
247 + "cause": "بازاستفادهٔ شمارهٔ یادداشت میان صورت‌ها: تجمیع منبع بر پایهٔ شمارهٔ یادداشت (نه صورت) است، بنابراین مقدار یادداشت BS به مقایسهٔ CF نشت می‌کند حالی ردیف رسمی CF آن شماره ۰/متفاوت است. اصلاح: تجمیع note scoped به صورت در C3/C4.",
248 + "cause_status": "caused",
249 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 10 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
250 + "year": 1404
251 + },
252 + {
253 + "row": "CF note 15",
254 + "statement": "CF",
255 + "note": "15",
256 + "our_amount": "19951136477703",
257 + "official_amount": "3368287000000",
258 + "our_million_rounded": 19951136,
259 + "official_million": 3368287,
260 + "delta_million": 16582849,
261 + "cause": "بازاستفادهٔ شمارهٔ یادداشت میان صورت‌ها: تجمیع منبع بر پایهٔ شمارهٔ یادداشت (نه صورت) است، بنابراین مقدار یادداشت BS به مقایسهٔ CF نشت می‌کند حالی ردیف رسمی CF آن شماره ۰/متفاوت است. اصلاح: تجمیع note scoped به صورت در C3/C4.",
262 + "cause_status": "caused",
263 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 15 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
264 + "year": 1404
265 + },
266 + {
267 + "row": "CF note 20-1",
268 + "statement": "CF",
269 + "note": "20-1",
270 + "our_amount": "0",
271 + "official_amount": "-149426000000",
272 + "our_million_rounded": 0,
273 + "official_million": -149426,
274 + "delta_million": 149426,
275 + "cause": "یادداشت در ستون statement_balance منبع حضور ندارد (src_rial=0)؛ تعریف/نگاشت یادداشت یا استخراج آن هنوز انجام نشده (C2/C3)؛ مقدار رسمی غیرصفر است.",
276 + "cause_status": "caused",
277 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 20-1 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
278 + "year": 1404
279 + },
280 + {
281 + "row": "CF note 23",
282 + "statement": "CF",
283 + "note": "23",
284 + "our_amount": "0",
285 + "official_amount": "99230533000000",
286 + "our_million_rounded": 0,
287 + "official_million": 99230533,
288 + "delta_million": -99230533,
289 + "cause": "صورت جریان نقد هنوز توسط موتور محاسبه نشده (C3)؛ یادداشت CF نیازمند محاسبه از گردش‌ها است نه صرفاً statement_balance منبع؛ مقدار رسمی غیرصفر ولی منبع ۰.",
290 + "cause_status": "caused",
291 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 23 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
292 + "year": 1404
293 + },
294 + {
295 + "row": "CF note 24",
296 + "statement": "CF",
297 + "note": "24",
298 + "our_amount": "0",
299 + "official_amount": "159859431000000",
300 + "our_million_rounded": 0,
301 + "official_million": 159859431,
302 + "delta_million": -159859431,
303 + "cause": "صورت جریان نقد هنوز توسط موتور محاسبه نشده (C3)؛ یادداشت CF نیازمند محاسبه از گردش‌ها است نه صرفاً statement_balance منبع؛ مقدار رسمی غیرصفر ولی منبع ۰.",
304 + "cause_status": "caused",
305 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 24 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
306 + "year": 1404
307 + },
308 + {
309 + "row": "CF note 46268",
310 + "statement": "CF",
311 + "note": "46268",
312 + "our_amount": "0",
313 + "official_amount": "12556000000",
314 + "our_million_rounded": 0,
315 + "official_million": 12556,
316 + "delta_million": -12556,
317 + "cause": "ردیف رسمی CF با کلید '46268' ظاهراً کد حساب است نه شمارهٔ یادداشت؛ در تجمیع note منبع حضور ندارد. نیازمند طبقه‌بندی ردیف‌های شیت رسمی در C3.",
318 + "cause_status": "caused",
319 + "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 46268 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
320 + "year": 1404
321 + }
322 + ]
323 +}
\ No newline at end of file
docs/handoff/LATEST_HANDOFF.md
+21 -76
@@ -2,52 +2,31 @@
2
3 > Durable accepted-state record with persistent role assignments and recovery workflow.
4 > GitHub remote evidence remains authoritative. Always fetch the live branch head and open PRs before acting; recorded SHAs are verified events, not perpetual current-head claims.
5 +> Handoff cadence: refreshed at the end of each B-category (B0…B12) and on governance change, not after every commit (booklet §0.5; ADR-026).
6
7 ## Accepted repository state
8
9 - Repository: davoodmehraban89/Aram
9 -- Canonical branch: source-data-cleanup
10 -- Recorded accepted control event: [PR #18](https://github.com/davoodmehraban89/Aram/pull/18), reviewed head `fcbeb7387218e9ab294318ae462ed59de717fc95`, squash merge `f213d321ff4cd7d3d6fa65ba78dc48f090ee846b` at `2026-08-25T06:46:16Z`.
11 -- Durable post-merge record: [PR #19](https://github.com/davoodmehraban89/Aram/pull/19), reviewed head `b9059592409606a0a4f11a71c30778cff158b6b6`, squash merge `77f9f595ccfe67a87b11024ff0f6143629dba438` at `2026-08-25T06:57:02Z`.
12 -- Earlier accepted work includes PR #1, #4, #6, #8, #10, #12, #13, and #15.
13 -- PR #7, PR #9, PR #16, and PR #17 are closed without merge and contribute no accepted code.
14 -- [Issue #14](https://github.com/davoodmehraban89/Aram/issues/14) is completed. [Issue #11](https://github.com/davoodmehraban89/Aram/issues/11) records Gate 3 as ready for a new focused task definition.
15 -- No user-ready V1 release, tag, ZIP, EXE, or retained release artifact is accepted or proven.
10 +- Canonical branch: `source-data-cleanup`
11 +- **Live accepted head: `46253c94405abd065dfc5e8cf080b295cb83cde4`** — squash merge of [PR #96](https://github.com/davoodmehraban89/Aram/pull/96) at 2026-12-03T15:22:02Z (owner final acceptance).
12 +- **Release tag `v1.0.0`** → `46253c94405abd065dfc5e8cf080b295cb83cde4` (owner-authorized, pre-mission). Author does not tag (§19).
13 +- Post-merge CI on accepted head: [Backend #47137691800](https://github.com/davoodmehraban89/Aram/actions/runs/47137691800) ✅, [Frontend #47137691857](https://github.com/davoodmehraban89/Aram/actions/runs/47137691857) ✅.
14 +- Booklet Phases 0–9 are **VERIFIED_AND_MERGED** at this head (319 backend tests; see `PROJECT_STATUS.md`).
15 +- Earlier accepted control events: PR #1/#4/#6/#8/#10/#12/#13/#15/#18/#19/#20/#21. Closed-unmerged PR #7/#9/#16/#17 contribute no accepted code (reference only).
16 +- Authoritative work order: «کتابچهٔ اجرایی تکمیل Aram» v1.0 at `docs/booklet/BOOKLET_v1.0.md` (SHA-256 anchor in `docs/booklet/MANIFEST.json`, ADR-025).
17
17 -## Accepted Gate 2A evidence
18 +## Active mission — booklet 2 course correction + C0…C10 roadmap
19
19 -- PR: https://github.com/davoodmehraban89/Aram/pull/15
20 -- Base: `source-data-cleanup@7c7533ee87146dc8fc78b46ebf423be55532c7eb`
21 -- Reviewed PR head: `74b6a6397a2a2c9199a5c7bcf818bb661b2ebe06`
22 -- Squash merge: `4ab54f4a3cf666827fa1ed30c4e43259ea79f2d4`
23 -- Final GitHub Actions: https://github.com/davoodmehraban89/Aram/actions/runs/32712900800
24 -- CI conclusion: success; 52 passed, 1 warning; Alembic upgrade/downgrade and compileall succeeded.
25 -- Accepted capabilities: governed Pilot workbook v0.1 contract, approved blank template, reproducible generator, and deterministic read-only in-memory preflight.
26 -- Template path: `samples/Aram_Pilot_Input_and_Mapping_Template_v0.1.xlsx`
27 -- Independently recomputed SHA-256: `e14a7feb80a216d79ed9cb6dde2b0df3e55317f3da6b26efc77f7118f4702b6f`
28 -- Protected boundary: PR #15 changed no canonical XLSX/PDF, `data/`, database, financial-source, workflow, migration, desktop/release, ZIP, or EXE path.
20 +Booklet 2 v2.0 (`docs/booklet/BOOKLET_v2.0.md`, ADR-027) supersedes conflicting parts of booklet 1 and the B0…B12 framing; governing roadmap is **C0…C10** (see `PROJECT_STATUS.md`). One focused PR per phase task, ≤ ~1,500 changed lines excl. tests/generated data (الف‌5); PR body matches `git diff --stat` + real head (الف‌4). Executor only; independent reviewer separate; no "done" without evidence (§19). Ambiguities closed via booklet 2 §14 (OD-01..OD-14), never by querying the owner. `data/` + `samples/` read-only with before/after tree-hash evidence per PR. No merge, no tag, no runtime network, no company-specific code (§16).
21
30 -## Accepted PR #18 control evidence
22 +- **C0 (this PR, IN_PROGRESS — re-scoped from B0):** الف‌1 browser-edition removal (ADR-028); الف‌2 persistent core verified main path; الف‌3 phase 0/1 + golden 1404 verified merged; الف‌4/5 PR honesty/size + generality + offline rules in AGENTS.md; الف‌6 `docs/PR_TRIAGE.md`; الف‌7 exit criteria; booklet 1+2 references + manifests. B0 deliverables (archive, status rewrite, discrepancy skeleton, ADR-025/026) retained as C0-compatible.
23 +- **C0 addendum (owner appendix revision, 2026-12-03):** Databan catalog studied by owner (marketing, unverified; no agent site access); positioning = independent pluggable product + Host Integration API; **OD-09 revised pyodbc-first** (python-tds fallback); accepted elements mapped to C4–C9/C11; rejected scope binding (government systems, bank invoices, form builder/cartable, messenger bots for financial data); ADR-029; booklet 2 re-anchored with revision history in MANIFEST.json.
24 +- **C1…C10 (+ optional C11):** NOT_IMPLEMENTED; see the phase table in `PROJECT_STATUS.md`. C10 = Shadow Run two companies + owner signature; C11 = optional AI assistant, OFF by default, never generates numbers (engine + approved CalculationRun lineage only). History rewrite / large-file migration BLOCKED absent owner directive (C9).
25
32 -- Base: `source-data-cleanup@4ab54f4a3cf666827fa1ed30c4e43259ea79f2d4`
33 -- Reviewed head: `fcbeb7387218e9ab294318ae462ed59de717fc95`
34 -- Squash merge: `f213d321ff4cd7d3d6fa65ba78dc48f090ee846b`
35 -- Exact changed files: `PROJECT_STATUS.md`, `docs/PROJECT_LOG.md`, `docs/handoff/LATEST_HANDOFF.md`, `docs/handoff/MASTER_RECOVERY_PROMPT.md`
36 -- Verification: complete remote four-file diff and metadata reviewed; append-only project-log behavior and protected-data boundary confirmed.
37 -- GitHub Actions: none on the reviewed head; documentation-only paths did not trigger Backend CI.
38 -- Artifacts/releases: `NONE`
39 -- Protected boundary: no application code, tests, workflow, migration, dependency, workbook content, financial data, binary, ZIP, EXE, artifact, or release file changed.
40 -- Acceptance authority: Davood explicitly authorized the merge after independent review.
26 +### C0 protected-data evidence
27
42 -## Accepted PR #19 control evidence
43 -
44 -- Base: `source-data-cleanup@f213d321ff4cd7d3d6fa65ba78dc48f090ee846b`
45 -- Reviewed head: `b9059592409606a0a4f11a71c30778cff158b6b6`
46 -- Squash merge: `77f9f595ccfe67a87b11024ff0f6143629dba438`
47 -- Exact changed files: `PROJECT_STATUS.md`, `docs/PROJECT_LOG.md`, `docs/handoff/LATEST_HANDOFF.md`
48 -- Verification: complete remote three-file diff, append-only log, whitespace, protected-data boundary, and post-merge accepted-head state passed.
49 -- GitHub Actions: none on the reviewed head; documentation-only paths did not trigger Backend CI.
50 -- Artifacts/releases: `NONE`
28 +- `data/` tree `2ef8a512523f62f0cf84c5009f141be2f8a9cb5f`, `samples/` tree `00aba54b1dc30485ba9b164c8036a7b4bbe9020e` — unchanged before/after (C0 removes browser edition + docs/process only).
29 +- Working branch `arena/094f314c-aram` aligned to accepted base `46253c9` via merge (no force-push). Browser edition recoverable from history @`46253c9`; `experiment/browser-edition` branch = owner action (Arena single-branch constraint, ADR-028).
30
31 ## Durable role-based operating model
32
@@ -56,55 +35,21 @@
35 - Introduced through: [PR #20](https://github.com/davoodmehraban89/Aram/pull/20)
36 - Davood is Project Owner and the accounting/product authority.
37 - ChatGPT chat is Operational Coordinator: recovery, task scoping, implementation prompts, first-pass review, and copy-ready handoffs.
59 -- Jules is the primary Implementation Agent: exact-base focused implementation, tests, Draft PR, and evidence; it never merges its own PR.
60 -- Codex Work is Senior Technical Supervisor, Independent Reviewer, and Authorized Maintainer: technical sequencing, remote evidence review, conflict resolution, exceptional critical fixes, acceptance decisions, and routine merges under standing delegation.
38 +- Implementation agent (Arena/Jules): exact-base focused implementation, tests, PR, and evidence; never merges its own PR.
39 +- Independent reviewer / authorized maintainer: technical sequencing, remote evidence review, conflict resolution, acceptance decisions, and merges under owner delegation.
40 - GitHub is the evidence source of truth.
41 - Accounting ambiguity, material scope, protected-data changes, releases, destructive actions, credentials, and new external authority remain Davood escalation points.
42 - A repository mismatch pauses only the affected task without edits; it does not halt the project.
43
65 -## Closed superseded work
66 -
67 -- PR #16 was closed without merge on 2026-08-25.
68 -- It duplicated accepted PR #15, used stale base `7c7533ee87146dc8fc78b46ebf423be55532c7eb`, was dirty, and recorded incorrect merge SHA `35d45c3f200672a6ef97f13a84cf7c823ecf1bb8`.
69 -- No file or claim from PR #16 is accepted.
70 -
71 -## Closed Gate 3 / Gate 2B reference
72 -
73 -- PR: https://github.com/davoodmehraban89/Aram/pull/17
74 -- Base: `source-data-cleanup@7c7533ee87146dc8fc78b46ebf423be55532c7eb`
75 -- Head: `4f8648add0e2ed60f01753e979fa3fbe9ccf0f18`
76 -- Final state: closed without merge on 2026-08-25; its code is not accepted.
77 -- GitHub reports 12 changed files although the PR narrative names only 9.
78 -- Backend CI run #31 succeeded with 51 tests on the stale branch head; that does not prove compatibility with accepted Gate 2A.
79 -- Use PR #17 only as reference. Do not reopen, revive, or merge it.
80 -- Comprehensive Mapping Excel import/export, carry-forward, unknown-account queue, note/sub-note mapping, management UI, reproducible Windows packaging, and end-to-end Pilot acceptance remain unimplemented.
81 -
44 ## Governance and release reality
45
46 - GitHub remote evidence outranks this record and every agent report.
47 - The accepted branch is currently unprotected; explicit review discipline is mandatory.
86 -- There are no accepted Git tags or GitHub Releases.
48 +- Tag `v1.0.0` exists on `46253c9` (owner pre-mission authorization); no further tagging without owner directive.
49 - Canonical financial XLSX/PDF and source data remain protected.
50 - Green CI on an unmerged PR is not acceptance evidence.
89 -- No Gate 3 implementation candidate is accepted or active.
90 -
91 -## Active V1-01 safety-gate candidate
92 -
93 -- Verified base: `source-data-cleanup@b1ddee87d31ee73b3a5aeac8f9953d0a604c206a`
94 -- Working branch: `codex/v1-01-safety-gate-hardening`
95 -- Draft PR: [#21](https://github.com/davoodmehraban89/Aram/pull/21)
96 -- Independently reviewed implementation head: `700d800dbd9c657f6bd510faafedcbde4847fafd`.
97 -- Earlier exact-head candidate: `aba10b61c770ce319b1b67d960a4f0a1057e25f6`; [Backend CI #36](https://github.com/davoodmehraban89/Aram/actions/runs/32989551021) succeeded.
98 -- A later documentation-triggered [Backend CI #38](https://github.com/davoodmehraban89/Aram/actions/runs/33015151139) exposed a flaky message-specific reparent assertion: protection fired correctly, but through the equally valid parent-company invariant.
99 -- Stabilized candidate: `b3dc8b3a18934ffe63f615e4f650248be21a5f9c`; the single test assertion now accepts either valid `cannot be mutated` protection message without changing product behavior.
100 -- Latest verified CI: [Backend CI #39](https://github.com/davoodmehraban89/Aram/actions/runs/33015277194), success on `b3dc8b3a18934ffe63f615e4f650248be21a5f9c`; 67 tests passed, migration upgrade/downgrade and compile succeeded.
101 -- Purpose: close the independently reproduced protected-year deletion/mutation and Pilot-preflight false-negative defects before any Mapping/UI expansion.
102 -- Planned changed files: `index.html`, `PROJECT_STATUS.md`, `backend/src/aram_backend/models.py`, `backend/src/aram_backend/pilot_workbook.py`, `backend/tests/test_models.py`, `backend/tests/test_pilot_workbook.py`, `docs/PROJECT_LOG.md`, `docs/handoff/LATEST_HANDOFF.md`.
103 -- Local evidence at preparation: 67 pytest tests passed; isolated Alembic upgrade/downgrade and compileall passed; focused Ruff and mypy checks passed.
104 -- Protected boundary: no canonical financial data, workbook, PDF, database, financial value, binary, ZIP, EXE, tag, or release is in scope.
105 -- Independent-review decision: code, scope, diff, and protected-data boundary passed. CI #38 later revealed only a nondeterministic error-message assertion; CI #39 passed after the one-line assertion stabilization.
106 -- Status: `IN_PROGRESS`; this durable-document reconciliation records the complete CI sequence. The resulting documentation-only head must be re-fetched and compared with `b3dc8b3a18934ffe63f615e4f650248be21a5f9c` before Ready/Squash Merge.
51 +- Windows EXE not built; clean-machine install log + §14 UAT signature pending (Phase 9 release checklist, owner).
52
53 ## Single next action
54
110 -Publish this requested two-document reconciliation on PR #21 and route the resulting documentation-only head back to the independent reviewer. The reviewer must confirm that only `PROJECT_STATUS.md` and `docs/handoff/LATEST_HANDOFF.md` changed after the CI-verified stabilized head `b3dc8b3a18934ffe63f615e4f650248be21a5f9c`, verify the final workflow result, then Ready/Squash Merge. Do not begin Gate 3 Mapping until V1-01 is accepted.
55 +Independent GitHub review of the C0 PR (#97, re-scoped from B0: booklet 1+2 references + browser-edition removal + PR triage + process rules). After C0 acceptance, start C1 (real vertical slice: 1404 → LedgerBalance → C-01/C-02 → mapping → BS/IS → official reconciliation) from the new accepted head, recording evidence in `PROJECT_STATUS.md`. Do not merge or tag; do not begin C1 before C0 acceptance.
docs/index.html deleted
-139
@@ -1,139 +0,0 @@
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, viewport-fit=cover">
6 - <meta name="theme-color" content="#0a1220">
7 - <meta name="mobile-web-app-capable" content="yes">
8 - <meta name="apple-mobile-web-app-capable" content="yes">
9 - <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
10 - <title>آرام — میز کار پایلوت</title>
11 - <link rel="stylesheet" href="styles.css">
12 - <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>">
13 -</head>
14 -<body>
15 - <!-- Engine loading overlay -->
16 - <div id="boot" class="boot">
17 - <div class="boot-card">
18 - <div class="boot-mark">آ</div>
19 - <h2>آرام — میز کار پایلوت</h2>
20 - <p id="boot-status">در حال بارگذاری موتور محاسباتی…</p>
21 - <div class="boot-bar"><div id="boot-progress" class="boot-progress"></div></div>
22 - <p class="muted">نسخهٔ مرورگری — همان موتور تست‌شده، بدون نیاز به سرور. بار اول چند ثانیه طول می‌کشد.</p>
23 - <p id="boot-error" class="boot-error hidden"></p>
24 - </div>
25 - </div>
26 -
27 - <header class="topbar">
28 - <div class="brand">
29 - <span class="brand-mark">آ</span>
30 - <div class="brand-text">
31 - <h1>آرام — میز کار پایلوت</h1>
32 - <p class="tagline">از اکسل منبع تا پیش‌نویس صورت‌های مالی، با ردیابی کامل</p>
33 - </div>
34 - </div>
35 - <div class="topbar-actions">
36 - <label class="actor-field" title="نام شما در ردّ ممیزی ثبت می‌شود">
37 - <span class="actor-label">نام کاربر:</span>
38 - <input id="actor-input" type="text" placeholder="نام بازبین" autocomplete="name">
39 - </label>
40 - <button id="new-session-btn" class="btn ghost small hidden">جلسهٔ جدید</button>
41 - </div>
42 - </header>
43 -
44 - <main id="main">
45 - <section id="view-landing">
46 - <div class="hero">
47 - <h2>صورت‌های مالیِ قابل‌ردیابی، برای هر شرکت</h2>
48 - <p>
49 - فایل پایلوت (قرارداد v0.1) را وارد کنید یا دمو را اجرا کنید؛ حساب‌ها و یادداشت‌ها را
50 - آزادانه اضافه، ویرایش یا جایگزین کنید، نگاشت را تعیین کنید و ترازنامه و سود و زیان را
51 - با کنترل‌های تراز و معادلهٔ حسابداری بسازید — هر رقم تا سطر منبع قابل ردیابی است.
52 - </p>
53 - <p class="safety-note">
54 - هیچ مبلغی حدس زده نمی‌شود · دادهٔ منبع تغییر نمی‌کند · خروجی «پیش‌نویس کاری» است، نه صورت مالی رسمی
55 - </p>
56 - </div>
57 -
58 - <div class="action-cards">
59 - <div class="card action-card">
60 - <div class="action-icon">📥</div>
61 - <h3>ورود فایل پایلوت</h3>
62 - <p>فایل <span class="mono">.xlsx</span> مطابق قالب v0.1 (حداکثر ۲۵ مگابایت)</p>
63 - <input id="file-input" type="file" accept=".xlsx" class="hidden">
64 - <button id="upload-btn" class="btn primary" disabled>انتخاب و بررسی فایل</button>
65 - </div>
66 - <div class="card action-card">
67 - <div class="action-icon">🧪</div>
68 - <h3>دموی ساختگی</h3>
69 - <p>دادهٔ غیرواقعی و تراز، با دو حساب نگاشت‌نشده برای تجربهٔ گردش کار کامل</p>
70 - <button id="demo-btn" class="btn accent" disabled>اجرای دمو</button>
71 - </div>
72 - </div>
73 -
74 - <div id="upload-progress" class="card progress-card hidden">
75 - <span class="spinner"></span> در حال پیش‌بررسی فایل…
76 - </div>
77 -
78 - <div id="issues-panel" class="card issues-card hidden">
79 - <h3>❌ فایل رد شد — خطاهای پیش‌بررسی</h3>
80 - <p id="issues-message"></p>
81 - <div class="table-wrap">
82 - <table id="issues-table">
83 - <thead><tr><th>برگه</th><th>سطر</th><th>فیلد</th><th>کد خطا</th><th>شرح</th></tr></thead>
84 - <tbody></tbody>
85 - </table>
86 - </div>
87 - </div>
88 -
89 - <div class="card info-card">
90 - <h3>سیاست صریح علامت‌ها (بدون حدس)</h3>
91 - <div class="policy-grid" id="policy-grid"></div>
92 - <p class="muted">
93 - مانده‌ها بدهکار-مثبت هستند؛ نمایش = علامت × مانده. بخش‌های ناشناخته به‌جای حدس، به صف استثنا می‌روند.
94 - مقصدهای CF و EQ در این نسخه رندر نمی‌شوند و شفاف گزارش می‌شوند.
95 - </p>
96 - </div>
97 - </section>
98 -
99 - <section id="view-workspace" class="hidden">
100 - <div class="session-bar card">
101 - <div id="session-info"></div>
102 - <div id="status-chip"></div>
103 - </div>
104 - <div id="tab-dashboard" class="tab-panel"></div>
105 - <div id="tab-accounts" class="tab-panel hidden"></div>
106 - <div id="tab-notes" class="tab-panel hidden"></div>
107 - <div id="tab-statements" class="tab-panel hidden"></div>
108 - <div id="tab-more" class="tab-panel hidden"></div>
109 - </section>
110 - </main>
111 -
112 - <nav class="tabbar hidden" id="tabbar" aria-label="ناوبری بخش‌ها">
113 - <button data-tab="dashboard" class="tab active"><span class="tab-ico">🏠</span><span>داشبورد</span></button>
114 - <button data-tab="accounts" class="tab"><span class="tab-ico">📒</span><span>حساب‌ها</span><span id="mapping-badge" class="badge"></span></button>
115 - <button data-tab="notes" class="tab"><span class="tab-ico">🗂️</span><span>یادداشت‌ها</span></button>
116 - <button data-tab="statements" class="tab"><span class="tab-ico">📑</span><span>صورت‌ها</span></button>
117 - <button data-tab="more" class="tab"><span class="tab-ico">⚙️</span><span>بیشتر</span></button>
118 - </nav>
119 -
120 - <div id="sheet-backdrop" class="sheet-backdrop hidden"></div>
121 - <div id="sheet" class="sheet hidden" role="dialog" aria-modal="true">
122 - <div class="sheet-handle"></div>
123 - <div class="sheet-head">
124 - <h3 id="sheet-title"></h3>
125 - <button id="sheet-close" class="sheet-close" aria-label="بستن">✕</button>
126 - </div>
127 - <div id="sheet-body" class="sheet-body"></div>
128 - </div>
129 -
130 - <div id="toast" class="toast hidden"></div>
131 -
132 - <footer class="footer">
133 - Aram Pilot Workbench · نسخهٔ مرورگری · موتور <span id="engine-version"></span> ·
134 - خروجی پیش‌نویس کاری است؛ برای گزارشگری رسمی استفاده نکنید.
135 - </footer>
136 -
137 - <script src="app.js"></script>
138 -</body>
139 -</html>
docs/py/aram_backend/__init__.py deleted
-4
@@ -1,4 +0,0 @@
1 -"""Aram backend package."""
2 -
3 -__version__ = "0.1.0"
4 -
docs/py/aram_backend/pilot_demo.py deleted
-161
@@ -1,161 +0,0 @@
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()
docs/py/aram_backend/pilot_editing.py deleted
-190
@@ -1,190 +0,0 @@
1 -"""Domain rules for editing the Pilot working state.
2 -
3 -Pure validators/constructors that raise typed errors. The session store calls
4 -these under its lock and records every change in the audit trail. Nothing here
5 -guesses a financial value: a manually added account's closing balance is
6 -derived from the accounting identity opening + debit - credit, and any edit
7 -that would break referential integrity is rejected.
8 -"""
9 -
10 -from __future__ import annotations
11 -
12 -from decimal import Decimal, InvalidOperation
13 -
14 -from aram_backend.pilot_engine import (
15 - DEFERRED_STATEMENTS,
16 - RENDERED_STATEMENTS,
17 - NoteTarget,
18 - PilotAccount,
19 - PilotCompany,
20 -)
21 -
22 -STATEMENTS = frozenset(RENDERED_STATEMENTS) | frozenset(DEFERRED_STATEMENTS)
23 -APPROVAL_STATUSES = frozenset({"Draft", "Reviewed", "Approved"})
24 -ROW_STATUSES = frozenset({"Draft", "Reviewed", "Approved"})
25 -COMPANY_STATUSES = frozenset({"Draft", "Approved", "Locked"})
26 -
27 -# Workbench-added accounts use a reserved synthetic source-row range so they
28 -# are never confused with real general-ledger source rows.
29 -SYNTHETIC_SOURCE_ROW_BASE = 900_000
30 -
31 -
32 -class EditingError(ValueError):
33 - """Base class for rejected edits; message is safe to show to the user."""
34 -
35 -
36 -class DuplicateAccountError(EditingError):
37 - pass
38 -
39 -
40 -class DuplicateNoteError(EditingError):
41 - pass
42 -
43 -
44 -class InvalidAccountError(EditingError):
45 - pass
46 -
47 -
48 -class InvalidNoteError(EditingError):
49 - pass
50 -
51 -
52 -class InvalidCompanyError(EditingError):
53 - pass
54 -
55 -
56 -class UnknownNoteError(EditingError):
57 - pass
58 -
59 -
60 -class NoteInUseError(EditingError):
61 - pass
62 -
63 -
64 -def _clean_code(value: str) -> str:
65 - code = (value or "").strip()
66 - if not code:
67 - raise InvalidAccountError("کد نمی‌تواند خالی باشد.")
68 - if code.startswith("="):
69 - raise InvalidAccountError("کد باید متن ساده باشد؛ فرمول ممنوع است.")
70 - return code
71 -
72 -
73 -def _clean_text(value: str, field_fa: str) -> str:
74 - text = (value or "").strip()
75 - if not text:
76 - raise InvalidAccountError(f"{field_fa} نمی‌تواند خالی باشد.")
77 - return text
78 -
79 -
80 -def parse_decimal(value, field_fa: str) -> Decimal:
81 - if isinstance(value, bool):
82 - raise InvalidAccountError(f"{field_fa} باید عدد باشد.")
83 - try:
84 - parsed = Decimal(str(value).strip())
85 - except (InvalidOperation, ValueError, AttributeError) as exc:
86 - raise InvalidAccountError(f"{field_fa} یک عدد معتبر نیست.") from exc
87 - if not parsed.is_finite():
88 - raise InvalidAccountError(f"{field_fa} نمی‌تواند NaN یا بی‌نهایت باشد.")
89 - return parsed
90 -
91 -
92 -def make_account(
93 - *,
94 - full_code: str,
95 - name: str,
96 - general_code: str,
97 - general_name: str,
98 - opening,
99 - debit,
100 - credit,
101 - source_row: int,
102 - row_status: str = "Draft",
103 - subsidiary_code: str = "",
104 - subsidiary_name: str = "",
105 -) -> PilotAccount:
106 - """Build a validated account. Closing is derived, never invented."""
107 - code = _clean_code(full_code)
108 - account_name = _clean_text(name, "نام حساب")
109 - gen_code = _clean_code(general_code)
110 - gen_name = _clean_text(general_name, "نام حساب کل")
111 - if row_status not in ROW_STATUSES:
112 - raise InvalidAccountError("وضعیت سطر باید Draft، Reviewed یا Approved باشد.")
113 - if not isinstance(source_row, int) or isinstance(source_row, bool) or source_row <= 0:
114 - raise InvalidAccountError("سطر منبع باید یک عدد صحیح مثبت باشد.")
115 - opening_d = parse_decimal(opening, "مانده ابتدای دوره")
116 - debit_d = parse_decimal(debit, "گردش بدهکار")
117 - credit_d = parse_decimal(credit, "گردش بستانکار")
118 - closing_d = opening_d + debit_d - credit_d
119 - return PilotAccount(
120 - full_code=code,
121 - name=account_name,
122 - general_code=gen_code,
123 - general_name=gen_name,
124 - opening=opening_d,
125 - debit=debit_d,
126 - credit=credit_d,
127 - closing=closing_d,
128 - source_row=source_row,
129 - row_status=row_status,
130 - subsidiary_code=(subsidiary_code or "").strip(),
131 - subsidiary_name=(subsidiary_name or "").strip(),
132 - )
133 -
134 -
135 -def make_note(
136 - *,
137 - statement: str,
138 - section: str,
139 - note_number: str,
140 - note_title: str,
141 - subnote_code: str = "",
142 - subnote_title: str = "",
143 -) -> NoteTarget:
144 - statement = (statement or "").strip()
145 - if statement not in STATEMENTS:
146 - raise InvalidNoteError("صورت مالی باید BS، IS، CF یا EQ باشد.")
147 - section = (section or "").strip()
148 - if not section:
149 - raise InvalidNoteError("بخش صورت مالی نمی‌تواند خالی باشد.")
150 - number = _clean_code(note_number)
151 - title = _clean_text(note_title, "عنوان یادداشت")
152 - sub_code = (subnote_code or "").strip()
153 - sub_title = (subnote_title or "").strip()
154 - if sub_code and not sub_title:
155 - raise InvalidNoteError("زیریادداشت دارای کد باید عنوان هم داشته باشد.")
156 - return NoteTarget(
157 - statement=statement,
158 - section=section,
159 - note_number=number,
160 - note_title=title,
161 - subnote_code=sub_code,
162 - subnote_title=sub_title,
163 - )
164 -
165 -
166 -def make_company(
167 - *,
168 - code: str,
169 - name: str,
170 - fiscal_year,
171 - currency: str = "",
172 - unit: str = "",
173 - prepared_by: str = "",
174 - status: str = "Draft",
175 -) -> PilotCompany:
176 - clean_code = _clean_code(code)
177 - clean_name = _clean_text(name, "نام شرکت")
178 - if isinstance(fiscal_year, bool) or not isinstance(fiscal_year, int) or fiscal_year <= 0:
179 - raise InvalidCompanyError("سال مالی باید یک عدد صحیح مثبت باشد.")
180 - if status not in COMPANY_STATUSES:
181 - raise InvalidCompanyError("وضعیت شرکت باید Draft، Approved یا Locked باشد.")
182 - return PilotCompany(
183 - code=clean_code,
184 - name=clean_name,
185 - fiscal_year=fiscal_year,
186 - currency=(currency or "").strip(),
187 - unit=(unit or "").strip(),
188 - prepared_by=(prepared_by or "").strip(),
189 - status=status,
190 - )
docs/py/aram_backend/pilot_engine.py deleted
-762
@@ -1,762 +0,0 @@
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.1.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 - subsidiary_code: str = ""
92 - subsidiary_name: str = ""
93 - detail1_code: str = ""
94 - detail1_name: str = ""
95 - detail2_code: str = ""
96 - detail2_name: str = ""
97 - detail3_code: str = ""
98 - detail3_name: str = ""
99 - detail4_code: str = ""
100 - detail4_name: str = ""
101 -
102 -
103 -@dataclass(frozen=True)
104 -class NoteTarget:
105 - statement: str
106 - section: str
107 - note_number: str
108 - note_title: str
109 - subnote_code: str
110 - subnote_title: str
111 -
112 - @property
113 - def key(self) -> tuple[str, str, str, str]:
114 - return (self.statement, self.section, self.note_number, self.subnote_code)
115 -
116 -
117 -@dataclass(frozen=True)
118 -class MappingEntry:
119 - account_code: str
120 - statement: str
121 - section: str
122 - note_number: str
123 - subnote_code: str
124 - approval_status: str
125 - reviewer: str
126 - source: str
127 - mapping_id: str
128 -
129 - @property
130 - def target_key(self) -> tuple[str, str, str, str]:
131 - return (self.statement, self.section, self.note_number, self.subnote_code)
132 -
133 -
134 -@dataclass(frozen=True)
135 -class PilotModel:
136 - company: PilotCompany
137 - accounts: dict[str, PilotAccount]
138 - notes: dict[tuple[str, str, str, str], NoteTarget]
139 - mappings: dict[str, MappingEntry]
140 - conflicts: dict[str, tuple[MappingEntry, ...]]
141 - source_sha256: str
142 -
143 -
144 -@dataclass
145 -class WorkingModel:
146 - """Mutable, in-session edit state. Same shape as PilotModel so every
147 - report/table/export function accepts it unchanged. Individual records
148 - remain frozen dataclasses; edits replace records, never mutate them."""
149 -
150 - company: PilotCompany
151 - accounts: dict[str, PilotAccount]
152 - notes: dict[tuple[str, str, str, str], NoteTarget]
153 - mappings: dict[str, MappingEntry]
154 - conflicts: dict[str, tuple[MappingEntry, ...]]
155 - source_sha256: str
156 -
157 - @classmethod
158 - def from_model(cls, model: PilotModel) -> "WorkingModel":
159 - return cls(
160 - company=model.company,
161 - accounts=dict(model.accounts),
162 - notes=dict(model.notes),
163 - mappings=dict(model.mappings),
164 - conflicts=dict(model.conflicts),
165 - source_sha256=model.source_sha256,
166 - )
167 -
168 - def copy(self) -> "WorkingModel":
169 - return WorkingModel(
170 - company=self.company,
171 - accounts=dict(self.accounts),
172 - notes=dict(self.notes),
173 - mappings=dict(self.mappings),
174 - conflicts=dict(self.conflicts),
175 - source_sha256=self.source_sha256,
176 - )
177 -
178 -
179 -_HIERARCHY_CODE_FIELDS = (
180 - "general_code", "subsidiary_code", "detail1_code",
181 - "detail2_code", "detail3_code", "detail4_code",
182 -)
183 -_LEVEL_NAMES = ("General", "Subsidiary", "Detail1", "Detail2", "Detail3", "Detail4")
184 -
185 -
186 -def hierarchy_codes(account: PilotAccount) -> tuple[str, ...]:
187 - return tuple(getattr(account, field) for field in _HIERARCHY_CODE_FIELDS)
188 -
189 -
190 -def account_level_of(account: PilotAccount) -> str:
191 - """Deepest populated hierarchy level; General is always present."""
192 - codes = hierarchy_codes(account)
193 - depth = 1
194 - for index in range(1, len(codes)):
195 - if codes[index]:
196 - depth = index + 1
197 - return _LEVEL_NAMES[depth - 1]
198 -
199 -
200 -def _rows(sheet: Any, headers: tuple[str, ...]) -> list[dict[str, Any]]:
201 - result = []
202 - for values in sheet.iter_rows(min_row=2, values_only=True):
203 - row = dict(zip(headers, values))
204 - if any(v is not None and not (isinstance(v, str) and not v.strip()) for v in row.values()):
205 - result.append(row)
206 - return result
207 -
208 -
209 -def _text(value: Any) -> str:
210 - return value.strip() if isinstance(value, str) else ""
211 -
212 -
213 -def _decimal(value: Any) -> Decimal:
214 - return Decimal(str(value).strip())
215 -
216 -
217 -def parse_pilot_model(workbook_bytes: bytes) -> PilotModel:
218 - """Parse a preflight-valid workbook into a typed, immutable model."""
219 - preflight = preflight_pilot_workbook(workbook_bytes)
220 - if not preflight.valid:
221 - raise PilotModelError(list(preflight.issues))
222 -
223 - workbook = load_workbook(BytesIO(workbook_bytes), read_only=True, data_only=True)
224 - parsed = {
225 - name: _rows(workbook[name], headers) for name, headers in SHEET_HEADERS.items()
226 - }
227 - workbook.close()
228 -
229 - company_rows = parsed["Company"]
230 - if len(company_rows) != 1:
231 - raise PilotModelError([PilotIssue(
232 - "ERROR", "WORKBENCH_SINGLE_COMPANY_REQUIRED", "Company", 0, "__sheet__",
233 - "The workbench renders exactly one company/fiscal year per workbook; "
234 - f"found {len(company_rows)} company rows.",
235 - )])
236 - crow = company_rows[0]
237 - company = PilotCompany(
238 - code=_text(crow["company_code"]),
239 - name=_text(crow["company_name"]),
240 - fiscal_year=int(crow["fiscal_year"]),
241 - currency=_text(crow["currency"]),
242 - unit=_text(crow["unit"]),
243 - prepared_by=_text(crow["prepared_by"]),
244 - status=_text(crow["status"]),
245 - )
246 -
247 - accounts: dict[str, PilotAccount] = {}
248 - for row in parsed["Accounts"]:
249 - account = PilotAccount(
250 - full_code=_text(row["account_full_code"]),
251 - name=_text(row["account_name"]),
252 - general_code=_text(row["general_code"]),
253 - general_name=_text(row["general_name"]),
254 - opening=_decimal(row["opening"]),
255 - debit=_decimal(row["debit"]),
256 - credit=_decimal(row["credit"]),
257 - closing=_decimal(row["closing"]),
258 - source_row=int(row["source_row"]),
259 - row_status=_text(row["row_status"]),
260 - subsidiary_code=_text(row["subsidiary_code"]),
261 - subsidiary_name=_text(row["subsidiary_name"]),
262 - detail1_code=_text(row["detail1_code"]),
263 - detail1_name=_text(row["detail1_name"]),
264 - detail2_code=_text(row["detail2_code"]),
265 - detail2_name=_text(row["detail2_name"]),
266 - detail3_code=_text(row["detail3_code"]),
267 - detail3_name=_text(row["detail3_name"]),
268 - detail4_code=_text(row["detail4_code"]),
269 - detail4_name=_text(row["detail4_name"]),
270 - )
271 - accounts[account.full_code] = account
272 - accounts = dict(sorted(accounts.items()))
273 -
274 - notes: dict[tuple[str, str, str, str], NoteTarget] = {}
275 - for row in parsed["Notes"]:
276 - note = NoteTarget(
277 - statement=_text(row["statement"]),
278 - section=_text(row["statement_section"]),
279 - note_number=_text(row["note_number"]),
280 - note_title=_text(row["note_title"]),
281 - subnote_code=_text(row["subnote_code"]),
282 - subnote_title=_text(row["subnote_title"]),
283 - )
284 - notes[note.key] = note
285 -
286 - mappings: dict[str, MappingEntry] = {}
287 - conflicts: dict[str, tuple[MappingEntry, ...]] = {}
288 - for row in parsed["Mapping"]:
289 - entry = MappingEntry(
290 - account_code=_text(row["account_full_code"]),
291 - statement=_text(row["target_statement"]),
292 - section=_text(row["statement_section"]),
293 - note_number=_text(row["note_number"]),
294 - subnote_code=_text(row["subnote_code"]),
295 - approval_status=_text(row["approval_status"]),
296 - reviewer=_text(row["reviewer"]),
297 - source=_text(row["source"]),
298 - mapping_id=_text(row["mapping_id"]),
299 - )
300 - existing = mappings.get(entry.account_code)
301 - if entry.account_code in conflicts:
302 - conflicts[entry.account_code] += (entry,)
303 - elif existing is None:
304 - mappings[entry.account_code] = entry
305 - elif existing.target_key != entry.target_key:
306 - conflicts[entry.account_code] = (existing, entry)
307 - del mappings[entry.account_code]
308 - # Identical duplicate targets are deduplicated deterministically.
309 -
310 - return PilotModel(
311 - company=company,
312 - accounts=accounts,
313 - notes=notes,
314 - mappings=mappings,
315 - conflicts=conflicts,
316 - source_sha256=hashlib.sha256(workbook_bytes).hexdigest(),
317 - )
318 -
319 -
320 -def _amount(value: Decimal) -> str:
321 - """Exact decimal as string; JSON never loses precision through floats."""
322 - return format(value, "f")
323 -
324 -
325 -def _account_json(account: PilotAccount, mapping: MappingEntry | None, sign: int | None) -> dict:
326 - payload = {
327 - "code": account.full_code,
328 - "name": account.name,
329 - "closing": _amount(account.closing),
330 - "source_row": account.source_row,
331 - "row_status": account.row_status,
332 - }
333 - if sign is not None:
334 - payload["display"] = _amount(sign * account.closing)
335 - if mapping is not None:
336 - payload["approval_status"] = mapping.approval_status
337 - return payload
338 -
339 -
340 -def build_report(model: PilotModel, mappings: dict[str, MappingEntry]) -> dict:
341 - """Compute coverage, exceptions, checks and BS/IS drafts deterministically."""
342 - exceptions: list[dict] = []
343 - buckets: dict[tuple[str, str, str, str], list[tuple[PilotAccount, MappingEntry]]] = {}
344 - mapped_count = 0
345 -
346 - for code, account in model.accounts.items():
347 - resolved = mappings.get(code)
348 - if code in model.conflicts and not (resolved and resolved.source == "workbench"):
349 - exceptions.append({
350 - "code": "MAPPING_CONFLICT",
351 - "account_code": code,
352 - "account_name": account.name,
353 - "closing": _amount(account.closing),
354 - "source_row": account.source_row,
355 - "details": "چند نگاشت با مقصدهای متفاوت برای این حساب وجود دارد؛ "
356 - "تا رفع تعارض، حساب در صورت‌ها منظور نمی‌شود.",
357 - })
358 - continue
359 - mapping = mappings.get(code)
360 - if mapping is None:
361 - exceptions.append({
362 - "code": "UNMAPPED_ACCOUNT",
363 - "account_code": code,
364 - "account_name": account.name,
365 - "closing": _amount(account.closing),
366 - "source_row": account.source_row,
367 - "details": "حساب نگاشت نشده است؛ مقصد آن را در زبانهٔ نگاشت تعیین کنید.",
368 - })
369 - continue
370 - mapped_count += 1
371 - if mapping.statement in DEFERRED_STATEMENTS:
372 - exceptions.append({
373 - "code": "DEFERRED_STATEMENT",
374 - "account_code": code,
375 - "account_name": account.name,
376 - "closing": _amount(account.closing),
377 - "source_row": account.source_row,
378 - "details": f"مقصد {mapping.statement} در این نسخه رندر نمی‌شود؛ "
379 - "موتور جریان نقدی/تغییرات حقوق مالکانه در گام بعدی است.",
380 - })
381 - continue
382 - policy = SECTION_POLICY.get(mapping.statement, {})
383 - if mapping.section not in policy:
384 - exceptions.append({
385 - "code": "UNSUPPORTED_SECTION",
386 - "account_code": code,
387 - "account_name": account.name,
388 - "closing": _amount(account.closing),
389 - "source_row": account.source_row,
390 - "details": f"بخش «{mapping.section}» در سیاست علامت صریح تعریف نشده است؛ "
391 - "حدس زدن ممنوع است.",
392 - })
393 - continue
394 - buckets.setdefault(mapping.target_key, []).append((account, mapping))
395 -
396 - statements: dict[str, dict] = {}
397 - section_totals: dict[tuple[str, str], Decimal] = {}
398 - for statement in RENDERED_STATEMENTS:
399 - sections = []
400 - for section, sign in SECTION_POLICY[statement].items():
401 - lines = []
402 - for key in sorted(k for k in buckets if k[0] == statement and k[1] == section):
403 - members = buckets[key]
404 - note = model.notes.get(key)
405 - line_total = sum((sign * a.closing for a, _ in members), _ZERO)
406 - lines.append({
407 - "note_number": key[2],
408 - "note_title": note.note_title if note else "",
409 - "subnote_code": key[3],
410 - "subnote_title": note.subnote_title if note else "",
411 - "total": _amount(line_total),
412 - "accounts": [
413 - _account_json(a, m, sign)
414 - for a, m in sorted(members, key=lambda item: item[0].full_code)
415 - ],
416 - })
417 - total = sum((Decimal(line["total"]) for line in lines), _ZERO)
418 - section_totals[(statement, section)] = total
419 - sections.append({
420 - "name": section,
421 - "label_fa": SECTION_LABELS_FA.get(section, section),
422 - "total": _amount(total),
423 - "lines": lines,
424 - })
425 - statements[statement] = {"label_fa": STATEMENT_LABELS_FA[statement], "sections": sections}
426 -
427 - assets = section_totals[("BS", "Assets")]
428 - liabilities = section_totals[("BS", "Liabilities")]
429 - equity = section_totals[("BS", "Equity")]
430 - revenue = section_totals[("IS", "Revenue")]
431 - expenses = section_totals[("IS", "Expenses")]
432 - profit = revenue - expenses
433 - trial_balance_sum = sum((a.closing for a in model.accounts.values()), _ZERO)
434 - equation_residual = assets - liabilities - equity - profit
435 - all_approved = bool(mappings) and all(
436 - m.approval_status == "Approved" for m in mappings.values()
437 - )
438 -
439 - checks = [
440 - {
441 - "code": "NON_EMPTY_ACCOUNTS",
442 - "name_fa": "وجود حساب‌های منبع",
443 - "passed": bool(model.accounts),
444 - "amount": None,
445 - "details": f"{len(model.accounts)} حساب در فایل ورودی ثبت شده است.",
446 - },
447 - {
448 - "code": "TRIAL_BALANCE_CLOSED",
449 - "name_fa": "تراز بودن مانده‌های دفتر کل",
450 - "passed": trial_balance_sum == _ZERO,
451 - "amount": _amount(trial_balance_sum),
452 - "details": "جمع مانده‌های پایان دوره (بدهکار مثبت) باید صفر باشد.",
453 - },
454 - {
455 - "code": "FULL_COVERAGE",
456 - "name_fa": "پوشش کامل نگاشت",
457 - "passed": not exceptions,
458 - "amount": None,
459 - "details": f"{len(exceptions)} استثنا باقی مانده است." if exceptions
460 - else "همهٔ حساب‌ها نگاشت معتبر دارند.",
461 - },
462 - {
463 - "code": "ACCOUNTING_EQUATION",
464 - "name_fa": "معادلهٔ حسابداری",
465 - "passed": equation_residual == _ZERO,
466 - "amount": _amount(equation_residual),
467 - "details": "دارایی‌ها − بدهی‌ها − حقوق مالکانه − سود دوره باید صفر باشد.",
468 - },
469 - {
470 - "code": "MAPPINGS_APPROVED",
471 - "name_fa": "تأیید همهٔ نگاشت‌ها",
472 - "passed": all_approved,
473 - "amount": None,
474 - "details": "همهٔ نگاشت‌های مؤثر وضعیت Approved دارند." if all_approved
475 - else "برخی نگاشت‌ها هنوز Approved نیستند؛ خروجی پیش‌نویس می‌ماند.",
476 - },
477 - ]
478 - complete = all(c["passed"] for c in checks if c["code"] != "MAPPINGS_APPROVED")
479 - label = (
480 - "COMPLETE_APPROVED" if complete and all_approved
481 - else "COMPLETE_DRAFT" if complete
482 - else "INCOMPLETE"
483 - )
484 -
485 - return {
486 - "engine_version": ENGINE_VERSION,
487 - "company": {
488 - "code": model.company.code,
489 - "name": model.company.name,
490 - "fiscal_year": model.company.fiscal_year,
491 - "currency": model.company.currency,
492 - "unit": model.company.unit,
493 - "prepared_by": model.company.prepared_by,
494 - "status": model.company.status,
495 - },
496 - "source_sha256": model.source_sha256,
497 - "status": {"label": label, "complete": complete, "all_mappings_approved": all_approved},
498 - "coverage": {
499 - "total_accounts": len(model.accounts),
500 - "mapped_accounts": mapped_count,
501 - "exception_count": len(exceptions),
502 - },
503 - "totals": {
504 - "assets": _amount(assets),
505 - "liabilities": _amount(liabilities),
506 - "equity": _amount(equity),
507 - "liabilities_and_equity": _amount(liabilities + equity),
508 - "revenue": _amount(revenue),
509 - "expenses": _amount(expenses),
510 - "profit": _amount(profit),
511 - },
512 - "checks": checks,
513 - "statements": statements,
514 - "exceptions": exceptions,
515 - }
516 -
517 -
518 -def accounts_table(model: PilotModel, mappings: dict[str, MappingEntry]) -> list[dict]:
519 - rows = []
520 - for code, account in model.accounts.items():
521 - mapping = mappings.get(code)
522 - rows.append({
523 - **_account_json(account, mapping, None),
524 - "general_code": account.general_code,
525 - "general_name": account.general_name,
526 - "conflict": code in model.conflicts
527 - and not (mapping and mapping.source == "workbench"),
528 - "mapping": None if mapping is None else {
529 - "statement": mapping.statement,
530 - "section": mapping.section,
531 - "note_number": mapping.note_number,
532 - "subnote_code": mapping.subnote_code,
533 - "approval_status": mapping.approval_status,
534 - "reviewer": mapping.reviewer,
535 - "source": mapping.source,
536 - "mapping_id": mapping.mapping_id,
537 - },
538 - })
539 - return rows
540 -
541 -
542 -def notes_table(model: PilotModel) -> list[dict]:
543 - return [
544 - {
545 - "statement": note.statement,
546 - "section": note.section,
547 - "note_number": note.note_number,
548 - "note_title": note.note_title,
549 - "subnote_code": note.subnote_code,
550 - "subnote_title": note.subnote_title,
551 - }
552 - for note in sorted(model.notes.values(), key=lambda n: n.key)
553 - ]
554 -
555 -
556 -def export_report_workbook(
557 - model: PilotModel,
558 - mappings: dict[str, MappingEntry],
559 - report: dict,
560 - audit_trail: list[dict],
561 - source_label: str,
562 -) -> bytes:
563 - """Render the reviewable Excel output. Values are derived, never invented."""
564 - workbook = Workbook()
565 - workbook.remove(workbook.active)
566 - header_font = Font(bold=True, color="FFFFFF")
567 - header_fill = PatternFill("solid", fgColor="1F4E78")
568 - title_font = Font(bold=True, size=13)
569 -
570 - def sheet(name: str, headers: tuple[str, ...]) -> Any:
571 - ws = workbook.create_sheet(name)
572 - ws.append(headers)
573 - for cell in ws[1]:
574 - cell.font = header_font
575 - cell.fill = header_fill
576 - ws.freeze_panes = "A2"
577 - ws.sheet_view.rightToLeft = True
578 - for column in range(1, len(headers) + 1):
579 - ws.column_dimensions[ws.cell(1, column).column_letter].width = 22
580 - return ws
581 -
582 - info = sheet("Info", ("field", "value"))
583 - company = report["company"]
584 - for field_name, value in (
585 - ("company_code", company["code"]),
586 - ("company_name", company["name"]),
587 - ("fiscal_year", company["fiscal_year"]),
588 - ("unit", company["unit"]),
589 - ("source", source_label),
590 - ("source_sha256", report["source_sha256"]),
591 - ("engine_version", ENGINE_VERSION),
592 - ("generated_at_utc", datetime.now(UTC).isoformat(timespec="seconds")),
593 - ("status", report["status"]["label"]),
594 - ("disclaimer", "خروجی پیش‌نویس کاری برای بررسی است؛ صورت مالی رسمی نیست. "
595 - "هیچ مبلغی حدس زده یا جایگزین نشده است."),
596 - ):
597 - info.append((field_name, value))
598 - if source_label == "demo":
599 - info.append(("synthetic_data", "TRUE — داده‌های دمو کاملاً ساختگی و غیرواقعی هستند."))
600 - info.column_dimensions["B"].width = 80
601 -
602 - checks = sheet("Checks", ("check_code", "name_fa", "passed", "amount", "details"))
603 - for check in report["checks"]:
604 - checks.append((
605 - check["code"], check["name_fa"], "PASS" if check["passed"] else "FAIL",
606 - float(check["amount"]) if check["amount"] is not None else None,
607 - check["details"],
608 - ))
609 -
610 - for statement in RENDERED_STATEMENTS:
611 - data = report["statements"][statement]
612 - ws = sheet(
613 - "BalanceSheet" if statement == "BS" else "IncomeStatement",
614 - ("level", "section", "note", "title", "amount", "account_code", "source_row"),
615 - )
616 - ws.append(("title", "", "", f"{data['label_fa']} — {company['name']} — {company['fiscal_year']}", None, "", None))
617 - ws.cell(ws.max_row, 4).font = title_font
618 - for section in data["sections"]:
619 - ws.append(("section", section["name"], "", section["label_fa"], float(section["total"]), "", None))
620 - ws.cell(ws.max_row, 5).font = Font(bold=True)
621 - for line in section["lines"]:
622 - title = line["note_title"]
623 - if line["subnote_code"]:
624 - title += f" / {line['subnote_code']} {line['subnote_title']}".rstrip()
625 - ws.append(("note", section["name"], line["note_number"], title, float(line["total"]), "", None))
626 - for account in line["accounts"]:
627 - ws.append((
628 - "account", section["name"], line["note_number"], account["name"],
629 - float(account["display"]), account["code"], account["source_row"],
630 - ))
631 - ws.cell(ws.max_row, 4).alignment = Alignment(indent=1)
632 - if statement == "IS":
633 - ws.append(("total", "", "", "سود (زیان) دوره", float(report["totals"]["profit"]), "", None))
634 - ws.cell(ws.max_row, 5).font = Font(bold=True)
635 - ws.column_dimensions["D"].width = 48
636 -
637 - coverage = sheet("Coverage", (
638 - "account_code", "account_name", "closing", "source_row", "statement",
639 - "section", "note_number", "subnote_code", "approval_status", "mapping_source",
640 - ))
641 - for row in accounts_table(model, mappings):
642 - mapping = row["mapping"] or {}
643 - coverage.append((
644 - row["code"], row["name"], float(row["closing"]), row["source_row"],
645 - mapping.get("statement"), mapping.get("section"), mapping.get("note_number"),
646 - mapping.get("subnote_code"), mapping.get("approval_status"), mapping.get("source"),
647 - ))
648 -
649 - exceptions = sheet("Exceptions", ("code", "account_code", "account_name", "closing", "source_row", "details"))
650 - for item in report["exceptions"]:
651 - exceptions.append((
652 - item["code"], item["account_code"], item["account_name"],
653 - float(item["closing"]), item["source_row"], item["details"],
654 - ))
655 - exceptions.column_dimensions["F"].width = 70
656 -
657 - trail = sheet("AuditTrail", ("at_utc", "actor", "account_code", "action", "before", "after"))
658 - for entry in audit_trail:
659 - trail.append((
660 - entry["at"], entry["actor"], entry["account_code"], entry["action"],
661 - entry["before"], entry["after"],
662 - ))
663 - trail.column_dimensions["E"].width = 46
664 - trail.column_dimensions["F"].width = 46
665 -
666 - stream = BytesIO()
667 - workbook.save(stream)
668 - return stream.getvalue()
669 -
670 -
671 -def export_working_workbook(model: WorkingModel) -> bytes:
672 - """Serialize the full working state back to a valid Pilot v0.1 workbook.
673 -
674 - This is the durable "save workspace" artifact: re-uploading it rebuilds
675 - the same accounts, notes, mappings and company. Codes are written as text
676 - and mapping hierarchy is derived from each account so preflight passes.
677 - """
678 - workbook = Workbook()
679 - workbook.remove(workbook.active)
680 - header_font = Font(bold=True, color="FFFFFF")
681 - header_fill = PatternFill("solid", fgColor="1F4E78")
682 - sheets: dict[str, Any] = {}
683 - for name, headers in SHEET_HEADERS.items():
684 - ws = workbook.create_sheet(name)
685 - ws.append(headers)
686 - for cell in ws[1]:
687 - cell.font = header_font
688 - cell.fill = header_fill
689 - ws.freeze_panes = "A2"
690 - ws.sheet_view.rightToLeft = True
691 - sheets[name] = ws
692 -
693 - def row(sheet: str, values: dict) -> None:
694 - sheets[sheet].append(tuple(values.get(h) for h in SHEET_HEADERS[sheet]))
695 -
696 - company = model.company
697 - row("Company", {
698 - "company_code": company.code, "company_name": company.name,
699 - "fiscal_year": company.fiscal_year, "currency": company.currency,
700 - "unit": company.unit, "prepared_by": company.prepared_by,
701 - "status": company.status or "Draft",
702 - })
703 -
704 - for account in model.accounts.values():
705 - codes = hierarchy_codes(account)
706 - names = (
707 - account.general_name, account.subsidiary_name, account.detail1_name,
708 - account.detail2_name, account.detail3_name, account.detail4_name,
709 - )
710 - values = {
711 - "company_code": company.code, "fiscal_year": company.fiscal_year,
712 - "account_full_code": account.full_code, "account_name": account.name,
713 - "opening": float(account.opening), "debit": float(account.debit),
714 - "credit": float(account.credit), "closing": float(account.closing),
715 - "source_row": account.source_row, "row_status": account.row_status or "Draft",
716 - "closing_delta": 0,
717 - }
718 - for index, field_name in enumerate(_HIERARCHY_CODE_FIELDS):
719 - values[field_name] = codes[index] or None
720 - values[field_name.replace("_code", "_name")] = names[index] or None
721 - row("Accounts", values)
722 -
723 - for note in model.notes.values():
724 - row("Notes", {
725 - "company_code": company.code, "fiscal_year": company.fiscal_year,
726 - "statement": note.statement, "statement_section": note.section,
727 - "note_number": note.note_number, "note_title": note.note_title,
728 - "subnote_code": note.subnote_code or None,
729 - "subnote_title": note.subnote_title or None,
730 - })
731 -
732 - today = datetime.now(UTC).date().isoformat()
733 - for mapping in model.mappings.values():
734 - account = model.accounts.get(mapping.account_code)
735 - if account is None:
736 - continue
737 - codes = hierarchy_codes(account)
738 - approved = mapping.approval_status == "Approved"
739 - reviewed = mapping.approval_status in {"Reviewed", "Approved"}
740 - values = {
741 - "mapping_id": mapping.mapping_id or f"WB-{mapping.account_code}",
742 - "company_code": company.code, "fiscal_year": company.fiscal_year,
743 - "account_full_code": mapping.account_code,
744 - "account_level": account_level_of(account),
745 - "target_statement": mapping.statement, "statement_section": mapping.section,
746 - "note_number": mapping.note_number, "subnote_code": mapping.subnote_code or None,
747 - "mapping_version": 1, "approval_status": mapping.approval_status or "Draft",
748 - "reviewer": mapping.reviewer or (company.prepared_by or "workbench"),
749 - "review_date": today if reviewed else None,
750 - "source": mapping.source or "workbench",
751 - "validation_status": "Valid" if approved else "Pending",
752 - }
753 - for index, field_name in enumerate(_HIERARCHY_CODE_FIELDS):
754 - values[field_name] = codes[index] or None
755 - row("Mapping", values)
756 -
757 - sheets["Guide_FA"].append(
758 - ("ذخیرهٔ کارگاه", "این فایل خروجی «ذخیرهٔ کارگاه» است؛ برای ادامهٔ کار دوباره آپلودش کنید.")
759 - )
760 - stream = BytesIO()
761 - workbook.save(stream)
762 - return stream.getvalue()
docs/py/aram_backend/pilot_store.py deleted
-351
@@ -1,351 +0,0 @@
1 -"""Bounded, thread-safe in-memory session store for the Pilot workbench.
2 -
3 -Each session holds a mutable WorkingModel (company, accounts, notes, mappings)
4 -plus an append-only audit trail. Source workbook bytes are never retained.
5 -Everything disappears on restart by design; the durable artifacts are the
6 -exported Excel report and the re-uploadable "save workspace" workbook.
7 -"""
8 -
9 -from __future__ import annotations
10 -
11 -import threading
12 -import uuid
13 -from dataclasses import dataclass, field
14 -from datetime import UTC, datetime
15 -
16 -from aram_backend.pilot_editing import (
17 - SYNTHETIC_SOURCE_ROW_BASE,
18 - DuplicateAccountError,
19 - DuplicateNoteError,
20 - NoteInUseError,
21 - UnknownNoteError,
22 - make_account,
23 -)
24 -from aram_backend.pilot_engine import (
25 - MappingEntry,
26 - NoteTarget,
27 - PilotAccount,
28 - PilotCompany,
29 - PilotModel,
30 - WorkingModel,
31 -)
32 -
33 -MAX_SESSIONS = 32
34 -
35 -
36 -def _now() -> str:
37 - return datetime.now(UTC).isoformat(timespec="seconds")
38 -
39 -
40 -def _mapping_summary(entry: MappingEntry | None) -> str:
41 - if entry is None:
42 - return "(بدون نگاشت)"
43 - return (
44 - f"{entry.statement}/{entry.section}/{entry.note_number}"
45 - + (f"/{entry.subnote_code}" if entry.subnote_code else "")
46 - + f" [{entry.approval_status}]"
47 - )
48 -
49 -
50 -def _account_summary(account: PilotAccount | None) -> str:
51 - if account is None:
52 - return "(حذف شد)"
53 - return f"{account.full_code} {account.name} | مانده {account.closing}"
54 -
55 -
56 -def _note_summary(note: NoteTarget | None) -> str:
57 - if note is None:
58 - return "(حذف شد)"
59 - return (
60 - f"{note.statement}/{note.section}/{note.note_number}"
61 - + (f"/{note.subnote_code}" if note.subnote_code else "")
62 - + f" — {note.note_title}"
63 - )
64 -
65 -
66 -def _company_summary(company: PilotCompany) -> str:
67 - return f"{company.code} {company.name} | سال {company.fiscal_year} | {company.unit}"
68 -
69 -
70 -@dataclass
71 -class PilotSession:
72 - id: str
73 - working: WorkingModel
74 - source: str
75 - filename: str
76 - created_at: str = field(default_factory=_now)
77 - audit_trail: list[dict] = field(default_factory=list)
78 - synthetic_counter: int = 0
79 -
80 - # Compatibility surface: report/table/export functions accept WorkingModel.
81 - @property
82 - def model(self) -> WorkingModel:
83 - return self.working
84 -
85 - @property
86 - def mappings(self) -> dict[str, MappingEntry]:
87 - return self.working.mappings
88 -
89 -
90 -class UnknownSessionError(KeyError):
91 - pass
92 -
93 -
94 -class UnknownAccountError(KeyError):
95 - pass
96 -
97 -
98 -class UnknownTargetError(ValueError):
99 - pass
100 -
101 -
102 -class InvalidApprovalError(ValueError):
103 - pass
104 -
105 -
106 -class PilotSessionStore:
107 - def __init__(self, max_sessions: int = MAX_SESSIONS) -> None:
108 - self._sessions: dict[str, PilotSession] = {}
109 - self._order: list[str] = []
110 - self._lock = threading.RLock()
111 - self._max = max_sessions
112 -
113 - # ------------------------------------------------------------------ core
114 - def create(self, model: PilotModel, source: str, filename: str) -> PilotSession:
115 - session = PilotSession(
116 - id=uuid.uuid4().hex,
117 - working=WorkingModel.from_model(model),
118 - source=source,
119 - filename=filename,
120 - )
121 - with self._lock:
122 - self._sessions[session.id] = session
123 - self._order.append(session.id)
124 - while len(self._order) > self._max:
125 - oldest = self._order.pop(0)
126 - self._sessions.pop(oldest, None)
127 - return session
128 -
129 - def get(self, session_id: str) -> PilotSession:
130 - with self._lock:
131 - session = self._sessions.get(session_id)
132 - if session is None:
133 - raise UnknownSessionError(session_id)
134 - return session
135 -
136 - def snapshot(self, session_id: str) -> tuple[PilotSession, WorkingModel, list]:
137 - """Consistent working-model copy + trail for lock-free report building."""
138 - session = self.get(session_id)
139 - with self._lock:
140 - return session, session.working.copy(), list(session.audit_trail)
141 -
142 - def delete(self, session_id: str) -> None:
143 - with self._lock:
144 - if session_id not in self._sessions:
145 - raise UnknownSessionError(session_id)
146 - del self._sessions[session_id]
147 - self._order.remove(session_id)
148 -
149 - def _audit(self, session: PilotSession, actor: str, account_code: str,
150 - action: str, before: str, after: str) -> None:
151 - session.audit_trail.append({
152 - "at": _now(),
153 - "actor": actor.strip() or "workbench-user",
154 - "account_code": account_code,
155 - "action": action,
156 - "before": before,
157 - "after": after,
158 - })
159 -
160 - # -------------------------------------------------------------- mappings
161 - def set_mapping(
162 - self, session_id: str, account_code: str, *, statement: str, section: str,
163 - note_number: str, subnote_code: str = "", approval_status: str = "Draft",
164 - reviewer: str = "", actor: str = "workbench-user",
165 - ) -> PilotSession:
166 - session = self.get(session_id)
167 - with self._lock:
168 - if account_code not in session.working.accounts:
169 - raise UnknownAccountError(account_code)
170 - key = (statement, section, note_number, subnote_code)
171 - if key not in session.working.notes:
172 - raise UnknownTargetError(
173 - "Target statement/section/note/sub-note does not exist in Notes."
174 - )
175 - if approval_status not in {"Draft", "Reviewed", "Approved"}:
176 - raise InvalidApprovalError("Allowed approval statuses: Draft, Reviewed, Approved.")
177 - if approval_status in {"Reviewed", "Approved"} and not reviewer.strip():
178 - raise InvalidApprovalError(
179 - "Reviewed/Approved mappings require a reviewer name as evidence."
180 - )
181 - before = session.mappings.get(account_code)
182 - entry = MappingEntry(
183 - account_code=account_code, statement=statement, section=section,
184 - note_number=note_number, subnote_code=subnote_code,
185 - approval_status=approval_status, reviewer=reviewer.strip(),
186 - source="workbench", mapping_id=f"WB-{uuid.uuid4().hex[:10]}",
187 - )
188 - session.mappings[account_code] = entry
189 - session.working.conflicts.pop(account_code, None)
190 - self._audit(session, actor, account_code, "set_mapping",
191 - _mapping_summary(before),
192 - _mapping_summary(entry)
193 - + (f" بازبین: {entry.reviewer}" if entry.reviewer else ""))
194 - return session
195 -
196 - def clear_mapping(self, session_id: str, account_code: str,
197 - actor: str = "workbench-user") -> PilotSession:
198 - session = self.get(session_id)
199 - with self._lock:
200 - if account_code not in session.working.accounts:
201 - raise UnknownAccountError(account_code)
202 - before = session.mappings.pop(account_code, None)
203 - self._audit(session, actor, account_code, "clear_mapping",
204 - _mapping_summary(before), "(بدون نگاشت)")
205 - return session
206 -
207 - # -------------------------------------------------------------- accounts
208 - def add_account(
209 - self, session_id: str, *, full_code: str, name: str, general_code: str,
210 - general_name: str, opening, debit, credit, source_row: int | None = None,
211 - row_status: str = "Draft", subsidiary_code: str = "", subsidiary_name: str = "",
212 - actor: str = "workbench-user",
213 - ) -> PilotSession:
214 - session = self.get(session_id)
215 - with self._lock:
216 - code = (full_code or "").strip()
217 - if code in session.working.accounts:
218 - raise DuplicateAccountError(f"حساب با کد {code} از قبل وجود دارد.")
219 - if source_row is None:
220 - session.synthetic_counter += 1
221 - source_row = SYNTHETIC_SOURCE_ROW_BASE + session.synthetic_counter
222 - account = make_account(
223 - full_code=code, name=name, general_code=general_code,
224 - general_name=general_name, opening=opening, debit=debit, credit=credit,
225 - source_row=source_row, row_status=row_status,
226 - subsidiary_code=subsidiary_code, subsidiary_name=subsidiary_name,
227 - )
228 - session.working.accounts[account.full_code] = account
229 - session.working.accounts = dict(sorted(session.working.accounts.items()))
230 - self._audit(session, actor, account.full_code, "add_account",
231 - "(وجود نداشت)", _account_summary(account))
232 - return session
233 -
234 - def update_account(
235 - self, session_id: str, code: str, *, name: str, general_code: str,
236 - general_name: str, opening, debit, credit, row_status: str = "Draft",
237 - subsidiary_code: str = "", subsidiary_name: str = "",
238 - actor: str = "workbench-user",
239 - ) -> PilotSession:
240 - session = self.get(session_id)
241 - with self._lock:
242 - existing = session.working.accounts.get(code)
243 - if existing is None:
244 - raise UnknownAccountError(code)
245 - account = make_account(
246 - full_code=code, name=name, general_code=general_code,
247 - general_name=general_name, opening=opening, debit=debit, credit=credit,
248 - source_row=existing.source_row, row_status=row_status,
249 - subsidiary_code=subsidiary_code, subsidiary_name=subsidiary_name,
250 - )
251 - session.working.accounts[code] = account
252 - self._audit(session, actor, code, "update_account",
253 - _account_summary(existing), _account_summary(account))
254 - return session
255 -
256 - def rename_account(self, session_id: str, old_code: str, new_code: str,
257 - actor: str = "workbench-user") -> PilotSession:
258 - session = self.get(session_id)
259 - with self._lock:
260 - existing = session.working.accounts.get(old_code)
261 - if existing is None:
262 - raise UnknownAccountError(old_code)
263 - new_code = (new_code or "").strip()
264 - if not new_code or new_code.startswith("="):
265 - raise DuplicateAccountError("کد جدید باید متن ساده و غیرخالی باشد.")
266 - if new_code != old_code and new_code in session.working.accounts:
267 - raise DuplicateAccountError(f"حساب با کد {new_code} از قبل وجود دارد.")
268 - from dataclasses import replace
269 - renamed = replace(existing, full_code=new_code)
270 - del session.working.accounts[old_code]
271 - session.working.accounts[new_code] = renamed
272 - session.working.accounts = dict(sorted(session.working.accounts.items()))
273 - mapping = session.mappings.pop(old_code, None)
274 - if mapping is not None:
275 - session.mappings[new_code] = replace(mapping, account_code=new_code)
276 - conflict = session.working.conflicts.pop(old_code, None)
277 - if conflict is not None:
278 - session.working.conflicts[new_code] = tuple(
279 - replace(item, account_code=new_code) for item in conflict
280 - )
281 - self._audit(session, actor, new_code, "rename_account",
282 - f"کد قبلی: {old_code}", f"کد جدید: {new_code} (نگاشت منتقل شد)")
283 - return session
284 -
285 - def delete_account(self, session_id: str, code: str,
286 - actor: str = "workbench-user") -> PilotSession:
287 - session = self.get(session_id)
288 - with self._lock:
289 - existing = session.working.accounts.pop(code, None)
290 - if existing is None:
291 - raise UnknownAccountError(code)
292 - session.mappings.pop(code, None)
293 - session.working.conflicts.pop(code, None)
294 - self._audit(session, actor, code, "delete_account",
295 - _account_summary(existing), "(حذف شد)")
296 - return session
297 -
298 - # ----------------------------------------------------------------- notes
299 - def add_note(self, session_id: str, note: NoteTarget,
300 - actor: str = "workbench-user") -> PilotSession:
301 - session = self.get(session_id)
302 - with self._lock:
303 - if note.key in session.working.notes:
304 - raise DuplicateNoteError("این یادداشت/زیریادداشت از قبل وجود دارد.")
305 - session.working.notes[note.key] = note
306 - self._audit(session, actor, "", "add_note", "(وجود نداشت)", _note_summary(note))
307 - return session
308 -
309 - def update_note(self, session_id: str, key: tuple, note: NoteTarget,
310 - actor: str = "workbench-user") -> PilotSession:
311 - session = self.get(session_id)
312 - with self._lock:
313 - existing = session.working.notes.get(key)
314 - if existing is None:
315 - raise UnknownNoteError("یادداشت مورد نظر یافت نشد.")
316 - if note.key != key:
317 - raise UnknownNoteError("کلید یادداشت قابل تغییر نیست؛ فقط عنوان ویرایش می‌شود.")
318 - session.working.notes[key] = note
319 - self._audit(session, actor, "", "update_note",
320 - _note_summary(existing), _note_summary(note))
321 - return session
322 -
323 - def delete_note(self, session_id: str, key: tuple,
324 - actor: str = "workbench-user") -> PilotSession:
325 - session = self.get(session_id)
326 - with self._lock:
327 - existing = session.working.notes.get(key)
328 - if existing is None:
329 - raise UnknownNoteError("یادداشت مورد نظر یافت نشد.")
330 - in_use = [code for code, m in session.mappings.items() if m.target_key == key]
331 - if in_use:
332 - raise NoteInUseError(
333 - f"این یادداشت مقصد {len(in_use)} نگاشت است؛ ابتدا نگاشت‌ها را جابه‌جا کنید."
334 - )
335 - del session.working.notes[key]
336 - self._audit(session, actor, "", "delete_note", _note_summary(existing), "(حذف شد)")
337 - return session
338 -
339 - # --------------------------------------------------------------- company
340 - def update_company(self, session_id: str, company: PilotCompany,
341 - actor: str = "workbench-user") -> PilotSession:
342 - session = self.get(session_id)
343 - with self._lock:
344 - before = session.working.company
345 - session.working.company = company
346 - self._audit(session, actor, "", "update_company",
347 - _company_summary(before), _company_summary(company))
348 - return session
349 -
350 -
351 -store = PilotSessionStore()
docs/py/aram_backend/pilot_workbook.py deleted
-424
@@ -1,424 +0,0 @@
1 -from __future__ import annotations
2 -
3 -from collections import Counter
4 -from dataclasses import dataclass
5 -from datetime import date, datetime
6 -from decimal import Decimal, InvalidOperation
7 -from io import BytesIO
8 -from typing import Any
9 -from zipfile import BadZipFile
10 -
11 -from openpyxl import load_workbook
12 -from openpyxl.utils.exceptions import InvalidFileException
13 -
14 -SHEET_HEADERS: dict[str, tuple[str, ...]] = {
15 - "Company": (
16 - "company_code", "company_name", "fiscal_year", "currency", "unit",
17 - "prepared_by", "status",
18 - ),
19 - "Accounts": (
20 - "company_code", "fiscal_year", "general_code", "general_name",
21 - "subsidiary_code", "subsidiary_name", "detail1_code", "detail1_name",
22 - "detail2_code", "detail2_name", "detail3_code", "detail3_name",
23 - "detail4_code", "detail4_name", "account_full_code", "account_name",
24 - "opening", "debit", "credit", "closing", "source_row", "row_status",
25 - "closing_delta",
26 - ),
27 - "Notes": (
28 - "company_code", "fiscal_year", "statement", "statement_section",
29 - "note_number", "note_title", "subnote_code", "subnote_title",
30 - ),
31 - "Mapping": (
32 - "mapping_id", "company_code", "fiscal_year", "account_full_code",
33 - "account_level", "general_code", "subsidiary_code", "detail1_code",
34 - "detail2_code", "detail3_code", "detail4_code", "target_statement",
35 - "statement_section", "note_number", "subnote_code", "mapping_version",
36 - "approval_status", "reviewer", "review_date", "source", "notes",
37 - "validation_status",
38 - ),
39 - "Test_Log": (
40 - "tester", "feature", "expected_result", "actual_result", "status",
41 - "severity", "evidence", "notes",
42 - ),
43 - "Checks": ("check_code", "check_name", "status", "affected_rows", "details"),
44 - "Guide_FA": ("section", "instruction"),
45 - "Lists": ("list_name", "value"),
46 -}
47 -
48 -_SHEET_ORDER = {name: position for position, name in enumerate(SHEET_HEADERS)}
49 -_CODE_FIELDS = {
50 - "company_code", "general_code", "subsidiary_code", "detail1_code",
51 - "detail2_code", "detail3_code", "detail4_code", "account_full_code",
52 - "note_number", "subnote_code", "mapping_id",
53 -}
54 -_REQUIRED: dict[str, set[str]] = {
55 - "Company": {"company_code", "company_name", "fiscal_year", "status"},
56 - "Accounts": {
57 - "company_code", "fiscal_year", "general_code", "general_name",
58 - "account_full_code", "account_name", "opening", "debit", "credit",
59 - "closing", "source_row", "row_status", "closing_delta",
60 - },
61 - "Notes": {
62 - "company_code", "fiscal_year", "statement", "statement_section",
63 - "note_number", "note_title",
64 - },
65 - "Mapping": {
66 - "mapping_id", "company_code", "fiscal_year", "account_full_code",
67 - "account_level", "target_statement", "statement_section", "note_number",
68 - "mapping_version", "approval_status", "source", "validation_status",
69 - },
70 -}
71 -
72 -_STATEMENTS = {"BS", "IS", "CF", "EQ"}
73 -_ACCOUNT_LEVELS: dict[str, tuple[str, ...]] = {
74 - "General": ("general_code",),
75 - "Subsidiary": ("general_code", "subsidiary_code"),
76 - "Detail1": ("general_code", "subsidiary_code", "detail1_code"),
77 - "Detail2": (
78 - "general_code", "subsidiary_code", "detail1_code", "detail2_code",
79 - ),
80 - "Detail3": (
81 - "general_code", "subsidiary_code", "detail1_code", "detail2_code",
82 - "detail3_code",
83 - ),
84 - "Detail4": (
85 - "general_code", "subsidiary_code", "detail1_code", "detail2_code",
86 - "detail3_code", "detail4_code",
87 - ),
88 -}
89 -_HIERARCHY_FIELDS = (
90 - "general_code", "subsidiary_code", "detail1_code", "detail2_code",
91 - "detail3_code", "detail4_code",
92 -)
93 -
94 -
95 -@dataclass(frozen=True)
96 -class PilotIssue:
97 - severity: str
98 - code: str
99 - sheet: str
100 - row: int
101 - field: str
102 - message: str
103 -
104 -
105 -@dataclass(frozen=True)
106 -class PilotPreflightResult:
107 - valid: bool
108 - issues: tuple[PilotIssue, ...]
109 - issue_counts: dict[str, int]
110 -
111 -
112 -def _empty(value: Any) -> bool:
113 - return value is None or (isinstance(value, str) and not value.strip())
114 -
115 -
116 -def _issue(issues: list[PilotIssue], code: str, sheet: str, row: int,
117 - field: str, message: str, severity: str = "ERROR") -> None:
118 - issues.append(PilotIssue(severity, code, sheet, row, field, message))
119 -
120 -
121 -def _text_code(value: Any, issues: list[PilotIssue], sheet: str, row: int,
122 - field: str) -> str | None:
123 - if _empty(value):
124 - return None
125 - if not isinstance(value, str):
126 - _issue(issues, "CODE_NOT_TEXT", sheet, row, field,
127 - "Code cells must use Excel text format; numeric coercion is forbidden.")
128 - return None
129 - code = value.strip()
130 - if code.startswith("="):
131 - _issue(issues, "CODE_FORMULA_FORBIDDEN", sheet, row, field,
132 - "Code cells must contain literal text; formulas are forbidden.")
133 - return None
134 - return code
135 -
136 -
137 -def _positive_int(value: Any, issues: list[PilotIssue], sheet: str, row: int,
138 - field: str) -> int | None:
139 - if _empty(value):
140 - return None
141 - if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
142 - _issue(issues, "INVALID_POSITIVE_INTEGER", sheet, row, field,
143 - "Value must be a positive integer.")
144 - return None
145 - return value
146 -
147 -
148 -def _finite_decimal(value: Any, issues: list[PilotIssue], sheet: str, row: int,
149 - field: str) -> Decimal | None:
150 - if _empty(value):
151 - return None
152 - if isinstance(value, bool) or isinstance(value, str) and value.startswith("="):
153 - _issue(issues, "INVALID_FINANCIAL_VALUE", sheet, row, field,
154 - "Financial values must be finite numbers, not booleans or formulas.")
155 - return None
156 - try:
157 - parsed = Decimal(str(value).strip())
158 - except (InvalidOperation, ValueError):
159 - _issue(issues, "INVALID_FINANCIAL_VALUE", sheet, row, field,
160 - "Financial value is not a valid decimal number.")
161 - return None
162 - if not parsed.is_finite():
163 - _issue(issues, "NON_FINITE_FINANCIAL_VALUE", sheet, row, field,
164 - "NaN and Infinity are not permitted.")
165 - return None
166 - return parsed
167 -
168 -
169 -def _rows(sheet: Any, headers: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]:
170 - result: list[tuple[int, dict[str, Any]]] = []
171 - for row_number, values in enumerate(sheet.iter_rows(min_row=2, values_only=True), 2):
172 - row = dict(zip(headers, values))
173 - if any(not _empty(value) for value in row.values()):
174 - result.append((row_number, row))
175 - return result
176 -
177 -
178 -def preflight_pilot_workbook(workbook_bytes: bytes) -> PilotPreflightResult:
179 - """Validate a Pilot workbook fully in memory without persistence or mutation."""
180 - issues: list[PilotIssue] = []
181 - try:
182 - workbook = load_workbook(BytesIO(workbook_bytes), read_only=True, data_only=False)
183 - except (BadZipFile, InvalidFileException, OSError, ValueError, KeyError) as exc:
184 - issue = PilotIssue("ERROR", "INVALID_WORKBOOK", "__workbook__", 0, "__file__", str(exc))
185 - return PilotPreflightResult(False, (issue,), {"ERROR": 1})
186 -
187 - valid_sheets: set[str] = set()
188 - for sheet_name, expected in SHEET_HEADERS.items():
189 - if sheet_name not in workbook.sheetnames:
190 - _issue(issues, "MISSING_SHEET", sheet_name, 1, "__sheet__",
191 - f"Required sheet {sheet_name!r} is missing.")
192 - continue
193 - actual = tuple(cell.value for cell in workbook[sheet_name][1])
194 - if actual != expected:
195 - _issue(issues, "HEADER_MISMATCH", sheet_name, 1, "__headers__",
196 - f"Expected exact header order: {', '.join(expected)}.")
197 - continue
198 - valid_sheets.add(sheet_name)
199 -
200 - parsed: dict[str, list[tuple[int, dict[str, Any]]]] = {
201 - name: _rows(workbook[name], SHEET_HEADERS[name])
202 - for name in valid_sheets
203 - }
204 - workbook.close()
205 -
206 - for sheet_name in ("Company", "Accounts", "Notes", "Mapping"):
207 - for row_number, row in parsed.get(sheet_name, []):
208 - for field in _REQUIRED[sheet_name]:
209 - if _empty(row[field]):
210 - _issue(issues, "REQUIRED_FIELD", sheet_name, row_number, field,
211 - "Required field is empty.")
212 - for field in _CODE_FIELDS.intersection(row):
213 - _text_code(row[field], issues, sheet_name, row_number, field)
214 - _positive_int(row.get("fiscal_year"), issues, sheet_name, row_number, "fiscal_year")
215 -
216 - companies: set[tuple[str, int]] = set()
217 - for row_number, row in parsed.get("Company", []):
218 - code = _text_code(row["company_code"], [], "Company", row_number, "company_code")
219 - year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
220 - if code and year and year > 0:
221 - company_key = (code, year)
222 - if company_key in companies:
223 - _issue(issues, "DUPLICATE_COMPANY_YEAR", "Company", row_number,
224 - "company_code", "Company/fiscal-year key must be unique.")
225 - companies.add(company_key)
226 - if not _empty(row["status"]) and row["status"] not in {"Draft", "Approved", "Locked"}:
227 - _issue(issues, "INVALID_LIFECYCLE", "Company", row_number, "status",
228 - "Allowed values are Draft, Approved, and Locked.")
229 -
230 - account_keys: set[tuple[str, int, str]] = set()
231 - account_rows: dict[tuple[str, int, str], dict[str, Any]] = {}
232 - for row_number, row in parsed.get("Accounts", []):
233 - code = row["company_code"] if isinstance(row["company_code"], str) else None
234 - year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
235 - account = row["account_full_code"] if isinstance(row["account_full_code"], str) else None
236 - if code and year and (code.strip(), year) not in companies:
237 - _issue(issues, "UNKNOWN_COMPANY_YEAR", "Accounts", row_number, "company_code",
238 - "Referenced company/fiscal year is not defined in Company.")
239 - if code and year and account:
240 - account_key = (code.strip(), year, account.strip())
241 - if account_key in account_keys:
242 - _issue(issues, "DUPLICATE_ACCOUNT", "Accounts", row_number,
243 - "account_full_code", "Account key is duplicated within company/fiscal year.")
244 - account_keys.add(account_key)
245 - account_rows.setdefault(account_key, row)
246 - opening, debit, credit, closing = (
247 - _finite_decimal(row[field], issues, "Accounts", row_number, field)
248 - for field in ("opening", "debit", "credit", "closing")
249 - )
250 - declared_delta = _finite_decimal(
251 - row["closing_delta"], issues, "Accounts", row_number, "closing_delta"
252 - )
253 - _positive_int(row["source_row"], issues, "Accounts", row_number, "source_row")
254 - if not _empty(row["row_status"]) and row["row_status"] not in {"Draft", "Reviewed", "Approved"}:
255 - _issue(issues, "INVALID_LIFECYCLE", "Accounts", row_number, "row_status",
256 - "Allowed values are Draft, Reviewed, and Approved.")
257 - if (
258 - opening is not None
259 - and debit is not None
260 - and credit is not None
261 - and closing is not None
262 - ):
263 - delta = opening + debit - credit - closing
264 - if delta != 0:
265 - _issue(issues, "NON_ZERO_CLOSING_DELTA", "Accounts", row_number,
266 - "closing_delta", f"opening + debit - credit - closing equals {delta}.")
267 - if declared_delta is not None and declared_delta != delta:
268 - _issue(
269 - issues, "CLOSING_DELTA_MISMATCH", "Accounts", row_number,
270 - "closing_delta",
271 - f"Declared closing_delta {declared_delta} does not equal computed delta {delta}.",
272 - )
273 -
274 - for sheet_name in ("Notes", "Mapping"):
275 - for row_number, row in parsed.get(sheet_name, []):
276 - code = row["company_code"] if isinstance(row["company_code"], str) else None
277 - year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
278 - if code and year and (code.strip(), year) not in companies:
279 - _issue(issues, "UNKNOWN_COMPANY_YEAR", sheet_name, row_number,
280 - "company_code", "Referenced company/fiscal year is not defined in Company.")
281 -
282 - note_keys: set[tuple[str, int, str, str, str, str]] = set()
283 - for row_number, row in parsed.get("Notes", []):
284 - statement = row["statement"]
285 - if not _empty(statement) and statement not in _STATEMENTS:
286 - _issue(
287 - issues, "INVALID_STATEMENT", "Notes", row_number, "statement",
288 - "Allowed statement values are BS, IS, CF, and EQ.",
289 - )
290 - code = row["company_code"] if isinstance(row["company_code"], str) else None
291 - year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
292 - note_number = row["note_number"] if isinstance(row["note_number"], str) else None
293 - section = row["statement_section"] if isinstance(row["statement_section"], str) else None
294 - subnote = row["subnote_code"] if isinstance(row["subnote_code"], str) else ""
295 - if code and year and statement in _STATEMENTS and section and note_number:
296 - note_key = (
297 - code.strip(), year, statement, section.strip(), note_number.strip(),
298 - subnote.strip(),
299 - )
300 - if note_key in note_keys:
301 - _issue(
302 - issues, "DUPLICATE_NOTE_TARGET", "Notes", row_number,
303 - "note_number", "Note/sub-note target is duplicated.",
304 - )
305 - note_keys.add(note_key)
306 -
307 - mapping_ids: set[str] = set()
308 - for row_number, row in parsed.get("Mapping", []):
309 - mapping_id = row["mapping_id"] if isinstance(row["mapping_id"], str) else None
310 - if mapping_id:
311 - if mapping_id.strip() in mapping_ids:
312 - _issue(issues, "DUPLICATE_MAPPING_ID", "Mapping", row_number,
313 - "mapping_id", "Mapping ID must be unique.")
314 - mapping_ids.add(mapping_id.strip())
315 - _positive_int(row["mapping_version"], issues, "Mapping", row_number, "mapping_version")
316 - if not _empty(row["approval_status"]) and row["approval_status"] not in {"Draft", "Reviewed", "Approved"}:
317 - _issue(issues, "INVALID_LIFECYCLE", "Mapping", row_number, "approval_status",
318 - "Allowed values are Draft, Reviewed, and Approved.")
319 - if not _empty(row["validation_status"]) and row["validation_status"] not in {"Valid", "Invalid", "Pending"}:
320 - _issue(
321 - issues, "INVALID_VALIDATION_STATUS", "Mapping", row_number,
322 - "validation_status", "Allowed values are Valid, Invalid, and Pending.",
323 - )
324 - if not _empty(row["target_statement"]) and row["target_statement"] not in _STATEMENTS:
325 - _issue(
326 - issues, "INVALID_STATEMENT", "Mapping", row_number,
327 - "target_statement", "Allowed statement values are BS, IS, CF, and EQ.",
328 - )
329 -
330 - level = row["account_level"]
331 - if not _empty(level) and level not in _ACCOUNT_LEVELS:
332 - _issue(
333 - issues, "INVALID_ACCOUNT_LEVEL", "Mapping", row_number,
334 - "account_level",
335 - "Allowed levels are General, Subsidiary, Detail1, Detail2, Detail3, and Detail4.",
336 - )
337 - elif level in _ACCOUNT_LEVELS:
338 - required_fields = set(_ACCOUNT_LEVELS[level])
339 - for field in required_fields:
340 - if _empty(row[field]):
341 - _issue(
342 - issues, "MAPPING_HIERARCHY_MISSING", "Mapping", row_number,
343 - field, f"{field} is required for account level {level}.",
344 - )
345 - for field in _HIERARCHY_FIELDS[len(_ACCOUNT_LEVELS[level]):]:
346 - if not _empty(row[field]):
347 - _issue(
348 - issues, "MAPPING_HIERARCHY_EXCESS", "Mapping", row_number,
349 - field, f"{field} must be empty for account level {level}.",
350 - )
351 -
352 - approval_status = row["approval_status"]
353 - if approval_status in {"Reviewed", "Approved"}:
354 - if _empty(row["reviewer"]):
355 - _issue(
356 - issues, "REVIEW_EVIDENCE_REQUIRED", "Mapping", row_number,
357 - "reviewer", "Reviewed and Approved mappings require a reviewer.",
358 - )
359 - review_date = row["review_date"]
360 - if _empty(review_date):
361 - _issue(
362 - issues, "REVIEW_EVIDENCE_REQUIRED", "Mapping", row_number,
363 - "review_date", "Reviewed and Approved mappings require a review date.",
364 - )
365 - elif not isinstance(review_date, (str, date, datetime)):
366 - _issue(
367 - issues, "INVALID_REVIEW_DATE", "Mapping", row_number,
368 - "review_date", "Review date must be an Excel date or text date.",
369 - )
370 - if approval_status == "Approved" and row["validation_status"] != "Valid":
371 - _issue(
372 - issues, "APPROVAL_REQUIRES_VALID_MAPPING", "Mapping", row_number,
373 - "validation_status", "Approved mappings must have validation_status Valid.",
374 - )
375 -
376 - code = row["company_code"] if isinstance(row["company_code"], str) else None
377 - year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
378 - account = row["account_full_code"] if isinstance(row["account_full_code"], str) else None
379 - mapping_account_key = (
380 - (code.strip(), year, account.strip())
381 - if code and year and account else None
382 - )
383 - if mapping_account_key and mapping_account_key not in account_keys:
384 - _issue(
385 - issues, "UNKNOWN_MAPPING_ACCOUNT", "Mapping", row_number,
386 - "account_full_code",
387 - "Mapped account does not exist in Accounts for this company/fiscal year.",
388 - )
389 - elif mapping_account_key:
390 - source_account = account_rows[mapping_account_key]
391 - for field in _HIERARCHY_FIELDS:
392 - mapping_value = row[field].strip() if isinstance(row[field], str) else None
393 - account_value = source_account[field].strip() if isinstance(source_account[field], str) else None
394 - if mapping_value != account_value:
395 - _issue(
396 - issues, "MAPPING_HIERARCHY_MISMATCH", "Mapping", row_number,
397 - field,
398 - f"Mapping hierarchy does not match Accounts for {field}.",
399 - )
400 -
401 - statement = row["target_statement"]
402 - section = row["statement_section"] if isinstance(row["statement_section"], str) else None
403 - note_number = row["note_number"] if isinstance(row["note_number"], str) else None
404 - subnote = row["subnote_code"] if isinstance(row["subnote_code"], str) else ""
405 - if code and year and statement in _STATEMENTS and section and note_number:
406 - target_key = (
407 - code.strip(), year, statement, section.strip(), note_number.strip(),
408 - subnote.strip(),
409 - )
410 - if target_key not in note_keys:
411 - _issue(
412 - issues, "UNKNOWN_MAPPING_TARGET", "Mapping", row_number,
413 - "note_number",
414 - "Mapped statement/note/sub-note target does not exist in Notes.",
415 - )
416 -
417 - ordered = tuple(sorted(issues, key=lambda item: (
418 - _SHEET_ORDER.get(item.sheet, -1), item.row,
419 - SHEET_HEADERS.get(item.sheet, ()).index(item.field)
420 - if item.field in SHEET_HEADERS.get(item.sheet, ()) else -1,
421 - item.code, item.message,
422 - )))
423 - counts = dict(sorted(Counter(item.severity for item in ordered).items()))
424 - return PilotPreflightResult(not any(item.severity == "ERROR" for item in ordered), ordered, counts)
docs/styles.css deleted
-293
@@ -1,293 +0,0 @@
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 - --nav-h: 64px;
16 - color-scheme: dark;
17 -}
18 -
19 -* { box-sizing: border-box; }
20 -html { -webkit-text-size-adjust: 100%; }
21 -
22 -body {
23 - margin: 0;
24 - font-family: Vazirmatn, "Segoe UI", Tahoma, Arial, sans-serif;
25 - background: radial-gradient(1100px 500px at 85% -10%, #14264a 0%, transparent 60%), 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: 12px; flex-wrap: wrap; padding: 14px 20px;
39 - border-bottom: 1px solid var(--line);
40 - background: rgb(10 18 32 / 85%); backdrop-filter: blur(6px);
41 - position: sticky; top: 0; z-index: 20;
42 -}
43 -.brand { display: flex; align-items: center; gap: 12px; min-width: 0; }
44 -.brand-mark {
45 - width: 42px; height: 42px; border-radius: 12px; flex: none;
46 - display: grid; place-items: center;
47 - background: linear-gradient(135deg, var(--primary), #7c5cff);
48 - font-size: 22px; font-weight: 800; color: #fff;
49 -}
50 -.topbar h1 { margin: 0; font-size: 17px; white-space: nowrap; }
51 -.tagline { margin: 0; font-size: 11.5px; color: var(--muted); }
52 -.topbar-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
53 -.actor-field { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--muted); }
54 -.actor-field input {
55 - background: var(--bg-soft); border: 1px solid var(--line); color: var(--text);
56 - border-radius: 8px; padding: 8px 10px; width: 150px; font-family: inherit; font-size: 14px;
57 -}
58 -
59 -main { max-width: 1200px; margin: 0 auto; padding: 22px 18px 60px; }
60 -
61 -/* ---------- cards / buttons ---------- */
62 -.card { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 18px; }
63 -.btn {
64 - border: 1px solid var(--line); border-radius: 10px; background: var(--card-2); color: var(--text);
65 - padding: 11px 18px; font-family: inherit; font-size: 14px; cursor: pointer;
66 - transition: filter .15s, transform .05s; min-height: 44px;
67 -}
68 -.btn:hover { filter: brightness(1.15); }
69 -.btn:active { transform: translateY(1px); }
70 -.btn:disabled { opacity: .5; cursor: wait; }
71 -.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; font-weight: 700; }
72 -.btn.accent { background: var(--accent); border-color: var(--accent); color: #201400; font-weight: 700; }
73 -.btn.ghost { background: transparent; }
74 -.btn.small { padding: 7px 13px; font-size: 12.5px; border-radius: 8px; min-height: 36px; }
75 -.btn.danger { background: #3a1420; border-color: #7f1d1d; color: #fca5a5; }
76 -.btn.block { width: 100%; }
77 -
78 -/* ---------- landing ---------- */
79 -.hero { text-align: center; padding: 22px 8px 8px; }
80 -.hero h2 { font-size: 24px; margin: 0 0 10px; }
81 -.hero p { max-width: 760px; margin: 0 auto 8px; color: var(--muted); }
82 -.safety-note {
83 - display: inline-block; margin-top: 10px; padding: 6px 16px;
84 - border: 1px dashed var(--accent); border-radius: 999px; color: var(--accent); font-size: 12.5px;
85 -}
86 -.action-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(270px, 1fr)); gap: 16px; margin: 24px 0; }
87 -.action-card { text-align: center; padding: 26px 20px; }
88 -.action-icon { font-size: 36px; }
89 -.action-card h3 { margin: 10px 0 6px; }
90 -.action-card p { color: var(--muted); font-size: 13.5px; min-height: 44px; }
91 -.progress-card { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
92 -.spinner { width: 18px; height: 18px; border-radius: 50%; border: 3px solid var(--line); border-top-color: var(--primary); animation: spin .9s linear infinite; display: inline-block; }
93 -@keyframes spin { to { transform: rotate(360deg); } }
94 -.issues-card { border-color: #7f1d1d; margin-bottom: 16px; }
95 -.issues-card h3 { color: var(--red); margin-top: 0; }
96 -.info-card h3 { margin-top: 0; }
97 -.policy-grid { display: flex; gap: 10px; flex-wrap: wrap; margin: 10px 0; }
98 -.policy-item { background: var(--bg-soft); border: 1px solid var(--line); border-radius: 10px; padding: 7px 13px; font-size: 13px; }
99 -.policy-item b { color: var(--blue); }
100 -
101 -/* ---------- session bar ---------- */
102 -.session-bar { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
103 -.session-meta { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
104 -.session-meta .company-name { font-weight: 800; font-size: 16px; }
105 -.chip { padding: 3px 11px; border-radius: 999px; font-size: 12px; border: 1px solid var(--line); background: var(--bg-soft); color: var(--muted); }
106 -.chip.demo { border-color: var(--accent); color: var(--accent); }
107 -.status-chip { padding: 8px 16px; border-radius: 12px; font-weight: 800; font-size: 13.5px; }
108 -.status-INCOMPLETE { background: #3a2a10; color: #fbbf24; border: 1px solid #92600a; }
109 -.status-COMPLETE_DRAFT { background: #122a4a; color: #93c5fd; border: 1px solid #1d4ed8; }
110 -.status-COMPLETE_APPROVED { background: #0c2f24; color: #6ee7b7; border: 1px solid #047857; }
111 -
112 -/* ---------- tab bar (bottom on mobile, top on desktop) ---------- */
113 -.tabbar { display: flex; gap: 6px; flex-wrap: wrap; margin: 0 0 18px; }
114 -.tab {
115 - position: relative; background: transparent; border: 1px solid transparent; color: var(--muted);
116 - padding: 9px 15px; border-radius: 10px; cursor: pointer; font-family: inherit; font-size: 14px;
117 - display: inline-flex; align-items: center; gap: 6px;
118 -}
119 -.tab:hover { color: var(--text); background: var(--bg-soft); }
120 -.tab.active { background: var(--card); border-color: var(--line); color: var(--text); font-weight: 700; }
121 -.tab-ico { font-size: 16px; }
122 -.badge { background: var(--accent); color: #201400; border-radius: 999px; font-size: 11px; padding: 1px 7px; font-weight: 800; }
123 -.badge.zero { background: var(--green); }
124 -
125 -/* ---------- dashboard ---------- */
126 -.grid { display: grid; gap: 12px; }
127 -.checks-grid { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); margin-bottom: 14px; }
128 -.check-card { padding: 13px 15px; border-radius: 12px; border: 1px solid var(--line); background: var(--card); }
129 -.check-card .check-name { font-size: 13px; color: var(--muted); }
130 -.check-card .check-state { font-size: 16px; font-weight: 800; margin: 3px 0; }
131 -.check-card.pass .check-state { color: var(--green); }
132 -.check-card.fail .check-state { color: var(--red); }
133 -.check-card .check-details { font-size: 12px; color: var(--muted); }
134 -.check-amount { direction: ltr; font-family: Consolas, monospace; font-size: 12.5px; }
135 -.totals-grid { grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); margin: 14px 0; }
136 -.total-card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 13px 15px; }
137 -.total-card .label { font-size: 12.5px; color: var(--muted); }
138 -.total-card .value { font-size: 17px; font-weight: 800; direction: ltr; text-align: right; font-family: Consolas, monospace; }
139 -.total-card.highlight { border-color: var(--primary); }
140 -.total-card .value.neg { color: var(--red); }
141 -.coverage-bar-wrap { background: var(--bg-soft); border-radius: 999px; height: 14px; overflow: hidden; border: 1px solid var(--line); }
142 -.coverage-bar { height: 100%; background: linear-gradient(90deg, var(--primary), var(--green)); transition: width .4s; }
143 -
144 -/* ---------- tables ---------- */
145 -.table-wrap { overflow-x: auto; border-radius: 12px; border: 1px solid var(--line); -webkit-overflow-scrolling: touch; }
146 -table { width: 100%; border-collapse: collapse; font-size: 13.5px; background: var(--card); }
147 -th, td { padding: 9px 12px; border-bottom: 1px solid var(--line); text-align: right; vertical-align: middle; }
148 -thead th { background: var(--card-2); color: var(--muted); font-size: 12.5px; white-space: nowrap; }
149 -tbody tr:hover { background: rgb(79 140 255 / 6%); }
150 -td.num, th.num { direction: ltr; text-align: left; font-family: Consolas, monospace; white-space: nowrap; }
151 -td.num.neg { color: var(--red); }
152 -.table-toolbar { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-bottom: 12px; }
153 -.table-toolbar input[type="search"], .table-toolbar select {
154 - background: var(--bg-soft); border: 1px solid var(--line); color: var(--text);
155 - border-radius: 9px; padding: 9px 12px; font-family: inherit; font-size: 14px;
156 -}
157 -.table-toolbar input[type="search"] { flex: 1; min-width: 160px; }
158 -
159 -.approval-chip { font-size: 11.5px; padding: 2px 10px; border-radius: 999px; border: 1px solid var(--line); white-space: nowrap; }
160 -.approval-Approved { background: #0c2f24; color: #6ee7b7; border-color: #047857; }
161 -.approval-Reviewed { background: #122a4a; color: #93c5fd; border-color: #1d4ed8; }
162 -.approval-Draft { background: #3a2a10; color: #fbbf24; border-color: #92600a; }
163 -.approval-none { background: #3a1420; color: #fca5a5; border-color: #7f1d1d; }
164 -
165 -/* ---------- item cards (accounts / notes) ---------- */
166 -.item-list { display: flex; flex-direction: column; gap: 10px; }
167 -.item-card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 13px 15px; }
168 -.item-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 10px; }
169 -.item-title { font-weight: 700; font-size: 14.5px; }
170 -.item-code { font-size: 12px; color: var(--muted); }
171 -.item-sub { font-size: 12.5px; color: var(--muted); margin-top: 4px; }
172 -.item-amount { direction: ltr; font-family: Consolas, monospace; font-weight: 700; white-space: nowrap; }
173 -.item-amount.neg { color: var(--red); }
174 -.item-actions { display: flex; gap: 7px; flex-wrap: wrap; margin-top: 10px; }
175 -.item-actions .btn { flex: 1; min-width: 90px; }
176 -.section-label { font-size: 13px; font-weight: 800; color: var(--blue); margin: 16px 0 8px; display: flex; align-items: center; gap: 8px; }
177 -.section-label::after { content: ""; flex: 1; height: 1px; background: var(--line); }
178 -
179 -/* ---------- statements ---------- */
180 -.statement-paper { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 22px 24px; }
181 -.statement-head { text-align: center; margin-bottom: 16px; }
182 -.statement-head h2 { margin: 0; font-size: 20px; }
183 -.statement-head .sub { color: var(--muted); font-size: 13px; }
184 -.draft-watermark { display: inline-block; margin-top: 8px; padding: 3px 14px; border-radius: 999px; border: 1px dashed var(--accent); color: var(--accent); font-size: 12px; }
185 -.statement-section { margin: 16px 0; }
186 -.statement-section > .section-head { display: flex; justify-content: space-between; align-items: center; background: var(--card-2); padding: 9px 15px; border-radius: 10px; font-weight: 800; border: 1px solid var(--line); }
187 -.note-line { display: flex; justify-content: space-between; align-items: center; padding: 10px 16px; border-bottom: 1px solid var(--line); cursor: pointer; gap: 10px; }
188 -.note-line:hover { background: rgb(79 140 255 / 6%); }
189 -.note-line .note-title { display: flex; gap: 9px; align-items: center; flex-wrap: wrap; min-width: 0; }
190 -.note-number { background: var(--bg-soft); border: 1px solid var(--line); border-radius: 7px; min-width: 32px; text-align: center; font-size: 12px; padding: 1px 6px; color: var(--muted); }
191 -.note-total { direction: ltr; font-family: Consolas, monospace; font-weight: 700; white-space: nowrap; }
192 -.note-total.neg { color: var(--red); }
193 -.drill { padding: 4px 14px 12px; }
194 -.drill table { font-size: 12.5px; background: var(--bg-soft); }
195 -.statement-total { display: flex; justify-content: space-between; padding: 12px 16px; margin-top: 12px; border-top: 2px solid var(--primary); font-weight: 900; font-size: 15px; gap: 10px; }
196 -.statement-tools { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 12px; flex-wrap: wrap; }
197 -.segmented { display: inline-flex; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
198 -.segmented button { background: transparent; border: none; color: var(--muted); padding: 9px 18px; font-family: inherit; font-size: 14px; cursor: pointer; min-height: 42px; }
199 -.segmented button.active { background: var(--primary); color: #fff; font-weight: 700; }
200 -
201 -/* ---------- more / audit ---------- */
202 -.provenance-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 10px; margin-bottom: 14px; }
203 -.prov-item { background: var(--bg-soft); border: 1px solid var(--line); border-radius: 10px; padding: 10px 13px; font-size: 13px; }
204 -.prov-item .k { color: var(--muted); font-size: 11.5px; }
205 -.prov-item .v { word-break: break-all; }
206 -.action-stack { display: flex; flex-direction: column; gap: 10px; }
207 -
208 -/* ---------- bottom sheet ---------- */
209 -.sheet-backdrop { position: fixed; inset: 0; background: rgb(0 0 0 / 55%); z-index: 40; }
210 -.sheet {
211 - position: fixed; z-index: 41; background: var(--bg-soft); border: 1px solid var(--line);
212 - left: 0; right: 0; bottom: 0; max-height: 88vh; display: flex; flex-direction: column;
213 - border-radius: 20px 20px 0 0; box-shadow: 0 -12px 50px rgb(0 0 0 / 5%);
214 - animation: sheet-up .22s ease;
215 -}
216 -@keyframes sheet-up { from { transform: translateY(40px); opacity: .4; } to { transform: none; opacity: 1; } }
217 -.sheet-handle { width: 44px; height: 4px; border-radius: 2px; background: var(--line); margin: 10px auto 2px; flex: none; }
218 -.sheet-head { display: flex; justify-content: space-between; align-items: center; padding: 8px 20px; border-bottom: 1px solid var(--line); flex: none; }
219 -.sheet-head h3 { margin: 0; font-size: 16px; }
220 -.sheet-close { background: transparent; border: none; color: var(--muted); font-size: 18px; cursor: pointer; width: 40px; height: 40px; }
221 -.sheet-body { padding: 18px 20px 26px; overflow-y: auto; }
222 -.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
223 -.form-grid .full { grid-column: 1 / -1; }
224 -.form-field { display: flex; flex-direction: column; gap: 5px; font-size: 12.5px; color: var(--muted); }
225 -.form-field input, .form-field select {
226 - background: var(--card); border: 1px solid var(--line); color: var(--text);
227 - border-radius: 9px; padding: 11px 12px; font-family: inherit; font-size: 15px; width: 100%;
228 -}
229 -.form-field input:focus, .form-field select:focus { outline: 2px solid var(--primary); outline-offset: -1px; }
230 -.form-hint { font-size: 12px; color: var(--muted); margin: 8px 0; }
231 -.form-actions { display: flex; gap: 10px; margin-top: 18px; }
232 -.form-actions .btn { flex: 1; }
233 -.computed-box { background: var(--card); border: 1px dashed var(--line); border-radius: 9px; padding: 10px 12px; font-size: 14px; }
234 -.computed-box b { direction: ltr; font-family: Consolas, monospace; }
235 -
236 -/* ---------- toast / footer ---------- */
237 -.toast { position: fixed; bottom: calc(var(--nav-h) + 16px); right: 50%; transform: translateX(50%); background: var(--card-2); border: 1px solid var(--line); color: var(--text); padding: 12px 20px; border-radius: 12px; z-index: 50; max-width: 92vw; box-shadow: 0 12px 40px rgb(0 0 0 / 45%); font-size: 14px; text-align: center; }
238 -.toast.error { border-color: #7f1d1d; color: #fca5a5; }
239 -.toast.success { border-color: #047857; color: #6ee7b7; }
240 -.footer { text-align: center; color: var(--muted); font-size: 12px; padding: 16px; border-top: 1px solid var(--line); }
241 -
242 -/* ---------- mobile ---------- */
243 -@media (max-width: 760px) {
244 - main { padding: 16px 12px calc(var(--nav-h) + 28px); }
245 - .topbar { padding: 10px 14px; }
246 - .tagline { display: none; }
247 - .topbar h1 { font-size: 15px; }
248 - .actor-label { display: none; }
249 - .actor-field input { width: 110px; }
250 - .hero h2 { font-size: 20px; }
251 - .statement-paper { padding: 16px 14px; }
252 - .form-grid { grid-template-columns: 1fr; }
253 - .tabbar {
254 - position: fixed; bottom: 0; left: 0; right: 0; z-index: 30; margin: 0;
255 - background: rgb(10 18 32 / 95%); backdrop-filter: blur(8px);
256 - border-top: 1px solid var(--line); padding: 6px 6px calc(6px + env(safe-area-inset-bottom));
257 - display: flex; justify-content: space-around; gap: 2px; flex-wrap: nowrap;
258 - min-height: var(--nav-h);
259 - }
260 - .tabbar .tab { flex-direction: column; gap: 2px; font-size: 10.5px; padding: 6px 4px; flex: 1; border-radius: 10px; justify-content: center; }
261 - .tabbar .tab-ico { font-size: 19px; }
262 - .tabbar .badge { position: absolute; top: 2px; left: 50%; margin-inline-start: 8px; }
263 - .footer { display: none; }
264 - .toast { bottom: calc(var(--nav-h) + 14px); }
265 - .desktop-only { display: none !important; }
266 -}
267 -@media (min-width: 761px) {
268 - .mobile-only { display: none !important; }
269 - .tabbar { position: static; }
270 -}
271 -
272 -/* ---------- print ---------- */
273 -@media print {
274 - body { background: #fff; color: #111; }
275 - .topbar, .tabbar, .session-bar, .footer, .statement-tools, .toast, .sheet, .sheet-backdrop { display: none !important; }
276 - .statement-paper { border: none; background: #fff; }
277 - .statement-section > .section-head { background: #eef2f7; color: #111; }
278 - .note-line, th, td { border-color: #cbd5e1; }
279 - .note-number, .chip { color: #334155; background: #f1f5f9; }
280 - thead th { background: #eef2f7; color: #334155; }
281 - table { background: #fff; }
282 - .draft-watermark { color: #92400e; border-color: #92400e; }
283 -}
284 -
285 -/* ---------- boot / engine loading ---------- */
286 -.boot { position: fixed; inset: 0; z-index: 100; display: grid; place-items: center; background: radial-gradient(900px 500px at 70% -10%, #14264a 0%, transparent 60%), var(--bg); padding: 20px; }
287 -.boot-card { text-align: center; max-width: 420px; width: 100%; }
288 -.boot-mark { width: 64px; height: 64px; margin: 0 auto 14px; border-radius: 18px; display: grid; place-items: center; background: linear-gradient(135deg, var(--primary), #7c5cff); font-size: 32px; font-weight: 800; color: #fff; }
289 -.boot-card h2 { margin: 0 0 8px; font-size: 20px; }
290 -.boot-card p { color: var(--muted); font-size: 13.5px; }
291 -.boot-bar { background: var(--bg-soft); border: 1px solid var(--line); border-radius: 999px; height: 12px; overflow: hidden; margin: 16px 0; }
292 -.boot-progress { height: 100%; width: 5%; background: linear-gradient(90deg, var(--primary), var(--green)); transition: width .4s; }
293 -.boot-error { color: var(--red) !important; border: 1px solid #7f1d1d; border-radius: 10px; padding: 10px; margin-top: 12px; }
docs/vendor/et_xmlfile-2.0.0-py3-none-any.whl
Binary files a/docs/vendor/et_xmlfile-2.0.0-py3-none-any.whl and /dev/null differ
docs/vendor/openpyxl-3.1.5-py2.py3-none-any.whl
Binary files a/docs/vendor/openpyxl-3.1.5-py2.py3-none-any.whl and /dev/null differ
scripts/build_webapp.py deleted
-51
@@ -1,51 +0,0 @@
1 -#!/usr/bin/env python3
2 -"""Assemble the browser edition into docs/ for GitHub Pages.
3 -
4 -Copies the UI shell (webapp/) plus the exact, unmodified engine modules from
5 -backend/src/aram_backend/ so the deployed app runs the same tested code.
6 -
7 -Usage: python scripts/build_webapp.py
8 -"""
9 -
10 -from __future__ import annotations
11 -
12 -import shutil
13 -from pathlib import Path
14 -
15 -ROOT = Path(__file__).resolve().parents[1]
16 -SRC = ROOT / "backend" / "src" / "aram_backend"
17 -WEB = ROOT / "webapp"
18 -OUT = ROOT / "docs"
19 -
20 -ENGINE_FILES = [
21 - "__init__.py",
22 - "pilot_workbook.py",
23 - "pilot_engine.py",
24 - "pilot_editing.py",
25 - "pilot_demo.py",
26 - "pilot_store.py",
27 -]
28 -UI_FILES = ["index.html", "styles.css", "app.js", "bridge.py"]
29 -
30 -
31 -def main() -> None:
32 - pkg = OUT / "py" / "aram_backend"
33 - pkg.mkdir(parents=True, exist_ok=True)
34 - for name in ENGINE_FILES:
35 - shutil.copyfile(SRC / name, pkg / name)
36 - for name in UI_FILES:
37 - shutil.copyfile(WEB / name, OUT / name)
38 - vendor = OUT / "vendor"
39 - vendor.mkdir(parents=True, exist_ok=True)
40 - for whl in sorted((WEB / "vendor").glob("*.whl")):
41 - shutil.copyfile(whl, vendor / whl.name)
42 - # GitHub Pages: skip Jekyll so every file is served verbatim.
43 - (OUT / ".nojekyll").write_text("")
44 - print("Built browser edition into docs/:")
45 - for p in sorted(OUT.rglob("*")):
46 - if p.is_file():
47 - print(f" {p.relative_to(ROOT)} ({p.stat().st_size} bytes)")
48 -
49 -
50 -if __name__ == "__main__":
51 - main()
webapp/README.md deleted
-50
@@ -1,50 +0,0 @@
1 -# Aram Pilot Workbench — Browser Edition
2 -
3 -A permanent, server-free build of the pilot workbench that runs entirely in the
4 -user's browser (mobile-first, Persian RTL). It executes the **exact same tested
5 -Python engine** as the backend — `pilot_workbook.py`, `pilot_engine.py`,
6 -`pilot_editing.py`, `pilot_demo.py`, `pilot_store.py` — inside
7 -[Pyodide](https://pyodide.org) (Python 3.12 + openpyxl compiled to WebAssembly).
8 -No financial logic is reimplemented in JavaScript.
9 -
10 -## Layout
11 -
12 -- `index.html`, `styles.css`, `app.js` — UI shell (same UX as `backend/src/aram_backend/static/pilot/`).
13 -- `bridge.py` — JSON-in/JSON-out dispatcher mirroring `pilot_api.py` without FastAPI.
14 -- `../scripts/build_webapp.py` — assembles `docs/` (UI + unmodified engine copies + `.nojekyll`).
15 -
16 -## Rebuild
17 -
18 -```bash
19 -python scripts/build_webapp.py
20 -```
21 -
22 -The `docs/` folder on this branch is the GitHub Pages source, so the app is
23 -served at `https://davoodmehraban89.github.io/Aram/`.
24 -
25 -## Runtime
26 -
27 -On first load the page fetches the Pyodide runtime (jsDelivr, with an unpkg
28 -fallback), installs the **vendored** pure-Python wheels in `vendor/`
29 -(openpyxl + et_xmlfile, extracted straight into site-packages — no PyPI or
30 -micropip needed), then loads the engine modules from `py/aram_backend/`. All
31 -data stays in the browser's memory; the durable artifacts are the downloaded
32 -workbooks (`ذخیرهٔ کارگاه` is a lossless, re-uploadable v0.1 workbook).
33 -
34 -## Permanent links (no setup required)
35 -
36 -The bundle is served verbatim, with correct MIME types, at commit-pinned URLs:
37 -
38 -- `https://rawcdn.githack.com/davoodmehraban89/Aram/<commit>/docs/index.html`
39 -- `https://cdn.jsdelivr.net/gh/davoodmehraban89/Aram@<commit>/docs/index.html`
40 -
41 -If the owner enables GitHub Pages (Settings → Pages → Source: GitHub Actions),
42 -dispatch `.github/workflows/pilot-pages.yml` to also publish at
43 -`https://davoodmehraban89.github.io/Aram/`.
44 -
45 -## Verification
46 -
47 -- Bridge parity + full workflow tested under Node + Pyodide 0.26.4 (same version as the CDN).
48 -- Round-trip: export workspace → re-upload preserves accounts, mappings, approvals, totals.
49 -- Balance semantics: one-sided entries fail the balance check honestly; balanced pairs restore it.
50 -- Error paths: invalid workbook → structured preflight issues; duplicates → 409-style errors.
webapp/app.js deleted
-692
@@ -1,692 +0,0 @@
1 -/* Aram Pilot Workbench — browser edition.
2 - Runs the exact, tested Python engine client-side via Pyodide. No server. */
3 -"use strict";
4 -
5 -const S = {
6 - meta: null, data: null, tab: "dashboard",
7 - filter: "all", search: "", noteSearch: "",
8 - statementView: "BS", expanded: new Set(),
9 - ready: false,
10 -};
11 -let PY = null, BRIDGE = null;
12 -
13 -const $ = (s) => document.querySelector(s);
14 -const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => (
15 - { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]
16 -));
17 -function fmt(v) {
18 - if (v === null || v === undefined || v === "") return "—";
19 - let s = String(v); const neg = s.startsWith("-"); if (neg) s = s.slice(1);
20 - let [i, d] = s.split("."); i = i.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
21 - if (d) d = d.replace(/0+$/, "");
22 - return (neg ? "−" : "") + i + (d ? "." + d : "");
23 -}
24 -const isNeg = (v) => String(v ?? "").startsWith("-");
25 -const numCell = (v) => `<td class="num${isNeg(v) ? " neg" : ""}">${fmt(v)}</td>`;
26 -const STATUS_FA = {
27 - INCOMPLETE: "ناقص — پیش‌نویس کاری",
28 - COMPLETE_DRAFT: "کامل — نگاشت‌ها در انتظار تأیید",
29 - COMPLETE_APPROVED: "کامل — همهٔ نگاشت‌ها تأییدشده",
30 -};
31 -const APPROVAL_FA = { Draft: "پیش‌نویس", Reviewed: "بررسی‌شده", Approved: "تأییدشده" };
32 -
33 -let toastTimer = null;
34 -function toast(msg, kind = "") {
35 - const el = $("#toast"); el.textContent = msg; el.className = `toast ${kind}`;
36 - clearTimeout(toastTimer); toastTimer = setTimeout(() => el.classList.add("hidden"), 4200);
37 -}
38 -
39 -/* ---------------- engine bridge ---------------- */
40 -function call(action, data = {}) {
41 - const resJson = BRIDGE.handle(action, JSON.stringify(data));
42 - const r = JSON.parse(resJson);
43 - if (!r.ok) { const e = new Error(r.error || "خطا"); e.issues = r.issues; e.status = r.status; throw e; }
44 - return r.data;
45 -}
46 -const actor = () => ($("#actor-input").value || "").trim();
47 -const sid = () => S.data.session.id;
48 -function applyPayload(p) { S.data = p; renderAll(); }
49 -
50 -function bufToB64(buf) {
51 - const bytes = new Uint8Array(buf); let bin = ""; const CH = 0x8000;
52 - for (let i = 0; i < bytes.length; i += CH) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CH));
53 - return btoa(bin);
54 -}
55 -function downloadB64(b64, filename) {
56 - const bin = atob(b64); const arr = new Uint8Array(bin.length);
57 - for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
58 - const blob = new Blob([arr], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
59 - const url = URL.createObjectURL(blob);
60 - const a = document.createElement("a"); a.href = url; a.download = filename;
61 - document.body.appendChild(a); a.click(); a.remove();
62 - setTimeout(() => URL.revokeObjectURL(url), 2000);
63 -}
64 -
65 -/* ---------------- boot ---------------- */
66 -const PYODIDE_VERSION = "0.26.4";
67 -const PYODIDE_BASES = [
68 - `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`,
69 - `https://unpkg.com/pyodide@${PYODIDE_VERSION}/`,
70 -];
71 -const VENDOR_WHEELS = ["et_xmlfile-2.0.0-py3-none-any.whl", "openpyxl-3.1.5-py2.py3-none-any.whl"];
72 -
73 -function bootProgress(pct, msg) {
74 - $("#boot-progress").style.width = pct + "%";
75 - if (msg) $("#boot-status").textContent = msg;
76 -}
77 -function loadScript(src) {
78 - return new Promise((resolve, reject) => {
79 - const s = document.createElement("script");
80 - s.src = src;
81 - s.onload = resolve;
82 - s.onerror = () => reject(new Error("بارگذاری اسکریپت ناموفق: " + src));
83 - document.head.appendChild(s);
84 - });
85 -}
86 -async function loadPyodideRuntime() {
87 - let lastErr = null;
88 - for (const base of PYODIDE_BASES) {
89 - try {
90 - if (typeof globalThis.loadPyodide !== "function") await loadScript(base + "pyodide.js");
91 - return await loadPyodide({ indexURL: base });
92 - } catch (err) { lastErr = err; }
93 - }
94 - throw lastErr || new Error("بارگذاری پایتون ناموفق بود.");
95 -}
96 -async function boot() {
97 - try {
98 - bootProgress(10, "در حال بارگذاری پایتون در مرورگر…");
99 - PY = await loadPyodideRuntime();
100 - bootProgress(45, "در حال نصب کتابخانهٔ اکسل…");
101 - const site = PY.runPython("import site; site.getsitepackages()[0]");
102 - for (const w of VENDOR_WHEELS) {
103 - const resp = await fetch(`vendor/${w}`);
104 - if (!resp.ok) throw new Error("بارگذاری کتابخانه ناموفق: " + w);
105 - PY.FS.writeFile(`/tmp/${w}`, new Uint8Array(await resp.arrayBuffer()));
106 - PY.runPython(`import zipfile; zipfile.ZipFile('/tmp/${w}').extractall('${site}')`);
107 - }
108 - bootProgress(70, "در حال بارگذاری موتور آرام…");
109 - PY.FS.mkdirTree("/pkg/aram_backend");
110 - const files = ["__init__.py", "pilot_workbook.py", "pilot_engine.py", "pilot_editing.py", "pilot_demo.py", "pilot_store.py"];
111 - for (const f of files) {
112 - const text = await (await fetch(`py/aram_backend/${f}`)).text();
113 - PY.FS.writeFile(`/pkg/aram_backend/${f}`, text);
114 - }
115 - const bridgeText = await (await fetch("bridge.py")).text();
116 - PY.FS.writeFile("/pkg/bridge.py", bridgeText);
117 - PY.runPython("import sys; sys.path.insert(0, '/pkg')");
118 - BRIDGE = PY.pyimport("bridge");
119 - bootProgress(95, "آماده‌سازی…");
120 - S.meta = call("meta");
121 - renderPolicy();
122 - S.ready = true;
123 - $("#upload-btn").disabled = false;
124 - $("#demo-btn").disabled = false;
125 - bootProgress(100, "آماده است");
126 - setTimeout(() => $("#boot").classList.add("hidden"), 350);
127 - } catch (err) {
128 - const el = $("#boot-error");
129 - el.classList.remove("hidden");
130 - el.textContent = "بارگذاری موتور ناموفق بود: " + (err?.message || err) +
131 - " — اتصال اینترنت را بررسی کنید و صفحه را دوباره بارگذاری کنید.";
132 - $("#boot-status").textContent = "خطا در بارگذاری";
133 - }
134 -}
135 -
136 -/* ---------------- landing ---------------- */
137 -function renderPolicy() {
138 - const m = S.meta, items = [];
139 - for (const st of m.rendered_statements)
140 - for (const [sec, sign] of Object.entries(m.section_policy[st]))
141 - 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>`);
142 - for (const st of m.deferred_statements)
143 - items.push(`<div class="policy-item muted">${esc(m.statement_labels_fa[st])} — نسخهٔ بعدی</div>`);
144 - $("#policy-grid").innerHTML = items.join("");
145 -}
146 -function showIssues(err) {
147 - const panel = $("#issues-panel");
148 - if (!err.issues?.length) { toast(err.message, "error"); return; }
149 - $("#issues-message").textContent = err.message;
150 - $("#issues-table tbody").innerHTML = err.issues.map((i) =>
151 - `<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>`).join("");
152 - panel.classList.remove("hidden");
153 - panel.scrollIntoView({ behavior: "smooth", block: "start" });
154 -}
155 -async function uploadFile(file) {
156 - $("#issues-panel").classList.add("hidden");
157 - $("#upload-progress").classList.remove("hidden"); $("#upload-btn").disabled = true;
158 - try {
159 - if (!file.name.toLowerCase().endsWith(".xlsx")) throw new Error("فقط فایل .xlsx پذیرفته می‌شود.");
160 - if (file.size > 25 * 1024 * 1024) throw new Error("حداکثر حجم مجاز ۲۵ مگابایت است.");
161 - const b64 = bufToB64(await file.arrayBuffer());
162 - enterWorkspace(call("upload", { filename: file.name, bytes_b64: b64 }));
163 - toast("فایل پذیرفته شد؛ پیش‌بررسی بدون خطا بود.", "success");
164 - } catch (err) { showIssues(err); }
165 - finally { $("#upload-progress").classList.add("hidden"); $("#upload-btn").disabled = false; $("#file-input").value = ""; }
166 -}
167 -function startDemo() {
168 - $("#issues-panel").classList.add("hidden"); $("#demo-btn").disabled = true;
169 - try {
170 - enterWorkspace(call("demo"));
171 - toast("دموی ساختگی آماده شد؛ دو حساب نگاشت‌نشده منتظر شما هستند.", "success");
172 - } catch (err) { toast(err.message, "error"); }
173 - finally { $("#demo-btn").disabled = false; }
174 -}
175 -
176 -/* ---------------- workspace ---------------- */
177 -function enterWorkspace(payload) {
178 - S.data = payload; S.tab = "dashboard"; S.filter = "all"; S.search = "";
179 - S.noteSearch = ""; S.expanded = new Set();
180 - $("#view-landing").classList.add("hidden");
181 - $("#view-workspace").classList.remove("hidden");
182 - $("#tabbar").classList.remove("hidden");
183 - $("#new-session-btn").classList.remove("hidden");
184 - $("#engine-version").textContent = payload.report.engine_version;
185 - renderAll(); window.scrollTo({ top: 0 });
186 -}
187 -function leaveWorkspace() {
188 - S.data = null;
189 - $("#view-workspace").classList.add("hidden");
190 - $("#view-landing").classList.remove("hidden");
191 - $("#tabbar").classList.add("hidden");
192 - $("#new-session-btn").classList.add("hidden");
193 -}
194 -function renderAll() {
195 - const { report, session } = S.data, c = report.company;
196 - const sourceChip = session.source === "demo"
197 - ? `<span class="chip demo">دموی ساختگی</span>`
198 - : `<span class="chip mono">${esc(session.filename)}</span>`;
199 - $("#session-info").innerHTML = `<div class="session-meta">
200 - <span class="company-name">${esc(c.name)}</span>
201 - <span class="chip">کد ${esc(c.code)}</span>
202 - <span class="chip">سال ${c.fiscal_year}</span>
203 - <span class="chip">${esc(c.unit || "واحد نامشخص")}</span>${sourceChip}</div>`;
204 - $("#status-chip").innerHTML = `<span class="status-chip status-${report.status.label}">${STATUS_FA[report.status.label]}</span>`;
205 - const ex = report.coverage.exception_count, badge = $("#mapping-badge");
206 - badge.textContent = ex; badge.className = `badge${ex === 0 ? " zero" : ""}`;
207 - document.querySelectorAll(".tabbar .tab").forEach((t) => t.classList.toggle("active", t.dataset.tab === S.tab));
208 - document.querySelectorAll(".tab-panel").forEach((p) => p.classList.add("hidden"));
209 - $(`#tab-${S.tab}`).classList.remove("hidden");
210 - ({ dashboard: renderDashboard, accounts: renderAccounts, notes: renderNotes, statements: renderStatements, more: renderMore })[S.tab]();
211 -}
212 -
213 -/* ---------------- dashboard ---------------- */
214 -function renderDashboard() {
215 - const { report } = S.data, t = report.totals, cov = report.coverage;
216 - const pct = cov.total_accounts ? Math.round((cov.mapped_accounts / cov.total_accounts) * 100) : 0;
217 - const totalCard = (label, v, hl = false) =>
218 - `<div class="total-card${hl ? " highlight" : ""}"><div class="label">${label}</div><div class="value${isNeg(v) ? " neg" : ""}">${fmt(v)}</div></div>`;
219 - const exceptions = report.exceptions.length ? `
220 - <div class="card" style="margin-top:14px">
221 - <h3 style="margin-top:0">صف استثنا (${report.exceptions.length})</h3>
222 - <div class="item-list">${report.exceptions.map((e) => `
223 - <div class="item-card">
224 - <div class="item-top">
225 - <div><div class="item-title">${esc(e.account_name)}</div><div class="item-code mono">${esc(e.account_code)} · سطر منبع ${e.source_row}</div></div>
226 - <span class="item-amount${isNeg(e.closing) ? " neg" : ""}">${fmt(e.closing)}</span>
227 - </div>
228 - <div class="item-sub"><span class="approval-chip approval-none">${esc(e.code)}</span> ${esc(e.details)}</div>
229 - <div class="item-actions"><button class="btn small primary" data-action="resolve-exception" data-code="${esc(e.account_code)}">رسیدگی و نگاشت</button></div>
230 - </div>`).join("")}</div>
231 - </div>` : `<div class="card" style="margin-top:14px"><b style="color:var(--green)">✓ هیچ استثنایی باقی نمانده است.</b></div>`;
232 - $("#tab-dashboard").innerHTML = `
233 - <div class="grid checks-grid">${report.checks.map((ch) => `
234 - <div class="check-card ${ch.passed ? "pass" : "fail"}">
235 - <div class="check-name">${esc(ch.name_fa)}</div>
236 - <div class="check-state">${ch.passed ? "✓ قبول" : "✗ رد"}</div>
237 - ${ch.amount !== null ? `<div class="check-amount">${fmt(ch.amount)}</div>` : ""}
238 - <div class="check-details">${esc(ch.details)}</div>
239 - </div>`).join("")}</div>
240 - <div class="card"><b>پوشش نگاشت:</b> ${cov.mapped_accounts} از ${cov.total_accounts} حساب (${pct}٪)
241 - <div class="coverage-bar-wrap" style="margin-top:8px"><div class="coverage-bar" style="width:${pct}%"></div></div></div>
242 - <div class="grid totals-grid">
243 - ${totalCard("جمع دارایی‌ها", t.assets)}${totalCard("جمع بدهی‌ها", t.liabilities)}
244 - ${totalCard("حقوق مالکانه", t.equity)}${totalCard("درآمدها", t.revenue)}
245 - ${totalCard("هزینه‌ها", t.expenses)}${totalCard("سود (زیان) دوره", t.profit, true)}
246 - </div>${exceptions}`;
247 -}
248 -
249 -/* ---------------- accounts ---------------- */
250 -function mappingSummary(a) {
251 - if (a.conflict) return `<span class="approval-chip approval-none">تعارض نگاشت</span>`;
252 - if (!a.mapping) return `<span class="approval-chip approval-none">بدون نگاشت</span>`;
253 - const m = a.mapping;
254 - const note = S.data.notes.find((n) => n.statement === m.statement && n.section === m.section && n.note_number === m.note_number && n.subnote_code === m.subnote_code);
255 - const label = note ? `${note.note_number} — ${note.note_title}` : m.note_number;
256 - return `<span class="mono">${esc(m.statement)}/${esc(m.section)}</span> · ${esc(label)} <span class="approval-chip approval-${esc(m.approval_status)}">${APPROVAL_FA[m.approval_status] || m.approval_status}</span>`;
257 -}
258 -function filteredAccounts() {
259 - const q = S.search.trim();
260 - return S.data.accounts.filter((a) => {
261 - if (S.filter === "unmapped" && a.mapping) return false;
262 - if (S.filter === "unapproved" && a.mapping?.approval_status === "Approved") return false;
263 - if (S.filter === "conflict" && !a.conflict) return false;
264 - if (q && !(a.code.includes(q) || a.name.includes(q))) return false;
265 - return true;
266 - });
267 -}
268 -function accountCard(a) {
269 - return `<div class="item-card">
270 - <div class="item-top">
271 - <div><div class="item-title">${esc(a.name)}</div><div class="item-code mono">${esc(a.code)} · کل ${esc(a.general_code)} · سطر ${a.source_row}</div></div>
272 - <span class="item-amount${isNeg(a.closing) ? " neg" : ""}">${fmt(a.closing)}</span>
273 - </div>
274 - <div class="item-sub">${mappingSummary(a)}</div>
275 - <div class="item-actions">
276 - <button class="btn small primary" data-action="map-account" data-code="${esc(a.code)}">${a.mapping ? "ویرایش نگاشت" : "تعیین مقصد"}</button>
277 - <button class="btn small" data-action="edit-account" data-code="${esc(a.code)}">ویرایش حساب</button>
278 - <button class="btn small" data-action="rename-account" data-code="${esc(a.code)}">تغییر کد</button>
279 - <button class="btn small danger" data-action="delete-account" data-code="${esc(a.code)}">حذف</button>
280 - </div>
281 - </div>`;
282 -}
283 -function updateAccList() {
284 - const list = $("#acc-list"); if (!list) return;
285 - const rows = filteredAccounts().map(accountCard).join("");
286 - list.innerHTML = rows || `<div class="card muted">حسابی با این فیلتر یافت نشد.</div>`;
287 -}
288 -function renderAccounts() {
289 - $("#tab-accounts").innerHTML = `
290 - <div class="table-toolbar">
291 - <input type="search" id="acc-search" placeholder="جستجوی کد یا نام…" value="${esc(S.search)}">
292 - <select id="acc-filter">
293 - <option value="all">همه</option><option value="unmapped">بدون نگاشت</option>
294 - <option value="unapproved">تأییدنشده</option><option value="conflict">تعارض</option>
295 - </select>
296 - <button class="btn accent small" data-action="add-account">+ حساب جدید</button>
297 - </div>
298 - <p class="muted">${S.data.accounts.length} حساب · مانده بدهکار-مثبت · هر تغییر در ردّ ممیزی ثبت می‌شود</p>
299 - <div class="item-list" id="acc-list"></div>`;
300 - $("#acc-filter").value = S.filter;
301 - $("#acc-search").oninput = (e) => { S.search = e.target.value; updateAccList(); };
302 - $("#acc-filter").onchange = (e) => { S.filter = e.target.value; updateAccList(); };
303 - updateAccList();
304 -}
305 -
306 -/* ---------------- account forms ---------------- */
307 -function accountFormHtml(a) {
308 - const v = a || { full_code: "", name: "", general_code: "", general_name: "", opening: "0", debit: "0", credit: "0", subsidiary_code: "", subsidiary_name: "", row_status: "Draft" };
309 - const codeField = a
310 - ? `<div class="form-field full"><span>کد حساب (ثابت)</span><input value="${esc(v.full_code)}" disabled></div>`
311 - : `<div class="form-field full"><span>کد کامل حساب *</span><input id="f-code" value="${esc(v.full_code)}" placeholder="مثلاً 1201"></div>`;
312 - return `<div class="form-grid">
313 - ${codeField}
314 - <div class="form-field full"><span>نام حساب *</span><input id="f-name" value="${esc(v.name)}"></div>
315 - <div class="form-field"><span>کد حساب کل *</span><input id="f-gencode" value="${esc(v.general_code)}"></div>
316 - <div class="form-field"><span>نام حساب کل *</span><input id="f-genname" value="${esc(v.general_name)}"></div>
317 - <div class="form-field"><span>کد معین (اختیاری)</span><input id="f-subcode" value="${esc(v.subsidiary_code)}"></div>
318 - <div class="form-field"><span>نام معین (اختیاری)</span><input id="f-subname" value="${esc(v.subsidiary_name)}"></div>
319 - <div class="form-field"><span>مانده ابتدای دوره</span><input id="f-opening" inputmode="decimal" value="${esc(v.opening)}"></div>
320 - <div class="form-field"><span>گردش بدهکار</span><input id="f-debit" inputmode="decimal" value="${esc(v.debit)}"></div>
321 - <div class="form-field"><span>گردش بستانکار</span><input id="f-credit" inputmode="decimal" value="${esc(v.credit)}"></div>
322 - <div class="form-field"><span>وضعیت سطر</span><select id="f-rowstatus">
323 - <option value="Draft">Draft</option><option value="Reviewed">Reviewed</option><option value="Approved">Approved</option>
324 - </select></div>
325 - <div class="form-field full"><span>مانده پایان دوره (محاسبه‌شده)</span><div class="computed-box">بدهکار+ = <b id="f-closing">—</b></div></div>
326 - </div>
327 - <p class="form-hint">مانده پایان دوره از «ابتدای دوره + بدهکار − بستانکار» محاسبه می‌شود؛ هیچ مبلغی حدس زده نمی‌شود.</p>
328 - <div class="form-actions">
329 - <button class="btn primary" data-action="submit-account" data-code="${a ? esc(a.code) : ""}">${a ? "ذخیره تغییرات" : "افزودن حساب"}</button>
330 - <button class="btn ghost" data-action="close-sheet">انصراف</button>
331 - </div>`;
332 -}
333 -function wireAccountForm(a) {
334 - $("#f-rowstatus").value = a?.row_status || "Draft";
335 - const calc = () => {
336 - const o = parseFloat($("#f-opening").value) || 0, d = parseFloat($("#f-debit").value) || 0, c = parseFloat($("#f-credit").value) || 0;
337 - $("#f-closing").textContent = fmt(String(o + d - c));
338 - };
339 - ["f-opening", "f-debit", "f-credit"].forEach((id) => $("#" + id).addEventListener("input", calc));
340 - calc();
341 -}
342 -function submitAccount(code) {
343 - const body = {
344 - sid: sid(), name: $("#f-name").value, general_code: $("#f-gencode").value, general_name: $("#f-genname").value,
345 - opening: $("#f-opening").value || "0", debit: $("#f-debit").value || "0", credit: $("#f-credit").value || "0",
346 - row_status: $("#f-rowstatus").value, subsidiary_code: $("#f-subcode").value, subsidiary_name: $("#f-subname").value,
347 - actor: actor(),
348 - };
349 - try {
350 - if (code) applyPayload(call("update_account", { ...body, code }));
351 - else applyPayload(call("add_account", { ...body, full_code: $("#f-code").value }));
352 - closeSheet(); toast(code ? "حساب ویرایش شد." : "حساب جدید افزوده شد؛ اکنون مقصدش را تعیین کنید.", "success");
353 - } catch (err) { toast(err.message, "error"); }
354 -}
355 -function openRename(a) {
356 - openSheet("تغییر کد حساب", `<div class="form-grid">
357 - <div class="form-field full"><span>کد فعلی</span><input value="${esc(a.code)}" disabled></div>
358 - <div class="form-field full"><span>کد جدید *</span><input id="f-newcode" placeholder="کد جدید"></div>
359 - </div><p class="form-hint">نگاشت این حساب به‌صورت خودکار به کد جدید منتقل می‌شود.</p>
360 - <div class="form-actions"><button class="btn primary" data-action="submit-rename" data-code="${esc(a.code)}">تغییر کد</button>
361 - <button class="btn ghost" data-action="close-sheet">انصراف</button></div>`);
362 -}
363 -function submitRename(code) {
364 - try {
365 - applyPayload(call("rename_account", { sid: sid(), code, new_code: $("#f-newcode").value, actor: actor() }));
366 - closeSheet(); toast("کد حساب تغییر کرد و نگاشت منتقل شد.", "success");
367 - } catch (err) { toast(err.message, "error"); }
368 -}
369 -function deleteAccount(code) {
370 - if (!confirm(`حساب ${code} و نگاشت آن حذف شود؟`)) return;
371 - try { applyPayload(call("delete_account", { sid: sid(), code, actor: actor() })); toast("حساب حذف شد.", "success"); }
372 - catch (err) { toast(err.message, "error"); }
373 -}
374 -
375 -/* ---------------- mapping form ---------------- */
376 -function noteOptions(statement, section) {
377 - return S.data.notes.filter((n) => n.statement === statement && n.section === section);
378 -}
379 -function openMapping(a) {
380 - const m = a.mapping || {};
381 - const statements = [...S.meta.rendered_statements, ...S.meta.deferred_statements];
382 - openSheet(`نگاشت حساب ${a.code}`, `<div class="form-grid">
383 - <div class="form-field full"><span>حساب</span><input value="${esc(a.code)} — ${esc(a.name)}" disabled></div>
384 - <div class="form-field"><span>صورت مالی</span><select id="m-statement">${statements.map((st) => `<option value="${st}">${esc(S.meta.statement_labels_fa[st])} (${st})</option>`).join("")}</select></div>
385 - <div class="form-field"><span>بخش</span><select id="m-section"></select></div>
386 - <div class="form-field full"><span>یادداشت / زیریادداشت</span><select id="m-note"></select></div>
387 - <div class="form-field"><span>وضعیت تأیید</span><select id="m-approval">
388 - <option value="Draft">Draft</option><option value="Reviewed">Reviewed</option><option value="Approved">Approved</option>
389 - </select></div>
390 - <div class="form-field"><span>نام بازبین</span><input id="m-reviewer" value="${esc(m.reviewer || actor())}" placeholder="برای Reviewed/Approved الزامی"></div>
391 - </div>
392 - <div class="form-actions">
393 - <button class="btn primary" data-action="submit-mapping" data-code="${esc(a.code)}">ثبت نگاشت</button>
394 - ${a.mapping ? `<button class="btn danger" data-action="clear-mapping" data-code="${esc(a.code)}">حذف نگاشت</button>` : ""}
395 - <button class="btn ghost" data-action="close-sheet">انصراف</button>
396 - </div>`, () => {
397 - const stSel = $("#m-statement"), secSel = $("#m-section"), noteSel = $("#m-note");
398 - stSel.value = m.statement || "BS";
399 - const fillSections = () => {
400 - const st = stSel.value;
401 - const sections = S.meta.section_policy[st] ? Object.keys(S.meta.section_policy[st])
402 - : [...new Set(S.data.notes.filter((n) => n.statement === st).map((n) => n.section))];
403 - secSel.innerHTML = sections.map((sec) => `<option value="${esc(sec)}">${esc(S.meta.section_labels_fa[sec] || sec)}</option>`).join("");
404 - if (m.section && sections.includes(m.section)) secSel.value = m.section;
405 - fillNotes();
406 - };
407 - const fillNotes = () => {
408 - const opts = noteOptions(stSel.value, secSel.value);
409 - noteSel.innerHTML = opts.length ? opts.map((n) => {
410 - const val = `${n.note_number}|${n.subnote_code}`;
411 - const label = `${n.note_number} — ${n.note_title}${n.subnote_code ? ` / ${n.subnote_code} ${n.subnote_title}` : ""}`;
412 - return `<option value="${esc(val)}">${esc(label)}</option>`;
413 - }).join("") : `<option value="">— یادداشتی تعریف نشده؛ ابتدا از زبانهٔ یادداشت‌ها اضافه کنید —</option>`;
414 - const cur = `${m.note_number}|${m.subnote_code || ""}`;
415 - if ([...noteSel.options].some((o) => o.value === cur)) noteSel.value = cur;
416 - };
417 - stSel.onchange = fillSections; secSel.onchange = fillNotes; fillSections();
418 - $("#m-approval").value = m.approval_status || "Draft";
419 - });
420 -}
421 -function submitMapping(code) {
422 - const noteVal = $("#m-note").value;
423 - if (!noteVal) { toast("برای این بخش یادداشتی نیست؛ ابتدا یادداشت اضافه کنید.", "error"); return; }
424 - const [note_number, subnote_code] = noteVal.split("|");
425 - const approval_status = $("#m-approval").value, reviewer = $("#m-reviewer").value.trim();
426 - if (approval_status !== "Draft" && !reviewer) { toast("برای Reviewed/Approved نام بازبین الزامی است.", "error"); return; }
427 - try {
428 - applyPayload(call("set_mapping", { sid: sid(), code, statement: $("#m-statement").value, section: $("#m-section").value, note_number, subnote_code: subnote_code || "", approval_status, reviewer, actor: actor() }));
429 - closeSheet(); toast(`نگاشت حساب ${code} ثبت شد.`, "success");
430 - } catch (err) { toast(err.message, "error"); }
431 -}
432 -function clearMapping(code) {
433 - try { applyPayload(call("clear_mapping", { sid: sid(), code, actor: actor() })); closeSheet(); toast("نگاشت حذف شد.", "success"); }
434 - catch (err) { toast(err.message, "error"); }
435 -}
436 -
437 -/* ---------------- notes ---------------- */
438 -function updateNoteList() {
439 - const list = $("#note-list"); if (!list) return;
440 - const q = S.noteSearch.trim();
441 - const notes = S.data.notes.filter((n) => !q || n.note_number.includes(q) || n.note_title.includes(q) || n.section.includes(q));
442 - const groups = {};
443 - for (const n of notes) { const k = `${n.statement}|${n.section}`; (groups[k] = groups[k] || []).push(n); }
444 - const usedKeys = new Set(S.data.accounts.filter((a) => a.mapping).map((a) => `${a.mapping.statement}|${a.mapping.section}|${a.mapping.note_number}|${a.mapping.subnote_code}`));
445 - let html = "";
446 - const order = Object.keys(groups).sort();
447 - if (!order.length) html = `<div class="card muted">یادداشتی یافت نشد.</div>`;
448 - for (const k of order) {
449 - const [st, sec] = k.split("|");
450 - html += `<div class="section-label">${esc(S.meta.statement_labels_fa[st] || st)} / ${esc(S.meta.section_labels_fa[sec] || sec)}</div><div class="item-list">`;
451 - for (const n of groups[k].sort((a, b) => a.note_number.localeCompare(b.note_number) || a.subnote_code.localeCompare(b.subnote_code))) {
452 - const key = `${n.statement}|${n.section}|${n.note_number}|${n.subnote_code}`;
453 - const inUse = usedKeys.has(key);
454 - html += `<div class="item-card">
455 - <div class="item-top">
456 - <div><div class="item-title">${esc(n.note_title)}${n.subnote_code ? ` <span class="muted">/ ${esc(n.subnote_code)} ${esc(n.subnote_title)}</span>` : ""}</div>
457 - <div class="item-code mono">یادداشت ${esc(n.note_number)}${n.subnote_code ? ` · زیریادداشت ${esc(n.subnote_code)}` : ""}</div></div>
458 - ${inUse ? `<span class="approval-chip approval-Approved">در استفاده</span>` : `<span class="approval-chip">آزاد</span>`}
459 - </div>
460 - <div class="item-actions">
461 - <button class="btn small" data-action="edit-note" data-key="${esc(key)}">ویرایش عنوان</button>
462 - <button class="btn small danger" data-action="delete-note" data-key="${esc(key)}" ${inUse ? 'title="ابتدا نگاشت‌های متصل را جابه‌جا کنید"' : ""}>حذف</button>
463 - </div>
464 - </div>`;
465 - }
466 - html += `</div>`;
467 - }
468 - list.innerHTML = html;
469 -}
470 -function renderNotes() {
471 - $("#tab-notes").innerHTML = `<div class="table-toolbar">
472 - <input type="search" id="note-search" placeholder="جستجوی یادداشت…" value="${esc(S.noteSearch)}">
473 - <button class="btn accent small" data-action="add-note">+ یادداشت جدید</button>
474 - </div><p class="muted">${S.data.notes.length} یادداشت/زیریادداشت · مقصدهای نگاشت از اینجا تعریف می‌شوند</p>
475 - <div id="note-list"></div>`;
476 - $("#note-search").oninput = (e) => { S.noteSearch = e.target.value; updateNoteList(); };
477 - updateNoteList();
478 -}
479 -function noteFormHtml(n) {
480 - const statements = [...S.meta.rendered_statements, ...S.meta.deferred_statements];
481 - const v = n || { statement: "BS", section: "Assets", note_number: "", note_title: "", subnote_code: "", subnote_title: "" };
482 - const keyLocked = !!n;
483 - return `<div class="form-grid">
484 - <div class="form-field"><span>صورت مالی</span><select id="n-statement" ${keyLocked ? "disabled" : ""}>${statements.map((st) => `<option value="${st}">${esc(S.meta.statement_labels_fa[st])} (${st})</option>`).join("")}</select></div>
485 - <div class="form-field"><span>بخش *</span><input id="n-section" value="${esc(v.section)}" ${keyLocked ? "disabled" : ""} placeholder="Assets / Liabilities / …"></div>
486 - <div class="form-field"><span>شماره یادداشت *</span><input id="n-number" value="${esc(v.note_number)}" ${keyLocked ? "disabled" : ""}></div>
487 - <div class="form-field"><span>کد زیریادداشت (اختیاری)</span><input id="n-subcode" value="${esc(v.subnote_code)}" ${keyLocked ? "disabled" : ""}></div>
488 - <div class="form-field full"><span>عنوان یادداشت *</span><input id="n-title" value="${esc(v.note_title)}"></div>
489 - <div class="form-field full"><span>عنوان زیریادداشت</span><input id="n-subtitle" value="${esc(v.subnote_title)}"></div>
490 - </div>
491 - ${keyLocked ? `<p class="form-hint">کلید یادداشت ثابت است؛ فقط عنوان‌ها ویرایش می‌شوند.</p>` : `<p class="form-hint">برای زیریادداشت، کد و عنوان آن را پر کنید. بخش‌های استاندارد: Assets، Liabilities، Equity، Revenue، Expenses.</p>`}
492 - <div class="form-actions">
493 - <button class="btn primary" data-action="submit-note" data-key="${n ? esc(`${n.statement}|${n.section}|${n.note_number}|${n.subnote_code}`) : ""}">${n ? "ذخیره عنوان" : "افزودن یادداشت"}</button>
494 - <button class="btn ghost" data-action="close-sheet">انصراف</button>
495 - </div>`;
496 -}
497 -function submitNote(key) {
498 - const body = {
499 - sid: sid(), statement: $("#n-statement").value, section: $("#n-section").value,
500 - note_number: $("#n-number").value, note_title: $("#n-title").value,
501 - subnote_code: $("#n-subcode").value, subnote_title: $("#n-subtitle").value, actor: actor(),
502 - };
503 - try {
504 - if (key) { const [st, sec, num, sub] = key.split("|"); Object.assign(body, { statement: st, section: sec, note_number: num, subnote_code: sub }); }
505 - applyPayload(call(key ? "update_note" : "add_note", body));
506 - closeSheet(); toast(key ? "عنوان یادداشت ویرایش شد." : "یادداشت جدید افزوده شد.", "success");
507 - } catch (err) { toast(err.message, "error"); }
508 -}
509 -function deleteNote(key) {
510 - const [statement, section, note_number, subnote_code] = key.split("|");
511 - if (!confirm("این یادداشت حذف شود؟")) return;
512 - try {
513 - applyPayload(call("delete_note", { sid: sid(), statement, section, note_number, subnote_code, actor: actor() }));
514 - toast("یادداشت حذف شد.", "success");
515 - } catch (err) { toast(err.message, "error"); }
516 -}
517 -
518 -/* ---------------- statements ---------------- */
519 -function renderStatements() {
520 - const code = S.statementView;
521 - const { report } = S.data, st = report.statements[code], c = report.company;
522 - const sections = st.sections.map((sec) => `
523 - <div class="statement-section">
524 - <div class="section-head"><span>${esc(sec.label_fa)}</span><span class="note-total${isNeg(sec.total) ? " neg" : ""}">${fmt(sec.total)}</span></div>
525 - ${sec.lines.map((line) => {
526 - const key = `${code}|${sec.name}|${line.note_number}|${line.subnote_code}`;
527 - const open = S.expanded.has(key);
528 - const title = `${line.note_title}${line.subnote_code ? ` / ${line.subnote_code} ${line.subnote_title}` : ""}`;
529 - return `<div class="note-line" data-action="toggle-line" data-key="${esc(key)}">
530 - <span class="note-title"><span class="note-number">${esc(line.note_number)}</span>${esc(title)} <span class="muted">${open ? "▾" : "◂"} ${line.accounts.length} حساب</span></span>
531 - <span class="note-total${isNeg(line.total) ? " neg" : ""}">${fmt(line.total)}</span></div>
532 - ${open ? `<div class="drill"><div class="table-wrap"><table>
533 - <thead><tr><th>کد</th><th>حساب</th><th class="num">مانده دفتر</th><th class="num">نمایشی</th><th>سطر</th><th>تأیید</th></tr></thead>
534 - <tbody>${line.accounts.map((a) => `<tr><td class="mono">${esc(a.code)}</td><td>${esc(a.name)}</td>${numCell(a.closing)}${numCell(a.display)}<td class="num">${a.source_row}</td><td><span class="approval-chip approval-${esc(a.approval_status)}">${APPROVAL_FA[a.approval_status] || a.approval_status}</span></td></tr>`).join("")}</tbody>
535 - </table></div></div>` : ""}`;
536 - }).join("") || `<div class="note-line muted">رقمی در این بخش منظور نشده است.</div>`}
537 - </div>`).join("");
538 - const grand = code === "BS"
539 - ? `<div class="statement-total"><span>جمع دارایی‌ها</span><span class="note-total">${fmt(report.totals.assets)}</span></div>
540 - <div class="statement-total"><span>جمع بدهی‌ها و حقوق مالکانه</span><span class="note-total">${fmt(report.totals.liabilities_and_equity)}</span></div>`
541 - : `<div class="statement-total"><span>سود (زیان) دوره</span><span class="note-total${isNeg(report.totals.profit) ? " neg" : ""}">${fmt(report.totals.profit)}</span></div>`;
542 - $("#tab-statements").innerHTML = `
543 - <div class="statement-tools">
544 - <div class="segmented">
545 - <button data-action="view-statement" data-code="BS" class="${code === "BS" ? "active" : ""}">ترازنامه</button>
546 - <button data-action="view-statement" data-code="IS" class="${code === "IS" ? "active" : ""}">سود و زیان</button>
547 - </div>
548 - <button class="btn small ghost" data-action="print">🖨 چاپ</button>
549 - </div>
550 - <div class="statement-paper">
551 - <div class="statement-head"><h2>${esc(st.label_fa)}</h2>
552 - <div class="sub">${esc(c.name)} — سال مالی ${c.fiscal_year} — به ${esc(c.unit || "واحد نامشخص")}</div>
553 - <span class="draft-watermark">${STATUS_FA[report.status.label]} · پیش‌نویس کاری، نه صورت مالی رسمی</span></div>
554 - ${sections}${grand}
555 - ${code === "BS" ? `<p class="muted">سود دوره (${fmt(report.totals.profit)}) از طریق معادلهٔ حسابداری در حقوق مالکانه کنترل می‌شود.</p>` : ""}
556 - </div>`;
557 -}
558 -
559 -/* ---------------- more / audit / export ---------------- */
560 -function renderMore() {
561 - const { report, session, audit_trail: trail } = S.data, c = report.company;
562 - const prov = (k, v, mono = false) => `<div class="prov-item"><div class="k">${k}</div><div class="v${mono ? " mono" : ""}">${esc(v)}</div></div>`;
563 - $("#tab-more").innerHTML = `
564 - <div class="card" style="margin-bottom:14px">
565 - <h3 style="margin-top:0">شرکت و سال مالی</h3>
566 - <div class="provenance-grid">
567 - ${prov("نام", c.name)}${prov("کد", c.code, true)}${prov("سال مالی", c.fiscal_year)}
568 - ${prov("واحد", c.unit || "—")}${prov("ارز", c.currency || "—")}
569 - </div>
570 - <button class="btn block" data-action="edit-company">ویرایش اطلاعات شرکت</button>
571 - </div>
572 - <div class="card" style="margin-bottom:14px">
573 - <h3 style="margin-top:0">خروجی و ذخیره</h3>
574 - <div class="action-stack">
575 - <button class="btn primary block" data-action="export-report">⬇ دانلود گزارش اکسل (صورت‌ها + کنترل‌ها + ردّ ممیزی)</button>
576 - <button class="btn accent block" data-action="export-workspace">💾 ذخیرهٔ کارگاه (قابل آپلود مجدد برای ادامهٔ کار)</button>
577 - <button class="btn danger block" data-action="delete-session">حذف جلسه از حافظه</button>
578 - </div>
579 - <p class="muted">جلسه‌ها فقط در حافظهٔ مرورگر هستند؛ «ذخیرهٔ کارگاه» را دانلود کنید و بعداً دوباره آپلود کنید تا کار ادامه یابد.</p>
580 - </div>
581 - <div class="card" style="margin-bottom:14px">
582 - <h3 style="margin-top:0">شناسنامه</h3>
583 - <div class="provenance-grid">
584 - ${prov("SHA-256 فایل ورودی", report.source_sha256, true)}
585 - ${prov("زمان ایجاد (UTC)", session.created_at, true)}
586 - ${prov("منبع", session.source === "demo" ? "دموی ساختگی" : `فایل ${session.filename}`)}
587 - ${prov("نسخهٔ موتور", report.engine_version, true)}
588 - </div>
589 - </div>
590 - <div class="card">
591 - <h3 style="margin-top:0">ردّ ممیزی (${trail.length})</h3>
592 - ${trail.length ? `<div class="table-wrap"><table>
593 - <thead><tr><th>زمان</th><th>کاربر</th><th>حساب</th><th>اقدام</th><th>قبل</th><th>بعد</th></tr></thead>
594 - <tbody>${trail.map((e) => `<tr><td class="mono">${esc(e.at)}</td><td>${esc(e.actor)}</td><td class="mono">${esc(e.account_code)}</td><td>${esc(e.action)}</td><td class="mono">${esc(e.before)}</td><td class="mono">${esc(e.after)}</td></tr>`).join("")}</tbody>
595 - </table></div>` : `<p class="muted">هنوز تغییری ثبت نشده است.</p>`}
596 - </div>`;
597 -}
598 -function openCompany() {
599 - const c = S.data.report.company;
600 - openSheet("ویرایش شرکت", `<div class="form-grid">
601 - <div class="form-field full"><span>نام شرکت *</span><input id="c-name" value="${esc(c.name)}"></div>
602 - <div class="form-field"><span>کد شرکت *</span><input id="c-code" value="${esc(c.code)}"></div>
603 - <div class="form-field"><span>سال مالی *</span><input id="c-year" inputmode="numeric" value="${c.fiscal_year}"></div>
604 - <div class="form-field"><span>واحد پول</span><input id="c-unit" value="${esc(c.unit)}"></div>
605 - <div class="form-field"><span>ارز</span><input id="c-currency" value="${esc(c.currency)}"></div>
606 - <div class="form-field full"><span>تهیه‌کننده</span><input id="c-prepared" value="${esc(c.prepared_by)}"></div>
607 - </div>
608 - <div class="form-actions"><button class="btn primary" data-action="submit-company">ذخیره</button>
609 - <button class="btn ghost" data-action="close-sheet">انصراف</button></div>`);
610 -}
611 -function submitCompany() {
612 - try {
613 - applyPayload(call("update_company", { sid: sid(), name: $("#c-name").value, code: $("#c-code").value, fiscal_year: parseInt($("#c-year").value, 10), unit: $("#c-unit").value, currency: $("#c-currency").value, prepared_by: $("#c-prepared").value, actor: actor() }));
614 - closeSheet(); toast("اطلاعات شرکت ویرایش شد.", "success");
615 - } catch (err) { toast(err.message, "error"); }
616 -}
617 -function exportReport() {
618 - try { const r = call("export_report", { sid: sid() }); downloadB64(r.bytes_b64, r.filename); toast("گزارش اکسل دانلود شد.", "success"); }
619 - catch (err) { toast(err.message, "error"); }
620 -}
621 -function exportWorkspace() {
622 - try { const r = call("export_workspace", { sid: sid() }); downloadB64(r.bytes_b64, r.filename); toast("ذخیرهٔ کارگاه دانلود شد.", "success"); }
623 - catch (err) { toast(err.message, "error"); }
624 -}
625 -function deleteSession() {
626 - if (!confirm("جلسه از حافظهٔ مرورگر حذف شود؟ فایل‌های دانلودشده باقی می‌مانند.")) return;
627 - try { call("delete_session", { sid: sid() }); leaveWorkspace(); toast("جلسه حذف شد.", "success"); }
628 - catch (err) { toast(err.message, "error"); }
629 -}
630 -
631 -/* ---------------- bottom sheet ---------------- */
632 -function openSheet(title, html, onMount) {
633 - $("#sheet-title").textContent = title;
634 - $("#sheet-body").innerHTML = html;
635 - $("#sheet").classList.remove("hidden");
636 - $("#sheet-backdrop").classList.remove("hidden");
637 - document.body.style.overflow = "hidden";
638 - if (onMount) onMount();
639 -}
640 -function closeSheet() {
641 - $("#sheet").classList.add("hidden");
642 - $("#sheet-backdrop").classList.add("hidden");
643 - document.body.style.overflow = "";
644 -}
645 -
646 -/* ---------------- events ---------------- */
647 -document.addEventListener("click", (e) => {
648 - const el = e.target.closest("[data-action]");
649 - if (!el) return;
650 - const { action, code, key } = el.dataset;
651 - const findAcc = (c) => S.data.accounts.find((a) => a.code === c);
652 - if (action === "close-sheet") closeSheet();
653 - else if (action === "add-account") openSheet("افزودن حساب جدید", accountFormHtml(null), () => wireAccountForm(null));
654 - else if (action === "edit-account") { const a = findAcc(code); openSheet(`ویرایش حساب ${code}`, accountFormHtml(a), () => wireAccountForm(a)); }
655 - else if (action === "submit-account") submitAccount(code);
656 - else if (action === "rename-account") openRename(findAcc(code));
657 - else if (action === "submit-rename") submitRename(code);
658 - else if (action === "delete-account") deleteAccount(code);
659 - else if (action === "map-account") openMapping(findAcc(code));
660 - else if (action === "submit-mapping") submitMapping(code);
661 - else if (action === "clear-mapping") clearMapping(code);
662 - else if (action === "resolve-exception") { S.tab = "accounts"; renderAll(); openMapping(findAcc(code)); }
663 - else if (action === "add-note") openSheet("افزودن یادداشت جدید", noteFormHtml(null), () => { $("#n-statement").value = "BS"; });
664 - else if (action === "edit-note") { const n = S.data.notes.find((x) => `${x.statement}|${x.section}|${x.note_number}|${x.subnote_code}` === key); openSheet("ویرایش یادداشت", noteFormHtml(n), () => { $("#n-statement").value = n.statement; }); }
665 - else if (action === "submit-note") submitNote(key);
666 - else if (action === "delete-note") deleteNote(key);
667 - else if (action === "view-statement") { S.statementView = code; renderStatements(); }
668 - else if (action === "toggle-line") { S.expanded.has(key) ? S.expanded.delete(key) : S.expanded.add(key); renderStatements(); }
669 - else if (action === "print") window.print();
670 - else if (action === "edit-company") openCompany();
671 - else if (action === "submit-company") submitCompany();
672 - else if (action === "export-report") exportReport();
673 - else if (action === "export-workspace") exportWorkspace();
674 - else if (action === "delete-session") deleteSession();
675 -});
676 -
677 -document.addEventListener("DOMContentLoaded", () => {
678 - $("#actor-input").value = localStorage.getItem("aram-actor") || "";
679 - $("#actor-input").addEventListener("input", (e) => localStorage.setItem("aram-actor", e.target.value));
680 - $("#upload-btn").addEventListener("click", () => $("#file-input").click());
681 - $("#file-input").addEventListener("change", (e) => { if (e.target.files[0]) uploadFile(e.target.files[0]); });
682 - $("#demo-btn").addEventListener("click", startDemo);
683 - $("#new-session-btn").addEventListener("click", leaveWorkspace);
684 - $("#sheet-close").addEventListener("click", closeSheet);
685 - $("#sheet-backdrop").addEventListener("click", closeSheet);
686 - $("#tabbar").addEventListener("click", (e) => {
687 - const tab = e.target.closest(".tab");
688 - if (!tab || !S.data) return;
689 - S.tab = tab.dataset.tab; renderAll(); window.scrollTo({ top: 0 });
690 - });
691 - boot();
692 -});
webapp/bridge.py deleted
-207
@@ -1,207 +0,0 @@
1 -"""JSON-in / JSON-out bridge that runs the exact Aram engine in the browser.
2 -
3 -This mirrors backend/src/aram_backend/pilot_api.py but without FastAPI, so the
4 -identical, tested engine/store/editing code runs client-side under Pyodide.
5 -Everything stays in memory; the durable artifacts are the exported workbooks.
6 -"""
7 -
8 -from __future__ import annotations
9 -
10 -import base64
11 -import json
12 -import re
13 -
14 -from aram_backend.pilot_demo import build_demo_workbook
15 -from aram_backend.pilot_editing import (
16 - DuplicateAccountError,
17 - DuplicateNoteError,
18 - EditingError,
19 - NoteInUseError,
20 - UnknownNoteError,
21 - make_company,
22 - make_note,
23 -)
24 -from aram_backend.pilot_engine import (
25 - DEFERRED_STATEMENTS,
26 - RENDERED_STATEMENTS,
27 - SECTION_LABELS_FA,
28 - SECTION_POLICY,
29 - STATEMENT_LABELS_FA,
30 - PilotModelError,
31 - accounts_table,
32 - build_report,
33 - export_report_workbook,
34 - export_working_workbook,
35 - notes_table,
36 - parse_pilot_model,
37 -)
38 -from aram_backend.pilot_store import (
39 - InvalidApprovalError,
40 - PilotSessionStore,
41 - UnknownAccountError,
42 - UnknownSessionError,
43 - UnknownTargetError,
44 -)
45 -
46 -store = PilotSessionStore()
47 -
48 -
49 -def _payload(session_id: str) -> dict:
50 - session, working, trail = store.snapshot(session_id)
51 - report = build_report(working, working.mappings)
52 - return {
53 - "session": {
54 - "id": session.id, "created_at": session.created_at,
55 - "source": session.source, "filename": session.filename,
56 - },
57 - "report": report,
58 - "accounts": accounts_table(working, working.mappings),
59 - "notes": notes_table(working),
60 - "audit_trail": trail,
61 - }
62 -
63 -
64 -def _meta() -> dict:
65 - return {
66 - "rendered_statements": list(RENDERED_STATEMENTS),
67 - "deferred_statements": list(DEFERRED_STATEMENTS),
68 - "statement_labels_fa": STATEMENT_LABELS_FA,
69 - "section_policy": SECTION_POLICY,
70 - "section_labels_fa": SECTION_LABELS_FA,
71 - "contract": "Pilot workbook v0.1",
72 - "disclaimer_fa": "خروجی این ابزار پیش‌نویس کاری برای بررسی است، نه صورت مالی رسمی.",
73 - }
74 -
75 -
76 -def _create(data: bytes, source: str, filename: str) -> dict:
77 - model = parse_pilot_model(data)
78 - session = store.create(model, source=source, filename=filename)
79 - return _payload(session.id)
80 -
81 -
82 -def _export(session_id: str, kind: str) -> dict:
83 - session = store.get(session_id)
84 - _, working, trail = store.snapshot(session_id)
85 - safe = re.sub(r"[^A-Za-z0-9_-]", "", working.company.code) or "session"
86 - if kind == "workspace":
87 - data = export_working_workbook(working)
88 - name = f"aram-workspace-{safe}-{working.company.fiscal_year}.xlsx"
89 - else:
90 - report = build_report(working, working.mappings)
91 - data = export_report_workbook(working, working.mappings, report, trail, session.source)
92 - name = f"aram-pilot-{safe}-{working.company.fiscal_year}.xlsx"
93 - return {"filename": name, "bytes_b64": base64.b64encode(data).decode("ascii")}
94 -
95 -
96 -def _dispatch(action: str, d: dict):
97 - if action == "meta":
98 - return _meta()
99 - if action == "demo":
100 - return _create(build_demo_workbook(), "demo", "aram-synthetic-demo.xlsx")
101 - if action == "upload":
102 - raw = base64.b64decode(d["bytes_b64"])
103 - if not raw:
104 - raise EditingError("فایل خالی است.")
105 - return _create(raw, "upload", d.get("filename", "upload.xlsx"))
106 - if action == "get":
107 - return _payload(d["sid"])
108 - if action == "delete_session":
109 - store.delete(d["sid"])
110 - return {"deleted": d["sid"]}
111 - if action == "set_mapping":
112 - store.set_mapping(
113 - d["sid"], d["code"], statement=d["statement"].strip(), section=d["section"].strip(),
114 - note_number=d["note_number"].strip(), subnote_code=d.get("subnote_code", "").strip(),
115 - approval_status=d.get("approval_status", "Draft"), reviewer=d.get("reviewer", ""),
116 - actor=d.get("actor", ""),
117 - )
118 - return _payload(d["sid"])
119 - if action == "clear_mapping":
120 - store.clear_mapping(d["sid"], d["code"], actor=d.get("actor", ""))
121 - return _payload(d["sid"])
122 - if action == "add_account":
123 - store.add_account(
124 - d["sid"], full_code=d["full_code"], name=d["name"], general_code=d["general_code"],
125 - general_name=d["general_name"], opening=d.get("opening", "0"), debit=d.get("debit", "0"),
126 - credit=d.get("credit", "0"), source_row=d.get("source_row"), row_status=d.get("row_status", "Draft"),
127 - subsidiary_code=d.get("subsidiary_code", ""), subsidiary_name=d.get("subsidiary_name", ""),
128 - actor=d.get("actor", ""),
129 - )
130 - return _payload(d["sid"])
131 - if action == "update_account":
132 - store.update_account(
133 - d["sid"], d["code"], name=d["name"], general_code=d["general_code"],
134 - general_name=d["general_name"], opening=d.get("opening", "0"), debit=d.get("debit", "0"),
135 - credit=d.get("credit", "0"), row_status=d.get("row_status", "Draft"),
136 - subsidiary_code=d.get("subsidiary_code", ""), subsidiary_name=d.get("subsidiary_name", ""),
137 - actor=d.get("actor", ""),
138 - )
139 - return _payload(d["sid"])
140 - if action == "rename_account":
141 - store.rename_account(d["sid"], d["code"], d["new_code"], actor=d.get("actor", ""))
142 - return _payload(d["sid"])
143 - if action == "delete_account":
144 - store.delete_account(d["sid"], d["code"], actor=d.get("actor", ""))
145 - return _payload(d["sid"])
146 - if action == "add_note":
147 - note = make_note(
148 - statement=d["statement"], section=d["section"], note_number=d["note_number"],
149 - note_title=d["note_title"], subnote_code=d.get("subnote_code", ""),
150 - subnote_title=d.get("subnote_title", ""),
151 - )
152 - store.add_note(d["sid"], note, actor=d.get("actor", ""))
153 - return _payload(d["sid"])
154 - if action == "update_note":
155 - key = (d["statement"].strip(), d["section"].strip(), d["note_number"].strip(), d.get("subnote_code", "").strip())
156 - note = make_note(
157 - statement=d["statement"], section=d["section"], note_number=d["note_number"],
158 - note_title=d["note_title"], subnote_code=d.get("subnote_code", ""),
159 - subnote_title=d.get("subnote_title", ""),
160 - )
161 - store.update_note(d["sid"], key, note, actor=d.get("actor", ""))
162 - return _payload(d["sid"])
163 - if action == "delete_note":
164 - key = (d["statement"].strip(), d["section"].strip(), d["note_number"].strip(), d.get("subnote_code", "").strip())
165 - store.delete_note(d["sid"], key, actor=d.get("actor", ""))
166 - return _payload(d["sid"])
167 - if action == "update_company":
168 - company = make_company(
169 - code=d["code"], name=d["name"], fiscal_year=d["fiscal_year"],
170 - currency=d.get("currency", ""), unit=d.get("unit", ""),
171 - prepared_by=d.get("prepared_by", ""), status=d.get("status", "Draft"),
172 - )
173 - store.update_company(d["sid"], company, actor=d.get("actor", ""))
174 - return _payload(d["sid"])
175 - if action == "export_report":
176 - return _export(d["sid"], "report")
177 - if action == "export_workspace":
178 - return _export(d["sid"], "workspace")
179 - raise EditingError(f"اقدام ناشناخته: {action}")
180 -
181 -
182 -def handle(action: str, data_json: str = "") -> str:
183 - """Single entry point called from JavaScript. Always returns a JSON string."""
184 - try:
185 - data = json.loads(data_json) if data_json else {}
186 - except json.JSONDecodeError:
187 - data = {}
188 - try:
189 - return json.dumps({"ok": True, "data": _dispatch(action, data)}, ensure_ascii=False)
190 - except PilotModelError as exc:
191 - return json.dumps({
192 - "ok": False,
193 - "error": "فایل با قرارداد پایلوت v0.1 سازگار نیست؛ خطاهای زیر را رفع کنید.",
194 - "issues": [
195 - {"severity": i.severity, "code": i.code, "sheet": i.sheet,
196 - "row": i.row, "field": i.field, "message": i.message}
197 - for i in exc.issues
198 - ],
199 - }, ensure_ascii=False)
200 - except (UnknownSessionError, UnknownAccountError, UnknownNoteError) as exc:
201 - return json.dumps({"ok": False, "error": str(exc) or "مورد یافت نشد.", "status": 404}, ensure_ascii=False)
202 - except (DuplicateAccountError, DuplicateNoteError, NoteInUseError) as exc:
203 - return json.dumps({"ok": False, "error": str(exc), "status": 409}, ensure_ascii=False)
204 - except (EditingError, UnknownTargetError, InvalidApprovalError) as exc:
205 - return json.dumps({"ok": False, "error": str(exc), "status": 422}, ensure_ascii=False)
206 - except Exception as exc: # noqa: BLE001 - surface a safe message to the UI
207 - return json.dumps({"ok": False, "error": f"خطای غیرمنتظره: {exc}"}, ensure_ascii=False)
webapp/index.html deleted
-139
@@ -1,139 +0,0 @@
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, viewport-fit=cover">
6 - <meta name="theme-color" content="#0a1220">
7 - <meta name="mobile-web-app-capable" content="yes">
8 - <meta name="apple-mobile-web-app-capable" content="yes">
9 - <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
10 - <title>آرام — میز کار پایلوت</title>
11 - <link rel="stylesheet" href="styles.css">
12 - <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>">
13 -</head>
14 -<body>
15 - <!-- Engine loading overlay -->
16 - <div id="boot" class="boot">
17 - <div class="boot-card">
18 - <div class="boot-mark">آ</div>
19 - <h2>آرام — میز کار پایلوت</h2>
20 - <p id="boot-status">در حال بارگذاری موتور محاسباتی…</p>
21 - <div class="boot-bar"><div id="boot-progress" class="boot-progress"></div></div>
22 - <p class="muted">نسخهٔ مرورگری — همان موتور تست‌شده، بدون نیاز به سرور. بار اول چند ثانیه طول می‌کشد.</p>
23 - <p id="boot-error" class="boot-error hidden"></p>
24 - </div>
25 - </div>
26 -
27 - <header class="topbar">
28 - <div class="brand">
29 - <span class="brand-mark">آ</span>
30 - <div class="brand-text">
31 - <h1>آرام — میز کار پایلوت</h1>
32 - <p class="tagline">از اکسل منبع تا پیش‌نویس صورت‌های مالی، با ردیابی کامل</p>
33 - </div>
34 - </div>
35 - <div class="topbar-actions">
36 - <label class="actor-field" title="نام شما در ردّ ممیزی ثبت می‌شود">
37 - <span class="actor-label">نام کاربر:</span>
38 - <input id="actor-input" type="text" placeholder="نام بازبین" autocomplete="name">
39 - </label>
40 - <button id="new-session-btn" class="btn ghost small hidden">جلسهٔ جدید</button>
41 - </div>
42 - </header>
43 -
44 - <main id="main">
45 - <section id="view-landing">
46 - <div class="hero">
47 - <h2>صورت‌های مالیِ قابل‌ردیابی، برای هر شرکت</h2>
48 - <p>
49 - فایل پایلوت (قرارداد v0.1) را وارد کنید یا دمو را اجرا کنید؛ حساب‌ها و یادداشت‌ها را
50 - آزادانه اضافه، ویرایش یا جایگزین کنید، نگاشت را تعیین کنید و ترازنامه و سود و زیان را
51 - با کنترل‌های تراز و معادلهٔ حسابداری بسازید — هر رقم تا سطر منبع قابل ردیابی است.
52 - </p>
53 - <p class="safety-note">
54 - هیچ مبلغی حدس زده نمی‌شود · دادهٔ منبع تغییر نمی‌کند · خروجی «پیش‌نویس کاری» است، نه صورت مالی رسمی
55 - </p>
56 - </div>
57 -
58 - <div class="action-cards">
59 - <div class="card action-card">
60 - <div class="action-icon">📥</div>
61 - <h3>ورود فایل پایلوت</h3>
62 - <p>فایل <span class="mono">.xlsx</span> مطابق قالب v0.1 (حداکثر ۲۵ مگابایت)</p>
63 - <input id="file-input" type="file" accept=".xlsx" class="hidden">
64 - <button id="upload-btn" class="btn primary" disabled>انتخاب و بررسی فایل</button>
65 - </div>
66 - <div class="card action-card">
67 - <div class="action-icon">🧪</div>
68 - <h3>دموی ساختگی</h3>
69 - <p>دادهٔ غیرواقعی و تراز، با دو حساب نگاشت‌نشده برای تجربهٔ گردش کار کامل</p>
70 - <button id="demo-btn" class="btn accent" disabled>اجرای دمو</button>
71 - </div>
72 - </div>
73 -
74 - <div id="upload-progress" class="card progress-card hidden">
75 - <span class="spinner"></span> در حال پیش‌بررسی فایل…
76 - </div>
77 -
78 - <div id="issues-panel" class="card issues-card hidden">
79 - <h3>❌ فایل رد شد — خطاهای پیش‌بررسی</h3>
80 - <p id="issues-message"></p>
81 - <div class="table-wrap">
82 - <table id="issues-table">
83 - <thead><tr><th>برگه</th><th>سطر</th><th>فیلد</th><th>کد خطا</th><th>شرح</th></tr></thead>
84 - <tbody></tbody>
85 - </table>
86 - </div>
87 - </div>
88 -
89 - <div class="card info-card">
90 - <h3>سیاست صریح علامت‌ها (بدون حدس)</h3>
91 - <div class="policy-grid" id="policy-grid"></div>
92 - <p class="muted">
93 - مانده‌ها بدهکار-مثبت هستند؛ نمایش = علامت × مانده. بخش‌های ناشناخته به‌جای حدس، به صف استثنا می‌روند.
94 - مقصدهای CF و EQ در این نسخه رندر نمی‌شوند و شفاف گزارش می‌شوند.
95 - </p>
96 - </div>
97 - </section>
98 -
99 - <section id="view-workspace" class="hidden">
100 - <div class="session-bar card">
101 - <div id="session-info"></div>
102 - <div id="status-chip"></div>
103 - </div>
104 - <div id="tab-dashboard" class="tab-panel"></div>
105 - <div id="tab-accounts" class="tab-panel hidden"></div>
106 - <div id="tab-notes" class="tab-panel hidden"></div>
107 - <div id="tab-statements" class="tab-panel hidden"></div>
108 - <div id="tab-more" class="tab-panel hidden"></div>
109 - </section>
110 - </main>
111 -
112 - <nav class="tabbar hidden" id="tabbar" aria-label="ناوبری بخش‌ها">
113 - <button data-tab="dashboard" class="tab active"><span class="tab-ico">🏠</span><span>داشبورد</span></button>
114 - <button data-tab="accounts" class="tab"><span class="tab-ico">📒</span><span>حساب‌ها</span><span id="mapping-badge" class="badge"></span></button>
115 - <button data-tab="notes" class="tab"><span class="tab-ico">🗂️</span><span>یادداشت‌ها</span></button>
116 - <button data-tab="statements" class="tab"><span class="tab-ico">📑</span><span>صورت‌ها</span></button>
117 - <button data-tab="more" class="tab"><span class="tab-ico">⚙️</span><span>بیشتر</span></button>
118 - </nav>
119 -
120 - <div id="sheet-backdrop" class="sheet-backdrop hidden"></div>
121 - <div id="sheet" class="sheet hidden" role="dialog" aria-modal="true">
122 - <div class="sheet-handle"></div>
123 - <div class="sheet-head">
124 - <h3 id="sheet-title"></h3>
125 - <button id="sheet-close" class="sheet-close" aria-label="بستن">✕</button>
126 - </div>
127 - <div id="sheet-body" class="sheet-body"></div>
128 - </div>
129 -
130 - <div id="toast" class="toast hidden"></div>
131 -
132 - <footer class="footer">
133 - Aram Pilot Workbench · نسخهٔ مرورگری · موتور <span id="engine-version"></span> ·
134 - خروجی پیش‌نویس کاری است؛ برای گزارشگری رسمی استفاده نکنید.
135 - </footer>
136 -
137 - <script src="app.js"></script>
138 -</body>
139 -</html>
webapp/styles.css deleted
-293
@@ -1,293 +0,0 @@
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 - --nav-h: 64px;
16 - color-scheme: dark;
17 -}
18 -
19 -* { box-sizing: border-box; }
20 -html { -webkit-text-size-adjust: 100%; }
21 -
22 -body {
23 - margin: 0;
24 - font-family: Vazirmatn, "Segoe UI", Tahoma, Arial, sans-serif;
25 - background: radial-gradient(1100px 500px at 85% -10%, #14264a 0%, transparent 60%), 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: 12px; flex-wrap: wrap; padding: 14px 20px;
39 - border-bottom: 1px solid var(--line);
40 - background: rgb(10 18 32 / 85%); backdrop-filter: blur(6px);
41 - position: sticky; top: 0; z-index: 20;
42 -}
43 -.brand { display: flex; align-items: center; gap: 12px; min-width: 0; }
44 -.brand-mark {
45 - width: 42px; height: 42px; border-radius: 12px; flex: none;
46 - display: grid; place-items: center;
47 - background: linear-gradient(135deg, var(--primary), #7c5cff);
48 - font-size: 22px; font-weight: 800; color: #fff;
49 -}
50 -.topbar h1 { margin: 0; font-size: 17px; white-space: nowrap; }
51 -.tagline { margin: 0; font-size: 11.5px; color: var(--muted); }
52 -.topbar-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
53 -.actor-field { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--muted); }
54 -.actor-field input {
55 - background: var(--bg-soft); border: 1px solid var(--line); color: var(--text);
56 - border-radius: 8px; padding: 8px 10px; width: 150px; font-family: inherit; font-size: 14px;
57 -}
58 -
59 -main { max-width: 1200px; margin: 0 auto; padding: 22px 18px 60px; }
60 -
61 -/* ---------- cards / buttons ---------- */
62 -.card { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 18px; }
63 -.btn {
64 - border: 1px solid var(--line); border-radius: 10px; background: var(--card-2); color: var(--text);
65 - padding: 11px 18px; font-family: inherit; font-size: 14px; cursor: pointer;
66 - transition: filter .15s, transform .05s; min-height: 44px;
67 -}
68 -.btn:hover { filter: brightness(1.15); }
69 -.btn:active { transform: translateY(1px); }
70 -.btn:disabled { opacity: .5; cursor: wait; }
71 -.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; font-weight: 700; }
72 -.btn.accent { background: var(--accent); border-color: var(--accent); color: #201400; font-weight: 700; }
73 -.btn.ghost { background: transparent; }
74 -.btn.small { padding: 7px 13px; font-size: 12.5px; border-radius: 8px; min-height: 36px; }
75 -.btn.danger { background: #3a1420; border-color: #7f1d1d; color: #fca5a5; }
76 -.btn.block { width: 100%; }
77 -
78 -/* ---------- landing ---------- */
79 -.hero { text-align: center; padding: 22px 8px 8px; }
80 -.hero h2 { font-size: 24px; margin: 0 0 10px; }
81 -.hero p { max-width: 760px; margin: 0 auto 8px; color: var(--muted); }
82 -.safety-note {
83 - display: inline-block; margin-top: 10px; padding: 6px 16px;
84 - border: 1px dashed var(--accent); border-radius: 999px; color: var(--accent); font-size: 12.5px;
85 -}
86 -.action-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(270px, 1fr)); gap: 16px; margin: 24px 0; }
87 -.action-card { text-align: center; padding: 26px 20px; }
88 -.action-icon { font-size: 36px; }
89 -.action-card h3 { margin: 10px 0 6px; }
90 -.action-card p { color: var(--muted); font-size: 13.5px; min-height: 44px; }
91 -.progress-card { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
92 -.spinner { width: 18px; height: 18px; border-radius: 50%; border: 3px solid var(--line); border-top-color: var(--primary); animation: spin .9s linear infinite; display: inline-block; }
93 -@keyframes spin { to { transform: rotate(360deg); } }
94 -.issues-card { border-color: #7f1d1d; margin-bottom: 16px; }
95 -.issues-card h3 { color: var(--red); margin-top: 0; }
96 -.info-card h3 { margin-top: 0; }
97 -.policy-grid { display: flex; gap: 10px; flex-wrap: wrap; margin: 10px 0; }
98 -.policy-item { background: var(--bg-soft); border: 1px solid var(--line); border-radius: 10px; padding: 7px 13px; font-size: 13px; }
99 -.policy-item b { color: var(--blue); }
100 -
101 -/* ---------- session bar ---------- */
102 -.session-bar { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
103 -.session-meta { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
104 -.session-meta .company-name { font-weight: 800; font-size: 16px; }
105 -.chip { padding: 3px 11px; border-radius: 999px; font-size: 12px; border: 1px solid var(--line); background: var(--bg-soft); color: var(--muted); }
106 -.chip.demo { border-color: var(--accent); color: var(--accent); }
107 -.status-chip { padding: 8px 16px; border-radius: 12px; font-weight: 800; font-size: 13.5px; }
108 -.status-INCOMPLETE { background: #3a2a10; color: #fbbf24; border: 1px solid #92600a; }
109 -.status-COMPLETE_DRAFT { background: #122a4a; color: #93c5fd; border: 1px solid #1d4ed8; }
110 -.status-COMPLETE_APPROVED { background: #0c2f24; color: #6ee7b7; border: 1px solid #047857; }
111 -
112 -/* ---------- tab bar (bottom on mobile, top on desktop) ---------- */
113 -.tabbar { display: flex; gap: 6px; flex-wrap: wrap; margin: 0 0 18px; }
114 -.tab {
115 - position: relative; background: transparent; border: 1px solid transparent; color: var(--muted);
116 - padding: 9px 15px; border-radius: 10px; cursor: pointer; font-family: inherit; font-size: 14px;
117 - display: inline-flex; align-items: center; gap: 6px;
118 -}
119 -.tab:hover { color: var(--text); background: var(--bg-soft); }
120 -.tab.active { background: var(--card); border-color: var(--line); color: var(--text); font-weight: 700; }
121 -.tab-ico { font-size: 16px; }
122 -.badge { background: var(--accent); color: #201400; border-radius: 999px; font-size: 11px; padding: 1px 7px; font-weight: 800; }
123 -.badge.zero { background: var(--green); }
124 -
125 -/* ---------- dashboard ---------- */
126 -.grid { display: grid; gap: 12px; }
127 -.checks-grid { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); margin-bottom: 14px; }
128 -.check-card { padding: 13px 15px; border-radius: 12px; border: 1px solid var(--line); background: var(--card); }
129 -.check-card .check-name { font-size: 13px; color: var(--muted); }
130 -.check-card .check-state { font-size: 16px; font-weight: 800; margin: 3px 0; }
131 -.check-card.pass .check-state { color: var(--green); }
132 -.check-card.fail .check-state { color: var(--red); }
133 -.check-card .check-details { font-size: 12px; color: var(--muted); }
134 -.check-amount { direction: ltr; font-family: Consolas, monospace; font-size: 12.5px; }
135 -.totals-grid { grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); margin: 14px 0; }
136 -.total-card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 13px 15px; }
137 -.total-card .label { font-size: 12.5px; color: var(--muted); }
138 -.total-card .value { font-size: 17px; font-weight: 800; direction: ltr; text-align: right; font-family: Consolas, monospace; }
139 -.total-card.highlight { border-color: var(--primary); }
140 -.total-card .value.neg { color: var(--red); }
141 -.coverage-bar-wrap { background: var(--bg-soft); border-radius: 999px; height: 14px; overflow: hidden; border: 1px solid var(--line); }
142 -.coverage-bar { height: 100%; background: linear-gradient(90deg, var(--primary), var(--green)); transition: width .4s; }
143 -
144 -/* ---------- tables ---------- */
145 -.table-wrap { overflow-x: auto; border-radius: 12px; border: 1px solid var(--line); -webkit-overflow-scrolling: touch; }
146 -table { width: 100%; border-collapse: collapse; font-size: 13.5px; background: var(--card); }
147 -th, td { padding: 9px 12px; border-bottom: 1px solid var(--line); text-align: right; vertical-align: middle; }
148 -thead th { background: var(--card-2); color: var(--muted); font-size: 12.5px; white-space: nowrap; }
149 -tbody tr:hover { background: rgb(79 140 255 / 6%); }
150 -td.num, th.num { direction: ltr; text-align: left; font-family: Consolas, monospace; white-space: nowrap; }
151 -td.num.neg { color: var(--red); }
152 -.table-toolbar { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-bottom: 12px; }
153 -.table-toolbar input[type="search"], .table-toolbar select {
154 - background: var(--bg-soft); border: 1px solid var(--line); color: var(--text);
155 - border-radius: 9px; padding: 9px 12px; font-family: inherit; font-size: 14px;
156 -}
157 -.table-toolbar input[type="search"] { flex: 1; min-width: 160px; }
158 -
159 -.approval-chip { font-size: 11.5px; padding: 2px 10px; border-radius: 999px; border: 1px solid var(--line); white-space: nowrap; }
160 -.approval-Approved { background: #0c2f24; color: #6ee7b7; border-color: #047857; }
161 -.approval-Reviewed { background: #122a4a; color: #93c5fd; border-color: #1d4ed8; }
162 -.approval-Draft { background: #3a2a10; color: #fbbf24; border-color: #92600a; }
163 -.approval-none { background: #3a1420; color: #fca5a5; border-color: #7f1d1d; }
164 -
165 -/* ---------- item cards (accounts / notes) ---------- */
166 -.item-list { display: flex; flex-direction: column; gap: 10px; }
167 -.item-card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 13px 15px; }
168 -.item-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 10px; }
169 -.item-title { font-weight: 700; font-size: 14.5px; }
170 -.item-code { font-size: 12px; color: var(--muted); }
171 -.item-sub { font-size: 12.5px; color: var(--muted); margin-top: 4px; }
172 -.item-amount { direction: ltr; font-family: Consolas, monospace; font-weight: 700; white-space: nowrap; }
173 -.item-amount.neg { color: var(--red); }
174 -.item-actions { display: flex; gap: 7px; flex-wrap: wrap; margin-top: 10px; }
175 -.item-actions .btn { flex: 1; min-width: 90px; }
176 -.section-label { font-size: 13px; font-weight: 800; color: var(--blue); margin: 16px 0 8px; display: flex; align-items: center; gap: 8px; }
177 -.section-label::after { content: ""; flex: 1; height: 1px; background: var(--line); }
178 -
179 -/* ---------- statements ---------- */
180 -.statement-paper { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 22px 24px; }
181 -.statement-head { text-align: center; margin-bottom: 16px; }
182 -.statement-head h2 { margin: 0; font-size: 20px; }
183 -.statement-head .sub { color: var(--muted); font-size: 13px; }
184 -.draft-watermark { display: inline-block; margin-top: 8px; padding: 3px 14px; border-radius: 999px; border: 1px dashed var(--accent); color: var(--accent); font-size: 12px; }
185 -.statement-section { margin: 16px 0; }
186 -.statement-section > .section-head { display: flex; justify-content: space-between; align-items: center; background: var(--card-2); padding: 9px 15px; border-radius: 10px; font-weight: 800; border: 1px solid var(--line); }
187 -.note-line { display: flex; justify-content: space-between; align-items: center; padding: 10px 16px; border-bottom: 1px solid var(--line); cursor: pointer; gap: 10px; }
188 -.note-line:hover { background: rgb(79 140 255 / 6%); }
189 -.note-line .note-title { display: flex; gap: 9px; align-items: center; flex-wrap: wrap; min-width: 0; }
190 -.note-number { background: var(--bg-soft); border: 1px solid var(--line); border-radius: 7px; min-width: 32px; text-align: center; font-size: 12px; padding: 1px 6px; color: var(--muted); }
191 -.note-total { direction: ltr; font-family: Consolas, monospace; font-weight: 700; white-space: nowrap; }
192 -.note-total.neg { color: var(--red); }
193 -.drill { padding: 4px 14px 12px; }
194 -.drill table { font-size: 12.5px; background: var(--bg-soft); }
195 -.statement-total { display: flex; justify-content: space-between; padding: 12px 16px; margin-top: 12px; border-top: 2px solid var(--primary); font-weight: 900; font-size: 15px; gap: 10px; }
196 -.statement-tools { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 12px; flex-wrap: wrap; }
197 -.segmented { display: inline-flex; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
198 -.segmented button { background: transparent; border: none; color: var(--muted); padding: 9px 18px; font-family: inherit; font-size: 14px; cursor: pointer; min-height: 42px; }
199 -.segmented button.active { background: var(--primary); color: #fff; font-weight: 700; }
200 -
201 -/* ---------- more / audit ---------- */
202 -.provenance-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 10px; margin-bottom: 14px; }
203 -.prov-item { background: var(--bg-soft); border: 1px solid var(--line); border-radius: 10px; padding: 10px 13px; font-size: 13px; }
204 -.prov-item .k { color: var(--muted); font-size: 11.5px; }
205 -.prov-item .v { word-break: break-all; }
206 -.action-stack { display: flex; flex-direction: column; gap: 10px; }
207 -
208 -/* ---------- bottom sheet ---------- */
209 -.sheet-backdrop { position: fixed; inset: 0; background: rgb(0 0 0 / 55%); z-index: 40; }
210 -.sheet {
211 - position: fixed; z-index: 41; background: var(--bg-soft); border: 1px solid var(--line);
212 - left: 0; right: 0; bottom: 0; max-height: 88vh; display: flex; flex-direction: column;
213 - border-radius: 20px 20px 0 0; box-shadow: 0 -12px 50px rgb(0 0 0 / 5%);
214 - animation: sheet-up .22s ease;
215 -}
216 -@keyframes sheet-up { from { transform: translateY(40px); opacity: .4; } to { transform: none; opacity: 1; } }
217 -.sheet-handle { width: 44px; height: 4px; border-radius: 2px; background: var(--line); margin: 10px auto 2px; flex: none; }
218 -.sheet-head { display: flex; justify-content: space-between; align-items: center; padding: 8px 20px; border-bottom: 1px solid var(--line); flex: none; }
219 -.sheet-head h3 { margin: 0; font-size: 16px; }
220 -.sheet-close { background: transparent; border: none; color: var(--muted); font-size: 18px; cursor: pointer; width: 40px; height: 40px; }
221 -.sheet-body { padding: 18px 20px 26px; overflow-y: auto; }
222 -.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
223 -.form-grid .full { grid-column: 1 / -1; }
224 -.form-field { display: flex; flex-direction: column; gap: 5px; font-size: 12.5px; color: var(--muted); }
225 -.form-field input, .form-field select {
226 - background: var(--card); border: 1px solid var(--line); color: var(--text);
227 - border-radius: 9px; padding: 11px 12px; font-family: inherit; font-size: 15px; width: 100%;
228 -}
229 -.form-field input:focus, .form-field select:focus { outline: 2px solid var(--primary); outline-offset: -1px; }
230 -.form-hint { font-size: 12px; color: var(--muted); margin: 8px 0; }
231 -.form-actions { display: flex; gap: 10px; margin-top: 18px; }
232 -.form-actions .btn { flex: 1; }
233 -.computed-box { background: var(--card); border: 1px dashed var(--line); border-radius: 9px; padding: 10px 12px; font-size: 14px; }
234 -.computed-box b { direction: ltr; font-family: Consolas, monospace; }
235 -
236 -/* ---------- toast / footer ---------- */
237 -.toast { position: fixed; bottom: calc(var(--nav-h) + 16px); right: 50%; transform: translateX(50%); background: var(--card-2); border: 1px solid var(--line); color: var(--text); padding: 12px 20px; border-radius: 12px; z-index: 50; max-width: 92vw; box-shadow: 0 12px 40px rgb(0 0 0 / 45%); font-size: 14px; text-align: center; }
238 -.toast.error { border-color: #7f1d1d; color: #fca5a5; }
239 -.toast.success { border-color: #047857; color: #6ee7b7; }
240 -.footer { text-align: center; color: var(--muted); font-size: 12px; padding: 16px; border-top: 1px solid var(--line); }
241 -
242 -/* ---------- mobile ---------- */
243 -@media (max-width: 760px) {
244 - main { padding: 16px 12px calc(var(--nav-h) + 28px); }
245 - .topbar { padding: 10px 14px; }
246 - .tagline { display: none; }
247 - .topbar h1 { font-size: 15px; }
248 - .actor-label { display: none; }
249 - .actor-field input { width: 110px; }
250 - .hero h2 { font-size: 20px; }
251 - .statement-paper { padding: 16px 14px; }
252 - .form-grid { grid-template-columns: 1fr; }
253 - .tabbar {
254 - position: fixed; bottom: 0; left: 0; right: 0; z-index: 30; margin: 0;
255 - background: rgb(10 18 32 / 95%); backdrop-filter: blur(8px);
256 - border-top: 1px solid var(--line); padding: 6px 6px calc(6px + env(safe-area-inset-bottom));
257 - display: flex; justify-content: space-around; gap: 2px; flex-wrap: nowrap;
258 - min-height: var(--nav-h);
259 - }
260 - .tabbar .tab { flex-direction: column; gap: 2px; font-size: 10.5px; padding: 6px 4px; flex: 1; border-radius: 10px; justify-content: center; }
261 - .tabbar .tab-ico { font-size: 19px; }
262 - .tabbar .badge { position: absolute; top: 2px; left: 50%; margin-inline-start: 8px; }
263 - .footer { display: none; }
264 - .toast { bottom: calc(var(--nav-h) + 14px); }
265 - .desktop-only { display: none !important; }
266 -}
267 -@media (min-width: 761px) {
268 - .mobile-only { display: none !important; }
269 - .tabbar { position: static; }
270 -}
271 -
272 -/* ---------- print ---------- */
273 -@media print {
274 - body { background: #fff; color: #111; }
275 - .topbar, .tabbar, .session-bar, .footer, .statement-tools, .toast, .sheet, .sheet-backdrop { display: none !important; }
276 - .statement-paper { border: none; background: #fff; }
277 - .statement-section > .section-head { background: #eef2f7; color: #111; }
278 - .note-line, th, td { border-color: #cbd5e1; }
279 - .note-number, .chip { color: #334155; background: #f1f5f9; }
280 - thead th { background: #eef2f7; color: #334155; }
281 - table { background: #fff; }
282 - .draft-watermark { color: #92400e; border-color: #92400e; }
283 -}
284 -
285 -/* ---------- boot / engine loading ---------- */
286 -.boot { position: fixed; inset: 0; z-index: 100; display: grid; place-items: center; background: radial-gradient(900px 500px at 70% -10%, #14264a 0%, transparent 60%), var(--bg); padding: 20px; }
287 -.boot-card { text-align: center; max-width: 420px; width: 100%; }
288 -.boot-mark { width: 64px; height: 64px; margin: 0 auto 14px; border-radius: 18px; display: grid; place-items: center; background: linear-gradient(135deg, var(--primary), #7c5cff); font-size: 32px; font-weight: 800; color: #fff; }
289 -.boot-card h2 { margin: 0 0 8px; font-size: 20px; }
290 -.boot-card p { color: var(--muted); font-size: 13.5px; }
291 -.boot-bar { background: var(--bg-soft); border: 1px solid var(--line); border-radius: 999px; height: 12px; overflow: hidden; margin: 16px 0; }
292 -.boot-progress { height: 100%; width: 5%; background: linear-gradient(90deg, var(--primary), var(--green)); transition: width .4s; }
293 -.boot-error { color: var(--red) !important; border: 1px solid #7f1d1d; border-radius: 10px; padding: 10px; margin-top: 12px; }
webapp/vendor/et_xmlfile-2.0.0-py3-none-any.whl
Binary files a/webapp/vendor/et_xmlfile-2.0.0-py3-none-any.whl and /dev/null differ
webapp/vendor/openpyxl-3.1.5-py2.py3-none-any.whl
Binary files a/webapp/vendor/openpyxl-3.1.5-py2.py3-none-any.whl and /dev/null differ