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

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

Synced Dec 4, 04:15 UTC

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>

davoodmehraban89 committed Dec 3, 2026 at 20:02 UTC 6e3fe70f2c7b5333746ee2156ce197f60d598093
30 files changed +469 -4746
.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
+5 -1
@@ -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.
PROJECT_STATUS.md
+39 -29
@@ -10,7 +10,7 @@
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 order: «کتابچهٔ اجرایی تکمیل Aram» v1.0 — version-controlled at [`docs/booklet/BOOKLET_v1.0.md`](docs/booklet/BOOKLET_v1.0.md), integrity anchored by SHA-256 in [`docs/booklet/MANIFEST.json`](docs/booklet/MANIFEST.json) (ADR-025).
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
@@ -47,25 +47,32 @@ All Phase 0–9 work below is **VERIFIED_AND_MERGED** on `source-data-cleanup` a
47
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
50 -## Active mission — booklet-compliance remediation B0…B12
50 +## Active mission — booklet 2 course correction + C0…C10 roadmap
51
52 -One focused PR per category, strictly sequential (next only after prior acceptance). Executor only; independent reviewer separate; no "done" without evidence (§19). Ambiguities closed via §17 (default + proof + ADR), never by querying the owner. `data/` + `samples/` read-only with before/after tree-hash evidence per PR.
52 +Booklet 2 v2.0 («اصلاح مسیر و معماری نهایی Aram», [`docs/booklet/BOOKLET_v2.0.md`](docs/booklet/BOOKLET_v2.0.md), ADR-027) **supersedes** the conflicting parts of booklet 1 and the earlier B0…B12 framing; it defines the governing roadmap **C0…C10** below. 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
54 -| Category | Scope (summary) | State |
54 +| Phase | Scope (summary) | State |
55 |---|---|---|
56 -| B0 | Booklet version-controlled + manifest; status/log refresh; root analytical docs → `docs/archive/`; AGENTS.md ↔ §0.5 alignment (ADR-026); `docs/discrepancies.json` skeleton | IN_PROGRESS (this PR) |
57 -| B1 | Security fail-closed: pilot API auth+role+audit; login lockout; PBKDF2→Argon2id; no amounts/account names in logs | NOT_IMPLEMENTED |
58 -| B2 | Money/Persian UI: exact-rial formatting, bundled Vazirmatn, negatives/digits/dir, dark/light, Jalali in domain | NOT_IMPLEMENTED |
59 -| B3 | Controls C-05..C-15 wired into run_controls + approval gate; ERROR year unapprovable | NOT_IMPLEMENTED |
60 -| B4 | Data model: ImportRun/CalculationRun/LineageEdge/Adjustment/UnknownAccountQueue/carried_from_year_id/calculation_run_id; migration round-trip | NOT_IMPLEMENTED |
61 -| B5 | Import hardening: formula-cache error, idempotency, perf, destructive tests | NOT_IMPLEMENTED |
62 -| B6 | Mapping studio: suggestions, bulk preview, split validation, Excel diff, carry-forward | NOT_IMPLEMENTED |
63 -| B7 | Outputs: reportlab PDF (Vazirmatn, watermark), XLSX controls sheet, real-number cells, official-from-approved-run | NOT_IMPLEMENTED |
64 -| B8 | Golden 1403 + registry; C-05 automatic; every official difference recorded in `docs/discrepancies.json` | NOT_IMPLEMENTED |
65 -| B9 | CI gates: npm audit, coverage 80/90, mypy --strict services, ruff format, windows build+smoke, OpenAPI contract | NOT_IMPLEMENTED |
66 -| B10 | Encrypted backup (AES-GCM + Argon2 KDF); CI full-restore test | NOT_IMPLEMENTED |
67 -| B11 | Drift/target layout: Pyodide layer out of scope, pilot-pages workflow, single reference UI, api/ + packaging/windows/ | NOT_IMPLEMENTED |
68 -| B12 | Large files: `docs/data_manifest.json` SHA-256 + LFS/external plan; history rewrite BLOCKED absent owner directive | NOT_IMPLEMENTED |
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), 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) | NOT_IMPLEMENTED |
63 +| C7 | Full UI + outputs (booklet 1 phases 5–6 on new model): exact-rial Persian UI, PDF/XLSX | NOT_IMPLEMENTED |
64 +| C8 | Security + audit (booklet 1 phase 7 + ب‌10): pilot API auth, Argon2id, DPAPI vault, encrypted backup, plugin allowlist | NOT_IMPLEMENTED |
65 +| C9 | Packaging + deployment (booklet 1 phase 8 + SBOM/signing): offline Windows, CI gates, large-file manifest | NOT_IMPLEMENTED |
66 +| C10 | Acceptance: Shadow Run on a real period of two companies + owner signature | NOT_IMPLEMENTED |
67 +
68 +### C0 progress (بخش الف)
69 +
70 +- **الف‌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).
71 +- **الف‌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.
72 +- **الف‌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.
73 +- **الف‌4/الف‌5 (PR honesty/size):** rules added to `AGENTS.md`; this PR body matches the diff.
74 +- **الف‌6 (PR triage):** DONE — `docs/PR_TRIAGE.md` (ADOPT #81/#89/#92; CLOSE NO-GO #82/#88; SUPERSEDED #90/#91 + #22–#80 backlog).
75 +- **الف‌7 (exit criteria):** CI green at accepted head; `PROJECT_STATUS.md` consistent with head; golden 1404 core notes reconcile rial-for-rial, remaining diffs to be recorded one-by-one in `docs/discrepancies.json` (C1/C3). See residual risks.
76
77 ## Phase 9 UAT evidence (real source_1404.xlsx, read-only)
78
@@ -78,28 +85,31 @@ One focused PR per category, strictly sequential (next only after prior acceptan
85 - Export: XLSX (6.27 MB) + JSON with **158,050 lineage rows** (file/SHA-256/sheet/row).
86 - Backup: created + verified (hashes + audit chain); audit chain valid.
87
81 -## Known gaps feeding the B-categories (honest residual risks)
88 +## Known gaps feeding the C-phases (honest residual risks)
89
83 -- `pilot_api.py` exposes 17 unauthenticated routes (B1).
84 -- `frontend/src/lib/format.ts` uses `Number(value)` (float risk) (B2).
85 -- Only controls C-01..C-04 implemented; C-05..C-15 absent (B3).
86 -- ImportRun/CalculationRun/LineageEdge/Adjustment/UnknownAccountQueue/carried_from_year_id/calculation_run_id refs absent (B4).
87 -- `note_engine.acct()` is closing-only; statement_balance-only rows evaluate 0 in notes (B4/B8).
88 -- CI: `npm ci --no-audit`, coverage gate not 80/90, services mypy non-strict (B9).
89 -- Backup unencrypted (B10).
90 -- Pyodide drift (`docs/py` vs `backend/src`), 3 parallel UIs, vendored wheels (B11).
91 -- Windows EXE not built; clean-machine install log + §14 UAT signature pending (Phase 9 release checklist, owner).
90 +- `pilot_api.py` exposes 17 unauthenticated routes; legacy in-memory pilot still mounted (C8 security, then retire) (الف‌2).
91 +- `frontend/src/lib/format.ts` uses `Number(value)` (float risk) (C7).
92 +- Only controls C-01..C-04 implemented; C-05..C-15 absent (C3).
93 +- ImportRun/CalculationRun/LineageEdge/Adjustment/UnknownAccountQueue/carried_from_year_id/calculation_run_id refs absent; pilot exception queue not persisted in `domain/` (C1/C4).
94 +- `note_engine.acct()` is closing-only; statement_balance-only rows evaluate 0 in notes (C1/C3).
95 +- No connector framework / Source Adapter / snapshot reconciliation / packs yet; generality grep test pending (C4/C5/C6).
96 +- CI: `npm ci --no-audit`, coverage gate not 80/90, services mypy non-strict (C9).
97 +- Backup unencrypted; no DPAPI vault / plugin allowlist / SBOM yet (C8/C9).
98 +- Browser edition removed (C0); single reference UI = React workbench, developed in C7. Backend `static/pilot` legacy retained until C8.
99 +- Windows EXE not built; clean-machine install log + Shadow Run two-company + owner signature pending (C9/C10).
100 +- `docs/discrepancies.json` is a skeleton; real-1404 BS/IS differences not yet recorded one-by-one with cause+evidence (C1/C3).
101
102 ## Release procedure (owner)
103
95 -The implementation author does **not** merge or tag (§19). Tag `v1.0.0` already exists on `46253c9` (owner-authorized pre-mission). After B0…B11 acceptance, prepare the Phase 9 release checklist here (owner tags, retained artifact, clean-machine install log, §14 UAT signature); do not tag. B12 history rewrite stays BLOCKED absent an explicit owner directive.
104 +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).
105
106 ## Control documents
107
108 - [Project log](docs/PROJECT_LOG.md)
109 - [Decision log](docs/DECISION_LOG.md)
110 - [Acceptance policy](docs/ACCEPTANCE_POLICY.md)
102 -- [Booklet v1.0 (reference)](docs/booklet/BOOKLET_v1.0.md) · [manifest](docs/booklet/MANIFEST.json)
111 +- [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)
112 +- [PR triage (الف‌6)](docs/PR_TRIAGE.md)
113 - [Discrepancy registry (skeleton)](docs/discrepancies.json)
114 - [Archived analytical documents](docs/archive/README.md)
115 - [Master recovery prompt](docs/handoff/MASTER_RECOVERY_PROMPT.md)
docs/PROJECT_LOG.md
+17
@@ -379,3 +379,20 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
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.
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-027-booklet-v2-course-correction.md new
+76
@@ -0,0 +1,76 @@
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 supersedes the B0…B12 framing
24 +
25 +Booklet 2 §13 defines the governing roadmap **C0…C10**. The earlier B0…B12 categories
26 +are folded into it (B0 groundwork → C0; B1 security → C8; B2 money/UI → C7; B3 controls
27 +→ C3; B4 data model → C1/C4; B5 import → C4; B6 mapping → C2/C6; B7 outputs → C7;
28 +B8 golden/registry → C1/C3; B9 CI → C9; B10 backup → C8; B11 drift/layout → C0/C4;
29 +B12 large files → C9). B0's deliverables (booklet reference, archive, status rewrite,
30 +discrepancy skeleton, process ADRs) are C0-compatible and retained. One focused PR per
31 +phase task, ≤ ~1,500 changed lines excluding tests/generated data (الف‌5); PR body must
32 +match `git diff --stat` and the real head (الف‌4).
33 +
34 +### Automatic decisions OD-09…OD-14 (booklet 2 §14) adopted
35 +
36 +- **OD-09** SQL Server driver: default `python-tds` (pure-Python, offline packaging);
37 + `pyodbc` fallback. Proof gate: connection + 100k-row extraction in C5; switch if unstable.
38 +- **OD-10** adapter language: YAML validated by JSON Schema; round-trip test + precise
39 + Persian error messages (C4).
40 +- **OD-11** plugin execution: separate process for Connectors; if it blocks Windows
41 + packaging, same-process with restricted permissions + a new ADR (C4/C9).
42 +- **OD-12** data level: trial-balance default; document-level optional, only after C6 and
43 + only if a note cannot be computed without document detail.
44 +- **OD-13** concurrency: single local install for V1; multi-user server out of scope;
45 + PostgreSQL exercised in CI for the future path.
46 +- **OD-14** similar tools: inspiration only; no code/brand/content copied; capability
47 + comparison recorded in an ADR.
48 +- Other ambiguities: most conservative option (the one that blocks approval) + ADR with
49 + rejected options.
50 +
51 +### Generality rule (ب‌1, non-negotiable)
52 +
53 +No company name, account code, heading, or industry constant in source code; these live
54 +only in `packs/` and the database. An automated grep test enforces this (added with the
55 +packs work in C6; the rule is recorded now and in `AGENTS.md`). Company/industry-specific
56 +content (including the current transmission-company pack) is **data**, never a code default.
57 +
58 +### databansoft.ir appendix — not accessible from this environment
59 +
60 +The sandbox network allowlist permits only github.com / npmjs / pypi hosts; `databansoft.ir`
61 +is **not** reachable. No capability claims are made (the booklet makes none either). The
62 +booklet takes precedence. If access becomes available, only observable capabilities will be
63 +listed and compared against ب‌3..ب‌6 in a follow-up ADR; no code/text/design/brand copied (OD-14).
64 +
65 +## Proof
66 +
67 +- Booklet 2 verbatim + SHA-256 `9738f8049703ca63ea6eae471538cdadc6328e4f15efaaf87a250315e516e2fc` in `MANIFEST.json`.
68 +- 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`).
69 +- 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).
70 +
71 +## Consequences
72 +
73 +- C0 (this PR) executes الف‌1 (browser removal, ADR-028), الف‌6 (`docs/PR_TRIAGE.md`),
74 + الف‌4/الف‌5 (process rules in `AGENTS.md`), and records الف‌2/الف‌3/الف‌7 status.
75 +- Subsequent phases follow C1…C10 with evidence recorded in `PROJECT_STATUS.md` before
76 + advancing. No merge, no tag, no runtime network, no company-specific code (§16).
docs/adr/ADR-028-remove-browser-edition.md new
+62
@@ -0,0 +1,62 @@
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 46253c9 && git push origin experiment/browser-edition`.
43 +3. The backend in-memory pilot subsystem (`pilot_engine.py`, `pilot_store.py`,
44 + `pilot_api.py`, `pilot_editing.py`, `static/pilot`) is **not** removed here. It is legacy
45 + (الف‌2): the persistent core is the main product path. It is secured in **C8** (B1) and
46 + retired/relocated per the target layout afterwards; `pilot_engine.py` is retained as a
47 + logic reference until its exception-queue logic is persisted in `domain/` (C4/B4).
48 +
49 +## Proof
50 +
51 +- `grep -rnE "webapp|docs/py|docs/vendor|build_webapp|pilot-pages" backend/src frontend/src`
52 + → no code references (only the removed `build_webapp.py` / `pilot-pages.yml` self-refs).
53 +- `main.py` mounts `statement_router` + `admin_router` (persistent) alongside the legacy
54 + `pilot_router`; `domain/controls.py` + `domain/money.py` run on stored `LedgerBalance`.
55 +- Removed wheels are binary artifacts (§19); their removal reduces committed binaries.
56 +
57 +## Consequences
58 +
59 +- The accepted path is offline-only (no Pages/CDN/Pyodide). The single reference UI is the
60 + React workbench (`frontend/`), developed further in C7.
61 +- The browser edition is recoverable from history; the named experiment branch is an owner
62 + action recorded here, not performed in this single-branch session.
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/booklet/BOOKLET_v2.0.md new
+170
@@ -0,0 +1,170 @@
1 +# کتابچهٔ ۲ — اصلاح مسیر و معماری نهایی Aram
2 +
3 +> **سند مرجعِ version-controlled (نسخهٔ ۲٫۰).** متنِ زیر عیناً دستور کارِ مالک است که
4 +> در پیام 2026-12-03 ارائه شد. این کتابچه جایگزین بخش‌های متناقض کتابچهٔ ۱ و مکمل بقیهٔ
5 +> آن است. لنگر یکپارچگی: SHA-256 همین فایل در `MANIFEST.json` (منبع: پیام مالک، بدون فایل اصلی).
6 +> مبنا: بررسی PR #96 و مخزن davoodmehraban89/Aram. مالک خواسته است ایجنت **هیچ سؤالی نپرسد**؛
7 +> ابهام‌ها با قواعد بخش ۱۴ بسته می‌شوند.
8 +
9 +نسخهٔ ۲٫۰ — جایگزین بخش‌های متناقض کتابچهٔ ۱ و مکمل بقیهٔ آن. مخاطب: ایجنت کدنویسی. مبنا: بررسی PR #96 (head 2fce09d) و مخزن davoodmehraban89/Aram. مالک خواسته است ایجنت هیچ سؤالی نپرسد؛ ابهام‌ها با قواعد بخش ۱۴ بسته می‌شوند.
10 +
11 +## بخش الف — اصلاح مسیر فوری (قبل از هر قابلیت جدید)
12 +
13 +بررسی PR #96 نشان داد کار به سمت یک ابزار موقت درون‌حافظه‌ای و مرورگری رفته است. موارد زیر اجباری و به همین ترتیب‌اند:
14 +
15 +**الف‌۱. توقف انشعاب Pyodide / GitHub Pages / CDN.** فایل‌های `.github/workflows/pilot-pages.yml`، پوشهٔ `webapp/`، خروجی ساخته‌شده در `docs/` (که با مستندات حاکمیتی تداخل دارد)، `docs/vendor/` و `scripts/build_webapp.py` از PR #96 حذف و در شاخهٔ جدا `experiment/browser-edition` نگهداری شوند (ادغام‌نشدنی). دلیل: وابستگی به شبکه در زمان اجرا برای ابزار مالی نقض اصل آفلاین است.
16 +
17 +**الف‌۲. تکمیل هستهٔ ماندگار به‌جای حافظهٔ موقت.** `pilot_engine.py` فقط به‌عنوان مرجع منطق حفظ شود: سیاست علامت، صف استثنا و کنترل‌های آن به `domain/` منتقل و روی داده‌های ذخیره‌شده اجرا شوند. جلسهٔ درون‌حافظه‌ای (`pilot_store`) نباید مسیر اصلی محصول بماند. ورودی‌ها: لجر واقعی سال ۱۴۰۴ (`data/source_ledgers`) + نگاشت، نه فقط قالب Pilot.
18 +
19 +**الف‌۳. اجرای فاز ۰ و فاز ۱ کتابچه ۱ کامل:** بدهی‌های D-01 تا D-12 (به‌ویژه جدول LedgerBalance، ذخیرهٔ محتوا-آدرس‌پذیر فایل منبع، قفل سطح دیتابیس، audit زنجیره‌ای، Decimal دقیق روی SQLite) و سپس برش عمودی ۱۴۰۴ با تست طلایی تطبیق ریال‌به‌ریال با `official_statements`.
20 +
21 +**الف‌۴. صداقت PR.** متن هر PR باید دقیقاً با `git diff --stat` و head واقعی هم‌خوان باشد (تعداد فایل، خطوط، تست‌ها، SHA). PRای که مشخصاتش با واقعیت نمی‌خواند برای بازبینی پذیرفته نیست.
22 +
23 +**الف‌۵. اندازه PR.** هر PR یک وظیفهٔ فاز، حداکثر حدود ۱٬۵۰۰ خط تغییر (بدون تست و دادهٔ تولیدشده). ادغام چند فاز در یک PR ممنوع است.
24 +
25 +**الف‌۶. تعیین تکلیف PRهای انباشته (#81 تا #92، #88/#89 و بقیه).** در یک فایل `docs/PR_TRIAGE.md` برای هر PR باز یکی از سه حکم ثبت شود: اتخاذ (cherry-pick شود به PR جدید و کوچک)، جایگزین‌شده (بست)، بستن. هیچ PR با برچسب NO-GO ادغام نشود. معیار اتخاذ: با کتابچه‌ها هم‌خوان باشد و تست داشته باشد.
26 +
27 +**الف‌۷. معیار خروج از بخش الف:** CI سبز، `PROJECT_STATUS.md` هم‌خوان با head، تست طلایی ۱۴۰۴ سبز یا اختلاف‌ها در `docs/discrepancies.json` با علت ثبت شده باشند.
28 +
29 +## بخش ب — هدف نهایی: Aram به‌عنوان پلتفرم عمومی و دیتابیس‌محور
30 +
31 +### ب‌۱. چشم‌انداز
32 +
33 +Aram نباید ابزار یک شرکت (مثلاً انتقال گاز) باشد. باید برای هر شرکت صورت‌های مالی اساسی و یادداشت‌ها را از روی داده‌های حسابداری آن شرکت تهیه کند، با دو مسیر ورود: فایل (Excel/CSV) و اتصال مستقیم به بانک اطلاعاتی نرم‌افزار حسابداری/ERP. هرچه به یک شرکت یا صنعت خاص مربوط است باید داده باشد (بستهٔ قالب/نگاشت)، نه کد.
34 +
35 +**قاعدهٔ عمومی‌بودن (غیرقابل‌مذاکره):** هیچ نام شرکت، کد حساب، سرفصل یا ثابت صنعتی در کد منبع نباشد؛ این‌ها فقط در `packs/` و دیتابیس می‌آیند. تست خودکار با grep این را بررسی کند.
36 +
37 +### ب‌۲. معماری لایه‌ای
38 +
39 +1. **Connectors (افزونه‌های منبع داده):** استخراج فقط‌خواندنی از یک منبع.
40 +2. **Source Adapter (پروفایل منبع):** توصیف اعلانی (YAML/JSON) که ساختار جدول‌ها/ویوهای منبع را به مدل کانونی لجر ترجمه می‌کند.
41 +3. **Canonical Ledger:** مدل استاندارد داخلی (LedgerBalance و اختیاری JournalLine).
42 +4. **Snapshot:** هر استخراج یک عکس فوری تغییرناپذیر با hash است؛ محاسبه فقط روی snapshot انجام می‌شود، نه روی منبع زنده.
43 +5. **Engine:** نگاشت، یادداشت‌ها، صورت‌ها، کنترل‌ها (کتابچهٔ ۱ بخش‌های ۶ و ۷).
44 +6. **Packs:** قالب صورت‌ها، نگاشت‌ها و قواعد اعتبارسنجی به‌صورت داده نسخه‌دار.
45 +7. **API و UI** و **Exports**.
46 +
47 +### ب‌۳. مدل افزونه (Plugin)
48 +
49 +- انواع افزونه: SourceConnector، MappingPack (الگوی نگاشت سرفصل‌ها)، StatementTemplatePack (قالب صورت‌ها و یادداشت‌ها)، ValidationPack (کنترل‌های اضافه)، ExportRenderer.
50 +- رابط پایدار و نسخه‌دار `aram_plugin_api` v1؛ افزونه فقط از همین رابط استفاده کند و به ORM داخلی دست نزند.
51 +- مانیفست: نام، نسخه، نسخهٔ سازگار API، نوع، مجوزهای لازم (شبکهٔ محلی، فایل)، JSON Schema تنظیمات.
52 +- اجرا: افزونه‌های Connector در فرایند جدا با حداقل مجوز اجرا شوند؛ خروجی فقط از رابط ساخت‌یافته می‌آید.
53 +- امضا و فهرست مجاز: افزونه فقط با hash/امضای ثبت‌شده توسط Admin بار می‌شود. بارگذاری کد دلخواه از شبکه ممنوع است.
54 +- تست انطباق (Conformance Suite): هر Connector باید مجموعه‌تست مشترک را بگذراند (تست اتصال، شناسایی ساختار، استخراج صفحه‌ای، قطع ارتباط، timeout، دادهٔ ناقص، یونیکد فارسی).
55 +
56 +### ب‌۴. Connectorها (ترتیب پیاده‌سازی)
57 +
58 +1. **FileConnector** (Excel/CSV): پیاده‌سازی مرجع و پایهٔ تست انطباق.
59 +2. **SQL عمومی** بر پایهٔ SQLAlchemy Core برای PostgreSQL و SQLite، سپس **SQL Server** (پیش‌فرض: درایور خالص‌پایتون python-tds برای بسته‌بندی آفلاین؛ جایگزین: pyodbc در صورت نصب درایور ODBC).
60 +3. **ODBC عمومی** برای بقیهٔ سامانه‌ها (از جمله Oracle/MySQL) از راه افزونهٔ جدا.
61 +
62 +هر Connector این قرارداد را دارد: `test_connection()`، `discover_schema()`، `preview(table, n)`، `extract(adapter, period) → iterator`، `fingerprint()` (hash ساختار و مجموع‌ها).
63 +
64 +### ب‌۵. ایمنی اتصال به دیتابیس
65 +
66 +- فقط‌خواندنی: کاربر دیتابیس با دسترسی SELECT؛ برنامه در ثبت اتصال، نبود مجوز نوشتن را بررسی و در صورت وجود مجوز نوشتن هشدار مسدودکننده بدهد.
67 +- کوئری‌ها قالبی و پارامتری‌اند (بدون الحاق رشته). حالت «کوئری سفارشی» فقط برای Admin و پس از تجزیهٔ نحوی (مثلاً sqlglot) با اجازهٔ منحصراً SELECT، با timeout و سقف تعداد ردیف.
68 +- رمزها: در Windows با DPAPI و در بقیهٔ سامانه‌ها با keyring رمز شوند؛ هرگز در لاگ، فایل پیکربندی یا خروجی نیایند.
69 +- شبکه: فقط به میزبان/درگاه ثبت‌شدهٔ اتصال؛ بدون هیچ فراخوانی اینترنتی. TLS در صورت پشتیبانی دیتابیس فعال و وضعیتش نمایش داده شود.
70 +- تغییرنکردن منبع: استخراج در تراکنش با سطح ایزولاسیون snapshot/read-committed و بدون قفل طولانی.
71 +
72 +### ب‌۶. Source Adapter (پروفایل منبع)
73 +
74 +یک فایل اعلانی نسخه‌دار با این بخش‌ها: اتصال (ارجاع به رمز)، queries پارامتری برای سال/دوره، columns (نگاشت ستون‌های منبع به فیلدهای کانونی)، transforms (مثل normalize_fa، پر کردن صفر کد)، sign_convention، unit (ریال/میلیون ریال)، و expectations (انتظارات اعتبارسنجی مثل «جمع بدهکار برابر جمع بستانکار»). تغییر هر چیز در adapter = نسخهٔ جدید و ثبت در audit.
75 +
76 +**فیلدهای کانونی:** 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.
77 +
78 +**ب‌۶‌-۱. جریان کاربر برای اتصال (ویزارد):** اتصال ← تست ← کشف ساختار ← انتخاب جدول/ویوی منبع ← نگاشت ستون‌ها با پیشنهاد خودکار ← پیش‌نمایش ۵۰ ردیف ← تطبیق خودکار با انتظارات ← ذخیره به‌عنوان adapter ← استخراج آزمایشی ← گزارش تطبیق (تعداد ردیف، مجموع‌ها، hash) ← تأیید و ساخت snapshot.
79 +
80 +### ب‌۷. Snapshot و تطبیق با منبع
81 +
82 +- هر استخراج: ExtractionRun با پارامترها، نسخهٔ adapter، زمان، تعداد ردیف، مجموع‌های کنترلی (جمع بدهکار، بستانکار، ماندهٔ ابتدا/پایان) و hash کل.
83 +- تطبیق دوطرفه: مجموع‌های محاسبه‌شده توسط خود دیتابیس مبدأ (با SUM در پرس‌وجوی جداگانه) باید دقیقاً با مجموع‌های snapshot برابر باشد؛ اختلاف = توقف.
84 +- استخراج دوباره برای همان دوره، snapshot جدید می‌سازد و تفاوت با قبلی را نشان می‌دهد (حساب‌های تغییرکرده). تا وقتی سال Draft است مجاز است، پس از تأیید فقط از مسیر Reopen.
85 +- پشتیبانی از استخراج افزایشی فقط وقتی منبع شناسهٔ تغییر قابل‌اتکا دارد؛ پیش‌فرض همیشه استخراج کامل دوره است (سادگی و صحت مقدم بر سرعت).
86 +
87 +### ب‌۸. بسته‌های داده (Packs) برای عمومی‌بودن
88 +
89 +- **StatementTemplatePack:** ردیف‌ها، ترتیب، شمارهٔ یادداشت، فرمول، قواعد مرتب‌سازی و عنوان‌ها به‌صورت داده؛ نسخه‌دار؛ هر صورت یک قالب و هر شرکت یک قالب انتخاب‌شده دارد.
90 +- **MappingPack:** الگوی نگاشت سرفصل‌ها به یادداشت‌ها برای یک نوع کسب‌وکار/استاندارد؛ هنگام راه‌اندازی شرکت جدید، موتور پیشنهاد نگاشت می‌دهد (بر پایهٔ پیشوند کد، شباهت نام فارسی نرمال‌شده و نگاشت شرکت‌های مشابه)، هرگز تأیید خودکار.
91 +- **Industry Profiles:** صنایع نمونه (تولیدی، بازرگانی، خدماتی، انرژی/انتقال) فقط به‌صورت بستهٔ داده؛ بستهٔ فعلی شرکت انتقال‌دهنده یکی از آن‌هاست، نه پیش‌فرض سامانه.
92 +- **قاعده:** افزودن شرکت یا صنعت جدید باید بدون تغییر کد و فقط با افزودن بسته ممکن باشد؛ این با تست «شرکت ساختگی دوم» در CI اثبات شود.
93 +
94 +### ب‌۹. هرم اعتماد («ضدگلوله» یعنی چه)
95 +
96 +ضدگلوله‌بودن با ادعا حاصل نمی‌شود، با لایه‌های قابل‌اندازه‌گیری حاصل می‌شود:
97 +
98 +1. **تست طلایی چندشرکتی:** حداقل سه مجموعه‌داده با ساختار متفاوت (شرکت فعلی + دو شرکت دیگر، واقعی یا ناشناس‌شده) که خروجی هرکدام با صورت رسمی/دستی همان شرکت ریال‌به‌ریال می‌خواند.
99 +2. **محاسبهٔ مستقل دوگانه (Dual-path):** جمع‌های هر ردیف صورت علاوه بر موتور اصلی، با یک مسیر مستقل (پرس‌وجوی SQL تجمیعی روی snapshot) محاسبه و برابری الزامی شود. نتیجهٔ ناهمخوان = باگ تا اثبات خلاف.
100 +3. **تست‌های متامورفیک:** جابه‌جایی ترتیب ردیف‌ها، تقسیم یک حساب به دو حساب با جمع برابر، یا اضافه‌کردن حساب با مانده صفر نباید جمع‌ها را عوض کند.
101 +4. **Property-based و تخریبی** (کتابچهٔ ۱ بخش ۱۴).
102 +5. **حالت اجرای موازی (Shadow Run):** برای یک دورهٔ واقعی، خروجی Aram کنار صورت دستی قرار می‌گیرد و گزارش اختلاف ردیف‌به‌ردیف تولید می‌شود؛ پذیرش نهایی بر پایهٔ همین گزارش است.
103 +6. **بازتولیدپذیری:** هر خروجی رسمی از CalculationRun با hash ورودی/کد/adapter/قالب؛ اجرای دوباره بایت‌به‌بایت یکسان.
104 +
105 +### ب‌۱۰. امنیت (افزون بر کتابچهٔ ۱ بخش ۱۳)
106 +
107 +- حداقل دسترسی برای کاربر دیتابیس منبع؛ ثبت اینکه کدام کاربر/ماشین چه استخراجی انجام داد.
108 +- فهرست مجاز افزونه‌ها با hash؛ افزونهٔ Connector بدون اجازهٔ صریح به فایل‌سیستم/شبکهٔ غیرمنبع دسترسی ندارد.
109 +- ناشناس‌سازی خروجی پشتیبانی (حذف نام شرکت/مبالغ) برای ارسال خطا.
110 +- SBOM و لاک‌فایل با hash برای وابستگی‌ها؛ بسته‌های نصب امضاشده؛ به‌روزرسانی آفلاین با بستهٔ امضاشده.
111 +- سیاست نگه‌داری: مدت نگه‌داری snapshotها و لاگ‌ها قابل‌تنظیم؛ حذف فقط با دو نقش و ثبت در audit.
112 +
113 +### ب‌۱۱. تجربهٔ کاربری
114 +
115 +وب‌اپ محلی فارسی RTL با پشتیبانی کامل موبایل در سطح مرورگر؛ کاربر اصلی مسیرهایی را بدون ابزار جانبی طی کند: راه‌اندازی شرکت ← اتصال/ورود داده ← نگاشت ← یادداشت‌ها ← صورت‌ها و کنترل‌ها ← تأیید ← خروجی. هر صفحه وضعیت واقعی سال (Draft/Reviewed/Approved/Locked) و علت غیرفعال‌بودن دکمه‌ها را نشان دهد. طرح صفحات در بوم طراحی ضمیمه به‌عنوان مرجع سبک است؛ مجاز به بهبود ولی نه حذف عناصر کنترلی (کنترل‌ها، ردیابی، وضعیت).
116 +
117 +### ب‌۱۲. استقرار
118 +
119 +پیش‌فرض: نصب محلی آفلاین Windows با SQLite. حالت سرور (چندکاربره هم‌زمان، PostgreSQL، TLS) در نسخهٔ بعد؛ از هم‌اکنون معماری، مدل داده و migrationها روی PostgreSQL در CI تست می‌شوند. هر دو حالت از یک کد با پیکربندی اجرا شوند.
120 +
121 +## بخش ۱۳ — نقشهٔ راه (به ترتیب؛ هر فاز با معیار پذیرش مبتنی بر شواهد)
122 +
123 +- **فاز C0 — اصلاح مسیر:** بخش الف کامل.
124 +- **فاز C1 — برش عمودی واقعی:** لجر ۱۴۰۴ ← LedgerBalance ← کنترل‌های C-01/C-02 ← نگاشت ← BS/IS ← تطبیق با صورت رسمی. پذیرش: تست طلایی سبز یا اختلاف‌ها مستند.
125 +- **فاز C2 — نگاشت و یادداشت‌ها:** کتابچهٔ ۱ فازهای ۲ و ۳.
126 +- **فاز C3 — چهار صورت و کنترل‌ها:** BS/IS/EQ/CF، همهٔ کنترل‌های C-01..C-15، مقایسهٔ دو سال، سال ۱۴۰۳.
127 +- **فاز C4 — چارچوب Connector و FileConnector:** مدل افزونه، مانیفست، Conformance Suite، Adapter، snapshot و تطبیق. پذیرش: ورود لجر فعلی از طریق FileConnector دقیقاً همان snapshot فاز C1 را بدهد.
128 +- **فاز C5 — Connector دیتابیس:** SQLite/PostgreSQL، سپس SQL Server، با دیتابیس آزمایشی در CI؛ وزارت/شرکت واقعی فقط با کاربر فقط‌خواندنی.
129 +- **فاز C6 — بسته‌های داده و عمومی‌سازی:** قالب و نگاشت به‌صورت بسته؛ اثبات با «شرکت ساختگی دوم» و سپس شرکت دوم واقعی.
130 +- **فاز C7 — UI کامل و خروجی‌ها:** کتابچهٔ ۱ فازهای ۵ و ۶ بر پایهٔ مدل جدید.
131 +- **فاز C8 — امنیت و ممیزی:** کتابچهٔ ۱ فاز ۷ + بخش ب‌۱۰.
132 +- **فاز C9 — بسته‌بندی و استقرار:** کتابچهٔ ۱ فاز ۸ + SBOM و امضا.
133 +- **فاز C10 — پذیرش:** Shadow Run روی دورهٔ واقعی دو شرکت و امضای مالک.
134 +
135 +قاعدهٔ ورود به فاز بعد: شواهد فاز قبل (SHA، CI، خروجی تست، گزارش تطبیق) در `PROJECT_STATUS.md` ثبت شده باشد.
136 +
137 +## بخش ۱۴ — قواعد تصمیم خودکار (بدون پرسش از مالک)
138 +
139 +برای هر ابهام: پیش‌فرض را اعمال کن، با داده بسنج، شواهد را در ADR ثبت کن، ادامه بده. شواهد بر پیش‌فرض مقدم است. تصمیم‌های کتابچهٔ ۱ بخش ۱۷ (OD-01 تا OD-08) معتبر و ادامه‌دارند. تصمیم‌های تازه:
140 +
141 +| کد | پیش‌فرض | اثبات یا اصلاح |
142 +|---|---|---|
143 +| OD-09 درایور SQL Server | python-tds (خالص‌پایتون)، با pyodbc به‌عنوان جایگزین | آزمون اتصال و استخراج ۱۰۰هزار ردیف؛ اگر ناپایدار بود pyodbc |
144 +| OD-10 زبان adapter | YAML با اعتبارسنجی JSON Schema | تست round-trip و پیام خطای فارسی دقیق |
145 +| OD-11 اجرای افزونه | فرایند جداگانه برای Connectorها | اگر مانع بسته‌بندی Windows شد، همان‌فرایند با مجوز محدود و ثبت ADR |
146 +| OD-12 سطح داده | پیش‌فرض تراز آزمایشی؛ سطح سند اختیاری و بعد از فاز C6 | فقط وقتی یادداشت خاصی بدون ریز سند قابل‌محاسبه نبود فعال شود |
147 +| OD-13 همزمانی | تک‌نصب محلی؛ سرور چندکاربره خارج از V1 | تست PostgreSQL در CI برای مسیر آینده |
148 +| OD-14 مقایسه با ابزارهای مشابه | از آن‌ها فقط الهام بگیر؛ کد، برند و محتوا کپی نشود | ردیف مقایسهٔ قابلیت‌ها در یک ADR |
149 +| سایر ابهام‌ها | محافظه‌کارانه‌ترین گزینه (آنی که تأیید را مسدود می‌کند) | ADR با گزینه‌های ردشده |
150 +
151 +**توقف مجاز فقط در دو حالت:** خطر تغییر یا نابودی داده/دیتابیس مبدأ، یا تضاد مستقیم با `AGENTS.md`. در این دو حالت وضعیت را گزارش و روی کارهای مستقل ادامه بده.
152 +
153 +## بخش ۱۵ — تعریف «تمام‌شده» نسخهٔ ۲
154 +
155 +1. تست طلایی سه شرکت سبز (یا اختلاف‌ها با علت و امضا در `docs/discrepancies.json`).
156 +2. ورود از FileConnector و حداقل دو Connector دیتابیس از مسیر Conformance Suite.
157 +3. شرکت دوم بدون تغییر کد فقط با افزودن بسته راه‌اندازی شد.
158 +4. محاسبهٔ مستقل دوگانه و تست‌های متامورفیک سبز.
159 +5. SQL خام روی سال قفل‌شده شکست می‌خورد و audit زنجیره‌ای تأیید می‌شود.
160 +6. بستهٔ Windows روی ماشین تمیز آفلاین نصب و اجرا می‌شود.
161 +7. Shadow Run دو شرکت و امضای مالک.
162 +8. گزارش پایان هر فاز با قالب کتابچهٔ ۱ بخش ۱۸ و جملهٔ `Ready for independent GitHub review; not merged.`
163 +
164 +## بخش ۱۶ — ممنوعیت‌ها
165 +
166 +همهٔ ممنوعیت‌های کتابچهٔ ۱ بخش ۱۹، و افزون بر آن: وابستگی به شبکه در زمان اجرا؛ هر نام/کد/سرفصل مختص یک شرکت در کد؛ نوشتن در دیتابیس مبدأ؛ ذخیرهٔ رمز در متن آشکار؛ کوئری سفارشی بدون تجزیهٔ نحوی؛ ادغام PR توسط خود ایجنت؛ ادعای تکمیل بدون شواهد؛ و افزودن مستند تحلیلی جدید در ریشهٔ مخزن.
167 +
168 +## پیوست — ایدهٔ مرجع: databansoft.ir
169 +
170 +مالک این سایت را به‌عنوان الهام برای اتصال دیتابیس‌محور معرفی کرده است. نگارندهٔ این کتابچه نتوانست صفحهٔ آن را بارگذاری کند، پس هیچ ادعایی دربارهٔ قابلیت‌های آن نوشته نشده است. اگر خودت به آن دسترسی داری، فقط قابلیت‌های قابل‌مشاهده را فهرست کن و در ADR با بخش‌های ب‌۳ تا ب‌۶ مقایسه کن؛ کد، متن، طراحی و برند آن هرگز کپی نشود. هرجا تفاوتی بود، این کتابچه مقدم است مگر اینکه شواهدی بهتر ارائه شود.
docs/booklet/MANIFEST.json
+23 -9
@@ -1,11 +1,25 @@
1 {
2 - "reference": "BOOKLET_v1.0.md",
3 - "original_filename": "کتابچهٔ اجرایی تکمیل Aram.pdf",
4 - "original_format": "PDF",
5 - "original_sha256": "7dd508274babd604f74d10b692464ce42f26a88c4a7116cfd861188abd4a2baf",
6 - "original_size_bytes": 745088,
7 - "page_count": 14,
8 - "extraction_tool": "pymupdf",
9 - "extraction_method": "per-line whitespace-token reversal (visual RTL -> logical reading order)",
10 - "note": "Original binary not committed (§19); SHA-256 is the integrity anchor. Mission B0.1 referenced docx; the actual provided source is PDF."
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": "9738f8049703ca63ea6eae471538cdadc6328e4f15efaaf87a250315e516e2fc",
21 + "markdown_size_bytes": 23389,
22 + "note": "Verbatim owner work order. Supersedes conflicting sections of booklet 1 and supplements the rest. Integrity anchor is the SHA-256 of this markdown. See ADR-027."
23 + }
24 + ]
25 }
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/handoff/LATEST_HANDOFF.md
+8 -8
@@ -15,17 +15,17 @@
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
18 -## Active mission — B0…B12 remediation
18 +## Active mission — booklet 2 course correction + C0…C10 roadmap
19
20 -One focused PR per category, strictly sequential (next only after prior acceptance). Executor only; independent reviewer separate; no "done" without evidence (§19). Ambiguities closed via §17 (default + proof + ADR), never by querying the owner. `data/` + `samples/` read-only with before/after tree-hash evidence per PR. No merge, no tag, no binaries/secrets committed.
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
22 -- **B0 (this PR, IN_PROGRESS):** booklet version-controlled + manifest (ADR-025); `PROJECT_STATUS.md` rewritten to GitHub reality; 14 root analytical docs → `docs/archive/`; AGENTS.md ↔ §0.5 conflict resolved, handoff cadence → per-category (ADR-026); `docs/discrepancies.json` skeleton.
23 -- **B1…B12:** NOT_IMPLEMENTED; see the category table in `PROJECT_STATUS.md` for scope. B12 history rewrite BLOCKED absent explicit owner directive.
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 +- **C1…C10:** NOT_IMPLEMENTED; see the phase table in `PROJECT_STATUS.md`. C10 = Shadow Run two companies + owner signature. History rewrite / large-file migration BLOCKED absent owner directive (C9).
24
25 -### B0 protected-data evidence
25 +### C0 protected-data evidence
26
27 -- `data/` tree `2ef8a512523f62f0cf84c5009f141be2f8a9cb5f`, `samples/` tree `00aba54b1dc30485ba9b164c8036a7b4bbe9020e` — unchanged before/after (B0 is docs/process only).
28 -- Working branch `arena/094f314c-aram` aligned to accepted base `46253c9` via merge (no force-push).
27 +- `data/` tree `2ef8a512523f62f0cf84c5009f141be2f8a9cb5f`, `samples/` tree `00aba54b1dc30485ba9b164c8036a7b4bbe9020e` — unchanged before/after (C0 removes browser edition + docs/process only).
28 +- 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).
29
30 ## Durable role-based operating model
31
@@ -51,4 +51,4 @@ One focused PR per category, strictly sequential (next only after prior acceptan
51
52 ## Single next action
53
54 -Independent GitHub review of the B0 PR (booklet reference + lightweight-process reconciliation). After B0 acceptance, start B1 (security fail-closed) from the new accepted head. Do not merge or tag; do not begin B1 before B0 acceptance.
54 +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