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

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

Synced Dec 3, 23:15 UTC

feat: Booklet v1.0 Phases 0-9 — auditable statements, workbench, outputs, admin, desktop, UAT (#96)

Owner-accepted merge (independent review waived by owner). Offline desktop/local app: exact-rial BS/IS/CF/EQ + notes from real 1403/1404 ledgers, drill-down lineage, approval gate, users/roles, reopen/lock, verifiable backup, reviewable XLSX/JSON outputs, PyInstaller recipe. 319 backend tests green; mypy/ruff clean; frontend eslint/tsc/vitest/Playwright green; CI green; source data unchanged. 5-pass compliance review: docs/reviews/BOOKLET_COMPLIANCE_REVIEW.md.

davoodmehraban89 committed Dec 3, 2026 at 18:52 UTC 46253c94405abd065dfc5e8cf080b295cb83cde4
154 files changed +24327 -102
.github/workflows/backend-ci.yml
+64 -4
@@ -16,7 +16,8 @@ permissions:
16 contents: read
17
18 jobs:
19 - test:
19 + quality:
20 + name: Lint, types, coverage
21 runs-on: ubuntu-latest
22 defaults:
23 run:
@@ -30,13 +31,72 @@ jobs:
31 cache-dependency-path: backend/pyproject.toml
32 - name: Install
33 run: python -m pip install -e '.[test]'
33 - - name: Test
34 - run: pytest
35 - - name: Validate migration round-trip
34 + - name: Whitespace guard
35 + run: git diff --check
36 + - name: Ruff lint
37 + run: ruff check src tests
38 + - name: Ruff format (Phase-0 layers)
39 + run: ruff format --check src/aram_backend/domain src/aram_backend/services migrations
40 + - name: Mypy (domain, strict)
41 + run: mypy src/aram_backend/domain
42 + - name: Mypy (services)
43 + run: mypy src/aram_backend/services
44 + - name: Tests + coverage gates
45 + run: |
46 + pytest --cov=aram_backend --cov-report=term-missing --cov-report=xml \
47 + --cov-fail-under=80
48 + coverage report --include='*/domain/*' --fail-under=90
49 + - name: Dependency vulnerability scan
50 + run: pip-audit --progress-spinner off
51 +
52 + migrations:
53 + name: Migration round-trip (${{ matrix.dialect }})
54 + runs-on: ubuntu-latest
55 + strategy:
56 + fail-fast: false
57 + matrix:
58 + dialect: [sqlite, postgresql]
59 + defaults:
60 + run:
61 + working-directory: backend
62 + services:
63 + postgres:
64 + image: postgres:16
65 + env:
66 + POSTGRES_USER: aram
67 + POSTGRES_PASSWORD: aram
68 + POSTGRES_DB: aram_test
69 + ports:
70 + - 5432:5432
71 + options: >-
72 + --health-cmd "pg_isready -U aram"
73 + --health-interval 10s
74 + --health-timeout 5s
75 + --health-retries 5
76 + steps:
77 + - uses: actions/checkout@v4
78 + - uses: actions/setup-python@v5
79 + with:
80 + python-version: "3.12"
81 + cache: pip
82 + cache-dependency-path: backend/pyproject.toml
83 + - name: Install
84 + run: python -m pip install -e '.[test,ci]'
85 + - name: SQLite round-trip
86 + if: matrix.dialect == 'sqlite'
87 env:
88 ARAM_DATABASE_URL: sqlite:///./ci-migration.db
89 run: |
90 alembic upgrade head
91 alembic downgrade base
92 + alembic upgrade head
93 + - name: PostgreSQL round-trip
94 + if: matrix.dialect == 'postgresql'
95 + env:
96 + ARAM_DATABASE_URL: postgresql+psycopg://aram:aram@localhost:5432/aram_test
97 + run: |
98 + alembic upgrade head
99 + alembic downgrade base
100 + alembic upgrade head
101 - name: Compile
102 run: python -m compileall -q src tests migrations
.github/workflows/frontend-ci.yml new
+68
@@ -0,0 +1,68 @@
1 +name: Frontend CI
2 +
3 +on:
4 + pull_request:
5 + paths:
6 + - "frontend/**"
7 + - ".github/workflows/frontend-ci.yml"
8 + push:
9 + branches:
10 + - source-data-cleanup
11 + paths:
12 + - "frontend/**"
13 + - ".github/workflows/frontend-ci.yml"
14 +
15 +permissions:
16 + contents: read
17 +
18 +jobs:
19 + quality:
20 + name: Lint, types, unit tests, build
21 + runs-on: ubuntu-latest
22 + defaults:
23 + run:
24 + working-directory: frontend
25 + steps:
26 + - uses: actions/checkout@v4
27 + - uses: actions/setup-node@v4
28 + with:
29 + node-version: "22"
30 + cache: npm
31 + cache-dependency-path: frontend/package-lock.json
32 + - name: Install
33 + run: npm ci --no-audit --no-fund
34 + - name: ESLint
35 + run: npm run lint
36 + - name: TypeScript
37 + run: npm run typecheck
38 + - name: Unit tests (vitest)
39 + run: npm test
40 + - name: Build
41 + run: npm run build
42 +
43 + e2e:
44 + name: Playwright e2e
45 + runs-on: ubuntu-latest
46 + defaults:
47 + run:
48 + working-directory: frontend
49 + steps:
50 + - uses: actions/checkout@v4
51 + - uses: actions/setup-node@v4
52 + with:
53 + node-version: "22"
54 + cache: npm
55 + cache-dependency-path: frontend/package-lock.json
56 + - name: Install
57 + run: npm ci --no-audit --no-fund
58 + - name: Install Playwright browsers
59 + run: npx playwright install --with-deps chromium
60 + - name: Run e2e
61 + run: npm run test:e2e
62 + - name: Upload report
63 + if: always()
64 + uses: actions/upload-artifact@v4
65 + with:
66 + name: playwright-report
67 + path: frontend/playwright-report
68 + retention-days: 7
.github/workflows/pilot-pages.yml new
+44
@@ -0,0 +1,44 @@
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
PROJECT_STATUS.md
+69
@@ -78,6 +78,75 @@ The accepted branch does not include PR #7 desktop/release work, PR #16 alternat
78 2. The independent reviewer re-fetches the resulting documentation-only head, confirms that its comparison with `b3dc8b3a18934ffe63f615e4f650248be21a5f9c` changes only `PROJECT_STATUS.md` and `docs/handoff/LATEST_HANDOFF.md`, verifies the final workflow result, then marks the PR ready and squash-merges it.
79 3. Only after V1-01 is accepted, start the first focused Gate 3 Mapping import/persistence task from the new accepted head.
80
81 +## Booklet v1.0 — Phase 0 (execution work order)
82 +
83 +Authoritative work order: «کتابچهٔ اجرایی تکمیل Aram» v1.0 (base head `7dc864fd032f0c4ae4d650d89304a01286a6d914`, PR #21 merge). Branch `arena/094f314c-aram`. Per §17 the agent resolves ambiguities by default + real-data proof + ADR and never queries the owner; the owner's sole role is Phase-9 final acceptance.
84 +
85 +| Debt | State | Evidence |
86 +|---|---|---|
87 +| D-01 LedgerBalance model | VERIFIED_BUT_UNMERGED | commit `a3c330b`; exact-rial round-trip + aggregation tests |
88 +| D-02 controls in preflight | VERIFIED_BUT_UNMERGED | commit `8f2f902`; C-01..C-04 preflight tests |
89 +| D-03 Rial money column | VERIFIED_BUT_UNMERGED | commit `a3c330b`; BIGINT storage >2^53 via ORM; ADR-012 |
90 +| D-04 numeric code normalization | VERIFIED_BUT_UNMERGED | commit `ac565e9`; integral-numeric exact, leading zeros preserved |
91 +| D-05 Persian header matching | VERIFIED_BUT_UNMERGED | commit `ac565e9`; normalize_fa header matching |
92 +| D-06 source bytes + CSV | VERIFIED_BUT_UNMERGED | commit `a661423`; content-addressed store + CSV encodings/delimiters |
93 +| D-07 immutability + audit + reopen | VERIFIED_BUT_UNMERGED | commit `00ca58e`; raw-SQL locked-year guards, hash chain, ADR-016 |
94 +| D-08 status/log refresh | IN_PROGRESS | this entry |
95 +| D-09 git-history rewrite | BLOCKED | owner-only; requires explicit owner approval (§19) |
96 +| D-10 hierarchy mapping | VERIFIED_BUT_UNMERGED | commit `ac565e9`; ADR-014 (general=kol, subsidiary=حساب) |
97 +| D-11 inspection guards | VERIFIED_BUT_UNMERGED | commit `ac565e9`; max_column None guard |
98 +| D-12 CI quality gates | VERIFIED_BUT_UNMERGED | commit `8412c56`; ruff/mypy/coverage/pip-audit/PG matrix; ADR-017 |
99 +
100 +Phase-0 local evidence: 201 tests passed; ruff clean; mypy domain strict clean; coverage total 92% / domain 97%; pip-audit no known vulnerabilities; SQLite migration up/down/up clean. PostgreSQL migration path is exercised by the CI matrix (no local PG). Real-data evidence (source_1404.xlsx, 252,898 rows): debit-positive C-01 holds 252,892/252,898; Σdebit=Σcredit=10,823,163,409,740,108; OD-01 refuted (T1..T4 concat ≠ حساب), ADR-014 adopted. No canonical `data/` or `samples/` file changed.
101 +
102 +ADRs added: 012 (money scale/rounding), 013 (sign contract), 014 (T1..T4 hierarchy), 016 (reopen/immutability), 017 (CI gates/tooling).
103 +
104 +## Booklet v1.0 — Phases 1–4 + owner priority fixes (execution work order)
105 +
106 +Continuation on branch `arena/094f314c-aram` (base `7dc864fd`). Per §17 the agent resolves by default + real-data proof + ADR and never queries the owner.
107 +
108 +| Phase / item | State | Evidence |
109 +|---|---|---|
110 +| Phase 1 statements + drill-down | VERIFIED_BUT_UNMERGED | commit `9c33586`; build_statements BS/IS, drill_down source{filename,file_hash,sheet,row} |
111 +| Phase 2 mapping import/export | VERIFIED_BUT_UNMERGED | commit `cfbd879`; mapping_io Mappings sheet, fail-closed, idempotent |
112 +| Phase 3 note formula engine | VERIFIED_BUT_UNMERGED | commit `9fba3c6`; AST formula (no eval), acct/row/note/sum/abs, cycle detection |
113 +| Phase 4 golden comparison | VERIFIED_BUT_UNMERGED | commit `225a38c`; golden.py header-name columns; 1403+1404 real-data tests pass |
114 +| Fix 1 money/P-02 (ADR-012) | VERIFIED_BUT_UNMERGED | commit `a00b0dc`; 457,074 rows, 0 fractional rial; 7 guard tests |
115 +| Fix 2 raw-row drill-down (D3/P-01) | VERIFIED_BUT_UNMERGED | commit `f7c3b4a`; one LedgerBalance per source row; ledger_aggregate service; migration 20261203_05 round-trip |
116 +| Fix 3 approval gate (D5/C-03) | VERIFIED_BUT_UNMERGED | commit `1844a62`; evaluate_controls explicit; hard ERROR gate; 13 tests |
117 +| Fix 4 tests + CI (D-12/§14) | VERIFIED_BUT_UNMERGED | commits `225a38c`,`be08192`; mypy services gate; frontend eslint/tsc/vitest/Playwright |
118 +| Phase 5 UI + Playwright | VERIFIED_BUT_UNMERGED | commits `fa64baf`,`77fbe70`; RTL workbench (setup/import/mapping/statements/drill-down/approval/admin); eslint/tsc/vitest/build + Playwright gates |
119 +| Phase 6 reviewable outputs | VERIFIED_BUT_UNMERGED | commit `c4c37c0`; statement_export XLSX+JSON with exact rial + lineage; ADR-022 |
120 +| Phase 7 users/audit/reopen/backup | VERIFIED_BUT_UNMERGED | commit `e20572d`; roles+PBKDF2, controlled reopen/lock, verifiable backup; migration 20261203_07; ADR-023 |
121 +| Phase 8 desktop packaging | VERIFIED_BUT_UNMERGED | commit `ffc9888`; desktop entrypoint (127.0.0.1) + PyInstaller recipe; ADR-024; no binary committed (§19) |
122 +| Phase 9 UAT + release prep | VERIFIED_BUT_UNMERGED | `scripts/uat_real_data.py`; real-1404 UAT evidence below; tag v1.0.0 is the owner's post-acceptance action |
123 +
124 +Local evidence at head `dafb559`: backend **308 tests passed**; ruff clean; mypy domain strict + services clean; frontend lint/tsc/vitest/build pass; Playwright smoke + workflow specs valid. Migrations 20261203_05/06/07 up/down/up verified (SQLite). No canonical `data/` or `samples/` file changed.
125 +
126 +### Phase 9 UAT evidence (real source_1404.xlsx, read-only)
127 +
128 +`python scripts/uat_real_data.py --year 1404` on a fresh local DB:
129 +- Import: **131,280 raw rows** preserved (4 anomalous rows skipped + reported).
130 +- Auto-mapping from embedded note numbers: 22 notes, 244 mappings.
131 +- Build: BS/IS/CF/EQ persisted; 1 unmapped ordinary account surfaced.
132 +- Golden reconciliation: core balance-sheet notes match official **rial-for-rial**
133 + (÷10⁶ half-up): 10→673,740,637 · 11→242,194 · 12-1→13,386,398 · 12-2→8,310,168 ·
134 + 13→6,839,535 · 14→11,273,650 · 15→19,951,136 (plus zero notes 17-1/17-2). Remaining
135 + BS/IS differences are surfaced as discrepancies (OD-08), never silently corrected.
136 +- Approval gate: correctly **blocks** on real-data control failures (C-01/C-03/C-04) —
137 + fail-loud, no bypass.
138 +- Export: XLSX (6.27 MB) + JSON with **158,050 lineage rows** (file/SHA-256/sheet/row).
139 +- Backup: created + verified (hashes + audit chain); audit chain valid.
140 +
141 +ADRs added in this stretch: 021 (golden scale/columns), 022 (outputs), 023 (users/reopen/backup), 024 (desktop packaging).
142 +
143 +### Release procedure (owner, after independent review)
144 +
145 +The implementation author does **not** merge or tag (§19). After independent GitHub
146 +review approves PR #96 and it is merged into `source-data-cleanup`, the owner creates
147 +the release tag `v1.0.0` on the accepted head and builds the Windows package from
148 +`packaging/build_desktop.py` (artifact retained in the release, not committed).
149 +
150 ## Control documents
151
152 - [Project log](docs/PROJECT_LOG.md)
backend/.gitignore
+7
@@ -1,8 +1,15 @@
1 .venv/
2 __pycache__/
3 .pytest_cache/
4 +*.egg-info/
5 *.py[cod]
6 *.db
7 *.sqlite
8 *.sqlite3
9 +.coverage
10 +.coverage.*
11 +htmlcov/
12 +coverage.xml
13 +.mypy_cache/
14 +.ruff_cache/
15
backend/README.md
+58
@@ -1,5 +1,63 @@
1 # Aram backend
2
3 +## Pilot Workbench (working V1 slice)
4 +
5 +A runnable, end-to-end pilot application lives at `/pilot/` (the root URL
6 +redirects there). It takes a Pilot workbook v0.1 `.xlsx`, runs the accepted
7 +read-only preflight, lets a reviewer resolve the mapping exception queue,
8 +and produces draft Balance Sheet and Income Statement output with full
9 +account-to-source-row drill-down, explicit checks, an audit trail, and a
10 +reviewable Excel export.
11 +
12 +```bash
13 +cd backend
14 +python -m pip install -e '.[test]'
15 +uvicorn aram_backend.main:app --host 0.0.0.0 --port 8000
16 +# open http://localhost:8000/pilot/
17 +```
18 +
19 +- `POST /api/v1/pilot/demo` starts a clearly-labelled **synthetic** demo with
20 + two unmapped suspense accounts so the full workflow can be exercised.
21 +- `POST /api/v1/pilot/sessions` (multipart `file`) uploads a real workbook.
22 +- `PUT/DELETE /api/v1/pilot/sessions/{id}/mappings/{account}` edit mappings;
23 + every change is recorded in the session audit trail. Reviewed/Approved
24 + statuses require a reviewer name, mirroring the workbook contract.
25 +- `GET /api/v1/pilot/sessions/{id}/export.xlsx` downloads the reviewable
26 + output (Info, Checks, BalanceSheet, IncomeStatement, Coverage, Exceptions,
27 + AuditTrail).
28 +
29 +### Generic, company-agnostic editing
30 +
31 +The workbench is not tied to any specific company. Within a session you can:
32 +
33 +- **Accounts** — `POST /accounts` add, `PUT /accounts/{code}` edit,
34 + `POST /accounts/{code}/rename` change the code (the mapping is carried
35 + forward automatically), `DELETE /accounts/{code}` remove. A manually added
36 + account's closing balance is derived from `opening + debit - credit`, never
37 + invented; duplicate codes and non-finite values are rejected.
38 +- **Notes & sub-notes** — `POST /notes` add a note or sub-note, `PUT /notes`
39 + edit its title, `DELETE /notes` remove it. Deleting a note that is the
40 + target of any mapping is blocked (HTTP 409) until those mappings move.
41 +- **Company** — `PUT /company` changes name/code/fiscal-year/unit/currency, so
42 + the same workspace serves any entity.
43 +- **Save / resume** — `GET /sessions/{id}/workspace.xlsx` serializes the full
44 + working state back to a valid Pilot v0.1 workbook. Re-uploading it rebuilds
45 + the same accounts, notes, mappings and company (lossless round-trip), so work
46 + survives across sessions without a database.
47 +
48 +Every edit is append-only audited (actor, action, before, after). The UI is
49 +mobile-first: bottom navigation, bottom-sheet forms, card layouts, and numeric
50 +keyboards, so the whole workflow is usable on a phone.
51 +
52 +Safety boundary: sessions are strictly in memory (bounded, thread-safe) and
53 +disappear on restart; the durable artifact is the exported Excel file. No
54 +canonical file, database row, or source value is read or modified. Closing
55 +balances are debit-positive; display signs come only from the explicit
56 +`SECTION_POLICY` in `pilot_engine.py` (BS: Assets +, Liabilities −, Equity −;
57 +IS: Revenue −, Expenses +). Unknown sections, conflicting mappings, unmapped
58 +accounts, and CF/EQ targets fail closed into the exception queue — nothing is
59 +guessed. Output is always a working draft, never an official statement.
60 +
61 ## Pilot workbook preflight
62
63 Gate 2A adds a strictly in-memory validator for the governed Pilot workbook.
backend/migrations/env.py
-1
@@ -46,4 +46,3 @@ if context.is_offline_mode():
46 run_migrations_offline()
47 else:
48 run_migrations_online()
49 -
backend/migrations/versions/20260820_01_initial_schema.py
+1 -1
@@ -2,6 +2,7 @@
2
3 Revision ID: 20260820_01
4 """
5 +
6 from alembic import op
7
8 from aram_backend.database import Base
@@ -21,4 +22,3 @@ def upgrade() -> None:
22 def downgrade() -> None:
23 bind = op.get_bind()
24 Base.metadata.drop_all(bind=bind)
24 -
backend/migrations/versions/20261203_02_ledger_balance_and_rial.py new
+49
@@ -0,0 +1,49 @@
1 +"""LedgerBalance table + exact integer-rial money column (D-01, D-03).
2 +
3 +Revision ID: 20261203_02
4 +Revises: 20260820_01
5 +
6 +The initial revision uses ``Base.metadata.create_all``, so on a fresh database
7 +the table may already exist; creation is therefore guarded. The money column is
8 +converted to ``BIGINT`` (the ``Rial`` TypeDecorator's impl) in batch mode so the
9 +migration runs identically on SQLite and PostgreSQL (P-11).
10 +"""
11 +
12 +import sqlalchemy as sa
13 +from alembic import op
14 +
15 +from aram_backend.models import LedgerBalance
16 +
17 +revision = "20261203_02"
18 +down_revision = "20260820_01"
19 +branch_labels = None
20 +depends_on = None
21 +
22 +
23 +def upgrade() -> None:
24 + bind = op.get_bind()
25 + inspector = sa.inspect(bind)
26 + if "ledger_balances" not in inspector.get_table_names():
27 + # Use the model table so naming conventions match create_all exactly.
28 + LedgerBalance.__table__.create(bind=bind)
29 + with op.batch_alter_table("statement_lines") as batch:
30 + batch.alter_column(
31 + "mapped_total",
32 + existing_type=sa.Numeric(24, 4),
33 + type_=sa.BigInteger(),
34 + existing_nullable=True,
35 + )
36 +
37 +
38 +def downgrade() -> None:
39 + with op.batch_alter_table("statement_lines") as batch:
40 + batch.alter_column(
41 + "mapped_total",
42 + existing_type=sa.BigInteger(),
43 + type_=sa.Numeric(24, 4),
44 + existing_nullable=True,
45 + )
46 + bind = op.get_bind()
47 + inspector = sa.inspect(bind)
48 + if "ledger_balances" in inspector.get_table_names():
49 + op.drop_table("ledger_balances")
backend/migrations/versions/20261203_03_source_file_store.py new
+42
@@ -0,0 +1,42 @@
1 +"""Content-addressed source file storage (D-06).
2 +
3 +Revision ID: 20261203_03
4 +Revises: 20261203_02
5 +"""
6 +
7 +import sqlalchemy as sa
8 +from alembic import op
9 +
10 +from aram_backend.models import SourceFile
11 +
12 +revision = "20261203_03"
13 +down_revision = "20261203_02"
14 +branch_labels = None
15 +depends_on = None
16 +
17 +
18 +def upgrade() -> None:
19 + bind = op.get_bind()
20 + inspector = sa.inspect(bind)
21 + if "source_files" not in inspector.get_table_names():
22 + SourceFile.__table__.create(bind=bind)
23 + columns = {c["name"] for c in inspector.get_columns("source_documents")}
24 + if "source_file_hash" not in columns:
25 + with op.batch_alter_table("source_documents") as batch:
26 + batch.add_column(
27 + sa.Column(
28 + "source_file_hash",
29 + sa.String(64),
30 + sa.ForeignKey("source_files.sha256", ondelete="RESTRICT"),
31 + nullable=True,
32 + )
33 + )
34 +
35 +
36 +def downgrade() -> None:
37 + with op.batch_alter_table("source_documents") as batch:
38 + batch.drop_column("source_file_hash")
39 + bind = op.get_bind()
40 + inspector = sa.inspect(bind)
41 + if "source_files" in inspector.get_table_names():
42 + op.drop_table("source_files")
backend/migrations/versions/20261203_04_immutability_audit.py new
+54
@@ -0,0 +1,54 @@
1 +"""Locked-year immutability triggers + hash-chained audit + reopen (D-07).
2 +
3 +Revision ID: 20261203_04
4 +Revises: 20261203_03
5 +"""
6 +
7 +import sqlalchemy as sa
8 +from alembic import op
9 +
10 +from aram_backend.db_triggers import install_triggers
11 +from aram_backend.models import AuditEntry, ReopenRequest
12 +
13 +revision = "20261203_04"
14 +down_revision = "20261203_03"
15 +branch_labels = None
16 +depends_on = None
17 +
18 +
19 +def upgrade() -> None:
20 + bind = op.get_bind()
21 + inspector = sa.inspect(bind)
22 + tables = inspector.get_table_names()
23 + if "reopen_requests" not in tables:
24 + ReopenRequest.__table__.create(bind=bind)
25 + if "audit_entries" not in tables:
26 + AuditEntry.__table__.create(bind=bind)
27 + install_triggers(bind)
28 +
29 +
30 +def downgrade() -> None:
31 + bind = op.get_bind()
32 + dialect = bind.dialect.name
33 + from aram_backend.db_triggers import _YEAR_TABLES
34 +
35 + names = [f"aram_lock_{t}_{op}" for t in _YEAR_TABLES for op in ("insert", "update", "delete")]
36 + names += [
37 + "aram_audit_update",
38 + "aram_audit_delete",
39 + "aram_fiscal_year_transition",
40 + "aram_fiscal_year_no_delete",
41 + ]
42 + for name in names:
43 + if dialect == "sqlite":
44 + bind.execute(sa.text(f"DROP TRIGGER IF EXISTS {name}"))
45 + else:
46 + # Postgres triggers are table-scoped; drop via IF EXISTS on each table.
47 + for t in list(_YEAR_TABLES) + ["audit_entries", "fiscal_years"]:
48 + bind.execute(sa.text(f"DROP TRIGGER IF EXISTS {name} ON {t}"))
49 + inspector = sa.inspect(bind)
50 + tables = inspector.get_table_names()
51 + if "audit_entries" in tables:
52 + op.drop_table("audit_entries")
53 + if "reopen_requests" in tables:
54 + op.drop_table("reopen_requests")
backend/migrations/versions/20261203_05_raw_ledger_rows.py new
+60
@@ -0,0 +1,60 @@
1 +"""Raw ledger rows: uniqueness per source row instead of per account (D3, P-01).
2 +
3 +LedgerBalance now stores one row per source ledger row (no import-time
4 +aggregation) so drill-down to file/sheet/row is preserved. Fresh databases get the
5 +new constraint from the live model; this revision swaps it on pre-existing DBs and
6 +reinstalls the D-07 triggers (batch-alter recreates the table).
7 +
8 +Revision ID: 20261203_05
9 +Revises: 20261203_04
10 +"""
11 +
12 +import sqlalchemy as sa
13 +from alembic import op
14 +
15 +from aram_backend.db_triggers import install_triggers
16 +
17 +revision = "20261203_05"
18 +down_revision = "20261203_04"
19 +branch_labels = None
20 +depends_on = None
21 +
22 +_OLD = "uq_ledger_balance_year_code_version"
23 +_NEW = "uq_ledger_balance_year_source_row_version"
24 +_NEW_COLS = ["year_id", "source_document_id", "source_row", "import_version"]
25 +_OLD_COLS = ["year_id", "account_full_code", "import_version"]
26 +
27 +
28 +def _unique_names(bind) -> set:
29 + inspector = sa.inspect(bind)
30 + if "ledger_balances" not in inspector.get_table_names():
31 + return set()
32 + return {c["name"] for c in inspector.get_unique_constraints("ledger_balances")}
33 +
34 +
35 +def upgrade() -> None:
36 + bind = op.get_bind()
37 + names = _unique_names(bind)
38 + if not names and "ledger_balances" not in sa.inspect(bind).get_table_names():
39 + return
40 + if _OLD in names or _NEW not in names:
41 + with op.batch_alter_table("ledger_balances") as batch:
42 + if _OLD in names:
43 + batch.drop_constraint(_OLD, type_="unique")
44 + if _NEW not in names:
45 + batch.create_unique_constraint(_NEW, _NEW_COLS)
46 + install_triggers(bind)
47 +
48 +
49 +def downgrade() -> None:
50 + bind = op.get_bind()
51 + names = _unique_names(bind)
52 + if not names and "ledger_balances" not in sa.inspect(bind).get_table_names():
53 + return
54 + if _NEW in names or _OLD not in names:
55 + with op.batch_alter_table("ledger_balances") as batch:
56 + if _NEW in names:
57 + batch.drop_constraint(_NEW, type_="unique")
58 + if _OLD not in names:
59 + batch.create_unique_constraint(_OLD, _OLD_COLS)
60 + install_triggers(bind)
backend/migrations/versions/20261203_06_statement_balance.py new
+48
@@ -0,0 +1,48 @@
1 +"""Preserve the signed statement balance (مانده صورت مالی) on raw ledger rows.
2 +
3 +Reclassified source rows carry only the signed statement-balance figure and leave
4 +OPENING/Debit/Credit/CLOSING empty. The tolerant import keeps those rows (exact
5 +zero for the empty money cells) and stores the statement balance here so the
6 +compute layer can build statements that reconcile rial-for-rial with the official
7 +workbooks (Phase 4 golden). Nullable BIGINT via the Rial type (P-02 exact rial).
8 +
9 +Revision ID: 20261203_06
10 +Revises: 20261203_05
11 +"""
12 +
13 +import sqlalchemy as sa
14 +from alembic import op
15 +
16 +from aram_backend.db_triggers import install_triggers
17 +
18 +revision = "20261203_06"
19 +down_revision = "20261203_05"
20 +branch_labels = None
21 +depends_on = None
22 +
23 +
24 +def _has_column(bind) -> bool:
25 + inspector = sa.inspect(bind)
26 + if "ledger_balances" not in inspector.get_table_names():
27 + return False
28 + return any(c["name"] == "statement_balance" for c in inspector.get_columns("ledger_balances"))
29 +
30 +
31 +def upgrade() -> None:
32 + bind = op.get_bind()
33 + if "ledger_balances" not in sa.inspect(bind).get_table_names():
34 + return
35 + if not _has_column(bind):
36 + with op.batch_alter_table("ledger_balances") as batch:
37 + batch.add_column(sa.Column("statement_balance", sa.BigInteger(), nullable=True))
38 + install_triggers(bind)
39 +
40 +
41 +def downgrade() -> None:
42 + bind = op.get_bind()
43 + if "ledger_balances" not in sa.inspect(bind).get_table_names():
44 + return
45 + if _has_column(bind):
46 + with op.batch_alter_table("ledger_balances") as batch:
47 + batch.drop_column("statement_balance")
48 + install_triggers(bind)
backend/migrations/versions/20261203_07_users.py new
+56
@@ -0,0 +1,56 @@
1 +"""Local users with roles (Phase 7, booklet §7/§12).
2 +
3 +Adds the ``users`` table for offline desktop identity: username, role, and a
4 +PBKDF2-HMAC-SHA256 password hash + per-user salt (no plaintext). Fresh databases
5 +get the table from the live model; this revision creates it on pre-existing DBs.
6 +
7 +Revision ID: 20261203_07
8 +Revises: 20261203_06
9 +"""
10 +
11 +import sqlalchemy as sa
12 +from alembic import op
13 +
14 +from aram_backend.models import UserRole
15 +
16 +revision = "20261203_07"
17 +down_revision = "20261203_06"
18 +branch_labels = None
19 +depends_on = None
20 +
21 +
22 +def _has_table(bind, name: str) -> bool:
23 + return name in sa.inspect(bind).get_table_names()
24 +
25 +
26 +def upgrade() -> None:
27 + bind = op.get_bind()
28 + if _has_table(bind, "users"):
29 + return
30 + op.create_table(
31 + "users",
32 + sa.Column("id", sa.Integer(), primary_key=True),
33 + sa.Column("username", sa.String(length=64), nullable=False),
34 + sa.Column("display_name", sa.String(length=128), nullable=False, server_default=""),
35 + sa.Column(
36 + "role",
37 + sa.Enum(UserRole, native_enum=False, length=16),
38 + nullable=False,
39 + server_default="PREPARER",
40 + ),
41 + sa.Column("password_hash", sa.String(length=128), nullable=False),
42 + sa.Column("salt", sa.String(length=64), nullable=False),
43 + sa.Column("active", sa.Boolean(), nullable=False, server_default=sa.true()),
44 + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
45 + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
46 + sa.UniqueConstraint("username", name="uq_users_username"),
47 + )
48 + op.create_index("ix_users_username", "users", ["username"])
49 +
50 +
51 +def downgrade() -> None:
52 + bind = op.get_bind()
53 + if not _has_table(bind, "users"):
54 + return
55 + op.drop_index("ix_users_username", table_name="users")
56 + op.drop_table("users")
backend/pyproject.toml
+45 -1
@@ -14,12 +14,22 @@ dependencies = [
14 "sqlalchemy>=2.0,<3",
15 "uvicorn[standard]>=0.34,<1",
16 "openpyxl>=3.1,<4",
17 + "python-multipart>=0.0.18,<1",
18 ]
19
20 [project.optional-dependencies]
21 test = [
22 "httpx>=0.28,<1",
22 - "pytest>=8.3,<9",
23 + "pytest>=9.0.3,<10",
24 + "hypothesis>=6.100,<7",
25 + "ruff>=0.8,<1",
26 + "mypy>=1.13,<2",
27 + "coverage>=7.6,<8",
28 + "pytest-cov>=6.0,<7",
29 + "pip-audit>=2.7,<3",
30 +]
31 +ci = [
32 + "psycopg[binary]>=3.2,<4",
33 ]
34
35 [tool.setuptools.packages.find]
@@ -29,3 +39,37 @@ where = ["src"]
39 testpaths = ["tests"]
40 addopts = "-q"
41
42 +[tool.ruff]
43 +line-length = 100
44 +target-version = "py311"
45 +src = ["src", "tests"]
46 +
47 +[tool.ruff.lint]
48 +select = ["E", "F", "I", "UP", "B"]
49 +ignore = ["E501"]
50 +
51 +[tool.ruff.lint.flake8-bugbear]
52 +extend-immutable-calls = ["fastapi.File", "fastapi.Depends", "fastapi.Query", "fastapi.Form"]
53 +
54 +[tool.mypy]
55 +python_version = "3.11"
56 +plugins = []
57 +warn_unused_ignores = true
58 +warn_redundant_casts = true
59 +
60 +[[tool.mypy.overrides]]
61 +module = "aram_backend.domain.*"
62 +strict = true
63 +
64 +[[tool.mypy.overrides]]
65 +module = ["openpyxl.*", "hypothesis.*"]
66 +ignore_missing_imports = true
67 +
68 +[tool.coverage.run]
69 +source = ["aram_backend"]
70 +branch = true
71 +
72 +[tool.coverage.report]
73 +show_missing = true
74 +exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:", "raise NotImplementedError"]
75 +
backend/src/aram_backend/admin_api.py new
+275
@@ -0,0 +1,275 @@
1 +"""HTTP API for Phase 7 administration: users, audit, reopen/lock, backup.
2 +
3 +Sensitive actions are gated by local role (``require_role``) and attributed to a
4 +username in the hash-chained audit log. Offline desktop: no runtime network.
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +from fastapi import APIRouter, Depends, HTTPException
10 +from pydantic import BaseModel, Field
11 +from sqlalchemy import select
12 +from sqlalchemy.orm import Session
13 +
14 +from aram_backend.config import get_settings
15 +from aram_backend.database import get_session
16 +from aram_backend.models import AuditEntry, UserRole
17 +from aram_backend.services.audit import verify_chain
18 +from aram_backend.services.backup import BackupError, create_backup, verify_backup
19 +from aram_backend.services.reopen import (
20 + ReopenError,
21 + approve_reopen,
22 + list_reopen_requests,
23 + lock_year,
24 + reopen_year,
25 + request_reopen,
26 +)
27 +from aram_backend.services.users import (
28 + AuthorizationError,
29 + UserError,
30 + authenticate,
31 + create_user,
32 + list_users,
33 + require_role,
34 + set_active,
35 + set_role,
36 +)
37 +
38 +router = APIRouter(prefix="/api/v1", tags=["admin"])
39 +
40 +_ADMIN = {UserRole.ADMIN}
41 +_REVIEW = {UserRole.ADMIN, UserRole.REVIEWER}
42 +
43 +
44 +def _guard(session: Session, actor: str, allowed: set[UserRole]) -> None:
45 + try:
46 + require_role(session, username=actor, allowed=allowed)
47 + except AuthorizationError as exc:
48 + raise HTTPException(status_code=403, detail=str(exc)) from exc
49 +
50 +
51 +# --------------------------------------------------------------------- users
52 +class UserIn(BaseModel):
53 + username: str = Field(min_length=1, max_length=64)
54 + password: str = Field(min_length=8, max_length=256)
55 + role: UserRole = UserRole.PREPARER
56 + display_name: str = Field(default="", max_length=128)
57 + actor: str = Field(default="", max_length=64)
58 +
59 +
60 +@router.post("/users")
61 +def create_user_endpoint(body: UserIn, session: Session = Depends(get_session)) -> dict:
62 + # Bootstrap: the very first user is created without an existing admin and is
63 + # forced to the admin role (offline desktop install). Afterwards, only an
64 + # admin may create users.
65 + bootstrap = not list_users(session)
66 + if not bootstrap:
67 + _guard(session, body.actor, _ADMIN)
68 + role = UserRole.ADMIN if bootstrap else body.role
69 + try:
70 + user = create_user(
71 + session,
72 + username=body.username,
73 + password=body.password,
74 + role=role,
75 + display_name=body.display_name,
76 + actor=body.actor,
77 + )
78 + except UserError as exc:
79 + raise HTTPException(status_code=422, detail=str(exc)) from exc
80 + session.commit()
81 + return {"username": user.username, "role": user.role.value}
82 +
83 +
84 +@router.get("/users")
85 +def list_users_endpoint(actor: str = "", session: Session = Depends(get_session)) -> dict:
86 + _guard(session, actor, _ADMIN)
87 + return {
88 + "users": [
89 + {
90 + "username": u.username,
91 + "display_name": u.display_name,
92 + "role": u.role.value,
93 + "active": u.active,
94 + }
95 + for u in list_users(session)
96 + ]
97 + }
98 +
99 +
100 +class LoginIn(BaseModel):
101 + username: str = Field(min_length=1, max_length=64)
102 + password: str = Field(min_length=1, max_length=256)
103 +
104 +
105 +@router.post("/auth/login")
106 +def login(body: LoginIn, session: Session = Depends(get_session)) -> dict:
107 + try:
108 + user = authenticate(session, username=body.username, password=body.password)
109 + except UserError as exc:
110 + raise HTTPException(status_code=401, detail=str(exc)) from exc
111 + return {"username": user.username, "display_name": user.display_name, "role": user.role.value}
112 +
113 +
114 +class RoleIn(BaseModel):
115 + role: UserRole
116 + actor: str = Field(default="", max_length=64)
117 +
118 +
119 +@router.post("/users/{username}/role")
120 +def set_role_endpoint(username: str, body: RoleIn, session: Session = Depends(get_session)) -> dict:
121 + _guard(session, body.actor, _ADMIN)
122 + try:
123 + user = set_role(session, username=username, role=body.role, actor=body.actor)
124 + except UserError as exc:
125 + raise HTTPException(status_code=422, detail=str(exc)) from exc
126 + session.commit()
127 + return {"username": user.username, "role": user.role.value}
128 +
129 +
130 +class ActiveIn(BaseModel):
131 + active: bool
132 + actor: str = Field(default="", max_length=64)
133 +
134 +
135 +@router.post("/users/{username}/active")
136 +def set_active_endpoint(
137 + username: str, body: ActiveIn, session: Session = Depends(get_session)
138 +) -> dict:
139 + _guard(session, body.actor, _ADMIN)
140 + try:
141 + user = set_active(session, username=username, active=body.active, actor=body.actor)
142 + except UserError as exc:
143 + raise HTTPException(status_code=422, detail=str(exc)) from exc
144 + session.commit()
145 + return {"username": user.username, "active": user.active}
146 +
147 +
148 +# --------------------------------------------------------------------- audit
149 +@router.get("/audit")
150 +def list_audit(year_id: int | None = None, session: Session = Depends(get_session)) -> dict:
151 + stmt = select(AuditEntry).order_by(AuditEntry.id.asc())
152 + if year_id is not None:
153 + stmt = stmt.where(AuditEntry.year_id == year_id)
154 + entries = session.scalars(stmt).all()
155 + return {
156 + "chain_valid": verify_chain(session),
157 + "entries": [
158 + {
159 + "id": e.id,
160 + "year_id": e.year_id,
161 + "actor": e.actor,
162 + "action": e.action,
163 + "chain_hash": e.chain_hash,
164 + "created_at": e.created_at.isoformat(),
165 + }
166 + for e in entries
167 + ],
168 + }
169 +
170 +
171 +@router.get("/audit/verify")
172 +def verify_audit(session: Session = Depends(get_session)) -> dict:
173 + return {"chain_valid": verify_chain(session)}
174 +
175 +
176 +# --------------------------------------------------------------- reopen/lock
177 +class ReopenRequestIn(BaseModel):
178 + reason: str = Field(min_length=1, max_length=2000)
179 + actor: str = Field(default="", max_length=64)
180 +
181 +
182 +@router.post("/years/{year_id}/reopen/request")
183 +def reopen_request(
184 + year_id: int, body: ReopenRequestIn, session: Session = Depends(get_session)
185 +) -> dict:
186 + _guard(session, body.actor, _REVIEW)
187 + try:
188 + request = request_reopen(session, year_id, reason=body.reason, requested_by=body.actor)
189 + except ReopenError as exc:
190 + raise HTTPException(status_code=422, detail=str(exc)) from exc
191 + session.commit()
192 + return {"request_id": request.id, "status": request.status}
193 +
194 +
195 +class ActorIn(BaseModel):
196 + actor: str = Field(default="", max_length=64)
197 +
198 +
199 +@router.post("/reopen/{request_id}/approve")
200 +def reopen_approve(request_id: int, body: ActorIn, session: Session = Depends(get_session)) -> dict:
201 + _guard(session, body.actor, _REVIEW)
202 + try:
203 + request = approve_reopen(session, request_id, approved_by=body.actor)
204 + except ReopenError as exc:
205 + raise HTTPException(status_code=422, detail=str(exc)) from exc
206 + session.commit()
207 + return {"request_id": request.id, "status": request.status}
208 +
209 +
210 +@router.post("/years/{year_id}/reopen")
211 +def reopen(year_id: int, body: ActorIn, session: Session = Depends(get_session)) -> dict:
212 + _guard(session, body.actor, _REVIEW)
213 + try:
214 + year = reopen_year(session, year_id, actor=body.actor)
215 + except ReopenError as exc:
216 + raise HTTPException(status_code=422, detail=str(exc)) from exc
217 + session.commit()
218 + return {"year_id": year.id, "status": year.status.value}
219 +
220 +
221 +@router.post("/years/{year_id}/lock")
222 +def lock(year_id: int, body: ActorIn, session: Session = Depends(get_session)) -> dict:
223 + _guard(session, body.actor, _REVIEW)
224 + try:
225 + year = lock_year(session, year_id, actor=body.actor)
226 + except ReopenError as exc:
227 + raise HTTPException(status_code=422, detail=str(exc)) from exc
228 + session.commit()
229 + return {"year_id": year.id, "status": year.status.value}
230 +
231 +
232 +@router.get("/years/{year_id}/reopen/requests")
233 +def reopen_requests(year_id: int, session: Session = Depends(get_session)) -> dict:
234 + return {
235 + "requests": [
236 + {
237 + "id": r.id,
238 + "reason": r.reason,
239 + "requested_by": r.requested_by,
240 + "approved_by": r.approved_by,
241 + "status": r.status,
242 + }
243 + for r in list_reopen_requests(session, year_id)
244 + ]
245 + }
246 +
247 +
248 +# -------------------------------------------------------------------- backup
249 +class BackupIn(BaseModel):
250 + dest: str = Field(min_length=1, max_length=512)
251 + actor: str = Field(default="", max_length=64)
252 +
253 +
254 +@router.post("/backup")
255 +def backup(body: BackupIn, session: Session = Depends(get_session)) -> dict:
256 + _guard(session, body.actor, _ADMIN)
257 + try:
258 + manifest = create_backup(session, body.dest, store_root=get_settings().source_store_root)
259 + except BackupError as exc:
260 + raise HTTPException(status_code=422, detail=str(exc)) from exc
261 + return {"dest": body.dest, "manifest": manifest}
262 +
263 +
264 +class VerifyBackupIn(BaseModel):
265 + dest: str = Field(min_length=1, max_length=512)
266 + actor: str = Field(default="", max_length=64)
267 +
268 +
269 +@router.post("/backup/verify")
270 +def backup_verify(body: VerifyBackupIn, session: Session = Depends(get_session)) -> dict:
271 + _guard(session, body.actor, _ADMIN)
272 + try:
273 + return verify_backup(body.dest)
274 + except BackupError as exc:
275 + raise HTTPException(status_code=422, detail=str(exc)) from exc
backend/src/aram_backend/config.py
+1
@@ -7,6 +7,7 @@ class Settings(BaseSettings):
7 app_name: str = "Aram API"
8 environment: str = "development"
9 database_url: str = "sqlite:///./aram.db"
10 + source_store_root: str = "./source_store"
11 model_config = SettingsConfigDict(env_prefix="ARAM_", env_file=".env")
12
13
backend/src/aram_backend/database.py
+25 -2
@@ -1,4 +1,5 @@
1 from collections.abc import Generator
2 +from typing import Any
3
4 from sqlalchemy import MetaData, create_engine, event
5 from sqlalchemy.engine import Engine
@@ -28,7 +29,18 @@ def build_engine(database_url: str | None = None) -> Engine:
29 return engine
30
31
31 -def _enable_sqlite_foreign_keys(dbapi_connection, _connection_record) -> None:
32 +def ensure_triggers(engine: Engine) -> None:
33 + """Install DB-level immutability/audit triggers (D-07), idempotent.
34 +
35 + Call after the schema exists (post create_all / alembic upgrade). Safe to
36 + call repeatedly; triggers are dropped and recreated.
37 + """
38 + from aram_backend.db_triggers import install_on_engine
39 +
40 + install_on_engine(engine)
41 +
42 +
43 +def _enable_sqlite_foreign_keys(dbapi_connection: Any, _connection_record: Any) -> None:
44 cursor = dbapi_connection.cursor()
45 cursor.execute("PRAGMA foreign_keys=ON")
46 cursor.close()
@@ -38,7 +50,18 @@ engine = build_engine()
50 SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
51
52
53 +def reconfigure(database_url: str) -> None:
54 + """Rebind the shared engine/session factory to a new database URL.
55 +
56 + Used by the desktop entrypoint to point at the per-user local SQLite file
57 + after import time. ``get_session`` reads ``SessionLocal`` at call time, so
58 + reassigning it here takes effect for all subsequent requests.
59 + """
60 + global engine, SessionLocal
61 + engine = build_engine(database_url)
62 + SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
63 +
64 +
65 def get_session() -> Generator[Session, None, None]:
66 with SessionLocal() as session:
67 yield session
44 -
backend/src/aram_backend/db_triggers.py new
+248
@@ -0,0 +1,248 @@
1 +"""Dialect-specific DB triggers for locked-year immutability and audit (D-07).
2 +
3 +These run inside the database so raw SQL cannot bypass them (P-08). They are
4 +installed idempotently (DROP IF EXISTS + CREATE) and work on SQLite and
5 +PostgreSQL. The application-level guards in ``database.py`` remain as a first
6 +line; these are the database-level guarantee.
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +from sqlalchemy import text
12 +from sqlalchemy.engine import Connection, Engine
13 +
14 +# Year-owned tables and how to resolve their owning fiscal-year id from a row.
15 +# ``alias`` is the row reference in the trigger body.
16 +_YEAR_TABLES: dict[str, str] = {
17 + "ledger_balances": "{alias}.year_id",
18 + "account_versions": "{alias}.year_id",
19 + "note_definitions": "{alias}.year_id",
20 + "mapping_rules": "{alias}.year_id",
21 + "financial_statements": "{alias}.year_id",
22 + "source_documents": "{alias}.year_id",
23 + "note_rows": ("(SELECT nd.year_id FROM note_definitions nd WHERE nd.id = {alias}.note_id)"),
24 + "statement_lines": (
25 + "(SELECT fs.year_id FROM financial_statements fs WHERE fs.id = {alias}.statement_id)"
26 + ),
27 +}
28 +
29 +
30 +def _locked_check_sqlite(table: str, alias: str) -> str:
31 + year_expr = _YEAR_TABLES[table].format(alias=alias)
32 + return (
33 + f"SELECT RAISE(ABORT, 'fiscal year is locked; row is immutable') "
34 + f"WHERE (SELECT status FROM fiscal_years WHERE id = {year_expr}) = 'LOCKED'"
35 + )
36 +
37 +
38 +def install_triggers(conn: Connection) -> None:
39 + """Install immutability + audit triggers (idempotent)."""
40 + dialect = conn.dialect.name
41 + if dialect == "sqlite":
42 + _install_sqlite(conn)
43 + elif dialect == "postgresql":
44 + _install_postgresql(conn)
45 +
46 +
47 +def _install_sqlite(conn: Connection) -> None:
48 + for table in _YEAR_TABLES:
49 + for op, alias in (("INSERT", "NEW"), ("UPDATE", "NEW"), ("DELETE", "OLD")):
50 + name = f"aram_lock_{table}_{op.lower()}"
51 + conn.execute(text(f"DROP TRIGGER IF EXISTS {name}"))
52 + check = _locked_check_sqlite(table, alias)
53 + conn.execute(text(f"CREATE TRIGGER {name} BEFORE {op} ON {table} BEGIN {check}; END"))
54 + # Audit log is append-only.
55 + for op in ("UPDATE", "DELETE"):
56 + name = f"aram_audit_{op.lower()}"
57 + conn.execute(text(f"DROP TRIGGER IF EXISTS {name}"))
58 + conn.execute(
59 + text(
60 + f"CREATE TRIGGER {name} BEFORE {op} ON audit_entries "
61 + f"BEGIN SELECT RAISE(ABORT, 'audit log is append-only'); END"
62 + )
63 + )
64 + _install_lifecycle_sqlite(conn)
65 +
66 +
67 +def _install_lifecycle_sqlite(conn: Connection) -> None:
68 + conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_transition"))
69 + conn.execute(
70 + text(
71 + """
72 + CREATE TRIGGER aram_fiscal_year_transition
73 + BEFORE UPDATE OF status ON fiscal_years
74 + BEGIN
75 + SELECT RAISE(ABORT, 'invalid fiscal-year transition')
76 + WHERE NOT (
77 + (OLD.status = 'DRAFT' AND NEW.status = 'APPROVED')
78 + OR (OLD.status = 'APPROVED' AND NEW.status = 'LOCKED')
79 + OR (OLD.status = 'LOCKED' AND NEW.status = 'APPROVED'
80 + AND EXISTS (SELECT 1 FROM reopen_requests
81 + WHERE year_id = OLD.id AND status = 'approved'))
82 + );
83 + END
84 + """
85 + )
86 + )
87 + conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_no_delete"))
88 + conn.execute(
89 + text(
90 + """
91 + CREATE TRIGGER aram_fiscal_year_no_delete
92 + BEFORE DELETE ON fiscal_years
93 + BEGIN
94 + SELECT RAISE(ABORT, 'approved or locked fiscal year cannot be deleted')
95 + WHERE OLD.status IN ('APPROVED', 'LOCKED');
96 + END
97 + """
98 + )
99 + )
100 +
101 +
102 +def _install_postgresql(conn: Connection) -> None:
103 + conn.execute(
104 + text(
105 + """
106 + CREATE OR REPLACE FUNCTION aram_guard_locked() RETURNS trigger AS $$
107 + DECLARE yid integer; ystatus varchar;
108 + BEGIN
109 + IF TG_TABLE_NAME = 'note_rows' THEN
110 + SELECT year_id INTO yid FROM note_definitions WHERE id = NEW.note_id;
111 + ELSIF TG_TABLE_NAME = 'statement_lines' THEN
112 + SELECT year_id INTO yid FROM financial_statements WHERE id = NEW.statement_id;
113 + ELSE
114 + yid := NEW.year_id;
115 + END IF;
116 + SELECT status INTO ystatus FROM fiscal_years WHERE id = yid;
117 + IF ystatus = 'LOCKED' THEN
118 + RAISE EXCEPTION 'fiscal year is locked; row is immutable';
119 + END IF;
120 + RETURN NEW;
121 + END;
122 + $$ LANGUAGE plpgsql
123 + """
124 + )
125 + )
126 + for table in _YEAR_TABLES:
127 + # DELETE uses OLD; route via a separate function for OLD reference.
128 + for op in ("INSERT", "UPDATE"):
129 + name = f"aram_lock_{table}_{op.lower()}"
130 + conn.execute(text(f"DROP TRIGGER IF EXISTS {name} ON {table}"))
131 + conn.execute(
132 + text(
133 + f"CREATE TRIGGER {name} BEFORE {op} ON {table} "
134 + f"FOR EACH ROW EXECUTE FUNCTION aram_guard_locked()"
135 + )
136 + )
137 + conn.execute(
138 + text(
139 + """
140 + CREATE OR REPLACE FUNCTION aram_guard_locked_delete() RETURNS trigger AS $$
141 + DECLARE yid integer; ystatus varchar;
142 + BEGIN
143 + IF TG_TABLE_NAME = 'note_rows' THEN
144 + SELECT year_id INTO yid FROM note_definitions WHERE id = OLD.note_id;
145 + ELSIF TG_TABLE_NAME = 'statement_lines' THEN
146 + SELECT year_id INTO yid FROM financial_statements WHERE id = OLD.statement_id;
147 + ELSE
148 + yid := OLD.year_id;
149 + END IF;
150 + SELECT status INTO ystatus FROM fiscal_years WHERE id = yid;
151 + IF ystatus = 'LOCKED' THEN
152 + RAISE EXCEPTION 'fiscal year is locked; row is immutable';
153 + END IF;
154 + RETURN OLD;
155 + END;
156 + $$ LANGUAGE plpgsql
157 + """
158 + )
159 + )
160 + for table in _YEAR_TABLES:
161 + name = f"aram_lock_{table}_delete"
162 + conn.execute(text(f"DROP TRIGGER IF EXISTS {name} ON {table}"))
163 + conn.execute(
164 + text(
165 + f"CREATE TRIGGER {name} BEFORE DELETE ON {table} "
166 + f"FOR EACH ROW EXECUTE FUNCTION aram_guard_locked_delete()"
167 + )
168 + )
169 + conn.execute(
170 + text(
171 + """
172 + CREATE OR REPLACE FUNCTION aram_audit_append_only() RETURNS trigger AS $$
173 + BEGIN
174 + RAISE EXCEPTION 'audit log is append-only';
175 + END;
176 + $$ LANGUAGE plpgsql
177 + """
178 + )
179 + )
180 + for op in ("UPDATE", "DELETE"):
181 + name = f"aram_audit_{op.lower()}"
182 + conn.execute(text(f"DROP TRIGGER IF EXISTS {name} ON audit_entries"))
183 + conn.execute(
184 + text(
185 + f"CREATE TRIGGER {name} BEFORE {op} ON audit_entries "
186 + f"FOR EACH ROW EXECUTE FUNCTION aram_audit_append_only()"
187 + )
188 + )
189 + _install_lifecycle_postgresql(conn)
190 +
191 +
192 +def _install_lifecycle_postgresql(conn: Connection) -> None:
193 + conn.execute(
194 + text(
195 + """
196 + CREATE OR REPLACE FUNCTION aram_fiscal_year_transition() RETURNS trigger AS $$
197 + BEGIN
198 + IF NOT (
199 + (OLD.status = 'DRAFT' AND NEW.status = 'APPROVED')
200 + OR (OLD.status = 'APPROVED' AND NEW.status = 'LOCKED')
201 + OR (OLD.status = 'LOCKED' AND NEW.status = 'APPROVED'
202 + AND EXISTS (SELECT 1 FROM reopen_requests
203 + WHERE year_id = OLD.id AND status = 'approved'))
204 + ) THEN
205 + RAISE EXCEPTION 'invalid fiscal-year transition';
206 + END IF;
207 + RETURN NEW;
208 + END;
209 + $$ LANGUAGE plpgsql
210 + """
211 + )
212 + )
213 + conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_transition ON fiscal_years"))
214 + conn.execute(
215 + text(
216 + "CREATE TRIGGER aram_fiscal_year_transition BEFORE UPDATE OF status "
217 + "ON fiscal_years FOR EACH ROW EXECUTE FUNCTION aram_fiscal_year_transition()"
218 + )
219 + )
220 + conn.execute(
221 + text(
222 + """
223 + CREATE OR REPLACE FUNCTION aram_fiscal_year_no_delete() RETURNS trigger AS $$
224 + BEGIN
225 + IF OLD.status IN ('APPROVED', 'LOCKED') THEN
226 + RAISE EXCEPTION 'approved or locked fiscal year cannot be deleted';
227 + END IF;
228 + RETURN OLD;
229 + END;
230 + $$ LANGUAGE plpgsql
231 + """
232 + )
233 + )
234 + conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_no_delete ON fiscal_years"))
235 + conn.execute(
236 + text(
237 + "CREATE TRIGGER aram_fiscal_year_no_delete BEFORE DELETE ON fiscal_years "
238 + "FOR EACH ROW EXECUTE FUNCTION aram_fiscal_year_no_delete()"
239 + )
240 + )
241 +
242 +
243 +def install_on_engine(engine: Engine) -> None:
244 + with engine.begin() as conn:
245 + install_triggers(conn)
246 +
247 +
248 +__all__ = ["install_triggers", "install_on_engine"]
backend/src/aram_backend/desktop.py new
+102
@@ -0,0 +1,102 @@
1 +"""Offline Windows desktop entrypoint (Phase 8, booklet §15).
2 +
3 +Runs the FastAPI backend and serves the bundled React workbench on 127.0.0.1
4 +(loopback only; zero runtime network). On first launch it initializes a local
5 +SQLite database (WAL, foreign keys ON) and the content-addressed source store in
6 +a per-user data directory, applying the schema and D-07 immutability triggers.
7 +
8 +The packaged executable (PyInstaller, see packaging/aram.spec) bundles this
9 +module, the migrations, and the built frontend (frontend/dist). No external
10 +service, browser plugin, or network access is required at runtime.
11 +"""
12 +
13 +from __future__ import annotations
14 +
15 +import os
16 +import sys
17 +from pathlib import Path
18 +
19 +from fastapi import FastAPI
20 +from fastapi.staticfiles import StaticFiles
21 +
22 +from aram_backend import __version__
23 +from aram_backend.admin_api import router as admin_router
24 +from aram_backend.config import get_settings
25 +from aram_backend.database import Base, build_engine, ensure_triggers
26 +from aram_backend.models import FiscalYearStatus, StatementType # noqa: F401 (register mappers)
27 +from aram_backend.schemas import HealthResponse
28 +from aram_backend.statement_api import router as statement_router
29 +
30 +
31 +def default_data_dir() -> Path:
32 + """Per-user data directory (override with ARAM_DATA_DIR)."""
33 + override = os.environ.get("ARAM_DATA_DIR")
34 + if override:
35 + return Path(override)
36 + if sys.platform == "win32":
37 + base = Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming"))
38 + return base / "Aram"
39 + return Path.home() / ".aram"
40 +
41 +
42 +def _bundled_frontend() -> Path | None:
43 + """Locate the built React workbench (PyInstaller _MEIPASS or repo dist)."""
44 + candidates = []
45 + meipass = getattr(sys, "_MEIPASS", None)
46 + if meipass:
47 + candidates.append(Path(meipass) / "frontend_dist")
48 + candidates.append(Path(__file__).resolve().parents[2] / "frontend_dist")
49 + candidates.append(Path(__file__).resolve().parents[3] / "frontend" / "dist")
50 + for candidate in candidates:
51 + if (candidate / "index.html").exists():
52 + return candidate
53 + return None
54 +
55 +
56 +def initialize_database(data_dir: Path) -> None:
57 + """Create the schema + triggers idempotently for a fresh local install."""
58 + data_dir.mkdir(parents=True, exist_ok=True)
59 + (data_dir / "source_store").mkdir(exist_ok=True)
60 + db_path = data_dir / "aram.db"
61 + engine = build_engine(f"sqlite:///{db_path}")
62 + Base.metadata.create_all(engine)
63 + ensure_triggers(engine)
64 + engine.dispose()
65 +
66 +
67 +def create_desktop_app() -> FastAPI:
68 + app = FastAPI(title="Aram Desktop", version=__version__)
69 + app.include_router(statement_router)
70 + app.include_router(admin_router)
71 +
72 + @app.get("/api/v1/health", response_model=HealthResponse, tags=["system"])
73 + def health() -> HealthResponse:
74 + return HealthResponse(status="ok", service="Aram Desktop", version=__version__)
75 +
76 + frontend = _bundled_frontend()
77 + if frontend is not None:
78 + app.mount("/", StaticFiles(directory=str(frontend), html=True), name="workbench")
79 + return app
80 +
81 +
82 +def main() -> None:
83 + import uvicorn
84 +
85 + from aram_backend.database import reconfigure
86 +
87 + data_dir = default_data_dir()
88 + initialize_database(data_dir)
89 + # Point the shared settings + engine at the local data dir before serving.
90 + db_url = f"sqlite:///{data_dir / 'aram.db'}"
91 + os.environ["ARAM_DATABASE_URL"] = db_url
92 + os.environ["ARAM_SOURCE_STORE_ROOT"] = str(data_dir / "source_store")
93 + get_settings.cache_clear()
94 + reconfigure(db_url)
95 +
96 + app = create_desktop_app()
97 + # Loopback only: the desktop app never exposes a network interface.
98 + uvicorn.run(app, host="127.0.0.1", port=int(os.environ.get("ARAM_PORT", "8765")), log_level="info")
99 +
100 +
101 +if __name__ == "__main__":
102 + main()
backend/src/aram_backend/domain/__init__.py new
+24
@@ -0,0 +1,24 @@
1 +"""Pure domain rules for Aram (no I/O, no database).
2 +
3 +This package holds the non-negotiable financial primitives mandated by the
4 +executive booklet: Persian normalization (P-04), exact money (P-02), text codes
5 +(P-03), the evidence-based account hierarchy (OD-01), and the blocking financial
6 +controls (C-01..C-04). Every function here is deterministic and unit-testable
7 +without a database (booklet section 4, domain layer).
8 +"""
9 +
10 +from aram_backend.domain.money import Rial, allocate_remainder, round_half_up
11 +from aram_backend.domain.normalization import (
12 + decimal_from_cell,
13 + normalize_code,
14 + normalize_fa,
15 +)
16 +
17 +__all__ = [
18 + "normalize_fa",
19 + "normalize_code",
20 + "decimal_from_cell",
21 + "Rial",
22 + "round_half_up",
23 + "allocate_remainder",
24 +]
backend/src/aram_backend/domain/controls.py new
+163
@@ -0,0 +1,163 @@
1 +"""Blocking financial controls C-01..C-04 (booklet section 7, debt D-02).
2 +
3 +Pure, deterministic functions over balance rows and active mappings. Each
4 +returns a :class:`ControlResult` with a Persian message and the affected
5 +accounts/rows. ERROR severity blocks approval (P-09); these are not ignorable
6 +warnings. Sign convention is debit-positive (ADR-013, evidence: 252892/252898
7 +canonical rows satisfy C-01 under debit-positive vs 37% under credit-positive).
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +from dataclasses import dataclass, field
13 +from decimal import Decimal
14 +
15 +_ZERO = Decimal(0)
16 +
17 +
18 +@dataclass(frozen=True)
19 +class BalanceRow:
20 + """One ledger balance row (all amounts exact Decimal rial)."""
21 +
22 + row_number: int
23 + account_code: str
24 + opening: Decimal
25 + debit: Decimal
26 + credit: Decimal
27 + closing: Decimal
28 +
29 +
30 +@dataclass(frozen=True)
31 +class MappingTarget:
32 + """One active mapping target for an account; weight is a percentage."""
33 +
34 + target: str
35 + weight: Decimal = Decimal(100)
36 +
37 +
38 +@dataclass(frozen=True)
39 +class ControlResult:
40 + code: str
41 + severity: str
42 + passed: bool
43 + message_fa: str
44 + affected: tuple[str, ...] = field(default_factory=tuple)
45 +
46 +
47 +def _aggregate(rows: list[BalanceRow]) -> dict[str, dict[str, Decimal]]:
48 + totals: dict[str, dict[str, Decimal]] = {}
49 + for row in rows:
50 + bucket = totals.setdefault(
51 + row.account_code,
52 + {"opening": _ZERO, "debit": _ZERO, "credit": _ZERO, "closing": _ZERO},
53 + )
54 + bucket["opening"] += row.opening
55 + bucket["debit"] += row.debit
56 + bucket["credit"] += row.credit
57 + bucket["closing"] += row.closing
58 + return totals
59 +
60 +
61 +def check_c01(rows: list[BalanceRow]) -> ControlResult:
62 + """C-01: every row satisfies opening + debit - credit - closing = 0."""
63 + bad = tuple(
64 + str(r.row_number) for r in rows if r.opening + r.debit - r.credit - r.closing != _ZERO
65 + )
66 + return ControlResult(
67 + code="C-01",
68 + severity="ERROR",
69 + passed=not bad,
70 + message_fa=(
71 + "همهٔ ردیف‌ها: ابتدای دوره + بدهکار − بستانکار − پایان دوره = ۰"
72 + if not bad
73 + else f"{len(bad)} ردیف معادلهٔ مانده را نقض می‌کنند"
74 + ),
75 + affected=bad,
76 + )
77 +
78 +
79 +def check_c02(rows: list[BalanceRow]) -> ControlResult:
80 + """C-02: trial balance — total debit == total credit and sum(closing) == 0."""
81 + total_debit = sum((r.debit for r in rows), _ZERO)
82 + total_credit = sum((r.credit for r in rows), _ZERO)
83 + total_closing = sum((r.closing for r in rows), _ZERO)
84 + passed = total_debit == total_credit and total_closing == _ZERO
85 + return ControlResult(
86 + code="C-02",
87 + severity="ERROR",
88 + passed=passed,
89 + message_fa=(
90 + "تراز کل برقرار است: جمع بدهکار = جمع بستانکار و جمع مانده‌ها صفر"
91 + if passed
92 + else "تراز کل نقض شده است: جمع بدهکار ≠ جمع بستانکار یا جمع مانده‌ها ≠ صفر"
93 + ),
94 + affected=() if passed else ("trial_balance",),
95 + )
96 +
97 +
98 +def _is_active(bucket: dict[str, Decimal]) -> bool:
99 + return any(bucket[k] != _ZERO for k in ("opening", "debit", "credit", "closing"))
100 +
101 +
102 +def check_c03(rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]) -> ControlResult:
103 + """C-03: each active account has exactly one active mapping (or 100% split)."""
104 + bad: list[str] = []
105 + for code, bucket in sorted(_aggregate(rows).items()):
106 + if not _is_active(bucket):
107 + continue
108 + targets = mappings.get(code, [])
109 + if len(targets) == 0:
110 + bad.append(code)
111 + elif len(targets) > 1:
112 + if sum((t.weight for t in targets), _ZERO) != Decimal(100):
113 + bad.append(code)
114 + return ControlResult(
115 + code="C-03",
116 + severity="ERROR",
117 + passed=not bad,
118 + message_fa=(
119 + "هر حساب فعال دقیقاً یک نگاشت فعال دارد (یا تقسیم ۱۰۰٪)"
120 + if not bad
121 + else f"{len(bad)} حساب فعال نگاشت معتبر ندارند"
122 + ),
123 + affected=tuple(bad),
124 + )
125 +
126 +
127 +def check_c04(rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]) -> ControlResult:
128 + """C-04: unmapped active accounts enter the unknown queue and block approval."""
129 + queue = tuple(
130 + code
131 + for code, bucket in sorted(_aggregate(rows).items())
132 + if _is_active(bucket) and not mappings.get(code)
133 + )
134 + return ControlResult(
135 + code="C-04",
136 + severity="ERROR",
137 + passed=not queue,
138 + message_fa=(
139 + "صف حساب‌های ناشناخته خالی است"
140 + if not queue
141 + else f"{len(queue)} حساب بدون نگاشت در صف ناشناخته؛ تا تعیین تکلیف مانع تأیید"
142 + ),
143 + affected=queue,
144 + )
145 +
146 +
147 +def run_controls(
148 + rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]
149 +) -> list[ControlResult]:
150 + """Run the Phase-0 blocking control set in stable order."""
151 + return [check_c01(rows), check_c02(rows), check_c03(rows, mappings), check_c04(rows, mappings)]
152 +
153 +
154 +__all__ = [
155 + "BalanceRow",
156 + "MappingTarget",
157 + "ControlResult",
158 + "check_c01",
159 + "check_c02",
160 + "check_c03",
161 + "check_c04",
162 + "run_controls",
163 +]
backend/src/aram_backend/domain/formula.py new
+213
@@ -0,0 +1,213 @@
1 +"""Safe note formula grammar (Phase 3, ADR-020, P-05: no eval/exec).
2 +
3 +A hand-written tokenizer + recursive-descent parser produces a whitelisted AST
4 +that is evaluated with exact Decimal. Unknown tokens/functions fail closed.
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +import re
10 +from collections.abc import Callable
11 +from dataclasses import dataclass
12 +from decimal import Decimal, DivisionByZero, InvalidOperation
13 +
14 +_ZERO = Decimal(0)
15 +
16 +
17 +class FormulaError(ValueError):
18 + """Raised when a formula cannot be parsed or evaluated safely."""
19 +
20 +
21 +# --------------------------------------------------------------------------- AST
22 +@dataclass(frozen=True)
23 +class Num:
24 + value: Decimal
25 +
26 +
27 +@dataclass(frozen=True)
28 +class Str:
29 + value: str
30 +
31 +
32 +@dataclass(frozen=True)
33 +class Unary:
34 + op: str
35 + operand: object
36 +
37 +
38 +@dataclass(frozen=True)
39 +class Binary:
40 + op: str
41 + left: object
42 + right: object
43 +
44 +
45 +@dataclass(frozen=True)
46 +class Call:
47 + name: str
48 + args: tuple[object, ...]
49 +
50 +
51 +# ------------------------------------------------------------------- tokenizer
52 +_TOKEN_RE = re.compile(
53 + r"""
54 + (?P<NUMBER>\d+(?:\.\d+)?)
55 + | (?P<STRING>"[^"]*")
56 + | (?P<IDENT>[A-Za-z_][A-Za-z_0-9]*)
57 + | (?P<OP>[+\-*/(),])
58 + | (?P<WS>\s+)
59 + """,
60 + re.VERBOSE,
61 +)
62 +
63 +
64 +def _tokenize(text: str) -> list[tuple[str, str]]:
65 + tokens: list[tuple[str, str]] = []
66 + pos = 0
67 + while pos < len(text):
68 + match = _TOKEN_RE.match(text, pos)
69 + if match is None:
70 + raise FormulaError(f"illegal character at position {pos}: {text[pos]!r}")
71 + kind = match.lastgroup
72 + value = match.group()
73 + pos = match.end()
74 + if kind == "WS":
75 + continue
76 + assert kind is not None
77 + tokens.append((kind, value))
78 + return tokens
79 +
80 +
81 +# ---------------------------------------------------------------------- parser
82 +class _Parser:
83 + def __init__(self, tokens: list[tuple[str, str]]) -> None:
84 + self._tokens = tokens
85 + self._pos = 0
86 +
87 + def _peek(self) -> tuple[str, str] | None:
88 + return self._tokens[self._pos] if self._pos < len(self._tokens) else None
89 +
90 + def _next(self) -> tuple[str, str]:
91 + token = self._peek()
92 + if token is None:
93 + raise FormulaError("unexpected end of formula")
94 + self._pos += 1
95 + return token
96 +
97 + def _peek_value(self) -> str | None:
98 + token = self._peek()
99 + return token[1] if token is not None else None
100 +
101 + def parse(self) -> object:
102 + node = self._expr()
103 + if self._peek() is not None:
104 + raise FormulaError(f"unexpected token {self._peek_value()!r}")
105 + return node
106 +
107 + def _expr(self) -> object:
108 + node = self._term()
109 + while self._peek_value() in ("+", "-"):
110 + op = self._next()[1]
111 + node = Binary(op, node, self._term())
112 + return node
113 +
114 + def _term(self) -> object:
115 + node = self._factor()
116 + while self._peek_value() in ("*", "/"):
117 + op = self._next()[1]
118 + node = Binary(op, node, self._factor())
119 + return node
120 +
121 + def _factor(self) -> object:
122 + token = self._peek()
123 + if token is None:
124 + raise FormulaError("unexpected end of formula")
125 + kind, value = token
126 + if value in ("+", "-"):
127 + self._next()
128 + return Unary(value, self._factor())
129 + if value == "(":
130 + self._next()
131 + node = self._expr()
132 + if self._next()[1] != ")":
133 + raise FormulaError("expected ')'")
134 + return node
135 + if kind == "NUMBER":
136 + self._next()
137 + return Num(Decimal(value))
138 + if kind == "STRING":
139 + self._next()
140 + return Str(value[1:-1])
141 + if kind == "IDENT":
142 + self._next()
143 + if self._peek_value() != "(":
144 + raise FormulaError(f"unknown name {value!r}; only function calls are allowed")
145 + self._next() # consume '('
146 + args: list[object] = []
147 + if self._peek_value() not in (None, ")"):
148 + args.append(self._expr())
149 + while self._peek_value() == ",":
150 + self._next()
151 + args.append(self._expr())
152 + if self._next()[1] != ")":
153 + raise FormulaError("expected ')' after arguments")
154 + return Call(value, tuple(args))
155 + raise FormulaError(f"unexpected token {value!r}")
156 +
157 +
158 +def parse_formula(text: str) -> object:
159 + if not text or not text.strip():
160 + raise FormulaError("formula is empty")
161 + return _Parser(_tokenize(text)).parse()
162 +
163 +
164 +# -------------------------------------------------------------------- evaluator
165 +Resolver = Callable[[str, tuple[object, ...]], Decimal]
166 +
167 +
168 +def evaluate(node: object, resolver: Resolver) -> Decimal:
169 + if isinstance(node, Num):
170 + return node.value
171 + if isinstance(node, Unary):
172 + operand = evaluate(node.operand, resolver)
173 + return -operand if node.op == "-" else operand
174 + if isinstance(node, Binary):
175 + left = evaluate(node.left, resolver)
176 + right = evaluate(node.right, resolver)
177 + if node.op == "+":
178 + return left + right
179 + if node.op == "-":
180 + return left - right
181 + if node.op == "*":
182 + return left * right
183 + if node.op == "/":
184 + if right == _ZERO:
185 + raise FormulaError("division by zero")
186 + try:
187 + return left / right
188 + except (DivisionByZero, InvalidOperation) as exc:
189 + raise FormulaError("division is not exact") from exc
190 + raise FormulaError(f"unknown operator {node.op!r}")
191 + if isinstance(node, Call):
192 + args = tuple(
193 + arg.value if isinstance(arg, Str) else evaluate(arg, resolver) for arg in node.args
194 + )
195 + return resolver(node.name, args)
196 + raise FormulaError(f"unsupported node {type(node).__name__}")
197 +
198 +
199 +def eval_formula(text: str, resolver: Resolver) -> Decimal:
200 + return evaluate(parse_formula(text), resolver)
201 +
202 +
203 +__all__ = [
204 + "FormulaError",
205 + "parse_formula",
206 + "evaluate",
207 + "eval_formula",
208 + "Num",
209 + "Str",
210 + "Unary",
211 + "Binary",
212 + "Call",
213 +]
backend/src/aram_backend/domain/hierarchy.py new
+124
@@ -0,0 +1,124 @@
1 +"""Evidence-based account hierarchy mapping: ledger <-> Pilot (D-10, OD-01).
2 +
3 +The booklet OD-01 default (map T1..T4 to general..detail4 in order and expect
4 +their concatenation to equal the ``حساب`` column) is **refuted by the canonical
5 +data**: a read-only probe of all 252898 rows of source_1404.xlsx found 0 matches.
6 +
7 +What the data actually shows (ADR-014):
8 +* ``kol`` -> 2-digit general account (``general_code``).
9 +* ``حساب`` -> 4-digit subsidiary account (``subsidiary_code``); it is the leaf,
10 + not a concatenation of the T-codes.
11 +* ``T1_CODE..T4_CODE`` -> auxiliary detail dimensions (``detail1..4_code``),
12 + preserved as text but not part of the canonical account identity.
13 +* ``AccountId`` is unreliable (only ~77% equal ``kol + حساب``) and is NOT used.
14 +
15 +The canonical account full code is therefore ``general_code + subsidiary_code``
16 +(``kol + حساب``). The verifiable invariant is that for 100% of rows the
17 +subsidiary segment equals ``حساب`` and the general segment equals ``kol``.
18 +"""
19 +
20 +from __future__ import annotations
21 +
22 +from dataclasses import dataclass
23 +
24 +from aram_backend.domain.normalization import normalize_code
25 +
26 +
27 +@dataclass(frozen=True)
28 +class AccountLevels:
29 + """Six text levels of the Pilot hierarchy (P-03: codes are always text)."""
30 +
31 + general_code: str = ""
32 + subsidiary_code: str = ""
33 + detail1_code: str = ""
34 + detail2_code: str = ""
35 + detail3_code: str = ""
36 + detail4_code: str = ""
37 +
38 + def as_tuple(self) -> tuple[str, str, str, str, str, str]:
39 + return (
40 + self.general_code,
41 + self.subsidiary_code,
42 + self.detail1_code,
43 + self.detail2_code,
44 + self.detail3_code,
45 + self.detail4_code,
46 + )
47 +
48 +
49 +def ledger_to_pilot(
50 + *,
51 + kol: object,
52 + hesab: object,
53 + t1: object = None,
54 + t2: object = None,
55 + t3: object = None,
56 + t4: object = None,
57 + row: int = 0,
58 +) -> AccountLevels:
59 + """Map a canonical ledger row to Pilot levels (ADR-014).
60 +
61 + ``kol`` -> general, ``حساب`` -> subsidiary, ``T1..T4`` -> detail1..4.
62 + Empty/``None`` auxiliary codes become the empty string; codes keep their
63 + text form and leading zeros (P-03).
64 + """
65 + general = normalize_code(kol, row=row, field="kol") if kol not in (None, "") else ""
66 + subsidiary = normalize_code(hesab, row=row, field="حساب")
67 + details = [
68 + normalize_code(t, row=row, field=f"T{i}_CODE") if t not in (None, "") else ""
69 + for i, t in enumerate((t1, t2, t3, t4), start=1)
70 + ]
71 + return AccountLevels(
72 + general_code=general,
73 + subsidiary_code=subsidiary,
74 + detail1_code=details[0],
75 + detail2_code=details[1],
76 + detail3_code=details[2],
77 + detail4_code=details[3],
78 + )
79 +
80 +
81 +def pilot_to_ledger(levels: AccountLevels) -> dict[str, str]:
82 + """Inverse mapping for the bidirectional conversion test (D-10)."""
83 + return {
84 + "kol": levels.general_code,
85 + "حساب": levels.subsidiary_code,
86 + "T1_CODE": levels.detail1_code,
87 + "T2_CODE": levels.detail2_code,
88 + "T3_CODE": levels.detail3_code,
89 + "T4_CODE": levels.detail4_code,
90 + }
91 +
92 +
93 +def canonical_full_code(levels: AccountLevels) -> str:
94 + """Canonical account identity = general + subsidiary (ADR-014).
95 +
96 + Auxiliary detail codes are preserved on the level record but do not change
97 + the canonical account identity of the canonical ledger.
98 + """
99 + return levels.general_code + levels.subsidiary_code
100 +
101 +
102 +def reconstruct_full_code(levels: AccountLevels) -> str:
103 + """Pilot-style concatenation of every non-empty level, in order."""
104 + return "".join(code for code in levels.as_tuple() if code)
105 +
106 +
107 +def account_level(levels: AccountLevels) -> str:
108 + """Deepest populated level name, matching the Pilot contract vocabulary."""
109 + names = ("General", "Subsidiary", "Detail1", "Detail2", "Detail3", "Detail4")
110 + deepest = "General"
111 + for name, code in zip(names, levels.as_tuple(), strict=True):
112 + if code:
113 + deepest = name
114 + return deepest
115 +
116 +
117 +__all__ = [
118 + "AccountLevels",
119 + "ledger_to_pilot",
120 + "pilot_to_ledger",
121 + "canonical_full_code",
122 + "reconstruct_full_code",
123 + "account_level",
124 +]
backend/src/aram_backend/domain/money.py new
+96
@@ -0,0 +1,96 @@
1 +"""Exact money: scaled-integer storage, Decimal in Python (P-02, D-03, OD-03).
2 +
3 +No float ever touches persistence. Amounts are stored as scaled integers in a
4 +``BIGINT`` column and exposed as :class:`~decimal.Decimal`. The scale is fixed at
5 +0 (full rial) because a read-only probe of the canonical 1404 ledger found zero
6 +fractional-rial cells; this is recorded in ADR-012. Rounding happens only in the
7 +display/output layer through :func:`round_half_up`, and the rounding difference
8 +between rows and their total is allocated by the largest-remainder method
9 +(:func:`allocate_remainder`) so displayed rows always sum to the displayed total.
10 +"""
11 +
12 +from __future__ import annotations
13 +
14 +from decimal import ROUND_HALF_UP, Decimal
15 +from typing import Any
16 +
17 +from sqlalchemy import BigInteger
18 +from sqlalchemy.engine.interfaces import Dialect
19 +from sqlalchemy.types import TypeDecorator
20 +
21 +#: Integer rial; evidence-based (ADR-012). 10**0 == 1.
22 +RIAL_SCALE = 0
23 +_FACTOR: int = 10**RIAL_SCALE
24 +
25 +
26 +class Rial(TypeDecorator[Decimal]):
27 + """Store a Decimal rial amount as an exact scaled integer (P-02).
28 +
29 + Works identically on SQLite and PostgreSQL (``BIGINT``). Accepts Decimal,
30 + int, or exact numeric text; rejects float and fractional rial loudly (P-09)
31 + so no silent rounding can occur on the way into the database.
32 + """
33 +
34 + impl = BigInteger
35 + cache_ok = True
36 +
37 + def process_bind_param(self, value: Any, dialect: Dialect) -> int | None:
38 + if value is None:
39 + return None
40 + if isinstance(value, float):
41 + raise TypeError("float is forbidden for money (P-02); pass Decimal")
42 + if isinstance(value, Decimal):
43 + number = value
44 + elif isinstance(value, int):
45 + number = Decimal(value)
46 + elif isinstance(value, str):
47 + number = Decimal(value)
48 + else:
49 + raise TypeError(f"unsupported money type: {type(value).__name__}")
50 + if not number.is_finite():
51 + raise ValueError("money must be finite")
52 + scaled = number * _FACTOR
53 + if scaled != scaled.to_integral_value():
54 + raise ValueError(
55 + f"fractional rial is not representable at scale {RIAL_SCALE}: {number}"
56 + )
57 + return int(scaled)
58 +
59 + def process_result_value(self, value: Any, dialect: Dialect) -> Decimal | None:
60 + if value is None:
61 + return None
62 + return Decimal(int(value)) / Decimal(_FACTOR)
63 +
64 +
65 +def round_half_up(value: Decimal, places: int = 0) -> Decimal:
66 + """The single central rounding rule: half-up (OD-03), output layer only."""
67 + quantum = Decimal(1).scaleb(-places)
68 + return value.quantize(quantum, rounding=ROUND_HALF_UP)
69 +
70 +
71 +def allocate_remainder(values: list[Decimal], total: Decimal, places: int = 0) -> list[Decimal]:
72 + """Round rows so they sum exactly to the rounded total (largest remainder).
73 +
74 + Deterministic and stable: rows are adjusted in order of their rounding
75 + error, ties broken by original index. Guarantees
76 + ``sum(result) == round_half_up(total, places)``.
77 + """
78 + if not values:
79 + return []
80 + quantum = Decimal(1).scaleb(-places)
81 + rounded = [round_half_up(v, places) for v in values]
82 + target = round_half_up(total, places)
83 + diff = target - sum(rounded)
84 + if diff == 0:
85 + return rounded
86 + steps = int(diff / quantum)
87 + errors = [v - r for v, r in zip(values, rounded, strict=True)]
88 + order = sorted(range(len(values)), key=lambda i: (errors[i], -i), reverse=steps > 0)
89 + result = list(rounded)
90 + sign = 1 if steps > 0 else -1
91 + for k in range(abs(steps)):
92 + result[order[k % len(order)]] += sign * quantum
93 + return result
94 +
95 +
96 +__all__ = ["Rial", "RIAL_SCALE", "round_half_up", "allocate_remainder"]
backend/src/aram_backend/domain/normalization.py new
+114
@@ -0,0 +1,114 @@
1 +"""Single-source Persian normalization and exact cell decoding (P-03, P-04).
2 +
3 +Every Persian text input passes through :func:`normalize_fa` (booklet P-04).
4 +Account/note codes are always text and keep leading zeros and length (P-03);
5 +they are never numerified. Excel floats become :class:`~decimal.Decimal` through
6 +the shortest round-trip ``repr`` so no binary float artifact survives (D-04).
7 +
8 +Evidence (read-only probe of data/source_ledgers/source_1404.xlsx, 252898 rows):
9 +the canonical ``حساب`` and ``kol`` cells are stored as integers and there are no
10 +fractional rial cells. The booklet D-04 default "raw numeric code -> explicit
11 +error" is therefore refuted by the real data (section 17 rule 3, evidence wins):
12 +integral numeric codes are accepted and converted to text exactly, text codes
13 +keep their leading zeros, and only non-integral/ambiguous numeric codes raise.
14 +"""
15 +
16 +from __future__ import annotations
17 +
18 +from decimal import Decimal, InvalidOperation
19 +
20 +# Arabic -> Persian letters and Persian/Arabic-Indic digits -> Latin (P-04, §8).
21 +_TRANSLATION = {
22 + 0x064A: 0x06CC, # Arabic yeh ي -> Persian yeh ی
23 + 0x0643: 0x06A9, # Arabic kaf ك -> Persian kaf ک
24 + 0x0640: None, # tatweel / kashida ـ removed
25 + 0x00A0: None, # no-break space removed
26 + 0x200B: None, # zero-width space removed
27 + 0x200E: None, # left-to-right mark removed
28 + 0x200F: None, # right-to-left mark removed
29 + 0xFEFF: None, # zero-width no-break space / BOM removed
30 +}
31 +for _i in range(10):
32 + _TRANSLATION[0x06F0 + _i] = 0x30 + _i # Persian digits ۰-۹
33 + _TRANSLATION[0x0660 + _i] = 0x30 + _i # Arabic digits ٠-٩
34 +# Control characters (except tab/newline which trim handles) are removed.
35 +for _c in range(0x20):
36 + if _c not in (0x09, 0x0A, 0x0D):
37 + _TRANSLATION[_c] = None
38 +_TRANSLATION[0x7F] = None
39 +
40 +# Thousands separators that may appear inside numeric text cells.
41 +_SEPARATORS = str.maketrans({",": None, "٬": None, "،": None, " ": None, "\u200c": None})
42 +
43 +
44 +class NormalizationError(ValueError):
45 + """Raised when a cell cannot be normalized safely (fail loud, P-09)."""
46 +
47 +
48 +def normalize_fa(text: str) -> str:
49 + """Normalize Persian text: letters, digits, invisible chars, trim (P-04).
50 +
51 + Idempotent: ``normalize_fa(normalize_fa(x)) == normalize_fa(x)``. The
52 + zero-width non-joiner (U+200C, the Persian half-space) is preserved because
53 + it is linguistically meaningful; only invisible *format* controls are dropped.
54 + """
55 + cleaned = text.translate(_TRANSLATION)
56 + return cleaned.strip()
57 +
58 +
59 +def normalize_code(value: object, *, row: int, field: str) -> str:
60 + """Return an account/note code as text, preserving leading zeros (P-03, D-04).
61 +
62 + * ``str`` -> :func:`normalize_fa`, leading zeros and length preserved.
63 + * ``int`` -> exact decimal text (the canonical ledger stores codes as int).
64 + * integral ``float``/``Decimal`` -> exact integer text.
65 + * non-integral numeric, ``bool``, ``None`` -> :class:`NormalizationError`.
66 +
67 + A code is never silently truncated or numerified; ``'0101'`` stays ``'0101'``.
68 + """
69 + if value is None or isinstance(value, bool):
70 + raise NormalizationError(f"row {row}: {field} is not a valid code")
71 + if isinstance(value, str):
72 + code = normalize_fa(value)
73 + if not code:
74 + raise NormalizationError(f"row {row}: {field} is empty")
75 + return code
76 + if isinstance(value, int):
77 + return str(value)
78 + if isinstance(value, (float, Decimal)):
79 + number = decimal_from_cell(value, row=row, field=field)
80 + if number != number.to_integral_value():
81 + raise NormalizationError(f"row {row}: {field} must be an integer code, got {number}")
82 + return str(int(number))
83 + raise NormalizationError(f"row {row}: {field} is not a valid code")
84 +
85 +
86 +def decimal_from_cell(value: object, *, row: int, field: str) -> Decimal:
87 + """Decode a numeric cell to an exact :class:`Decimal` (D-04, §8).
88 +
89 + Floats use the shortest round-trip ``repr`` (never ``str(float)`` artifacts
90 + nor the exact binary expansion). Text is Persian-normalized and thousands
91 + separators are removed before parsing. Non-finite or non-numeric values
92 + raise :class:`NormalizationError`.
93 + """
94 + if value is None or isinstance(value, bool):
95 + raise NormalizationError(f"row {row}: {field} is required and numeric")
96 + if isinstance(value, Decimal):
97 + parsed = value
98 + elif isinstance(value, int):
99 + parsed = Decimal(value)
100 + elif isinstance(value, float):
101 + parsed = Decimal(repr(value))
102 + elif isinstance(value, str):
103 + candidate = normalize_fa(value).translate(_SEPARATORS)
104 + if not candidate:
105 + raise NormalizationError(f"row {row}: {field} is required and numeric")
106 + try:
107 + parsed = Decimal(candidate)
108 + except InvalidOperation as exc:
109 + raise NormalizationError(f"row {row}: {field} is not numeric") from exc
110 + else:
111 + raise NormalizationError(f"row {row}: {field} is not numeric")
112 + if not parsed.is_finite():
113 + raise NormalizationError(f"row {row}: {field} must be finite")
114 + return parsed
backend/src/aram_backend/ingestion.py
+38 -8
@@ -6,8 +6,8 @@ from pathlib import Path
6 from sqlalchemy import select
7 from sqlalchemy.orm import Session
8
9 -from aram_backend.models import FiscalYear, FiscalYearStatus, SourceDocument
10 -
9 +from aram_backend.models import FiscalYear, FiscalYearStatus, SourceDocument, SourceFile
10 +from aram_backend.services.source_store import SourceStore
11
12 ALLOWED_SOURCE_SUFFIXES = frozenset({".csv", ".xlsx"})
13 ALLOWED_DOCUMENT_TYPES = frozenset(
@@ -26,11 +26,14 @@ def register_source_document(
26 filename: str,
27 document_type: str,
28 content: bytes,
29 + store: SourceStore | None = None,
30 ) -> SourceDocument:
30 - """Register immutable source metadata without persisting source bytes.
31 + """Register immutable source metadata; optionally persist bytes (D-06).
32
32 - Re-registering the same bytes for the same fiscal year is idempotent. The
33 - caller owns the transaction and may inspect the returned row before commit.
33 + Re-registering the same bytes for the same fiscal year is idempotent. When a
34 + ``store`` is given, the bytes are written to the content-addressed store and
35 + referenced via ``SourceFile``; the SourceDocument row itself never holds the
36 + payload. The caller owns the transaction.
37 """
38
39 if not filename or "/" in filename or "\\" in filename:
@@ -52,6 +55,27 @@ def register_source_document(
55 )
56
57 file_hash = hashlib.sha256(content).hexdigest()
58 +
59 + stored = None
60 + if store is not None:
61 + stored = store.put(content)
62 + if session.get(SourceFile, stored.sha256) is None:
63 + suffix = Path(safe_name).suffix.lower()
64 + content_type = (
65 + "text/csv"
66 + if suffix == ".csv"
67 + else "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
68 + )
69 + session.add(
70 + SourceFile(
71 + sha256=stored.sha256,
72 + size=stored.size,
73 + content_type=content_type,
74 + stored_path=stored.stored_path,
75 + )
76 + )
77 + session.flush()
78 +
79 existing = session.scalar(
80 select(SourceDocument).where(
81 SourceDocument.year_id == year_id,
@@ -60,11 +84,16 @@ def register_source_document(
84 )
85 if existing is not None:
86 if existing.document_type != document_type and existing.filename != safe_name:
63 - raise SourceRegistrationError(f"document type and filename mismatch for existing content hash")
87 + raise SourceRegistrationError(
88 + "document type and filename mismatch for existing content hash"
89 + )
90 if existing.document_type != document_type:
65 - raise SourceRegistrationError(f"document type mismatch for existing content hash")
91 + raise SourceRegistrationError("document type mismatch for existing content hash")
92 if existing.filename != safe_name:
67 - raise SourceRegistrationError(f"filename mismatch for existing content hash")
93 + raise SourceRegistrationError("filename mismatch for existing content hash")
94 + if stored is not None and existing.source_file_hash is None:
95 + existing.source_file_hash = stored.sha256
96 + session.flush()
97 return existing
98
99 source = SourceDocument(
@@ -72,6 +101,7 @@ def register_source_document(
101 filename=safe_name,
102 file_hash=file_hash,
103 document_type=document_type,
104 + source_file_hash=stored.sha256 if stored is not None else None,
105 )
106 session.add(source)
107 session.flush()
backend/src/aram_backend/ledger_parser.py
+225 -51
@@ -1,12 +1,20 @@
1 from __future__ import annotations
2
3 +import csv
4 +import io
5 from collections.abc import Iterator
6 from dataclasses import dataclass
5 -from decimal import Decimal, InvalidOperation
7 +from decimal import Decimal
8 from io import BytesIO
9
10 from openpyxl import load_workbook
11
12 +from aram_backend.domain.normalization import (
13 + NormalizationError,
14 + decimal_from_cell,
15 + normalize_code,
16 + normalize_fa,
17 +)
18 from aram_backend.workbook_inspection import inspect_xlsx
19
20
@@ -14,6 +22,7 @@ from aram_backend.workbook_inspection import inspect_xlsx
22 class LedgerRecord:
23 row_number: int
24 account_code: str
25 + general_code: str | None
26 account_name: str
27 source_year: int
28 entry_type: str
@@ -25,6 +34,15 @@ class LedgerRecord:
34 debit: Decimal
35 credit: Decimal
36 closing: Decimal
37 + statement_balance: Decimal | None = None
38 +
39 +
40 +@dataclass(frozen=True)
41 +class SkippedRow:
42 + """A source row that could not be imported, with the reason (fail-loud report)."""
43 +
44 + row_number: int
45 + reason: str
46
47
48 class LedgerParseError(ValueError):
@@ -46,14 +64,26 @@ _FIELDS = {
64 "closing": "CLOSING",
65 }
66
67 +_STATEMENT_BALANCE_HEADER = "مانده صورت مالی"
68
50 -def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
51 - """Stream typed ledger rows without persisting or calculating values."""
69 +_CSV_ENCODINGS = ("utf-8-sig", "utf-8", "cp1256")
70
71 +
72 +def parse_general_ledger(
73 + content: bytes, *, tolerant: bool = False, skipped: list[SkippedRow] | None = None
74 +) -> Iterator[LedgerRecord]:
75 + """Stream typed XLSX ledger rows without persisting or calculating values.
76 +
77 + Codes are normalized as text (leading zeros preserved, P-03/D-04) and money
78 + is decoded to exact Decimal via the shortest round-trip repr (D-04). Header
79 + matching is Persian-normalized (D-05).
80 +
81 + With ``tolerant=True`` (real-ledger import) reclassified rows whose money
82 + cells are empty are kept with exact zero, ``مانده صورت مالی`` is captured as
83 + ``statement_balance``, and anomalous rows are skipped into ``skipped``.
84 + """
85 inspection = inspect_xlsx(content, document_type="general_ledger")
54 - workbook = load_workbook(
55 - BytesIO(content), read_only=True, data_only=True, keep_links=False
56 - )
86 + workbook = load_workbook(BytesIO(content), read_only=True, data_only=True, keep_links=False)
87 try:
88 worksheet = workbook[inspection.data_sheet]
89 header_values = next(
@@ -64,46 +94,199 @@ def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
94 )
95 )
96 indexes = {
67 - str(value).strip(): index
97 + normalize_fa(str(value)): index
98 for index, value in enumerate(header_values)
99 if value is not None
100 }
71 -
101 + kol_index = indexes.get(normalize_fa("kol"))
102 + statement_index = indexes.get(normalize_fa(_STATEMENT_BALANCE_HEADER))
103 for row_number, values in enumerate(
73 - worksheet.iter_rows(
74 - min_row=inspection.header_row + 1, values_only=True
75 - ),
104 + worksheet.iter_rows(min_row=inspection.header_row + 1, values_only=True),
105 start=inspection.header_row + 1,
106 ):
107 if not any(value is not None for value in values):
108 continue
80 -
81 - def value(field: str):
82 - return values[indexes[_FIELDS[field]]]
83 -
84 - yield LedgerRecord(
85 - row_number=row_number,
86 - account_code=_required_code(value("account_code"), row_number, "حساب"),
87 - account_name=_required_text(
88 - value("account_name"), row_number, "ACCOUNT_NAME"
89 - ),
90 - source_year=_required_year(value("source_year"), row_number),
91 - entry_type=_required_text(value("entry_type"), row_number, "نوع"),
92 - t1_code=_optional_code(value("t1_code"), row_number, "T1_CODE"),
93 - t2_code=_optional_code(value("t2_code"), row_number, "T2_CODE"),
94 - t3_code=_optional_code(value("t3_code"), row_number, "T3_CODE"),
95 - t4_code=_optional_code(value("t4_code"), row_number, "T4_CODE"),
96 - opening=_required_decimal(value("opening"), row_number, "OPENING"),
97 - debit=_required_decimal(value("debit"), row_number, "Debit"),
98 - credit=_required_decimal(value("credit"), row_number, "Credit"),
99 - closing=_required_decimal(value("closing"), row_number, "CLOSING"),
100 - )
109 + if tolerant:
110 + record, skip = _build_record_tolerant(
111 + values, indexes, kol_index, statement_index, row_number
112 + )
113 + if skip is not None:
114 + if skipped is not None:
115 + skipped.append(skip)
116 + continue
117 + if record is not None:
118 + yield record
119 + else:
120 + yield _build_record(values, indexes, kol_index, row_number)
121 finally:
122 workbook.close()
123
124
125 +def parse_general_ledger_csv(
126 + content: bytes, *, tolerant: bool = False, skipped: list[SkippedRow] | None = None
127 +) -> Iterator[LedgerRecord]:
128 + """Stream typed CSV ledger rows (D-06, booklet §8).
129 +
130 + Supports UTF-8, UTF-8-BOM and Windows-1256; sniffs the delimiter; applies the
131 + same Persian normalization and exact-money rules as the XLSX path. Reading is
132 + streaming (csv.reader over the decoded text), never materializing all rows.
133 + With ``tolerant=True`` the same reclassified-row handling as XLSX applies.
134 + """
135 + text = _decode_csv(content)
136 + sample = text[:4096]
137 + try:
138 + dialect = csv.Sniffer().sniff(sample, delimiters=",\t;")
139 + except csv.Error:
140 + dialect = csv.excel
141 + reader = csv.reader(io.StringIO(text), dialect)
142 + header = next(reader, None)
143 + if header is None:
144 + raise LedgerParseError("CSV ledger is empty")
145 + indexes = {normalize_fa(name): i for i, name in enumerate(header) if name.strip()}
146 + required = {normalize_fa(name) for name in _FIELDS.values()}
147 + missing = required.difference(indexes)
148 + if missing:
149 + raise LedgerParseError(f"CSV ledger is missing required headers: {sorted(missing)}")
150 + kol_index = indexes.get(normalize_fa("kol"))
151 + statement_index = indexes.get(normalize_fa(_STATEMENT_BALANCE_HEADER))
152 + for row_number, values in enumerate(reader, start=2):
153 + if not any(value.strip() for value in values):
154 + continue
155 + if tolerant:
156 + record, skip = _build_record_tolerant(
157 + values, indexes, kol_index, statement_index, row_number
158 + )
159 + if skip is not None:
160 + if skipped is not None:
161 + skipped.append(skip)
162 + continue
163 + if record is not None:
164 + yield record
165 + else:
166 + yield _build_record(values, indexes, kol_index, row_number)
167 +
168 +
169 +def parse_ledger(
170 + content: bytes,
171 + filename: str,
172 + *,
173 + tolerant: bool = False,
174 + skipped: list[SkippedRow] | None = None,
175 +) -> Iterator[LedgerRecord]:
176 + """Route to the XLSX or CSV parser by file extension (D-06)."""
177 + lower = filename.lower()
178 + if lower.endswith(".csv"):
179 + return parse_general_ledger_csv(content, tolerant=tolerant, skipped=skipped)
180 + if lower.endswith(".xlsx"):
181 + return parse_general_ledger(content, tolerant=tolerant, skipped=skipped)
182 + raise LedgerParseError("only .xlsx and .csv ledger files are supported")
183 +
184 +
185 +def _decode_csv(content: bytes) -> str:
186 + for encoding in _CSV_ENCODINGS:
187 + try:
188 + return content.decode(encoding)
189 + except UnicodeDecodeError:
190 + continue
191 + raise LedgerParseError("CSV encoding must be UTF-8, UTF-8-BOM, or Windows-1256")
192 +
193 +
194 +def _build_record(values, indexes, kol_index, row_number) -> LedgerRecord:
195 + def value(field: str):
196 + i = indexes[normalize_fa(_FIELDS[field])]
197 + return values[i] if i < len(values) else None
198 +
199 + return LedgerRecord(
200 + row_number=row_number,
201 + account_code=_required_code(value("account_code"), row_number, "حساب"),
202 + general_code=(
203 + _optional_code(values[kol_index], row_number, "kol")
204 + if kol_index is not None and kol_index < len(values)
205 + else None
206 + ),
207 + account_name=_required_text(value("account_name"), row_number, "ACCOUNT_NAME"),
208 + source_year=_required_year(value("source_year"), row_number),
209 + entry_type=_required_text(value("entry_type"), row_number, "نوع"),
210 + t1_code=_optional_code(value("t1_code"), row_number, "T1_CODE"),
211 + t2_code=_optional_code(value("t2_code"), row_number, "T2_CODE"),
212 + t3_code=_optional_code(value("t3_code"), row_number, "T3_CODE"),
213 + t4_code=_optional_code(value("t4_code"), row_number, "T4_CODE"),
214 + opening=_required_decimal(value("opening"), row_number, "OPENING"),
215 + debit=_required_decimal(value("debit"), row_number, "Debit"),
216 + credit=_required_decimal(value("credit"), row_number, "Credit"),
217 + closing=_required_decimal(value("closing"), row_number, "CLOSING"),
218 + )
219 +
220 +
221 +def _build_record_tolerant(
222 + values, indexes, kol_index, statement_index, row_number
223 +) -> tuple[LedgerRecord | None, SkippedRow | None]:
224 + """Build a record for real-ledger import.
225 +
226 + Reclassified source rows carry only ``مانده صورت مالی`` and leave the
227 + OPENING/Debit/Credit/CLOSING cells empty; those are stored as exact zero
228 + (the row is preserved for drill-down, D3). A *non-numeric* money cell is a
229 + genuine anomaly: the row is skipped and reported (fail-loud, never invented).
230 + Identity fields (account code/name/year/type) remain strictly required.
231 + """
232 +
233 + def value(field: str):
234 + i = indexes[normalize_fa(_FIELDS[field])]
235 + return values[i] if i < len(values) else None
236 +
237 + def money(field: str, header: str) -> Decimal:
238 + raw = value(field)
239 + if raw is None or (isinstance(raw, str) and not raw.strip()):
240 + return Decimal(0)
241 + return _required_decimal(raw, row_number, header)
242 +
243 + try:
244 + account_code = _required_code(value("account_code"), row_number, "حساب")
245 + account_name = _required_text(value("account_name"), row_number, "ACCOUNT_NAME")
246 + source_year = _required_year(value("source_year"), row_number)
247 + entry_type = _required_text(value("entry_type"), row_number, "نوع")
248 + opening = money("opening", "OPENING")
249 + debit = money("debit", "Debit")
250 + credit = money("credit", "Credit")
251 + closing = money("closing", "CLOSING")
252 + except LedgerParseError as exc:
253 + return None, SkippedRow(row_number=row_number, reason=str(exc))
254 +
255 + statement_balance: Decimal | None = None
256 + if statement_index is not None and statement_index < len(values):
257 + raw = values[statement_index]
258 + if raw is not None and not (isinstance(raw, str) and not raw.strip()):
259 + try:
260 + statement_balance = _required_decimal(raw, row_number, _STATEMENT_BALANCE_HEADER)
261 + except LedgerParseError:
262 + statement_balance = None
263 +
264 + record = LedgerRecord(
265 + row_number=row_number,
266 + account_code=account_code,
267 + general_code=(
268 + _optional_code(values[kol_index], row_number, "kol")
269 + if kol_index is not None and kol_index < len(values)
270 + else None
271 + ),
272 + account_name=account_name,
273 + source_year=source_year,
274 + entry_type=entry_type,
275 + t1_code=_optional_code(value("t1_code"), row_number, "T1_CODE"),
276 + t2_code=_optional_code(value("t2_code"), row_number, "T2_CODE"),
277 + t3_code=_optional_code(value("t3_code"), row_number, "T3_CODE"),
278 + t4_code=_optional_code(value("t4_code"), row_number, "T4_CODE"),
279 + opening=opening,
280 + debit=debit,
281 + credit=credit,
282 + closing=closing,
283 + statement_balance=statement_balance,
284 + )
285 + return record, None
286 +
287 +
288 def _required_text(value: object, row_number: int, field: str) -> str:
106 - text = str(value).strip() if value is not None else ""
289 + text = normalize_fa(str(value)) if value is not None else ""
290 if not text:
291 raise LedgerParseError(f"row {row_number}: {field} is required")
292 return text
@@ -126,25 +309,16 @@ def _required_code(value: object, row_number: int, field: str) -> str:
309 def _optional_code(value: object, row_number: int, field: str) -> str | None:
310 if value is None:
311 return None
129 - if isinstance(value, bool):
130 - raise LedgerParseError(f"row {row_number}: {field} is not a valid code")
131 - if isinstance(value, str):
132 - code = value.strip()
133 - return code or None
134 - parsed = _required_decimal(value, row_number, field)
135 - if parsed != parsed.to_integral_value():
136 - raise LedgerParseError(f"row {row_number}: {field} must be an integer code")
137 - return str(int(parsed))
312 + if isinstance(value, str) and not value.strip():
313 + return None
314 + try:
315 + return normalize_code(value, row=row_number, field=field)
316 + except NormalizationError as exc:
317 + raise LedgerParseError(str(exc)) from exc
318
319
320 def _required_decimal(value: object, row_number: int, field: str) -> Decimal:
141 - if value is None or isinstance(value, bool):
142 - raise LedgerParseError(f"row {row_number}: {field} is required and numeric")
143 - candidate = str(value).strip().replace(",", "").replace("٬", "")
321 try:
145 - parsed = Decimal(candidate)
146 - except (InvalidOperation, ValueError) as exc:
147 - raise LedgerParseError(f"row {row_number}: {field} is not numeric") from exc
148 - if not parsed.is_finite():
149 - raise LedgerParseError(f"row {row_number}: {field} must be finite")
150 - return parsed
322 + return decimal_from_cell(value, row=row_number, field=field)
323 + except NormalizationError as exc:
324 + raise LedgerParseError(str(exc)) from exc
backend/src/aram_backend/main.py
+22
@@ -1,12 +1,34 @@
1 +from pathlib import Path
2 +
3 from fastapi import FastAPI
4 +from fastapi.responses import HTMLResponse
5 +from fastapi.staticfiles import StaticFiles
6
7 from aram_backend import __version__
8 +from aram_backend.admin_api import router as admin_router
9 from aram_backend.config import get_settings
10 from aram_backend.models import FiscalYearStatus, StatementType
11 +from aram_backend.pilot_api import router as pilot_router
12 from aram_backend.schemas import EntityDescriptor, EnumCatalog, HealthResponse, SchemaCatalog
13 +from aram_backend.statement_api import router as statement_router
14
15 settings = get_settings()
16 app = FastAPI(title=settings.app_name, version=__version__)
17 +app.include_router(pilot_router)
18 +app.include_router(statement_router)
19 +app.include_router(admin_router)
20 +app.mount(
21 + "/pilot",
22 + StaticFiles(directory=Path(__file__).parent / "static" / "pilot", html=True),
23 + name="pilot-workbench",
24 +)
25 +
26 +
27 +@app.get("/", include_in_schema=False)
28 +def root() -> HTMLResponse:
29 + """Serve the workbench directly at the root (no redirect, proxy-safe)."""
30 + page = Path(__file__).parent / "static" / "pilot" / "index.html"
31 + return HTMLResponse(page.read_text(encoding="utf-8"))
32
33
34 @app.get("/api/v1/health", response_model=HealthResponse, tags=["system"])
backend/src/aram_backend/models.py
+189 -18
@@ -12,7 +12,6 @@ from sqlalchemy import (
12 Enum,
13 ForeignKey,
14 Integer,
15 - Numeric,
15 String,
16 Text,
17 UniqueConstraint,
@@ -23,25 +22,39 @@ from sqlalchemy import (
22 from sqlalchemy.orm import Mapped, Session, mapped_column, relationship
23
24 from aram_backend.database import Base
25 +from aram_backend.domain.money import Rial
26
27
28 def utc_now() -> datetime:
29 return datetime.now(UTC)
30
31
32 -class FiscalYearStatus(str, enum.Enum):
32 +class FiscalYearStatus(enum.StrEnum):
33 DRAFT = "Draft"
34 APPROVED = "Approved"
35 LOCKED = "Locked"
36
37
38 -class StatementType(str, enum.Enum):
38 +class StatementType(enum.StrEnum):
39 BALANCE_SHEET = "BS"
40 INCOME_STATEMENT = "IS"
41 CASH_FLOW = "CF"
42 EQUITY = "EQ"
43
44
45 +class UserRole(enum.StrEnum):
46 + """Local application roles (Phase 7, offline desktop; no runtime network).
47 +
48 + admin: manage users, approve reopen requests, lock years, backup.
49 + reviewer: approve years and reopen requests.
50 + preparer: import, map, build statements, request reopen.
51 + """
52 +
53 + ADMIN = "admin"
54 + REVIEWER = "reviewer"
55 + PREPARER = "preparer"
56 +
57 +
58 class TimestampMixin:
59 created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
60 updated_at: Mapped[datetime] = mapped_column(
@@ -75,7 +88,79 @@ class FiscalYear(TimestampMixin, Base):
88
89
90 class YearOwnedMixin:
78 - year_id: Mapped[int] = mapped_column(ForeignKey("fiscal_years.id", ondelete="RESTRICT"), index=True)
91 + year_id: Mapped[int] = mapped_column(
92 + ForeignKey("fiscal_years.id", ondelete="RESTRICT"), index=True
93 + )
94 +
95 +
96 +class ReopenRequest(TimestampMixin, YearOwnedMixin, Base):
97 + """A controlled request to reopen a LOCKED year (D-07, booklet §7).
98 +
99 + LOCKED -> APPROVED is permitted only when an ``approved`` request exists.
100 + Reopening versions the output; it never edits locked rows in place.
101 + """
102 +
103 + __tablename__ = "reopen_requests"
104 + id: Mapped[int] = mapped_column(primary_key=True)
105 + reason: Mapped[str] = mapped_column(Text)
106 + requested_by: Mapped[str] = mapped_column(String(128), default="")
107 + approved_by: Mapped[str | None] = mapped_column(String(128), nullable=True)
108 + status: Mapped[str] = mapped_column(String(16), default="pending")
109 +
110 +
111 +class AuditEntry(Base):
112 + """Append-only, hash-chained audit log (D-07, booklet §12).
113 +
114 + chain_hash = SHA256(previous_hash || payload_hash). UPDATE/DELETE are blocked
115 + by triggers; verify_chain detects any tampering with past entries.
116 + """
117 +
118 + __tablename__ = "audit_entries"
119 + id: Mapped[int] = mapped_column(primary_key=True)
120 + year_id: Mapped[int | None] = mapped_column(
121 + ForeignKey("fiscal_years.id", ondelete="RESTRICT"), nullable=True, index=True
122 + )
123 + actor: Mapped[str] = mapped_column(String(128), default="")
124 + action: Mapped[str] = mapped_column(String(64))
125 + payload_hash: Mapped[str] = mapped_column(String(64))
126 + previous_hash: Mapped[str] = mapped_column(String(64))
127 + chain_hash: Mapped[str] = mapped_column(String(64))
128 + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
129 +
130 +
131 +class User(TimestampMixin, Base):
132 + """Local application user with a role (Phase 7, booklet §7/§12).
133 +
134 + Passwords are stored only as a PBKDF2-HMAC-SHA256 hash with a per-user random
135 + salt (stdlib hashlib; no plaintext, no new dependency). Actions are attributed
136 + to a username in the hash-chained audit log. This is an offline desktop app:
137 + there is no runtime network or external identity provider.
138 + """
139 +
140 + __tablename__ = "users"
141 + id: Mapped[int] = mapped_column(primary_key=True)
142 + username: Mapped[str] = mapped_column(String(64), unique=True, index=True)
143 + display_name: Mapped[str] = mapped_column(String(128), default="")
144 + role: Mapped[UserRole] = mapped_column(
145 + Enum(UserRole, native_enum=False, length=16), default=UserRole.PREPARER
146 + )
147 + password_hash: Mapped[str] = mapped_column(String(128))
148 + salt: Mapped[str] = mapped_column(String(64))
149 + active: Mapped[bool] = mapped_column(default=True)
150 +
151 +
152 +class SourceFile(TimestampMixin, Base):
153 + """Content-addressed source bytes stored on disk (D-06, booklet §5).
154 +
155 + The primary key is the SHA-256 of the bytes; ``stored_path`` points at the
156 + immutable file in the content-addressed store. SourceDocument references it.
157 + """
158 +
159 + __tablename__ = "source_files"
160 + sha256: Mapped[str] = mapped_column(String(64), primary_key=True)
161 + size: Mapped[int] = mapped_column(Integer)
162 + content_type: Mapped[str] = mapped_column(String(64), default="")
163 + stored_path: Mapped[str] = mapped_column(String(512))
164
165
166 class SourceDocument(TimestampMixin, YearOwnedMixin, Base):
@@ -88,6 +173,9 @@ class SourceDocument(TimestampMixin, YearOwnedMixin, Base):
173 file_hash: Mapped[str] = mapped_column(String(128))
174 document_type: Mapped[str] = mapped_column(String(64))
175 uploaded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
176 + source_file_hash: Mapped[str | None] = mapped_column(
177 + ForeignKey("source_files.sha256", ondelete="RESTRICT"), nullable=True
178 + )
179
180
181 class AccountVersion(TimestampMixin, YearOwnedMixin, Base):
@@ -107,6 +195,52 @@ class AccountVersion(TimestampMixin, YearOwnedMixin, Base):
195 nature: Mapped[str | None] = mapped_column(String(64))
196
197
198 +class LedgerBalance(TimestampMixin, YearOwnedMixin, Base):
199 + """Persisted account balance from a source ledger import (D-01, booklet §5).
200 +
201 + Money is exact integer rial via the ``Rial`` TypeDecorator (P-02). Codes are
202 + text (P-03). **One row per source ledger row** (raw, never aggregated on
203 + import) so every figure drills down to its exact file/sheet/row (D3, P-01).
204 + Unique per ``(year_id, source_document_id, source_row, import_version)``; a new
205 + import for a Draft year creates a new version rather than mutating the prior
206 + snapshot. Account-level totals are computed in the service layer.
207 + """
208 +
209 + __tablename__ = "ledger_balances"
210 + __table_args__ = (
211 + UniqueConstraint(
212 + "year_id",
213 + "source_document_id",
214 + "source_row",
215 + "import_version",
216 + name="uq_ledger_balance_year_source_row_version",
217 + ),
218 + CheckConstraint("import_version > 0", name="positive_import_version"),
219 + CheckConstraint("source_row > 0", name="positive_source_row"),
220 + )
221 + id: Mapped[int] = mapped_column(primary_key=True)
222 + source_document_id: Mapped[int] = mapped_column(
223 + ForeignKey("source_documents.id", ondelete="RESTRICT"), index=True
224 + )
225 + source_sheet: Mapped[str] = mapped_column(String(128))
226 + source_row: Mapped[int] = mapped_column(Integer)
227 + import_version: Mapped[int] = mapped_column(Integer, default=1)
228 + account_full_code: Mapped[str] = mapped_column(String(64), index=True)
229 + general_code: Mapped[str] = mapped_column(String(64), default="")
230 + subsidiary_code: Mapped[str] = mapped_column(String(64), default="")
231 + detail1_code: Mapped[str] = mapped_column(String(128), default="")
232 + detail2_code: Mapped[str] = mapped_column(String(128), default="")
233 + detail3_code: Mapped[str] = mapped_column(String(128), default="")
234 + detail4_code: Mapped[str] = mapped_column(String(128), default="")
235 + account_name: Mapped[str] = mapped_column(String(512))
236 + opening: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
237 + debit: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
238 + credit: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
239 + closing: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
240 + statement_balance: Mapped[Decimal | None] = mapped_column(Rial(), nullable=True, default=None)
241 + entry_type: Mapped[str] = mapped_column(String(32), default="")
242 +
243 +
244 class NoteDefinition(TimestampMixin, YearOwnedMixin, Base):
245 __tablename__ = "note_definitions"
246 __table_args__ = (
@@ -128,7 +262,9 @@ class NoteRow(TimestampMixin, Base):
262 CheckConstraint("row_order >= 0", name="nonnegative_row_order"),
263 )
264 id: Mapped[int] = mapped_column(primary_key=True)
131 - note_id: Mapped[int] = mapped_column(ForeignKey("note_definitions.id", ondelete="CASCADE"), index=True)
265 + note_id: Mapped[int] = mapped_column(
266 + ForeignKey("note_definitions.id", ondelete="CASCADE"), index=True
267 + )
268 row_order: Mapped[int] = mapped_column(Integer)
269 label: Mapped[str] = mapped_column(String(512))
270 formula_logic: Mapped[str | None] = mapped_column(Text)
@@ -146,7 +282,9 @@ class MappingRule(TimestampMixin, YearOwnedMixin, Base):
282 rule_key: Mapped[str] = mapped_column(String(128))
283 version: Mapped[int] = mapped_column(Integer, default=1)
284 account_code: Mapped[str] = mapped_column(String(64), index=True)
149 - target_note_id: Mapped[int] = mapped_column(ForeignKey("note_definitions.id", ondelete="RESTRICT"))
285 + target_note_id: Mapped[int] = mapped_column(
286 + ForeignKey("note_definitions.id", ondelete="RESTRICT")
287 + )
288 mapping_type: Mapped[str] = mapped_column(String(32))
289 target_note: Mapped[NoteDefinition] = relationship()
290
@@ -154,7 +292,9 @@ class MappingRule(TimestampMixin, YearOwnedMixin, Base):
292 class FinancialStatement(TimestampMixin, YearOwnedMixin, Base):
293 __tablename__ = "financial_statements"
294 __table_args__ = (
157 - UniqueConstraint("year_id", "statement_type", "version", name="uq_statement_year_type_version"),
295 + UniqueConstraint(
296 + "year_id", "statement_type", "version", name="uq_statement_year_type_version"
297 + ),
298 CheckConstraint("version > 0", name="positive_version"),
299 )
300 id: Mapped[int] = mapped_column(primary_key=True)
@@ -172,11 +312,15 @@ class StatementLine(TimestampMixin, Base):
312 CheckConstraint("line_order >= 0", name="nonnegative_line_order"),
313 )
314 id: Mapped[int] = mapped_column(primary_key=True)
175 - statement_id: Mapped[int] = mapped_column(ForeignKey("financial_statements.id", ondelete="CASCADE"), index=True)
315 + statement_id: Mapped[int] = mapped_column(
316 + ForeignKey("financial_statements.id", ondelete="CASCADE"), index=True
317 + )
318 line_order: Mapped[int] = mapped_column(Integer)
319 line_label: Mapped[str] = mapped_column(String(512))
178 - target_note_id: Mapped[int | None] = mapped_column(ForeignKey("note_definitions.id", ondelete="RESTRICT"))
179 - mapped_total: Mapped[Decimal | None] = mapped_column(Numeric(24, 4))
320 + target_note_id: Mapped[int | None] = mapped_column(
321 + ForeignKey("note_definitions.id", ondelete="RESTRICT")
322 + )
323 + mapped_total: Mapped[Decimal | None] = mapped_column(Rial())
324 statement: Mapped[FinancialStatement] = relationship(back_populates="lines")
325 target_note: Mapped[NoteDefinition | None] = relationship()
326
@@ -201,7 +345,9 @@ def _year_id_for(obj: object, session: Session) -> int | None:
345 if isinstance(obj, NoteRow):
346 return _resolve_parent_year_id(obj, session, "note", "note_id", NoteDefinition)
347 if isinstance(obj, StatementLine):
204 - return _resolve_parent_year_id(obj, session, "statement", "statement_id", FinancialStatement)
348 + return _resolve_parent_year_id(
349 + obj, session, "statement", "statement_id", FinancialStatement
350 + )
351 return None
352
353
@@ -210,10 +356,12 @@ _PROTECTED_YEAR_STATUSES = {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}
356
357 def _company_has_protected_year(session: Session, company_id: int) -> bool:
358 status = session.scalar(
213 - select(FiscalYear.status).where(
359 + select(FiscalYear.status)
360 + .where(
361 FiscalYear.company_id == company_id,
362 FiscalYear.status.in_(_PROTECTED_YEAR_STATUSES),
216 - ).limit(1)
363 + )
364 + .limit(1)
365 )
366 return status is not None
367
@@ -246,12 +394,25 @@ def enforce_audit_invariants(session: Session, _flush_context, _instances) -> No
394 allowed = {
395 FiscalYearStatus.DRAFT: {FiscalYearStatus.APPROVED},
396 FiscalYearStatus.APPROVED: {FiscalYearStatus.LOCKED},
249 - FiscalYearStatus.LOCKED: set(),
397 + FiscalYearStatus.LOCKED: {FiscalYearStatus.APPROVED},
398 }
399 if obj.status not in allowed[old_status]:
400 raise ValueError(
401 f"Invalid fiscal-year transition: {old_status.value} -> {obj.status.value}"
402 )
403 + if old_status == FiscalYearStatus.LOCKED and obj.status == FiscalYearStatus.APPROVED:
404 + approved_reopen = session.scalar(
405 + select(ReopenRequest.id)
406 + .where(
407 + ReopenRequest.year_id == obj.id,
408 + ReopenRequest.status == "approved",
409 + )
410 + .limit(1)
411 + )
412 + if approved_reopen is None:
413 + raise ValueError(
414 + f"Fiscal year {obj.id} is locked; reopening requires an approved ReopenRequest"
415 + )
416
417 protected_metadata_changed = state.attrs.company.history.has_changes() or any(
418 state.attrs[field].history.has_changes() for field in ("company_id", "year")
@@ -271,10 +432,14 @@ def enforce_audit_invariants(session: Session, _flush_context, _instances) -> No
432 f"Company {obj.id} has approved or locked fiscal years and cannot be deleted"
433 )
434
274 - protected = (session.new | session.dirty | session.deleted)
435 + protected = session.new | session.dirty | session.deleted
436 for obj in protected:
437 if isinstance(obj, FiscalYear):
438 continue
439 + # A ReopenRequest is the authorized mechanism to act on a locked year
440 + # (ADR-016); creating/approving it must not be blocked by the year guard.
441 + if isinstance(obj, ReopenRequest):
442 + continue
443 year_id = _year_id_for(obj, session)
444 if year_id is None:
445 continue
@@ -285,10 +450,16 @@ def enforce_audit_invariants(session: Session, _flush_context, _instances) -> No
450 )
451
452 if isinstance(obj, MappingRule):
288 - target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition)
453 + target_year_id = _resolve_parent_year_id(
454 + obj, session, "target_note", "target_note_id", NoteDefinition
455 + )
456 if target_year_id != obj.year_id:
457 raise ValueError("Mapping rule and target note must belong to the same fiscal year")
458 if isinstance(obj, StatementLine) and obj.target_note_id is not None:
292 - target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition)
459 + target_year_id = _resolve_parent_year_id(
460 + obj, session, "target_note", "target_note_id", NoteDefinition
461 + )
462 if target_year_id != year_id:
294 - raise ValueError("Statement line and target note must belong to the same fiscal year")
463 + raise ValueError(
464 + "Statement line and target note must belong to the same fiscal year"
465 + )
backend/src/aram_backend/pilot_api.py new
+401
@@ -0,0 +1,401 @@
1 +"""HTTP API for the Pilot workbench (in-memory, audit-friendly, fail-closed)."""
2 +
3 +from __future__ import annotations
4 +
5 +import re
6 +from io import BytesIO
7 +
8 +from fastapi import APIRouter, File, HTTPException, Query, UploadFile
9 +from fastapi.responses import StreamingResponse
10 +from pydantic import BaseModel, Field
11 +
12 +from aram_backend.pilot_demo import build_demo_workbook
13 +from aram_backend.pilot_editing import (
14 + DuplicateAccountError,
15 + DuplicateNoteError,
16 + EditingError,
17 + InvalidCompanyError,
18 + NoteInUseError,
19 + UnknownNoteError,
20 + make_company,
21 + make_note,
22 +)
23 +from aram_backend.pilot_engine import (
24 + DEFERRED_STATEMENTS,
25 + RENDERED_STATEMENTS,
26 + SECTION_LABELS_FA,
27 + SECTION_POLICY,
28 + STATEMENT_LABELS_FA,
29 + PilotModelError,
30 + accounts_table,
31 + build_report,
32 + export_report_workbook,
33 + export_working_workbook,
34 + notes_table,
35 + parse_pilot_model,
36 +)
37 +from aram_backend.pilot_store import (
38 + InvalidApprovalError,
39 + UnknownAccountError,
40 + UnknownSessionError,
41 + UnknownTargetError,
42 + store,
43 +)
44 +
45 +router = APIRouter(prefix="/api/v1/pilot", tags=["pilot-workbench"])
46 +
47 +MAX_UPLOAD_BYTES = 25 * 1024 * 1024
48 +XLSX_MEDIA_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
49 +
50 +Amount = str | int | float
51 +
52 +
53 +class MappingUpdate(BaseModel):
54 + statement: str = Field(min_length=1)
55 + section: str = Field(min_length=1)
56 + note_number: str = Field(min_length=1)
57 + subnote_code: str = ""
58 + approval_status: str = "Draft"
59 + reviewer: str = ""
60 + actor: str = ""
61 +
62 +
63 +class AccountCreate(BaseModel):
64 + full_code: str = Field(min_length=1)
65 + name: str = Field(min_length=1)
66 + general_code: str = Field(min_length=1)
67 + general_name: str = Field(min_length=1)
68 + opening: Amount = "0"
69 + debit: Amount = "0"
70 + credit: Amount = "0"
71 + source_row: int | None = None
72 + row_status: str = "Draft"
73 + subsidiary_code: str = ""
74 + subsidiary_name: str = ""
75 + actor: str = ""
76 +
77 +
78 +class AccountUpdate(BaseModel):
79 + name: str = Field(min_length=1)
80 + general_code: str = Field(min_length=1)
81 + general_name: str = Field(min_length=1)
82 + opening: Amount = "0"
83 + debit: Amount = "0"
84 + credit: Amount = "0"
85 + row_status: str = "Draft"
86 + subsidiary_code: str = ""
87 + subsidiary_name: str = ""
88 + actor: str = ""
89 +
90 +
91 +class AccountRename(BaseModel):
92 + new_code: str = Field(min_length=1)
93 + actor: str = ""
94 +
95 +
96 +class NoteCreate(BaseModel):
97 + statement: str = Field(min_length=1)
98 + section: str = Field(min_length=1)
99 + note_number: str = Field(min_length=1)
100 + note_title: str = Field(min_length=1)
101 + subnote_code: str = ""
102 + subnote_title: str = ""
103 + actor: str = ""
104 +
105 +
106 +class NoteUpdate(BaseModel):
107 + statement: str = Field(min_length=1)
108 + section: str = Field(min_length=1)
109 + note_number: str = Field(min_length=1)
110 + subnote_code: str = ""
111 + note_title: str = Field(min_length=1)
112 + subnote_title: str = ""
113 + actor: str = ""
114 +
115 +
116 +class CompanyUpdate(BaseModel):
117 + code: str = Field(min_length=1)
118 + name: str = Field(min_length=1)
119 + fiscal_year: int
120 + currency: str = ""
121 + unit: str = ""
122 + prepared_by: str = ""
123 + status: str = "Draft"
124 + actor: str = ""
125 +
126 +
127 +def _issues_payload(exc: PilotModelError) -> list[dict]:
128 + return [
129 + {
130 + "severity": issue.severity, "code": issue.code, "sheet": issue.sheet,
131 + "row": issue.row, "field": issue.field, "message": issue.message,
132 + }
133 + for issue in exc.issues
134 + ]
135 +
136 +
137 +def _session_payload(session_id: str) -> dict:
138 + session, working, trail = store.snapshot(session_id)
139 + report = build_report(working, working.mappings)
140 + return {
141 + "session": {
142 + "id": session.id, "created_at": session.created_at,
143 + "source": session.source, "filename": session.filename,
144 + },
145 + "report": report,
146 + "accounts": accounts_table(working, working.mappings),
147 + "notes": notes_table(working),
148 + "audit_trail": trail,
149 + }
150 +
151 +
152 +def _create_session(data: bytes, source: str, filename: str) -> dict:
153 + try:
154 + model = parse_pilot_model(data)
155 + except PilotModelError as exc:
156 + raise HTTPException(
157 + status_code=422,
158 + detail={
159 + "message": "فایل با قرارداد پایلوت v0.1 سازگار نیست؛ خطاهای زیر را رفع کنید.",
160 + "issues": _issues_payload(exc),
161 + },
162 + ) from exc
163 + session = store.create(model, source=source, filename=filename)
164 + return _session_payload(session.id)
165 +
166 +
167 +def _get_session_or_404(session_id: str):
168 + try:
169 + return store.get(session_id)
170 + except UnknownSessionError as exc:
171 + raise HTTPException(404, detail={"message": "جلسه یافت نشد؛ دوباره فایل را وارد کنید."}) from exc
172 +
173 +
174 +def _editing_http_error(exc: Exception) -> HTTPException:
175 + if isinstance(exc, (UnknownAccountError, UnknownNoteError)):
176 + return HTTPException(404, detail={"message": str(exc) or "مورد یافت نشد."})
177 + if isinstance(exc, NoteInUseError):
178 + return HTTPException(409, detail={"message": str(exc)})
179 + if isinstance(exc, (DuplicateAccountError, DuplicateNoteError)):
180 + return HTTPException(409, detail={"message": str(exc)})
181 + if isinstance(exc, (EditingError, InvalidApprovalError, UnknownTargetError, InvalidCompanyError)):
182 + return HTTPException(422, detail={"message": str(exc)})
183 + raise exc
184 +
185 +
186 +@router.get("/meta")
187 +def pilot_meta() -> dict:
188 + return {
189 + "rendered_statements": list(RENDERED_STATEMENTS),
190 + "deferred_statements": list(DEFERRED_STATEMENTS),
191 + "statement_labels_fa": STATEMENT_LABELS_FA,
192 + "section_policy": SECTION_POLICY,
193 + "section_labels_fa": SECTION_LABELS_FA,
194 + "contract": "Pilot workbook v0.1",
195 + "disclaimer_fa": "خروجی این ابزار پیش‌نویس کاری برای بررسی است، نه صورت مالی رسمی.",
196 + }
197 +
198 +
199 +@router.post("/sessions")
200 +async def create_session_from_upload(file: UploadFile = File(...)) -> dict:
201 + filename = file.filename or "upload.xlsx"
202 + if not filename.lower().endswith(".xlsx"):
203 + raise HTTPException(422, detail={"message": "فقط فایل .xlsx پذیرفته می‌شود."})
204 + data = await file.read()
205 + if not data:
206 + raise HTTPException(422, detail={"message": "فایل خالی است."})
207 + if len(data) > MAX_UPLOAD_BYTES:
208 + raise HTTPException(413, detail={"message": "حداکثر حجم مجاز ۲۵ مگابایت است."})
209 + return _create_session(data, source="upload", filename=filename)
210 +
211 +
212 +@router.post("/demo")
213 +def create_demo_session() -> dict:
214 + return _create_session(
215 + build_demo_workbook(), source="demo", filename="aram-synthetic-demo.xlsx"
216 + )
217 +
218 +
219 +@router.get("/sessions/{session_id}")
220 +def get_session(session_id: str) -> dict:
221 + _get_session_or_404(session_id)
222 + return _session_payload(session_id)
223 +
224 +
225 +@router.delete("/sessions/{session_id}")
226 +def delete_session(session_id: str) -> dict:
227 + _get_session_or_404(session_id)
228 + store.delete(session_id)
229 + return {"deleted": session_id}
230 +
231 +
232 +# ------------------------------------------------------------------ mappings
233 +@router.put("/sessions/{session_id}/mappings/{account_code}")
234 +def set_mapping(session_id: str, account_code: str, update: MappingUpdate) -> dict:
235 + _get_session_or_404(session_id)
236 + try:
237 + store.set_mapping(
238 + session_id, account_code,
239 + statement=update.statement.strip(), section=update.section.strip(),
240 + note_number=update.note_number.strip(), subnote_code=update.subnote_code.strip(),
241 + approval_status=update.approval_status, reviewer=update.reviewer, actor=update.actor,
242 + )
243 + except (UnknownAccountError, UnknownTargetError, InvalidApprovalError) as exc:
244 + raise _editing_http_error(exc) from exc
245 + return _session_payload(session_id)
246 +
247 +
248 +@router.delete("/sessions/{session_id}/mappings/{account_code}")
249 +def clear_mapping(session_id: str, account_code: str, actor: str = Query(default="")) -> dict:
250 + _get_session_or_404(session_id)
251 + try:
252 + store.clear_mapping(session_id, account_code, actor=actor)
253 + except UnknownAccountError as exc:
254 + raise _editing_http_error(exc) from exc
255 + return _session_payload(session_id)
256 +
257 +
258 +# ------------------------------------------------------------------ accounts
259 +@router.post("/sessions/{session_id}/accounts")
260 +def add_account(session_id: str, body: AccountCreate) -> dict:
261 + _get_session_or_404(session_id)
262 + try:
263 + store.add_account(
264 + session_id, full_code=body.full_code, name=body.name,
265 + general_code=body.general_code, general_name=body.general_name,
266 + opening=body.opening, debit=body.debit, credit=body.credit,
267 + source_row=body.source_row, row_status=body.row_status,
268 + subsidiary_code=body.subsidiary_code, subsidiary_name=body.subsidiary_name,
269 + actor=body.actor,
270 + )
271 + except (EditingError, UnknownAccountError) as exc:
272 + raise _editing_http_error(exc) from exc
273 + return _session_payload(session_id)
274 +
275 +
276 +@router.put("/sessions/{session_id}/accounts/{account_code}")
277 +def update_account(session_id: str, account_code: str, body: AccountUpdate) -> dict:
278 + _get_session_or_404(session_id)
279 + try:
280 + store.update_account(
281 + session_id, account_code, name=body.name,
282 + general_code=body.general_code, general_name=body.general_name,
283 + opening=body.opening, debit=body.debit, credit=body.credit,
284 + row_status=body.row_status, subsidiary_code=body.subsidiary_code,
285 + subsidiary_name=body.subsidiary_name, actor=body.actor,
286 + )
287 + except (EditingError, UnknownAccountError) as exc:
288 + raise _editing_http_error(exc) from exc
289 + return _session_payload(session_id)
290 +
291 +
292 +@router.post("/sessions/{session_id}/accounts/{account_code}/rename")
293 +def rename_account(session_id: str, account_code: str, body: AccountRename) -> dict:
294 + _get_session_or_404(session_id)
295 + try:
296 + store.rename_account(session_id, account_code, body.new_code, actor=body.actor)
297 + except (EditingError, UnknownAccountError) as exc:
298 + raise _editing_http_error(exc) from exc
299 + return _session_payload(session_id)
300 +
301 +
302 +@router.delete("/sessions/{session_id}/accounts/{account_code}")
303 +def delete_account(session_id: str, account_code: str, actor: str = Query(default="")) -> dict:
304 + _get_session_or_404(session_id)
305 + try:
306 + store.delete_account(session_id, account_code, actor=actor)
307 + except UnknownAccountError as exc:
308 + raise _editing_http_error(exc) from exc
309 + return _session_payload(session_id)
310 +
311 +
312 +# --------------------------------------------------------------------- notes
313 +@router.post("/sessions/{session_id}/notes")
314 +def add_note(session_id: str, body: NoteCreate) -> dict:
315 + _get_session_or_404(session_id)
316 + try:
317 + note = make_note(
318 + statement=body.statement, section=body.section, note_number=body.note_number,
319 + note_title=body.note_title, subnote_code=body.subnote_code,
320 + subnote_title=body.subnote_title,
321 + )
322 + store.add_note(session_id, note, actor=body.actor)
323 + except EditingError as exc:
324 + raise _editing_http_error(exc) from exc
325 + return _session_payload(session_id)
326 +
327 +
328 +@router.put("/sessions/{session_id}/notes")
329 +def update_note(session_id: str, body: NoteUpdate) -> dict:
330 + _get_session_or_404(session_id)
331 + try:
332 + key = (body.statement.strip(), body.section.strip(),
333 + body.note_number.strip(), body.subnote_code.strip())
334 + note = make_note(
335 + statement=body.statement, section=body.section, note_number=body.note_number,
336 + note_title=body.note_title, subnote_code=body.subnote_code,
337 + subnote_title=body.subnote_title,
338 + )
339 + store.update_note(session_id, key, note, actor=body.actor)
340 + except EditingError as exc:
341 + raise _editing_http_error(exc) from exc
342 + return _session_payload(session_id)
343 +
344 +
345 +@router.delete("/sessions/{session_id}/notes")
346 +def delete_note(
347 + session_id: str, statement: str = Query(...), section: str = Query(...),
348 + note_number: str = Query(...), subnote_code: str = Query(default=""),
349 + actor: str = Query(default=""),
350 +) -> dict:
351 + _get_session_or_404(session_id)
352 + key = (statement.strip(), section.strip(), note_number.strip(), subnote_code.strip())
353 + try:
354 + store.delete_note(session_id, key, actor=actor)
355 + except EditingError as exc:
356 + raise _editing_http_error(exc) from exc
357 + return _session_payload(session_id)
358 +
359 +
360 +# ------------------------------------------------------------------- company
361 +@router.put("/sessions/{session_id}/company")
362 +def update_company(session_id: str, body: CompanyUpdate) -> dict:
363 + _get_session_or_404(session_id)
364 + try:
365 + company = make_company(
366 + code=body.code, name=body.name, fiscal_year=body.fiscal_year,
367 + currency=body.currency, unit=body.unit, prepared_by=body.prepared_by,
368 + status=body.status,
369 + )
370 + store.update_company(session_id, company, actor=body.actor)
371 + except EditingError as exc:
372 + raise _editing_http_error(exc) from exc
373 + return _session_payload(session_id)
374 +
375 +
376 +# ------------------------------------------------------------------- exports
377 +@router.get("/sessions/{session_id}/export.xlsx")
378 +def export_session(session_id: str) -> StreamingResponse:
379 + session = _get_session_or_404(session_id)
380 + _, working, trail = store.snapshot(session_id)
381 + report = build_report(working, working.mappings)
382 + data = export_report_workbook(working, working.mappings, report, trail, session.source)
383 + safe_code = re.sub(r"[^A-Za-z0-9_-]", "", working.company.code) or "session"
384 + filename = f"aram-pilot-{safe_code}-{working.company.fiscal_year}.xlsx"
385 + return StreamingResponse(
386 + BytesIO(data), media_type=XLSX_MEDIA_TYPE,
387 + headers={"Content-Disposition": f'attachment; filename="{filename}"'},
388 + )
389 +
390 +
391 +@router.get("/sessions/{session_id}/workspace.xlsx")
392 +def export_workspace(session_id: str) -> StreamingResponse:
393 + _get_session_or_404(session_id)
394 + _, working, _ = store.snapshot(session_id)
395 + data = export_working_workbook(working)
396 + safe_code = re.sub(r"[^A-Za-z0-9_-]", "", working.company.code) or "session"
397 + filename = f"aram-workspace-{safe_code}-{working.company.fiscal_year}.xlsx"
398 + return StreamingResponse(
399 + BytesIO(data), media_type=XLSX_MEDIA_TYPE,
400 + headers={"Content-Disposition": f'attachment; filename="{filename}"'},
401 + )
backend/src/aram_backend/pilot_demo.py new
+161
@@ -0,0 +1,161 @@
1 +"""Synthetic demo workbook for the Pilot workbench.
2 +
3 +Every value here is fabricated for demonstration and is clearly labelled as
4 +such in the company name, the workbook itself, the API and the UI. It never
5 +touches canonical data and must never be used for real financial reporting.
6 +The trial balance is balanced; two suspense accounts are intentionally left
7 +unmapped so the exception-queue workflow can be exercised end to end.
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +from datetime import UTC, datetime
13 +from io import BytesIO
14 +
15 +from openpyxl import Workbook
16 +
17 +from aram_backend.pilot_workbook import SHEET_HEADERS
18 +
19 +DEMO_COMPANY_CODE = "DEMO"
20 +DEMO_COMPANY_NAME = "شرکت ساختگی دمو (دادهٔ کاملاً غیرواقعی)"
21 +DEMO_YEAR = 1404
22 +DEMO_REVIEWER = "بازبین دمو (ساختگی)"
23 +DEMO_REVIEW_DATE = "2026-12-03"
24 +
25 +# (full_code, name, general_code, general_name, subsidiary_code,
26 +# closing, debit, credit, statement, section, note_number, approval)
27 +_DEMO_ACCOUNTS = [
28 + ("1001", "نقد و بانک", "10", "دارایی‌های جاری", "01", 12_500_000_000, 7_500_000_000, 5_000_000_000, "BS", "Assets", "01", "Approved"),
29 + ("1002", "دریافتنی‌های تجاری", "10", "دارایی‌های جاری", "02", 8_300_000_000, 6_100_000_000, 4_300_000_000, "BS", "Assets", "02", "Approved"),
30 + ("1003", "موجودی کالا", "10", "دارایی‌های جاری", "03", 15_200_000_000, 9_400_000_000, 7_100_000_000, "BS", "Assets", "03", "Approved"),
31 + ("1004", "پیش‌پرداخت‌ها", "10", "دارایی‌های جاری", "04", 1_100_000_000, 800_000_000, 500_000_000, "BS", "Assets", "04", "Draft"),
32 + ("1101", "دارایی‌های ثابت مشهود", "11", "دارایی‌های غیرجاری", "01", 22_000_000_000, 4_000_000_000, 0, "BS", "Assets", "05", "Approved"),
33 + ("1102", "استهلاک انباشته", "11", "دارایی‌های غیرجاری", "02", -3_600_000_000, 0, 900_000_000, "BS", "Assets", "05", "Approved"),
34 + ("2001", "پرداختنی‌های تجاری", "20", "بدهی‌های جاری", "01", -6_400_000_000, 3_200_000_000, 4_100_000_000, "BS", "Liabilities", "06", "Approved"),
35 + ("2003", "ذخیره مالیات", "20", "بدهی‌های جاری", "03", -1_900_000_000, 0, 1_900_000_000, "BS", "Liabilities", "08", "Approved"),
36 + ("2101", "تسهیلات مالی", "21", "بدهی‌های غیرجاری", "01", -14_000_000_000, 2_000_000_000, 5_000_000_000, "BS", "Liabilities", "07", "Approved"),
37 + ("3001", "سرمایه", "30", "حقوق مالکانه", "01", -20_000_000_000, 0, 0, "BS", "Equity", "09", "Approved"),
38 + ("3002", "سود انباشته", "30", "حقوق مالکانه", "02", -13_000_000_000, 0, 0, "BS", "Equity", "10", "Approved"),
39 + ("4001", "فروش", "40", "درآمدها", "01", -18_700_000_000, 0, 18_700_000_000, "IS", "Revenue", "11", "Approved"),
40 + ("4002", "سایر درآمدها", "40", "درآمدها", "02", -400_000_000, 0, 400_000_000, "IS", "Revenue", "12", "Approved"),
41 + ("5001", "بهای تمام‌شده کالای فروش‌رفته", "50", "هزینه‌ها", "01", 9_800_000_000, 9_800_000_000, 0, "IS", "Expenses", "13", "Approved"),
42 + ("5002", "حقوق و دستمزد", "50", "هزینه‌ها", "02", 3_900_000_000, 3_900_000_000, 0, "IS", "Expenses", "14", "Approved"),
43 + ("5003", "اجاره و اداری", "50", "هزینه‌ها", "03", 1_250_000_000, 1_250_000_000, 0, "IS", "Expenses", "15", "Approved"),
44 + ("5004", "هزینه استهلاک", "50", "هزینه‌ها", "04", 900_000_000, 900_000_000, 0, "IS", "Expenses", "16", "Approved"),
45 + ("5005", "هزینه‌های مالی", "50", "هزینه‌ها", "05", 1_150_000_000, 1_150_000_000, 0, "IS", "Expenses", "17", "Approved"),
46 + ("5006", "مالیات بر درآمد", "50", "هزینه‌ها", "06", 1_900_000_000, 1_900_000_000, 0, "IS", "Expenses", "18", "Approved"),
47 + # Intentionally unmapped suspense pair: balanced, but incomplete coverage.
48 + ("9001", "حساب موقت — قلم شناسایی‌نشده بدهکار", "90", "حساب‌های موقت", "01", 500_000_000, 500_000_000, 0, None, None, None, None),
49 + ("9002", "حساب موقت — قلم شناسایی‌نشده بستانکار", "90", "حساب‌های موقت", "02", -500_000_000, 0, 500_000_000, None, None, None, None),
50 +]
51 +
52 +_DEMO_NOTES = [
53 + ("BS", "Assets", "01", "نقد و بانک"),
54 + ("BS", "Assets", "02", "دریافتنی‌های تجاری"),
55 + ("BS", "Assets", "03", "موجودی‌ها"),
56 + ("BS", "Assets", "04", "پیش‌پرداخت‌ها"),
57 + ("BS", "Assets", "05", "دارایی‌های ثابت مشهود"),
58 + ("BS", "Liabilities", "06", "پرداختنی‌های تجاری"),
59 + ("BS", "Liabilities", "07", "تسهیلات مالی"),
60 + ("BS", "Liabilities", "08", "ذخیره مالیات"),
61 + ("BS", "Equity", "09", "سرمایه"),
62 + ("BS", "Equity", "10", "سود انباشته"),
63 + ("IS", "Revenue", "11", "درآمد عملیاتی"),
64 + ("IS", "Revenue", "12", "سایر درآمدها"),
65 + ("IS", "Expenses", "13", "بهای تمام‌شده"),
66 + ("IS", "Expenses", "14", "حقوق و دستمزد"),
67 + ("IS", "Expenses", "15", "هزینه‌های اداری و تشکیلاتی"),
68 + ("IS", "Expenses", "16", "استهلاک"),
69 + ("IS", "Expenses", "17", "هزینه‌های مالی"),
70 + ("IS", "Expenses", "18", "مالیات بر درآمد"),
71 +]
72 +
73 +
74 +def _row(sheet: str, values: dict) -> tuple:
75 + return tuple(values.get(header) for header in SHEET_HEADERS[sheet])
76 +
77 +
78 +def build_demo_workbook() -> bytes:
79 + """Build the synthetic, balanced demo workbook fully in memory."""
80 + workbook = Workbook()
81 + workbook.remove(workbook.active)
82 + workbook.properties.creator = "Aram Pilot Workbench (synthetic demo)"
83 + workbook.properties.title = "SYNTHETIC DEMO — NOT REAL FINANCIAL DATA"
84 + fixed = datetime(2026, 12, 3, tzinfo=UTC)
85 + workbook.properties.created = fixed
86 + workbook.properties.modified = fixed
87 + for name, headers in SHEET_HEADERS.items():
88 + workbook.create_sheet(name).append(headers)
89 +
90 + company = {
91 + "company_code": DEMO_COMPANY_CODE,
92 + "company_name": DEMO_COMPANY_NAME,
93 + "fiscal_year": DEMO_YEAR,
94 + "currency": "IRR",
95 + "unit": "ریال (ساختگی)",
96 + "prepared_by": "Aram Demo",
97 + "status": "Draft",
98 + }
99 + workbook["Company"].append(_row("Company", company))
100 +
101 + mapping_index = 0
102 + for (code, name, general, general_name, subsidiary, closing, debit, credit,
103 + statement, section, note_number, approval) in _DEMO_ACCOUNTS:
104 + opening = closing - debit + credit
105 + source_row = 100 + int(code)
106 + workbook["Accounts"].append(_row("Accounts", {
107 + "company_code": DEMO_COMPANY_CODE,
108 + "fiscal_year": DEMO_YEAR,
109 + "general_code": general,
110 + "general_name": general_name,
111 + "subsidiary_code": subsidiary,
112 + "subsidiary_name": name,
113 + "account_full_code": code,
114 + "account_name": name,
115 + "opening": opening,
116 + "debit": debit,
117 + "credit": credit,
118 + "closing": closing,
119 + "source_row": source_row,
120 + "row_status": "Reviewed",
121 + "closing_delta": 0,
122 + }))
123 + if statement is None:
124 + continue
125 + mapping_index += 1
126 + reviewed = approval in {"Reviewed", "Approved"}
127 + workbook["Mapping"].append(_row("Mapping", {
128 + "mapping_id": f"DM{mapping_index:03d}",
129 + "company_code": DEMO_COMPANY_CODE,
130 + "fiscal_year": DEMO_YEAR,
131 + "account_full_code": code,
132 + "account_level": "Subsidiary",
133 + "general_code": general,
134 + "subsidiary_code": subsidiary,
135 + "target_statement": statement,
136 + "statement_section": section,
137 + "note_number": note_number,
138 + "mapping_version": 1,
139 + "approval_status": approval,
140 + "reviewer": DEMO_REVIEWER if reviewed else None,
141 + "review_date": DEMO_REVIEW_DATE if reviewed else None,
142 + "source": "synthetic-demo",
143 + "validation_status": "Valid" if approval == "Approved" else "Pending",
144 + }))
145 +
146 + for statement, section, note_number, title in _DEMO_NOTES:
147 + workbook["Notes"].append(_row("Notes", {
148 + "company_code": DEMO_COMPANY_CODE,
149 + "fiscal_year": DEMO_YEAR,
150 + "statement": statement,
151 + "statement_section": section,
152 + "note_number": note_number,
153 + "note_title": title,
154 + }))
155 +
156 + workbook["Guide_FA"].append(("هشدار", "همهٔ ارقام این فایل ساختگی و غیرواقعی هستند."))
157 + workbook["Lists"].append(("demo", "SYNTHETIC"))
158 +
159 + stream = BytesIO()
160 + workbook.save(stream)
161 + return stream.getvalue()
backend/src/aram_backend/pilot_editing.py new
+190
@@ -0,0 +1,190 @@
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 + )
backend/src/aram_backend/pilot_engine.py new
+762
@@ -0,0 +1,762 @@
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, strict=False))
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()
backend/src/aram_backend/pilot_store.py new
+351
@@ -0,0 +1,351 @@
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()
backend/src/aram_backend/pilot_workbook.py
+1 -1
@@ -169,7 +169,7 @@ def _finite_decimal(value: Any, issues: list[PilotIssue], sheet: str, row: int,
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))
172 + row = dict(zip(headers, values, strict=False))
173 if any(not _empty(value) for value in row.values()):
174 result.append((row_number, row))
175 return result
backend/src/aram_backend/services/__init__.py new
+6
@@ -0,0 +1,6 @@
1 +"""Service layer: import, mapping, calculation, workflow (booklet section 4).
2 +
3 +Services orchestrate the pure domain rules with persistence. They contain no
4 +financial guesswork; all money/sign/hierarchy decisions live in the domain layer
5 +and its ADRs.
6 +"""
backend/src/aram_backend/services/approval.py new
+91
@@ -0,0 +1,91 @@
1 +"""Approval gate (Phase 2, P-09, D5): ERROR controls block Draft -> Approved.
2 +
3 +Approval runs the FULL C-01..C-04 control set over the latest ledger import AND
4 +the active mappings. Mappings are always passed to the controls — C-03 (no double
5 +mapping / valid 100% split) and C-04 (unknown queue) depend on them. Any blocking
6 +ERROR refuses the transition; a clean pass transitions the year and writes a
7 +hash-chained audit entry. There is no path that approves while a control fails.
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +from dataclasses import dataclass
13 +
14 +from sqlalchemy import select
15 +from sqlalchemy.orm import Session
16 +
17 +from aram_backend.domain.controls import BalanceRow, ControlResult, MappingTarget, run_controls
18 +from aram_backend.models import FiscalYear, FiscalYearStatus, MappingRule
19 +from aram_backend.services.audit import append_entry
20 +from aram_backend.services.ledger_aggregate import latest_raw_rows
21 +
22 +
23 +class ApprovalError(ValueError):
24 + """Raised when approval is attempted on an invalid state."""
25 +
26 +
27 +@dataclass(frozen=True)
28 +class ApprovalResult:
29 + approved: bool
30 + blocking: tuple[ControlResult, ...]
31 + controls: tuple[ControlResult, ...]
32 +
33 +
34 +def _load_rows(session: Session, year_id: int) -> list[BalanceRow]:
35 + return [
36 + BalanceRow(
37 + row_number=b.source_row,
38 + account_code=b.account_full_code,
39 + opening=b.opening,
40 + debit=b.debit,
41 + credit=b.credit,
42 + closing=b.closing,
43 + )
44 + for b in latest_raw_rows(session, year_id)
45 + ]
46 +
47 +
48 +def _load_mappings(session: Session, year_id: int) -> dict[str, list[MappingTarget]]:
49 + mappings: dict[str, list[MappingTarget]] = {}
50 + for rule in session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all():
51 + mappings.setdefault(rule.account_code, []).append(
52 + MappingTarget(target=str(rule.target_note_id))
53 + )
54 + return mappings
55 +
56 +
57 +def evaluate_controls(
58 + rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]
59 +) -> list[ControlResult]:
60 + """Run every control with the mappings explicitly supplied (C-03/C-04 need them)."""
61 + return run_controls(rows, mappings)
62 +
63 +
64 +def approve_year(session: Session, year_id: int, *, actor: str = "") -> ApprovalResult:
65 + year = session.get(FiscalYear, year_id)
66 + if year is None:
67 + raise ApprovalError(f"fiscal year {year_id} does not exist")
68 + if year.status != FiscalYearStatus.DRAFT:
69 + raise ApprovalError(f"only a Draft year can be approved (current: {year.status.value})")
70 +
71 + rows = _load_rows(session, year_id)
72 + mappings = _load_mappings(session, year_id)
73 + controls = evaluate_controls(rows, mappings)
74 + blocking = tuple(r for r in controls if r.severity == "ERROR" and not r.passed)
75 + if blocking:
76 + # Hard gate: even a single ERROR blocks approval (P-09, D5).
77 + return ApprovalResult(approved=False, blocking=blocking, controls=tuple(controls))
78 +
79 + year.status = FiscalYearStatus.APPROVED
80 + append_entry(
81 + session,
82 + action="approve",
83 + actor=actor,
84 + year_id=year_id,
85 + payload={"controls": [r.code for r in controls]},
86 + )
87 + session.flush()
88 + return ApprovalResult(approved=True, blocking=(), controls=tuple(controls))
89 +
90 +
91 +__all__ = ["approve_year", "evaluate_controls", "ApprovalResult", "ApprovalError"]
backend/src/aram_backend/services/audit.py new
+75
@@ -0,0 +1,75 @@
1 +"""Hash-chained audit log (D-07, booklet §12).
2 +
3 +Each entry's chain_hash = SHA256(previous_hash || payload_hash). The first entry
4 +chains from a fixed genesis hash. ``verify_chain`` recomputes the whole chain and
5 +detects any tampering with past entries (which the append-only triggers also
6 +block at the database level).
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +import hashlib
12 +import json
13 +
14 +from sqlalchemy import select
15 +from sqlalchemy.orm import Session
16 +
17 +from aram_backend.models import AuditEntry
18 +
19 +GENESIS_HASH = "0" * 64
20 +
21 +
22 +def _payload_hash(action: str, actor: str, year_id: int | None, payload: dict[str, object]) -> str:
23 + canonical = json.dumps(
24 + {"action": action, "actor": actor, "year_id": year_id, "payload": payload},
25 + sort_keys=True,
26 + ensure_ascii=False,
27 + separators=(",", ":"),
28 + )
29 + return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
30 +
31 +
32 +def _chain_hash(previous_hash: str, payload_hash: str) -> str:
33 + return hashlib.sha256(f"{previous_hash}{payload_hash}".encode("ascii")).hexdigest()
34 +
35 +
36 +def append_entry(
37 + session: Session,
38 + *,
39 + action: str,
40 + actor: str = "",
41 + year_id: int | None = None,
42 + payload: dict[str, object] | None = None,
43 +) -> AuditEntry:
44 + """Append a new audit entry, chaining from the current head."""
45 + payload = payload or {}
46 + head = session.scalar(select(AuditEntry).order_by(AuditEntry.id.desc()).limit(1))
47 + previous_hash = head.chain_hash if head is not None else GENESIS_HASH
48 + payload_hash = _payload_hash(action, actor, year_id, payload)
49 + entry = AuditEntry(
50 + year_id=year_id,
51 + actor=actor,
52 + action=action,
53 + payload_hash=payload_hash,
54 + previous_hash=previous_hash,
55 + chain_hash=_chain_hash(previous_hash, payload_hash),
56 + )
57 + session.add(entry)
58 + session.flush()
59 + return entry
60 +
61 +
62 +def verify_chain(session: Session) -> bool:
63 + """Return True iff the entire audit chain is intact."""
64 + previous_hash = GENESIS_HASH
65 + entries = session.scalars(select(AuditEntry).order_by(AuditEntry.id.asc())).all()
66 + for entry in entries:
67 + if entry.previous_hash != previous_hash:
68 + return False
69 + if entry.chain_hash != _chain_hash(previous_hash, entry.payload_hash):
70 + return False
71 + previous_hash = entry.chain_hash
72 + return True
73 +
74 +
75 +__all__ = ["append_entry", "verify_chain", "GENESIS_HASH"]
backend/src/aram_backend/services/backup.py new
+143
@@ -0,0 +1,143 @@
1 +"""Local backup and integrity verification (Phase 7, booklet §7/§12).
2 +
3 +Creates a consistent snapshot of the SQLite database (sqlite3 online backup API,
4 +safe while the app is running), copies the content-addressed source store, and
5 +writes a manifest recording the SHA-256 of the database and every source file plus
6 +the audit-chain verification result. ``verify_backup`` recomputes every hash and
7 +re-checks the audit chain so a backup is provably intact before restore. Offline
8 +desktop only: no runtime network; PostgreSQL deployments use native pg_dump.
9 +"""
10 +
11 +from __future__ import annotations
12 +
13 +import hashlib
14 +import json
15 +import shutil
16 +import sqlite3
17 +from datetime import UTC, datetime
18 +from pathlib import Path
19 +from typing import Any, cast
20 +
21 +from sqlalchemy.engine import Engine
22 +from sqlalchemy.orm import Session
23 +
24 +from aram_backend.services.audit import verify_chain
25 +
26 +
27 +class BackupError(ValueError):
28 + """Raised when a backup cannot be created or verified safely."""
29 +
30 +
31 +def _sha256_file(path: Path) -> str:
32 + digest = hashlib.sha256()
33 + with path.open("rb") as handle:
34 + for chunk in iter(lambda: handle.read(1024 * 1024), b""):
35 + digest.update(chunk)
36 + return digest.hexdigest()
37 +
38 +
39 +def _database_path(session: Session) -> Path:
40 + url = cast(Engine, session.get_bind()).url
41 + if url.get_backend_name() != "sqlite":
42 + raise BackupError("local backup supports SQLite only; use pg_dump for PostgreSQL")
43 + database = url.database
44 + if not database or database == ":memory:":
45 + raise BackupError("cannot back up an in-memory database")
46 + return Path(database)
47 +
48 +
49 +def create_backup(session: Session, dest: str | Path, *, store_root: str | Path) -> dict[str, Any]:
50 + """Write a consistent backup directory and return its manifest."""
51 + dest = Path(dest)
52 + if dest.exists() and any(dest.iterdir()):
53 + raise BackupError(f"backup destination '{dest}' is not empty")
54 + dest.mkdir(parents=True, exist_ok=True)
55 +
56 + db_path = _database_path(session)
57 + backup_db = dest / "aram.db"
58 + # Online backup API: a consistent snapshot even with concurrent writers.
59 + source_conn = sqlite3.connect(str(db_path))
60 + try:
61 + target_conn = sqlite3.connect(str(backup_db))
62 + try:
63 + source_conn.backup(target_conn)
64 + finally:
65 + target_conn.close()
66 + finally:
67 + source_conn.close()
68 +
69 + store_src = Path(store_root)
70 + store_dest = dest / "source_store"
71 + source_hashes: dict[str, str] = {}
72 + if store_src.exists():
73 + shutil.copytree(store_src, store_dest)
74 + for file in sorted(store_dest.rglob("*")):
75 + if file.is_file():
76 + rel = file.relative_to(store_dest).as_posix()
77 + source_hashes[rel] = _sha256_file(file)
78 + else:
79 + store_dest.mkdir()
80 +
81 + chain_ok = verify_chain(session)
82 + manifest: dict[str, Any] = {
83 + "format": "aram-backup-1",
84 + "created_at": datetime.now(UTC).isoformat(),
85 + "database_sha256": _sha256_file(backup_db),
86 + "source_store_sha256": source_hashes,
87 + "audit_chain_valid": chain_ok,
88 + }
89 + (dest / "manifest.json").write_text(
90 + json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8"
91 + )
92 + if not chain_ok:
93 + raise BackupError("audit chain is not intact; backup refused")
94 + return manifest
95 +
96 +
97 +def verify_backup(backup_dir: str | Path) -> dict[str, Any]:
98 + """Recompute every recorded hash and re-check the audit chain in the snapshot."""
99 + backup_dir = Path(backup_dir)
100 + manifest_path = backup_dir / "manifest.json"
101 + if not manifest_path.exists():
102 + raise BackupError("manifest.json is missing")
103 + manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
104 +
105 + db_path = backup_dir / "aram.db"
106 + if not db_path.exists():
107 + raise BackupError("aram.db is missing from the backup")
108 + if _sha256_file(db_path) != manifest.get("database_sha256"):
109 + raise BackupError("database hash mismatch; backup is corrupt")
110 +
111 + store_dest = backup_dir / "source_store"
112 + recorded: dict[str, str] = manifest.get("source_store_sha256", {})
113 + for rel, expected in recorded.items():
114 + file = store_dest / rel
115 + if not file.exists() or _sha256_file(file) != expected:
116 + raise BackupError(f"source file '{rel}' is missing or corrupt")
117 +
118 + # Re-verify the audit chain directly inside the backed-up database.
119 + conn = sqlite3.connect(str(db_path))
120 + try:
121 + rows = conn.execute(
122 + "SELECT previous_hash, payload_hash, chain_hash FROM audit_entries ORDER BY id ASC"
123 + ).fetchall()
124 + finally:
125 + conn.close()
126 + previous = "0" * 64
127 + for prev_hash, payload_hash, chain_hash in rows:
128 + if prev_hash != previous:
129 + raise BackupError("audit chain break detected in backup")
130 + expected = hashlib.sha256(f"{previous}{payload_hash}".encode("ascii")).hexdigest()
131 + if chain_hash != expected:
132 + raise BackupError("audit chain hash mismatch in backup")
133 + previous = chain_hash
134 +
135 + return {
136 + "valid": True,
137 + "database_sha256": manifest["database_sha256"],
138 + "source_files": len(recorded),
139 + "audit_entries": len(rows),
140 + }
141 +
142 +
143 +__all__ = ["BackupError", "create_backup", "verify_backup"]
backend/src/aram_backend/services/golden.py new
+157
@@ -0,0 +1,157 @@
1 +"""Golden comparison against official statements (Phase 4, ADR-021, OD-08).
2 +
3 +The canonical ledger embeds the authoritative mapping (column 0 = note number)
4 +and the statement balance in rial (column 25). Summing by note and rounding to
5 +million rial (half-up, ADR-012) reproduces the official balance sheet exactly.
6 +Every non-match is surfaced as a discrepancy, never silently corrected (P-01).
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +import json
12 +import re
13 +from collections import defaultdict
14 +from dataclasses import asdict, dataclass
15 +from decimal import Decimal
16 +from pathlib import Path
17 +
18 +from openpyxl import load_workbook
19 +
20 +from aram_backend.domain.money import round_half_up
21 +
22 +STATEMENT_SHEETS = {
23 + "BS": "وضعيت مالي",
24 + "IS": "سودوزيان",
25 + "EQ": "حقوق مالكانه",
26 + "CF": "جريان هاي نقدي",
27 +}
28 +_MILLION = Decimal(1_000_000)
29 +_NOTE_RE = re.compile(r"^\d+(?:-\d+)?$")
30 +_UNMAPPED = {"", "-", "#N/A", "None"}
31 +
32 +
33 +@dataclass(frozen=True)
34 +class NoteComparison:
35 + statement: str
36 + note: str
37 + source_rial: str
38 + source_million_rounded: int
39 + official_million: int
40 + delta: int
41 + match: bool
42 +
43 +
44 +def aggregate_source_by_note(source_path: str | Path, year: int) -> dict[str, Decimal]:
45 + """Sum the source statement balance by note number, locating columns by header.
46 +
47 + Column positions differ between ledger vintages (e.g. 1403 vs 1404), so the
48 + note / year / statement-balance columns are resolved by header name, never by
49 + a fixed index. This keeps the comparison generic across source layouts.
50 + """
51 + wb = load_workbook(source_path, read_only=True, data_only=True, keep_links=False)
52 + try:
53 + ws = wb["Source"]
54 + rows = ws.iter_rows(values_only=True)
55 + next(rows) # title row
56 + header = next(rows)
57 + idx = {str(h).strip(): i for i, h in enumerate(header) if h is not None}
58 + note_i = idx.get("یادداشت کل")
59 + year_i = idx.get("year")
60 + balance_i = idx.get("مانده صورت مالی")
61 + if note_i is None or year_i is None or balance_i is None:
62 + raise ValueError("source ledger missing note/year/statement-balance headers")
63 + sums: dict[str, Decimal] = defaultdict(lambda: Decimal(0))
64 + for vals in rows:
65 + if not any(v is not None for v in vals):
66 + continue
67 + if str(vals[year_i]) != str(year):
68 + continue
69 + note = str(vals[note_i]).strip() if vals[note_i] is not None else ""
70 + if note in _UNMAPPED:
71 + continue
72 + balance = vals[balance_i]
73 + if balance is None:
74 + continue
75 + sums[note] += Decimal(str(balance))
76 + return dict(sums)
77 + finally:
78 + wb.close()
79 +
80 +
81 +def read_official_notes(official_path: str | Path, sheet: str, year: int) -> dict[str, int]:
82 + """Extract note -> amount (million rial) from an official statement sheet."""
83 + wb = load_workbook(official_path, read_only=True, data_only=True, keep_links=False)
84 + try:
85 + if sheet not in wb.sheetnames:
86 + return {}
87 + rows = list(wb[sheet].iter_rows(values_only=True))
88 + amount_col = 5
89 + for row in rows[:10]:
90 + for i, cell in enumerate(row):
91 + if cell is not None and str(year) in str(cell):
92 + amount_col = i
93 + break
94 + notes: dict[str, int] = {}
95 + for row in rows:
96 + note = None
97 + for i in (2, 3):
98 + if i < len(row) and row[i] is not None and _NOTE_RE.fullmatch(str(row[i]).strip()):
99 + note = str(row[i]).strip()
100 + break
101 + if (
102 + note is not None
103 + and amount_col < len(row)
104 + and isinstance(row[amount_col], (int, float))
105 + ):
106 + notes[note] = int(row[amount_col])
107 + return notes
108 + finally:
109 + wb.close()
110 +
111 +
112 +def compare_year(
113 + source_path: str | Path, official_path: str | Path, year: int
114 +) -> list[NoteComparison]:
115 + source = aggregate_source_by_note(source_path, year)
116 + comparisons: list[NoteComparison] = []
117 + for statement, sheet in STATEMENT_SHEETS.items():
118 + official = read_official_notes(official_path, sheet, year)
119 + for note, official_million in sorted(official.items()):
120 + src_rial = source.get(note, Decimal(0))
121 + rounded = int(round_half_up(src_rial / _MILLION, 0))
122 + delta = rounded - official_million
123 + comparisons.append(
124 + NoteComparison(
125 + statement=statement,
126 + note=note,
127 + source_rial=str(src_rial),
128 + source_million_rounded=rounded,
129 + official_million=official_million,
130 + delta=delta,
131 + match=delta == 0,
132 + )
133 + )
134 + return comparisons
135 +
136 +
137 +def write_discrepancies(comparisons: list[NoteComparison], out_path: str | Path) -> dict[str, int]:
138 + discrepancies = [asdict(c) for c in comparisons if not c.match]
139 + matched = sum(1 for c in comparisons if c.match)
140 + summary: dict[str, int] = {
141 + "total": len(comparisons),
142 + "matched": matched,
143 + "discrepancies": len(discrepancies),
144 + }
145 + payload: dict[str, object] = {"summary": summary, "discrepancies": discrepancies}
146 + Path(out_path).write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
147 + return summary
148 +
149 +
150 +__all__ = [
151 + "aggregate_source_by_note",
152 + "read_official_notes",
153 + "compare_year",
154 + "write_discrepancies",
155 + "NoteComparison",
156 + "STATEMENT_SHEETS",
157 +]
backend/src/aram_backend/services/ledger_aggregate.py new
+83
@@ -0,0 +1,83 @@
1 +"""Account-level aggregation over raw ledger rows (compute layer, D3/P-01).
2 +
3 +Raw LedgerBalance rows are stored one-per-source-row (never collapsed on import).
4 +Account totals are derived here, in the compute layer, by exact Decimal summation
5 +of the latest import version. This keeps drill-down intact while giving the
6 +statement/preflight/mapping services the account-level figures they need.
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +from dataclasses import dataclass
12 +from decimal import Decimal
13 +
14 +from sqlalchemy import func, select
15 +from sqlalchemy.orm import Session
16 +
17 +from aram_backend.models import LedgerBalance
18 +
19 +_ZERO = Decimal(0)
20 +
21 +
22 +@dataclass(frozen=True)
23 +class AccountTotal:
24 + account_full_code: str
25 + account_name: str
26 + opening: Decimal
27 + debit: Decimal
28 + credit: Decimal
29 + closing: Decimal
30 + row_count: int
31 + first_source_row: int
32 +
33 +
34 +def latest_import_version(session: Session, year_id: int) -> int | None:
35 + return session.scalar(
36 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
37 + )
38 +
39 +
40 +def latest_raw_rows(session: Session, year_id: int) -> list[LedgerBalance]:
41 + version = latest_import_version(session, year_id)
42 + if version is None:
43 + return []
44 + return list(
45 + session.scalars(
46 + select(LedgerBalance)
47 + .where(LedgerBalance.year_id == year_id, LedgerBalance.import_version == version)
48 + .order_by(LedgerBalance.source_row)
49 + ).all()
50 + )
51 +
52 +
53 +def aggregate_by_account(session: Session, year_id: int) -> dict[str, AccountTotal]:
54 + """Sum raw rows per canonical account (exact Decimal, no rounding)."""
55 + totals: dict[str, AccountTotal] = {}
56 + for row in latest_raw_rows(session, year_id):
57 + existing = totals.get(row.account_full_code)
58 + if existing is None:
59 + totals[row.account_full_code] = AccountTotal(
60 + account_full_code=row.account_full_code,
61 + account_name=row.account_name,
62 + opening=row.opening,
63 + debit=row.debit,
64 + credit=row.credit,
65 + closing=row.closing,
66 + row_count=1,
67 + first_source_row=row.source_row,
68 + )
69 + else:
70 + totals[row.account_full_code] = AccountTotal(
71 + account_full_code=existing.account_full_code,
72 + account_name=existing.account_name,
73 + opening=existing.opening + row.opening,
74 + debit=existing.debit + row.debit,
75 + credit=existing.credit + row.credit,
76 + closing=existing.closing + row.closing,
77 + row_count=existing.row_count + 1,
78 + first_source_row=min(existing.first_source_row, row.source_row),
79 + )
80 + return totals
81 +
82 +
83 +__all__ = ["AccountTotal", "aggregate_by_account", "latest_import_version", "latest_raw_rows"]
backend/src/aram_backend/services/ledger_import.py new
+78
@@ -0,0 +1,78 @@
1 +"""Persist parsed ledger rows as RAW LedgerBalance records (D-01, D3, P-01).
2 +
3 +One LedgerBalance row per source ledger row, preserving ``source_row`` so every
4 +figure is traceable to its exact origin (file/sheet/row). **No aggregation happens
5 +here** — aggregation is a compute-layer concern (see ``ledger_aggregate`` and the
6 +statement/preflight services). This preserves drill-down (D3) and the sacred-source
7 +principle (P-01): raw rows are never collapsed or rewritten on the way in.
8 +
9 +The canonical account identity is ``general + subsidiary`` (ADR-014). The caller
10 +owns the transaction.
11 +"""
12 +
13 +from __future__ import annotations
14 +
15 +from collections.abc import Iterable
16 +
17 +from sqlalchemy.orm import Session
18 +
19 +from aram_backend.domain.hierarchy import canonical_full_code, ledger_to_pilot
20 +from aram_backend.ledger_parser import LedgerRecord
21 +from aram_backend.models import LedgerBalance
22 +
23 +
24 +def import_ledger_balances(
25 + session: Session,
26 + *,
27 + year_id: int,
28 + source_document_id: int,
29 + records: Iterable[LedgerRecord],
30 + source_sheet: str = "Source",
31 + import_version: int = 1,
32 +) -> int:
33 + """Persist each parsed record as a distinct raw row; return the row count.
34 +
35 + Raises on a uniqueness conflict (re-importing the same source rows under the
36 + same import version). A new import for a Draft year uses a new
37 + ``import_version``; prior versions remain immutable snapshots.
38 + """
39 + count = 0
40 + for record in records:
41 + levels = ledger_to_pilot(
42 + kol=record.general_code,
43 + hesab=record.account_code,
44 + t1=record.t1_code,
45 + t2=record.t2_code,
46 + t3=record.t3_code,
47 + t4=record.t4_code,
48 + row=record.row_number,
49 + )
50 + session.add(
51 + LedgerBalance(
52 + year_id=year_id,
53 + source_document_id=source_document_id,
54 + source_sheet=source_sheet,
55 + source_row=record.row_number,
56 + import_version=import_version,
57 + account_full_code=canonical_full_code(levels),
58 + general_code=levels.general_code,
59 + subsidiary_code=levels.subsidiary_code,
60 + detail1_code=levels.detail1_code,
61 + detail2_code=levels.detail2_code,
62 + detail3_code=levels.detail3_code,
63 + detail4_code=levels.detail4_code,
64 + account_name=record.account_name,
65 + opening=record.opening,
66 + debit=record.debit,
67 + credit=record.credit,
68 + closing=record.closing,
69 + statement_balance=record.statement_balance,
70 + entry_type=record.entry_type,
71 + )
72 + )
73 + count += 1
74 + session.flush()
75 + return count
76 +
77 +
78 +__all__ = ["import_ledger_balances"]
backend/src/aram_backend/services/mapping_io.py new
+162
@@ -0,0 +1,162 @@
1 +"""Comprehensive mapping Excel import/export (Phase 2, booklet §15).
2 +
3 +Round-trips account->note mappings through a governed workbook. Codes are text
4 +(leading zeros preserved). Import is fail-closed: invalid rows are reported and
5 +nothing partial is committed for them. Export joins mappings with note metadata
6 +and the imported account names.
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +from dataclasses import dataclass, field
12 +from io import BytesIO
13 +
14 +from openpyxl import Workbook, load_workbook
15 +from sqlalchemy import select
16 +from sqlalchemy.orm import Session
17 +
18 +from aram_backend.domain.normalization import normalize_code
19 +from aram_backend.models import LedgerBalance, MappingRule, NoteDefinition
20 +
21 +_HEADERS = (
22 + "account_code",
23 + "account_name",
24 + "target_note_number",
25 + "statement",
26 + "section",
27 + "mapping_type",
28 +)
29 +_VALID_STATEMENTS = {"BS", "IS", "CF", "EQ"}
30 +
31 +
32 +class MappingImportError(ValueError):
33 + """Raised when a mapping workbook cannot be imported safely."""
34 +
35 +
36 +@dataclass
37 +class MappingImportResult:
38 + created: int = 0
39 + notes_created: int = 0
40 + errors: list[str] = field(default_factory=list)
41 +
42 +
43 +def _latest_note(session: Session, year_id: int, note_number: str) -> NoteDefinition | None:
44 + return session.scalar(
45 + select(NoteDefinition)
46 + .where(NoteDefinition.year_id == year_id, NoteDefinition.note_number == note_number)
47 + .order_by(NoteDefinition.version.desc())
48 + .limit(1)
49 + )
50 +
51 +
52 +def export_mappings_workbook(session: Session, year_id: int) -> bytes:
53 + rules = session.scalars(
54 + select(MappingRule).where(MappingRule.year_id == year_id).order_by(MappingRule.account_code)
55 + ).all()
56 + names: dict[str, str] = {}
57 + for balance in session.scalars(
58 + select(LedgerBalance).where(LedgerBalance.year_id == year_id)
59 + ).all():
60 + names.setdefault(balance.account_full_code, balance.account_name)
61 +
62 + wb = Workbook()
63 + ws = wb.active
64 + ws.title = "Mappings"
65 + ws.append(list(_HEADERS))
66 + for rule in rules:
67 + note = rule.target_note
68 + config = note.configuration_json if note else {}
69 + ws.append(
70 + [
71 + rule.account_code,
72 + names.get(rule.account_code, ""),
73 + note.note_number if note else "",
74 + config.get("statement", ""),
75 + config.get("section", ""),
76 + rule.mapping_type,
77 + ]
78 + )
79 + buf = BytesIO()
80 + wb.save(buf)
81 + wb.close()
82 + return buf.getvalue()
83 +
84 +
85 +def import_mappings_workbook(session: Session, year_id: int, content: bytes) -> MappingImportResult:
86 + wb = load_workbook(BytesIO(content), read_only=True, data_only=True, keep_links=False)
87 + try:
88 + ws = wb["Mappings"] if "Mappings" in wb.sheetnames else wb.active
89 + rows = ws.iter_rows(values_only=True)
90 + header = next(rows, None)
91 + if header is None:
92 + raise MappingImportError("mapping workbook is empty")
93 + idx = {str(v).strip(): i for i, v in enumerate(header) if v is not None}
94 + missing = [h for h in _HEADERS if h not in idx and h != "account_name"]
95 + if missing:
96 + raise MappingImportError(f"mapping workbook missing columns: {missing}")
97 +
98 + result = MappingImportResult()
99 + for row_number, vals in enumerate(rows, start=2):
100 + if vals is None or not any(v is not None and str(v).strip() for v in vals):
101 + continue
102 + try:
103 + code = normalize_code(
104 + vals[idx["account_code"]], row=row_number, field="account_code"
105 + )
106 + note_number = str(vals[idx["target_note_number"]]).strip()
107 + statement = str(vals[idx["statement"]]).strip().upper()
108 + section = str(vals[idx["section"]]).strip()
109 + mapping_type = str(vals[idx["mapping_type"]]).strip() or "closing"
110 + if not note_number:
111 + raise ValueError("target_note_number is required")
112 + if statement not in _VALID_STATEMENTS:
113 + raise ValueError(f"invalid statement '{statement}'")
114 + if not section:
115 + raise ValueError("section is required")
116 + except (ValueError, KeyError) as exc:
117 + result.errors.append(f"row {row_number}: {exc}")
118 + continue
119 +
120 + note = _latest_note(session, year_id, note_number)
121 + if note is None:
122 + note = NoteDefinition(
123 + year_id=year_id,
124 + note_number=note_number,
125 + title=note_number,
126 + configuration_json={"statement": statement, "section": section},
127 + )
128 + session.add(note)
129 + session.flush()
130 + result.notes_created += 1
131 +
132 + existing = session.scalar(
133 + select(MappingRule).where(
134 + MappingRule.year_id == year_id,
135 + MappingRule.account_code == code,
136 + MappingRule.target_note_id == note.id,
137 + )
138 + )
139 + if existing is not None:
140 + continue
141 + session.add(
142 + MappingRule(
143 + year_id=year_id,
144 + rule_key=f"{code}->{note.id}",
145 + account_code=code,
146 + target_note_id=note.id,
147 + mapping_type=mapping_type,
148 + )
149 + )
150 + result.created += 1
151 + session.flush()
152 + return result
153 + finally:
154 + wb.close()
155 +
156 +
157 +__all__ = [
158 + "export_mappings_workbook",
159 + "import_mappings_workbook",
160 + "MappingImportResult",
161 + "MappingImportError",
162 +]
backend/src/aram_backend/services/mapping_workflow.py new
+127
@@ -0,0 +1,127 @@
1 +"""Unknown-account queue and mapping carry-forward (Phase 2, D1/D4).
2 +
3 +The queue lists active accounts that have no mapping (C-04); resolving them is
4 +mandatory before approval. Carry-forward copies a prior year's notes + mappings
5 +into a new Draft year so 1403 -> 1404 continuity does not start from scratch.
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +from dataclasses import dataclass
11 +from decimal import Decimal
12 +
13 +from sqlalchemy import select
14 +from sqlalchemy.orm import Session
15 +
16 +from aram_backend.models import (
17 + FiscalYear,
18 + FiscalYearStatus,
19 + MappingRule,
20 + NoteDefinition,
21 +)
22 +from aram_backend.services.ledger_aggregate import aggregate_by_account
23 +
24 +_ZERO = Decimal(0)
25 +
26 +
27 +class CarryForwardError(ValueError):
28 + """Raised when carry-forward is attempted on an invalid state."""
29 +
30 +
31 +def unknown_accounts(session: Session, year_id: int) -> list[dict[str, object]]:
32 + """Active accounts with no mapping, aggregated from raw rows (compute layer)."""
33 + mapped = {
34 + r.account_code
35 + for r in session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all()
36 + }
37 + queue = []
38 + for code, total in aggregate_by_account(session, year_id).items():
39 + if code in mapped:
40 + continue
41 + if any(getattr(total, k) != _ZERO for k in ("opening", "debit", "credit", "closing")):
42 + queue.append(
43 + {
44 + "account_full_code": code,
45 + "account_name": total.account_name,
46 + "closing": str(total.closing),
47 + "source_row": total.first_source_row,
48 + "row_count": total.row_count,
49 + }
50 + )
51 + queue.sort(key=lambda item: str(item["account_full_code"]))
52 + return queue
53 +
54 +
55 +@dataclass(frozen=True)
56 +class CarryForwardResult:
57 + notes_created: int
58 + mappings_created: int
59 +
60 +
61 +def carry_forward_mappings(
62 + session: Session, from_year_id: int, to_year_id: int
63 +) -> CarryForwardResult:
64 + target = session.get(FiscalYear, to_year_id)
65 + if target is None:
66 + raise CarryForwardError(f"target year {to_year_id} does not exist")
67 + if target.status != FiscalYearStatus.DRAFT:
68 + raise CarryForwardError("carry-forward target must be a Draft year")
69 +
70 + source_notes = session.scalars(
71 + select(NoteDefinition).where(NoteDefinition.year_id == from_year_id)
72 + ).all()
73 + note_map: dict[int, int] = {}
74 + notes_created = 0
75 + for note in source_notes:
76 + existing = session.scalar(
77 + select(NoteDefinition)
78 + .where(
79 + NoteDefinition.year_id == to_year_id, NoteDefinition.note_number == note.note_number
80 + )
81 + .order_by(NoteDefinition.version.desc())
82 + .limit(1)
83 + )
84 + if existing is None:
85 + existing = NoteDefinition(
86 + year_id=to_year_id,
87 + note_number=note.note_number,
88 + title=note.title,
89 + configuration_json=dict(note.configuration_json),
90 + )
91 + session.add(existing)
92 + session.flush()
93 + notes_created += 1
94 + note_map[note.id] = existing.id
95 +
96 + mappings_created = 0
97 + source_rules = session.scalars(
98 + select(MappingRule).where(MappingRule.year_id == from_year_id)
99 + ).all()
100 + for rule in source_rules:
101 + target_note_id = note_map.get(rule.target_note_id)
102 + if target_note_id is None:
103 + continue
104 + existing_rule = session.scalar(
105 + select(MappingRule).where(
106 + MappingRule.year_id == to_year_id,
107 + MappingRule.account_code == rule.account_code,
108 + MappingRule.target_note_id == target_note_id,
109 + )
110 + )
111 + if existing_rule is not None:
112 + continue
113 + session.add(
114 + MappingRule(
115 + year_id=to_year_id,
116 + rule_key=f"{rule.account_code}->{target_note_id}",
117 + account_code=rule.account_code,
118 + target_note_id=target_note_id,
119 + mapping_type=rule.mapping_type,
120 + )
121 + )
122 + mappings_created += 1
123 + session.flush()
124 + return CarryForwardResult(notes_created=notes_created, mappings_created=mappings_created)
125 +
126 +
127 +__all__ = ["unknown_accounts", "carry_forward_mappings", "CarryForwardResult", "CarryForwardError"]
backend/src/aram_backend/services/note_engine.py new
+177
@@ -0,0 +1,177 @@
1 +"""Note engine (Phase 3, ADR-020): evaluate disclosure-row formulas safely.
2 +
3 +Computes note row values on demand from the latest ledger import using the safe
4 +formula grammar (no eval). Rows may reference earlier rows and other notes; cross
5 +note references are cycle-detected. Each row reports the accounts it references
6 +for drill-down.
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +from decimal import Decimal
12 +from typing import Any, cast
13 +
14 +from sqlalchemy import func, select
15 +from sqlalchemy.orm import Session
16 +
17 +from aram_backend.domain.formula import (
18 + Binary,
19 + Call,
20 + FormulaError,
21 + Str,
22 + Unary,
23 + eval_formula,
24 + parse_formula,
25 +)
26 +from aram_backend.models import LedgerBalance, NoteDefinition
27 +
28 +_ZERO = Decimal(0)
29 +_FIELDS = {"opening", "debit", "credit", "closing"}
30 +
31 +
32 +class NoteEngineError(ValueError):
33 + """Raised when a note cannot be evaluated."""
34 +
35 +
36 +def _balances(session: Session, year_id: int) -> dict[str, LedgerBalance]:
37 + version = session.scalar(
38 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
39 + )
40 + if version is None:
41 + return {}
42 + rows = session.scalars(
43 + select(LedgerBalance).where(
44 + LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
45 + )
46 + ).all()
47 + return {b.account_full_code: b for b in rows}
48 +
49 +
50 +def _referenced_accounts(node: object) -> set[str]:
51 + found: set[str] = set()
52 + if isinstance(node, Call):
53 + if node.name == "acct" and node.args and isinstance(node.args[0], Str):
54 + found.add(node.args[0].value)
55 + for arg in node.args:
56 + found |= _referenced_accounts(arg)
57 + elif isinstance(node, Binary):
58 + found |= _referenced_accounts(node.left) | _referenced_accounts(node.right)
59 + elif isinstance(node, Unary):
60 + found |= _referenced_accounts(node.operand)
61 + return found
62 +
63 +
64 +def evaluate_note(
65 + session: Session,
66 + note_id: int,
67 + *,
68 + _stack: tuple[int, ...] = (),
69 + _cache: dict[int, dict[str, object]] | None = None,
70 +) -> dict[str, object]:
71 + if _cache is not None and note_id in _cache:
72 + return _cache[note_id]
73 + if note_id in _stack:
74 + raise NoteEngineError(f"circular note reference involving note {note_id}")
75 + note = session.get(NoteDefinition, note_id)
76 + if note is None:
77 + raise NoteEngineError(f"note {note_id} does not exist")
78 +
79 + balances = _balances(session, note.year_id)
80 + rows = sorted(note.rows, key=lambda r: r.row_order)
81 + values: dict[int, Decimal] = {}
82 + stack = _stack + (note_id,)
83 + cache: dict[int, dict[str, object]] = _cache if _cache is not None else {}
84 +
85 + def _other_note_row(note_number: str, row_order: int) -> Decimal:
86 + other = session.scalar(
87 + select(NoteDefinition)
88 + .where(
89 + NoteDefinition.year_id == note.year_id, NoteDefinition.note_number == note_number
90 + )
91 + .order_by(NoteDefinition.version.desc())
92 + .limit(1)
93 + )
94 + if other is None:
95 + raise FormulaError(f"note '{note_number}' not found")
96 + result = evaluate_note(session, other.id, _stack=stack, _cache=cache)
97 + for row in cast(list[dict[str, object]], result["rows"]):
98 + if row["row_order"] == row_order:
99 + return Decimal(str(row["value"]))
100 + raise FormulaError(f"note '{note_number}' has no row {row_order}")
101 +
102 + def resolver(name: str, args: tuple[Any, ...]) -> Decimal:
103 + if name == "acct":
104 + if not args or not isinstance(args[0], str):
105 + raise FormulaError("acct() requires an account code string")
106 + field = args[1] if len(args) > 1 else "closing"
107 + if field not in _FIELDS:
108 + raise FormulaError(f"unknown account field '{field}'")
109 + balance = balances.get(args[0])
110 + if balance is None:
111 + raise FormulaError(f"account '{args[0]}' not found in the latest import")
112 + return cast(Decimal, getattr(balance, field))
113 + if name == "row":
114 + if not args:
115 + raise FormulaError("row() requires a row order")
116 + order = int(args[0])
117 + if order not in values:
118 + raise FormulaError(f"row {order} is not an earlier computed row")
119 + return values[order]
120 + if name == "note":
121 + if len(args) < 2 or not isinstance(args[0], str):
122 + raise FormulaError("note() requires a note number and row order")
123 + return _other_note_row(args[0], int(args[1]))
124 + if name == "sum":
125 + return sum((Decimal(a) for a in args), _ZERO)
126 + if name == "abs":
127 + if len(args) != 1:
128 + raise FormulaError("abs() requires one argument")
129 + return abs(Decimal(args[0]))
130 + raise FormulaError(f"unknown function '{name}'")
131 +
132 + out_rows = []
133 + for row in rows:
134 + referenced: set[str] = set()
135 + if row.formula_logic:
136 + try:
137 + ast = parse_formula(row.formula_logic)
138 + referenced = _referenced_accounts(ast)
139 + value = eval_formula(row.formula_logic, resolver)
140 + except FormulaError as exc:
141 + raise NoteEngineError(
142 + f"note {note.note_number} row {row.row_order}: {exc}"
143 + ) from exc
144 + else:
145 + value = _ZERO
146 + values[row.row_order] = value
147 + out_rows.append(
148 + {
149 + "row_order": row.row_order,
150 + "label": row.label,
151 + "formula": row.formula_logic,
152 + "value": str(value),
153 + "accounts_referenced": sorted(referenced),
154 + }
155 + )
156 +
157 + result = {
158 + "note_id": note.id,
159 + "note_number": note.note_number,
160 + "title": note.title,
161 + "rows": out_rows,
162 + }
163 + cache[note_id] = result
164 + return result
165 +
166 +
167 +def evaluate_year_notes(session: Session, year_id: int) -> list[dict[str, object]]:
168 + notes = session.scalars(
169 + select(NoteDefinition)
170 + .where(NoteDefinition.year_id == year_id)
171 + .order_by(NoteDefinition.note_number)
172 + ).all()
173 + cache: dict[int, dict[str, object]] = {}
174 + return [evaluate_note(session, note.id, _cache=cache) for note in notes]
175 +
176 +
177 +__all__ = ["evaluate_note", "evaluate_year_notes", "NoteEngineError"]
backend/src/aram_backend/services/preflight.py new
+96
@@ -0,0 +1,96 @@
1 +"""Ingestion preflight: run blocking controls C-01..C-04 (D-02, booklet §7).
2 +
3 +The controls are evaluated against the parsed ledger rows and the active mapping
4 +rules *before* a fiscal year can be approved. ERROR results block approval
5 +(P-09); they are surfaced, never silently dropped. At ingestion time no mappings
6 +exist yet, so C-03/C-04 report the unknown-account queue — exactly the accounts
7 +that must be mapped in Phase 2 before approval.
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +from collections.abc import Iterable
13 +from dataclasses import dataclass
14 +from decimal import Decimal
15 +
16 +from sqlalchemy import select
17 +from sqlalchemy.orm import Session
18 +
19 +from aram_backend.domain.controls import BalanceRow, ControlResult, MappingTarget, run_controls
20 +from aram_backend.domain.hierarchy import AccountLevels, canonical_full_code
21 +from aram_backend.ledger_parser import LedgerRecord
22 +from aram_backend.models import MappingRule
23 +
24 +
25 +@dataclass(frozen=True)
26 +class PreflightReport:
27 + results: tuple[ControlResult, ...]
28 +
29 + @property
30 + def blocking(self) -> tuple[ControlResult, ...]:
31 + return tuple(r for r in self.results if r.severity == "ERROR" and not r.passed)
32 +
33 + @property
34 + def can_approve(self) -> bool:
35 + return not self.blocking
36 +
37 + @property
38 + def unknown_accounts(self) -> tuple[str, ...]:
39 + for r in self.results:
40 + if r.code == "C-04":
41 + return r.affected
42 + return ()
43 +
44 +
45 +def _to_balance_rows(records: Iterable[LedgerRecord]) -> list[BalanceRow]:
46 + rows: list[BalanceRow] = []
47 + for rec in records:
48 + code = canonical_full_code(
49 + AccountLevels(general_code=rec.general_code or "", subsidiary_code=rec.account_code)
50 + )
51 + rows.append(
52 + BalanceRow(
53 + row_number=rec.row_number,
54 + account_code=code,
55 + opening=rec.opening,
56 + debit=rec.debit,
57 + credit=rec.credit,
58 + closing=rec.closing,
59 + )
60 + )
61 + return rows
62 +
63 +
64 +def _active_mappings(session: Session, year_id: int) -> dict[str, list[MappingTarget]]:
65 + rules = session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all()
66 + mappings: dict[str, list[MappingTarget]] = {}
67 + for rule in rules:
68 + mappings.setdefault(rule.account_code, []).append(
69 + MappingTarget(target=str(rule.target_note_id), weight=Decimal(100))
70 + )
71 + return mappings
72 +
73 +
74 +def run_preflight(
75 + records: Iterable[LedgerRecord],
76 + *,
77 + session: Session | None = None,
78 + year_id: int | None = None,
79 + mappings: dict[str, list[MappingTarget]] | None = None,
80 +) -> PreflightReport:
81 + """Evaluate C-01..C-04 over parsed records.
82 +
83 + ``mappings`` may be supplied directly (pure/test path) or loaded from the
84 + year's active MappingRule rows when ``session`` and ``year_id`` are given.
85 + """
86 + rows = _to_balance_rows(records)
87 + if mappings is None:
88 + mappings = (
89 + _active_mappings(session, year_id)
90 + if session is not None and year_id is not None
91 + else {}
92 + )
93 + return PreflightReport(results=tuple(run_controls(rows, mappings)))
94 +
95 +
96 +__all__ = ["PreflightReport", "run_preflight"]
backend/src/aram_backend/services/reopen.py new
+116
@@ -0,0 +1,116 @@
1 +"""Controlled reopen and lock workflow (Phase 7, D-07, ADR-016).
2 +
3 +A LOCKED year is immutable. Reopening it requires an approved ``ReopenRequest``;
4 +the ORM guard and the DB trigger both enforce this, so there is no bypass path.
5 +Reopening transitions LOCKED -> APPROVED (never edits locked rows in place); a
6 +subsequent build versions the output. Locking transitions APPROVED -> LOCKED.
7 +Every step writes a hash-chained audit entry attributed to the actor.
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +from sqlalchemy import select
13 +from sqlalchemy.orm import Session
14 +
15 +from aram_backend.models import FiscalYear, FiscalYearStatus, ReopenRequest
16 +from aram_backend.services.audit import append_entry
17 +
18 +
19 +class ReopenError(ValueError):
20 + """Raised when a reopen/lock operation is attempted on an invalid state."""
21 +
22 +
23 +def request_reopen(
24 + session: Session, year_id: int, *, reason: str, requested_by: str = ""
25 +) -> ReopenRequest:
26 + year = session.get(FiscalYear, year_id)
27 + if year is None:
28 + raise ReopenError(f"fiscal year {year_id} does not exist")
29 + if year.status != FiscalYearStatus.LOCKED:
30 + raise ReopenError(f"only a Locked year can be reopened (current: {year.status.value})")
31 + if not reason.strip():
32 + raise ReopenError("a reason is required to reopen a locked year")
33 + request = ReopenRequest(
34 + year_id=year_id, reason=reason.strip(), requested_by=requested_by, status="pending"
35 + )
36 + session.add(request)
37 + session.flush()
38 + append_entry(
39 + session,
40 + action="reopen.request",
41 + actor=requested_by,
42 + year_id=year_id,
43 + payload={"request_id": request.id, "reason": request.reason},
44 + )
45 + return request
46 +
47 +
48 +def approve_reopen(session: Session, request_id: int, *, approved_by: str = "") -> ReopenRequest:
49 + request = session.get(ReopenRequest, request_id)
50 + if request is None:
51 + raise ReopenError(f"reopen request {request_id} does not exist")
52 + if request.status != "pending":
53 + raise ReopenError(f"only a pending request can be approved (current: {request.status})")
54 + request.status = "approved"
55 + request.approved_by = approved_by
56 + session.flush()
57 + append_entry(
58 + session,
59 + action="reopen.approve",
60 + actor=approved_by,
61 + year_id=request.year_id,
62 + payload={"request_id": request.id},
63 + )
64 + return request
65 +
66 +
67 +def reopen_year(session: Session, year_id: int, *, actor: str = "") -> FiscalYear:
68 + year = session.get(FiscalYear, year_id)
69 + if year is None:
70 + raise ReopenError(f"fiscal year {year_id} does not exist")
71 + if year.status != FiscalYearStatus.LOCKED:
72 + raise ReopenError(f"only a Locked year can be reopened (current: {year.status.value})")
73 + approved = session.scalar(
74 + select(ReopenRequest.id).where(
75 + ReopenRequest.year_id == year_id, ReopenRequest.status == "approved"
76 + )
77 + )
78 + if approved is None:
79 + raise ReopenError("reopening requires an approved reopen request")
80 + # The ORM guard + DB trigger re-check the approved request on transition.
81 + year.status = FiscalYearStatus.APPROVED
82 + session.flush()
83 + append_entry(
84 + session, action="reopen", actor=actor, year_id=year_id, payload={"request_id": approved}
85 + )
86 + return year
87 +
88 +
89 +def lock_year(session: Session, year_id: int, *, actor: str = "") -> FiscalYear:
90 + year = session.get(FiscalYear, year_id)
91 + if year is None:
92 + raise ReopenError(f"fiscal year {year_id} does not exist")
93 + if year.status != FiscalYearStatus.APPROVED:
94 + raise ReopenError(f"only an Approved year can be locked (current: {year.status.value})")
95 + year.status = FiscalYearStatus.LOCKED
96 + session.flush()
97 + append_entry(session, action="lock", actor=actor, year_id=year_id, payload={})
98 + return year
99 +
100 +
101 +def list_reopen_requests(session: Session, year_id: int) -> list[ReopenRequest]:
102 + return list(
103 + session.scalars(
104 + select(ReopenRequest).where(ReopenRequest.year_id == year_id).order_by(ReopenRequest.id)
105 + ).all()
106 + )
107 +
108 +
109 +__all__ = [
110 + "ReopenError",
111 + "request_reopen",
112 + "approve_reopen",
113 + "reopen_year",
114 + "lock_year",
115 + "list_reopen_requests",
116 +]
backend/src/aram_backend/services/source_store.py new
+69
@@ -0,0 +1,69 @@
1 +"""Content-addressed source-byte store on disk (D-06, booklet §5, P-01).
2 +
3 +Source bytes are immutable once written: the path is derived from the SHA-256 of
4 +the content, writes are atomic and idempotent, and reads re-verify the hash so a
5 +corrupted or tampered store fails loudly (P-09). The database keeps only
6 +metadata (SourceFile); the bytes live here, never in a DB blob.
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +import hashlib
12 +import os
13 +import tempfile
14 +from dataclasses import dataclass
15 +from pathlib import Path
16 +
17 +
18 +class SourceStoreError(ValueError):
19 + """Raised when stored bytes cannot be trusted."""
20 +
21 +
22 +@dataclass(frozen=True)
23 +class StoredFile:
24 + sha256: str
25 + size: int
26 + stored_path: str
27 +
28 +
29 +class SourceStore:
30 + """A sharded, content-addressed directory of immutable source files."""
31 +
32 + def __init__(self, root: str | Path) -> None:
33 + self.root = Path(root)
34 +
35 + def _path_for(self, sha256: str) -> Path:
36 + return self.root / sha256[:2] / sha256
37 +
38 + def put(self, content: bytes) -> StoredFile:
39 + if not content:
40 + raise SourceStoreError("source file must not be empty")
41 + digest = hashlib.sha256(content).hexdigest()
42 + target = self._path_for(digest)
43 + if target.exists():
44 + existing = target.read_bytes()
45 + if hashlib.sha256(existing).hexdigest() != digest:
46 + raise SourceStoreError("content-addressed store is corrupted")
47 + else:
48 + target.parent.mkdir(parents=True, exist_ok=True)
49 + fd, tmp = tempfile.mkstemp(dir=str(target.parent))
50 + try:
51 + with os.fdopen(fd, "wb") as handle:
52 + handle.write(content)
53 + os.replace(tmp, target)
54 + finally:
55 + if os.path.exists(tmp):
56 + os.unlink(tmp)
57 + return StoredFile(sha256=digest, size=len(content), stored_path=str(target))
58 +
59 + def get(self, sha256: str) -> bytes:
60 + target = self._path_for(sha256)
61 + if not target.exists():
62 + raise SourceStoreError(f"source file {sha256} is not in the store")
63 + content = target.read_bytes()
64 + if hashlib.sha256(content).hexdigest() != sha256:
65 + raise SourceStoreError("stored bytes do not match their hash")
66 + return content
67 +
68 +
69 +__all__ = ["SourceStore", "StoredFile", "SourceStoreError"]
backend/src/aram_backend/services/statement_build.py new
+283
@@ -0,0 +1,283 @@
1 +"""Persistent, audited statement build + drill-down lineage (Phase 1, ADR-018).
2 +
3 +Turns imported LedgerBalance rows + active mappings/notes into versioned
4 +FinancialStatement/StatementLine records with exact integer-rial totals and a
5 +full lineage back to the source file/sheet/row. Display signs follow ADR-013
6 +(debit-positive closing; display = sign x closing).
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +from dataclasses import dataclass
12 +from decimal import Decimal
13 +
14 +from sqlalchemy import func, select
15 +from sqlalchemy.orm import Session
16 +
17 +from aram_backend.models import (
18 + FinancialStatement,
19 + FiscalYear,
20 + LedgerBalance,
21 + MappingRule,
22 + NoteDefinition,
23 + SourceDocument,
24 + StatementLine,
25 + StatementType,
26 +)
27 +
28 +_ZERO = Decimal(0)
29 +
30 +# Display sign policy (ADR-013/018). Closing is debit-positive.
31 +SECTION_POLICY: dict[str, dict[str, int]] = {
32 + "BS": {"Assets": 1, "Liabilities": -1, "Equity": -1},
33 + "IS": {"Revenue": -1, "Expenses": 1},
34 + "CF": {"Operating": 1, "Investing": 1, "Financing": 1},
35 + "EQ": {"Equity": -1},
36 +}
37 +SECTION_ORDER: dict[str, list[str]] = {
38 + "BS": ["Assets", "Liabilities", "Equity"],
39 + "IS": ["Revenue", "Expenses"],
40 + "CF": ["Operating", "Investing", "Financing"],
41 + "EQ": ["Equity"],
42 +}
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 + "Operating": "عملیاتی",
56 + "Investing": "سرمایه‌گذاری",
57 + "Financing": "تأمین مالی",
58 +}
59 +RENDERED_STATEMENTS = ("BS", "IS")
60 +ALL_STATEMENTS = ("BS", "IS", "CF", "EQ")
61 +
62 +
63 +class StatementBuildError(ValueError):
64 + """Raised when a statement cannot be built safely."""
65 +
66 +
67 +@dataclass(frozen=True)
68 +class BuildResult:
69 + statements: tuple[FinancialStatement, ...]
70 + unmapped_accounts: tuple[str, ...]
71 +
72 +
73 +def _effective_balance(balance: LedgerBalance) -> Decimal:
74 + """The figure that contributes to a statement line.
75 +
76 + Reclassified source rows carry only ``مانده صورت مالی`` (statement_balance)
77 + and leave CLOSING empty; that signed figure is authoritative for statement
78 + presentation (Phase 4 golden). Ordinary rows use the debit-positive closing.
79 + """
80 + if balance.statement_balance is not None:
81 + return balance.statement_balance
82 + return balance.closing
83 +
84 +
85 +def _latest_import_version(session: Session, year_id: int) -> int | None:
86 + return session.scalar(
87 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
88 + )
89 +
90 +
91 +def _latest_balances(session: Session, year_id: int) -> list[LedgerBalance]:
92 + version = _latest_import_version(session, year_id)
93 + if version is None:
94 + return []
95 + return list(
96 + session.scalars(
97 + select(LedgerBalance).where(
98 + LedgerBalance.year_id == year_id,
99 + LedgerBalance.import_version == version,
100 + )
101 + ).all()
102 + )
103 +
104 +
105 +def _next_statement_version(session: Session, year_id: int, stype: StatementType) -> int:
106 + current = session.scalar(
107 + select(func.max(FinancialStatement.version)).where(
108 + FinancialStatement.year_id == year_id,
109 + FinancialStatement.statement_type == stype,
110 + )
111 + )
112 + return (current or 0) + 1
113 +
114 +
115 +def build_statements(
116 + session: Session,
117 + year_id: int,
118 + *,
119 + statement_types: tuple[str, ...] = RENDERED_STATEMENTS,
120 +) -> BuildResult:
121 + """Build persisted, versioned statements for a Draft year.
122 +
123 + Aggregates the latest ledger import per mapped note, applies the display sign
124 + policy, and writes a new FinancialStatement version per requested type.
125 + Unmapped active accounts are surfaced (they block approval via preflight).
126 + """
127 + year = session.get(FiscalYear, year_id)
128 + if year is None:
129 + raise StatementBuildError(f"fiscal year {year_id} does not exist")
130 +
131 + balances = _latest_balances(session, year_id)
132 + notes = {
133 + n.id: n
134 + for n in session.scalars(
135 + select(NoteDefinition).where(NoteDefinition.year_id == year_id)
136 + ).all()
137 + }
138 + rules = session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all()
139 +
140 + account_to_notes: dict[str, list[int]] = {}
141 + for rule in rules:
142 + account_to_notes.setdefault(rule.account_code, []).append(rule.target_note_id)
143 +
144 + # Per-note display sign (ADR-013). Reclassified rows already carry a
145 + # presentation-signed statement_balance, so the sign is applied only to
146 + # ordinary closing-based rows; this reproduces the Phase-4 golden exactly.
147 + note_sign: dict[int, int] = {}
148 + for note in notes.values():
149 + stype_code = str(note.configuration_json.get("statement") or "")
150 + section = str(note.configuration_json.get("section") or "")
151 + note_sign[note.id] = SECTION_POLICY.get(stype_code, {}).get(section, 1)
152 +
153 + note_totals: dict[int, Decimal] = {}
154 + unmapped: list[str] = []
155 + for balance in balances:
156 + targets = account_to_notes.get(balance.account_full_code, [])
157 + if not targets:
158 + if _effective_balance(balance) != _ZERO:
159 + unmapped.append(balance.account_full_code)
160 + continue
161 + for note_id in targets:
162 + if balance.statement_balance is not None:
163 + contribution = balance.statement_balance
164 + else:
165 + contribution = note_sign.get(note_id, 1) * balance.closing
166 + note_totals[note_id] = note_totals.get(note_id, _ZERO) + contribution
167 +
168 + built: list[FinancialStatement] = []
169 + for stype_code in statement_types:
170 + if stype_code not in SECTION_POLICY:
171 + raise StatementBuildError(f"unknown statement type {stype_code}")
172 + stype = StatementType(stype_code)
173 + policy = SECTION_POLICY[stype_code]
174 + order = SECTION_ORDER[stype_code]
175 +
176 + member_notes = [
177 + n for n in notes.values() if n.configuration_json.get("statement") == stype_code
178 + ]
179 +
180 + def _sort_key(n: NoteDefinition, order: list[str] = order) -> tuple[int, str]:
181 + section = str(n.configuration_json.get("section") or "")
182 + return (order.index(section) if section in order else len(order), n.note_number)
183 +
184 + member_notes.sort(key=_sort_key)
185 +
186 + statement = FinancialStatement(
187 + year_id=year_id,
188 + statement_type=stype,
189 + version=_next_statement_version(session, year_id, stype),
190 + )
191 + session.add(statement)
192 + session.flush()
193 +
194 + for line_order, note in enumerate(member_notes):
195 + section = note.configuration_json.get("section", "")
196 + sign = policy.get(section)
197 + if sign is None:
198 + raise StatementBuildError(
199 + f"note {note.note_number}: section '{section}' has no sign policy for {stype_code}"
200 + )
201 + # note_totals already carries the presentation sign (statement_balance
202 + # rows are pre-signed; closing rows were signed during accumulation).
203 + total = note_totals.get(note.id, _ZERO)
204 + session.add(
205 + StatementLine(
206 + statement_id=statement.id,
207 + line_order=line_order,
208 + line_label=f"{note.note_number} — {note.title}",
209 + target_note_id=note.id,
210 + mapped_total=total,
211 + )
212 + )
213 + built.append(statement)
214 +
215 + session.flush()
216 + return BuildResult(statements=tuple(built), unmapped_accounts=tuple(sorted(set(unmapped))))
217 +
218 +
219 +def drill_down(session: Session, statement_line_id: int) -> dict[str, object]:
220 + """Return the full lineage of a statement line to source file/sheet/row."""
221 + line = session.get(StatementLine, statement_line_id)
222 + if line is None:
223 + raise StatementBuildError(f"statement line {statement_line_id} does not exist")
224 + note = line.target_note
225 + if note is None:
226 + return {"line_id": line.id, "note": None, "accounts": []}
227 +
228 + rules = session.scalars(select(MappingRule).where(MappingRule.target_note_id == note.id)).all()
229 + codes = sorted({r.account_code for r in rules})
230 + version = _latest_import_version(session, note.year_id)
231 + balances = (
232 + session.scalars(
233 + select(LedgerBalance).where(
234 + LedgerBalance.year_id == note.year_id,
235 + LedgerBalance.import_version == version,
236 + LedgerBalance.account_full_code.in_(codes),
237 + )
238 + ).all()
239 + if version is not None and codes
240 + else []
241 + )
242 +
243 + accounts = []
244 + for balance in balances:
245 + source = session.get(SourceDocument, balance.source_document_id)
246 + accounts.append(
247 + {
248 + "account_full_code": balance.account_full_code,
249 + "account_name": balance.account_name,
250 + "closing": str(balance.closing),
251 + "statement_balance": str(balance.statement_balance)
252 + if balance.statement_balance is not None
253 + else None,
254 + "effective_balance": str(_effective_balance(balance)),
255 + "source": {
256 + "filename": source.filename if source else None,
257 + "file_hash": source.file_hash if source else None,
258 + "sheet": balance.source_sheet,
259 + "row": balance.source_row,
260 + },
261 + }
262 + )
263 + return {
264 + "line_id": line.id,
265 + "line_label": line.line_label,
266 + "mapped_total": str(line.mapped_total) if line.mapped_total is not None else None,
267 + "note": {"id": note.id, "note_number": note.note_number, "title": note.title},
268 + "accounts": accounts,
269 + }
270 +
271 +
272 +__all__ = [
273 + "build_statements",
274 + "drill_down",
275 + "BuildResult",
276 + "StatementBuildError",
277 + "SECTION_POLICY",
278 + "SECTION_ORDER",
279 + "STATEMENT_LABELS_FA",
280 + "SECTION_LABELS_FA",
281 + "RENDERED_STATEMENTS",
282 + "ALL_STATEMENTS",
283 +]
backend/src/aram_backend/services/statement_export.py new
+259
@@ -0,0 +1,259 @@
1 +"""Reviewable statement outputs (Phase 6, booklet §15).
2 +
3 +Exports the persisted, audited statements (BS/IS/CF/EQ) plus evaluated notes and
4 +a full source-lineage register as a governed XLSX workbook and as structured
5 +JSON. Every figure is the exact integer-rial ``mapped_total`` from the latest
6 +statement version; a million-rial display column (half-up, ADR-012) is added for
7 +readability only and never replaces the exact rial. The lineage sheet traces each
8 +statement line to its source file/SHA-256/sheet/row (D2/D3), so the output is
9 +independently auditable. No new dependency: openpyxl is already required.
10 +"""
11 +
12 +from __future__ import annotations
13 +
14 +import json
15 +from datetime import UTC, datetime
16 +from decimal import Decimal
17 +from io import BytesIO
18 +from typing import Any, cast
19 +
20 +from openpyxl import Workbook
21 +from openpyxl.styles import Alignment, Font
22 +from openpyxl.utils import get_column_letter
23 +from sqlalchemy import func, select
24 +from sqlalchemy.orm import Session
25 +
26 +from aram_backend.domain.money import round_half_up
27 +from aram_backend.models import (
28 + FinancialStatement,
29 + FiscalYear,
30 + StatementLine,
31 + StatementType,
32 +)
33 +from aram_backend.services.note_engine import evaluate_year_notes
34 +from aram_backend.services.statement_build import (
35 + ALL_STATEMENTS,
36 + STATEMENT_LABELS_FA,
37 + drill_down,
38 +)
39 +
40 +_MILLION = Decimal(1_000_000)
41 +_RTL = Alignment(horizontal="right", readingOrder=2)
42 +
43 +
44 +class StatementExportError(ValueError):
45 + """Raised when statements cannot be exported safely."""
46 +
47 +
48 +def _latest_statement(
49 + session: Session, year_id: int, stype: StatementType
50 +) -> FinancialStatement | None:
51 + version = session.scalar(
52 + select(func.max(FinancialStatement.version)).where(
53 + FinancialStatement.year_id == year_id,
54 + FinancialStatement.statement_type == stype,
55 + )
56 + )
57 + if version is None:
58 + return None
59 + return session.scalar(
60 + select(FinancialStatement).where(
61 + FinancialStatement.year_id == year_id,
62 + FinancialStatement.statement_type == stype,
63 + FinancialStatement.version == version,
64 + )
65 + )
66 +
67 +
68 +def _ordered_lines(session: Session, statement_id: int) -> list[StatementLine]:
69 + return list(
70 + session.scalars(
71 + select(StatementLine)
72 + .where(StatementLine.statement_id == statement_id)
73 + .order_by(StatementLine.line_order)
74 + ).all()
75 + )
76 +
77 +
78 +def _million(rial: Decimal | None) -> int | None:
79 + if rial is None:
80 + return None
81 + return int(round_half_up(rial / _MILLION, 0))
82 +
83 +
84 +def collect_export(session: Session, year_id: int) -> dict[str, Any]:
85 + """Assemble the full export payload (statements + notes + lineage)."""
86 + year = session.get(FiscalYear, year_id)
87 + if year is None:
88 + raise StatementExportError(f"fiscal year {year_id} does not exist")
89 +
90 + statements: list[dict[str, Any]] = []
91 + lineage: list[dict[str, Any]] = []
92 + for code in ALL_STATEMENTS:
93 + statement = _latest_statement(session, year_id, StatementType(code))
94 + if statement is None:
95 + continue
96 + lines = _ordered_lines(session, statement.id)
97 + line_payload = []
98 + for line in lines:
99 + line_payload.append(
100 + {
101 + "line_order": line.line_order,
102 + "label": line.line_label,
103 + "mapped_total_rial": str(line.mapped_total)
104 + if line.mapped_total is not None
105 + else None,
106 + "mapped_total_million": _million(line.mapped_total),
107 + "target_note_id": line.target_note_id,
108 + }
109 + )
110 + detail = drill_down(session, line.id)
111 + note = detail.get("note")
112 + note_number = note.get("note_number") if isinstance(note, dict) else None
113 + for acc in cast(list[Any], detail.get("accounts", [])):
114 + if not isinstance(acc, dict):
115 + continue
116 + source = acc.get("source", {})
117 + lineage.append(
118 + {
119 + "statement": code,
120 + "line_label": line.line_label,
121 + "note_number": note_number,
122 + "account_full_code": acc.get("account_full_code"),
123 + "account_name": acc.get("account_name"),
124 + "effective_balance_rial": acc.get("effective_balance"),
125 + "filename": source.get("filename"),
126 + "file_hash": source.get("file_hash"),
127 + "sheet": source.get("sheet"),
128 + "source_row": source.get("row"),
129 + }
130 + )
131 + statements.append(
132 + {
133 + "type": code,
134 + "label_fa": STATEMENT_LABELS_FA.get(code, code),
135 + "version": statement.version,
136 + "lines": line_payload,
137 + }
138 + )
139 +
140 + notes = evaluate_year_notes(session, year_id)
141 + return {
142 + "year": year.year,
143 + "year_id": year_id,
144 + "company": year.company.name if year.company else "",
145 + "status": year.status.value,
146 + "generated_at": datetime.now(UTC).isoformat(),
147 + "statements": statements,
148 + "notes": notes,
149 + "lineage": lineage,
150 + }
151 +
152 +
153 +def export_statements_json(session: Session, year_id: int) -> dict[str, Any]:
154 + return collect_export(session, year_id)
155 +
156 +
157 +def _style_header(ws: Any, ncols: int) -> None:
158 + for col in range(1, ncols + 1):
159 + cell = ws.cell(row=1, column=col)
160 + cell.font = Font(bold=True)
161 + cell.alignment = _RTL
162 + ws.freeze_panes = "A2"
163 + ws.sheet_view.rightToLeft = True
164 +
165 +
166 +def _autosize(ws: Any) -> None:
167 + for col in ws.columns:
168 + width = max((len(str(c.value)) for c in col if c.value is not None), default=8)
169 + ws.column_dimensions[get_column_letter(col[0].column)].width = min(max(width + 2, 10), 60)
170 +
171 +
172 +def export_statements_workbook(session: Session, year_id: int) -> bytes:
173 + payload = collect_export(session, year_id)
174 + wb = Workbook()
175 +
176 + summary = wb.active
177 + summary.title = "Summary"
178 + summary.append(["field", "value"])
179 + summary.append(["year", payload["year"]])
180 + summary.append(["company", payload["company"]])
181 + summary.append(["status", payload["status"]])
182 + summary.append(["generated_at", payload["generated_at"]])
183 + for st in payload["statements"]:
184 + summary.append([f"{st['type']} version", st["version"]])
185 + summary.append(["lineage rows", len(payload["lineage"])])
186 + _style_header(summary, 2)
187 + _autosize(summary)
188 +
189 + for st in payload["statements"]:
190 + ws = wb.create_sheet(title=st["type"])
191 + ws.append(["line_order", "label", "mapped_total_rial", "mapped_total_million"])
192 + for line in st["lines"]:
193 + ws.append(
194 + [
195 + line["line_order"],
196 + line["label"],
197 + line["mapped_total_rial"],
198 + line["mapped_total_million"],
199 + ]
200 + )
201 + _style_header(ws, 4)
202 + _autosize(ws)
203 +
204 + for note in payload["notes"]:
205 + number = str(note.get("note_number", ""))
206 + title = f"Note {number}"[:31]
207 + ws = wb.create_sheet(title=title)
208 + ws.append(["row_order", "label", "formula", "value_rial", "accounts_referenced"])
209 + for row in note.get("rows", []):
210 + ws.append(
211 + [
212 + row.get("row_order"),
213 + row.get("label"),
214 + row.get("formula"),
215 + row.get("value"),
216 + ", ".join(row.get("accounts_referenced", [])),
217 + ]
218 + )
219 + _style_header(ws, 5)
220 + _autosize(ws)
221 +
222 + lineage_ws = wb.create_sheet(title="Lineage")
223 + headers = [
224 + "statement",
225 + "line_label",
226 + "note_number",
227 + "account_full_code",
228 + "account_name",
229 + "effective_balance_rial",
230 + "filename",
231 + "file_hash",
232 + "sheet",
233 + "source_row",
234 + ]
235 + lineage_ws.append(headers)
236 + for row in payload["lineage"]:
237 + lineage_ws.append([row.get(h) for h in headers])
238 + _style_header(lineage_ws, len(headers))
239 + _autosize(lineage_ws)
240 +
241 + buf = BytesIO()
242 + wb.save(buf)
243 + wb.close()
244 + return buf.getvalue()
245 +
246 +
247 +def export_statements_json_bytes(session: Session, year_id: int) -> bytes:
248 + return json.dumps(
249 + export_statements_json(session, year_id), ensure_ascii=False, indent=2
250 + ).encode("utf-8")
251 +
252 +
253 +__all__ = [
254 + "collect_export",
255 + "export_statements_json",
256 + "export_statements_json_bytes",
257 + "export_statements_workbook",
258 + "StatementExportError",
259 +]
backend/src/aram_backend/services/users.py new
+142
@@ -0,0 +1,142 @@
1 +"""Local user management and role authorization (Phase 7, booklet §7/§12).
2 +
3 +Offline desktop identity: usernames + roles, passwords hashed with
4 +PBKDF2-HMAC-SHA256 and a per-user random salt (stdlib only, no new dependency,
5 +no plaintext storage, no runtime network). Sensitive actions are gated by role
6 +and attributed to a username in the hash-chained audit log.
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +import hashlib
12 +import hmac
13 +import secrets
14 +
15 +from sqlalchemy import select
16 +from sqlalchemy.orm import Session
17 +
18 +from aram_backend.models import User, UserRole
19 +from aram_backend.services.audit import append_entry
20 +
21 +_PBKDF2_ROUNDS = 200_000
22 +
23 +
24 +class UserError(ValueError):
25 + """Raised when a user operation cannot be performed safely."""
26 +
27 +
28 +class AuthorizationError(PermissionError):
29 + """Raised when an actor lacks the role required for an action."""
30 +
31 +
32 +def _hash_password(password: str, salt: str) -> str:
33 + digest = hashlib.pbkdf2_hmac(
34 + "sha256", password.encode("utf-8"), bytes.fromhex(salt), _PBKDF2_ROUNDS
35 + )
36 + return digest.hex()
37 +
38 +
39 +def create_user(
40 + session: Session,
41 + *,
42 + username: str,
43 + password: str,
44 + role: UserRole = UserRole.PREPARER,
45 + display_name: str = "",
46 + actor: str = "",
47 +) -> User:
48 + username = username.strip()
49 + if not username:
50 + raise UserError("username is required")
51 + if len(password) < 8:
52 + raise UserError("password must be at least 8 characters")
53 + existing = session.scalar(select(User).where(User.username == username))
54 + if existing is not None:
55 + raise UserError(f"username '{username}' already exists")
56 + salt = secrets.token_hex(16)
57 + user = User(
58 + username=username,
59 + display_name=display_name or username,
60 + role=role,
61 + salt=salt,
62 + password_hash=_hash_password(password, salt),
63 + )
64 + session.add(user)
65 + session.flush()
66 + append_entry(
67 + session,
68 + action="user.create",
69 + actor=actor,
70 + payload={"username": username, "role": role.value},
71 + )
72 + return user
73 +
74 +
75 +def authenticate(session: Session, *, username: str, password: str) -> User:
76 + user = session.scalar(select(User).where(User.username == username.strip()))
77 + if user is None or not user.active:
78 + raise UserError("invalid credentials")
79 + candidate = _hash_password(password, user.salt)
80 + if not hmac.compare_digest(candidate, user.password_hash):
81 + raise UserError("invalid credentials")
82 + return user
83 +
84 +
85 +def list_users(session: Session) -> list[User]:
86 + return list(session.scalars(select(User).order_by(User.username)).all())
87 +
88 +
89 +def set_role(session: Session, *, username: str, role: UserRole, actor: str = "") -> User:
90 + user = session.scalar(select(User).where(User.username == username))
91 + if user is None:
92 + raise UserError(f"user '{username}' not found")
93 + user.role = role
94 + session.flush()
95 + append_entry(
96 + session,
97 + action="user.set_role",
98 + actor=actor,
99 + payload={"username": username, "role": role.value},
100 + )
101 + return user
102 +
103 +
104 +def set_active(session: Session, *, username: str, active: bool, actor: str = "") -> User:
105 + user = session.scalar(select(User).where(User.username == username))
106 + if user is None:
107 + raise UserError(f"user '{username}' not found")
108 + user.active = active
109 + session.flush()
110 + append_entry(
111 + session,
112 + action="user.set_active",
113 + actor=actor,
114 + payload={"username": username, "active": active},
115 + )
116 + return user
117 +
118 +
119 +def require_role(session: Session, *, username: str, allowed: set[UserRole]) -> User:
120 + """Return the active user iff their role is in ``allowed``; else raise.
121 +
122 + An empty/unknown username is rejected. This is the single authorization gate
123 + for sensitive actions (approve, reopen, lock, user management, backup).
124 + """
125 + user = session.scalar(select(User).where(User.username == username.strip()))
126 + if user is None or not user.active:
127 + raise AuthorizationError("actor is not an active user")
128 + if user.role not in allowed:
129 + raise AuthorizationError(f"role '{user.role.value}' is not permitted for this action")
130 + return user
131 +
132 +
133 +__all__ = [
134 + "UserError",
135 + "AuthorizationError",
136 + "create_user",
137 + "authenticate",
138 + "list_users",
139 + "set_role",
140 + "set_active",
141 + "require_role",
142 +]
backend/src/aram_backend/statement_api.py new
+655
@@ -0,0 +1,655 @@
1 +"""HTTP API for the persistent, audited vertical slice (Phase 1, ADR-018).
2 +
3 +Company/year setup -> source upload + year-filtered import -> notes + mappings ->
4 +statement build -> drill-down to source file/sheet/row. All mutations are
5 +year-isolated and subject to the D-07 immutability guards.
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
11 +from fastapi.responses import StreamingResponse
12 +from pydantic import BaseModel, Field
13 +from sqlalchemy import func, select
14 +from sqlalchemy.orm import Session
15 +
16 +from aram_backend.config import get_settings
17 +from aram_backend.database import get_session
18 +from aram_backend.domain.controls import BalanceRow, run_controls
19 +from aram_backend.ingestion import SourceRegistrationError, register_source_document
20 +from aram_backend.ledger_parser import LedgerParseError, SkippedRow, parse_ledger
21 +from aram_backend.models import (
22 + Company,
23 + FinancialStatement,
24 + FiscalYear,
25 + LedgerBalance,
26 + MappingRule,
27 + NoteDefinition,
28 + NoteRow,
29 + StatementLine,
30 + UserRole,
31 +)
32 +from aram_backend.services.approval import ApprovalError, approve_year
33 +from aram_backend.services.ledger_import import import_ledger_balances
34 +from aram_backend.services.mapping_io import (
35 + MappingImportError,
36 + export_mappings_workbook,
37 + import_mappings_workbook,
38 +)
39 +from aram_backend.services.mapping_workflow import (
40 + CarryForwardError,
41 + carry_forward_mappings,
42 + unknown_accounts,
43 +)
44 +from aram_backend.services.note_engine import NoteEngineError, evaluate_note
45 +from aram_backend.services.source_store import SourceStore, SourceStoreError
46 +from aram_backend.services.statement_build import (
47 + SECTION_LABELS_FA,
48 + STATEMENT_LABELS_FA,
49 + StatementBuildError,
50 + build_statements,
51 + drill_down,
52 +)
53 +from aram_backend.services.statement_export import (
54 + StatementExportError,
55 + export_statements_json_bytes,
56 + export_statements_workbook,
57 +)
58 +from aram_backend.services.users import AuthorizationError, list_users, require_role
59 +
60 +router = APIRouter(prefix="/api/v1", tags=["statements"])
61 +
62 +
63 +class CompanyIn(BaseModel):
64 + code: str = Field(min_length=1, max_length=64)
65 + name: str = Field(min_length=1, max_length=256)
66 + year: int = Field(gt=0)
67 +
68 +
69 +class NoteIn(BaseModel):
70 + note_number: str = Field(min_length=1, max_length=32)
71 + title: str = Field(min_length=1, max_length=512)
72 + statement: str = Field(pattern="^(BS|IS|CF|EQ)$")
73 + section: str = Field(min_length=1, max_length=64)
74 +
75 +
76 +class MappingIn(BaseModel):
77 + account_code: str = Field(min_length=1, max_length=64)
78 + target_note_id: int
79 + mapping_type: str = Field(default="closing", max_length=32)
80 +
81 +
82 +def _year_or_404(session: Session, year_id: int) -> FiscalYear:
83 + year = session.get(FiscalYear, year_id)
84 + if year is None:
85 + raise HTTPException(status_code=404, detail="fiscal year not found")
86 + return year
87 +
88 +
89 +@router.post("/companies")
90 +def create_company(body: CompanyIn, session: Session = Depends(get_session)) -> dict:
91 + company = Company(code=body.code, name=body.name)
92 + session.add(company)
93 + session.flush()
94 + year = FiscalYear(company_id=company.id, year=body.year)
95 + session.add(year)
96 + session.commit()
97 + return {
98 + "company_id": company.id,
99 + "year_id": year.id,
100 + "year": year.year,
101 + "status": year.status.value,
102 + }
103 +
104 +
105 +@router.post("/years/{year_id}/ledger")
106 +def upload_ledger(
107 + year_id: int,
108 + file: UploadFile = File(...),
109 + session: Session = Depends(get_session),
110 +) -> dict:
111 + year = _year_or_404(session, year_id)
112 + content = file.file.read()
113 + store = SourceStore(get_settings().source_store_root)
114 + try:
115 + source = register_source_document(
116 + session,
117 + year_id=year_id,
118 + filename=file.filename or "ledger.xlsx",
119 + document_type="general_ledger",
120 + content=content,
121 + store=store,
122 + )
123 + except (SourceRegistrationError, SourceStoreError) as exc:
124 + raise HTTPException(status_code=422, detail=str(exc)) from exc
125 +
126 + skipped: list[SkippedRow] = []
127 + try:
128 + records = [
129 + rec
130 + for rec in parse_ledger(
131 + content, file.filename or "ledger.xlsx", tolerant=True, skipped=skipped
132 + )
133 + if rec.source_year == year.year
134 + ]
135 + except LedgerParseError as exc:
136 + raise HTTPException(status_code=422, detail=str(exc)) from exc
137 +
138 + next_version = (
139 + session.scalar(
140 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
141 + )
142 + or 0
143 + ) + 1
144 + try:
145 + count = import_ledger_balances(
146 + session,
147 + year_id=year_id,
148 + source_document_id=source.id,
149 + records=records,
150 + import_version=next_version,
151 + )
152 + except ValueError as exc:
153 + raise HTTPException(status_code=422, detail=str(exc)) from exc
154 + session.commit()
155 + return {
156 + "source_document_id": source.id,
157 + "file_hash": source.file_hash,
158 + "import_version": next_version,
159 + "accounts_imported": count,
160 + "rows_for_year": len(records),
161 + "skipped_rows": [{"row": s.row_number, "reason": s.reason} for s in skipped],
162 + }
163 +
164 +
165 +@router.post("/years/{year_id}/notes")
166 +def create_note(year_id: int, body: NoteIn, session: Session = Depends(get_session)) -> dict:
167 + _year_or_404(session, year_id)
168 + note = NoteDefinition(
169 + year_id=year_id,
170 + note_number=body.note_number,
171 + title=body.title,
172 + configuration_json={"statement": body.statement, "section": body.section},
173 + )
174 + session.add(note)
175 + session.commit()
176 + return {"note_id": note.id, "note_number": note.note_number}
177 +
178 +
179 +@router.get("/years/{year_id}/notes")
180 +def list_notes(year_id: int, session: Session = Depends(get_session)) -> dict:
181 + _year_or_404(session, year_id)
182 + notes = session.scalars(
183 + select(NoteDefinition)
184 + .where(NoteDefinition.year_id == year_id)
185 + .order_by(NoteDefinition.note_number)
186 + ).all()
187 + return {
188 + "notes": [
189 + {
190 + "note_id": n.id,
191 + "note_number": n.note_number,
192 + "title": n.title,
193 + "statement": (n.configuration_json or {}).get("statement", ""),
194 + "section": (n.configuration_json or {}).get("section", ""),
195 + }
196 + for n in notes
197 + ]
198 + }
199 +
200 +
201 +@router.get("/years/{year_id}/mappings")
202 +def list_mappings(year_id: int, session: Session = Depends(get_session)) -> dict:
203 + _year_or_404(session, year_id)
204 + rules = session.scalars(
205 + select(MappingRule).where(MappingRule.year_id == year_id).order_by(MappingRule.account_code)
206 + ).all()
207 + return {
208 + "mappings": [
209 + {
210 + "mapping_id": r.id,
211 + "account_code": r.account_code,
212 + "target_note_id": r.target_note_id,
213 + "mapping_type": r.mapping_type,
214 + }
215 + for r in rules
216 + ]
217 + }
218 +
219 +
220 +@router.post("/years/{year_id}/mappings")
221 +def create_mapping(year_id: int, body: MappingIn, session: Session = Depends(get_session)) -> dict:
222 + _year_or_404(session, year_id)
223 + note = session.get(NoteDefinition, body.target_note_id)
224 + if note is None or note.year_id != year_id:
225 + raise HTTPException(status_code=422, detail="target note not found in this year")
226 + rule = MappingRule(
227 + year_id=year_id,
228 + rule_key=f"{body.account_code}->{body.target_note_id}",
229 + account_code=body.account_code,
230 + target_note_id=body.target_note_id,
231 + mapping_type=body.mapping_type,
232 + )
233 + session.add(rule)
234 + session.commit()
235 + return {"mapping_id": rule.id, "account_code": rule.account_code}
236 +
237 +
238 +@router.post("/years/{year_id}/statements/build")
239 +def build(year_id: int, session: Session = Depends(get_session)) -> dict:
240 + _year_or_404(session, year_id)
241 + try:
242 + result = build_statements(session, year_id)
243 + except StatementBuildError as exc:
244 + raise HTTPException(status_code=422, detail=str(exc)) from exc
245 + session.commit()
246 + return {
247 + "statements": [
248 + {"id": s.id, "type": s.statement_type.value, "version": s.version}
249 + for s in result.statements
250 + ],
251 + "unmapped_accounts": list(result.unmapped_accounts),
252 + }
253 +
254 +
255 +@router.get("/years/{year_id}/statements")
256 +def list_statements(year_id: int, session: Session = Depends(get_session)) -> dict:
257 + _year_or_404(session, year_id)
258 + statements = session.scalars(
259 + select(FinancialStatement)
260 + .where(FinancialStatement.year_id == year_id)
261 + .order_by(FinancialStatement.statement_type, FinancialStatement.version)
262 + ).all()
263 + payload = []
264 + for statement in statements:
265 + lines = session.scalars(
266 + select(StatementLine)
267 + .where(StatementLine.statement_id == statement.id)
268 + .order_by(StatementLine.line_order)
269 + ).all()
270 + payload.append(
271 + {
272 + "id": statement.id,
273 + "type": statement.statement_type.value,
274 + "label_fa": STATEMENT_LABELS_FA.get(statement.statement_type.value, ""),
275 + "version": statement.version,
276 + "lines": [
277 + {
278 + "id": ln.id,
279 + "line_order": ln.line_order,
280 + "label": ln.line_label,
281 + "mapped_total": str(ln.mapped_total)
282 + if ln.mapped_total is not None
283 + else None,
284 + "target_note_id": ln.target_note_id,
285 + }
286 + for ln in lines
287 + ],
288 + }
289 + )
290 + return {"statements": payload, "section_labels_fa": SECTION_LABELS_FA}
291 +
292 +
293 +@router.get("/years/{year_id}/statements/export")
294 +def export_statements(
295 + year_id: int, format: str = "xlsx", session: Session = Depends(get_session)
296 +) -> StreamingResponse:
297 + _year_or_404(session, year_id)
298 + try:
299 + if format == "json":
300 + data = export_statements_json_bytes(session, year_id)
301 + media = "application/json"
302 + ext = "json"
303 + elif format == "xlsx":
304 + data = export_statements_workbook(session, year_id)
305 + media = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
306 + ext = "xlsx"
307 + else:
308 + raise HTTPException(status_code=422, detail="format must be 'xlsx' or 'json'")
309 + except StatementExportError as exc:
310 + raise HTTPException(status_code=422, detail=str(exc)) from exc
311 + return StreamingResponse(
312 + iter([data]),
313 + media_type=media,
314 + headers={"Content-Disposition": f'attachment; filename="aram-statements-{year_id}.{ext}"'},
315 + )
316 +
317 +
318 +@router.get("/statement-lines/{line_id}/drilldown")
319 +def line_drilldown(line_id: int, session: Session = Depends(get_session)) -> dict:
320 + try:
321 + return drill_down(session, line_id)
322 + except StatementBuildError as exc:
323 + raise HTTPException(status_code=404, detail=str(exc)) from exc
324 +
325 +
326 +@router.get("/years/{year_id}/preflight")
327 +def preflight(year_id: int, session: Session = Depends(get_session)) -> dict:
328 + year = _year_or_404(session, year_id)
329 + version = session.scalar(
330 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
331 + )
332 + balances = (
333 + session.scalars(
334 + select(LedgerBalance).where(
335 + LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
336 + )
337 + ).all()
338 + if version is not None
339 + else []
340 + )
341 + rows = [
342 + BalanceRow(
343 + row_number=b.source_row,
344 + account_code=b.account_full_code,
345 + opening=b.opening,
346 + debit=b.debit,
347 + credit=b.credit,
348 + closing=b.closing,
349 + )
350 + for b in balances
351 + ]
352 + rules = session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all()
353 + from aram_backend.domain.controls import MappingTarget
354 +
355 + mappings: dict[str, list[MappingTarget]] = {}
356 + for rule in rules:
357 + mappings.setdefault(rule.account_code, []).append(
358 + MappingTarget(target=str(rule.target_note_id))
359 + )
360 + results = run_controls(rows, mappings)
361 + return {
362 + "year": year.year,
363 + "can_approve": all(r.passed for r in results if r.severity == "ERROR"),
364 + "controls": [
365 + {"code": r.code, "severity": r.severity, "passed": r.passed, "message_fa": r.message_fa}
366 + for r in results
367 + ],
368 + }
369 +
370 +
371 +# ----------------------------------------------------------- Phase 2: mapping I/O
372 +@router.get("/years/{year_id}/mappings/export")
373 +def export_mappings(year_id: int, session: Session = Depends(get_session)) -> StreamingResponse:
374 + _year_or_404(session, year_id)
375 + data = export_mappings_workbook(session, year_id)
376 + return StreamingResponse(
377 + iter([data]),
378 + media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
379 + headers={"Content-Disposition": f'attachment; filename="aram-mappings-{year_id}.xlsx"'},
380 + )
381 +
382 +
383 +@router.post("/years/{year_id}/mappings/import")
384 +def import_mappings(
385 + year_id: int,
386 + file: UploadFile = File(...),
387 + session: Session = Depends(get_session),
388 +) -> dict:
389 + _year_or_404(session, year_id)
390 + content = file.file.read()
391 + try:
392 + result = import_mappings_workbook(session, year_id, content)
393 + except MappingImportError as exc:
394 + raise HTTPException(status_code=422, detail=str(exc)) from exc
395 + session.commit()
396 + return {
397 + "created": result.created,
398 + "notes_created": result.notes_created,
399 + "errors": result.errors,
400 + }
401 +
402 +
403 +@router.get("/years/{year_id}/unknown-accounts")
404 +def unknown_queue(year_id: int, session: Session = Depends(get_session)) -> dict:
405 + _year_or_404(session, year_id)
406 + queue = unknown_accounts(session, year_id)
407 + return {"count": len(queue), "accounts": queue}
408 +
409 +
410 +class CarryForwardIn(BaseModel):
411 + from_year_id: int
412 +
413 +
414 +@router.post("/years/{year_id}/mappings/carry-forward")
415 +def carry_forward(
416 + year_id: int, body: CarryForwardIn, session: Session = Depends(get_session)
417 +) -> dict:
418 + _year_or_404(session, year_id)
419 + try:
420 + result = carry_forward_mappings(session, body.from_year_id, year_id)
421 + except CarryForwardError as exc:
422 + raise HTTPException(status_code=422, detail=str(exc)) from exc
423 + session.commit()
424 + return {"notes_created": result.notes_created, "mappings_created": result.mappings_created}
425 +
426 +
427 +class ApproveIn(BaseModel):
428 + actor: str = Field(default="", max_length=128)
429 +
430 +
431 +@router.post("/years/{year_id}/approve")
432 +def approve(year_id: int, body: ApproveIn, session: Session = Depends(get_session)) -> dict:
433 + _year_or_404(session, year_id)
434 + # Phase 7 role gate: once local users exist, only a reviewer/admin may approve
435 + # (consistent with /lock and /reopen). With no users yet (bootstrap/dev) the
436 + # action is allowed; the C-01..C-04 ERROR gate below always applies regardless.
437 + if list_users(session):
438 + try:
439 + require_role(session, username=body.actor, allowed={UserRole.ADMIN, UserRole.REVIEWER})
440 + except AuthorizationError as exc:
441 + raise HTTPException(status_code=403, detail=str(exc)) from exc
442 + try:
443 + result = approve_year(session, year_id, actor=body.actor)
444 + except ApprovalError as exc:
445 + raise HTTPException(status_code=422, detail=str(exc)) from exc
446 + if not result.approved:
447 + return {
448 + "approved": False,
449 + "blocking": [{"code": r.code, "message_fa": r.message_fa} for r in result.blocking],
450 + }
451 + session.commit()
452 + return {"approved": True, "status": "Approved"}
453 +
454 +
455 +# ----------------------------------------------------------- Phase 3: note engine
456 +class NoteRowIn(BaseModel):
457 + row_order: int = Field(ge=0)
458 + label: str = Field(min_length=1, max_length=512)
459 + formula_logic: str | None = Field(default=None, max_length=2000)
460 +
461 +
462 +@router.post("/years/{year_id}/notes/{note_id}/rows")
463 +def create_note_row(
464 + year_id: int, note_id: int, body: NoteRowIn, session: Session = Depends(get_session)
465 +) -> dict:
466 + _year_or_404(session, year_id)
467 + note = session.get(NoteDefinition, note_id)
468 + if note is None or note.year_id != year_id:
469 + raise HTTPException(status_code=404, detail="note not found in this year")
470 + if body.formula_logic:
471 + from aram_backend.domain.formula import FormulaError, parse_formula
472 +
473 + try:
474 + parse_formula(body.formula_logic)
475 + except FormulaError as exc:
476 + raise HTTPException(status_code=422, detail=f"invalid formula: {exc}") from exc
477 + row = NoteRow(
478 + note_id=note_id,
479 + row_order=body.row_order,
480 + label=body.label,
481 + formula_logic=body.formula_logic,
482 + )
483 + session.add(row)
484 + session.commit()
485 + return {"row_id": row.id, "row_order": row.row_order}
486 +
487 +
488 +@router.get("/notes/{note_id}/rows")
489 +def list_note_rows(note_id: int, session: Session = Depends(get_session)) -> dict:
490 + note = session.get(NoteDefinition, note_id)
491 + if note is None:
492 + raise HTTPException(status_code=404, detail="note not found")
493 + rows = sorted(note.rows, key=lambda r: r.row_order)
494 + return {
495 + "note_id": note.id,
496 + "rows": [
497 + {"row_order": r.row_order, "label": r.label, "formula_logic": r.formula_logic}
498 + for r in rows
499 + ],
500 + }
501 +
502 +
503 +@router.get("/notes/{note_id}/evaluate")
504 +def evaluate_note_endpoint(note_id: int, session: Session = Depends(get_session)) -> dict:
505 + try:
506 + return evaluate_note(session, note_id)
507 + except NoteEngineError as exc:
508 + raise HTTPException(status_code=422, detail=str(exc)) from exc
509 +
510 +
511 +# ------------------------------------------------- Phase 5: editable notes/mappings
512 +def _commit_guarded(session: Session) -> None:
513 + """Commit, translating the D-07 immutability guard into HTTP 409."""
514 + try:
515 + session.commit()
516 + except ValueError as exc:
517 + session.rollback()
518 + raise HTTPException(status_code=409, detail=str(exc)) from exc
519 +
520 +
521 +def _note_in_year(session: Session, year_id: int, note_id: int) -> NoteDefinition:
522 + note = session.get(NoteDefinition, note_id)
523 + if note is None or note.year_id != year_id:
524 + raise HTTPException(status_code=404, detail="note not found in this year")
525 + return note
526 +
527 +
528 +class NoteUpdate(BaseModel):
529 + note_number: str | None = Field(default=None, min_length=1, max_length=32)
530 + title: str | None = Field(default=None, min_length=1, max_length=512)
531 + statement: str | None = Field(default=None, pattern="^(BS|IS|CF|EQ)$")
532 + section: str | None = Field(default=None, min_length=1, max_length=64)
533 +
534 +
535 +@router.put("/years/{year_id}/notes/{note_id}")
536 +def update_note(
537 + year_id: int, note_id: int, body: NoteUpdate, session: Session = Depends(get_session)
538 +) -> dict:
539 + _year_or_404(session, year_id)
540 + note = _note_in_year(session, year_id, note_id)
541 + if body.note_number is not None:
542 + note.note_number = body.note_number
543 + if body.title is not None:
544 + note.title = body.title
545 + config = dict(note.configuration_json or {})
546 + if body.statement is not None:
547 + config["statement"] = body.statement
548 + if body.section is not None:
549 + config["section"] = body.section
550 + note.configuration_json = config
551 + _commit_guarded(session)
552 + return {"note_id": note.id, "note_number": note.note_number, "title": note.title}
553 +
554 +
555 +@router.delete("/years/{year_id}/notes/{note_id}")
556 +def delete_note(year_id: int, note_id: int, session: Session = Depends(get_session)) -> dict:
557 + _year_or_404(session, year_id)
558 + note = _note_in_year(session, year_id, note_id)
559 + referencing_mappings = session.scalar(
560 + select(func.count(MappingRule.id)).where(MappingRule.target_note_id == note_id)
561 + )
562 + referencing_lines = session.scalar(
563 + select(func.count(StatementLine.id)).where(StatementLine.target_note_id == note_id)
564 + )
565 + if referencing_mappings or referencing_lines:
566 + raise HTTPException(
567 + status_code=409,
568 + detail="note is referenced by mappings or statement lines; remove those first",
569 + )
570 + session.delete(note) # NoteRow rows cascade
571 + _commit_guarded(session)
572 + return {"deleted": note_id}
573 +
574 +
575 +class MappingUpdate(BaseModel):
576 + target_note_id: int | None = None
577 + mapping_type: str | None = Field(default=None, max_length=32)
578 +
579 +
580 +@router.put("/years/{year_id}/mappings/{mapping_id}")
581 +def update_mapping(
582 + year_id: int, mapping_id: int, body: MappingUpdate, session: Session = Depends(get_session)
583 +) -> dict:
584 + _year_or_404(session, year_id)
585 + rule = session.get(MappingRule, mapping_id)
586 + if rule is None or rule.year_id != year_id:
587 + raise HTTPException(status_code=404, detail="mapping not found in this year")
588 + if body.target_note_id is not None:
589 + _note_in_year(session, year_id, body.target_note_id)
590 + rule.target_note_id = body.target_note_id
591 + if body.mapping_type is not None:
592 + rule.mapping_type = body.mapping_type
593 + _commit_guarded(session)
594 + return {"mapping_id": rule.id, "account_code": rule.account_code}
595 +
596 +
597 +@router.delete("/years/{year_id}/mappings/{mapping_id}")
598 +def delete_mapping(year_id: int, mapping_id: int, session: Session = Depends(get_session)) -> dict:
599 + _year_or_404(session, year_id)
600 + rule = session.get(MappingRule, mapping_id)
601 + if rule is None or rule.year_id != year_id:
602 + raise HTTPException(status_code=404, detail="mapping not found in this year")
603 + session.delete(rule)
604 + _commit_guarded(session)
605 + return {"deleted": mapping_id}
606 +
607 +
608 +class NoteRowUpdate(BaseModel):
609 + row_order: int | None = Field(default=None, ge=0)
610 + label: str | None = Field(default=None, min_length=1, max_length=512)
611 + formula_logic: str | None = Field(default=None, max_length=2000)
612 +
613 +
614 +@router.put("/years/{year_id}/notes/{note_id}/rows/{row_id}")
615 +def update_note_row(
616 + year_id: int,
617 + note_id: int,
618 + row_id: int,
619 + body: NoteRowUpdate,
620 + session: Session = Depends(get_session),
621 +) -> dict:
622 + _year_or_404(session, year_id)
623 + _note_in_year(session, year_id, note_id)
624 + row = session.get(NoteRow, row_id)
625 + if row is None or row.note_id != note_id:
626 + raise HTTPException(status_code=404, detail="note row not found")
627 + if body.formula_logic:
628 + from aram_backend.domain.formula import FormulaError, parse_formula
629 +
630 + try:
631 + parse_formula(body.formula_logic)
632 + except FormulaError as exc:
633 + raise HTTPException(status_code=422, detail=f"invalid formula: {exc}") from exc
634 + if body.row_order is not None:
635 + row.row_order = body.row_order
636 + if body.label is not None:
637 + row.label = body.label
638 + if body.formula_logic is not None:
639 + row.formula_logic = body.formula_logic
640 + _commit_guarded(session)
641 + return {"row_id": row.id, "row_order": row.row_order}
642 +
643 +
644 +@router.delete("/years/{year_id}/notes/{note_id}/rows/{row_id}")
645 +def delete_note_row(
646 + year_id: int, note_id: int, row_id: int, session: Session = Depends(get_session)
647 +) -> dict:
648 + _year_or_404(session, year_id)
649 + _note_in_year(session, year_id, note_id)
650 + row = session.get(NoteRow, row_id)
651 + if row is None or row.note_id != note_id:
652 + raise HTTPException(status_code=404, detail="note row not found")
653 + session.delete(row)
654 + _commit_guarded(session)
655 + return {"deleted": row_id}
backend/src/aram_backend/static/pilot/app.js new
+600
@@ -0,0 +1,600 @@
1 +/* Aram Pilot Workbench — mobile-first, vanilla JS, RTL, no external deps. */
2 +"use strict";
3 +
4 +const API = "/api/v1/pilot";
5 +const S = {
6 + meta: null, data: null, tab: "dashboard",
7 + filter: "all", search: "", noteSearch: "",
8 + statementView: "BS", expanded: new Set(),
9 +};
10 +
11 +const $ = (s) => document.querySelector(s);
12 +const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => (
13 + { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]
14 +));
15 +function fmt(v) {
16 + if (v === null || v === undefined || v === "") return "—";
17 + let s = String(v); const neg = s.startsWith("-"); if (neg) s = s.slice(1);
18 + let [i, d] = s.split("."); i = i.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
19 + if (d) d = d.replace(/0+$/, "");
20 + return (neg ? "−" : "") + i + (d ? "." + d : "");
21 +}
22 +const isNeg = (v) => String(v ?? "").startsWith("-");
23 +const numCell = (v) => `<td class="num${isNeg(v) ? " neg" : ""}">${fmt(v)}</td>`;
24 +const STATUS_FA = {
25 + INCOMPLETE: "ناقص — پیش‌نویس کاری",
26 + COMPLETE_DRAFT: "کامل — نگاشت‌ها در انتظار تأیید",
27 + COMPLETE_APPROVED: "کامل — همهٔ نگاشت‌ها تأییدشده",
28 +};
29 +const APPROVAL_FA = { Draft: "پیش‌نویس", Reviewed: "بررسی‌شده", Approved: "تأییدشده" };
30 +
31 +let toastTimer = null;
32 +function toast(msg, kind = "") {
33 + const el = $("#toast"); el.textContent = msg; el.className = `toast ${kind}`;
34 + clearTimeout(toastTimer); toastTimer = setTimeout(() => el.classList.add("hidden"), 4200);
35 +}
36 +async function api(path, opts = {}) {
37 + const res = await fetch(API + path, opts);
38 + let body = null; try { body = await res.json(); } catch { /* non-JSON */ }
39 + if (!res.ok) {
40 + const d = body?.detail;
41 + const err = new Error(typeof d === "string" ? d : d?.message || `خطای سرور (${res.status})`);
42 + err.issues = d?.issues; err.status = res.status; throw err;
43 + }
44 + return body;
45 +}
46 +const actor = () => ($("#actor-input").value || "").trim();
47 +const sid = () => S.data.session.id;
48 +function applyPayload(payload) { S.data = payload; renderAll(); }
49 +
50 +/* ---------------- bottom sheet ---------------- */
51 +function openSheet(title, html, onMount) {
52 + $("#sheet-title").textContent = title;
53 + $("#sheet-body").innerHTML = html;
54 + $("#sheet").classList.remove("hidden");
55 + $("#sheet-backdrop").classList.remove("hidden");
56 + document.body.style.overflow = "hidden";
57 + if (onMount) onMount();
58 +}
59 +function closeSheet() {
60 + $("#sheet").classList.add("hidden");
61 + $("#sheet-backdrop").classList.add("hidden");
62 + document.body.style.overflow = "";
63 +}
64 +
65 +/* ---------------- landing ---------------- */
66 +function renderPolicy() {
67 + const m = S.meta, items = [];
68 + for (const st of m.rendered_statements)
69 + for (const [sec, sign] of Object.entries(m.section_policy[st]))
70 + 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>`);
71 + for (const st of m.deferred_statements)
72 + items.push(`<div class="policy-item muted">${esc(m.statement_labels_fa[st])} — نسخهٔ بعدی</div>`);
73 + $("#policy-grid").innerHTML = items.join("");
74 +}
75 +function showIssues(err) {
76 + const panel = $("#issues-panel");
77 + if (!err.issues?.length) { toast(err.message, "error"); return; }
78 + $("#issues-message").textContent = err.message;
79 + $("#issues-table tbody").innerHTML = err.issues.map((i) =>
80 + `<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("");
81 + panel.classList.remove("hidden");
82 + panel.scrollIntoView({ behavior: "smooth", block: "start" });
83 +}
84 +async function uploadFile(file) {
85 + $("#issues-panel").classList.add("hidden");
86 + $("#upload-progress").classList.remove("hidden"); $("#upload-btn").disabled = true;
87 + try {
88 + const form = new FormData(); form.append("file", file);
89 + enterWorkspace(await api("/sessions", { method: "POST", body: form }));
90 + toast("فایل پذیرفته شد؛ پیش‌بررسی بدون خطا بود.", "success");
91 + } catch (err) { showIssues(err); }
92 + finally { $("#upload-progress").classList.add("hidden"); $("#upload-btn").disabled = false; $("#file-input").value = ""; }
93 +}
94 +async function startDemo() {
95 + $("#issues-panel").classList.add("hidden"); $("#demo-btn").disabled = true;
96 + try {
97 + enterWorkspace(await api("/demo", { method: "POST" }));
98 + toast("دموی ساختگی آماده شد؛ دو حساب نگاشت‌نشده منتظر شما هستند.", "success");
99 + } catch (err) { toast(err.message, "error"); }
100 + finally { $("#demo-btn").disabled = false; }
101 +}
102 +
103 +/* ---------------- workspace ---------------- */
104 +function enterWorkspace(payload) {
105 + S.data = payload; S.tab = "dashboard"; S.filter = "all"; S.search = "";
106 + S.noteSearch = ""; S.expanded = new Set();
107 + $("#view-landing").classList.add("hidden");
108 + $("#view-workspace").classList.remove("hidden");
109 + $("#tabbar").classList.remove("hidden");
110 + $("#new-session-btn").classList.remove("hidden");
111 + $("#engine-version").textContent = payload.report.engine_version;
112 + renderAll(); window.scrollTo({ top: 0 });
113 +}
114 +function leaveWorkspace() {
115 + S.data = null;
116 + $("#view-workspace").classList.add("hidden");
117 + $("#view-landing").classList.remove("hidden");
118 + $("#tabbar").classList.add("hidden");
119 + $("#new-session-btn").classList.add("hidden");
120 +}
121 +function renderAll() {
122 + const { report, session } = S.data, c = report.company;
123 + const sourceChip = session.source === "demo"
124 + ? `<span class="chip demo">دموی ساختگی</span>`
125 + : `<span class="chip mono">${esc(session.filename)}</span>`;
126 + $("#session-info").innerHTML = `<div class="session-meta">
127 + <span class="company-name">${esc(c.name)}</span>
128 + <span class="chip">کد ${esc(c.code)}</span>
129 + <span class="chip">سال ${c.fiscal_year}</span>
130 + <span class="chip">${esc(c.unit || "واحد نامشخص")}</span>${sourceChip}</div>`;
131 + $("#status-chip").innerHTML = `<span class="status-chip status-${report.status.label}">${STATUS_FA[report.status.label]}</span>`;
132 + const ex = report.coverage.exception_count, badge = $("#mapping-badge");
133 + badge.textContent = ex; badge.className = `badge${ex === 0 ? " zero" : ""}`;
134 + document.querySelectorAll(".tabbar .tab").forEach((t) => t.classList.toggle("active", t.dataset.tab === S.tab));
135 + document.querySelectorAll(".tab-panel").forEach((p) => p.classList.add("hidden"));
136 + $(`#tab-${S.tab}`).classList.remove("hidden");
137 + ({ dashboard: renderDashboard, accounts: renderAccounts, notes: renderNotes, statements: renderStatements, more: renderMore })[S.tab]();
138 +}
139 +
140 +/* ---------------- dashboard ---------------- */
141 +function renderDashboard() {
142 + const { report } = S.data, t = report.totals, cov = report.coverage;
143 + const pct = cov.total_accounts ? Math.round((cov.mapped_accounts / cov.total_accounts) * 100) : 0;
144 + const totalCard = (label, v, hl = false) =>
145 + `<div class="total-card${hl ? " highlight" : ""}"><div class="label">${label}</div><div class="value${isNeg(v) ? " neg" : ""}">${fmt(v)}</div></div>`;
146 + const exceptions = report.exceptions.length ? `
147 + <div class="card" style="margin-top:14px">
148 + <h3 style="margin-top:0">صف استثنا (${report.exceptions.length})</h3>
149 + <div class="item-list">${report.exceptions.map((e) => `
150 + <div class="item-card">
151 + <div class="item-top">
152 + <div><div class="item-title">${esc(e.account_name)}</div><div class="item-code mono">${esc(e.account_code)} · سطر منبع ${e.source_row}</div></div>
153 + <span class="item-amount${isNeg(e.closing) ? " neg" : ""}">${fmt(e.closing)}</span>
154 + </div>
155 + <div class="item-sub"><span class="approval-chip approval-none">${esc(e.code)}</span> ${esc(e.details)}</div>
156 + <div class="item-actions"><button class="btn small primary" data-action="resolve-exception" data-code="${esc(e.account_code)}">رسیدگی و نگاشت</button></div>
157 + </div>`).join("")}</div>
158 + </div>` : `<div class="card" style="margin-top:14px"><b style="color:var(--green)">✓ هیچ استثنایی باقی نمانده است.</b></div>`;
159 + $("#tab-dashboard").innerHTML = `
160 + <div class="grid checks-grid">${report.checks.map((ch) => `
161 + <div class="check-card ${ch.passed ? "pass" : "fail"}">
162 + <div class="check-name">${esc(ch.name_fa)}</div>
163 + <div class="check-state">${ch.passed ? "✓ قبول" : "✗ رد"}</div>
164 + ${ch.amount !== null ? `<div class="check-amount">${fmt(ch.amount)}</div>` : ""}
165 + <div class="check-details">${esc(ch.details)}</div>
166 + </div>`).join("")}</div>
167 + <div class="card"><b>پوشش نگاشت:</b> ${cov.mapped_accounts} از ${cov.total_accounts} حساب (${pct}٪)
168 + <div class="coverage-bar-wrap" style="margin-top:8px"><div class="coverage-bar" style="width:${pct}%"></div></div></div>
169 + <div class="grid totals-grid">
170 + ${totalCard("جمع دارایی‌ها", t.assets)}${totalCard("جمع بدهی‌ها", t.liabilities)}
171 + ${totalCard("حقوق مالکانه", t.equity)}${totalCard("درآمدها", t.revenue)}
172 + ${totalCard("هزینه‌ها", t.expenses)}${totalCard("سود (زیان) دوره", t.profit, true)}
173 + </div>${exceptions}`;
174 +}
175 +
176 +/* ---------------- accounts ---------------- */
177 +function mappingSummary(a) {
178 + if (a.conflict) return `<span class="approval-chip approval-none">تعارض نگاشت</span>`;
179 + if (!a.mapping) return `<span class="approval-chip approval-none">بدون نگاشت</span>`;
180 + const m = a.mapping;
181 + 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);
182 + const label = note ? `${note.note_number} — ${note.note_title}` : m.note_number;
183 + 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>`;
184 +}
185 +function filteredAccounts() {
186 + const q = S.search.trim();
187 + return S.data.accounts.filter((a) => {
188 + if (S.filter === "unmapped" && a.mapping) return false;
189 + if (S.filter === "unapproved" && a.mapping?.approval_status === "Approved") return false;
190 + if (S.filter === "conflict" && !a.conflict) return false;
191 + if (q && !(a.code.includes(q) || a.name.includes(q))) return false;
192 + return true;
193 + });
194 +}
195 +function accountCard(a) {
196 + return `<div class="item-card">
197 + <div class="item-top">
198 + <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>
199 + <span class="item-amount${isNeg(a.closing) ? " neg" : ""}">${fmt(a.closing)}</span>
200 + </div>
201 + <div class="item-sub">${mappingSummary(a)}</div>
202 + <div class="item-actions">
203 + <button class="btn small primary" data-action="map-account" data-code="${esc(a.code)}">${a.mapping ? "ویرایش نگاشت" : "تعیین مقصد"}</button>
204 + <button class="btn small" data-action="edit-account" data-code="${esc(a.code)}">ویرایش حساب</button>
205 + <button class="btn small" data-action="rename-account" data-code="${esc(a.code)}">تغییر کد</button>
206 + <button class="btn small danger" data-action="delete-account" data-code="${esc(a.code)}">حذف</button>
207 + </div>
208 + </div>`;
209 +}
210 +function updateAccList() {
211 + const list = $("#acc-list"); if (!list) return;
212 + const rows = filteredAccounts().map(accountCard).join("");
213 + list.innerHTML = rows || `<div class="card muted">حسابی با این فیلتر یافت نشد.</div>`;
214 +}
215 +function renderAccounts() {
216 + $("#tab-accounts").innerHTML = `
217 + <div class="table-toolbar">
218 + <input type="search" id="acc-search" placeholder="جستجوی کد یا نام…" value="${esc(S.search)}">
219 + <select id="acc-filter">
220 + <option value="all">همه</option><option value="unmapped">بدون نگاشت</option>
221 + <option value="unapproved">تأییدنشده</option><option value="conflict">تعارض</option>
222 + </select>
223 + <button class="btn accent small" data-action="add-account">+ حساب جدید</button>
224 + </div>
225 + <p class="muted">${S.data.accounts.length} حساب · مانده بدهکار-مثبت · هر تغییر در ردّ ممیزی ثبت می‌شود</p>
226 + <div class="item-list" id="acc-list"></div>`;
227 + $("#acc-filter").value = S.filter;
228 + $("#acc-search").oninput = (e) => { S.search = e.target.value; updateAccList(); };
229 + $("#acc-filter").onchange = (e) => { S.filter = e.target.value; updateAccList(); };
230 + updateAccList();
231 +}
232 +
233 +/* ---------------- account forms ---------------- */
234 +function accountFormHtml(a) {
235 + const v = a || { full_code: "", name: "", general_code: "", general_name: "", opening: "0", debit: "0", credit: "0", subsidiary_code: "", subsidiary_name: "", row_status: "Draft" };
236 + const codeField = a
237 + ? `<div class="form-field full"><span>کد حساب (ثابت)</span><input value="${esc(v.full_code)}" disabled></div>`
238 + : `<div class="form-field full"><span>کد کامل حساب *</span><input id="f-code" value="${esc(v.full_code)}" placeholder="مثلاً 1201"></div>`;
239 + return `<div class="form-grid">
240 + ${codeField}
241 + <div class="form-field full"><span>نام حساب *</span><input id="f-name" value="${esc(v.name)}"></div>
242 + <div class="form-field"><span>کد حساب کل *</span><input id="f-gencode" value="${esc(v.general_code)}"></div>
243 + <div class="form-field"><span>نام حساب کل *</span><input id="f-genname" value="${esc(v.general_name)}"></div>
244 + <div class="form-field"><span>کد معین (اختیاری)</span><input id="f-subcode" value="${esc(v.subsidiary_code)}"></div>
245 + <div class="form-field"><span>نام معین (اختیاری)</span><input id="f-subname" value="${esc(v.subsidiary_name)}"></div>
246 + <div class="form-field"><span>مانده ابتدای دوره</span><input id="f-opening" inputmode="decimal" value="${esc(v.opening)}"></div>
247 + <div class="form-field"><span>گردش بدهکار</span><input id="f-debit" inputmode="decimal" value="${esc(v.debit)}"></div>
248 + <div class="form-field"><span>گردش بستانکار</span><input id="f-credit" inputmode="decimal" value="${esc(v.credit)}"></div>
249 + <div class="form-field"><span>وضعیت سطر</span><select id="f-rowstatus">
250 + <option value="Draft">Draft</option><option value="Reviewed">Reviewed</option><option value="Approved">Approved</option>
251 + </select></div>
252 + <div class="form-field full"><span>مانده پایان دوره (محاسبه‌شده)</span><div class="computed-box">بدهکار+ = <b id="f-closing">—</b></div></div>
253 + </div>
254 + <p class="form-hint">مانده پایان دوره از «ابتدای دوره + بدهکار − بستانکار» محاسبه می‌شود؛ هیچ مبلغی حدس زده نمی‌شود.</p>
255 + <div class="form-actions">
256 + <button class="btn primary" data-action="submit-account" data-code="${a ? esc(a.code) : ""}">${a ? "ذخیره تغییرات" : "افزودن حساب"}</button>
257 + <button class="btn ghost" data-action="close-sheet">انصراف</button>
258 + </div>`;
259 +}
260 +function wireAccountForm(a) {
261 + $("#f-rowstatus").value = a?.row_status || "Draft";
262 + const calc = () => {
263 + const o = parseFloat($("#f-opening").value) || 0, d = parseFloat($("#f-debit").value) || 0, c = parseFloat($("#f-credit").value) || 0;
264 + $("#f-closing").textContent = fmt(String(o + d - c));
265 + };
266 + ["f-opening", "f-debit", "f-credit"].forEach((id) => $("#" + id).addEventListener("input", calc));
267 + calc();
268 +}
269 +async function submitAccount(code) {
270 + const body = {
271 + name: $("#f-name").value, general_code: $("#f-gencode").value, general_name: $("#f-genname").value,
272 + opening: $("#f-opening").value || "0", debit: $("#f-debit").value || "0", credit: $("#f-credit").value || "0",
273 + row_status: $("#f-rowstatus").value, subsidiary_code: $("#f-subcode").value, subsidiary_name: $("#f-subname").value,
274 + actor: actor(),
275 + };
276 + try {
277 + if (code) applyPayload(await api(`/sessions/${sid()}/accounts/${encodeURIComponent(code)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
278 + else { body.full_code = $("#f-code").value; applyPayload(await api(`/sessions/${sid()}/accounts`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })); }
279 + closeSheet(); toast(code ? "حساب ویرایش شد." : "حساب جدید افزوده شد؛ اکنون مقصدش را تعیین کنید.", "success");
280 + } catch (err) { toast(err.message, "error"); }
281 +}
282 +function openRename(a) {
283 + openSheet("تغییر کد حساب", `<div class="form-grid">
284 + <div class="form-field full"><span>کد فعلی</span><input value="${esc(a.code)}" disabled></div>
285 + <div class="form-field full"><span>کد جدید *</span><input id="f-newcode" placeholder="کد جدید"></div>
286 + </div><p class="form-hint">نگاشت این حساب به‌صورت خودکار به کد جدید منتقل می‌شود.</p>
287 + <div class="form-actions"><button class="btn primary" data-action="submit-rename" data-code="${esc(a.code)}">تغییر کد</button>
288 + <button class="btn ghost" data-action="close-sheet">انصراف</button></div>`);
289 +}
290 +async function submitRename(code) {
291 + try {
292 + applyPayload(await api(`/sessions/${sid()}/accounts/${encodeURIComponent(code)}/rename`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ new_code: $("#f-newcode").value, actor: actor() }) }));
293 + closeSheet(); toast("کد حساب تغییر کرد و نگاشت منتقل شد.", "success");
294 + } catch (err) { toast(err.message, "error"); }
295 +}
296 +async function deleteAccount(code) {
297 + if (!confirm(`حساب ${code} و نگاشت آن حذف شود؟`)) return;
298 + try {
299 + applyPayload(await api(`/sessions/${sid()}/accounts/${encodeURIComponent(code)}?actor=${encodeURIComponent(actor())}`, { method: "DELETE" }));
300 + toast("حساب حذف شد.", "success");
301 + } catch (err) { toast(err.message, "error"); }
302 +}
303 +
304 +/* ---------------- mapping form ---------------- */
305 +function noteOptions(statement, section) {
306 + return S.data.notes.filter((n) => n.statement === statement && n.section === section);
307 +}
308 +function openMapping(a) {
309 + const m = a.mapping || {};
310 + const statements = [...S.meta.rendered_statements, ...S.meta.deferred_statements];
311 + openSheet(`نگاشت حساب ${a.code}`, `<div class="form-grid">
312 + <div class="form-field full"><span>حساب</span><input value="${esc(a.code)} — ${esc(a.name)}" disabled></div>
313 + <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>
314 + <div class="form-field"><span>بخش</span><select id="m-section"></select></div>
315 + <div class="form-field full"><span>یادداشت / زیریادداشت</span><select id="m-note"></select></div>
316 + <div class="form-field"><span>وضعیت تأیید</span><select id="m-approval">
317 + <option value="Draft">Draft</option><option value="Reviewed">Reviewed</option><option value="Approved">Approved</option>
318 + </select></div>
319 + <div class="form-field"><span>نام بازبین</span><input id="m-reviewer" value="${esc(m.reviewer || actor())}" placeholder="برای Reviewed/Approved الزامی"></div>
320 + </div>
321 + <div class="form-actions">
322 + <button class="btn primary" data-action="submit-mapping" data-code="${esc(a.code)}">ثبت نگاشت</button>
323 + ${a.mapping ? `<button class="btn danger" data-action="clear-mapping" data-code="${esc(a.code)}">حذف نگاشت</button>` : ""}
324 + <button class="btn ghost" data-action="close-sheet">انصراف</button>
325 + </div>`, () => {
326 + const stSel = $("#m-statement"), secSel = $("#m-section"), noteSel = $("#m-note");
327 + stSel.value = m.statement || "BS";
328 + const fillSections = () => {
329 + const st = stSel.value;
330 + const sections = S.meta.section_policy[st] ? Object.keys(S.meta.section_policy[st])
331 + : [...new Set(S.data.notes.filter((n) => n.statement === st).map((n) => n.section))];
332 + secSel.innerHTML = sections.map((sec) => `<option value="${esc(sec)}">${esc(S.meta.section_labels_fa[sec] || sec)}</option>`).join("");
333 + if (m.section && sections.includes(m.section)) secSel.value = m.section;
334 + fillNotes();
335 + };
336 + const fillNotes = () => {
337 + const opts = noteOptions(stSel.value, secSel.value);
338 + noteSel.innerHTML = opts.length ? opts.map((n) => {
339 + const val = `${n.note_number}|${n.subnote_code}`;
340 + const label = `${n.note_number} — ${n.note_title}${n.subnote_code ? ` / ${n.subnote_code} ${n.subnote_title}` : ""}`;
341 + return `<option value="${esc(val)}">${esc(label)}</option>`;
342 + }).join("") : `<option value="">— یادداشتی تعریف نشده؛ ابتدا از زبانهٔ یادداشت‌ها اضافه کنید —</option>`;
343 + const cur = `${m.note_number}|${m.subnote_code || ""}`;
344 + if ([...noteSel.options].some((o) => o.value === cur)) noteSel.value = cur;
345 + };
346 + stSel.onchange = fillSections; secSel.onchange = fillNotes; fillSections();
347 + $("#m-approval").value = m.approval_status || "Draft";
348 + });
349 +}
350 +async function submitMapping(code) {
351 + const noteVal = $("#m-note").value;
352 + if (!noteVal) { toast("برای این بخش یادداشتی نیست؛ ابتدا یادداشت اضافه کنید.", "error"); return; }
353 + const [note_number, subnote_code] = noteVal.split("|");
354 + const approval_status = $("#m-approval").value, reviewer = $("#m-reviewer").value.trim();
355 + if (approval_status !== "Draft" && !reviewer) { toast("برای Reviewed/Approved نام بازبین الزامی است.", "error"); return; }
356 + try {
357 + applyPayload(await api(`/sessions/${sid()}/mappings/${encodeURIComponent(code)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ statement: $("#m-statement").value, section: $("#m-section").value, note_number, subnote_code: subnote_code || "", approval_status, reviewer, actor: actor() }) }));
358 + closeSheet(); toast(`نگاشت حساب ${code} ثبت شد.`, "success");
359 + } catch (err) { toast(err.message, "error"); }
360 +}
361 +async function clearMapping(code) {
362 + try {
363 + applyPayload(await api(`/sessions/${sid()}/mappings/${encodeURIComponent(code)}?actor=${encodeURIComponent(actor())}`, { method: "DELETE" }));
364 + closeSheet(); toast("نگاشت حذف شد.", "success");
365 + } catch (err) { toast(err.message, "error"); }
366 +}
367 +
368 +/* ---------------- notes ---------------- */
369 +function updateNoteList() {
370 + const list = $("#note-list"); if (!list) return;
371 + const q = S.noteSearch.trim();
372 + const notes = S.data.notes.filter((n) => !q || n.note_number.includes(q) || n.note_title.includes(q) || n.section.includes(q));
373 + const groups = {};
374 + for (const n of notes) { const k = `${n.statement}|${n.section}`; (groups[k] = groups[k] || []).push(n); }
375 + 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}`));
376 + let html = "";
377 + const order = Object.keys(groups).sort();
378 + if (!order.length) html = `<div class="card muted">یادداشتی یافت نشد.</div>`;
379 + for (const k of order) {
380 + const [st, sec] = k.split("|");
381 + 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">`;
382 + for (const n of groups[k].sort((a, b) => a.note_number.localeCompare(b.note_number) || a.subnote_code.localeCompare(b.subnote_code))) {
383 + const key = `${n.statement}|${n.section}|${n.note_number}|${n.subnote_code}`;
384 + const inUse = usedKeys.has(key);
385 + html += `<div class="item-card">
386 + <div class="item-top">
387 + <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>
388 + <div class="item-code mono">یادداشت ${esc(n.note_number)}${n.subnote_code ? ` · زیریادداشت ${esc(n.subnote_code)}` : ""}</div></div>
389 + ${inUse ? `<span class="approval-chip approval-Approved">در استفاده</span>` : `<span class="approval-chip">آزاد</span>`}
390 + </div>
391 + <div class="item-actions">
392 + <button class="btn small" data-action="edit-note" data-key="${esc(key)}">ویرایش عنوان</button>
393 + <button class="btn small danger" data-action="delete-note" data-key="${esc(key)}" ${inUse ? 'title="ابتدا نگاشت‌های متصل را جابه‌جا کنید"' : ""}>حذف</button>
394 + </div>
395 + </div>`;
396 + }
397 + html += `</div>`;
398 + }
399 + list.innerHTML = html;
400 +}
401 +function renderNotes() {
402 + $("#tab-notes").innerHTML = `<div class="table-toolbar">
403 + <input type="search" id="note-search" placeholder="جستجوی یادداشت…" value="${esc(S.noteSearch)}">
404 + <button class="btn accent small" data-action="add-note">+ یادداشت جدید</button>
405 + </div><p class="muted">${S.data.notes.length} یادداشت/زیریادداشت · مقصدهای نگاشت از اینجا تعریف می‌شوند</p>
406 + <div id="note-list"></div>`;
407 + $("#note-search").oninput = (e) => { S.noteSearch = e.target.value; updateNoteList(); };
408 + updateNoteList();
409 +}
410 +function noteFormHtml(n) {
411 + const statements = [...S.meta.rendered_statements, ...S.meta.deferred_statements];
412 + const v = n || { statement: "BS", section: "Assets", note_number: "", note_title: "", subnote_code: "", subnote_title: "" };
413 + const keyLocked = !!n;
414 + return `<div class="form-grid">
415 + <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>
416 + <div class="form-field"><span>بخش *</span><input id="n-section" value="${esc(v.section)}" ${keyLocked ? "disabled" : ""} placeholder="Assets / Liabilities / …"></div>
417 + <div class="form-field"><span>شماره یادداشت *</span><input id="n-number" value="${esc(v.note_number)}" ${keyLocked ? "disabled" : ""}></div>
418 + <div class="form-field"><span>کد زیریادداشت (اختیاری)</span><input id="n-subcode" value="${esc(v.subnote_code)}" ${keyLocked ? "disabled" : ""}></div>
419 + <div class="form-field full"><span>عنوان یادداشت *</span><input id="n-title" value="${esc(v.note_title)}"></div>
420 + <div class="form-field full"><span>عنوان زیریادداشت</span><input id="n-subtitle" value="${esc(v.subnote_title)}"></div>
421 + </div>
422 + ${keyLocked ? `<p class="form-hint">کلید یادداشت ثابت است؛ فقط عنوان‌ها ویرایش می‌شوند.</p>` : `<p class="form-hint">برای زیریادداشت، کد و عنوان آن را پر کنید. بخش‌های استاندارد: Assets، Liabilities، Equity، Revenue، Expenses.</p>`}
423 + <div class="form-actions">
424 + <button class="btn primary" data-action="submit-note" data-key="${n ? esc(`${n.statement}|${n.section}|${n.note_number}|${n.subnote_code}`) : ""}">${n ? "ذخیره عنوان" : "افزودن یادداشت"}</button>
425 + <button class="btn ghost" data-action="close-sheet">انصراف</button>
426 + </div>`;
427 +}
428 +async function submitNote(key) {
429 + const body = {
430 + statement: $("#n-statement").value, section: $("#n-section").value,
431 + note_number: $("#n-number").value, note_title: $("#n-title").value,
432 + subnote_code: $("#n-subcode").value, subnote_title: $("#n-subtitle").value, actor: actor(),
433 + };
434 + try {
435 + if (key) { const [st, sec, num, sub] = key.split("|"); Object.assign(body, { statement: st, section: sec, note_number: num, subnote_code: sub }); }
436 + applyPayload(await api(`/sessions/${sid()}/notes`, { method: key ? "PUT" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
437 + closeSheet(); toast(key ? "عنوان یادداشت ویرایش شد." : "یادداشت جدید افزوده شد.", "success");
438 + } catch (err) { toast(err.message, "error"); }
439 +}
440 +async function deleteNote(key) {
441 + const [statement, section, note_number, subnote_code] = key.split("|");
442 + if (!confirm("این یادداشت حذف شود؟")) return;
443 + try {
444 + const params = new URLSearchParams({ statement, section, note_number, subnote_code, actor: actor() });
445 + applyPayload(await api(`/sessions/${sid()}/notes?${params}`, { method: "DELETE" }));
446 + toast("یادداشت حذف شد.", "success");
447 + } catch (err) { toast(err.message, "error"); }
448 +}
449 +
450 +/* ---------------- statements ---------------- */
451 +function renderStatements() {
452 + const code = S.statementView;
453 + const { report } = S.data, st = report.statements[code], c = report.company;
454 + const sections = st.sections.map((sec) => `
455 + <div class="statement-section">
456 + <div class="section-head"><span>${esc(sec.label_fa)}</span><span class="note-total${isNeg(sec.total) ? " neg" : ""}">${fmt(sec.total)}</span></div>
457 + ${sec.lines.map((line) => {
458 + const key = `${code}|${sec.name}|${line.note_number}|${line.subnote_code}`;
459 + const open = S.expanded.has(key);
460 + const title = `${line.note_title}${line.subnote_code ? ` / ${line.subnote_code} ${line.subnote_title}` : ""}`;
461 + return `<div class="note-line" data-action="toggle-line" data-key="${esc(key)}">
462 + <span class="note-title"><span class="note-number">${esc(line.note_number)}</span>${esc(title)} <span class="muted">${open ? "▾" : "◂"} ${line.accounts.length} حساب</span></span>
463 + <span class="note-total${isNeg(line.total) ? " neg" : ""}">${fmt(line.total)}</span></div>
464 + ${open ? `<div class="drill"><div class="table-wrap"><table>
465 + <thead><tr><th>کد</th><th>حساب</th><th class="num">مانده دفتر</th><th class="num">نمایشی</th><th>سطر</th><th>تأیید</th></tr></thead>
466 + <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>
467 + </table></div></div>` : ""}`;
468 + }).join("") || `<div class="note-line muted">رقمی در این بخش منظور نشده است.</div>`}
469 + </div>`).join("");
470 + const grand = code === "BS"
471 + ? `<div class="statement-total"><span>جمع دارایی‌ها</span><span class="note-total">${fmt(report.totals.assets)}</span></div>
472 + <div class="statement-total"><span>جمع بدهی‌ها و حقوق مالکانه</span><span class="note-total">${fmt(report.totals.liabilities_and_equity)}</span></div>`
473 + : `<div class="statement-total"><span>سود (زیان) دوره</span><span class="note-total${isNeg(report.totals.profit) ? " neg" : ""}">${fmt(report.totals.profit)}</span></div>`;
474 + $("#tab-statements").innerHTML = `
475 + <div class="statement-tools">
476 + <div class="segmented">
477 + <button data-action="view-statement" data-code="BS" class="${code === "BS" ? "active" : ""}">ترازنامه</button>
478 + <button data-action="view-statement" data-code="IS" class="${code === "IS" ? "active" : ""}">سود و زیان</button>
479 + </div>
480 + <button class="btn small ghost" data-action="print">🖨 چاپ</button>
481 + </div>
482 + <div class="statement-paper">
483 + <div class="statement-head"><h2>${esc(st.label_fa)}</h2>
484 + <div class="sub">${esc(c.name)} — سال مالی ${c.fiscal_year} — به ${esc(c.unit || "واحد نامشخص")}</div>
485 + <span class="draft-watermark">${STATUS_FA[report.status.label]} · پیش‌نویس کاری، نه صورت مالی رسمی</span></div>
486 + ${sections}${grand}
487 + ${code === "BS" ? `<p class="muted">سود دوره (${fmt(report.totals.profit)}) از طریق معادلهٔ حسابداری در حقوق مالکانه کنترل می‌شود.</p>` : ""}
488 + </div>`;
489 +}
490 +
491 +/* ---------------- more / audit / export ---------------- */
492 +function renderMore() {
493 + const { report, session, audit_trail: trail } = S.data, c = report.company;
494 + const prov = (k, v, mono = false) => `<div class="prov-item"><div class="k">${k}</div><div class="v${mono ? " mono" : ""}">${esc(v)}</div></div>`;
495 + $("#tab-more").innerHTML = `
496 + <div class="card" style="margin-bottom:14px">
497 + <h3 style="margin-top:0">شرکت و سال مالی</h3>
498 + <div class="provenance-grid">
499 + ${prov("نام", c.name)}${prov("کد", c.code, true)}${prov("سال مالی", c.fiscal_year)}
500 + ${prov("واحد", c.unit || "—")}${prov("ارز", c.currency || "—")}
501 + </div>
502 + <button class="btn block" data-action="edit-company">ویرایش اطلاعات شرکت</button>
503 + </div>
504 + <div class="card" style="margin-bottom:14px">
505 + <h3 style="margin-top:0">خروجی و ذخیره</h3>
506 + <div class="action-stack">
507 + <a class="btn primary block" href="${API}/sessions/${session.id}/export.xlsx" download>⬇ دانلود گزارش اکسل (صورت‌ها + کنترل‌ها + ردّ ممیزی)</a>
508 + <a class="btn accent block" href="${API}/sessions/${session.id}/workspace.xlsx" download>💾 ذخیرهٔ کارگاه (قابل آپلود مجدد برای ادامهٔ کار)</a>
509 + <button class="btn danger block" data-action="delete-session">حذف جلسه از حافظه</button>
510 + </div>
511 + <p class="muted">جلسه‌ها فقط در حافظهٔ سرور هستند؛ «ذخیرهٔ کارگاه» را دانلود کنید و بعداً دوباره آپلود کنید تا کار ادامه یابد.</p>
512 + </div>
513 + <div class="card" style="margin-bottom:14px">
514 + <h3 style="margin-top:0">شناسنامه</h3>
515 + <div class="provenance-grid">
516 + ${prov("SHA-256 فایل ورودی", report.source_sha256, true)}
517 + ${prov("زمان ایجاد (UTC)", session.created_at, true)}
518 + ${prov("منبع", session.source === "demo" ? "دموی ساختگی" : `فایل ${session.filename}`)}
519 + ${prov("نسخهٔ موتور", report.engine_version, true)}
520 + </div>
521 + </div>
522 + <div class="card">
523 + <h3 style="margin-top:0">ردّ ممیزی (${trail.length})</h3>
524 + ${trail.length ? `<div class="table-wrap"><table>
525 + <thead><tr><th>زمان</th><th>کاربر</th><th>حساب</th><th>اقدام</th><th>قبل</th><th>بعد</th></tr></thead>
526 + <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>
527 + </table></div>` : `<p class="muted">هنوز تغییری ثبت نشده است.</p>`}
528 + </div>`;
529 +}
530 +function openCompany() {
531 + const c = S.data.report.company;
532 + openSheet("ویرایش شرکت", `<div class="form-grid">
533 + <div class="form-field full"><span>نام شرکت *</span><input id="c-name" value="${esc(c.name)}"></div>
534 + <div class="form-field"><span>کد شرکت *</span><input id="c-code" value="${esc(c.code)}"></div>
535 + <div class="form-field"><span>سال مالی *</span><input id="c-year" inputmode="numeric" value="${c.fiscal_year}"></div>
536 + <div class="form-field"><span>واحد پول</span><input id="c-unit" value="${esc(c.unit)}"></div>
537 + <div class="form-field"><span>ارز</span><input id="c-currency" value="${esc(c.currency)}"></div>
538 + <div class="form-field full"><span>تهیه‌کننده</span><input id="c-prepared" value="${esc(c.prepared_by)}"></div>
539 + </div>
540 + <div class="form-actions"><button class="btn primary" data-action="submit-company">ذخیره</button>
541 + <button class="btn ghost" data-action="close-sheet">انصراف</button></div>`);
542 +}
543 +async function submitCompany() {
544 + try {
545 + applyPayload(await api(`/sessions/${sid()}/company`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ 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() }) }));
546 + closeSheet(); toast("اطلاعات شرکت ویرایش شد.", "success");
547 + } catch (err) { toast(err.message, "error"); }
548 +}
549 +async function deleteSession() {
550 + if (!confirm("جلسه از حافظهٔ سرور حذف شود؟ فایل‌های دانلودشده باقی می‌مانند.")) return;
551 + try { await api(`/sessions/${sid()}`, { method: "DELETE" }); leaveWorkspace(); toast("جلسه حذف شد.", "success"); }
552 + catch (err) { toast(err.message, "error"); }
553 +}
554 +
555 +/* ---------------- events ---------------- */
556 +document.addEventListener("click", (e) => {
557 + const el = e.target.closest("[data-action]");
558 + if (!el) return;
559 + const { action, code, key } = el.dataset;
560 + const findAcc = (c) => S.data.accounts.find((a) => a.code === c);
561 + if (action === "close-sheet") closeSheet();
562 + else if (action === "add-account") { openSheet("افزودن حساب جدید", accountFormHtml(null), () => wireAccountForm(null)); }
563 + else if (action === "edit-account") { const a = findAcc(code); openSheet(`ویرایش حساب ${code}`, accountFormHtml(a), () => wireAccountForm(a)); }
564 + else if (action === "submit-account") submitAccount(code);
565 + else if (action === "rename-account") openRename(findAcc(code));
566 + else if (action === "submit-rename") submitRename(code);
567 + else if (action === "delete-account") deleteAccount(code);
568 + else if (action === "map-account") openMapping(findAcc(code));
569 + else if (action === "submit-mapping") submitMapping(code);
570 + else if (action === "clear-mapping") clearMapping(code);
571 + else if (action === "resolve-exception") { S.tab = "accounts"; renderAll(); openMapping(findAcc(code)); }
572 + else if (action === "add-note") openSheet("افزودن یادداشت جدید", noteFormHtml(null), () => { $("#n-statement").value = "BS"; });
573 + 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; }); }
574 + else if (action === "submit-note") submitNote(key);
575 + else if (action === "delete-note") deleteNote(key);
576 + else if (action === "view-statement") { S.statementView = code; renderStatements(); }
577 + else if (action === "toggle-line") { S.expanded.has(key) ? S.expanded.delete(key) : S.expanded.add(key); renderStatements(); }
578 + else if (action === "print") window.print();
579 + else if (action === "edit-company") openCompany();
580 + else if (action === "submit-company") submitCompany();
581 + else if (action === "delete-session") deleteSession();
582 +});
583 +
584 +document.addEventListener("DOMContentLoaded", async () => {
585 + $("#actor-input").value = localStorage.getItem("aram-actor") || "";
586 + $("#actor-input").addEventListener("input", (e) => localStorage.setItem("aram-actor", e.target.value));
587 + $("#upload-btn").addEventListener("click", () => $("#file-input").click());
588 + $("#file-input").addEventListener("change", (e) => { if (e.target.files[0]) uploadFile(e.target.files[0]); });
589 + $("#demo-btn").addEventListener("click", startDemo);
590 + $("#new-session-btn").addEventListener("click", leaveWorkspace);
591 + $("#sheet-close").addEventListener("click", closeSheet);
592 + $("#sheet-backdrop").addEventListener("click", closeSheet);
593 + $("#tabbar").addEventListener("click", (e) => {
594 + const tab = e.target.closest(".tab");
595 + if (!tab || !S.data) return;
596 + S.tab = tab.dataset.tab; renderAll(); window.scrollTo({ top: 0 });
597 + });
598 + try { S.meta = await api("/meta"); renderPolicy(); }
599 + catch (err) { toast("بارگذاری اطلاعات موتور ناموفق بود: " + err.message, "error"); }
600 +});
backend/src/aram_backend/static/pilot/index.html new
+130
@@ -0,0 +1,130 @@
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="/pilot/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 + <header class="topbar">
16 + <div class="brand">
17 + <span class="brand-mark">آ</span>
18 + <div class="brand-text">
19 + <h1>آرام — میز کار پایلوت</h1>
20 + <p class="tagline">از اکسل منبع تا پیش‌نویس صورت‌های مالی، با ردیابی کامل</p>
21 + </div>
22 + </div>
23 + <div class="topbar-actions">
24 + <label class="actor-field" title="نام شما در ردّ ممیزی ثبت می‌شود">
25 + <span class="actor-label">نام کاربر:</span>
26 + <input id="actor-input" type="text" placeholder="نام بازبین" autocomplete="name">
27 + </label>
28 + <button id="new-session-btn" class="btn ghost small hidden">جلسهٔ جدید</button>
29 + </div>
30 + </header>
31 +
32 + <main id="main">
33 + <!-- Landing -->
34 + <section id="view-landing">
35 + <div class="hero">
36 + <h2>صورت‌های مالیِ قابل‌ردیابی، برای هر شرکت</h2>
37 + <p>
38 + فایل پایلوت (قرارداد v0.1) را وارد کنید یا دمو را اجرا کنید؛ حساب‌ها و یادداشت‌ها را
39 + آزادانه اضافه، ویرایش یا جایگزین کنید، نگاشت را تعیین کنید و ترازنامه و سود و زیان را
40 + با کنترل‌های تراز و معادلهٔ حسابداری بسازید — هر رقم تا سطر منبع قابل ردیابی است.
41 + </p>
42 + <p class="safety-note">
43 + هیچ مبلغی حدس زده نمی‌شود · دادهٔ منبع تغییر نمی‌کند · خروجی «پیش‌نویس کاری» است، نه صورت مالی رسمی
44 + </p>
45 + </div>
46 +
47 + <div class="action-cards">
48 + <div class="card action-card">
49 + <div class="action-icon">📥</div>
50 + <h3>ورود فایل پایلوت</h3>
51 + <p>فایل <span class="mono">.xlsx</span> مطابق قالب v0.1 (حداکثر ۲۵ مگابایت)</p>
52 + <input id="file-input" type="file" accept=".xlsx" class="hidden">
53 + <button id="upload-btn" class="btn primary">انتخاب و بررسی فایل</button>
54 + </div>
55 + <div class="card action-card">
56 + <div class="action-icon">🧪</div>
57 + <h3>دموی ساختگی</h3>
58 + <p>دادهٔ غیرواقعی و تراز، با دو حساب نگاشت‌نشده برای تجربهٔ گردش کار کامل</p>
59 + <button id="demo-btn" class="btn accent">اجرای دمو</button>
60 + </div>
61 + </div>
62 +
63 + <div id="upload-progress" class="card progress-card hidden">
64 + <span class="spinner"></span> در حال پیش‌بررسی فایل…
65 + </div>
66 +
67 + <div id="issues-panel" class="card issues-card hidden">
68 + <h3>❌ فایل رد شد — خطاهای پیش‌بررسی</h3>
69 + <p id="issues-message"></p>
70 + <div class="table-wrap">
71 + <table id="issues-table">
72 + <thead><tr><th>برگه</th><th>سطر</th><th>فیلد</th><th>کد خطا</th><th>شرح</th></tr></thead>
73 + <tbody></tbody>
74 + </table>
75 + </div>
76 + </div>
77 +
78 + <div class="card info-card">
79 + <h3>سیاست صریح علامت‌ها (بدون حدس)</h3>
80 + <div class="policy-grid" id="policy-grid"></div>
81 + <p class="muted">
82 + مانده‌ها بدهکار-مثبت هستند؛ نمایش = علامت × مانده. بخش‌های ناشناخته به‌جای حدس، به صف استثنا می‌روند.
83 + مقصدهای CF و EQ در این نسخه رندر نمی‌شوند و شفاف گزارش می‌شوند.
84 + </p>
85 + </div>
86 + </section>
87 +
88 + <!-- Workspace -->
89 + <section id="view-workspace" class="hidden">
90 + <div class="session-bar card">
91 + <div id="session-info"></div>
92 + <div id="status-chip"></div>
93 + </div>
94 + <div id="tab-dashboard" class="tab-panel"></div>
95 + <div id="tab-accounts" class="tab-panel hidden"></div>
96 + <div id="tab-notes" class="tab-panel hidden"></div>
97 + <div id="tab-statements" class="tab-panel hidden"></div>
98 + <div id="tab-more" class="tab-panel hidden"></div>
99 + </section>
100 + </main>
101 +
102 + <nav class="tabbar hidden" id="tabbar" aria-label="ناوبری بخش‌ها">
103 + <button data-tab="dashboard" class="tab active"><span class="tab-ico">🏠</span><span>داشبورد</span></button>
104 + <button data-tab="accounts" class="tab"><span class="tab-ico">📒</span><span>حساب‌ها</span><span id="mapping-badge" class="badge"></span></button>
105 + <button data-tab="notes" class="tab"><span class="tab-ico">🗂️</span><span>یادداشت‌ها</span></button>
106 + <button data-tab="statements" class="tab"><span class="tab-ico">📑</span><span>صورت‌ها</span></button>
107 + <button data-tab="more" class="tab"><span class="tab-ico">⚙️</span><span>بیشتر</span></button>
108 + </nav>
109 +
110 + <!-- Bottom-sheet modal -->
111 + <div id="sheet-backdrop" class="sheet-backdrop hidden"></div>
112 + <div id="sheet" class="sheet hidden" role="dialog" aria-modal="true">
113 + <div class="sheet-handle"></div>
114 + <div class="sheet-head">
115 + <h3 id="sheet-title"></h3>
116 + <button id="sheet-close" class="sheet-close" aria-label="بستن">✕</button>
117 + </div>
118 + <div id="sheet-body" class="sheet-body"></div>
119 + </div>
120 +
121 + <div id="toast" class="toast hidden"></div>
122 +
123 + <footer class="footer">
124 + Aram Pilot Workbench · موتور <span id="engine-version"></span> ·
125 + خروجی پیش‌نویس کاری است؛ برای گزارشگری رسمی استفاده نکنید.
126 + </footer>
127 +
128 + <script src="/pilot/app.js"></script>
129 +</body>
130 +</html>
backend/src/aram_backend/static/pilot/styles.css new
+283
@@ -0,0 +1,283 @@
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 +}
backend/src/aram_backend/workbook_inspection.py
+19 -10
@@ -7,6 +7,7 @@ from zipfile import BadZipFile
7 from openpyxl import load_workbook
8 from openpyxl.utils.exceptions import InvalidFileException
9
10 +from aram_backend.domain.normalization import normalize_fa
11
12 MAX_WORKSHEETS = 100
13 MAX_HEADER_COLUMNS = 256
@@ -62,9 +63,7 @@ _TABULAR_PROFILES = {
63 },
64 }
65
65 -_PRIMARY_STATEMENT_SHEETS = frozenset(
66 - {"سودوزيان", "وضعيت مالي", "حقوق مالكانه", "جريان هاي نقدي"}
67 -)
66 +_PRIMARY_STATEMENT_SHEETS = frozenset({"سودوزيان", "وضعيت مالي", "حقوق مالكانه", "جريان هاي نقدي"})
67
68
69 def inspect_xlsx(content: bytes, *, document_type: str) -> WorkbookInspection:
@@ -88,7 +87,10 @@ def inspect_xlsx(content: bytes, *, document_type: str) -> WorkbookInspection:
87 raise WorkbookInspectionError("workbook contains too many worksheets")
88
89 if document_type == "financial_statement":
91 - missing = _PRIMARY_STATEMENT_SHEETS.difference(sheet_names)
90 + actual_normalized = {normalize_fa(name) for name in sheet_names}
91 + missing = {normalize_fa(name) for name in _PRIMARY_STATEMENT_SHEETS}.difference(
92 + actual_normalized
93 + )
94 if missing:
95 raise WorkbookInspectionError(
96 f"financial statement workbook is missing sheets: {sorted(missing)}"
@@ -102,26 +104,33 @@ def inspect_xlsx(content: bytes, *, document_type: str) -> WorkbookInspection:
104 )
105
106 profile = _TABULAR_PROFILES[document_type]
105 - sheet_name = profile["sheet"]
106 - if sheet_name not in workbook:
107 - raise WorkbookInspectionError(f"required worksheet is missing: {sheet_name}")
107 + target_normalized = normalize_fa(profile["sheet"])
108 + sheets_by_normalized = {normalize_fa(name): name for name in workbook.sheetnames}
109 + if target_normalized not in sheets_by_normalized:
110 + raise WorkbookInspectionError(f"required worksheet is missing: {profile['sheet']}")
111 + sheet_name = sheets_by_normalized[target_normalized]
112
113 worksheet = workbook[sheet_name]
114 header_row = profile["header_row"]
115 + # D-11: read-only worksheets may report max_column=None (no dimension).
116 + max_column = worksheet.max_column
117 + if max_column is None:
118 + max_column = MAX_HEADER_COLUMNS
119 values = next(
120 worksheet.iter_rows(
121 min_row=header_row,
122 max_row=header_row,
115 - max_col=min(worksheet.max_column, MAX_HEADER_COLUMNS),
123 + max_col=min(max_column, MAX_HEADER_COLUMNS),
124 values_only=True,
125 ),
126 (),
127 )
120 - headers = tuple(str(value).strip() for value in values if value is not None)
128 + headers = tuple(normalize_fa(str(value)) for value in values if value is not None)
129 if len(headers) != len(set(headers)):
130 raise WorkbookInspectionError("header row contains duplicate names")
131
124 - missing = profile["required_headers"].difference(headers)
132 + required_normalized = {normalize_fa(h) for h in profile["required_headers"]}
133 + missing = required_normalized.difference(headers)
134 if missing:
135 raise WorkbookInspectionError(f"required headers are missing: {sorted(missing)}")
136
backend/tests/conftest.py
+26 -1
@@ -2,7 +2,8 @@ import pytest
2 from fastapi.testclient import TestClient
3 from sqlalchemy.orm import Session, sessionmaker
4
5 -from aram_backend.database import Base, build_engine
5 +from aram_backend.config import Settings
6 +from aram_backend.database import Base, build_engine, ensure_triggers, get_session
7 from aram_backend.main import app
8
9
@@ -10,6 +11,7 @@ from aram_backend.main import app
11 def session(tmp_path) -> Session:
12 engine = build_engine(f"sqlite:///{tmp_path / 'test.db'}")
13 Base.metadata.create_all(engine)
14 + ensure_triggers(engine)
15 factory = sessionmaker(bind=engine, expire_on_commit=False)
16 with factory() as db:
17 yield db
@@ -21,3 +23,26 @@ def session(tmp_path) -> Session:
23 def client() -> TestClient:
24 return TestClient(app)
25
26 +
27 +@pytest.fixture
28 +def api_client(tmp_path, monkeypatch) -> TestClient:
29 + """DB-backed API client with an isolated SQLite DB + source store."""
30 + engine = build_engine(f"sqlite:///{tmp_path / 'api.db'}")
31 + Base.metadata.create_all(engine)
32 + ensure_triggers(engine)
33 + factory = sessionmaker(bind=engine, expire_on_commit=False)
34 +
35 + def override_session():
36 + with factory() as db:
37 + yield db
38 +
39 + app.dependency_overrides[get_session] = override_session
40 + monkeypatch.setattr(
41 + "aram_backend.statement_api.get_settings",
42 + lambda: Settings(source_store_root=str(tmp_path / "store")),
43 + )
44 + with TestClient(app) as test_client:
45 + yield test_client
46 + app.dependency_overrides.clear()
47 + Base.metadata.drop_all(engine)
48 + engine.dispose()
backend/tests/test_approval_gate.py new
+160
@@ -0,0 +1,160 @@
1 +"""Audit #3/#4: approval gate must run ALL controls (esp. C-03) and block on ERROR.
2 +
3 +Negative tests prove a year can never be approved while any control fails,
4 +including the double-mapping case (C-03) flagged in the owner's line-by-line audit.
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +from decimal import Decimal
10 +
11 +import pytest
12 +
13 +from aram_backend.domain.controls import BalanceRow, MappingTarget
14 +from aram_backend.models import FiscalYearStatus
15 +from aram_backend.services.approval import ApprovalError, approve_year, evaluate_controls
16 +from aram_backend.services.audit import verify_chain
17 +from test_statement_build import _balance, _map, _note, _setup
18 +
19 +
20 +def _balanced(session):
21 + year, source = _setup(session)
22 + _balance(session, year, source, "148348", 100, 3)
23 + _balance(session, year, source, "241001", -60, 4)
24 + _balance(session, year, source, "341001", -40, 5)
25 + n_a = _note(session, year, "6", "نقد", "BS", "Assets")
26 + n_l = _note(session, year, "10", "پرداختنی", "BS", "Liabilities")
27 + n_e = _note(session, year, "12", "سرمایه", "BS", "Equity")
28 + _map(session, year, "148348", n_a)
29 + _map(session, year, "241001", n_l)
30 + _map(session, year, "341001", n_e)
31 + session.flush()
32 + return year, n_a
33 +
34 +
35 +class TestApprovalNegative:
36 + def test_double_mapping_blocks_via_c03(self, session):
37 + # The exact audit concern: one account mapped to TWO notes must block.
38 + year, n_a = _balanced(session)
39 + n_a2 = _note(session, year, "6b", "نقد دوم", "BS", "Assets")
40 + _map(session, year, "148348", n_a2) # second mapping for the same account
41 + session.flush()
42 + result = approve_year(session, year.id)
43 + assert not result.approved
44 + assert any(r.code == "C-03" for r in result.blocking)
45 + assert year.status == FiscalYearStatus.DRAFT
46 +
47 + def test_c01_violation_blocks(self, session):
48 + year, source = _setup(session)
49 + _balance(session, year, source, "148348", 100, 3)
50 + # Corrupt the closing so opening+debit-credit-closing != 0.
51 + from aram_backend.models import LedgerBalance
52 +
53 + b = session.query(LedgerBalance).filter_by(year_id=year.id).one()
54 + b.closing = Decimal(999)
55 + n = _note(session, year, "6", "نقد", "BS", "Assets")
56 + _map(session, year, "148348", n)
57 + session.flush()
58 + result = approve_year(session, year.id)
59 + assert not result.approved
60 + assert any(r.code == "C-01" for r in result.blocking)
61 +
62 + def test_c02_imbalance_blocks(self, session):
63 + year, source = _setup(session)
64 + _balance(session, year, source, "148348", 100, 3)
65 + _balance(session, year, source, "148349", 50, 4) # no offsetting credit
66 + n = _note(session, year, "6", "نقد", "BS", "Assets")
67 + _map(session, year, "148348", n)
68 + _map(session, year, "148349", n)
69 + session.flush()
70 + result = approve_year(session, year.id)
71 + assert not result.approved
72 + assert any(r.code == "C-02" for r in result.blocking)
73 +
74 + def test_unmapped_blocks_via_c04(self, session):
75 + year, source = _setup(session)
76 + _balance(session, year, source, "148348", 100, 3)
77 + session.flush()
78 + result = approve_year(session, year.id)
79 + assert not result.approved
80 + assert any(r.code == "C-04" for r in result.blocking)
81 +
82 + def test_blocked_approval_writes_no_audit_and_stays_draft(self, session):
83 + year, source = _setup(session)
84 + _balance(session, year, source, "148348", 100, 3)
85 + session.flush()
86 + approve_year(session, year.id)
87 + session.commit()
88 + from aram_backend.models import AuditEntry
89 +
90 + assert session.query(AuditEntry).count() == 0
91 + assert year.status == FiscalYearStatus.DRAFT
92 +
93 + def test_non_draft_rejected(self, session):
94 + year, _ = _balanced(session)
95 + approve_year(session, year.id)
96 + session.commit()
97 + with pytest.raises(ApprovalError):
98 + approve_year(session, year.id)
99 +
100 + def test_nonexistent_year_rejected(self, session):
101 + with pytest.raises(ApprovalError):
102 + approve_year(session, 999999)
103 +
104 +
105 +class TestApprovalPositive:
106 + def test_clean_ledger_approves_and_audits(self, session):
107 + year, _ = _balanced(session)
108 + result = approve_year(session, year.id, actor="reviewer")
109 + session.commit()
110 + assert result.approved
111 + assert result.blocking == ()
112 + assert year.status == FiscalYearStatus.APPROVED
113 + assert verify_chain(session)
114 +
115 + def test_locked_after_approval_is_immutable(self, session):
116 + year, _ = _balanced(session)
117 + approve_year(session, year.id)
118 + session.commit()
119 + year.status = FiscalYearStatus.LOCKED
120 + session.commit()
121 + from sqlalchemy import text
122 + from sqlalchemy.exc import IntegrityError
123 +
124 + with pytest.raises(IntegrityError):
125 + session.execute(
126 + text("UPDATE ledger_balances SET debit = 1 WHERE year_id = :y"), {"y": year.id}
127 + )
128 + session.rollback()
129 +
130 +
131 +class TestEvaluateControlsUsesMappings:
132 + """Prove mappings are actually passed to the controls (C-03/C-04)."""
133 +
134 + def _rows(self):
135 + return [BalanceRow(row_number=3, account_code="148348", opening=Decimal(0),
136 + debit=Decimal(100), credit=Decimal(0), closing=Decimal(100))]
137 +
138 + def test_no_mappings_fails_c03_c04(self):
139 + results = {r.code: r for r in evaluate_controls(self._rows(), {})}
140 + assert not results["C-03"].passed
141 + assert not results["C-04"].passed
142 +
143 + def test_single_mapping_passes_c03_c04(self):
144 + mappings = {"148348": [MappingTarget(target="1")]}
145 + results = {r.code: r for r in evaluate_controls(self._rows(), mappings)}
146 + assert results["C-03"].passed
147 + assert results["C-04"].passed
148 +
149 + def test_double_mapping_fails_c03(self):
150 + mappings = {"148348": [MappingTarget(target="1"), MappingTarget(target="2")]}
151 + results = {r.code: r for r in evaluate_controls(self._rows(), mappings)}
152 + assert not results["C-03"].passed
153 +
154 + def test_valid_100_split_passes_c03(self):
155 + mappings = {
156 + "148348": [MappingTarget(target="1", weight=Decimal(60)),
157 + MappingTarget(target="2", weight=Decimal(40))]
158 + }
159 + results = {r.code: r for r in evaluate_controls(self._rows(), mappings)}
160 + assert results["C-03"].passed
backend/tests/test_desktop.py new
+49
@@ -0,0 +1,49 @@
1 +"""Phase 8 desktop entrypoint: local DB init, triggers, loopback API serving."""
2 +
3 +from __future__ import annotations
4 +
5 +import sqlite3
6 +
7 +from fastapi.testclient import TestClient
8 +
9 +from aram_backend.database import reconfigure
10 +from aram_backend.desktop import create_desktop_app, default_data_dir, initialize_database
11 +
12 +
13 +def test_initialize_database_creates_schema_and_triggers(tmp_path):
14 + data_dir = tmp_path / "aram-data"
15 + initialize_database(data_dir)
16 + assert (data_dir / "aram.db").exists()
17 + assert (data_dir / "source_store").is_dir()
18 + conn = sqlite3.connect(str(data_dir / "aram.db"))
19 + try:
20 + triggers = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='trigger'")}
21 + tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
22 + finally:
23 + conn.close()
24 + assert "ledger_balances" in tables
25 + assert "users" in tables
26 + assert any(t.startswith("aram_lock_") for t in triggers)
27 + assert "aram_audit_update" in triggers
28 + # Idempotent: a second init must not fail.
29 + initialize_database(data_dir)
30 +
31 +
32 +def test_desktop_app_serves_health_and_api(tmp_path):
33 + data_dir = tmp_path / "aram-data"
34 + initialize_database(data_dir)
35 + reconfigure(f"sqlite:///{data_dir / 'aram.db'}")
36 + app = create_desktop_app()
37 + with TestClient(app) as client:
38 + r = client.get("/api/v1/health")
39 + assert r.status_code == 200
40 + assert r.json()["status"] == "ok"
41 + # End-to-end through the desktop app's local DB.
42 + r = client.post("/api/v1/companies", json={"code": "D1", "name": "شرکت", "year": 1404})
43 + assert r.status_code == 200, r.text
44 + assert r.json()["year"] == 1404
45 +
46 +
47 +def test_default_data_dir_override(monkeypatch, tmp_path):
48 + monkeypatch.setenv("ARAM_DATA_DIR", str(tmp_path / "custom"))
49 + assert default_data_dir() == tmp_path / "custom"
backend/tests/test_domain_controls.py new
+85
@@ -0,0 +1,85 @@
1 +"""Positive and negative tests for blocking controls C-01..C-04 (D-02)."""
2 +
3 +from decimal import Decimal
4 +
5 +from aram_backend.domain.controls import (
6 + BalanceRow,
7 + MappingTarget,
8 + check_c01,
9 + check_c02,
10 + check_c03,
11 + check_c04,
12 + run_controls,
13 +)
14 +
15 +
16 +def row(n, code, o, d, c, cl):
17 + return BalanceRow(n, code, Decimal(o), Decimal(d), Decimal(c), Decimal(cl))
18 +
19 +
20 +class TestC01:
21 + def test_pass(self):
22 + rows = [row(2, "148348", 100, 50, 20, 130)]
23 + assert check_c01(rows).passed
24 +
25 + def test_fail_detects_row(self):
26 + rows = [row(2, "148348", 100, 50, 20, 999)]
27 + result = check_c01(rows)
28 + assert not result.passed
29 + assert result.severity == "ERROR"
30 + assert result.affected == ("2",)
31 +
32 +
33 +class TestC02:
34 + def test_pass(self):
35 + rows = [row(2, "a", 0, 100, 0, 100), row(3, "b", 0, 0, 100, -100)]
36 + assert check_c02(rows).passed
37 +
38 + def test_fail_unbalanced(self):
39 + rows = [row(2, "a", 0, 100, 0, 100)]
40 + assert not check_c02(rows).passed
41 +
42 +
43 +class TestC03:
44 + def test_single_mapping_pass(self):
45 + rows = [row(2, "a", 0, 100, 0, 100)]
46 + mappings = {"a": [MappingTarget("BS/Assets/04")]}
47 + assert check_c03(rows, mappings).passed
48 +
49 + def test_no_mapping_fail(self):
50 + rows = [row(2, "a", 0, 100, 0, 100)]
51 + result = check_c03(rows, {})
52 + assert not result.passed
53 + assert result.affected == ("a",)
54 +
55 + def test_split_100_pass(self):
56 + rows = [row(2, "a", 0, 100, 0, 100)]
57 + mappings = {"a": [MappingTarget("x", Decimal(60)), MappingTarget("y", Decimal(40))]}
58 + assert check_c03(rows, mappings).passed
59 +
60 + def test_split_not_100_fail(self):
61 + rows = [row(2, "a", 0, 100, 0, 100)]
62 + mappings = {"a": [MappingTarget("x", Decimal(60)), MappingTarget("y", Decimal(30))]}
63 + assert not check_c03(rows, mappings).passed
64 +
65 + def test_zero_balance_account_ignored(self):
66 + rows = [row(2, "a", 0, 0, 0, 0)]
67 + assert check_c03(rows, {}).passed
68 +
69 +
70 +class TestC04:
71 + def test_empty_queue_pass(self):
72 + rows = [row(2, "a", 0, 100, 0, 100)]
73 + assert check_c04(rows, {"a": [MappingTarget("x")]}).passed
74 +
75 + def test_unmapped_active_blocks(self):
76 + rows = [row(2, "a", 0, 100, 0, 100), row(3, "b", 0, 0, 0, 0)]
77 + result = check_c04(rows, {})
78 + assert not result.passed
79 + assert result.affected == ("a",) # zero-balance b is not queued
80 +
81 +
82 +class TestRunControls:
83 + def test_stable_order(self):
84 + results = run_controls([], {})
85 + assert [r.code for r in results] == ["C-01", "C-02", "C-03", "C-04"]
backend/tests/test_domain_hierarchy.py new
+60
@@ -0,0 +1,60 @@
1 +"""Bidirectional hierarchy conversion tests (D-10, OD-01, ADR-014)."""
2 +
3 +from aram_backend.domain.hierarchy import (
4 + AccountLevels,
5 + account_level,
6 + canonical_full_code,
7 + ledger_to_pilot,
8 + pilot_to_ledger,
9 + reconstruct_full_code,
10 +)
11 +
12 +
13 +class TestLedgerToPilot:
14 + def test_evidence_based_mapping(self):
15 + levels = ledger_to_pilot(kol=14, hesab=8348, t1=117001, t2="22200000000899", row=2)
16 + assert levels.general_code == "14"
17 + assert levels.subsidiary_code == "8348"
18 + assert levels.detail1_code == "117001"
19 + assert levels.detail2_code == "22200000000899"
20 + assert levels.detail3_code == ""
21 + assert levels.detail4_code == ""
22 +
23 + def test_canonical_full_code_is_general_plus_subsidiary(self):
24 + levels = ledger_to_pilot(kol=14, hesab=8348, row=2)
25 + assert canonical_full_code(levels) == "148348"
26 +
27 + def test_leading_zeros_preserved(self):
28 + levels = ledger_to_pilot(kol="01", hesab="0101", row=2)
29 + assert levels.general_code == "01"
30 + assert levels.subsidiary_code == "0101"
31 + assert canonical_full_code(levels) == "010101"
32 +
33 + def test_account_level(self):
34 + assert account_level(ledger_to_pilot(kol=14, hesab=8348, row=2)) == "Subsidiary"
35 + deep = AccountLevels("14", "8348", "117001", "222", "3", "4")
36 + assert account_level(deep) == "Detail4"
37 +
38 + def test_reconstruct_concatenates_all_levels(self):
39 + deep = AccountLevels("14", "8348", "117001", "222", "", "")
40 + assert reconstruct_full_code(deep) == "148348117001222"
41 +
42 +
43 +class TestBidirectionalRoundTrip:
44 + def test_roundtrip(self):
45 + levels = ledger_to_pilot(kol=19, hesab=8312, t1=117001, t2="22100000571471", row=5)
46 + back = pilot_to_ledger(levels)
47 + assert back["kol"] == "19"
48 + assert back["حساب"] == "8312"
49 + assert back["T1_CODE"] == "117001"
50 + assert back["T2_CODE"] == "22100000571471"
51 + again = ledger_to_pilot(
52 + kol=back["kol"],
53 + hesab=back["حساب"],
54 + t1=back["T1_CODE"],
55 + t2=back["T2_CODE"],
56 + t3=back["T3_CODE"],
57 + t4=back["T4_CODE"],
58 + row=5,
59 + )
60 + assert again == levels
backend/tests/test_domain_money.py new
+168
@@ -0,0 +1,168 @@
1 +"""Exact-money tests (P-02, D-03, OD-03), including Hypothesis property tests."""
2 +
3 +from decimal import Decimal
4 +
5 +import pytest
6 +from hypothesis import given, settings
7 +from hypothesis import strategies as st
8 +from sqlalchemy.exc import StatementError
9 +
10 +from aram_backend.domain.money import (
11 + Rial,
12 + allocate_remainder,
13 + round_half_up,
14 +)
15 +
16 +rial = Rial()
17 +
18 +
19 +class TestRialRoundTrip:
20 + @given(st.integers(min_value=-(10**18 - 1), max_value=10**18 - 1))
21 + @settings(max_examples=300)
22 + def test_exact_roundtrip_up_to_18_digits(self, n):
23 + value = Decimal(n)
24 + stored = rial.process_bind_param(value, dialect=None)
25 + assert isinstance(stored, int)
26 + assert rial.process_result_value(stored, dialect=None) == value
27 +
28 + def test_none_roundtrip(self):
29 + assert rial.process_bind_param(None, dialect=None) is None
30 + assert rial.process_result_value(None, dialect=None) is None
31 +
32 + def test_float_rejected(self):
33 + with pytest.raises(TypeError):
34 + rial.process_bind_param(1.5, dialect=None)
35 +
36 + def test_fractional_rial_rejected(self):
37 + with pytest.raises(ValueError):
38 + rial.process_bind_param(Decimal("1.5"), dialect=None)
39 +
40 + def test_non_finite_rejected(self):
41 + with pytest.raises(ValueError):
42 + rial.process_bind_param(Decimal("NaN"), dialect=None)
43 +
44 + def test_int_and_text_accepted(self):
45 + assert rial.process_bind_param(100, dialect=None) == 100
46 + assert rial.process_bind_param("100", dialect=None) == 100
47 +
48 + def test_large_rial_no_silent_rounding(self):
49 + big = Decimal("10823163409740108")
50 + assert (
51 + rial.process_result_value(rial.process_bind_param(big, dialect=None), dialect=None)
52 + == big
53 + )
54 +
55 +
56 +class TestRoundHalfUp:
57 + def test_half_up(self):
58 + assert round_half_up(Decimal("2.5")) == Decimal("3")
59 + assert round_half_up(Decimal("2.4")) == Decimal("2")
60 + assert round_half_up(Decimal("-2.5")) == Decimal("-3")
61 +
62 + def test_places(self):
63 + assert round_half_up(Decimal("1.2345"), 2) == Decimal("1.23")
64 + assert round_half_up(Decimal("1.2355"), 2) == Decimal("1.24")
65 +
66 +
67 +class TestAllocateRemainder:
68 + def test_rows_sum_to_rounded_total(self):
69 + values = [Decimal("0.5"), Decimal("0.5"), Decimal("0.5")]
70 + total = sum(values)
71 + result = allocate_remainder(values, total, 0)
72 + assert sum(result) == round_half_up(total, 0)
73 +
74 + def test_empty(self):
75 + assert allocate_remainder([], Decimal(0), 0) == []
76 +
77 + @given(
78 + st.lists(
79 + st.integers(min_value=-(10**9), max_value=10**9).map(lambda x: Decimal(x) / 100),
80 + min_size=1,
81 + max_size=25,
82 + )
83 + )
84 + @settings(max_examples=200)
85 + def test_property_sum_matches_rounded_total(self, values):
86 + total = sum(values)
87 + for places in (0, 2):
88 + result = allocate_remainder(values, total, places)
89 + assert sum(result) == round_half_up(total, places)
90 + assert len(result) == len(values)
91 +
92 +
93 +class TestP02NoSilentRoundingGuard:
94 + """Owner-audit regression: fractional rial must fail loudly, never round."""
95 +
96 + @pytest.mark.parametrize("bad", ["1.5", "100.5", "100.0001", "0.1", "-2.25"])
97 + def test_fractional_text_rejected_not_rounded(self, bad):
98 + with pytest.raises(ValueError):
99 + rial.process_bind_param(bad, dialect=None)
100 +
101 + def test_boundary_half_rial_rejected(self):
102 + # 100.5 must NOT become 100 or 101; it must raise.
103 + with pytest.raises(ValueError):
104 + rial.process_bind_param(Decimal("100.5"), dialect=None)
105 +
106 + def test_fractional_through_orm_rejected(self, session):
107 + from aram_backend.ingestion import register_source_document
108 + from aram_backend.models import Company, FiscalYear, LedgerBalance
109 +
110 + company = Company(code="P02", name="x")
111 + session.add(company)
112 + session.flush()
113 + year = FiscalYear(company_id=company.id, year=1404)
114 + session.add(year)
115 + session.flush()
116 + source = register_source_document(
117 + session,
118 + year_id=year.id,
119 + filename="l.xlsx",
120 + document_type="general_ledger",
121 + content=b"p02",
122 + )
123 + session.flush()
124 + session.add(
125 + LedgerBalance(
126 + year_id=year.id,
127 + source_document_id=source.id,
128 + source_sheet="Source",
129 + source_row=3,
130 + account_full_code="148348",
131 + account_name="x",
132 + closing=Decimal("100.5"),
133 + )
134 + )
135 + with pytest.raises(StatementError, match="fractional rial"):
136 + session.flush()
137 + session.rollback()
138 +
139 + def test_fractional_csv_import_fails_loudly(self, session):
140 + from aram_backend.ingestion import register_source_document
141 + from aram_backend.ledger_parser import parse_general_ledger_csv
142 + from aram_backend.models import Company, FiscalYear
143 + from aram_backend.services.ledger_import import import_ledger_balances
144 +
145 + company = Company(code="P02C", name="x")
146 + session.add(company)
147 + session.flush()
148 + year = FiscalYear(company_id=company.id, year=1404)
149 + session.add(year)
150 + session.flush()
151 + source = register_source_document(
152 + session,
153 + year_id=year.id,
154 + filename="l.csv",
155 + document_type="general_ledger",
156 + content=b"p02c",
157 + )
158 + session.flush()
159 + csv = (
160 + "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
161 + "8348,14,x,1404,O,,,,,0,100.5,0,100.5\n"
162 + ).encode()
163 + records = list(parse_general_ledger_csv(csv))
164 + with pytest.raises(StatementError, match="fractional rial"):
165 + import_ledger_balances(
166 + session, year_id=year.id, source_document_id=source.id, records=records
167 + )
168 + session.rollback()
backend/tests/test_domain_normalization.py new
+92
@@ -0,0 +1,92 @@
1 +"""Tests for the single-source Persian normalization (P-03, P-04, D-04, D-05)."""
2 +
3 +from decimal import Decimal
4 +
5 +import pytest
6 +
7 +from aram_backend.domain.normalization import (
8 + NormalizationError,
9 + decimal_from_cell,
10 + normalize_code,
11 + normalize_fa,
12 +)
13 +
14 +
15 +class TestNormalizeFa:
16 + def test_arabic_letters_to_persian(self):
17 + assert normalize_fa("سودوزيان") == "سودوزیان"
18 + assert normalize_fa("وضعيت مالي") == "وضعیت مالی"
19 + assert normalize_fa("حقوق مالكانه") == "حقوق مالکانه"
20 +
21 + def test_persian_and_arabic_digits_to_latin(self):
22 + assert normalize_fa("۱۴۰۴") == "1404"
23 + assert normalize_fa("١٤٠٤") == "1404"
24 +
25 + def test_removes_nbsp_tatweel_and_controls(self):
26 + assert normalize_fa("الف\u00a0بـج\x00د") == "الفبجد"
27 +
28 + def test_preserves_zwnj_half_space(self):
29 + assert normalize_fa("دارایی\u200cها") == "دارایی\u200cها"
30 +
31 + def test_trim(self):
32 + assert normalize_fa(" سلام ") == "سلام"
33 +
34 + def test_idempotent(self):
35 + for sample in ("سودوزيان", "۱۴۰۴", "دارایی\u200cها", "وضعيت مالي"):
36 + once = normalize_fa(sample)
37 + assert normalize_fa(once) == once
38 +
39 +
40 +class TestNormalizeCode:
41 + def test_text_leading_zeros_preserved(self):
42 + assert normalize_code("0101", row=2, field="حساب") == "0101"
43 +
44 + def test_persian_digit_code_stays_text(self):
45 + assert normalize_code("۰۱۰۱", row=2, field="حساب") == "0101"
46 +
47 + def test_integer_code_exact(self):
48 + assert normalize_code(8348, row=2, field="حساب") == "8348"
49 +
50 + def test_integral_float_code(self):
51 + assert normalize_code(101.0, row=2, field="حساب") == "101"
52 +
53 + def test_non_integral_float_code_raises(self):
54 + with pytest.raises(NormalizationError):
55 + normalize_code(101.5, row=2, field="حساب")
56 +
57 + def test_bool_and_none_raise(self):
58 + with pytest.raises(NormalizationError):
59 + normalize_code(True, row=2, field="حساب")
60 + with pytest.raises(NormalizationError):
61 + normalize_code(None, row=2, field="حساب")
62 +
63 + def test_empty_text_raises(self):
64 + with pytest.raises(NormalizationError):
65 + normalize_code(" ", row=2, field="حساب")
66 +
67 +
68 +class TestDecimalFromCell:
69 + def test_float_uses_shortest_roundtrip_repr(self):
70 + # 0.1 + 0.2 must not become the binary expansion nor lose precision.
71 + assert decimal_from_cell(0.1 + 0.2, row=2, field="Debit") == Decimal(
72 + "0.30000000000000004"
73 + )
74 + assert decimal_from_cell(0.1, row=2, field="Debit") == Decimal("0.1")
75 +
76 + def test_integer_and_decimal(self):
77 + assert decimal_from_cell(5, row=2, field="Debit") == Decimal(5)
78 + assert decimal_from_cell(Decimal("1.25"), row=2, field="Debit") == Decimal("1.25")
79 +
80 + def test_persian_digits_and_separators(self):
81 + assert decimal_from_cell("۱۲۳٬۴۵۶", row=2, field="Debit") == Decimal(123456)
82 + assert decimal_from_cell("1,234.5", row=2, field="Debit") == Decimal("1234.5")
83 +
84 + def test_non_numeric_and_non_finite_raise(self):
85 + with pytest.raises(NormalizationError):
86 + decimal_from_cell("abc", row=2, field="Debit")
87 + with pytest.raises(NormalizationError):
88 + decimal_from_cell(float("nan"), row=2, field="Debit")
89 + with pytest.raises(NormalizationError):
90 + decimal_from_cell(None, row=2, field="Debit")
91 + with pytest.raises(NormalizationError):
92 + decimal_from_cell(True, row=2, field="Debit")
backend/tests/test_editing.py new
+143
@@ -0,0 +1,143 @@
1 +"""Phase 5 editability: update/delete notes, mappings, note rows (Draft-guarded).
2 +
3 +Covers the owner's requirement that codes/accounts/notes/subnotes be editable, and
4 +proves edits are refused on a locked year (D-07) with HTTP 409.
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +_BALANCED_CSV = (
10 + "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
11 + "8348,14,نقد,1404,O,,,,,0,100,0,100\n"
12 + "1001,24,پرداختنی,1404,O,,,,,0,0,100,-100\n"
13 +).encode()
14 +
15 +
16 +def _year(client):
17 + return client.post(
18 + "/api/v1/companies", json={"code": "ED", "name": "شرکت", "year": 1404}
19 + ).json()["year_id"]
20 +
21 +
22 +def _note(client, year_id, number="10", title="دارایی", statement="BS", section="Assets"):
23 + return client.post(
24 + f"/api/v1/years/{year_id}/notes",
25 + json={"note_number": number, "title": title, "statement": statement, "section": section},
26 + ).json()["note_id"]
27 +
28 +
29 +class TestNoteEditing:
30 + def test_update_note(self, api_client):
31 + y = _year(api_client)
32 + n = _note(api_client, y)
33 + r = api_client.put(
34 + f"/api/v1/years/{y}/notes/{n}", json={"title": "عنوان جدید", "section": "Liabilities"}
35 + )
36 + assert r.status_code == 200, r.text
37 + assert r.json()["title"] == "عنوان جدید"
38 +
39 + def test_delete_note_cascades_rows(self, api_client):
40 + y = _year(api_client)
41 + n = _note(api_client, y)
42 + api_client.post(
43 + f"/api/v1/years/{y}/notes/{n}/rows",
44 + json={"row_order": 0, "label": "جمع", "formula_logic": None},
45 + )
46 + r = api_client.delete(f"/api/v1/years/{y}/notes/{n}")
47 + assert r.status_code == 200, r.text
48 + assert api_client.get(f"/api/v1/notes/{n}/rows").status_code == 404
49 +
50 + def test_delete_note_with_mapping_refused(self, api_client):
51 + y = _year(api_client)
52 + n = _note(api_client, y)
53 + api_client.post(
54 + f"/api/v1/years/{y}/mappings", json={"account_code": "148348", "target_note_id": n}
55 + )
56 + r = api_client.delete(f"/api/v1/years/{y}/notes/{n}")
57 + assert r.status_code == 409
58 +
59 + def test_update_missing_note_404(self, api_client):
60 + y = _year(api_client)
61 + assert (
62 + api_client.put(f"/api/v1/years/{y}/notes/999", json={"title": "x"}).status_code == 404
63 + )
64 +
65 +
66 +class TestMappingEditing:
67 + def test_update_and_delete_mapping(self, api_client):
68 + y = _year(api_client)
69 + n1 = _note(api_client, y, "10")
70 + n2 = _note(api_client, y, "11")
71 + m = api_client.post(
72 + f"/api/v1/years/{y}/mappings", json={"account_code": "148348", "target_note_id": n1}
73 + ).json()["mapping_id"]
74 + r = api_client.put(f"/api/v1/years/{y}/mappings/{m}", json={"target_note_id": n2})
75 + assert r.status_code == 200, r.text
76 + r = api_client.delete(f"/api/v1/years/{y}/mappings/{m}")
77 + assert r.status_code == 200, r.text
78 +
79 + def test_update_mapping_to_foreign_note_404(self, api_client):
80 + y = _year(api_client)
81 + n = _note(api_client, y)
82 + m = api_client.post(
83 + f"/api/v1/years/{y}/mappings", json={"account_code": "148348", "target_note_id": n}
84 + ).json()["mapping_id"]
85 + assert (
86 + api_client.put(
87 + f"/api/v1/years/{y}/mappings/{m}", json={"target_note_id": 999}
88 + ).status_code
89 + == 404
90 + )
91 +
92 +
93 +class TestNoteRowEditing:
94 + def test_update_row_formula_valid_and_invalid(self, api_client):
95 + y = _year(api_client)
96 + n = _note(api_client, y)
97 + row = api_client.post(
98 + f"/api/v1/years/{y}/notes/{n}/rows",
99 + json={"row_order": 0, "label": "جمع", "formula_logic": None},
100 + ).json()["row_id"]
101 + r = api_client.put(
102 + f"/api/v1/years/{y}/notes/{n}/rows/{row}",
103 + json={"label": "جمع کل", "formula_logic": 'acct("148348")'},
104 + )
105 + assert r.status_code == 200, r.text
106 + bad = api_client.put(
107 + f"/api/v1/years/{y}/notes/{n}/rows/{row}", json={"formula_logic": "acct("}
108 + )
109 + assert bad.status_code == 422
110 +
111 + def test_delete_row(self, api_client):
112 + y = _year(api_client)
113 + n = _note(api_client, y)
114 + row = api_client.post(
115 + f"/api/v1/years/{y}/notes/{n}/rows",
116 + json={"row_order": 0, "label": "جمع", "formula_logic": None},
117 + ).json()["row_id"]
118 + assert api_client.delete(f"/api/v1/years/{y}/notes/{n}/rows/{row}").status_code == 200
119 +
120 +
121 +class TestLockedYearEditing:
122 + def test_edit_locked_year_refused_409(self, api_client):
123 + # Bootstrap admin, import a balanced ledger, map, approve, lock.
124 + api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
125 + y = _year(api_client)
126 + api_client.post(
127 + f"/api/v1/years/{y}/ledger", files={"file": ("ledger.csv", _BALANCED_CSV, "text/csv")}
128 + )
129 + n_a = _note(api_client, y, "6", "نقد", "BS", "Assets")
130 + n_l = _note(api_client, y, "10", "پرداختنی", "BS", "Liabilities")
131 + api_client.post(
132 + f"/api/v1/years/{y}/mappings", json={"account_code": "148348", "target_note_id": n_a}
133 + )
134 + api_client.post(
135 + f"/api/v1/years/{y}/mappings", json={"account_code": "241001", "target_note_id": n_l}
136 + )
137 + ap = api_client.post(f"/api/v1/years/{y}/approve", json={"actor": "root"})
138 + assert ap.status_code == 200 and ap.json()["approved"] is True, ap.text
139 + lk = api_client.post(f"/api/v1/years/{y}/lock", json={"actor": "root"})
140 + assert lk.status_code == 200, lk.text
141 + # Editing a note on the locked year is refused by the D-07 guard.
142 + r = api_client.put(f"/api/v1/years/{y}/notes/{n_a}", json={"title": "تغییر"})
143 + assert r.status_code == 409, r.text
backend/tests/test_formula.py new
+78
@@ -0,0 +1,78 @@
1 +"""Phase 3: safe formula grammar (ADR-020) — parsing, evaluation, and safety."""
2 +
3 +from __future__ import annotations
4 +
5 +from decimal import Decimal
6 +
7 +import pytest
8 +
9 +from aram_backend.domain.formula import FormulaError, eval_formula
10 +
11 +
12 +def _resolver(name, args):
13 + if name == "acct":
14 + return Decimal(100)
15 + if name == "sum":
16 + return sum((Decimal(a) for a in args), Decimal(0))
17 + if name == "abs":
18 + return abs(Decimal(args[0]))
19 + if name == "row":
20 + return Decimal(int(args[0])) * 10
21 + raise FormulaError(f"unknown function {name}")
22 +
23 +
24 +@pytest.mark.parametrize(
25 + ("formula", "expected"),
26 + [
27 + ("1 + 2 * 3", Decimal(7)),
28 + ("(1 + 2) * 3", Decimal(9)),
29 + ("-5 + 3", Decimal(-2)),
30 + ("1.5 + 2.5", Decimal(4)),
31 + ("10 / 2", Decimal(5)),
32 + ("sum(1, 2, 3)", Decimal(6)),
33 + ("abs(-5)", Decimal(5)),
34 + ('acct("148348")', Decimal(100)),
35 + ("row(3)", Decimal(30)),
36 + ('sum(acct("148348"), 5)', Decimal(105)),
37 + ],
38 +)
39 +def test_evaluates(formula, expected):
40 + assert eval_formula(formula, _resolver) == expected
41 +
42 +
43 +@pytest.mark.parametrize(
44 + "formula",
45 + [
46 + "",
47 + " ",
48 + "1 @ 2",
49 + "foo",
50 + "1 +",
51 + "(1 + 2",
52 + "1 / 0",
53 + "__import__('os')",
54 + 'acct("x"); import os',
55 + "1 .. 2",
56 + ],
57 +)
58 +def test_rejects_unsafe_or_invalid(formula):
59 + with pytest.raises(FormulaError):
60 + eval_formula(formula, _resolver)
61 +
62 +
63 +def test_unknown_function_fails_closed():
64 + with pytest.raises(FormulaError):
65 + eval_formula('evil("x")', _resolver)
66 +
67 +
68 +def test_string_literal_passed_to_resolver():
69 + seen = {}
70 +
71 + def resolver(name, args):
72 + seen["name"] = name
73 + seen["args"] = args
74 + return Decimal(0)
75 +
76 + eval_formula('acct("148348", "debit")', resolver)
77 + assert seen["name"] == "acct"
78 + assert seen["args"] == ("148348", "debit")
backend/tests/test_golden.py new
+97
@@ -0,0 +1,97 @@
1 +"""Phase 4 acceptance: golden comparison (rial-for-rial), all 4 statements, 1403."""
2 +
3 +from __future__ import annotations
4 +
5 +from pathlib import Path
6 +
7 +import pytest
8 +
9 +from aram_backend.models import StatementType
10 +from aram_backend.services.golden import (
11 + aggregate_source_by_note,
12 + compare_year,
13 + read_official_notes,
14 + write_discrepancies,
15 +)
16 +from aram_backend.services.statement_build import ALL_STATEMENTS, build_statements
17 +from test_statement_build import _balance, _map, _note, _setup
18 +
19 +_REPO_ROOT = Path(__file__).resolve().parents[2]
20 +_SRC_1404 = _REPO_ROOT / "data" / "source_ledgers" / "source_1404.xlsx"
21 +_OFF_1404 = _REPO_ROOT / "data" / "official_statements" / "financial_1404.xlsx"
22 +_SRC_1403 = _REPO_ROOT / "data" / "source_ledgers" / "source_1403.xlsx"
23 +_OFF_1403 = _REPO_ROOT / "data" / "official_statements" / "financial_1403.xlsx"
24 +
25 +# Balance-sheet asset notes proven to reproduce the official figures exactly.
26 +_BS_ASSET_NOTES = {"10", "11", "12-1", "12-2", "13", "14", "15"}
27 +
28 +
29 +@pytest.mark.skipif(not (_SRC_1404.exists() and _OFF_1404.exists()), reason="canonical 1404 data absent")
30 +class TestGolden1404:
31 + def test_bs_asset_notes_match_official_exactly(self):
32 + comparisons = compare_year(_SRC_1404, _OFF_1404, 1404)
33 + bs = {c.note: c for c in comparisons if c.statement == "BS"}
34 + for note in _BS_ASSET_NOTES:
35 + assert note in bs, f"official BS missing note {note}"
36 + assert bs[note].match, f"note {note}: {bs[note].source_million_rounded} != {bs[note].official_million}"
37 +
38 + def test_aggregate_source_returns_real_totals(self):
39 + sums = aggregate_source_by_note(_SRC_1404, 1404)
40 + assert sums["10"] > 0
41 + assert "15" in sums
42 +
43 + def test_official_reader_extracts_notes(self):
44 + notes = read_official_notes(_OFF_1404, "وضعيت مالي", 1404)
45 + assert notes.get("10") == 673740637
46 + assert notes.get("15") == 19951136
47 +
48 + def test_discrepancies_written_with_summary(self, tmp_path):
49 + comparisons = compare_year(_SRC_1404, _OFF_1404, 1404)
50 + out = tmp_path / "discrepancies.json"
51 + summary = write_discrepancies(comparisons, out)
52 + assert summary["total"] == len(comparisons)
53 + assert summary["matched"] + summary["discrepancies"] == summary["total"]
54 + assert summary["matched"] >= len(_BS_ASSET_NOTES)
55 + import json
56 +
57 + payload = json.loads(out.read_text(encoding="utf-8"))
58 + assert "discrepancies" in payload
59 + for d in payload["discrepancies"]:
60 + assert d["match"] is False
61 +
62 +
63 +@pytest.mark.skipif(not (_SRC_1403.exists() and _OFF_1403.exists()), reason="canonical 1403 data absent")
64 +class TestGolden1403:
65 + def test_1403_aggregate_and_compare_run(self):
66 + sums = aggregate_source_by_note(_SRC_1403, 1403)
67 + assert len(sums) > 0
68 + comparisons = compare_year(_SRC_1403, _OFF_1403, 1403)
69 + assert len(comparisons) > 0
70 + # Year continuity: at least some 1403 BS notes reproduce the official figures.
71 + assert any(c.match for c in comparisons if c.statement == "BS")
72 +
73 +
74 +class TestAllFourStatements:
75 + def test_build_bs_is_cf_eq(self, session):
76 + year, source = _setup(session)
77 + _balance(session, year, source, "148348", 100, 3)
78 + _balance(session, year, source, "541001", -250, 4)
79 + _balance(session, year, source, "741001", 50, 5)
80 + _balance(session, year, source, "341001", -40, 6)
81 + n_bs = _note(session, year, "10", "دارایی", "BS", "Assets")
82 + n_is = _note(session, year, "5", "درآمد", "IS", "Revenue")
83 + n_cf = _note(session, year, "30", "عملیاتی", "CF", "Operating")
84 + n_eq = _note(session, year, "12", "سرمایه", "EQ", "Equity")
85 + _map(session, year, "148348", n_bs)
86 + _map(session, year, "541001", n_is)
87 + _map(session, year, "741001", n_cf)
88 + _map(session, year, "341001", n_eq)
89 + session.flush()
90 + result = build_statements(session, year.id, statement_types=ALL_STATEMENTS)
91 + session.commit()
92 + assert {s.statement_type for s in result.statements} == {
93 + StatementType.BALANCE_SHEET,
94 + StatementType.INCOME_STATEMENT,
95 + StatementType.CASH_FLOW,
96 + StatementType.EQUITY,
97 + }
backend/tests/test_immutability.py new
+194
@@ -0,0 +1,194 @@
1 +"""D-07 acceptance: locked-year immutability via DB triggers, reopen, audit chain.
2 +
3 +The key guarantee (booklet D3, P-08): a LOCKED year is immutable even through raw
4 +SQL, bypassing the ORM. These tests issue raw statements to prove the database
5 +itself enforces the rule.
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +import pytest
11 +from sqlalchemy import text
12 +from sqlalchemy.exc import IntegrityError
13 +
14 +from aram_backend.models import (
15 + Company,
16 + FiscalYear,
17 + FiscalYearStatus,
18 + ReopenRequest,
19 +)
20 +from aram_backend.services.audit import append_entry, verify_chain
21 +
22 +
23 +def _locked_year(session):
24 + company = Company(code="IMM", name="شرکت")
25 + session.add(company)
26 + session.flush()
27 + year = FiscalYear(company_id=company.id, year=1404)
28 + session.add(year)
29 + session.flush()
30 + year.status = FiscalYearStatus.APPROVED
31 + session.commit()
32 + year.status = FiscalYearStatus.LOCKED
33 + session.commit()
34 + return year
35 +
36 +
37 +def _draft_year(session):
38 + company = Company(code="IMM", name="شرکت")
39 + session.add(company)
40 + session.flush()
41 + year = FiscalYear(company_id=company.id, year=1404)
42 + session.add(year)
43 + session.commit()
44 + return year
45 +
46 +
47 +def _lock(session, year):
48 + year.status = FiscalYearStatus.APPROVED
49 + session.commit()
50 + year.status = FiscalYearStatus.LOCKED
51 + session.commit()
52 +
53 +
54 +def _seed_balance(session, year):
55 + session.execute(
56 + text(
57 + "INSERT INTO source_documents (year_id, filename, file_hash, document_type, uploaded_at, created_at, updated_at) "
58 + "VALUES (:y, 'l.xlsx', 'h1', 'general_ledger', '2026-01-01', '2026-01-01', '2026-01-01')"
59 + ),
60 + {"y": year.id},
61 + )
62 + sd_id = session.execute(
63 + text("SELECT id FROM source_documents WHERE year_id=:y"), {"y": year.id}
64 + ).scalar()
65 + session.execute(
66 + text(
67 + "INSERT INTO ledger_balances (year_id, source_document_id, source_sheet, source_row, import_version, "
68 + "account_full_code, general_code, subsidiary_code, detail1_code, detail2_code, detail3_code, detail4_code, "
69 + "account_name, opening, debit, credit, closing, entry_type, created_at, updated_at) "
70 + "VALUES (:y, :sd, 'Source', 3, 1, '148348', '14', '8348', '', '', '', '', "
71 + "'نمونه', 0, 100, 0, 100, 'O', '2026-01-01', '2026-01-01')"
72 + ),
73 + {"y": year.id, "sd": sd_id},
74 + )
75 + session.commit()
76 +
77 +
78 +class TestRawSqlImmutability:
79 + def test_locked_year_blocks_raw_insert(self, session):
80 + year = _locked_year(session)
81 + with pytest.raises(IntegrityError, match="locked"):
82 + session.execute(
83 + text(
84 + "INSERT INTO ledger_balances (year_id, source_document_id, source_sheet, source_row, "
85 + "import_version, account_full_code, account_name, opening, debit, credit, closing, created_at, updated_at) "
86 + "VALUES (:y, 1, 'Source', 4, 1, '148349', 'x', 0, 0, 0, 0, '2026-01-01', '2026-01-01')"
87 + ),
88 + {"y": year.id},
89 + )
90 + session.rollback()
91 +
92 + def test_locked_year_blocks_raw_update(self, session):
93 + year = _draft_year(session)
94 + _seed_balance(session, year)
95 + _lock(session, year)
96 + with pytest.raises(IntegrityError, match="locked"):
97 + session.execute(
98 + text("UPDATE ledger_balances SET debit = 999 WHERE year_id = :y"),
99 + {"y": year.id},
100 + )
101 + session.rollback()
102 + # Value unchanged.
103 + assert (
104 + session.execute(
105 + text("SELECT debit FROM ledger_balances WHERE year_id=:y"), {"y": year.id}
106 + ).scalar()
107 + == 100
108 + )
109 +
110 + def test_locked_year_blocks_raw_delete(self, session):
111 + year = _draft_year(session)
112 + _seed_balance(session, year)
113 + _lock(session, year)
114 + with pytest.raises(IntegrityError, match="locked"):
115 + session.execute(text("DELETE FROM ledger_balances WHERE year_id = :y"), {"y": year.id})
116 + session.rollback()
117 + assert (
118 + session.execute(
119 + text("SELECT COUNT(*) FROM ledger_balances WHERE year_id=:y"), {"y": year.id}
120 + ).scalar()
121 + == 1
122 + )
123 +
124 + def test_draft_year_allows_writes(self, session):
125 + company = Company(code="DFT", name="x")
126 + session.add(company)
127 + session.flush()
128 + year = FiscalYear(company_id=company.id, year=1404)
129 + session.add(year)
130 + session.commit()
131 + session.execute(
132 + text(
133 + "INSERT INTO source_documents (year_id, filename, file_hash, document_type, uploaded_at, created_at, updated_at) "
134 + "VALUES (:y, 'l.xlsx', 'h2', 'general_ledger', '2026-01-01', '2026-01-01', '2026-01-01')"
135 + ),
136 + {"y": year.id},
137 + )
138 + session.commit() # must not raise
139 +
140 +
141 +class TestReopen:
142 + def test_reopen_without_request_blocked(self, session):
143 + year = _locked_year(session)
144 + year.status = FiscalYearStatus.APPROVED
145 + with pytest.raises(ValueError, match="ReopenRequest"):
146 + session.commit()
147 + session.rollback()
148 +
149 + def test_reopen_with_approved_request_allowed(self, session):
150 + year = _locked_year(session)
151 + req = ReopenRequest(year_id=year.id, reason="اصلاح", status="approved", approved_by="owner")
152 + session.add(req)
153 + session.commit()
154 + year.status = FiscalYearStatus.APPROVED
155 + session.commit()
156 + assert year.status == FiscalYearStatus.APPROVED
157 +
158 + def test_reopen_via_raw_sql_requires_request(self, session):
159 + year = _locked_year(session)
160 + with pytest.raises(IntegrityError, match="transition"):
161 + session.execute(
162 + text("UPDATE fiscal_years SET status='APPROVED' WHERE id=:y"), {"y": year.id}
163 + )
164 + session.rollback()
165 +
166 +
167 +class TestAuditChain:
168 + def test_chain_builds_and_verifies(self, session):
169 + append_entry(session, action="import", actor="u", payload={"rows": 10})
170 + append_entry(session, action="approve", actor="u", payload={})
171 + session.commit()
172 + assert verify_chain(session) is True
173 +
174 + def test_tamper_detected(self, session):
175 + append_entry(session, action="import", actor="u", payload={"rows": 10})
176 + append_entry(session, action="approve", actor="u", payload={})
177 + session.commit()
178 + # Simulate an attacker with DB access who disables the append-only trigger
179 + # and corrupts a past payload hash. verify_chain must still detect it —
180 + # an independent tamper-evidence layer beyond the trigger.
181 + session.execute(text("DROP TRIGGER aram_audit_update"))
182 + session.execute(text("UPDATE audit_entries SET payload_hash='deadbeef' WHERE id=1"))
183 + session.commit()
184 + assert verify_chain(session) is False
185 +
186 + def test_audit_append_only_via_raw_sql(self, session):
187 + append_entry(session, action="import", actor="u", payload={})
188 + session.commit()
189 + with pytest.raises(IntegrityError, match="append-only"):
190 + session.execute(text("UPDATE audit_entries SET actor='hacker' WHERE id=1"))
191 + session.rollback()
192 + with pytest.raises(IntegrityError, match="append-only"):
193 + session.execute(text("DELETE FROM audit_entries WHERE id=1"))
194 + session.rollback()
backend/tests/test_ingestion.py
+3 -3
@@ -127,7 +127,7 @@ def test_duplicate_registration_different_document_type_rejected(session):
127 "content": b"safe-test-bytes-conflict",
128 }
129
130 - first = register_source_document(session, **arguments)
130 + register_source_document(session, **arguments)
131 session.commit()
132
133 conflict_arguments = arguments.copy()
@@ -151,7 +151,7 @@ def test_duplicate_registration_different_filename_rejected(session):
151 "content": b"safe-test-bytes-conflict-2",
152 }
153
154 - first = register_source_document(session, **arguments)
154 + register_source_document(session, **arguments)
155 session.commit()
156
157 conflict_arguments = arguments.copy()
@@ -175,7 +175,7 @@ def test_duplicate_registration_different_both_rejected(session):
175 "content": b"safe-test-bytes-conflict-3",
176 }
177
178 - first = register_source_document(session, **arguments)
178 + register_source_document(session, **arguments)
179 session.commit()
180
181 conflict_arguments = arguments.copy()
backend/tests/test_ledger_balance.py new
+221
@@ -0,0 +1,221 @@
1 +"""D-01/D-03 acceptance: LedgerBalance persistence with exact integer rial.
2 +
3 +Proves a small-sample import stores and reads exact Decimal values, aggregates
4 +duplicate accounts, persists money as BIGINT integers (no float), and that the
5 +migration upgrades and downgrades cleanly (P-11).
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +import io
11 +import os
12 +import subprocess
13 +import sys
14 +from decimal import Decimal
15 +from pathlib import Path
16 +
17 +import pytest
18 +from openpyxl import Workbook
19 +from sqlalchemy import text
20 +from sqlalchemy.exc import IntegrityError
21 +
22 +from aram_backend.ingestion import register_source_document
23 +from aram_backend.ledger_parser import parse_general_ledger
24 +from aram_backend.models import Company, FiscalYear, LedgerBalance
25 +from aram_backend.services.ledger_import import import_ledger_balances
26 +
27 +REPO_ROOT = Path(__file__).resolve().parents[2]
28 +BACKEND_DIR = REPO_ROOT / "backend"
29 +
30 +HEADERS = [
31 + "حساب",
32 + "kol",
33 + "ACCOUNT_NAME",
34 + "year",
35 + "نوع",
36 + "T1_CODE",
37 + "T2_CODE",
38 + "T3_CODE",
39 + "T4_CODE",
40 + "OPENING",
41 + "Debit",
42 + "Credit",
43 + "CLOSING",
44 +]
45 +
46 +
47 +def _ledger_bytes(*rows):
48 + wb = Workbook()
49 + ws = wb.active
50 + ws.title = "Source"
51 + ws.append(["source ledger"])
52 + ws.append(HEADERS)
53 + for r in rows:
54 + ws.append(r)
55 + buf = io.BytesIO()
56 + wb.save(buf)
57 + wb.close()
58 + return buf.getvalue()
59 +
60 +
61 +def _row(code, kol, opening=0, debit=0, credit=0, closing=0, name="حساب نمونه"):
62 + return [code, kol, name, 1404, "O", None, None, None, None, opening, debit, credit, closing]
63 +
64 +
65 +def _make_year(session):
66 + company = Company(code="C1", name="شرکت نمونه")
67 + session.add(company)
68 + session.flush()
69 + year = FiscalYear(company_id=company.id, year=1404)
70 + session.add(year)
71 + session.flush()
72 + return year
73 +
74 +
75 +def _import(session, year, content):
76 + doc = register_source_document(
77 + session,
78 + year_id=year.id,
79 + filename="ledger.xlsx",
80 + document_type="general_ledger",
81 + content=content,
82 + )
83 + records = list(parse_general_ledger(content))
84 + count = import_ledger_balances(
85 + session, year_id=year.id, source_document_id=doc.id, records=records
86 + )
87 + session.commit()
88 + return count
89 +
90 +
91 +class TestLedgerBalanceImport:
92 + def test_small_sample_exact_roundtrip(self, session):
93 + year = _make_year(session)
94 + content = _ledger_bytes(_row("8348", "14", opening=100, debit=50, credit=20, closing=130))
95 + count = _import(session, year, content)
96 + assert count == 1
97 + balance = session.query(LedgerBalance).filter_by(year_id=year.id).one()
98 + assert balance.account_full_code == "148348"
99 + assert balance.general_code == "14"
100 + assert balance.subsidiary_code == "8348"
101 + assert balance.opening == Decimal(100)
102 + assert balance.debit == Decimal(50)
103 + assert balance.credit == Decimal(20)
104 + assert balance.closing == Decimal(130)
105 + assert all(
106 + isinstance(getattr(balance, f), Decimal)
107 + for f in ("opening", "debit", "credit", "closing")
108 + )
109 +
110 + def test_large_rial_no_silent_rounding(self, session):
111 + # Insert via the ORM (bypassing Excel's own float64 cell storage, which
112 + # cannot represent integers above 2**53). This proves the D-03 fix: the
113 + # Rial BIGINT column stores large rial exactly, unlike Numeric-on-SQLite.
114 + year = _make_year(session)
115 + doc = register_source_document(
116 + session,
117 + year_id=year.id,
118 + filename="l.xlsx",
119 + document_type="general_ledger",
120 + content=_ledger_bytes(_row("8348", "14")),
121 + )
122 + big = Decimal("10823163409740108") # > 2**53, the canonical total debit
123 + session.add(
124 + LedgerBalance(
125 + year_id=year.id,
126 + source_document_id=doc.id,
127 + source_sheet="Source",
128 + source_row=3,
129 + account_full_code="148348",
130 + general_code="14",
131 + subsidiary_code="8348",
132 + account_name="x",
133 + debit=big,
134 + credit=big,
135 + )
136 + )
137 + session.commit()
138 + balance = session.query(LedgerBalance).filter_by(year_id=year.id).one()
139 + assert balance.debit == big
140 + # Raw column value must be an integer (BIGINT), not a float.
141 + raw = session.execute(text("SELECT debit FROM ledger_balances")).scalar_one()
142 + assert isinstance(raw, int)
143 + assert raw == int(big)
144 +
145 + def test_duplicate_accounts_stored_raw_and_aggregated_in_service(self, session):
146 + # D3/P-01: raw rows are preserved (one per source row); aggregation is a
147 + # compute-layer concern, never done on import.
148 + from aram_backend.services.ledger_aggregate import aggregate_by_account
149 +
150 + year = _make_year(session)
151 + content = _ledger_bytes(
152 + _row("8348", "14", debit=100, closing=100),
153 + _row("8348", "14", debit=200, closing=200),
154 + )
155 + count = _import(session, year, content)
156 + assert count == 2 # two raw rows, NOT collapsed
157 + rows = (
158 + session.query(LedgerBalance)
159 + .filter_by(year_id=year.id)
160 + .order_by(LedgerBalance.source_row)
161 + .all()
162 + )
163 + assert [r.source_row for r in rows] == [3, 4]
164 + assert [r.debit for r in rows] == [Decimal(100), Decimal(200)]
165 + # Aggregation happens in the service layer.
166 + totals = aggregate_by_account(session, year.id)
167 + assert totals["148348"].debit == Decimal(300)
168 + assert totals["148348"].closing == Decimal(300)
169 + assert totals["148348"].row_count == 2
170 +
171 + def test_uniqueness_per_import_version(self, session):
172 + year = _make_year(session)
173 + content = _ledger_bytes(_row("8348", "14"))
174 + _import(session, year, content)
175 + # Re-importing the same version conflicts; a new version is allowed.
176 + doc = session.query(LedgerBalance).first().source_document_id
177 + records = list(parse_general_ledger(content))
178 + with pytest.raises(IntegrityError):
179 + import_ledger_balances(
180 + session,
181 + year_id=year.id,
182 + source_document_id=doc,
183 + records=records,
184 + import_version=1,
185 + )
186 + session.rollback()
187 +
188 +
189 +class TestMigrationRoundTrip:
190 + def test_upgrade_downgrade_clean(self, tmp_path):
191 + db = tmp_path / "mig.db"
192 + env = {**os.environ, "ARAM_DATABASE_URL": f"sqlite:///{db}"}
193 + up = subprocess.run(
194 + [sys.executable, "-m", "alembic", "upgrade", "head"],
195 + cwd=BACKEND_DIR,
196 + env=env,
197 + capture_output=True,
198 + text=True,
199 + )
200 + assert up.returncode == 0, up.stderr
201 + # ledger_balances exists and mapped_total is BIGINT after upgrade.
202 + import sqlite3
203 +
204 + con = sqlite3.connect(db)
205 + tables = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
206 + assert "ledger_balances" in tables
207 + cols = {r[1]: r[2] for r in con.execute("PRAGMA table_info(statement_lines)")}
208 + assert cols["mapped_total"].upper() in ("BIGINT", "INTEGER")
209 + con.close()
210 + down = subprocess.run(
211 + [sys.executable, "-m", "alembic", "downgrade", "base"],
212 + cwd=BACKEND_DIR,
213 + env=env,
214 + capture_output=True,
215 + text=True,
216 + )
217 + assert down.returncode == 0, down.stderr
218 + con = sqlite3.connect(db)
219 + tables = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
220 + assert "ledger_balances" not in tables
221 + con.close()
backend/tests/test_ledger_csv.py new
+101
@@ -0,0 +1,101 @@
1 +"""D-06 acceptance: CSV ledger support with the same rules as XLSX."""
2 +
3 +from __future__ import annotations
4 +
5 +import pytest
6 +
7 +from aram_backend.ledger_parser import (
8 + LedgerParseError,
9 + parse_general_ledger_csv,
10 + parse_ledger,
11 +)
12 +
13 +HEADER = [
14 + "حساب",
15 + "kol",
16 + "ACCOUNT_NAME",
17 + "year",
18 + "نوع",
19 + "T1_CODE",
20 + "T2_CODE",
21 + "T3_CODE",
22 + "T4_CODE",
23 + "OPENING",
24 + "Debit",
25 + "Credit",
26 + "CLOSING",
27 +]
28 +ROW = ["0101", "14", "نمونه حساب", "۱۴۰۴", "O", "", "", "", "", "۰", "۱۲۵۰", "۰", "۱۲۵۰"]
29 +
30 +
31 +def _csv(header, row, sep=",", encoding="utf-8"):
32 + return (sep.join(header) + "\n" + sep.join(row) + "\n").encode(encoding)
33 +
34 +
35 +def test_csv_utf8_parses_with_normalization():
36 + content = _csv(HEADER, ROW)
37 + records = list(parse_general_ledger_csv(content))
38 + assert len(records) == 1
39 + r = records[0]
40 + assert r.account_code == "0101"
41 + assert r.source_year == 1404
42 + assert str(r.debit) == "1250"
43 + assert r.account_name == "نمونه حساب"
44 +
45 +
46 +def test_csv_utf8_bom():
47 + content = b"\xef\xbb\xbf" + _csv(HEADER, ROW)
48 + assert list(parse_general_ledger_csv(content))[0].account_code == "0101"
49 +
50 +
51 +def test_csv_windows_1256():
52 + # cp1256 cannot encode Persian digits; a Windows-1256 export uses ASCII numerals.
53 + row = ROW.copy()
54 + row[3] = "1404"
55 + row[9] = row[11] = row[12] = "0"
56 + row[10] = "1250"
57 + content = _csv(HEADER, row, encoding="cp1256")
58 + assert list(parse_general_ledger_csv(content))[0].debit == 1250
59 +
60 +
61 +def test_csv_tab_delimiter():
62 + content = _csv(HEADER, ROW, sep="\t")
63 + assert list(parse_general_ledger_csv(content))[0].account_code == "0101"
64 +
65 +
66 +def test_csv_semicolon_delimiter():
67 + content = _csv(HEADER, ROW, sep=";")
68 + assert list(parse_general_ledger_csv(content))[0].account_code == "0101"
69 +
70 +
71 +def test_csv_leading_zeros_preserved():
72 + row = ROW.copy()
73 + row[0] = "۰۰۱۲"
74 + content = _csv(HEADER, row)
75 + assert list(parse_general_ledger_csv(content))[0].account_code == "0012"
76 +
77 +
78 +def test_csv_missing_required_header_raises():
79 + header = [h for h in HEADER if h != "Debit"]
80 + row = ROW[:5] + ROW[6:]
81 + content = _csv(header, row)
82 + with pytest.raises(LedgerParseError, match="missing required headers"):
83 + list(parse_general_ledger_csv(content))
84 +
85 +
86 +def test_csv_empty_raises():
87 + with pytest.raises(LedgerParseError, match="empty"):
88 + list(parse_general_ledger_csv(b""))
89 +
90 +
91 +def test_parse_ledger_routes_by_extension():
92 + content = _csv(HEADER, ROW)
93 + assert list(parse_ledger(content, "ledger.csv"))[0].account_code == "0101"
94 + with pytest.raises(LedgerParseError, match="only .xlsx and .csv"):
95 + list(parse_ledger(content, "ledger.txt"))
96 +
97 +
98 +def test_csv_streaming_is_iterator():
99 + content = _csv(HEADER, ROW)
100 + result = parse_general_ledger_csv(content)
101 + assert hasattr(result, "__next__")
backend/tests/test_ledger_parser.py
-1
@@ -6,7 +6,6 @@ from openpyxl import Workbook
6
7 from aram_backend.ledger_parser import LedgerParseError, parse_general_ledger
8
9 -
9 HEADERS = [
10 "حساب",
11 "ACCOUNT_NAME",
backend/tests/test_mapping_workflow.py new
+291
@@ -0,0 +1,291 @@
1 +"""Phase 2 acceptance: mapping Excel I/O, unknown queue, approval gate, carry-forward."""
2 +
3 +from __future__ import annotations
4 +
5 +from io import BytesIO
6 +
7 +import pytest
8 +from openpyxl import load_workbook
9 +
10 +from aram_backend.models import Company, FiscalYear, FiscalYearStatus, MappingRule, NoteDefinition
11 +from aram_backend.services.approval import ApprovalError, approve_year
12 +from aram_backend.services.mapping_io import (
13 + export_mappings_workbook,
14 + import_mappings_workbook,
15 +)
16 +from aram_backend.services.mapping_workflow import (
17 + CarryForwardError,
18 + carry_forward_mappings,
19 + unknown_accounts,
20 +)
21 +from test_statement_build import _balance, _map, _note, _setup
22 +
23 +
24 +def _balanced_mapped(session):
25 + """A ledger that satisfies C-01..C-04 once mapped (debit==credit, sum closing 0)."""
26 + year, source = _setup(session)
27 + _balance(session, year, source, "148348", 100, 3) # asset, debit 100
28 + _balance(session, year, source, "241001", -60, 4) # liability, credit 60
29 + _balance(session, year, source, "341001", -40, 5) # equity, credit 40
30 + n_a = _note(session, year, "6", "نقد", "BS", "Assets")
31 + n_l = _note(session, year, "10", "پرداختنی", "BS", "Liabilities")
32 + n_e = _note(session, year, "12", "سرمایه", "BS", "Equity")
33 + _map(session, year, "148348", n_a)
34 + _map(session, year, "241001", n_l)
35 + _map(session, year, "341001", n_e)
36 + session.flush()
37 + return year
38 +
39 +
40 +class TestMappingIo:
41 + def test_export_import_roundtrip(self, session):
42 + year = _balanced_mapped(session)
43 + data = export_mappings_workbook(session, year.id)
44 + wb = load_workbook(BytesIO(data))
45 + ws = wb["Mappings"]
46 + rows = list(ws.iter_rows(values_only=True))
47 + assert rows[0][0] == "account_code"
48 + assert len(rows) == 4 # header + 3 mappings
49 + wb.close()
50 +
51 + # Import into a fresh year reproduces the mappings.
52 + company = Company(code="RT", name="x")
53 + session.add(company)
54 + session.flush()
55 + year2 = FiscalYear(company_id=company.id, year=1405)
56 + session.add(year2)
57 + session.flush()
58 + result = import_mappings_workbook(session, year2.id, data)
59 + session.commit()
60 + assert result.created == 3
61 + assert result.notes_created == 3
62 + assert not result.errors
63 + rules = session.query(MappingRule).filter_by(year_id=year2.id).count()
64 + assert rules == 3
65 +
66 + def test_import_invalid_row_reported_not_committed(self, session):
67 + year, _ = _setup(session)
68 + wb = load_workbook(BytesIO(export_mappings_workbook(session, year.id)))
69 + # Build a workbook with one valid + one invalid row.
70 + from openpyxl import Workbook
71 +
72 + out = Workbook()
73 + ws = out.active
74 + ws.title = "Mappings"
75 + ws.append(
76 + [
77 + "account_code",
78 + "account_name",
79 + "target_note_number",
80 + "statement",
81 + "section",
82 + "mapping_type",
83 + ]
84 + )
85 + ws.append(["148348", "نقد", "6", "BS", "Assets", "closing"])
86 + ws.append(["999999", "بد", "7", "INVALID", "Assets", "closing"])
87 + buf = BytesIO()
88 + out.save(buf)
89 + wb.close()
90 + result = import_mappings_workbook(session, year.id, buf.getvalue())
91 + session.commit()
92 + assert result.created == 1
93 + assert len(result.errors) == 1
94 + assert "invalid statement" in result.errors[0]
95 +
96 +
97 +class TestUnknownQueue:
98 + def test_queue_lists_unmapped_active_accounts(self, session):
99 + year, source = _setup(session)
100 + _balance(session, year, source, "148348", 100, 3)
101 + _balance(session, year, source, "241001", -60, 4)
102 + session.flush()
103 + queue = unknown_accounts(session, year.id)
104 + codes = {item["account_full_code"] for item in queue}
105 + assert codes == {"148348", "241001"}
106 +
107 + def test_mapping_removes_from_queue(self, session):
108 + year, source = _setup(session)
109 + _balance(session, year, source, "148348", 100, 3)
110 + note = _note(session, year, "6", "نقد", "BS", "Assets")
111 + _map(session, year, "148348", note)
112 + session.flush()
113 + assert unknown_accounts(session, year.id) == []
114 +
115 +
116 +class TestApproval:
117 + def test_approval_blocked_by_unmapped(self, session):
118 + year, source = _setup(session)
119 + _balance(session, year, source, "148348", 100, 3)
120 + session.flush()
121 + result = approve_year(session, year.id)
122 + assert not result.approved
123 + assert any(r.code == "C-04" for r in result.blocking)
124 + assert year.status == FiscalYearStatus.DRAFT
125 +
126 + def test_approval_succeeds_on_clean_ledger(self, session):
127 + year = _balanced_mapped(session)
128 + result = approve_year(session, year.id, actor="reviewer")
129 + session.commit()
130 + assert result.approved
131 + assert year.status == FiscalYearStatus.APPROVED
132 + from aram_backend.services.audit import verify_chain
133 +
134 + assert verify_chain(session)
135 +
136 + def test_approval_rejected_on_non_draft(self, session):
137 + year = _balanced_mapped(session)
138 + approve_year(session, year.id)
139 + session.commit()
140 + with pytest.raises(ApprovalError):
141 + approve_year(session, year.id)
142 +
143 +
144 +class TestCarryForward:
145 + def test_copies_notes_and_mappings(self, session):
146 + source_year = _balanced_mapped(session)
147 + company = Company(code="CF", name="x")
148 + session.add(company)
149 + session.flush()
150 + target = FiscalYear(company_id=company.id, year=1405)
151 + session.add(target)
152 + session.flush()
153 + result = carry_forward_mappings(session, source_year.id, target.id)
154 + session.commit()
155 + assert result.notes_created == 3
156 + assert result.mappings_created == 3
157 + assert session.query(NoteDefinition).filter_by(year_id=target.id).count() == 3
158 + assert session.query(MappingRule).filter_by(year_id=target.id).count() == 3
159 +
160 + def test_carry_forward_idempotent(self, session):
161 + source_year = _balanced_mapped(session)
162 + company = Company(code="CF2", name="x")
163 + session.add(company)
164 + session.flush()
165 + target = FiscalYear(company_id=company.id, year=1405)
166 + session.add(target)
167 + session.flush()
168 + carry_forward_mappings(session, source_year.id, target.id)
169 + session.commit()
170 + again = carry_forward_mappings(session, source_year.id, target.id)
171 + session.commit()
172 + assert again.notes_created == 0
173 + assert again.mappings_created == 0
174 +
175 + def test_carry_forward_rejects_non_draft_target(self, session):
176 + source_year = _balanced_mapped(session)
177 + company = Company(code="CF3", name="x")
178 + session.add(company)
179 + session.flush()
180 + target = FiscalYear(company_id=company.id, year=1405)
181 + session.add(target)
182 + session.flush()
183 + target.status = FiscalYearStatus.APPROVED
184 + session.commit()
185 + with pytest.raises(CarryForwardError):
186 + carry_forward_mappings(session, source_year.id, target.id)
187 +
188 +
189 +class TestPhase2Api:
190 + def test_mapping_export_import_and_approve(self, api_client):
191 + c = api_client
192 + year_id = c.post(
193 + "/api/v1/companies", json={"code": "P2", "name": "x", "year": 1404}
194 + ).json()["year_id"]
195 + csv = (
196 + "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
197 + "8348,14,نقد,1404,O,,,,,0,100,0,100\n"
198 + "1001,24,پرداختنی,1404,O,,,,,0,0,60,-60\n"
199 + "1001,34,سرمایه,1404,O,,,,,0,0,40,-40\n"
200 + ).encode()
201 + c.post(f"/api/v1/years/{year_id}/ledger", files={"file": ("l.csv", csv, "text/csv")})
202 +
203 + # Unknown queue initially has 3 accounts.
204 + q = c.get(f"/api/v1/years/{year_id}/unknown-accounts").json()
205 + assert q["count"] == 3
206 +
207 + # Approval blocked while unmapped.
208 + blocked = c.post(f"/api/v1/years/{year_id}/approve", json={"actor": "r"}).json()
209 + assert blocked["approved"] is False
210 +
211 + # Import a mapping workbook covering all three accounts.
212 + from openpyxl import Workbook
213 +
214 + wb = Workbook()
215 + ws = wb.active
216 + ws.title = "Mappings"
217 + ws.append(
218 + [
219 + "account_code",
220 + "account_name",
221 + "target_note_number",
222 + "statement",
223 + "section",
224 + "mapping_type",
225 + ]
226 + )
227 + ws.append(["148348", "نقد", "6", "BS", "Assets", "closing"])
228 + ws.append(["241001", "پرداختنی", "10", "BS", "Liabilities", "closing"])
229 + ws.append(["341001", "سرمایه", "12", "BS", "Equity", "closing"])
230 + buf = BytesIO()
231 + wb.save(buf)
232 + r = c.post(
233 + f"/api/v1/years/{year_id}/mappings/import",
234 + files={
235 + "file": (
236 + "mappings.xlsx",
237 + buf.getvalue(),
238 + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
239 + )
240 + },
241 + )
242 + assert r.status_code == 200, r.text
243 + assert r.json()["created"] == 3
244 +
245 + # Export round-trips.
246 + exp = c.get(f"/api/v1/years/{year_id}/mappings/export")
247 + assert exp.status_code == 200
248 + assert len(exp.content) > 0
249 +
250 + # Now approval succeeds.
251 + ok = c.post(f"/api/v1/years/{year_id}/approve", json={"actor": "r"}).json()
252 + assert ok["approved"] is True
253 +
254 +
255 +class TestMappingWorkflowNegative:
256 + def test_carry_forward_nonexistent_target_raises(self, session):
257 + source_year = _balanced_mapped(session)
258 + with pytest.raises(CarryForwardError):
259 + carry_forward_mappings(session, source_year.id, 999999)
260 +
261 + def test_unknown_queue_excludes_inactive_accounts(self, session):
262 + year, source = _setup(session)
263 + _balance(session, year, source, "148348", 0, 3) # all-zero -> inactive
264 + session.flush()
265 + assert unknown_accounts(session, year.id) == []
266 +
267 + def test_unknown_queue_aggregates_raw_rows(self, session):
268 + year, source = _setup(session)
269 + _balance(session, year, source, "148348", 100, 3)
270 + _balance(session, year, source, "148348", 200, 4) # same account, second raw row
271 + session.flush()
272 + queue = unknown_accounts(session, year.id)
273 + assert len(queue) == 1 # deduped by account
274 + assert queue[0]["account_full_code"] == "148348"
275 + assert queue[0]["closing"] == "300" # aggregated in compute layer
276 + assert queue[0]["row_count"] == 2
277 +
278 + def test_mapping_import_empty_workbook_raises(self, session):
279 + from io import BytesIO
280 +
281 + from openpyxl import Workbook
282 +
283 + from aram_backend.services.mapping_io import MappingImportError
284 +
285 + year, _ = _setup(session)
286 + wb = Workbook()
287 + wb.active.title = "Mappings" # header-less
288 + buf = BytesIO()
289 + wb.save(buf)
290 + with pytest.raises(MappingImportError):
291 + import_mappings_workbook(session, year.id, buf.getvalue())
backend/tests/test_note_engine.py new
+124
@@ -0,0 +1,124 @@
1 +"""Phase 3 acceptance: note engine evaluates formulas against real balances."""
2 +
3 +from __future__ import annotations
4 +
5 +import pytest
6 +
7 +from aram_backend.models import NoteRow
8 +from aram_backend.services.note_engine import NoteEngineError, evaluate_note, evaluate_year_notes
9 +from test_statement_build import _balance, _note, _setup
10 +
11 +
12 +def _row(session, note, order, label, formula):
13 + r = NoteRow(note_id=note.id, row_order=order, label=label, formula_logic=formula)
14 + session.add(r)
15 + session.flush()
16 + return r
17 +
18 +
19 +def _seed(session):
20 + year, source = _setup(session)
21 + _balance(session, year, source, "148348", 100, 3)
22 + _balance(session, year, source, "241001", -60, 4)
23 + session.flush()
24 + return year
25 +
26 +
27 +class TestNoteEngine:
28 + def test_rows_with_account_and_subtotal(self, session):
29 + year = _seed(session)
30 + note = _note(session, year, "6", "نقد", "BS", "Assets")
31 + _row(session, note, 0, "حساب نقد", 'acct("148348")')
32 + _row(session, note, 1, "پرداختنی", 'acct("241001")')
33 + _row(session, note, 2, "جمع", "sum(row(0), row(1))")
34 + session.flush()
35 + result = evaluate_note(session, note.id)
36 + values = [r["value"] for r in result["rows"]]
37 + assert values == ["100", "-60", "40"]
38 + assert result["rows"][0]["accounts_referenced"] == ["148348"]
39 +
40 + def test_cross_note_reference(self, session):
41 + year = _seed(session)
42 + n6 = _note(session, year, "6", "نقد", "BS", "Assets")
43 + _row(session, n6, 0, "نقد", 'acct("148348")')
44 + n7 = _note(session, year, "7", "مشتق", "BS", "Assets")
45 + _row(session, n7, 0, "مشتق", 'note("6", 0) + 5')
46 + session.flush()
47 + result = evaluate_note(session, n7.id)
48 + assert result["rows"][0]["value"] == "105"
49 +
50 + def test_circular_reference_detected(self, session):
51 + year = _seed(session)
52 + n6 = _note(session, year, "6", "الف", "BS", "Assets")
53 + _row(session, n6, 0, "a", 'note("7", 0)')
54 + n7 = _note(session, year, "7", "ب", "BS", "Assets")
55 + _row(session, n7, 0, "b", 'note("6", 0)')
56 + session.flush()
57 + with pytest.raises(NoteEngineError, match="circular"):
58 + evaluate_note(session, n6.id)
59 +
60 + def test_forward_row_reference_rejected(self, session):
61 + year = _seed(session)
62 + note = _note(session, year, "6", "نقد", "BS", "Assets")
63 + _row(session, note, 0, "bad", "row(1)")
64 + _row(session, note, 1, "x", 'acct("148348")')
65 + session.flush()
66 + with pytest.raises(NoteEngineError):
67 + evaluate_note(session, note.id)
68 +
69 + def test_unknown_account_rejected(self, session):
70 + year = _seed(session)
71 + note = _note(session, year, "6", "نقد", "BS", "Assets")
72 + _row(session, note, 0, "bad", 'acct("999999")')
73 + session.flush()
74 + with pytest.raises(NoteEngineError):
75 + evaluate_note(session, note.id)
76 +
77 + def test_evaluate_year_notes(self, session):
78 + year = _seed(session)
79 + note = _note(session, year, "6", "نقد", "BS", "Assets")
80 + _row(session, note, 0, "نقد", 'acct("148348")')
81 + session.flush()
82 + results = evaluate_year_notes(session, year.id)
83 + assert len(results) == 1
84 + assert results[0]["rows"][0]["value"] == "100"
85 +
86 +
87 +class TestNoteEngineApi:
88 + def test_create_rows_and_evaluate(self, api_client):
89 + c = api_client
90 + year_id = c.post(
91 + "/api/v1/companies", json={"code": "N3", "name": "x", "year": 1404}
92 + ).json()["year_id"]
93 + csv = (
94 + "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
95 + "8348,14,نقد,1404,O,,,,,0,100,0,100\n"
96 + ).encode()
97 + c.post(f"/api/v1/years/{year_id}/ledger", files={"file": ("l.csv", csv, "text/csv")})
98 + note_id = c.post(
99 + f"/api/v1/years/{year_id}/notes",
100 + json={"note_number": "6", "title": "نقد", "statement": "BS", "section": "Assets"},
101 + ).json()["note_id"]
102 + r = c.post(
103 + f"/api/v1/years/{year_id}/notes/{note_id}/rows",
104 + json={"row_order": 0, "label": "نقد", "formula_logic": 'acct("148348")'},
105 + )
106 + assert r.status_code == 200, r.text
107 + r = c.get(f"/api/v1/notes/{note_id}/evaluate")
108 + assert r.status_code == 200, r.text
109 + assert r.json()["rows"][0]["value"] == "100"
110 +
111 + def test_invalid_formula_rejected_on_create(self, api_client):
112 + c = api_client
113 + year_id = c.post(
114 + "/api/v1/companies", json={"code": "N4", "name": "x", "year": 1404}
115 + ).json()["year_id"]
116 + note_id = c.post(
117 + f"/api/v1/years/{year_id}/notes",
118 + json={"note_number": "6", "title": "نقد", "statement": "BS", "section": "Assets"},
119 + ).json()["note_id"]
120 + r = c.post(
121 + f"/api/v1/years/{year_id}/notes/{note_id}/rows",
122 + json={"row_order": 0, "label": "bad", "formula_logic": "__import__('os')"},
123 + )
124 + assert r.status_code == 422
backend/tests/test_phase0_fixes.py new
+188
@@ -0,0 +1,188 @@
1 +"""Acceptance tests for Phase-0 debts D-04, D-05, D-11 and real-data evidence.
2 +
3 +These prove the booklet's required fixes at the parser/inspection level and
4 +record the evidence behind ADR-013 (sign) and ADR-014 (hierarchy) on a bounded
5 +sample of the canonical 1404 ledger (read-only; skipped if data is absent).
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +import io
11 +import re
12 +import zipfile
13 +from decimal import Decimal
14 +from pathlib import Path
15 +
16 +import pytest
17 +from openpyxl import Workbook, load_workbook
18 +
19 +from aram_backend.domain.controls import BalanceRow, check_c01
20 +from aram_backend.domain.hierarchy import ledger_to_pilot
21 +from aram_backend.ledger_parser import parse_general_ledger
22 +from aram_backend.workbook_inspection import inspect_xlsx
23 +
24 +GL_HEADERS = [
25 + "حساب",
26 + "ACCOUNT_NAME",
27 + "year",
28 + "نوع",
29 + "T1_CODE",
30 + "T2_CODE",
31 + "T3_CODE",
32 + "T4_CODE",
33 + "OPENING",
34 + "Debit",
35 + "Credit",
36 + "CLOSING",
37 +]
38 +REPO_ROOT = Path(__file__).resolve().parents[2]
39 +LEDGER_1404 = REPO_ROOT / "data" / "source_ledgers" / "source_1404.xlsx"
40 +
41 +
42 +def _gl_bytes(*rows, headers=None):
43 + wb = Workbook()
44 + ws = wb.active
45 + ws.title = "Source"
46 + ws.append(["source ledger"])
47 + ws.append(headers or GL_HEADERS)
48 + for r in rows:
49 + ws.append(r)
50 + buf = io.BytesIO()
51 + wb.save(buf)
52 + wb.close()
53 + return buf.getvalue()
54 +
55 +
56 +def _strip_dimension(raw: bytes) -> bytes:
57 + zin = zipfile.ZipFile(io.BytesIO(raw))
58 + out = io.BytesIO()
59 + zout = zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED)
60 + for item in zin.infolist():
61 + data = zin.read(item.filename)
62 + if item.filename == "xl/worksheets/sheet1.xml":
63 + data = re.sub(rb"<dimension[^>]*/>", b"", data)
64 + zout.writestr(item, data)
65 + zout.close()
66 + return out.getvalue()
67 +
68 +
69 +def _row(code="0101", opening=0, debit=0, credit=0, closing=0):
70 + return [code, "x", 1404, "O", None, None, None, None, opening, debit, credit, closing]
71 +
72 +
73 +class TestD04CodesAndMoney:
74 + def test_text_leading_zero_code_preserved(self):
75 + rec = next(parse_general_ledger(_gl_bytes(_row(code="0101"))))
76 + assert rec.account_code == "0101"
77 +
78 + def test_persian_digit_code_normalized_to_text(self):
79 + rec = next(parse_general_ledger(_gl_bytes(_row(code="۰۱۰۱"))))
80 + assert rec.account_code == "0101"
81 +
82 + def test_integer_code_exact(self):
83 + rec = next(parse_general_ledger(_gl_bytes(_row(code=8348))))
84 + assert rec.account_code == "8348"
85 +
86 + def test_float_money_exact_roundtrip(self):
87 + # repr path: exact shortest round-trip, not the binary expansion.
88 + rec = next(parse_general_ledger(_gl_bytes(_row(debit=1234.56789012345))))
89 + assert rec.debit == Decimal("1234.56789012345")
90 +
91 +
92 +class TestD05Normalization:
93 + def test_persian_financial_statement_sheets_accepted(self):
94 + # Persian ی/ک variants of the canonical Arabic sheet names.
95 + names = ["سودوزیان", "وضعیت مالی", "حقوق مالکانه", "جریان های نقدی"]
96 + wb = Workbook()
97 + wb.remove(wb.active)
98 + for n in names:
99 + wb.create_sheet(n)
100 + buf = io.BytesIO()
101 + wb.save(buf)
102 + wb.close()
103 + result = inspect_xlsx(buf.getvalue(), document_type="financial_statement")
104 + assert result.sheet_names == tuple(names)
105 +
106 + def test_arabic_kaf_mapping_headers_accepted(self):
107 + # "كد حساب" with Arabic kaf must match the Persian "کد حساب" requirement.
108 + headers = [
109 + "كد حساب",
110 + "نوع",
111 + "كد یادداشت",
112 + "شرح یادداشت",
113 + "فرمول یادداشت اصلی",
114 + "فرمول یادداشت فرعی",
115 + ]
116 + wb = Workbook()
117 + ws = wb.active
118 + ws.title = "Data"
119 + ws.append(headers)
120 + buf = io.BytesIO()
121 + wb.save(buf)
122 + wb.close()
123 + result = inspect_xlsx(buf.getvalue(), document_type="mapping")
124 + assert result.data_sheet == "Data"
125 +
126 +
127 +class TestD11NoDimension:
128 + def test_dimensionless_file_inspects_and_parses(self):
129 + raw = _strip_dimension(_gl_bytes(_row()))
130 + # Confirm the fixture really has no dimension (max_column is None).
131 + probe = load_workbook(io.BytesIO(raw), read_only=True)
132 + assert probe["Source"].max_column is None
133 + probe.close()
134 + result = inspect_xlsx(raw, document_type="general_ledger")
135 + assert result.data_sheet == "Source"
136 + rec = next(parse_general_ledger(raw))
137 + assert rec.account_code == "0101"
138 +
139 +
140 +@pytest.mark.skipif(not LEDGER_1404.exists(), reason="canonical ledger not present")
141 +class TestRealDataEvidence:
142 + """Bounded read-only evidence for ADR-013 (sign) and ADR-014 (hierarchy)."""
143 +
144 + def _sample(self, limit=20000):
145 + wb = load_workbook(LEDGER_1404, read_only=True, data_only=True, keep_links=False)
146 + ws = wb["Source"]
147 + rows = ws.iter_rows(values_only=True)
148 + next(rows)
149 + header = next(rows)
150 + idx = {str(v).strip(): i for i, v in enumerate(header) if v is not None}
151 + out = []
152 + for vals in rows:
153 + if not any(v is not None for v in vals):
154 + continue
155 + out.append((idx, vals))
156 + if len(out) >= limit:
157 + break
158 + wb.close()
159 + return out
160 +
161 + def test_hierarchy_invariant_on_sample(self):
162 + for idx, vals in self._sample():
163 + kol = vals[idx["kol"]]
164 + hesab = vals[idx["حساب"]]
165 + levels = ledger_to_pilot(kol=kol, hesab=hesab, row=0)
166 + assert levels.subsidiary_code == str(hesab).strip()
167 + assert levels.general_code == str(kol).strip()
168 +
169 + def test_debit_positive_sign_dominates(self):
170 + debit_pos = 0
171 + credit_pos = 0
172 + n = 0
173 + for idx, vals in self._sample():
174 + o = Decimal(str(vals[idx["OPENING"]] or 0))
175 + d = Decimal(str(vals[idx["Debit"]] or 0))
176 + c = Decimal(str(vals[idx["Credit"]] or 0))
177 + cl = Decimal(str(vals[idx["CLOSING"]] or 0))
178 + n += 1
179 + if o + d - c - cl == 0:
180 + debit_pos += 1
181 + if o - d + c - cl == 0:
182 + credit_pos += 1
183 + assert n > 0
184 + assert debit_pos >= credit_pos
185 + assert debit_pos >= 0.99 * n
186 + # And the domain control agrees with the chosen convention.
187 + rows = [BalanceRow(1, "x", Decimal(0), Decimal(0), Decimal(0), Decimal(0))]
188 + assert check_c01(rows).passed
backend/tests/test_phase7_admin.py new
+237
@@ -0,0 +1,237 @@
1 +"""Phase 7: users/roles, controlled reopen/lock, backup integrity, audit API."""
2 +
3 +from __future__ import annotations
4 +
5 +import pytest
6 +
7 +from aram_backend.models import FiscalYearStatus, UserRole
8 +from aram_backend.services.approval import approve_year
9 +from aram_backend.services.audit import verify_chain
10 +from aram_backend.services.backup import BackupError, create_backup, verify_backup
11 +from aram_backend.services.reopen import (
12 + ReopenError,
13 + approve_reopen,
14 + lock_year,
15 + reopen_year,
16 + request_reopen,
17 +)
18 +from aram_backend.services.users import (
19 + AuthorizationError,
20 + UserError,
21 + authenticate,
22 + create_user,
23 + require_role,
24 + set_active,
25 +)
26 +from test_approval_gate import _balanced
27 +
28 +
29 +# --------------------------------------------------------------------- users
30 +class TestUsers:
31 + def test_create_and_authenticate(self, session):
32 + create_user(session, username="alice", password="supersecret", role=UserRole.REVIEWER)
33 + user = authenticate(session, username="alice", password="supersecret")
34 + assert user.role == UserRole.REVIEWER
35 + assert user.password_hash != "supersecret" # never plaintext
36 + assert len(user.salt) == 32
37 +
38 + def test_wrong_password_rejected(self, session):
39 + create_user(session, username="bob", password="supersecret")
40 + with pytest.raises(UserError):
41 + authenticate(session, username="bob", password="wrong-password")
42 +
43 + def test_duplicate_username_rejected(self, session):
44 + create_user(session, username="carol", password="supersecret")
45 + with pytest.raises(UserError):
46 + create_user(session, username="carol", password="anothersecret")
47 +
48 + def test_short_password_rejected(self, session):
49 + with pytest.raises(UserError):
50 + create_user(session, username="dave", password="short")
51 +
52 + def test_inactive_user_cannot_authenticate(self, session):
53 + create_user(session, username="erin", password="supersecret")
54 + set_active(session, username="erin", active=False)
55 + with pytest.raises(UserError):
56 + authenticate(session, username="erin", password="supersecret")
57 +
58 + def test_require_role_gate(self, session):
59 + create_user(session, username="prep", password="supersecret", role=UserRole.PREPARER)
60 + create_user(session, username="admin", password="supersecret", role=UserRole.ADMIN)
61 + require_role(session, username="admin", allowed={UserRole.ADMIN})
62 + with pytest.raises(AuthorizationError):
63 + require_role(session, username="prep", allowed={UserRole.ADMIN})
64 + with pytest.raises(AuthorizationError):
65 + require_role(session, username="ghost", allowed={UserRole.ADMIN})
66 +
67 +
68 +# --------------------------------------------------------------- reopen/lock
69 +class TestReopenLock:
70 + def _locked(self, session):
71 + year, _ = _balanced(session)
72 + assert approve_year(session, year.id).approved
73 + lock_year(session, year.id, actor="admin")
74 + assert year.status == FiscalYearStatus.LOCKED
75 + return year
76 +
77 + def test_full_reopen_workflow(self, session):
78 + year = self._locked(session)
79 + req = request_reopen(session, year.id, reason="اصلاح طبقه‌بندی", requested_by="prep")
80 + assert req.status == "pending"
81 + # Reopen before approval is refused.
82 + with pytest.raises(ReopenError):
83 + reopen_year(session, year.id, actor="admin")
84 + approve_reopen(session, req.id, approved_by="admin")
85 + reopen_year(session, year.id, actor="admin")
86 + assert year.status == FiscalYearStatus.APPROVED
87 + assert verify_chain(session)
88 +
89 + def test_request_on_non_locked_fails(self, session):
90 + year, _ = _balanced(session) # Draft
91 + with pytest.raises(ReopenError):
92 + request_reopen(session, year.id, reason="x", requested_by="prep")
93 +
94 + def test_lock_requires_approved(self, session):
95 + year, _ = _balanced(session) # Draft
96 + with pytest.raises(ReopenError):
97 + lock_year(session, year.id, actor="admin")
98 +
99 + def test_reopen_requires_reason(self, session):
100 + year = self._locked(session)
101 + with pytest.raises(ReopenError):
102 + request_reopen(session, year.id, reason=" ", requested_by="prep")
103 +
104 + def test_locked_year_is_immutable(self, session):
105 + year = self._locked(session)
106 + from aram_backend.models import NoteDefinition
107 +
108 + note = NoteDefinition(
109 + year_id=year.id,
110 + note_number="99",
111 + title="x",
112 + configuration_json={"statement": "BS", "section": "Assets"},
113 + )
114 + session.add(note)
115 + with pytest.raises(ValueError):
116 + session.flush()
117 + session.rollback()
118 +
119 +
120 +# -------------------------------------------------------------------- backup
121 +class TestBackup:
122 + def test_create_and_verify(self, session, tmp_path):
123 + year, _ = _balanced(session)
124 + approve_year(session, year.id)
125 + session.commit()
126 + store = tmp_path / "store"
127 + store.mkdir()
128 + (store / "ab").mkdir()
129 + (store / "ab" / "cd").write_bytes(b"source-bytes")
130 + dest = tmp_path / "backup"
131 + manifest = create_backup(session, dest, store_root=store)
132 + assert manifest["audit_chain_valid"] is True
133 + assert manifest["source_store_sha256"]
134 + result = verify_backup(dest)
135 + assert result["valid"] is True
136 + assert result["source_files"] == 1
137 +
138 + def test_tampered_database_detected(self, session, tmp_path):
139 + year, _ = _balanced(session)
140 + approve_year(session, year.id)
141 + session.commit()
142 + store = tmp_path / "store"
143 + store.mkdir()
144 + dest = tmp_path / "backup"
145 + create_backup(session, dest, store_root=store)
146 + # Corrupt the backed-up database bytes.
147 + db = dest / "aram.db"
148 + db.write_bytes(db.read_bytes() + b"tamper")
149 + with pytest.raises(BackupError):
150 + verify_backup(dest)
151 +
152 + def test_non_empty_destination_refused(self, session, tmp_path):
153 + store = tmp_path / "store"
154 + store.mkdir()
155 + dest = tmp_path / "backup"
156 + dest.mkdir()
157 + (dest / "existing").write_text("x")
158 + with pytest.raises(BackupError):
159 + create_backup(session, dest, store_root=store)
160 +
161 +
162 +# ----------------------------------------------------------------- admin API
163 +class TestAdminApi:
164 + def test_bootstrap_first_user_is_admin(self, api_client):
165 + r = api_client.post(
166 + "/api/v1/users",
167 + json={"username": "root", "password": "supersecret", "role": "preparer"},
168 + )
169 + assert r.status_code == 200, r.text
170 + assert r.json()["role"] == "admin" # bootstrap forces admin
171 +
172 + def test_login_and_role_gate(self, api_client):
173 + api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
174 + # login
175 + r = api_client.post(
176 + "/api/v1/auth/login", json={"username": "root", "password": "supersecret"}
177 + )
178 + assert r.status_code == 200
179 + assert r.json()["role"] == "admin"
180 + # bad login
181 + r = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "nope"})
182 + assert r.status_code == 401
183 + # admin can create a preparer
184 + r = api_client.post(
185 + "/api/v1/users",
186 + json={
187 + "username": "prep",
188 + "password": "supersecret",
189 + "role": "preparer",
190 + "actor": "root",
191 + },
192 + )
193 + assert r.status_code == 200
194 + # preparer cannot create users
195 + r = api_client.post(
196 + "/api/v1/users",
197 + json={"username": "x", "password": "supersecret", "actor": "prep"},
198 + )
199 + assert r.status_code == 403
200 +
201 + def test_approve_role_gated_once_users_exist(self, api_client):
202 + # Bootstrap admin + a preparer.
203 + api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
204 + api_client.post(
205 + "/api/v1/users",
206 + json={
207 + "username": "prep",
208 + "password": "supersecret",
209 + "role": "preparer",
210 + "actor": "root",
211 + },
212 + )
213 + year_id = api_client.post(
214 + "/api/v1/companies", json={"code": "RG", "name": "شرکت", "year": 1404}
215 + ).json()["year_id"]
216 + # Preparer is refused by the role gate (403) before controls even run.
217 + r = api_client.post(f"/api/v1/years/{year_id}/approve", json={"actor": "prep"})
218 + assert r.status_code == 403, r.text
219 + # Admin passes the role gate (controls may still block, but never 403).
220 + r = api_client.post(f"/api/v1/years/{year_id}/approve", json={"actor": "root"})
221 + assert r.status_code == 200, r.text
222 +
223 + def test_approve_open_when_no_users(self, api_client):
224 + # Bootstrap/dev: with no users, the role gate is inactive (control gate still applies).
225 + year_id = api_client.post(
226 + "/api/v1/companies", json={"code": "NU", "name": "شرکت", "year": 1404}
227 + ).json()["year_id"]
228 + r = api_client.post(f"/api/v1/years/{year_id}/approve", json={"actor": "anyone"})
229 + assert r.status_code == 200, r.text
230 +
231 + def test_audit_endpoint_chain_valid(self, api_client):
232 + api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
233 + r = api_client.get("/api/v1/audit/verify")
234 + assert r.status_code == 200
235 + assert r.json()["chain_valid"] is True
236 + r = api_client.get("/api/v1/audit")
237 + assert r.json()["entries"] # user.create recorded
backend/tests/test_pilot_api.py new
+179
@@ -0,0 +1,179 @@
1 +from __future__ import annotations
2 +
3 +from io import BytesIO
4 +
5 +from openpyxl import load_workbook
6 +
7 +import aram_backend.pilot_api as pilot_api
8 +from test_pilot_engine import build_balanced_workbook
9 +
10 +
11 +def test_meta_exposes_explicit_sign_policy(client):
12 + response = client.get("/api/v1/pilot/meta")
13 + assert response.status_code == 200
14 + body = response.json()
15 + assert body["rendered_statements"] == ["BS", "IS"]
16 + assert body["deferred_statements"] == ["CF", "EQ"]
17 + assert body["section_policy"]["BS"] == {"Assets": 1, "Liabilities": -1, "Equity": -1}
18 + assert body["section_policy"]["IS"] == {"Revenue": -1, "Expenses": 1}
19 +
20 +
21 +def test_root_serves_workbench_directly_and_ui_is_served(client):
22 + response = client.get("/", follow_redirects=False)
23 + assert response.status_code == 200
24 + assert "میز کار پایلوت" in response.text
25 + page = client.get("/pilot/")
26 + assert page.status_code == 200
27 + assert "میز کار پایلوت" in page.text
28 + assert client.get("/pilot/app.js").status_code == 200
29 + assert client.get("/pilot/styles.css").status_code == 200
30 +
31 +
32 +def test_demo_full_workflow_from_exceptions_to_approved_export(client):
33 + created = client.post("/api/v1/pilot/demo")
34 + assert created.status_code == 200
35 + body = created.json()
36 + sid = body["session"]["id"]
37 + assert body["session"]["source"] == "demo"
38 + assert body["report"]["status"]["label"] == "INCOMPLETE"
39 + assert {e["account_code"] for e in body["report"]["exceptions"]} == {"9001", "9002"}
40 + tb = next(c for c in body["report"]["checks"] if c["code"] == "TRIAL_BALANCE_CLOSED")
41 + assert tb["passed"] and tb["amount"] == "0"
42 +
43 + # Map the two suspense accounts; coverage and equation close, approval pending.
44 + for code, statement, section, note in (
45 + ("9001", "BS", "Assets", "04"),
46 + ("9002", "BS", "Liabilities", "06"),
47 + ):
48 + response = client.put(
49 + f"/api/v1/pilot/sessions/{sid}/mappings/{code}",
50 + json={"statement": statement, "section": section, "note_number": note,
51 + "actor": "آزمون"},
52 + )
53 + assert response.status_code == 200
54 + body = response.json()
55 + assert body["report"]["status"]["label"] == "COMPLETE_DRAFT"
56 + assert body["report"]["totals"]["assets"] == "56000000000"
57 + assert body["report"]["totals"]["liabilities"] == "22800000000"
58 + assert body["report"]["totals"]["equity"] == "33000000000"
59 + assert body["report"]["totals"]["profit"] == "200000000"
60 + assert all(c["passed"] for c in body["report"]["checks"] if c["code"] != "MAPPINGS_APPROVED")
61 +
62 + # Approve the remaining Draft mappings with reviewer evidence.
63 + for code, statement, section, note in (
64 + ("1004", "BS", "Assets", "04"),
65 + ("9001", "BS", "Assets", "04"),
66 + ("9002", "BS", "Liabilities", "06"),
67 + ):
68 + response = client.put(
69 + f"/api/v1/pilot/sessions/{sid}/mappings/{code}",
70 + json={"statement": statement, "section": section, "note_number": note,
71 + "approval_status": "Approved", "reviewer": "بازبین آزمون", "actor": "آزمون"},
72 + )
73 + assert response.status_code == 200
74 + body = response.json()
75 + assert body["report"]["status"]["label"] == "COMPLETE_APPROVED"
76 + assert len(body["audit_trail"]) == 5
77 + assert body["audit_trail"][0]["actor"] == "آزمون"
78 +
79 + export = client.get(f"/api/v1/pilot/sessions/{sid}/export.xlsx")
80 + assert export.status_code == 200
81 + assert "spreadsheetml" in export.headers["content-type"]
82 + book = load_workbook(BytesIO(export.content))
83 + assert "BalanceSheet" in book.sheetnames
84 + info = {row[0]: row[1] for row in book["Info"].iter_rows(min_row=2, values_only=True)}
85 + assert info["status"] == "COMPLETE_APPROVED"
86 + assert info["synthetic_data"].startswith("TRUE")
87 + assert book["AuditTrail"].max_row == 6
88 + book.close()
89 +
90 + assert client.delete(f"/api/v1/pilot/sessions/{sid}").status_code == 200
91 + assert client.get(f"/api/v1/pilot/sessions/{sid}").status_code == 404
92 +
93 +
94 +def test_upload_valid_workbook_creates_session(client):
95 + response = client.post(
96 + "/api/v1/pilot/sessions",
97 + files={"file": ("pilot.xlsx", build_balanced_workbook(),
98 + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
99 + )
100 + assert response.status_code == 200
101 + body = response.json()
102 + assert body["session"]["source"] == "upload"
103 + assert body["report"]["status"]["label"] == "COMPLETE_APPROVED"
104 + assert len(body["accounts"]) == 5
105 +
106 +
107 +def test_upload_invalid_workbook_returns_exact_preflight_issues(client):
108 + response = client.post(
109 + "/api/v1/pilot/sessions", files={"file": ("bad.xlsx", b"not an xlsx")}
110 + )
111 + assert response.status_code == 422
112 + detail = response.json()["detail"]
113 + assert detail["issues"][0]["code"] == "INVALID_WORKBOOK"
114 +
115 +
116 +def test_upload_rejects_wrong_extension_and_empty_file(client):
117 + response = client.post(
118 + "/api/v1/pilot/sessions", files={"file": ("data.csv", b"x,y\n1,2")}
119 + )
120 + assert response.status_code == 422
121 + response = client.post(
122 + "/api/v1/pilot/sessions", files={"file": ("empty.xlsx", b"")}
123 + )
124 + assert response.status_code == 422
125 +
126 +
127 +def test_upload_size_limit_is_enforced(client, monkeypatch):
128 + monkeypatch.setattr(pilot_api, "MAX_UPLOAD_BYTES", 8)
129 + response = client.post(
130 + "/api/v1/pilot/sessions", files={"file": ("big.xlsx", b"0123456789")}
131 + )
132 + assert response.status_code == 413
133 +
134 +
135 +def test_mapping_validation_is_fail_closed(client):
136 + sid = client.post("/api/v1/pilot/demo").json()["session"]["id"]
137 + base = f"/api/v1/pilot/sessions/{sid}/mappings"
138 + # Unknown account.
139 + assert client.put(f"{base}/9999", json={
140 + "statement": "BS", "section": "Assets", "note_number": "01",
141 + }).status_code == 404
142 + # Target that does not exist in Notes.
143 + assert client.put(f"{base}/9001", json={
144 + "statement": "BS", "section": "Assets", "note_number": "99",
145 + }).status_code == 422
146 + # Approved without reviewer evidence.
147 + assert client.put(f"{base}/9001", json={
148 + "statement": "BS", "section": "Assets", "note_number": "04",
149 + "approval_status": "Approved",
150 + }).status_code == 422
151 + # Invalid lifecycle value.
152 + assert client.put(f"{base}/9001", json={
153 + "statement": "BS", "section": "Assets", "note_number": "04",
154 + "approval_status": "Published",
155 + }).status_code == 422
156 +
157 +
158 +def test_clear_mapping_reopens_the_exception_queue(client):
159 + sid = client.post("/api/v1/pilot/demo").json()["session"]["id"]
160 + response = client.delete(f"/api/v1/pilot/sessions/{sid}/mappings/1001?actor=tester")
161 + assert response.status_code == 200
162 + body = response.json()
163 + assert body["report"]["status"]["label"] == "INCOMPLETE"
164 + assert "1001" in {e["account_code"] for e in body["report"]["exceptions"]}
165 + assert body["audit_trail"][-1]["action"] == "clear_mapping"
166 +
167 +
168 +def test_unknown_session_is_404_everywhere(client):
169 + assert client.get("/api/v1/pilot/sessions/nope").status_code == 404
170 + assert client.get("/api/v1/pilot/sessions/nope/export.xlsx").status_code == 404
171 + assert client.delete("/api/v1/pilot/sessions/nope").status_code == 404
172 + assert client.put("/api/v1/pilot/sessions/nope/mappings/10", json={
173 + "statement": "BS", "section": "Assets", "note_number": "01",
174 + }).status_code == 404
175 +
176 +
177 +def test_existing_api_surface_is_unchanged(client):
178 + assert client.get("/api/v1/health").json()["status"] == "ok"
179 + assert len(client.get("/api/v1/schema/entities").json()["entities"]) == 9
backend/tests/test_pilot_editing.py new
+274
@@ -0,0 +1,274 @@
1 +from __future__ import annotations
2 +
3 +from io import BytesIO
4 +
5 +from openpyxl import load_workbook
6 +
7 +from aram_backend.pilot_editing import (
8 + InvalidAccountError,
9 + InvalidCompanyError,
10 + InvalidNoteError,
11 + make_account,
12 + make_company,
13 + make_note,
14 +)
15 +from aram_backend.pilot_engine import build_report, export_working_workbook, parse_pilot_model
16 +from aram_backend.pilot_store import PilotSessionStore
17 +from test_pilot_engine import build_balanced_workbook
18 +
19 +
20 +def _session():
21 + store = PilotSessionStore()
22 + model = parse_pilot_model(build_balanced_workbook())
23 + return store, store.create(model, source="upload", filename="t.xlsx")
24 +
25 +
26 +# ----------------------------------------------------------- domain validators
27 +def test_make_account_derives_closing_and_never_invents():
28 + account = make_account(
29 + full_code="60", name="حساب جدید", general_code="60", general_name="کل",
30 + opening="100", debit="50", credit="20", source_row=900001,
31 + )
32 + assert account.closing == 130 # 100 + 50 - 20, derived not guessed
33 + assert account.opening + account.debit - account.credit == account.closing
34 +
35 +
36 +def test_make_account_rejects_bad_values():
37 + import pytest
38 + with pytest.raises(InvalidAccountError):
39 + make_account(full_code="", name="x", general_code="1", general_name="g",
40 + opening=0, debit=0, credit=0, source_row=1)
41 + with pytest.raises(InvalidAccountError):
42 + make_account(full_code="1", name="x", general_code="1", general_name="g",
43 + opening="NaN", debit=0, credit=0, source_row=1)
44 + with pytest.raises(InvalidAccountError):
45 + make_account(full_code="1", name="x", general_code="1", general_name="g",
46 + opening=0, debit=0, credit=0, source_row=0)
47 +
48 +
49 +def test_make_note_and_company_validation():
50 + import pytest
51 + note = make_note(statement="BS", section="Assets", note_number="07", note_title="یادداشت جدید")
52 + assert note.key == ("BS", "Assets", "07", "")
53 + with pytest.raises(InvalidNoteError):
54 + make_note(statement="XX", section="Assets", note_number="1", note_title="t")
55 + with pytest.raises(InvalidNoteError):
56 + make_note(statement="BS", section="Assets", note_number="1", note_title="t",
57 + subnote_code="A", subnote_title="")
58 + company = make_company(code="C9", name="شرکت عمومی", fiscal_year=1405)
59 + assert company.fiscal_year == 1405
60 + with pytest.raises(InvalidCompanyError):
61 + make_company(code="C9", name="x", fiscal_year=-1)
62 +
63 +
64 +# ------------------------------------------------------------- account CRUD
65 +def test_add_account_enters_exception_queue_then_maps():
66 + store, session = _session()
67 + store.add_account(session.id, full_code="60", name="هزینه جدید", general_code="60",
68 + general_name="هزینه‌ها", opening=0, debit=5, credit=0, actor="tester")
69 + report = build_report(session.working, session.mappings)
70 + assert "60" in {e["account_code"] for e in report["exceptions"]}
71 + assert report["status"]["label"] == "INCOMPLETE"
72 + # map it to the expense note; equation stays closed because TB now has +5
73 + store.set_mapping(session.id, "60", statement="IS", section="Expenses", note_number="05", actor="tester")
74 + report = build_report(session.working, session.mappings)
75 + assert report["totals"]["expenses"] == "15"
76 + assert session.audit_trail[-2]["action"] == "add_account"
77 +
78 +
79 +def test_add_duplicate_account_rejected():
80 + import pytest
81 +
82 + from aram_backend.pilot_editing import DuplicateAccountError
83 + store, session = _session()
84 + with pytest.raises(DuplicateAccountError):
85 + store.add_account(session.id, full_code="10", name="تکراری", general_code="10",
86 + general_name="کل", opening=0, debit=0, credit=0)
87 +
88 +
89 +def test_rename_account_carries_mapping_forward():
90 + store, session = _session()
91 + store.rename_account(session.id, "10", "1001", actor="tester")
92 + assert "10" not in session.working.accounts
93 + assert "1001" in session.working.accounts
94 + assert session.mappings["1001"].account_code == "1001"
95 + assert session.mappings["1001"].note_number == "01"
96 + report = build_report(session.working, session.mappings)
97 + assert report["totals"]["assets"] == "100"
98 + assert report["status"]["complete"]
99 +
100 +
101 +def test_update_and_delete_account():
102 + store, session = _session()
103 + store.update_account(session.id, "50", name="هزینه ویرایش‌شده", general_code="50",
104 + general_name="هزینه‌ها", opening=0, debit=12, credit=0, actor="tester")
105 + assert session.working.accounts["50"].closing == 12
106 + store.delete_account(session.id, "50", actor="tester")
107 + assert "50" not in session.working.accounts
108 + assert "50" not in session.mappings
109 + report = build_report(session.working, session.mappings)
110 + assert "50" not in {e["account_code"] for e in report["exceptions"]}
111 +
112 +
113 +# --------------------------------------------------------------- note CRUD
114 +def test_add_note_and_subnote_then_map_new_account_to_them():
115 + store, session = _session()
116 + store.add_note(session.id, make_note(statement="BS", section="Assets", note_number="06",
117 + note_title="سرمایه‌گذاری جدید"), actor="tester")
118 + store.add_note(session.id, make_note(statement="BS", section="Assets", note_number="06",
119 + note_title="سرمایه‌گذاری جدید", subnote_code="01",
120 + subnote_title="زیربخش الف"), actor="tester")
121 + store.add_account(session.id, full_code="15", name="سرمایه‌گذاری", general_code="15",
122 + general_name="دارایی", opening=0, debit=0, credit=0, actor="tester")
123 + store.set_mapping(session.id, "15", statement="BS", section="Assets",
124 + note_number="06", subnote_code="01", actor="tester")
125 + report = build_report(session.working, session.mappings)
126 + assets = report["statements"]["BS"]["sections"][0]
127 + sub = [ln for ln in assets["lines"] if ln["note_number"] == "06" and ln["subnote_code"] == "01"]
128 + assert sub and sub[0]["accounts"][0]["code"] == "15"
129 +
130 +
131 +def test_delete_note_in_use_is_blocked():
132 + import pytest
133 +
134 + from aram_backend.pilot_editing import NoteInUseError
135 + store, session = _session()
136 + with pytest.raises(NoteInUseError):
137 + store.delete_note(session.id, ("BS", "Assets", "01", ""), actor="tester")
138 + # after clearing the mapping, deletion succeeds
139 + store.clear_mapping(session.id, "10", actor="tester")
140 + store.delete_note(session.id, ("BS", "Assets", "01", ""), actor="tester")
141 + assert ("BS", "Assets", "01", "") not in session.working.notes
142 +
143 +
144 +def test_update_note_title():
145 + store, session = _session()
146 + key = ("BS", "Assets", "01", "")
147 + store.update_note(session.id, key, make_note(statement="BS", section="Assets",
148 + note_number="01", note_title="عنوان تازه"), actor="tester")
149 + assert session.working.notes[key].note_title == "عنوان تازه"
150 +
151 +
152 +# ------------------------------------------------------------- company edit
153 +def test_company_is_generic_and_editable():
154 + store, session = _session()
155 + store.update_company(session.id, make_company(code="GAS-01", name="شرکت انتقال گاز نمونه",
156 + fiscal_year=1404, unit="میلیون ریال"), actor="tester")
157 + assert session.working.company.name == "شرکت انتقال گاز نمونه"
158 + report = build_report(session.working, session.mappings)
159 + assert report["company"]["code"] == "GAS-01"
160 + # and equally any other company
161 + store.update_company(session.id, make_company(code="ANY-99", name="هر شرکت دیگر",
162 + fiscal_year=1405), actor="tester")
163 + assert session.working.company.code == "ANY-99"
164 +
165 +
166 +# ------------------------------------------------- save / reload round-trip
167 +def test_workspace_round_trip_is_lossless():
168 + store, session = _session()
169 + # make edits: add account+note, map, rename, edit company
170 + store.add_note(session.id, make_note(statement="IS", section="Expenses", note_number="06",
171 + note_title="هزینه تازه"), actor="tester")
172 + store.add_account(session.id, full_code="55", name="هزینه تازه", general_code="55",
173 + general_name="هزینه‌ها", opening=0, debit=0, credit=0, actor="tester")
174 + store.set_mapping(session.id, "55", statement="IS", section="Expenses", note_number="06",
175 + approval_status="Approved", reviewer="بازبین", actor="tester")
176 + store.rename_account(session.id, "10", "1001", actor="tester")
177 + store.update_company(session.id, make_company(code="NEW", name="شرکت بازطراحی‌شده",
178 + fiscal_year=1406, unit="ریال"), actor="tester")
179 +
180 + before = build_report(session.working, session.mappings)
181 + saved = export_working_workbook(session.working)
182 +
183 + # The saved workbook must pass preflight and rebuild the same state.
184 + reloaded = parse_pilot_model(saved)
185 + after = build_report(reloaded, reloaded.mappings)
186 + assert after["totals"] == before["totals"]
187 + assert after["status"] == before["status"]
188 + assert after["company"]["code"] == "NEW"
189 + assert after["company"]["fiscal_year"] == 1406
190 + assert "1001" in reloaded.accounts
191 + assert reloaded.mappings["55"].approval_status == "Approved"
192 + assert ("IS", "Expenses", "06", "") in reloaded.notes
193 +
194 +
195 +def test_workspace_export_is_preflight_valid():
196 + from aram_backend.pilot_workbook import preflight_pilot_workbook
197 + store, session = _session()
198 + data = export_working_workbook(session.working)
199 + result = preflight_pilot_workbook(data)
200 + assert result.valid, result.issues
201 + book = load_workbook(BytesIO(data))
202 + assert "Company" in book.sheetnames and "Mapping" in book.sheetnames
203 + book.close()
204 +
205 +
206 +# ------------------------------------------------------------------ API CRUD
207 +def test_api_account_note_company_crud_and_workspace(client):
208 + sid = client.post("/api/v1/pilot/demo").json()["session"]["id"]
209 + base = f"/api/v1/pilot/sessions/{sid}"
210 +
211 + # add a note + subnote
212 + assert client.post(f"{base}/notes", json={
213 + "statement": "BS", "section": "Assets", "note_number": "20",
214 + "note_title": "دارایی نامشهود", "actor": "tester",
215 + }).status_code == 200
216 + assert client.post(f"{base}/notes", json={
217 + "statement": "BS", "section": "Assets", "note_number": "20",
218 + "note_title": "دارایی نامشهود", "subnote_code": "01",
219 + "subnote_title": "سرقفلی", "actor": "tester",
220 + }).status_code == 200
221 + # duplicate note -> 409
222 + assert client.post(f"{base}/notes", json={
223 + "statement": "BS", "section": "Assets", "note_number": "20", "note_title": "x",
224 + }).status_code == 409
225 +
226 + # add an account and map it to the subnote
227 + assert client.post(f"{base}/accounts", json={
228 + "full_code": "1201", "name": "سرقفلی", "general_code": "12",
229 + "general_name": "دارایی نامشهود", "opening": 0, "debit": 0, "credit": 0,
230 + "actor": "tester",
231 + }).status_code == 200
232 + assert client.put(f"{base}/mappings/1201", json={
233 + "statement": "BS", "section": "Assets", "note_number": "20", "subnote_code": "01",
234 + "actor": "tester",
235 + }).status_code == 200
236 + # duplicate account -> 409
237 + assert client.post(f"{base}/accounts", json={
238 + "full_code": "1201", "name": "x", "general_code": "12", "general_name": "g",
239 + }).status_code == 409
240 +
241 + # rename carries mapping
242 + assert client.post(f"{base}/accounts/1201/rename", json={"new_code": "1299"}).status_code == 200
243 + body = client.get(base).json()
244 + acc = {a["code"]: a for a in body["accounts"]}
245 + assert "1299" in acc and acc["1299"]["mapping"]["note_number"] == "20"
246 +
247 + # edit company to a totally different generic company
248 + assert client.put(f"{base}/company", json={
249 + "code": "OTHER", "name": "شرکت دیگر", "fiscal_year": 1405, "unit": "ریال",
250 + }).status_code == 200
251 + assert client.get(base).json()["report"]["company"]["code"] == "OTHER"
252 +
253 + # delete note in use -> 409 ; delete account then note succeeds
254 + assert client.delete(f"{base}/notes", params={
255 + "statement": "BS", "section": "Assets", "note_number": "20", "subnote_code": "01",
256 + }).status_code == 409
257 + assert client.delete(f"{base}/accounts/1299").status_code == 200
258 + assert client.delete(f"{base}/notes", params={
259 + "statement": "BS", "section": "Assets", "note_number": "20", "subnote_code": "01",
260 + }).status_code == 200
261 +
262 + # workspace export downloads and is a valid workbook
263 + ws = client.get(f"{base}/workspace.xlsx")
264 + assert ws.status_code == 200 and "spreadsheetml" in ws.headers["content-type"]
265 + load_workbook(BytesIO(ws.content)).close()
266 +
267 +
268 +def test_api_invalid_account_value_is_422(client):
269 + sid = client.post("/api/v1/pilot/demo").json()["session"]["id"]
270 + response = client.post(f"/api/v1/pilot/sessions/{sid}/accounts", json={
271 + "full_code": "X1", "name": "بد", "general_code": "99", "general_name": "گ",
272 + "opening": "not-a-number",
273 + })
274 + assert response.status_code == 422
backend/tests/test_pilot_engine.py new
+251
@@ -0,0 +1,251 @@
1 +from __future__ import annotations
2 +
3 +from decimal import Decimal
4 +from io import BytesIO
5 +
6 +import pytest
7 +from openpyxl import load_workbook
8 +
9 +from aram_backend.pilot_engine import (
10 + PilotModelError,
11 + build_report,
12 + export_report_workbook,
13 + parse_pilot_model,
14 +)
15 +from test_pilot_workbook import workbook_bytes
16 +
17 +
18 +def account_row(code, name, closing, *, debit=0, credit=0, source_row=2):
19 + opening = closing - debit + credit
20 + return (
21 + "C1", 1404, code, "کل", None, None, None, None, None, None, None,
22 + None, None, None, code, name, opening, debit, credit, closing,
23 + source_row, "Draft", 0,
24 + )
25 +
26 +
27 +def note_row(statement, section, number, title):
28 + return ("C1", 1404, statement, section, number, title, None, None)
29 +
30 +
31 +def mapping_row(mid, code, statement, section, number, *, approval="Approved"):
32 + reviewed = approval in {"Reviewed", "Approved"}
33 + return (
34 + mid, "C1", 1404, code, "General", code, None, None, None, None, None,
35 + statement, section, number, None, 1, approval,
36 + "tester" if reviewed else None, "2026-12-03" if reviewed else None,
37 + "test", None, "Valid" if approval == "Approved" else "Pending",
38 + )
39 +
40 +
41 +BALANCED_NOTES = [
42 + note_row("BS", "Assets", "01", "نقد"),
43 + note_row("BS", "Liabilities", "02", "پرداختنی"),
44 + note_row("BS", "Equity", "03", "سرمایه"),
45 + note_row("IS", "Revenue", "04", "فروش"),
46 + note_row("IS", "Expenses", "05", "هزینه"),
47 +]
48 +BALANCED_ACCOUNTS = [
49 + account_row("10", "نقد", 100, debit=150, credit=50, source_row=10),
50 + account_row("20", "پرداختنی", -60, credit=60, source_row=11),
51 + account_row("30", "سرمایه", -30, credit=30, source_row=12),
52 + account_row("40", "فروش", -20, credit=20, source_row=13),
53 + account_row("50", "هزینه", 10, debit=10, source_row=14),
54 +]
55 +BALANCED_MAPPINGS = [
56 + mapping_row("M1", "10", "BS", "Assets", "01"),
57 + mapping_row("M2", "20", "BS", "Liabilities", "02"),
58 + mapping_row("M3", "30", "BS", "Equity", "03"),
59 + mapping_row("M4", "40", "IS", "Revenue", "04"),
60 + mapping_row("M5", "50", "IS", "Expenses", "05"),
61 +]
62 +
63 +
64 +def balanced_rows():
65 + return {
66 + "Company": [("C1", "شرکت آزمون", 1404, "IRR", "rial", "tester", "Draft")],
67 + "Accounts": list(BALANCED_ACCOUNTS),
68 + "Notes": list(BALANCED_NOTES),
69 + "Mapping": list(BALANCED_MAPPINGS),
70 + }
71 +
72 +
73 +def build_balanced_workbook() -> bytes:
74 + return workbook_bytes(balanced_rows())
75 +
76 +
77 +def test_balanced_workbook_produces_complete_approved_report():
78 + model = parse_pilot_model(build_balanced_workbook())
79 + report = build_report(model, model.mappings)
80 + assert report["status"] == {
81 + "label": "COMPLETE_APPROVED", "complete": True, "all_mappings_approved": True,
82 + }
83 + assert report["totals"]["assets"] == "100"
84 + assert report["totals"]["liabilities"] == "60"
85 + assert report["totals"]["equity"] == "30"
86 + assert report["totals"]["liabilities_and_equity"] == "90"
87 + assert report["totals"]["profit"] == "10"
88 + assert all(check["passed"] for check in report["checks"])
89 + assert report["exceptions"] == []
90 + assets = report["statements"]["BS"]["sections"][0]
91 + assert assets["total"] == "100"
92 + line = assets["lines"][0]
93 + assert line["accounts"][0]["source_row"] == 10
94 + assert line["accounts"][0]["display"] == "100"
95 +
96 +
97 +def test_unmapped_account_blocks_completeness_and_enters_queue():
98 + rows = balanced_rows()
99 + rows["Mapping"] = rows["Mapping"][:-1] # expense account unmapped
100 + model = parse_pilot_model(workbook_bytes(rows))
101 + report = build_report(model, model.mappings)
102 + assert report["status"]["label"] == "INCOMPLETE"
103 + assert [e["code"] for e in report["exceptions"]] == ["UNMAPPED_ACCOUNT"]
104 + assert report["exceptions"][0]["account_code"] == "50"
105 + failed = {c["code"] for c in report["checks"] if not c["passed"]}
106 + assert failed == {"FULL_COVERAGE", "ACCOUNTING_EQUATION"}
107 +
108 +
109 +def test_deferred_cf_and_eq_targets_are_reported_not_rendered():
110 + rows = balanced_rows()
111 + rows["Notes"].append(note_row("CF", "Operating", "06", "جریان نقدی"))
112 + rows["Mapping"][4] = mapping_row("M5", "50", "CF", "Operating", "06")
113 + model = parse_pilot_model(workbook_bytes(rows))
114 + report = build_report(model, model.mappings)
115 + assert report["status"]["label"] == "INCOMPLETE"
116 + assert report["exceptions"][0]["code"] == "DEFERRED_STATEMENT"
117 + assert set(report["statements"]) == {"BS", "IS"}
118 +
119 +
120 +def test_unknown_section_fails_closed_instead_of_guessing():
121 + rows = balanced_rows()
122 + rows["Notes"].append(note_row("BS", "Mystery", "06", "بخش ناشناخته"))
123 + rows["Mapping"][0] = mapping_row("M1", "10", "BS", "Mystery", "06")
124 + model = parse_pilot_model(workbook_bytes(rows))
125 + report = build_report(model, model.mappings)
126 + assert report["exceptions"][0]["code"] == "UNSUPPORTED_SECTION"
127 + assert report["statements"]["BS"]["sections"][0]["total"] == "0"
128 +
129 +
130 +def test_conflicting_mappings_are_excluded_until_explicit_resolution():
131 + rows = balanced_rows()
132 + rows["Notes"].append(note_row("BS", "Assets", "06", "مقصد دوم"))
133 + rows["Mapping"].append(mapping_row("M6", "10", "BS", "Assets", "06"))
134 + model = parse_pilot_model(workbook_bytes(rows))
135 + assert "10" in model.conflicts and "10" not in model.mappings
136 + report = build_report(model, model.mappings)
137 + assert report["exceptions"][0]["code"] == "MAPPING_CONFLICT"
138 +
139 + # An explicit workbench mapping resolves the conflict, with provenance.
140 + from aram_backend.pilot_engine import MappingEntry
141 + resolved = dict(model.mappings)
142 + resolved["10"] = MappingEntry(
143 + "10", "BS", "Assets", "01", "", "Draft", "", "workbench", "WB-1"
144 + )
145 + report = build_report(model, resolved)
146 + assert all(e["code"] != "MAPPING_CONFLICT" for e in report["exceptions"])
147 + assert report["statements"]["BS"]["sections"][0]["total"] == "100"
148 +
149 +
150 +def test_identical_duplicate_mappings_are_deduplicated():
151 + rows = balanced_rows()
152 + rows["Mapping"].append(mapping_row("M6", "10", "BS", "Assets", "01"))
153 + model = parse_pilot_model(workbook_bytes(rows))
154 + assert not model.conflicts
155 + report = build_report(model, model.mappings)
156 + assert report["coverage"]["mapped_accounts"] == 5
157 + assert report["status"]["complete"]
158 +
159 +
160 +def test_draft_mappings_keep_output_in_draft_state():
161 + rows = balanced_rows()
162 + rows["Mapping"][0] = mapping_row("M1", "10", "BS", "Assets", "01", approval="Draft")
163 + model = parse_pilot_model(workbook_bytes(rows))
164 + report = build_report(model, model.mappings)
165 + assert report["status"] == {
166 + "label": "COMPLETE_DRAFT", "complete": True, "all_mappings_approved": False,
167 + }
168 +
169 +
170 +def test_decimal_precision_is_preserved_as_exact_strings():
171 + rows = balanced_rows()
172 + rows["Accounts"] = [
173 + account_row("10", "نقد", Decimal("10.10")),
174 + account_row("20", "پرداختنی", Decimal("-6.06")),
175 + account_row("30", "سرمایه", Decimal("-3.03")),
176 + account_row("40", "فروش", Decimal("-2.02")),
177 + account_row("50", "هزینه", Decimal("1.01")),
178 + ]
179 + model = parse_pilot_model(workbook_bytes(rows))
180 + report = build_report(model, model.mappings)
181 + # Excel numeric storage drops trailing zeros (10.10 -> 10.1) but the
182 + # decimal value itself must survive exactly, with no float drift.
183 + assert report["totals"]["assets"] == "10.1"
184 + assert report["totals"]["profit"] == "1.01"
185 + assert report["totals"]["liabilities_and_equity"] == "9.09"
186 + assert report["status"]["complete"]
187 +
188 +
189 +def test_invalid_workbook_raises_typed_error_with_issues():
190 + rows = balanced_rows()
191 + broken = list(rows["Accounts"][0])
192 + broken[19] = 999 # closing no longer ties
193 + rows["Accounts"][0] = tuple(broken)
194 + with pytest.raises(PilotModelError) as exc:
195 + parse_pilot_model(workbook_bytes(rows))
196 + assert any(i.code == "NON_ZERO_CLOSING_DELTA" for i in exc.value.issues)
197 +
198 +
199 +def test_multiple_companies_are_rejected_explicitly():
200 + rows = balanced_rows()
201 + rows["Company"].append(("C2", "شرکت دوم", 1404, "IRR", "rial", "t", "Draft"))
202 + with pytest.raises(PilotModelError) as exc:
203 + parse_pilot_model(workbook_bytes(rows))
204 + assert exc.value.issues[0].code == "WORKBENCH_SINGLE_COMPANY_REQUIRED"
205 +
206 +
207 +def test_empty_accounts_never_report_complete():
208 + rows = balanced_rows()
209 + rows["Accounts"] = []
210 + rows["Mapping"] = []
211 + model = parse_pilot_model(workbook_bytes(rows))
212 + report = build_report(model, model.mappings)
213 + assert report["status"]["label"] == "INCOMPLETE"
214 + assert not report["checks"][0]["passed"]
215 +
216 +
217 +def test_report_is_deterministic():
218 + data = build_balanced_workbook()
219 + first = build_report(parse_pilot_model(data), parse_pilot_model(data).mappings)
220 + second = build_report(parse_pilot_model(data), parse_pilot_model(data).mappings)
221 + assert first == second
222 +
223 +
224 +def test_export_contains_all_sheets_and_exact_provenance():
225 + model = parse_pilot_model(build_balanced_workbook())
226 + report = build_report(model, model.mappings)
227 + trail = [{"at": "2026-12-03T00:00:00+00:00", "actor": "tester", "account_code": "10",
228 + "action": "set_mapping", "before": "(بدون نگاشت)", "after": "BS/Assets/01"}]
229 + data = export_report_workbook(model, model.mappings, report, trail, "upload")
230 + book = load_workbook(BytesIO(data))
231 + assert book.sheetnames == [
232 + "Info", "Checks", "BalanceSheet", "IncomeStatement",
233 + "Coverage", "Exceptions", "AuditTrail",
234 + ]
235 + info = {row[0]: row[1] for row in book["Info"].iter_rows(min_row=2, values_only=True)}
236 + assert info["source_sha256"] == model.source_sha256
237 + assert info["status"] == "COMPLETE_APPROVED"
238 + amounts = [row[4] for row in book["BalanceSheet"].iter_rows(min_row=2, values_only=True)
239 + if row[0] == "note"]
240 + assert 100.0 in amounts
241 + assert book["Coverage"].max_row == 6 # header + 5 accounts
242 + assert book["AuditTrail"].max_row == 2
243 + book.close()
244 +
245 +
246 +def test_engine_never_writes_files(tmp_path, monkeypatch):
247 + monkeypatch.chdir(tmp_path)
248 + model = parse_pilot_model(build_balanced_workbook())
249 + report = build_report(model, model.mappings)
250 + export_report_workbook(model, model.mappings, report, [], "demo")
251 + assert list(tmp_path.iterdir()) == []
backend/tests/test_preflight.py new
+75
@@ -0,0 +1,75 @@
1 +"""D-02 acceptance: controls C-01..C-04 run as an ingestion preflight."""
2 +
3 +from __future__ import annotations
4 +
5 +from decimal import Decimal
6 +
7 +from aram_backend.domain.controls import MappingTarget
8 +from aram_backend.ledger_parser import LedgerRecord
9 +from aram_backend.services.preflight import run_preflight
10 +
11 +
12 +def _rec(row, code, opening, debit, credit, closing, general="14"):
13 + return LedgerRecord(
14 + row_number=row,
15 + account_code=code,
16 + general_code=general,
17 + account_name="نمونه",
18 + source_year=1404,
19 + entry_type="O",
20 + t1_code=None,
21 + t2_code=None,
22 + t3_code=None,
23 + t4_code=None,
24 + opening=Decimal(opening),
25 + debit=Decimal(debit),
26 + credit=Decimal(credit),
27 + closing=Decimal(closing),
28 + )
29 +
30 +
31 +def test_clean_ledger_passes_c01_c02():
32 + # Two accounts that balance: debit total == credit total, closing sums to 0.
33 + records = [
34 + _rec(3, "8348", 0, 100, 0, 100),
35 + _rec(4, "8349", 0, 0, 100, -100),
36 + ]
37 + report = run_preflight(records)
38 + by_code = {r.code: r for r in report.results}
39 + assert by_code["C-01"].passed
40 + assert by_code["C-02"].passed
41 +
42 +
43 +def test_c01_violation_blocks():
44 + records = [_rec(3, "8348", 0, 100, 0, 999)] # closing wrong
45 + report = run_preflight(records)
46 + assert not report.can_approve
47 + assert any(r.code == "C-01" and not r.passed for r in report.blocking)
48 +
49 +
50 +def test_unmapped_accounts_enter_unknown_queue():
51 + records = [_rec(3, "8348", 0, 100, 0, 100)]
52 + report = run_preflight(records) # no mappings
53 + assert report.unknown_accounts == ("148348",)
54 + assert not report.can_approve # C-03/C-04 block approval
55 +
56 +
57 +def test_mapping_clears_unknown_queue():
58 + records = [_rec(3, "8348", 0, 100, 0, 100)]
59 + mappings = {"148348": [MappingTarget(target="note-1")]}
60 + report = run_preflight(records, mappings=mappings)
61 + assert report.unknown_accounts == ()
62 + by_code = {r.code: r for r in report.results}
63 + assert by_code["C-03"].passed
64 + assert by_code["C-04"].passed
65 +
66 +
67 +def test_all_four_controls_present():
68 + report = run_preflight([_rec(3, "8348", 0, 0, 0, 0)])
69 + assert [r.code for r in report.results] == ["C-01", "C-02", "C-03", "C-04"]
70 +
71 +
72 +def test_inactive_account_not_queued():
73 + # All-zero account is inactive; must not enter the unknown queue.
74 + report = run_preflight([_rec(3, "8348", 0, 0, 0, 0)])
75 + assert report.unknown_accounts == ()
backend/tests/test_source_store.py new
+126
@@ -0,0 +1,126 @@
1 +"""D-06 acceptance: content-addressed source storage + hash-verified re-import."""
2 +
3 +from __future__ import annotations
4 +
5 +import hashlib
6 +import io
7 +
8 +import pytest
9 +from openpyxl import Workbook
10 +
11 +from aram_backend.ingestion import register_source_document
12 +from aram_backend.ledger_parser import parse_general_ledger, parse_ledger
13 +from aram_backend.models import Company, FiscalYear, SourceFile
14 +from aram_backend.services.source_store import SourceStore, SourceStoreError
15 +
16 +
17 +def _xlsx_bytes():
18 + wb = Workbook()
19 + ws = wb.active
20 + ws.title = "Source"
21 + ws.append(["source ledger"])
22 + ws.append(
23 + [
24 + "حساب",
25 + "kol",
26 + "ACCOUNT_NAME",
27 + "year",
28 + "نوع",
29 + "T1_CODE",
30 + "T2_CODE",
31 + "T3_CODE",
32 + "T4_CODE",
33 + "OPENING",
34 + "Debit",
35 + "Credit",
36 + "CLOSING",
37 + ]
38 + )
39 + ws.append(["0101", "14", "نمونه", 1404, "O", None, None, None, None, 0, 100, 0, 100])
40 + buf = io.BytesIO()
41 + wb.save(buf)
42 + wb.close()
43 + return buf.getvalue()
44 +
45 +
46 +def _make_year(session):
47 + company = Company(code="SRC", name="شرکت")
48 + session.add(company)
49 + session.flush()
50 + year = FiscalYear(company_id=company.id, year=1404)
51 + session.add(year)
52 + session.flush()
53 + return year
54 +
55 +
56 +class TestSourceStore:
57 + def test_put_get_roundtrip(self, tmp_path):
58 + store = SourceStore(tmp_path / "store")
59 + content = b"immutable source bytes"
60 + stored = store.put(content)
61 + assert stored.sha256 == hashlib.sha256(content).hexdigest()
62 + assert stored.size == len(content)
63 + assert store.get(stored.sha256) == content
64 +
65 + def test_put_idempotent(self, tmp_path):
66 + store = SourceStore(tmp_path / "store")
67 + a = store.put(b"same")
68 + b = store.put(b"same")
69 + assert a.sha256 == b.sha256
70 + assert a.stored_path == b.stored_path
71 +
72 + def test_empty_rejected(self, tmp_path):
73 + with pytest.raises(SourceStoreError):
74 + SourceStore(tmp_path).put(b"")
75 +
76 + def test_corruption_detected(self, tmp_path):
77 + store = SourceStore(tmp_path / "store")
78 + stored = store.put(b"original")
79 + # Tamper with the stored bytes; the hash check must fail loudly.
80 + from pathlib import Path
81 +
82 + Path(stored.stored_path).write_bytes(b"tampered")
83 + with pytest.raises(SourceStoreError):
84 + store.get(stored.sha256)
85 +
86 + def test_missing_file_raises(self, tmp_path):
87 + with pytest.raises(SourceStoreError):
88 + SourceStore(tmp_path).get("0" * 64)
89 +
90 +
91 +class TestRegistrationWithStore:
92 + def test_bytes_persisted_and_reimport_matches_hash(self, session, tmp_path):
93 + year = _make_year(session)
94 + store = SourceStore(tmp_path / "store")
95 + content = _xlsx_bytes()
96 + source = register_source_document(
97 + session,
98 + year_id=year.id,
99 + filename="ledger.xlsx",
100 + document_type="general_ledger",
101 + content=content,
102 + store=store,
103 + )
104 + session.commit()
105 + assert source.source_file_hash == hashlib.sha256(content).hexdigest()
106 + assert not hasattr(source, "content") # metadata-only model (accepted contract)
107 + sf = session.get(SourceFile, source.source_file_hash)
108 + assert sf is not None and sf.size == len(content)
109 + # Re-import from the stored bytes: hash matches and rows parse identically.
110 + retrieved = store.get(source.source_file_hash)
111 + assert hashlib.sha256(retrieved).hexdigest() == source.file_hash
112 + original = list(parse_general_ledger(content))
113 + again = list(parse_ledger(retrieved, "ledger.xlsx"))
114 + assert again == original
115 +
116 + def test_without_store_backward_compatible(self, session):
117 + year = _make_year(session)
118 + source = register_source_document(
119 + session,
120 + year_id=year.id,
121 + filename="ledger.xlsx",
122 + document_type="general_ledger",
123 + content=_xlsx_bytes(),
124 + )
125 + session.commit()
126 + assert source.source_file_hash is None
backend/tests/test_statement_build.py new
+314
@@ -0,0 +1,314 @@
1 +"""Phase 1 acceptance: persistent statement build + drill-down + vertical-slice API."""
2 +
3 +from __future__ import annotations
4 +
5 +from decimal import Decimal
6 +from pathlib import Path
7 +
8 +import pytest
9 +from openpyxl import load_workbook
10 +
11 +from aram_backend.domain.normalization import decimal_from_cell, normalize_code
12 +from aram_backend.ingestion import register_source_document
13 +from aram_backend.ledger_parser import LedgerRecord
14 +from aram_backend.models import (
15 + Company,
16 + FiscalYear,
17 + LedgerBalance,
18 + MappingRule,
19 + NoteDefinition,
20 + StatementType,
21 +)
22 +from aram_backend.services.ledger_import import import_ledger_balances
23 +from aram_backend.services.statement_build import (
24 + StatementBuildError,
25 + build_statements,
26 + drill_down,
27 +)
28 +
29 +
30 +def _setup(session):
31 + company = Company(code="V1", name="شرکت نمونه")
32 + session.add(company)
33 + session.flush()
34 + year = FiscalYear(company_id=company.id, year=1404)
35 + session.add(year)
36 + session.flush()
37 + source = register_source_document(
38 + session,
39 + year_id=year.id,
40 + filename="source_1404.xlsx",
41 + document_type="general_ledger",
42 + content=b"vertical-slice-bytes",
43 + )
44 + session.flush()
45 + return year, source
46 +
47 +
48 +def _balance(session, year, source, code, closing, row):
49 + session.add(
50 + LedgerBalance(
51 + year_id=year.id,
52 + source_document_id=source.id,
53 + source_sheet="Source",
54 + source_row=row,
55 + import_version=1,
56 + account_full_code=code,
57 + general_code=code[:2],
58 + subsidiary_code=code[2:],
59 + account_name=f"حساب {code}",
60 + opening=Decimal(0),
61 + debit=Decimal(max(closing, 0)),
62 + credit=Decimal(max(-closing, 0)),
63 + closing=Decimal(closing),
64 + )
65 + )
66 +
67 +
68 +def _note(session, year, number, title, statement, section):
69 + note = NoteDefinition(
70 + year_id=year.id,
71 + note_number=number,
72 + title=title,
73 + configuration_json={"statement": statement, "section": section},
74 + )
75 + session.add(note)
76 + session.flush()
77 + return note
78 +
79 +
80 +def _map(session, year, code, note):
81 + session.add(
82 + MappingRule(
83 + year_id=year.id,
84 + rule_key=f"{code}->{note.id}",
85 + account_code=code,
86 + target_note_id=note.id,
87 + mapping_type="closing",
88 + )
89 + )
90 +
91 +
92 +def _seed_full(session):
93 + year, source = _setup(session)
94 + _balance(session, year, source, "148348", 100, 3) # asset
95 + _balance(session, year, source, "241001", -60, 4) # liability
96 + _balance(session, year, source, "341001", -40, 5) # equity
97 + _balance(session, year, source, "541001", -250, 6) # revenue
98 + _balance(session, year, source, "641001", 200, 7) # expense
99 + n_cash = _note(session, year, "6", "نقد", "BS", "Assets")
100 + n_pay = _note(session, year, "10", "پرداختنی", "BS", "Liabilities")
101 + n_cap = _note(session, year, "12", "سرمایه", "BS", "Equity")
102 + n_rev = _note(session, year, "20", "فروش", "IS", "Revenue")
103 + n_exp = _note(session, year, "22", "بهای تمام‌شده", "IS", "Expenses")
104 + _map(session, year, "148348", n_cash)
105 + _map(session, year, "241001", n_pay)
106 + _map(session, year, "341001", n_cap)
107 + _map(session, year, "541001", n_rev)
108 + _map(session, year, "641001", n_exp)
109 + session.flush()
110 + return year, n_cash
111 +
112 +
113 +class TestStatementBuild:
114 + def test_bs_is_totals_and_signs(self, session):
115 + year, _ = _seed_full(session)
116 + result = build_statements(session, year.id)
117 + session.commit()
118 + assert {s.statement_type for s in result.statements} == {
119 + StatementType.BALANCE_SHEET,
120 + StatementType.INCOME_STATEMENT,
121 + }
122 + bs = next(s for s in result.statements if s.statement_type == StatementType.BALANCE_SHEET)
123 + totals = {ln.line_label.split(" — ")[0]: ln.mapped_total for ln in bs.lines}
124 + assert totals["6"] == Decimal(100) # asset +1
125 + assert totals["10"] == Decimal(60) # liability -1 x -60
126 + assert totals["12"] == Decimal(40) # equity -1 x -40
127 + is_stmt = next(
128 + s for s in result.statements if s.statement_type == StatementType.INCOME_STATEMENT
129 + )
130 + is_totals = {ln.line_label.split(" — ")[0]: ln.mapped_total for ln in is_stmt.lines}
131 + assert is_totals["20"] == Decimal(250) # revenue -1 x -250
132 + assert is_totals["22"] == Decimal(200) # expense +1
133 +
134 + def test_drilldown_to_source_row(self, session):
135 + year, n_cash = _seed_full(session)
136 + result = build_statements(session, year.id)
137 + session.commit()
138 + bs = next(s for s in result.statements if s.statement_type == StatementType.BALANCE_SHEET)
139 + cash_line = next(ln for ln in bs.lines if ln.target_note_id == n_cash.id)
140 + lineage = drill_down(session, cash_line.id)
141 + assert lineage["note"]["note_number"] == "6"
142 + assert len(lineage["accounts"]) == 1
143 + acct = lineage["accounts"][0]
144 + assert acct["account_full_code"] == "148348"
145 + assert acct["source"]["filename"] == "source_1404.xlsx"
146 + assert acct["source"]["sheet"] == "Source"
147 + assert acct["source"]["row"] == 3
148 + assert acct["source"]["file_hash"]
149 +
150 + def test_new_version_per_build(self, session):
151 + year, _ = _seed_full(session)
152 + r1 = build_statements(session, year.id)
153 + session.commit()
154 + r2 = build_statements(session, year.id)
155 + session.commit()
156 + v1 = {s.statement_type: s.version for s in r1.statements}
157 + v2 = {s.statement_type: s.version for s in r2.statements}
158 + assert v2[StatementType.BALANCE_SHEET] == v1[StatementType.BALANCE_SHEET] + 1
159 +
160 + def test_unmapped_active_account_surfaced(self, session):
161 + year, source = _setup(session)
162 + _balance(session, year, source, "148348", 100, 3)
163 + session.flush()
164 + result = build_statements(session, year.id)
165 + session.commit()
166 + assert "148348" in result.unmapped_accounts
167 +
168 + def test_unknown_statement_type_raises(self, session):
169 + year, _ = _seed_full(session)
170 + with pytest.raises(StatementBuildError):
171 + build_statements(session, year.id, statement_types=("XX",))
172 +
173 +
174 +# --------------------------------------------------------------- API e2e
175 +CSV = (
176 + "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
177 + "8348,14,نقد,1404,O,,,,,0,100,0,100\n"
178 + "1001,24,پرداختنی,1404,O,,,,,0,0,60,-60\n"
179 +).encode()
180 +
181 +
182 +class TestVerticalSliceApi:
183 + def test_end_to_end(self, api_client):
184 + c = api_client
185 + r = c.post("/api/v1/companies", json={"code": "E2E", "name": "شرکت", "year": 1404})
186 + assert r.status_code == 200
187 + year_id = r.json()["year_id"]
188 +
189 + r = c.post(
190 + f"/api/v1/years/{year_id}/ledger",
191 + files={"file": ("ledger.csv", CSV, "text/csv")},
192 + )
193 + assert r.status_code == 200, r.text
194 + assert r.json()["accounts_imported"] == 2
195 +
196 + r = c.post(
197 + f"/api/v1/years/{year_id}/notes",
198 + json={"note_number": "6", "title": "نقد", "statement": "BS", "section": "Assets"},
199 + )
200 + note_id = r.json()["note_id"]
201 + r = c.post(
202 + f"/api/v1/years/{year_id}/mappings",
203 + json={"account_code": "148348", "target_note_id": note_id},
204 + )
205 + assert r.status_code == 200
206 +
207 + r = c.post(f"/api/v1/years/{year_id}/statements/build")
208 + assert r.status_code == 200, r.text
209 + assert "148348" not in r.json()["unmapped_accounts"]
210 +
211 + r = c.get(f"/api/v1/years/{year_id}/statements")
212 + assert r.status_code == 200
213 + bs = next(s for s in r.json()["statements"] if s["type"] == "BS")
214 + cash_line = next(ln for ln in bs["lines"] if ln["target_note_id"] == note_id)
215 + assert cash_line["mapped_total"] == "100"
216 +
217 + r = c.get(f"/api/v1/statement-lines/{cash_line['id']}/drilldown")
218 + assert r.status_code == 200
219 + acct = r.json()["accounts"][0]
220 + assert acct["source"]["filename"] == "ledger.csv"
221 + assert acct["source"]["row"] == 2
222 +
223 + def test_preflight_reports_controls(self, api_client):
224 + c = api_client
225 + year_id = c.post(
226 + "/api/v1/companies", json={"code": "PF", "name": "x", "year": 1404}
227 + ).json()["year_id"]
228 + c.post(f"/api/v1/years/{year_id}/ledger", files={"file": ("l.csv", CSV, "text/csv")})
229 + r = c.get(f"/api/v1/years/{year_id}/preflight")
230 + assert r.status_code == 200
231 + codes = {ctl["code"] for ctl in r.json()["controls"]}
232 + assert codes == {"C-01", "C-02", "C-03", "C-04"}
233 +
234 +
235 +# ------------------------------------------------- bounded real-data smoke
236 +_REPO_ROOT = Path(__file__).resolve().parents[2]
237 +_LEDGER_1404 = _REPO_ROOT / "data" / "source_ledgers" / "source_1404.xlsx"
238 +
239 +
240 +@pytest.mark.skipif(not _LEDGER_1404.exists(), reason="canonical ledger not present")
241 +class TestRealDataVerticalSlice:
242 + """Bounded read-only smoke: real 1404 rows -> import -> build -> drill-down.
243 +
244 + Proves the persistent pipeline and lineage on canonical account codes/rows.
245 + Full rial-for-rial reconciliation against official statements is Phase 4.
246 + """
247 +
248 + def _records(self, limit=3000):
249 + wb = load_workbook(_LEDGER_1404, read_only=True, data_only=True, keep_links=False)
250 + ws = wb["Source"]
251 + rows = ws.iter_rows(values_only=True)
252 + next(rows)
253 + header = next(rows)
254 + idx = {str(v).strip(): i for i, v in enumerate(header) if v is not None}
255 + out = []
256 + for row_number, vals in enumerate(rows, start=3):
257 + if not any(v is not None for v in vals):
258 + continue
259 + try:
260 + year = int(decimal_from_cell(vals[idx["year"]], row=row_number, field="year"))
261 + if year != 1404:
262 + continue
263 + money = [vals[idx[k]] for k in ("OPENING", "Debit", "Credit", "CLOSING")]
264 + if any(m is None for m in money):
265 + continue
266 + rec = LedgerRecord(
267 + row_number=row_number,
268 + account_code=normalize_code(vals[idx["حساب"]], row=row_number, field="حساب"),
269 + general_code=normalize_code(vals[idx["kol"]], row=row_number, field="kol"),
270 + account_name=str(vals[idx["ACCOUNT_NAME"]] or ""),
271 + source_year=year,
272 + entry_type=str(vals[idx["نوع"]] or ""),
273 + t1_code=None,
274 + t2_code=None,
275 + t3_code=None,
276 + t4_code=None,
277 + opening=decimal_from_cell(money[0], row=row_number, field="OPENING"),
278 + debit=decimal_from_cell(money[1], row=row_number, field="Debit"),
279 + credit=decimal_from_cell(money[2], row=row_number, field="Credit"),
280 + closing=decimal_from_cell(money[3], row=row_number, field="CLOSING"),
281 + )
282 + except Exception:
283 + continue
284 + out.append(rec)
285 + if len(out) >= limit:
286 + break
287 + wb.close()
288 + return out
289 +
290 + def test_import_build_drilldown_on_real_rows(self, session):
291 + records = self._records()
292 + assert len(records) > 100
293 + year, source = _setup(session)
294 + count = import_ledger_balances(
295 + session, year_id=year.id, source_document_id=source.id, records=records
296 + )
297 + assert count > 0
298 + first = records[0]
299 + code = (first.general_code or "") + first.account_code
300 + note = _note(session, year, "6", "نقد", "BS", "Assets")
301 + _map(session, year, code, note)
302 + session.flush()
303 + result = build_statements(session, year.id)
304 + session.commit()
305 + bs = next(s for s in result.statements if s.statement_type == StatementType.BALANCE_SHEET)
306 + line = next(ln for ln in bs.lines if ln.target_note_id == note.id)
307 + lineage = drill_down(session, line.id)
308 + assert lineage["accounts"], "drill-down must reach real ledger rows"
309 + src = lineage["accounts"][0]["source"]
310 + assert src["filename"] == "source_1404.xlsx"
311 + assert src["sheet"] == "Source"
312 + assert src["row"] >= 3
313 + # Most real accounts remain unmapped at this stage (Phase 2 resolves them).
314 + assert len(result.unmapped_accounts) > 0
backend/tests/test_statement_export.py new
+120
@@ -0,0 +1,120 @@
1 +"""Phase 6 reviewable outputs: XLSX + JSON export with exact rial and lineage."""
2 +
3 +from __future__ import annotations
4 +
5 +import json
6 +from decimal import Decimal
7 +from io import BytesIO
8 +
9 +from openpyxl import load_workbook
10 +
11 +from aram_backend.ledger_parser import parse_ledger
12 +from aram_backend.models import (
13 + Company,
14 + FiscalYear,
15 + MappingRule,
16 + NoteDefinition,
17 + NoteRow,
18 + SourceDocument,
19 +)
20 +from aram_backend.services.ledger_import import import_ledger_balances
21 +from aram_backend.services.statement_build import build_statements
22 +from aram_backend.services.statement_export import (
23 + export_statements_json,
24 + export_statements_workbook,
25 +)
26 +
27 +_HEADER = (
28 + "حساب,ACCOUNT_NAME,year,نوع,kol,T1_CODE,T2_CODE,T3_CODE,T4_CODE,"
29 + "OPENING,Debit,Credit,CLOSING,مانده صورت مالی"
30 +)
31 +
32 +
33 +def _setup(session):
34 + company = Company(code="X1", name="شرکت نمونه")
35 + session.add(company)
36 + session.flush()
37 + year = FiscalYear(company_id=company.id, year=1404)
38 + session.add(year)
39 + session.flush()
40 + # Ordinary closing-based row: acct() reads closing (ADR-020) and the BS
41 + # Assets sign (+1) keeps it positive, so note value == statement line total.
42 + content = (_HEADER + "\n1101,نقد و بانک,1404,e,11,,,,,0,0,0,673740637000000,\n").encode("utf-8")
43 + records = list(parse_ledger(content, "ledger.csv", tolerant=True))
44 + src = SourceDocument(
45 + year_id=year.id, filename="ledger.csv", document_type="general_ledger", file_hash="a" * 64
46 + )
47 + session.add(src)
48 + session.flush()
49 + import_ledger_balances(
50 + session, year_id=year.id, source_document_id=src.id, records=records, import_version=1
51 + )
52 + note = NoteDefinition(
53 + year_id=year.id,
54 + note_number="10",
55 + title="دارایی‌های جاری",
56 + configuration_json={"statement": "BS", "section": "Assets"},
57 + )
58 + session.add(note)
59 + session.flush()
60 + session.add(
61 + MappingRule(
62 + year_id=year.id,
63 + rule_key="111101->n",
64 + account_code="111101",
65 + target_note_id=note.id,
66 + mapping_type="closing",
67 + )
68 + )
69 + session.add(NoteRow(note_id=note.id, row_order=0, label="جمع", formula_logic='acct("111101")'))
70 + session.flush()
71 + build_statements(session, year.id, statement_types=("BS",))
72 + return year.id
73 +
74 +
75 +def test_json_export_exact_rial_and_lineage(session):
76 + year_id = _setup(session)
77 + payload = export_statements_json(session, year_id)
78 + assert payload["year"] == 1404
79 + bs = next(s for s in payload["statements"] if s["type"] == "BS")
80 + line = bs["lines"][0]
81 + assert line["mapped_total_rial"] == "673740637000000"
82 + assert line["mapped_total_million"] == 673740637
83 + # Lineage traces to the exact source row.
84 + assert payload["lineage"], "lineage must not be empty"
85 + row = payload["lineage"][0]
86 + assert row["filename"] == "ledger.csv"
87 + assert row["source_row"] == 2
88 + assert row["effective_balance_rial"] == "673740637000000"
89 + # Note evaluated.
90 + note = payload["notes"][0]
91 + assert note["rows"][0]["value"] == "673740637000000"
92 +
93 +
94 +def test_xlsx_export_sheets_and_values(session):
95 + year_id = _setup(session)
96 + data = export_statements_workbook(session, year_id)
97 + wb = load_workbook(BytesIO(data), data_only=True)
98 + assert "Summary" in wb.sheetnames
99 + assert "BS" in wb.sheetnames
100 + assert "Lineage" in wb.sheetnames
101 + assert "Note 10" in wb.sheetnames
102 + bs = wb["BS"]
103 + # header row + one line; rial column is exact integer text.
104 + assert bs.cell(row=2, column=3).value == "673740637000000"
105 + assert bs.cell(row=2, column=4).value == 673740637
106 + lineage = wb["Lineage"]
107 + assert lineage.max_row >= 2
108 + wb.close()
109 +
110 +
111 +def test_json_export_is_serializable(session):
112 + year_id = _setup(session)
113 + payload = export_statements_json(session, year_id)
114 + # Must round-trip through JSON without Decimal leakage.
115 + text = json.dumps(payload, ensure_ascii=False)
116 + assert "673740637000000" in text
117 + assert isinstance(payload["statements"][0]["lines"][0]["mapped_total_rial"], str)
118 + assert Decimal(payload["statements"][0]["lines"][0]["mapped_total_rial"]) == Decimal(
119 + "673740637000000"
120 + )
backend/tests/test_tolerant_import.py new
+145
@@ -0,0 +1,145 @@
1 +"""Tolerant real-ledger import: reclassified rows preserved, anomalies reported.
2 +
3 +Proves D3/P-01 (raw rows kept for drill-down) and the Phase-4 statement-balance
4 +capture: empty money cells on reclassified rows become exact zero, the signed
5 +``مانده صورت مالی`` is stored, and a non-numeric money cell is skipped + reported
6 +(fail-loud, never invented).
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +from decimal import Decimal
12 +
13 +import pytest
14 +
15 +from aram_backend.ledger_parser import SkippedRow, parse_ledger
16 +from aram_backend.models import LedgerBalance
17 +from aram_backend.services.ledger_import import import_ledger_balances
18 +from aram_backend.services.statement_build import build_statements
19 +
20 +# Column order matches _FIELDS plus the optional statement-balance column.
21 +_COLUMNS = [
22 + "حساب",
23 + "ACCOUNT_NAME",
24 + "year",
25 + "نوع",
26 + "kol",
27 + "T1_CODE",
28 + "T2_CODE",
29 + "T3_CODE",
30 + "T4_CODE",
31 + "OPENING",
32 + "Debit",
33 + "Credit",
34 + "CLOSING",
35 + "مانده صورت مالی",
36 +]
37 +
38 +
39 +def _row(**fields: str) -> str:
40 + return ",".join(fields.get(col, "") for col in _COLUMNS)
41 +
42 +
43 +def _csv(rows: list[str]) -> bytes:
44 + return ("\n".join([",".join(_COLUMNS), *rows]) + "\n").encode("utf-8")
45 +
46 +
47 +_BASE = {"حساب": "1101", "ACCOUNT_NAME": "نقد و بانک", "year": "1404", "نوع": "e", "kol": "11"}
48 +
49 +
50 +def test_reclassified_row_kept_with_statement_balance():
51 + content = _csv([_row(**_BASE, **{"مانده صورت مالی": "-52400000000000"})])
52 + skipped: list[SkippedRow] = []
53 + records = list(parse_ledger(content, "ledger.csv", tolerant=True, skipped=skipped))
54 + assert len(records) == 1
55 + rec = records[0]
56 + assert rec.opening == Decimal(0)
57 + assert rec.closing == Decimal(0)
58 + assert rec.statement_balance == Decimal("-52400000000000")
59 + assert skipped == []
60 +
61 +
62 +def test_non_numeric_money_row_skipped_and_reported():
63 + content = _csv([_row(**_BASE, Debit="abc", Credit="0", CLOSING="0", OPENING="0")])
64 + skipped: list[SkippedRow] = []
65 + records = list(parse_ledger(content, "ledger.csv", tolerant=True, skipped=skipped))
66 + assert records == []
67 + assert len(skipped) == 1
68 + assert skipped[0].row_number == 2
69 + assert "Debit" in skipped[0].reason
70 +
71 +
72 +def test_strict_mode_still_fails_loud():
73 + content = _csv([_row(**_BASE, **{"مانده صورت مالی": "-52400000000000"})])
74 + with pytest.raises(ValueError):
75 + list(parse_ledger(content, "ledger.csv"))
76 +
77 +
78 +def test_statement_balance_drives_build_and_drilldown(session):
79 + from aram_backend.models import Company, FiscalYear, MappingRule, NoteDefinition, SourceDocument
80 +
81 + company = Company(code="T1", name="شرکت آزمون")
82 + session.add(company)
83 + session.flush()
84 + year = FiscalYear(company_id=company.id, year=1404)
85 + session.add(year)
86 + session.flush()
87 + year_id = year.id
88 +
89 + content = _csv(
90 + [
91 + _row(**_BASE, **{"مانده صورت مالی": "-673740637000000"}),
92 + _row(
93 + **{**_BASE, "حساب": "1102"}, OPENING="0", Debit="0", Credit="0", CLOSING="1000000"
94 + ),
95 + ]
96 + )
97 + records = list(parse_ledger(content, "ledger.csv", tolerant=True))
98 + src = SourceDocument(
99 + year_id=year_id, filename="ledger.csv", document_type="general_ledger", file_hash="h" * 64
100 + )
101 + session.add(src)
102 + session.flush()
103 + import_ledger_balances(
104 + session, year_id=year_id, source_document_id=src.id, records=records, import_version=1
105 + )
106 +
107 + note = NoteDefinition(
108 + year_id=year_id,
109 + note_number="10",
110 + title="دارایی‌های جاری",
111 + configuration_json={"statement": "BS", "section": "Assets"},
112 + )
113 + session.add(note)
114 + session.flush()
115 + session.add(
116 + MappingRule(
117 + year_id=year_id,
118 + rule_key="111101->n",
119 + account_code="111101",
120 + target_note_id=note.id,
121 + mapping_type="closing",
122 + )
123 + )
124 + session.add(
125 + MappingRule(
126 + year_id=year_id,
127 + rule_key="111102->n",
128 + account_code="111102",
129 + target_note_id=note.id,
130 + mapping_type="closing",
131 + )
132 + )
133 + session.flush()
134 +
135 + result = build_statements(session, year_id, statement_types=("BS",))
136 + line = result.statements[0].lines[0]
137 + # Reclassified row contributes its signed statement balance directly;
138 + # the ordinary closing row contributes sign(Assets=+1) * closing.
139 + assert line.mapped_total == Decimal("-673740637000000") + Decimal("1000000")
140 +
141 + rows = session.query(LedgerBalance).filter_by(year_id=year_id).all()
142 + assert len(rows) == 2 # raw rows preserved, not aggregated
143 + reclassified = next(r for r in rows if r.subsidiary_code == "1101")
144 + assert reclassified.statement_balance == Decimal("-673740637000000")
145 + assert reclassified.source_row == 2
docs/.nojekyll
docs/PROJECT_LOG.md
+76
@@ -278,3 +278,79 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
278 - Recovery: close the candidate PR without merge; accepted branch remains at the recorded base
279 - Remaining risks: comprehensive Mapping, note/sub-note workflow, real Pilot UI/output, Windows packaging, and user acceptance remain incomplete
280 - Next action: publish the focused PR and obtain independent remote review after CI
281 +
282 +### 2026-12-03T09:30:00Z — Booklet v1.0 Phase 0 debts executed
283 +
284 +- Actor: Arena agent (implementation), per booklet §17 autonomous default+proof+ADR
285 +- Task/phase: Phase 0 — clear debts D-01..D-12 before Phase 1 vertical slice
286 +- Base: `source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914`
287 +- Working branch: `arena/094f314c-aram`
288 +- Commits: `ac565e9` (domain + D-04/D-05/D-10/D-11 + ADR-012/013/014), `a3c330b` (D-01/D-03 LedgerBalance + Rial), `a661423` (D-06 source store + CSV), `00ca58e` (D-07 immutability triggers + hash-chained audit + reopen + ADR-016), `8f2f902` (D-02 controls preflight), `8412c56` (D-12 CI gates + ADR-017)
289 +- Implementation: pure financial domain (normalization/money/hierarchy/controls); LedgerBalance model with exact integer-rial BIGINT; content-addressed source-byte store + full CSV (UTF-8/BOM/Windows-1256, delimiter sniff); DB triggers block raw-SQL mutation of locked years; append-only hash-chained audit log + controlled reopen; C-01..C-04 ingestion preflight; CI quality gates (ruff, mypy strict domain, coverage total>=80%/domain>=90%, pip-audit, SQLite+PostgreSQL migration matrix)
290 +- Local tests: `cd backend && pytest` -> 201 passed
291 +- Gates: ruff check clean; ruff format (domain/services/migrations) clean; mypy domain strict clean; coverage total 92.23% / domain 97%; pip-audit no known vulnerabilities; SQLite alembic up/down/up clean; compileall clean; git diff --check clean
292 +- Real-data evidence (read-only): source_1404.xlsx 252,898 rows; debit-positive C-01 holds 252,892/252,898; Σdebit=Σcredit=10,823,163,409,740,108; OD-01 refuted, ADR-014 hierarchy adopted (general=kol, subsidiary=حساب, canonical=kol+حساب)
293 +- GitHub Actions: pending push of branch; CI matrix will exercise PostgreSQL
294 +- Artifacts/releases: `NONE`
295 +- Protected data: no canonical `data/`, `samples/`, XLSX/PDF, database, financial-source value, ZIP, EXE, tag, or release changed
296 +- D-09 (git-history rewrite): BLOCKED — owner-only, requires explicit approval (§19); not performed
297 +- Acceptance: `IN_PROGRESS`; implementation author must not merge
298 +- Reviewer: independent reviewer pending
299 +- Remaining risks: PostgreSQL path validated only in CI (no local PG); Phase 1+ vertical slice, mapping, notes, statements, UI, packaging, UAT remain
300 +- Next action: push branch, open focused Phase-0 PR, obtain independent remote review after CI; then Phase 1 vertical slice (1404)
301 +
302 +### 2026-12-03T10:45:00Z — Booklet v1.0 Phases 1–4 + owner priority fixes
303 +
304 +- Actor: Arena agent (implementation), per booklet §17 autonomous default+proof+ADR
305 +- Task/phase: Phases 1–4 vertical slice, then owner's 4 high-priority architecture fixes before new phases
306 +- Base: `source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914`
307 +- Working branch: `arena/094f314c-aram`
308 +- PR: [#96](https://github.com/davoodmehraban89/Aram/pull/96) (draft -> source-data-cleanup)
309 +- Commits: `9c33586` (Phase 1 statements+drill-down), `cfbd879` (Phase 2 mapping io), `9fba3c6` (Phase 3 note formula engine), `b79d68e` (Phase 4 WIP), `a00b0dc` (Fix 1 money/P-02), `f7c3b4a` (Fix 2 raw ledger rows), `1844a62` (Fix 3 approval gate), `225a38c` (Fix 4 services mypy+golden+negative tests), `be08192` (Fix 4 frontend CI gates), `accf1cc` (ruff cleanup)
310 +- Implementation: build_statements (BS/IS/CF/EQ) with source drill-down; mapping Excel import/export (fail-closed, idempotent); AST note-formula engine (no eval) with cycle detection; golden comparison resolving columns BY HEADER NAME (1403/1404 layouts differ); raw-row LedgerBalance storage + ledger_aggregate compute service + migration 20261203_05; explicit approval evaluate_controls with hard ERROR gate (C-03 double-mapping enforced); type-clean services; frontend Vite+React+TS RTL scaffold with eslint/tsc/vitest/Playwright gates
311 +- Local tests: `cd backend && pytest` -> 281 passed; `mypy src/aram_backend/services src/aram_backend/domain` -> clean; ruff check/format clean; frontend `npm run lint`/`typecheck`/`test`/`build` pass; `npx playwright test --list` -> 2 specs
312 +- Fix 1 real-data evidence: both ledgers, 6 money columns, 457,074 rows -> 0 fractional rial; ADR-012 documents scale-0 storage guarantee; 7 no-silent-rounding guard tests
313 +- Fix 4 audit note: owner item #3 was partly inaccurate — approval.py already passed mappings to run_controls; refactor makes C-03 enforcement explicit and adds proof tests rather than claiming a wiring bug
314 +- GitHub Actions: Backend CI + Frontend CI triggered on push (run IDs recorded after completion)
315 +- Artifacts/releases: `NONE`
316 +- Protected data: no canonical `data/`, `samples/`, XLSX/PDF, database, financial-source value, ZIP, EXE, tag, or release changed
317 +- Acceptance: `IN_PROGRESS`; implementation author must not merge
318 +- Reviewer: independent reviewer pending
319 +- Remaining risks: Phase 5 full UI screens, Phase 6 outputs, Phase 7 users/audit/reopen/backup, Phase 8 installer, Phase 9 UAT+tag remain; PostgreSQL path validated only in CI
320 +- Next action: continue §15 phase order — Phase 5 UI + Playwright, then 6→9; finish §18 report
321 +
322 +### 2026-12-03T11:40:00Z — Booklet v1.0 Phases 5–9 (UI, outputs, admin, desktop, UAT)
323 +
324 +- Actor: Arena agent (implementation), per booklet §17 autonomous default+proof+ADR
325 +- Task/phase: Phases 5–9 in §15 order after the 4 owner priority fixes
326 +- Base: `source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914`
327 +- Working branch: `arena/094f314c-aram`
328 +- PR: [#96](https://github.com/davoodmehraban89/Aram/pull/96) (draft -> source-data-cleanup)
329 +- Commits: `eb9024a` (tolerant import + statement_balance), `fa64baf` (Phase 5 workbench), `c4c37c0` (Phase 6 outputs + ADR-022), `e20572d` (Phase 7 users/reopen/backup + ADR-023), `77fbe70` (admin UI), `ffc9888` (Phase 8 desktop + ADR-024), `dafb559` (e2e smoke fix)
330 +- Implementation: tolerant real-ledger import (reclassified rows kept, anomalies reported) + statement_balance capture (migration 20261203_06); RTL React workbench (setup/import/mapping/statements/drill-down/approval/admin) with eslint/tsc/vitest/Playwright gates; reviewable XLSX+JSON statement outputs with exact rial + full lineage; local users/roles (PBKDF2), controlled reopen/lock, verifiable backup (migration 20261203_07); offline desktop entrypoint on 127.0.0.1 + reproducible PyInstaller recipe (no binary committed)
331 +- Local tests: `cd backend && pytest` -> 308 passed; mypy domain strict + services clean; ruff clean; frontend lint/tsc/vitest/build pass; Playwright specs valid
332 +- Phase 9 UAT (real source_1404.xlsx, read-only, fresh local DB): 131,280 raw rows imported (4 skipped+reported); 22 notes/244 mappings auto-created; BS/IS/CF/EQ built; core BS notes reconcile rial-for-rial with official (10/11/12-1/12-2/13/14/15); remaining differences surfaced as discrepancies (OD-08); approval gate blocks on C-01/C-03/C-04 (fail-loud); export 158,050 lineage rows; backup created+verified; audit chain valid
333 +- GitHub Actions: Backend CI green on recent heads; Frontend CI e2e smoke fixed in `dafb559` (run pending)
334 +- Artifacts/releases: `NONE` committed (Windows package is a build artifact, §19); UAT report at /tmp/aram-uat-1404/uat_report.json (evidence, not committed)
335 +- Protected data: no canonical `data/`, `samples/`, XLSX/PDF, database, financial-source value, ZIP, EXE, tag, or release changed
336 +- Acceptance: `IN_PROGRESS`; implementation author must not merge or tag
337 +- Reviewer: independent reviewer pending
338 +- Remaining risks: real-data BS/IS discrepancies (OD-08) require owner accounting review; Windows package built+verified on a clean Windows machine by the owner; tag v1.0.0 is the owner's post-acceptance action
339 +- Next action: independent GitHub review of PR #96; owner acceptance, merge, tag v1.0.0, build Windows package
340 +
341 +### 2026-12-03T12:20:00Z — 5-pass deep compliance review + fixes (PR #96 ready)
342 +
343 +- Actor: Arena agent (implementation), owner-requested 5-perspective deep review
344 +- Task: verify booklet compliance across 5 reviewer roles; PR #96 marked ready for review (not merged)
345 +- Base: `source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914`; branch `arena/094f314c-aram`
346 +- Commits: `4726f5e` (approve role gate + editable notes/mappings/rows + ADR-018 dep note), `87b1929` (UI NotesManager)
347 +- Review report: `docs/reviews/BOOKLET_COMPLIANCE_REVIEW.md` (5 agents, checks, findings, verdicts)
348 +- Findings fixed: F2-1 (editable notes/mappings/rows: PUT/DELETE + list endpoints, Draft-guarded, D-07->409, 9 tests + UI), F3-1 (API /approve role-gated when users exist, 2 tests), F5-1 (python-multipart documented in ADR-018)
349 +- Observation O5-1: pilot vendored wheels (commit 2fce09d) noted for owner; left intact (accepted pilot deliverable)
350 +- Verified: domain/services layering clean; no eval; no runtime network; no hardcoded secrets; source data unchanged; no new root analytical doc; ADRs 012-024 present
351 +- Local tests: `cd backend && pytest` -> 319 passed; mypy domain strict + services clean; ruff clean; frontend eslint/tsc/vitest/build pass
352 +- GitHub Actions: re-triggered on new head (pending)
353 +- Artifacts/releases: NONE committed
354 +- Acceptance: IN_PROGRESS; author does not merge or tag
355 +- Reviewer: independent reviewer pending
356 +- Next action: independent GitHub review of PR #96; owner acceptance, merge, tag v1.0.0, build Windows package
docs/adr/ADR-012-money-scale-rounding.md new
+79
@@ -0,0 +1,79 @@
1 +# ADR-012 — Money scale, storage, and rounding (OD-03, P-02, D-03)
2 +
3 +- Status: Accepted (evidence-based, booklet section 17)
4 +- Date: 2026-12-03
5 +- Supersedes: the implicit `Numeric(24, 4)` money storage in `models.py`.
6 +
7 +## Context
8 +
9 +`StatementLine.mapped_total` used `Numeric(24, 4)`. On SQLite (the default
10 +`sqlite:///` install) SQLAlchemy stores `Numeric` as **float**, silently rounding
11 +large rial amounts (debt D-03). Booklet P-02 forbids float anywhere and requires
12 +scaled-integer storage with `Decimal` in Python.
13 +
14 +## Evidence (exhaustive read-only probe of BOTH canonical ledgers)
15 +
16 +- **457,074 data rows** streamed: `source_1403.xlsx` (204,176 rows) and
17 + `source_1404.xlsx` (252,898 rows).
18 +- **Zero fractional-rial cells** across ALL six money columns
19 + (`OPENING / Debit / Credit / PERIODTURNOVER / CLOSING / مانده صورت مالی`) in
20 + **both** years. Every money value is an exact integer rial.
21 +- Magnitudes reach ~1.08e16 rial (total debit == total credit ==
22 + 10,823,163,409,740,108), well within signed 64-bit (`BIGINT` ≈ 9.22e18).
23 +- Official statements (`data/official_statements/financial_1404.xlsx`) state
24 + **"(مبالغ به میلیون ریال)"** — amounts presented in **million rial**.
25 +- Data quirk (not a precision issue): `source_1403.xlsx` has 20,701 non-numeric
26 + `Debit` cells; these are rejected loudly by the parser, never coerced.
27 +
28 +## P-02 guarantee — no silent rounding (owner audit, 2026-12-03)
29 +
30 +The owner's line-by-line audit flagged `.to_integral_value()` as a possible silent
31 +round. Clarification and proof:
32 +
33 +- In `Rial.process_bind_param`, `.to_integral_value()` is used **only as a
34 + detector**: `if scaled != scaled.to_integral_value(): raise ValueError(...)`.
35 + It never rounds or truncates; a fractional value is **rejected loudly** (P-09).
36 +- The same detector pattern in `normalize_code` and the year check rejects
37 + non-integral codes/years; it does not round them.
38 +- `decimal_from_cell` returns the exact `Decimal` (float via shortest round-trip
39 + `repr`); it performs no rounding.
40 +- `round_half_up` / `allocate_remainder` are invoked **only in the display/output
41 + layer** (e.g. the golden million-rial comparison), never on the storage or
42 + calculation path. A repo-wide grep confirms no storage-path call site.
43 +- Because the canonical data has zero fractional rial, scale 0 is lossless. If
44 + fractional rial ever appears, the import **fails loudly** rather than silently
45 + rounding, forcing an explicit ADR revision before any scale change.
46 +
47 +## Decision
48 +
49 +1. **Storage scale = 0 (full integer rial).** Amounts persist as exact scaled
50 + integers in a `BIGINT` column via the `Rial` `TypeDecorator`
51 + (`backend/src/aram_backend/domain/money.py`); Python side is `Decimal`.
52 + `float` is rejected at bind time; fractional rial raises loudly (P-09).
53 + Works identically on SQLite and PostgreSQL.
54 +2. **No rounding in storage or calculation** (OD-03). Compute in full rial.
55 +3. **Display scale = million rial**, detected from the official statements.
56 + Rounding is **half-up**, only in the output layer, through the single central
57 + `round_half_up` function.
58 +4. **Rounding-difference allocation** uses the largest-remainder method
59 + (`allocate_remainder`) so displayed rows sum exactly to the displayed total;
60 + the allocation is deterministic and recorded.
61 +
62 +## Rejected options
63 +
64 +- `Numeric(24,4)` (float on SQLite) — silent rounding, violates P-02.
65 +- Storing million-rial directly — loses rial precision and contradicts OD-03
66 + ("store and calculate in full rial without rounding").
67 +- A non-zero scale — unnecessary; the canonical data has no fractional rial.
68 +
69 +## Acceptance / proof
70 +
71 +- Hypothesis property test: exact `Decimal -> BIGINT -> Decimal` round-trip for
72 + integers up to 18 digits (D-03).
73 +- `float` and fractional rial rejected.
74 +- `allocate_remainder` rows sum to `round_half_up(total)` for random inputs.
75 +
76 +## Dependency note (booklet section 19 requires an ADR for new dependencies)
77 +
78 +`hypothesis` is added to the `test` extra solely for the property-based tests
79 +mandated by booklet section 14. It is a test-only dependency, pinned.
docs/adr/ADR-013-sign-convention-closing.md new
+44
@@ -0,0 +1,44 @@
1 +# ADR-013 — Sign convention and meaning of closing (OD-02, C-01)
2 +
3 +- Status: Accepted (evidence-based, booklet section 17)
4 +- Date: 2026-12-03
5 +
6 +## Context
7 +
8 +Booklet OD-02 defaults to debit-positive / credit-negative with
9 +`closing = opening + debit − credit`, and requires choosing the convention that
10 +satisfies C-01 on all rows and C-02/C-06 on the data — not guessing.
11 +
12 +## Evidence (read-only probe of `data/source_ledgers/source_1404.xlsx`, 252,898 rows)
13 +
14 +| Convention | C-01 rows satisfied |
15 +|---|---|
16 +| **debit-positive**: `opening + debit − credit − closing = 0` | **252,892 / 252,898 (99.998%)** |
17 +| credit-positive: `opening − debit + credit − closing = 0` | 94,152 / 252,898 (37.2%) |
18 +
19 +- C-02 under debit-positive: total debit == total credit ==
20 + 10,823,163,409,740,108 rial; sum of closing == 0. **Holds.**
21 +- The 6 residual C-01 rows are recorded as data quirks to be reconciled in the
22 + Phase-1 golden comparison (OD-08), not silently corrected (P-01).
23 +
24 +## Decision
25 +
26 +- **Debit-positive, credit-negative.** `closing = opening + debit − credit`.
27 +- C-01 is evaluated per row as `opening + debit − credit − closing == 0`.
28 +- Credit-nature accounts (liabilities, equity, revenue) carry negative closing
29 + balances under this convention; the display layer applies the statement sign
30 + policy separately (the pilot engine already does this for BS/IS).
31 +- The 6 exceptional rows are surfaced, never auto-fixed; they belong in
32 + `docs/discrepancies.json` once the Phase-1 golden run characterizes them.
33 +
34 +## Rejected options
35 +
36 +- Credit-positive closing — fails C-01 on ~63% of canonical rows.
37 +- Per-account nature flipping before C-01 — unnecessary; the raw ledger already
38 + satisfies debit-positive C-01 almost universally.
39 +
40 +## Acceptance / proof
41 +
42 +- Unit tests: C-01 passes for debit-positive rows, fails for a flipped row.
43 +- Real-data evidence test (read-only, skipped if data absent) asserting the
44 + debit-positive pass rate dominates credit-positive.
docs/adr/ADR-014-hierarchy-mapping.md new
+55
@@ -0,0 +1,55 @@
1 +# ADR-014 — Ledger ↔ Pilot hierarchy mapping (OD-01, D-10)
2 +
3 +- Status: Accepted (evidence-based, booklet section 17 — default refuted)
4 +- Date: 2026-12-03
5 +
6 +## Context
7 +
8 +D-10: two namings for one hierarchy — ledger `T1..T4` vs Pilot
9 +`general / subsidiary / detail1..4` — with no documented mapping. OD-01 defaults
10 +to mapping ledger levels to Pilot levels in order and expects the reconstructed
11 +full code to equal the `حساب` column for 100% of rows.
12 +
13 +## Evidence (read-only probe of `data/source_ledgers/source_1404.xlsx`, 252,898 rows)
14 +
15 +- `حساب` is **always a 4-digit** code (e.g. `8348`); stored as integer.
16 +- `kol` is a **2-digit** general code (e.g. `14`); stored as integer.
17 +- `T1_CODE..T4_CODE` are auxiliary identifiers (e.g. `117001`,
18 + `22200000000899`, `0`, `0`) — **concatenating T1..T4 equals `حساب` for 0 rows.**
19 +- `AccountId == kol + حساب` for only **195,789 / 252,898 (~77%)**; it is
20 + unreliable (sometimes empty, sometimes a 14-digit code) and is **not used**.
21 +
22 +The OD-01 default is therefore **refuted**: `حساب` is the subsidiary leaf, not a
23 +concatenation of the T-codes.
24 +
25 +## Decision (evidence wins, section 17 rule 3)
26 +
27 +| Ledger column | Pilot level |
28 +|---|---|
29 +| `kol` | `general_code` |
30 +| `حساب` | `subsidiary_code` |
31 +| `T1_CODE` | `detail1_code` |
32 +| `T2_CODE` | `detail2_code` |
33 +| `T3_CODE` | `detail3_code` |
34 +| `T4_CODE` | `detail4_code` |
35 +
36 +- **Canonical account full code = `general_code + subsidiary_code`** (`kol + حساب`,
37 + 6 digits). Auxiliary detail codes are preserved as text attributes but do not
38 + change the canonical account identity.
39 +- All codes are text; leading zeros and length preserved (P-03). Integral numeric
40 + cells convert to text exactly (the canonical ledger stores codes as integers).
41 +- Verifiable invariant: for 100% of rows `subsidiary_code == حساب` and
42 + `general_code == kol`; `canonical_full_code == general + subsidiary`.
43 +
44 +## Rejected options
45 +
46 +- T1..T4 → general..detail4 in order with concatenation == `حساب` (the OD-01
47 + default) — 0/252,898 rows; refuted.
48 +- Using `AccountId` as the full code — only ~77% consistent; unreliable.
49 +
50 +## Acceptance / proof
51 +
52 +- Bidirectional conversion test (`ledger_to_pilot` / `pilot_to_ledger`) round-trips
53 + exactly (D-10).
54 +- Real-data evidence test (read-only, skipped if data absent): subsidiary == `حساب`
55 + and general == `kol` for 100% of streamed rows.
docs/adr/ADR-016-reopen-and-immutability.md new
+56
@@ -0,0 +1,56 @@
1 +# ADR-016 — Reopen model and locked-year immutability
2 +
3 +- Status: Accepted (Phase 0, D-07)
4 +- Date: 2026-12-03
5 +- Booklet: §7 (Reopen), §12 (D-07), P-07/P-08; §5
6 +
7 +## Context
8 +
9 +A LOCKED fiscal year must be immutable even against raw SQL. Reopening must be a
10 +controlled, audited act that never silently rewrites locked data. The database
11 +already enforces the DRAFT→APPROVED→LOCKED lifecycle via triggers
12 +(`protect_fiscal_year_transition`); D-07 adds the row-level guards.
13 +
14 +## Decision
15 +
16 +### Locked-year immutability (D-07)
17 +
18 +Database triggers block INSERT/UPDATE/DELETE on every year-owned financial table
19 +when the owning fiscal year is LOCKED: `ledger_balances`, `account_versions`,
20 +`note_definitions`, `note_rows`, `mapping_rules`, `financial_statements`,
21 +`statement_lines`, `source_documents`. The owning year is resolved directly
22 +(`year_id`) or through the parent (note→definition, line→statement), matching the
23 +application-level `_year_id_for` guard. Triggers run for SQLite and PostgreSQL via
24 +dialect-specific generation, so raw SQL cannot bypass them (P-08).
25 +
26 +### Reopen
27 +
28 +- LOCKED → APPROVED is allowed **only** when a `ReopenRequest` with status
29 + `approved` exists for the year. Without it, the transition trigger blocks the
30 + change. The existing transition trigger is extended to permit this path.
31 +- Reopening never edits locked rows: it produces a **new statement version**
32 + (`FinancialStatement.version + 1`) and the changes are recorded as adjustments
33 + with a reason. The original locked snapshot remains queryable.
34 +- Every reopen and every adjustment is written to the hash-chained audit log
35 + (D-07): `AuditEntry(previous_hash, payload_hash, chain_hash)` where
36 + `chain_hash = SHA256(previous_hash || payload_hash)`. Any edit to a past entry
37 + breaks the chain and is detected by `verify_chain`.
38 +
39 +### Audit log
40 +
41 +`AuditEntry` is append-only: triggers block UPDATE and DELETE. The chain is
42 +verified on demand and before final approval. Actor and timestamp are recorded.
43 +
44 +## Consequences
45 +
46 +- Raw SQL cannot mutate a locked year; the only path is an approved reopen that
47 + versions the output and leaves an audited adjustment trail.
48 +- The audit chain gives tamper evidence independent of the database's own
49 + integrity.
50 +- Phase 7 builds the full ReopenRequest workflow and adjustment layer on this
51 + foundation; Phase 0 establishes the model, triggers, and chain.
52 +
53 +## Rejected alternatives
54 +
55 +- Application-only immutability: bypassable by raw SQL (violates P-08).
56 +- Mutable audit rows with a "deleted" flag: breaks tamper evidence.
docs/adr/ADR-017-ci-quality-gates.md new
+49
@@ -0,0 +1,49 @@
1 +# ADR-017 — CI quality gates and tooling
2 +
3 +- Status: Accepted (Phase 0, D-12)
4 +- Date: 2026-12-03
5 +- Booklet: §13 (CI gates), §12 (D-12), §19 (no dependency without ADR)
6 +
7 +## Context
8 +
9 +The booklet requires green CI gates: ruff, mypy --strict, coverage (domain ≥90%,
10 +total ≥80%), SQLite + PostgreSQL migration round-trips, and `git diff --check`.
11 +The existing workflow only ran pytest + SQLite migrations + compileall.
12 +
13 +## Decision
14 +
15 +Add dev tooling to the `test` extra (single install in CI):
16 +
17 +- `ruff` — lint + format check.
18 +- `mypy` — static typing, `--strict` on the pure domain layer first; the broader
19 + package is type-checked with pragmatic settings and tightened toward strict as
20 + the services/api layers mature (Phases 1–7).
21 +- `coverage` / `pytest-cov` — enforce domain ≥90% and total ≥80%.
22 +- `pip-audit` — dependency vulnerability scan (advisory; fails on known CVEs).
23 +
24 +CI matrix runs migrations on **SQLite and PostgreSQL** (service container) in
25 +addition to the test suite. `git diff --check` guards whitespace.
26 +
27 +### New dependencies (justification)
28 +
29 +| Package | Purpose | Runtime? |
30 +|---|---|---|
31 +| ruff | lint/format gate | dev only |
32 +| mypy | type gate | dev only |
33 +| coverage, pytest-cov | coverage gate | dev only |
34 +| pip-audit | vuln scan | dev only |
35 +| psycopg[binary] (`ci` extra) | PostgreSQL driver for CI migration matrix | CI only |
36 +
37 +None are imported by the application at runtime; the offline desktop build is
38 +unaffected (P-10, zero runtime network). The `ci` extra is installed only in the
39 +migration-matrix job, never in the packaged desktop runner.
40 +
41 +## Consequences
42 +
43 +- Every PR must pass lint, types, coverage, and dual-dialect migrations.
44 +- Domain code is held to strict typing from Phase 0; other layers ratchet up.
45 +
46 +## Rejected alternatives
47 +
48 +- Coverage without a threshold: no enforcement.
49 +- Skipping PostgreSQL: the booklet requires both dialects for migration safety.
docs/adr/ADR-018-persistent-statements-drilldown.md new
+67
@@ -0,0 +1,67 @@
1 +# ADR-018 — Persistent statements and drill-down lineage (Phase 1)
2 +
3 +- Status: Accepted (Phase 1 vertical slice)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 1, D1/D2 (year continuity, drill-down to file/sheet/row)
6 +
7 +## Context
8 +
9 +Phase 0 delivered the domain, `LedgerBalance`, mappings, notes and the
10 +`FinancialStatement`/`StatementLine` models, but no service that turns imported
11 +balances + mappings into persisted, versioned, auditable statements with a
12 +traceable lineage back to the source file/sheet/row.
13 +
14 +## Decision
15 +
16 +### Statement build
17 +
18 +`services/statement_build.build_statements(session, year_id, statement_types)`:
19 +
20 +- Reads the **latest import version** of `LedgerBalance` for the year.
21 +- Reads active `MappingRule` (account_code → note) and `NoteDefinition`
22 + (`configuration_json` carries `statement` and `section`).
23 +- Aggregates exact integer-rial closing balances per note, applies the display
24 + sign policy (ADR-013: debit-positive closing; display = sign × closing), and
25 + persists a new `FinancialStatement` version with ordered `StatementLine` rows
26 + (`mapped_total` in Rial, `target_note_id` set).
27 +- Only Draft years may build; Approved/Locked are blocked by the D-07 triggers.
28 +- Each build creates a new version (never mutates a prior snapshot).
29 +
30 +### Display sign policy (single source for the persistent engine)
31 +
32 +| Statement | Section | sign |
33 +|---|---|---|
34 +| BS | Assets | +1 |
35 +| BS | Liabilities | −1 |
36 +| BS | Equity | −1 |
37 +| IS | Revenue | −1 |
38 +| IS | Expenses | +1 |
39 +
40 +Phase 1 renders BS/IS; CF/EQ are deferred to Phase 4.
41 +
42 +### Drill-down lineage (D2)
43 +
44 +`drill_down(session, statement_line_id)` returns the full chain:
45 +`StatementLine → NoteDefinition → MappingRule(s) → LedgerBalance row(s) →
46 +SourceDocument (filename + SHA-256) + source_sheet + source_row`. Every statement
47 +total is therefore traceable to the exact source file, sheet and row.
48 +
49 +## Consequences
50 +
51 +- Statements are persisted, versioned, year-isolated and immutable once locked.
52 +- Any figure can be audited down to the originating ledger row.
53 +- The in-memory Pilot workbench remains the interactive editor; this persistent
54 + engine is the audited system of record.
55 +
56 +## Dependencies
57 +
58 +- `python-multipart` is required by FastAPI to parse `multipart/form-data` for the
59 + ledger and mapping workbook uploads (`UploadFile`/`File`). It is the standard
60 + FastAPI file-upload dependency, pinned `>=0.0.18,<1` in `backend/pyproject.toml`.
61 + No other runtime dependency was added for the statement slice; Excel I/O uses the
62 + already-required `openpyxl` (ADR-017).
63 +
64 +## Rejected alternatives
65 +
66 +- Storing drill-down as a denormalized blob on StatementLine: loses the live
67 + join to source and duplicates data; the relational chain is authoritative.
docs/adr/ADR-019-mapping-io-approval.md new
+53
@@ -0,0 +1,53 @@
1 +# ADR-019 — Mapping Excel I/O, unknown queue, and approval gate (Phase 2)
2 +
3 +- Status: Accepted (Phase 2)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 2, D1/D4, P-09
6 +
7 +## Context
8 +
9 +Phase 1 built statements from mappings, but mappings could only be created one at
10 +a time. V1 requires comprehensive mapping Excel import/export, an unknown-account
11 +queue, carry-forward between years, and an approval gate that refuses to approve
12 +while any blocking control fails.
13 +
14 +## Decision
15 +
16 +### Mapping workbook contract
17 +
18 +A single `Mappings` sheet with columns:
19 +`account_code, account_name, target_note_number, statement, section, mapping_type`.
20 +Codes are text (leading zeros preserved). Import is fail-closed per row: invalid
21 +rows are collected in `errors` and skipped; valid rows create the note (if new)
22 +and the mapping. Export joins mappings with note metadata and imported account
23 +names. Re-import is idempotent (existing account→note pairs are not duplicated).
24 +
25 +### Unknown-account queue (C-04)
26 +
27 +`unknown_accounts` lists active accounts (any non-zero opening/debit/credit/
28 +closing) with no mapping, sorted by code, with name/closing/source_row. Resolving
29 +the queue is mandatory before approval.
30 +
31 +### Approval gate (P-09)
32 +
33 +`approve_year` runs C-01..C-04 over the latest import + active mappings. Any
34 +blocking ERROR refuses Draft→Approved and returns the failing controls. A clean
35 +pass transitions the year and appends a hash-chained audit entry. Only Draft
36 +years may be approved.
37 +
38 +### Carry-forward (D1)
39 +
40 +`carry_forward_mappings(from_year, to_year)` copies notes (by note_number) and
41 +mappings into a Draft target year, idempotently, so 1403→1404 continuity reuses
42 +prior mappings instead of starting from scratch.
43 +
44 +## Consequences
45 +
46 +- Mappings are portable through a governed, auditable workbook.
47 +- Approval is impossible while controls fail; the audit chain records each pass.
48 +- Year continuity is supported without re-keying mappings.
49 +
50 +## Rejected alternatives
51 +
52 +- Auto-creating mappings for unmapped accounts: would invent financial mappings
53 + (forbidden by §19); the queue forces explicit human resolution.
docs/adr/ADR-020-formula-grammar.md new
+56
@@ -0,0 +1,56 @@
1 +# ADR-020 — Safe note formula grammar (Phase 3)
2 +
3 +- Status: Accepted (Phase 3)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 3, P-05 (no eval of formulas), §7
6 +
7 +## Context
8 +
9 +Disclosure notes contain computed rows (subtotals, sums, derived figures). The
10 +booklet forbids `eval`/`exec` of user formulas. We need a small, deterministic,
11 +safe expression language that can reference account balances and other note rows.
12 +
13 +## Decision
14 +
15 +A restricted grammar parsed by a hand-written tokenizer + recursive-descent parser
16 +into a whitelisted AST, evaluated with exact `Decimal`. **No `eval`, `exec`,
17 +attribute access, imports, or arbitrary names.** Any unknown token/function fails
18 +closed with `FormulaError`.
19 +
20 +### Grammar (EBNF)
21 +
22 +```
23 +expr := term (('+' | '-') term)*
24 +term := factor (('*' | '/') factor)*
25 +factor := NUMBER | STRING | '(' expr ')' | ('-' | '+') factor | call
26 +call := IDENT '(' [expr (',' expr)*] ')'
27 +```
28 +
29 +### Allowed functions
30 +
31 +| Call | Meaning |
32 +|---|---|
33 +| `acct("code")` | closing balance of account (debit-positive, ADR-013) |
34 +| `acct("code", "opening"\|"debit"\|"credit"\|"closing")` | selected field |
35 +| `row(n)` | value of row `n` in the current note (must be earlier row) |
36 +| `note("6", n)` | value of row `n` in note `6` |
37 +| `sum(a, b, ...)` | exact sum |
38 +| `abs(x)` | absolute value |
39 +
40 +- Numbers are exact decimals; strings are double-quoted account/note codes.
41 +- Division by zero raises `FormulaError` (never silently coerced).
42 +- Evaluation order follows `row_order`; a row may only reference earlier rows in
43 + the same note. Cross-note references are resolved with cycle detection.
44 +
45 +## Consequences
46 +
47 +- Formulas are safe by construction (whitelist AST, no code execution).
48 +- Values are reproducible: same balances + formula ⇒ same result.
49 +- The note engine computes values on demand from the latest ledger import; the
50 + formula text is the single source of truth (no invented stored figures).
51 +
52 +## Rejected alternatives
53 +
54 +- Python `eval` with a restricted namespace: still executes arbitrary code and is
55 + explicitly forbidden (P-05).
56 +- A full spreadsheet engine: unnecessary scope and a larger attack surface.
docs/adr/ADR-021-golden-comparison-scale.md new
+53
@@ -0,0 +1,53 @@
1 +# ADR-021 — Golden comparison, display scale, and data-derived mapping (Phase 4)
2 +
3 +- Status: Accepted (Phase 4, evidence-based per §17)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 4, D1 (rial-for-rial), OD-03 (scale), OD-08 (discrepancies)
6 +
7 +## Context
8 +
9 +V1 must reproduce `data/official_statements` rial-for-rial. The official sheets
10 +display **million rial** (OD-03). The canonical ledger embeds the authoritative
11 +mapping and statement figures, so no mapping is invented (§19).
12 +
13 +## Evidence (read-only probe of `source_1404.xlsx`, year-1404 rows)
14 +
15 +- Column 0 `یادداشت کل` is the **official note number** (`10`, `11`, `12-1`,
16 + `12-2`, `13`, `14`, `15`, `5`, `6`, …). Values `-` and `#N/A` mark unmapped rows.
17 +- Column 25 `مانده صورت مالی` is the **statement balance in rial**, already
18 + reclassified and signed (e.g. receivables split into current `12-1` and
19 + non-current `12-2`). `CLOSING` is frequently NULL for these rows, so the
20 + statement figure is column 25, not the closing balance.
21 +- Summing column 25 by column 0 and rounding to million rial (half-up, ADR-012)
22 + reproduces the official BS exactly:
23 +
24 +| note | source Σ rial | ÷1e6 | official (million) | match |
25 +|---|---|---|---|---|
26 +| 10 | 673740636579631 | 673740636.58 | 673740637 | ✓ |
27 +| 11 | 242193702502 | 242193.70 | 242194 | ✓ |
28 +| 12-1 | 13386398349814 | 13386398.35 | 13386398 | ✓ |
29 +| 12-2 | 8310167506886 | 8310167.51 | 8310168 | ✓ |
30 +| 13 | 6839534905630 | 6839534.91 | 6839535 | ✓ |
31 +| 14 | 11273649604593 | 11273649.60 | 11273650 | ✓ |
32 +| 15 | 19951136477703 | 19951136.48 | 19951136 | ✓ |
33 +
34 +## Decision
35 +
36 +- **Data-derived mapping:** account → note number comes from column 0; the
37 + statement contribution is column 25. Nothing is invented.
38 +- **Display scale 6, half-up** (ADR-012): `round_half_up(source_rial / 1e6, 0)`.
39 +- `services/golden.compare_year` aggregates the source by note, reads the official
40 + sheets (`وضعيت مالي`=BS, `سودوزيان`=IS, `حقوق مالكانه`=EQ, `جريان هاي نقدي`=CF),
41 + and reports per-note match/delta.
42 +- **OD-08:** every non-match is written to `docs/discrepancies.json` with source
43 + rial, rounded million, official million, and delta. Differences are surfaced,
44 + never silently corrected (P-01). BS matches exactly; IS/CF/EQ netting rules that
45 + are not derivable from the source are recorded as discrepancies for resolution.
46 +- The generic engine also builds all four statement types (BS/IS/CF/EQ) from
47 + closing balances + sign policy for companies without pre-reclassified columns.
48 +
49 +## Rejected alternatives
50 +
51 +- Deriving the statement figure from `CLOSING`: NULL on most reclassified rows and
52 + ignores the current/non-current split — would not reproduce the official BS.
53 +- Inventing IS netting rules to force a match: forbidden (§19); record as discrepancy.
docs/adr/ADR-022-statement-outputs.md new
+57
@@ -0,0 +1,57 @@
1 +# ADR-022 — Reviewable statement outputs (Phase 6)
2 +
3 +- Status: Accepted (Phase 6)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 6 (reviewable output), D2/D3 (drill-down lineage)
6 +
7 +## Context
8 +
9 +Phases 1–5 persist audited, versioned statements (BS/IS/CF/EQ) with exact
10 +integer-rial totals and a live drill-down chain to the source file/sheet/row, and
11 +provide an RTL workbench to build and inspect them. The product still needs a
12 +portable, independently reviewable artifact: an output a reviewer can open without
13 +the application and audit rial-for-rial against the source and the official
14 +statements.
15 +
16 +## Decision
17 +
18 +`services/statement_export.py` produces two artifacts from the **latest statement
19 +version** per type for a year:
20 +
21 +1. **XLSX workbook** (`export_statements_workbook`):
22 + - `Summary`: year, company, status, generation timestamp, per-statement version,
23 + lineage row count.
24 + - One sheet per statement (`BS`/`IS`/`CF`/`EQ`): ordered lines with the exact
25 + `mapped_total_rial` (text, never rounded) and a `mapped_total_million`
26 + display column (half-up, ADR-012) for readability only.
27 + - One sheet per evaluated note (`Note {number}`): row order, label, formula,
28 + exact `value_rial`, and referenced accounts.
29 + - `Lineage`: every statement line traced to account, effective balance, source
30 + filename, SHA-256, sheet and row (D2/D3).
31 + - Sheets are RTL (`rightToLeft`, reading order 2) with frozen header rows.
32 +2. **Structured JSON** (`export_statements_json` / `_bytes`): the same payload for
33 + machine review and diffing; all money is exact integer-rial **strings** (no
34 + float/Decimal leakage).
35 +
36 +API: `GET /api/v1/years/{id}/statements/export?format=xlsx|json` streams the
37 +artifact as an attachment. The workbench exposes both as download buttons.
38 +
39 +## Consequences
40 +
41 +- The exact rial is always preserved; the million-rial column is display-only and
42 + never replaces it (P-02, ADR-012).
43 +- Every output figure is independently traceable to its source row (D2/D3).
44 +- No new dependency: openpyxl is already required (ADR-017). PDF output is
45 + deliberately deferred — it would need a new rendering dependency and a separate
46 + ADR; XLSX + JSON already satisfy reviewable, auditable output.
47 +- Export reads the latest persisted version; it never mutates statements or source
48 + data and works on Approved/Locked years (read-only).
49 +
50 +## Rejected alternatives
51 +
52 +- Rendering PDF directly: adds a dependency (reportlab/weasyprint) without a
53 + present need; XLSX matches the official workbook format reviewers already use.
54 +- Exporting rounded million-rial as the primary figure: violates exact-rial
55 + preservation (P-02); rounding is display-only.
56 +- Recomputing totals at export time: would diverge from the persisted, audited
57 + statement version; export must reflect the system of record exactly.
docs/adr/ADR-023-users-reopen-backup.md new
+71
@@ -0,0 +1,71 @@
1 +# ADR-023 — Users, controlled reopen/lock, and backup (Phase 7)
2 +
3 +- Status: Accepted (Phase 7)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 7, §7 (year lifecycle), §12 (audit), D-07 (immutability)
6 +
7 +## Context
8 +
9 +The system of record already enforces year immutability (DB triggers + ORM guard),
10 +a hash-chained append-only audit log, and a controlled reopen mechanism
11 +(`ReopenRequest`). Phase 7 adds attributable identity, role-gated administration,
12 +a reopen/lock workflow service + API, and provably-intact local backups — all
13 +offline, with no runtime network and no new dependency.
14 +
15 +## Decision
16 +
17 +### Users and roles (`services/users.py`, `User` model)
18 +
19 +- Local users with roles `admin` / `reviewer` / `preparer`.
20 +- Passwords stored only as PBKDF2-HMAC-SHA256 (200k rounds) with a per-user random
21 + 16-byte salt (stdlib `hashlib`/`secrets`); constant-time comparison
22 + (`hmac.compare_digest`). No plaintext, no external IdP, no network.
23 +- `require_role` is the single authorization gate for sensitive actions.
24 +- Bootstrap: the first user is created without an existing admin and is forced to
25 + `admin` (desktop install); afterwards only an admin manages users.
26 +- Every user mutation appends a hash-chained audit entry.
27 +
28 +### Reopen / lock (`services/reopen.py`)
29 +
30 +- `request_reopen` (Locked year, reason required) → pending `ReopenRequest`.
31 +- `approve_reopen` (pending → approved).
32 +- `reopen_year` transitions LOCKED → APPROVED **only** with an approved request;
33 + the ORM guard and DB trigger re-check this, so there is no bypass. Reopening
34 + never edits locked rows in place; a later build versions the output.
35 +- `lock_year` transitions APPROVED → LOCKED. Each step is audited.
36 +
37 +### Backup (`services/backup.py`)
38 +
39 +- Consistent SQLite snapshot via the sqlite3 online backup API (safe with
40 + concurrent writers), a copy of the content-addressed source store, and a
41 + `manifest.json` recording the SHA-256 of the database and every source file plus
42 + the audit-chain verification result.
43 +- `verify_backup` recomputes every hash and re-checks the audit chain inside the
44 + snapshot; a corrupt/tampered backup is rejected. Creation refuses a non-empty
45 + destination and refuses to proceed if the live audit chain is broken.
46 +- SQLite-only for the offline desktop; PostgreSQL deployments use native pg_dump.
47 +
48 +### API (`admin_api.py`, `/api/v1`)
49 +
50 +`POST /users` (bootstrap/admin), `GET /users`, `POST /auth/login`,
51 +`POST /users/{username}/role|active`, `GET /audit`, `GET /audit/verify`,
52 +`POST /years/{id}/reopen/request`, `POST /reopen/{id}/approve`,
53 +`POST /years/{id}/reopen`, `POST /years/{id}/lock`,
54 +`GET /years/{id}/reopen/requests`, `POST /backup`, `POST /backup/verify`.
55 +Sensitive endpoints are role-gated (admin for users/backup; reviewer/admin for
56 +reopen/lock) and return 403 on insufficient role.
57 +
58 +## Consequences
59 +
60 +- Actions are attributable to a username and provably ordered (audit chain).
61 +- Locked years remain immutable; reopening is controlled, reasoned, and audited.
62 +- Backups are independently verifiable before restore (hashes + audit chain).
63 +- No new dependency; all crypto is stdlib. No runtime network.
64 +
65 +## Rejected alternatives
66 +
67 +- External OAuth/IdP or session tokens over the network: violates the offline,
68 + zero-network constraint; local role-gated identity is sufficient for a desktop.
69 +- Storing passwords reversibly or with fast hashes: insecure; PBKDF2 + salt only.
70 +- File-copy backup without the online API: risks a torn snapshot under writers.
71 +- Allowing reopen without an approved request: would defeat D-07 immutability.
docs/adr/ADR-024-desktop-packaging.md new
+57
@@ -0,0 +1,57 @@
1 +# ADR-024 — Offline desktop packaging (Phase 8)
2 +
3 +- Status: Accepted (Phase 8)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 8 (reproducible Windows package), §19 (no committed binaries)
6 +
7 +## Context
8 +
9 +The product must run as an offline Windows desktop/local application: the React
10 +workbench and the FastAPI backend together, on loopback only, with a local SQLite
11 +database and content-addressed source store, and zero runtime network. The package
12 +must be reproducible from source and reviewable; binaries are build artifacts, not
13 +committed source (booklet §19).
14 +
15 +## Decision
16 +
17 +### Desktop entrypoint (`aram_backend/desktop.py`)
18 +
19 +- `default_data_dir()`: per-user data directory (`%APPDATA%/Aram` on Windows,
20 + `~/.aram` elsewhere; override `ARAM_DATA_DIR`).
21 +- `initialize_database()`: idempotent `create_all` + D-07 triggers on a local
22 + SQLite file (WAL-capable, foreign keys ON via the shared engine), and creates the
23 + source-store directory.
24 +- `create_desktop_app()`: FastAPI with the statement + admin routers, a health
25 + endpoint, and the bundled React workbench mounted at `/` (StaticFiles html).
26 +- `main()`: initialize the DB, rebind the shared engine to the local file
27 + (`database.reconfigure`), and run uvicorn on **127.0.0.1** only (port `ARAM_PORT`,
28 + default 8765). No network interface is exposed.
29 +
30 +### Reproducible build (`packaging/`)
31 +
32 +- `build_desktop.py`: builds `frontend/dist` (npm ci + build), then runs PyInstaller.
33 +- `aram.spec`: one-folder PyInstaller package `dist/Aram/` (`Aram.exe` on Windows)
34 + bundling the backend, the built frontend as `frontend_dist`, migrations, and
35 + required data/hidden imports (sqlalchemy sqlite dialect, uvicorn, openpyxl,
36 + multipart). `console=True` keeps logs visible for review.
37 +- The Windows package is built on Windows from this recipe; CI/release produces the
38 + artifact. **No EXE/ZIP/binary is committed** (§19).
39 +
40 +## Consequences
41 +
42 +- A clean Windows machine runs `Aram.exe` with no Python, Node, or network needed;
43 + all data stays local under the per-user data dir.
44 +- The build is reproducible from source (pinned frontend lockfile + spec).
45 +- Loopback-only binding satisfies the zero-runtime-network constraint.
46 +- Schema is created idempotently on first launch; migrations are bundled for
47 + upgrade paths.
48 +
49 +## Rejected alternatives
50 +
51 +- One-file EXE: slower startup and trickier data-file resolution for FastAPI/uvicorn;
52 + one-folder is more reliable and inspectable.
53 +- Bundling a separate web server or requiring an installed Python/Node: violates the
54 + clean-environment, offline goal.
55 +- Committing the built EXE/ZIP: prohibited by §19 (large binaries); the recipe is the
56 + reviewable source of truth.
57 +- Binding 0.0.0.0: would expose a network interface; the desktop app is loopback-only.
docs/app.js new
+692
@@ -0,0 +1,692 @@
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/bridge.py new
+207
@@ -0,0 +1,207 @@
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/index.html new
+139
@@ -0,0 +1,139 @@
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 new
+4
@@ -0,0 +1,4 @@
1 +"""Aram backend package."""
2 +
3 +__version__ = "0.1.0"
4 +
docs/py/aram_backend/pilot_demo.py new
+161
@@ -0,0 +1,161 @@
1 +"""Synthetic demo workbook for the Pilot workbench.
2 +
3 +Every value here is fabricated for demonstration and is clearly labelled as
4 +such in the company name, the workbook itself, the API and the UI. It never
5 +touches canonical data and must never be used for real financial reporting.
6 +The trial balance is balanced; two suspense accounts are intentionally left
7 +unmapped so the exception-queue workflow can be exercised end to end.
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +from datetime import UTC, datetime
13 +from io import BytesIO
14 +
15 +from openpyxl import Workbook
16 +
17 +from aram_backend.pilot_workbook import SHEET_HEADERS
18 +
19 +DEMO_COMPANY_CODE = "DEMO"
20 +DEMO_COMPANY_NAME = "شرکت ساختگی دمو (دادهٔ کاملاً غیرواقعی)"
21 +DEMO_YEAR = 1404
22 +DEMO_REVIEWER = "بازبین دمو (ساختگی)"
23 +DEMO_REVIEW_DATE = "2026-12-03"
24 +
25 +# (full_code, name, general_code, general_name, subsidiary_code,
26 +# closing, debit, credit, statement, section, note_number, approval)
27 +_DEMO_ACCOUNTS = [
28 + ("1001", "نقد و بانک", "10", "دارایی‌های جاری", "01", 12_500_000_000, 7_500_000_000, 5_000_000_000, "BS", "Assets", "01", "Approved"),
29 + ("1002", "دریافتنی‌های تجاری", "10", "دارایی‌های جاری", "02", 8_300_000_000, 6_100_000_000, 4_300_000_000, "BS", "Assets", "02", "Approved"),
30 + ("1003", "موجودی کالا", "10", "دارایی‌های جاری", "03", 15_200_000_000, 9_400_000_000, 7_100_000_000, "BS", "Assets", "03", "Approved"),
31 + ("1004", "پیش‌پرداخت‌ها", "10", "دارایی‌های جاری", "04", 1_100_000_000, 800_000_000, 500_000_000, "BS", "Assets", "04", "Draft"),
32 + ("1101", "دارایی‌های ثابت مشهود", "11", "دارایی‌های غیرجاری", "01", 22_000_000_000, 4_000_000_000, 0, "BS", "Assets", "05", "Approved"),
33 + ("1102", "استهلاک انباشته", "11", "دارایی‌های غیرجاری", "02", -3_600_000_000, 0, 900_000_000, "BS", "Assets", "05", "Approved"),
34 + ("2001", "پرداختنی‌های تجاری", "20", "بدهی‌های جاری", "01", -6_400_000_000, 3_200_000_000, 4_100_000_000, "BS", "Liabilities", "06", "Approved"),
35 + ("2003", "ذخیره مالیات", "20", "بدهی‌های جاری", "03", -1_900_000_000, 0, 1_900_000_000, "BS", "Liabilities", "08", "Approved"),
36 + ("2101", "تسهیلات مالی", "21", "بدهی‌های غیرجاری", "01", -14_000_000_000, 2_000_000_000, 5_000_000_000, "BS", "Liabilities", "07", "Approved"),
37 + ("3001", "سرمایه", "30", "حقوق مالکانه", "01", -20_000_000_000, 0, 0, "BS", "Equity", "09", "Approved"),
38 + ("3002", "سود انباشته", "30", "حقوق مالکانه", "02", -13_000_000_000, 0, 0, "BS", "Equity", "10", "Approved"),
39 + ("4001", "فروش", "40", "درآمدها", "01", -18_700_000_000, 0, 18_700_000_000, "IS", "Revenue", "11", "Approved"),
40 + ("4002", "سایر درآمدها", "40", "درآمدها", "02", -400_000_000, 0, 400_000_000, "IS", "Revenue", "12", "Approved"),
41 + ("5001", "بهای تمام‌شده کالای فروش‌رفته", "50", "هزینه‌ها", "01", 9_800_000_000, 9_800_000_000, 0, "IS", "Expenses", "13", "Approved"),
42 + ("5002", "حقوق و دستمزد", "50", "هزینه‌ها", "02", 3_900_000_000, 3_900_000_000, 0, "IS", "Expenses", "14", "Approved"),
43 + ("5003", "اجاره و اداری", "50", "هزینه‌ها", "03", 1_250_000_000, 1_250_000_000, 0, "IS", "Expenses", "15", "Approved"),
44 + ("5004", "هزینه استهلاک", "50", "هزینه‌ها", "04", 900_000_000, 900_000_000, 0, "IS", "Expenses", "16", "Approved"),
45 + ("5005", "هزینه‌های مالی", "50", "هزینه‌ها", "05", 1_150_000_000, 1_150_000_000, 0, "IS", "Expenses", "17", "Approved"),
46 + ("5006", "مالیات بر درآمد", "50", "هزینه‌ها", "06", 1_900_000_000, 1_900_000_000, 0, "IS", "Expenses", "18", "Approved"),
47 + # Intentionally unmapped suspense pair: balanced, but incomplete coverage.
48 + ("9001", "حساب موقت — قلم شناسایی‌نشده بدهکار", "90", "حساب‌های موقت", "01", 500_000_000, 500_000_000, 0, None, None, None, None),
49 + ("9002", "حساب موقت — قلم شناسایی‌نشده بستانکار", "90", "حساب‌های موقت", "02", -500_000_000, 0, 500_000_000, None, None, None, None),
50 +]
51 +
52 +_DEMO_NOTES = [
53 + ("BS", "Assets", "01", "نقد و بانک"),
54 + ("BS", "Assets", "02", "دریافتنی‌های تجاری"),
55 + ("BS", "Assets", "03", "موجودی‌ها"),
56 + ("BS", "Assets", "04", "پیش‌پرداخت‌ها"),
57 + ("BS", "Assets", "05", "دارایی‌های ثابت مشهود"),
58 + ("BS", "Liabilities", "06", "پرداختنی‌های تجاری"),
59 + ("BS", "Liabilities", "07", "تسهیلات مالی"),
60 + ("BS", "Liabilities", "08", "ذخیره مالیات"),
61 + ("BS", "Equity", "09", "سرمایه"),
62 + ("BS", "Equity", "10", "سود انباشته"),
63 + ("IS", "Revenue", "11", "درآمد عملیاتی"),
64 + ("IS", "Revenue", "12", "سایر درآمدها"),
65 + ("IS", "Expenses", "13", "بهای تمام‌شده"),
66 + ("IS", "Expenses", "14", "حقوق و دستمزد"),
67 + ("IS", "Expenses", "15", "هزینه‌های اداری و تشکیلاتی"),
68 + ("IS", "Expenses", "16", "استهلاک"),
69 + ("IS", "Expenses", "17", "هزینه‌های مالی"),
70 + ("IS", "Expenses", "18", "مالیات بر درآمد"),
71 +]
72 +
73 +
74 +def _row(sheet: str, values: dict) -> tuple:
75 + return tuple(values.get(header) for header in SHEET_HEADERS[sheet])
76 +
77 +
78 +def build_demo_workbook() -> bytes:
79 + """Build the synthetic, balanced demo workbook fully in memory."""
80 + workbook = Workbook()
81 + workbook.remove(workbook.active)
82 + workbook.properties.creator = "Aram Pilot Workbench (synthetic demo)"
83 + workbook.properties.title = "SYNTHETIC DEMO — NOT REAL FINANCIAL DATA"
84 + fixed = datetime(2026, 12, 3, tzinfo=UTC)
85 + workbook.properties.created = fixed
86 + workbook.properties.modified = fixed
87 + for name, headers in SHEET_HEADERS.items():
88 + workbook.create_sheet(name).append(headers)
89 +
90 + company = {
91 + "company_code": DEMO_COMPANY_CODE,
92 + "company_name": DEMO_COMPANY_NAME,
93 + "fiscal_year": DEMO_YEAR,
94 + "currency": "IRR",
95 + "unit": "ریال (ساختگی)",
96 + "prepared_by": "Aram Demo",
97 + "status": "Draft",
98 + }
99 + workbook["Company"].append(_row("Company", company))
100 +
101 + mapping_index = 0
102 + for (code, name, general, general_name, subsidiary, closing, debit, credit,
103 + statement, section, note_number, approval) in _DEMO_ACCOUNTS:
104 + opening = closing - debit + credit
105 + source_row = 100 + int(code)
106 + workbook["Accounts"].append(_row("Accounts", {
107 + "company_code": DEMO_COMPANY_CODE,
108 + "fiscal_year": DEMO_YEAR,
109 + "general_code": general,
110 + "general_name": general_name,
111 + "subsidiary_code": subsidiary,
112 + "subsidiary_name": name,
113 + "account_full_code": code,
114 + "account_name": name,
115 + "opening": opening,
116 + "debit": debit,
117 + "credit": credit,
118 + "closing": closing,
119 + "source_row": source_row,
120 + "row_status": "Reviewed",
121 + "closing_delta": 0,
122 + }))
123 + if statement is None:
124 + continue
125 + mapping_index += 1
126 + reviewed = approval in {"Reviewed", "Approved"}
127 + workbook["Mapping"].append(_row("Mapping", {
128 + "mapping_id": f"DM{mapping_index:03d}",
129 + "company_code": DEMO_COMPANY_CODE,
130 + "fiscal_year": DEMO_YEAR,
131 + "account_full_code": code,
132 + "account_level": "Subsidiary",
133 + "general_code": general,
134 + "subsidiary_code": subsidiary,
135 + "target_statement": statement,
136 + "statement_section": section,
137 + "note_number": note_number,
138 + "mapping_version": 1,
139 + "approval_status": approval,
140 + "reviewer": DEMO_REVIEWER if reviewed else None,
141 + "review_date": DEMO_REVIEW_DATE if reviewed else None,
142 + "source": "synthetic-demo",
143 + "validation_status": "Valid" if approval == "Approved" else "Pending",
144 + }))
145 +
146 + for statement, section, note_number, title in _DEMO_NOTES:
147 + workbook["Notes"].append(_row("Notes", {
148 + "company_code": DEMO_COMPANY_CODE,
149 + "fiscal_year": DEMO_YEAR,
150 + "statement": statement,
151 + "statement_section": section,
152 + "note_number": note_number,
153 + "note_title": title,
154 + }))
155 +
156 + workbook["Guide_FA"].append(("هشدار", "همهٔ ارقام این فایل ساختگی و غیرواقعی هستند."))
157 + workbook["Lists"].append(("demo", "SYNTHETIC"))
158 +
159 + stream = BytesIO()
160 + workbook.save(stream)
161 + return stream.getvalue()
docs/py/aram_backend/pilot_editing.py new
+190
@@ -0,0 +1,190 @@
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 new
+762
@@ -0,0 +1,762 @@
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 new
+351
@@ -0,0 +1,351 @@
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 new
+424
@@ -0,0 +1,424 @@
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/reviews/BOOKLET_COMPLIANCE_REVIEW.md new
+134
@@ -0,0 +1,134 @@
1 +# Booklet v1.0 — Deep Compliance Review (5 reviewer passes)
2 +
3 +- Date: 2026-12-03
4 +- Branch: `arena/094f314c-aram` · PR: [#96](https://github.com/davoodmehraban89/Aram/pull/96) (ready for review)
5 +- Method: five distinct reviewer roles, each with a concrete mandate, executed
6 + against the code/tests/CI with real evidence. This is a single author running
7 + five structured passes (not five independent models); findings are reproducible
8 + from the commands below. The independent GitHub reviewer remains the acceptance
9 + authority (§19 — author does not merge).
10 +
11 +## Agent 1 — Financial integrity & source sanctity
12 +
13 +Mandate: P-02 exact money, rial-for-rial reconciliation, sign convention, source
14 +sacred, drill-down lineage, discrepancies never invented, codes as text.
15 +
16 +Checks & evidence:
17 +- `domain/money.py`: `Rial.process_bind_param` rejects `float` (TypeError),
18 + fractional rial (ValueError), non-finite (ValueError); BIGINT scale-0; rounding
19 + (`round_half_up`/`allocate_remainder`) is display-only. `test_domain_money.py`
20 + includes the P-02 no-silent-rounding guards.
21 +- Exhaustive probe (ADR-012): 457,074 rows across both ledgers, **0 fractional rial**.
22 +- `git diff --name-only <base> HEAD -- data/ samples/` → **empty** (source untouched).
23 +- Golden reconciliation (UAT, real source_1404): core BS notes match official
24 + rial-for-rial (10/11/12-1/12-2/13/14/15); other differences surfaced as
25 + discrepancies (OD-08), never silently corrected.
26 +- Drill-down: `drill_down` returns file/SHA-256/sheet/row per account; UAT exported
27 + 158,050 lineage rows.
28 +
29 +Verdict: **PASS**. No defect found.
30 +
31 +## Agent 2 — Architecture & layering
32 +
33 +Mandate: domain←services←api←ui direction, raw rows + compute-layer aggregation
34 +(D3/P-01), approval runs all controls (D5/C-03), no eval, generic, editable.
35 +
36 +Checks & evidence:
37 +- `grep` domain imports → no services/api/models/fastapi upward imports.
38 +- `grep` services imports → no api/fastapi imports.
39 +- `ledger_import` stores one raw `LedgerBalance` per source row; aggregation lives
40 + in `ledger_aggregate`/`statement_build` (compute layer).
41 +- `domain/formula.py` + `note_engine.py`: AST tokenizer (`re.compile`), **no
42 + eval/exec**; cycle detection.
43 +- No company-specific logic in domain/services (`grep` for gas/company names).
44 +- **Finding F2-1 (FIXED):** notes/mappings/rows had only CREATE endpoints; the
45 + owner requires editable codes/accounts/notes/subnotes. Added PUT/DELETE for
46 + notes, mappings, note rows + GET list endpoints, Draft-guarded, D-07 → HTTP 409,
47 + note-delete refuses while referenced (rows cascade). `test_editing.py` (9 tests)
48 + incl. locked-year edit refusal; UI `NotesManager` wired.
49 +
50 +Verdict: **PASS after F2-1 fix**.
51 +
52 +## Agent 3 — Security, audit & immutability
53 +
54 +Mandate: hash-chained append-only audit, locked-year immutability, controlled
55 +reopen, users/roles (no plaintext), role gates, backup integrity, zero network.
56 +
57 +Checks & evidence:
58 +- `db_triggers`: locked-year insert/update/delete guards + audit append-only +
59 + fiscal-year transition (SQLite & PostgreSQL); `test_immutability.py` passes.
60 +- `audit.verify_chain` recomputes the SHA-256 chain; tamper tests pass.
61 +- Reopen requires an approved `ReopenRequest` (ORM guard + DB trigger re-check).
62 +- `users.py`: PBKDF2-HMAC-SHA256 200k rounds + per-user salt, `hmac.compare_digest`,
63 + no plaintext; `grep` for hardcoded secrets → none.
64 +- `backup.py`: online SQLite snapshot + source-store copy + SHA-256 manifest +
65 + chain re-verification; tamper/non-empty-dest/broken-chain refused.
66 +- `grep` backend src for requests/httpx/urllib/socket → **no outbound network**;
67 + desktop binds 127.0.0.1 only.
68 +- **Finding F3-1 (FIXED):** API `/approve` was not role-gated while `/lock` and
69 + `/reopen` were. Now requires reviewer/admin once users exist (bootstrap/dev
70 + open); the C-01..C-04 ERROR gate always applies. +2 tests.
71 +
72 +Verdict: **PASS after F3-1 fix**.
73 +
74 +## Agent 4 — Testing, CI & quality
75 +
76 +Mandate: full suite green, negative tests, mypy/ruff, frontend gates, Playwright,
77 +migration round-trips, coverage, no faked green.
78 +
79 +Checks & evidence:
80 +- `cd backend && pytest` → **319 passed** (after review fixes).
81 +- `mypy` domain strict + services → clean; `ruff check`/`format` → clean.
82 +- Frontend `eslint`/`tsc`/`vitest`/`build` → pass; Playwright smoke + workflow specs.
83 +- `grep` pytest skip/xfail → only `skipif` conditional on canonical-data presence
84 + (runs in CI where data exists); no unconditional skips faking green. The e2e
85 + workflow spec is backend-gated by design (frontend-only CI stays green).
86 +- Migrations 20261203_05/06/07 up/down/up verified (SQLite); PostgreSQL via CI matrix.
87 +- CI (head `969f608`): Backend [47101026519] ✅, Frontend [47101026555] ✅. Review
88 + fixes re-run CI on the new head.
89 +
90 +Verdict: **PASS**.
91 +
92 +## Agent 5 — Booklet process & deliverables
93 +
94 +Mandate: §15 phase order, §17 autonomous defaults+ADR, §19 bans, §0 status/log,
95 +ADRs, §18 report, reproducible packaging, no committed binaries.
96 +
97 +Checks & evidence:
98 +- Phases 0–9 present in §15 order; PROJECT_STATUS + PROJECT_LOG updated.
99 +- ADRs 012–024 present (015 reserved/unused; not a compliance gap).
100 +- §19: no source edits; no self-merge (PR ready, not merged); no bypassed controls;
101 + no runtime network; no secrets; no NEW root analytical doc (PROJECT_STATUS.md is
102 + the existing canonical status file required by §0).
103 +- **Finding F5-1 (FIXED):** `python-multipart` runtime dep (FastAPI uploads) now
104 + documented in ADR-018.
105 +- **Observation O5-1 (owner decision):** vendored `.whl` files (~250KB+18KB,
106 + duplicated in `docs/vendor` and `webapp/vendor`) were committed in the earlier
107 + **pilot** commit `2fce09d`, not the booklet work. They are small offline
108 + dependencies for the browser edition, not large binaries; a strict §19 reading
109 + flags ZIP-like artifacts. Left intact because they back the accepted pilot
110 + deliverable; the owner may split the pilot browser edition into a separate PR.
111 +- Packaging: `packaging/aram.spec` + `build_desktop.py` reproducible; **no EXE/ZIP
112 + committed**; tag `v1.0.0` is the owner's post-acceptance action.
113 +- §18 report delivered (base/branch/head/PR, tests, CI URLs, artifact NONE,
114 + source-unchanged, risks, "Ready for independent GitHub review; not merged.").
115 +
116 +Verdict: **PASS after F5-1 fix; O5-1 noted for owner**.
117 +
118 +## Findings summary
119 +
120 +| ID | Severity | Status | Resolution |
121 +|---|---|---|---|
122 +| F2-1 editable notes/mappings/rows | High | Fixed | PUT/DELETE + list endpoints, Draft-guarded, 9 tests, UI manager |
123 +| F3-1 approve role gate | Medium | Fixed | reviewer/admin gate when users exist, 2 tests |
124 +| F5-1 python-multipart ADR | Low | Fixed | documented in ADR-018 |
125 +| O5-1 pilot vendored wheels | Info | Noted | pre-existing pilot artifact; owner may split PR |
126 +
127 +## Overall verdict
128 +
129 +All five reviewer passes **PASS** after the fixes above. Backend 319 tests green,
130 +mypy/ruff clean, frontend gates green, CI green, source data unchanged. The work is
131 +complete and booklet-compliant to the extent verifiable without the owner's
132 +accounting judgment on the surfaced real-data discrepancies (OD-08).
133 +
134 +**Ready for independent GitHub review; not merged.**
docs/styles.css new
+293
@@ -0,0 +1,293 @@
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 /dev/null and b/docs/vendor/et_xmlfile-2.0.0-py3-none-any.whl differ
docs/vendor/openpyxl-3.1.5-py2.py3-none-any.whl
Binary files /dev/null and b/docs/vendor/openpyxl-3.1.5-py2.py3-none-any.whl differ
frontend/.gitignore new
+6
@@ -0,0 +1,6 @@
1 +node_modules
2 +dist
3 +playwright-report
4 +test-results
5 +coverage
6 +*.local
frontend/e2e/app.spec.ts new
+14
@@ -0,0 +1,14 @@
1 +import { expect, test } from '@playwright/test'
2 +
3 +test('renders the Aram workbench heading (RTL)', async ({ page }) => {
4 + await page.goto('/')
5 + await expect(page.getByRole('heading', { name: /آرام/ })).toBeVisible()
6 +})
7 +
8 +test('shows the company setup form before a year exists', async ({ page }) => {
9 + await page.goto('/')
10 + await expect(page.getByRole('button', { name: 'ایجاد' })).toBeVisible()
11 + await expect(page.getByLabel('کد شرکت')).toBeVisible()
12 + await expect(page.getByLabel('نام شرکت')).toBeVisible()
13 + await expect(page.getByLabel('سال مالی')).toBeVisible()
14 +})
frontend/e2e/workflow.spec.ts new
+41
@@ -0,0 +1,41 @@
1 +import { expect, test } from '@playwright/test'
2 +
3 +// The full workflow runs against the live FastAPI backend proxied at /api.
4 +// It is skipped when the backend is not reachable so the frontend-only CI job
5 +// stays green; set ARAM_E2E_BACKEND=1 (with the backend running) to enable it.
6 +const backendEnabled = process.env.ARAM_E2E_BACKEND === '1'
7 +
8 +test.describe('full workbench workflow', () => {
9 + test.skip(!backendEnabled, 'requires the backend (ARAM_E2E_BACKEND=1)')
10 +
11 + test('company -> ledger -> mapping -> statement -> drill-down -> approval', async ({ page }) => {
12 + await page.goto('/')
13 +
14 + // 1. Company + fiscal year
15 + await page.getByLabel('کد شرکت').fill('E2E')
16 + await page.getByLabel('نام شرکت').fill('شرکت آزمون')
17 + await page.getByLabel('سال مالی').fill('1404')
18 + await page.getByRole('button', { name: 'ایجاد' }).click()
19 + await expect(page.getByText('بارگذاری دفتر کل')).toBeVisible()
20 +
21 + // 2. Ledger import (real source workbook)
22 + const ledger = page.locator('input[type="file"]').first()
23 + await ledger.setInputFiles('../data/source_ledgers/source_1404.xlsx')
24 + await page.getByRole('button', { name: 'درون‌ریزی' }).click()
25 + await expect(page.getByText(/درون‌ریزی شد/)).toBeVisible({ timeout: 120000 })
26 +
27 + // 3. Build statements
28 + await page.getByRole('button', { name: 'ساخت صورت‌های مالی' }).click()
29 + await expect(page.getByRole('button', { name: 'مشاهدهٔ منبع' }).first()).toBeVisible({
30 + timeout: 60000,
31 + })
32 +
33 + // 4. Drill-down to a source row
34 + await page.getByRole('button', { name: 'مشاهدهٔ منبع' }).first().click()
35 + await expect(page.getByText('ریشه‌یابی:')).toBeVisible()
36 +
37 + // 5. Controls + approval gate
38 + await page.getByRole('button', { name: 'اجرای کنترل‌ها' }).click()
39 + await expect(page.getByText(/کنترل‌های حیاتی/)).toBeVisible()
40 + })
41 +})
frontend/eslint.config.js new
+20
@@ -0,0 +1,20 @@
1 +import js from '@eslint/js'
2 +import globals from 'globals'
3 +import reactHooks from 'eslint-plugin-react-hooks'
4 +import tseslint from 'typescript-eslint'
5 +
6 +export default tseslint.config(
7 + { ignores: ['dist', 'node_modules', 'playwright-report', 'test-results', 'coverage'] },
8 + {
9 + extends: [js.configs.recommended, ...tseslint.configs.recommended],
10 + files: ['**/*.{ts,tsx}'],
11 + languageOptions: {
12 + ecmaVersion: 2022,
13 + globals: { ...globals.browser, ...globals.node },
14 + },
15 + plugins: { 'react-hooks': reactHooks },
16 + rules: {
17 + ...reactHooks.configs.recommended.rules,
18 + },
19 + },
20 +)
frontend/index.html new
+12
@@ -0,0 +1,12 @@
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.0" />
6 + <title>آرام — میز کار صورت‌های مالی</title>
7 + </head>
8 + <body>
9 + <div id="root"></div>
10 + <script type="module" src="/src/main.tsx"></script>
11 + </body>
12 +</html>
frontend/package-lock.json new
+4702
@@ -0,0 +1,4702 @@
1 +{
2 + "name": "aram-frontend",
3 + "version": "0.1.0",
4 + "lockfileVersion": 3,
5 + "requires": true,
6 + "packages": {
7 + "": {
8 + "name": "aram-frontend",
9 + "version": "0.1.0",
10 + "dependencies": {
11 + "react": "^18.3.1",
12 + "react-dom": "^18.3.1"
13 + },
14 + "devDependencies": {
15 + "@eslint/js": "^9.13.0",
16 + "@playwright/test": "^1.48.2",
17 + "@testing-library/jest-dom": "^6.6.2",
18 + "@testing-library/react": "^16.0.1",
19 + "@types/node": "^22.20.7",
20 + "@types/react": "^18.3.12",
21 + "@types/react-dom": "^18.3.1",
22 + "@vitejs/plugin-react": "^4.3.3",
23 + "eslint": "^9.13.0",
24 + "eslint-plugin-react-hooks": "^5.0.0",
25 + "globals": "^15.11.0",
26 + "jsdom": "^25.0.1",
27 + "typescript": "^5.6.3",
28 + "typescript-eslint": "^8.11.0",
29 + "vite": "^5.4.10",
30 + "vitest": "^2.1.4"
31 + }
32 + },
33 + "node_modules/@adobe/css-tools": {
34 + "version": "4.5.0",
35 + "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz",
36 + "integrity": "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==",
37 + "dev": true,
38 + "license": "MIT"
39 + },
40 + "node_modules/@asamuzakjp/css-color": {
41 + "version": "3.2.0",
42 + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz",
43 + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==",
44 + "dev": true,
45 + "license": "MIT",
46 + "dependencies": {
47 + "@csstools/css-calc": "^2.1.3",
48 + "@csstools/css-color-parser": "^3.0.9",
49 + "@csstools/css-parser-algorithms": "^3.0.4",
50 + "@csstools/css-tokenizer": "^3.0.3",
51 + "lru-cache": "^10.4.3"
52 + }
53 + },
54 + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": {
55 + "version": "10.4.3",
56 + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
57 + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
58 + "dev": true,
59 + "license": "ISC"
60 + },
61 + "node_modules/@babel/code-frame": {
62 + "version": "7.29.17",
63 + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.17.tgz",
64 + "integrity": "sha512-IdlVpcDeoDATtN2cfmnVk0A4XJKhu7SlpGuSaiOFdko09YC1MD07WokWUSEdw5R2o4o8VObX2LzViQW6VXnzkA==",
65 + "dev": true,
66 + "license": "MIT",
67 + "dependencies": {
68 + "@babel/helper-validator-identifier": "^7.29.17",
69 + "js-tokens": "^4.0.0",
70 + "picocolors": "^1.1.1"
71 + },
72 + "engines": {
73 + "node": ">=6.9.0"
74 + }
75 + },
76 + "node_modules/@babel/compat-data": {
77 + "version": "7.29.17",
78 + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.17.tgz",
79 + "integrity": "sha512-pC/HCNB1loXYCLB9S7FDieWKJiXH8LJTUGFvVAm+7hWUKBjL07EcvVITNH9KlXdS/TTSbChZHZCYx/yag6LbRw==",
80 + "dev": true,
81 + "license": "MIT",
82 + "engines": {
83 + "node": ">=6.9.0"
84 + }
85 + },
86 + "node_modules/@babel/core": {
87 + "version": "7.29.17",
88 + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.17.tgz",
89 + "integrity": "sha512-dP4g0UpATLviwEEb46bBaeL5MyW3q7LwqGoaQJvjXGS8tdpxckLtDTI9FBwA5ioVHnYoR2nRqCf1BmlMwbZV5A==",
90 + "dev": true,
91 + "license": "MIT",
92 + "dependencies": {
93 + "@babel/code-frame": "^7.29.17",
94 + "@babel/generator": "^7.29.17",
95 + "@babel/helper-compilation-targets": "^7.29.17",
96 + "@babel/helper-module-transforms": "^7.29.17",
97 + "@babel/helpers": "^7.29.17",
98 + "@babel/parser": "^7.29.17",
99 + "@babel/template": "^7.29.17",
100 + "@babel/traverse": "^7.29.17",
101 + "@babel/types": "^7.29.17",
102 + "@jridgewell/remapping": "^2.3.5",
103 + "convert-source-map": "^2.0.0",
104 + "debug": "^4.1.0",
105 + "gensync": "^1.0.0-beta.2",
106 + "json5": "^2.2.3",
107 + "semver": "^6.3.1"
108 + },
109 + "engines": {
110 + "node": ">=6.9.0"
111 + },
112 + "funding": {
113 + "type": "opencollective",
114 + "url": "https://opencollective.com/babel"
115 + }
116 + },
117 + "node_modules/@babel/generator": {
118 + "version": "7.29.17",
119 + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.17.tgz",
120 + "integrity": "sha512-xjNUVINWex7s4U0vESYwa8ChCBnmvhCQ6nkAdnhM8WYPlhXvU9D9fPurOSYQLV4FwcNXacDkN/MWIPNHsTI2OA==",
121 + "dev": true,
122 + "license": "MIT",
123 + "dependencies": {
124 + "@babel/parser": "^7.29.17",
125 + "@babel/types": "^7.29.17",
126 + "@jridgewell/gen-mapping": "^0.3.12",
127 + "@jridgewell/trace-mapping": "^0.3.28",
128 + "jsesc": "^3.0.2"
129 + },
130 + "engines": {
131 + "node": ">=6.9.0"
132 + }
133 + },
134 + "node_modules/@babel/helper-compilation-targets": {
135 + "version": "7.29.17",
136 + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.17.tgz",
137 + "integrity": "sha512-6uFqkZstBw0lSRaEr/7HNuqURHubX4BvnN0FbbIBNFa5/nUcKLp5AFubCcUlbik9mI/Ztsz3mdjjpqoF3dVqrA==",
138 + "dev": true,
139 + "license": "MIT",
140 + "dependencies": {
141 + "@babel/compat-data": "^7.29.17",
142 + "@babel/helper-validator-option": "^7.29.17",
143 + "browserslist": "^4.24.0",
144 + "lru-cache": "^5.1.1",
145 + "semver": "^6.3.1"
146 + },
147 + "engines": {
148 + "node": ">=6.9.0"
149 + }
150 + },
151 + "node_modules/@babel/helper-globals": {
152 + "version": "7.29.17",
153 + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.17.tgz",
154 + "integrity": "sha512-SeQUwFlH8hH1vjUmBFeqwxt6Nsjp01MKEZOtZPJ86lpA4GBdb/o0dShjC+Awf7v74/+84KIL1RiJ4TOJj6gU+A==",
155 + "dev": true,
156 + "license": "MIT",
157 + "engines": {
158 + "node": ">=6.9.0"
159 + }
160 + },
161 + "node_modules/@babel/helper-module-imports": {
162 + "version": "7.29.17",
163 + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.17.tgz",
164 + "integrity": "sha512-bLxkfvUEHeWShbadKTm7EfDCkosXZh6PjWEa9bYiCuob24c0nm388ara2Hz6KisGaXe+XCsi6VyfJNSJjeUUwg==",
165 + "dev": true,
166 + "license": "MIT",
167 + "dependencies": {
168 + "@babel/traverse": "^7.29.17",
169 + "@babel/types": "^7.29.17"
170 + },
171 + "engines": {
172 + "node": ">=6.9.0"
173 + }
174 + },
175 + "node_modules/@babel/helper-module-transforms": {
176 + "version": "7.29.17",
177 + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.17.tgz",
178 + "integrity": "sha512-eY/pAYlV7pC5biPmW0M7fDqv1D+opqI0Ioa6OQeg0AV3465b8K8g9I9fvZIV11u35f7jU6q5RXYlUD6k4QLC3w==",
179 + "dev": true,
180 + "license": "MIT",
181 + "dependencies": {
182 + "@babel/helper-module-imports": "^7.29.17",
183 + "@babel/helper-validator-identifier": "^7.29.17",
184 + "@babel/traverse": "^7.29.17"
185 + },
186 + "engines": {
187 + "node": ">=6.9.0"
188 + },
189 + "peerDependencies": {
190 + "@babel/core": "^7.0.0"
191 + }
192 + },
193 + "node_modules/@babel/helper-plugin-utils": {
194 + "version": "7.29.17",
195 + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.17.tgz",
196 + "integrity": "sha512-pdztM6tDPJu52CYy07frAD1XpDAvndtxPhPyehcarNv5Pyq5hutWmTVXd0XIPaI749vUIJ+vxG6KYWoVExn+lg==",
197 + "dev": true,
198 + "license": "MIT",
199 + "engines": {
200 + "node": ">=6.9.0"
201 + }
202 + },
203 + "node_modules/@babel/helper-string-parser": {
204 + "version": "7.29.17",
205 + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.17.tgz",
206 + "integrity": "sha512-iY5lvqFhfgMXp4o4zWads4NvQZXizBxzCoADPOgFMcMwk1XefAdBJbc9i1y94aflY57lokjOjRTa3AOOW9R7BQ==",
207 + "dev": true,
208 + "license": "MIT",
209 + "engines": {
210 + "node": ">=6.9.0"
211 + }
212 + },
213 + "node_modules/@babel/helper-validator-identifier": {
214 + "version": "7.29.17",
215 + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.17.tgz",
216 + "integrity": "sha512-AG+olLB+teKhkQ2WYJeaZqJwNLjtWTz1waQIP/tEYITzVzpdHLP7IXx2c/bH2JTsNCgvWlkqdCv91xcb8lul8Q==",
217 + "dev": true,
218 + "license": "MIT",
219 + "engines": {
220 + "node": ">=6.9.0"
221 + }
222 + },
223 + "node_modules/@babel/helper-validator-option": {
224 + "version": "7.29.17",
225 + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.17.tgz",
226 + "integrity": "sha512-Pr+bjfbd4TYVax16KyHVyElTnid5nbWQWQvA/dPlESoKVZ8B4eTAUhoqug/mtD9hWAEgIQIOyvjUBMI9HjdrGw==",
227 + "dev": true,
228 + "license": "MIT",
229 + "engines": {
230 + "node": ">=6.9.0"
231 + }
232 + },
233 + "node_modules/@babel/helpers": {
234 + "version": "7.29.17",
235 + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.17.tgz",
236 + "integrity": "sha512-Q7LRJjIiFAiOtfkVBzXe4op1tQ8dXYsRsdojKzLfERndnXcmyyn9RZIBlSJzFo0O3CouXV3Tvb8AGolaDr1M7A==",
237 + "dev": true,
238 + "license": "MIT",
239 + "dependencies": {
240 + "@babel/template": "^7.29.17",
241 + "@babel/types": "^7.29.17"
242 + },
243 + "engines": {
244 + "node": ">=6.9.0"
245 + }
246 + },
247 + "node_modules/@babel/parser": {
248 + "version": "7.29.17",
249 + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.17.tgz",
250 + "integrity": "sha512-I+0olVqWMm9bimQJc/5B3jn1nivNDXtnMtDVs07XdHzZLcWa2N/mlCTPmAsQg95QcKoXSuFD2Yz4fwdtoyk7DQ==",
251 + "dev": true,
252 + "license": "MIT",
253 + "dependencies": {
254 + "@babel/types": "^7.29.17"
255 + },
256 + "bin": {
257 + "parser": "bin/babel-parser.js"
258 + },
259 + "engines": {
260 + "node": ">=6.0.0"
261 + }
262 + },
263 + "node_modules/@babel/plugin-transform-react-jsx-self": {
264 + "version": "7.29.7",
265 + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz",
266 + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==",
267 + "dev": true,
268 + "license": "MIT",
269 + "dependencies": {
270 + "@babel/helper-plugin-utils": "^7.29.7"
271 + },
272 + "engines": {
273 + "node": ">=6.9.0"
274 + },
275 + "peerDependencies": {
276 + "@babel/core": "^7.0.0-0"
277 + }
278 + },
279 + "node_modules/@babel/plugin-transform-react-jsx-source": {
280 + "version": "7.29.7",
281 + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz",
282 + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==",
283 + "dev": true,
284 + "license": "MIT",
285 + "dependencies": {
286 + "@babel/helper-plugin-utils": "^7.29.7"
287 + },
288 + "engines": {
289 + "node": ">=6.9.0"
290 + },
291 + "peerDependencies": {
292 + "@babel/core": "^7.0.0-0"
293 + }
294 + },
295 + "node_modules/@babel/runtime": {
296 + "version": "7.29.17",
297 + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.17.tgz",
298 + "integrity": "sha512-CvlZdpED5dsu21yK0DfpXksJWt1zeW09lY49hp7P9cA5Qedx/QkwEs1PfluSJjijH9i94oT9LmtgGWlPY8ISzw==",
299 + "dev": true,
300 + "license": "MIT",
301 + "engines": {
302 + "node": ">=6.9.0"
303 + }
304 + },
305 + "node_modules/@babel/template": {
306 + "version": "7.29.17",
307 + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.17.tgz",
308 + "integrity": "sha512-D4nOLKOzIBwn7/Z78h3UPEwzFObmPVTukBJ9+63BijgMVeLj6mQ77FJb6YCZ4QBo6VjAk/yj4QnpKusTcBy6vA==",
309 + "dev": true,
310 + "license": "MIT",
311 + "dependencies": {
312 + "@babel/code-frame": "^7.29.17",
313 + "@babel/parser": "^7.29.17",
314 + "@babel/types": "^7.29.17"
315 + },
316 + "engines": {
317 + "node": ">=6.9.0"
318 + }
319 + },
320 + "node_modules/@babel/traverse": {
321 + "version": "7.29.17",
322 + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.17.tgz",
323 + "integrity": "sha512-q+CnfQcmNfDdOUARkt9FWtdR0HPOCcyQBj1Z7l2SOpFIfUB/XI3dXS0B5UOlZWwQCun80xVhgcv4ip6w128u9g==",
324 + "dev": true,
325 + "license": "MIT",
326 + "dependencies": {
327 + "@babel/code-frame": "^7.29.17",
328 + "@babel/generator": "^7.29.17",
329 + "@babel/helper-globals": "^7.29.17",
330 + "@babel/parser": "^7.29.17",
331 + "@babel/template": "^7.29.17",
332 + "@babel/types": "^7.29.17",
333 + "debug": "^4.3.1"
334 + },
335 + "engines": {
336 + "node": ">=6.9.0"
337 + }
338 + },
339 + "node_modules/@babel/types": {
340 + "version": "7.29.17",
341 + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.17.tgz",
342 + "integrity": "sha512-kzo3lZUbI0gARA4QvhmOTH/aws2SrZ880ECQRIjPPSrdfBM0bZCkj1U7UN2fB0GNeXayqCiLVXa2+1jAhn377Q==",
343 + "dev": true,
344 + "license": "MIT",
345 + "dependencies": {
346 + "@babel/helper-string-parser": "^7.29.17",
347 + "@babel/helper-validator-identifier": "^7.29.17"
348 + },
349 + "engines": {
350 + "node": ">=6.9.0"
351 + }
352 + },
353 + "node_modules/@csstools/color-helpers": {
354 + "version": "5.1.0",
355 + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz",
356 + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==",
357 + "dev": true,
358 + "funding": [
359 + {
360 + "type": "github",
361 + "url": "https://github.com/sponsors/csstools"
362 + },
363 + {
364 + "type": "opencollective",
365 + "url": "https://opencollective.com/csstools"
366 + }
367 + ],
368 + "license": "MIT-0",
369 + "engines": {
370 + "node": ">=18"
371 + }
372 + },
373 + "node_modules/@csstools/css-calc": {
374 + "version": "2.1.4",
375 + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz",
376 + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==",
377 + "dev": true,
378 + "funding": [
379 + {
380 + "type": "github",
381 + "url": "https://github.com/sponsors/csstools"
382 + },
383 + {
384 + "type": "opencollective",
385 + "url": "https://opencollective.com/csstools"
386 + }
387 + ],
388 + "license": "MIT",
389 + "engines": {
390 + "node": ">=18"
391 + },
392 + "peerDependencies": {
393 + "@csstools/css-parser-algorithms": "^3.0.5",
394 + "@csstools/css-tokenizer": "^3.0.4"
395 + }
396 + },
397 + "node_modules/@csstools/css-color-parser": {
398 + "version": "3.1.0",
399 + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz",
400 + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==",
401 + "dev": true,
402 + "funding": [
403 + {
404 + "type": "github",
405 + "url": "https://github.com/sponsors/csstools"
406 + },
407 + {
408 + "type": "opencollective",
409 + "url": "https://opencollective.com/csstools"
410 + }
411 + ],
412 + "license": "MIT",
413 + "dependencies": {
414 + "@csstools/color-helpers": "^5.1.0",
415 + "@csstools/css-calc": "^2.1.4"
416 + },
417 + "engines": {
418 + "node": ">=18"
419 + },
420 + "peerDependencies": {
421 + "@csstools/css-parser-algorithms": "^3.0.5",
422 + "@csstools/css-tokenizer": "^3.0.4"
423 + }
424 + },
425 + "node_modules/@csstools/css-parser-algorithms": {
426 + "version": "3.0.5",
427 + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz",
428 + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==",
429 + "dev": true,
430 + "funding": [
431 + {
432 + "type": "github",
433 + "url": "https://github.com/sponsors/csstools"
434 + },
435 + {
436 + "type": "opencollective",
437 + "url": "https://opencollective.com/csstools"
438 + }
439 + ],
440 + "license": "MIT",
441 + "engines": {
442 + "node": ">=18"
443 + },
444 + "peerDependencies": {
445 + "@csstools/css-tokenizer": "^3.0.4"
446 + }
447 + },
448 + "node_modules/@csstools/css-tokenizer": {
449 + "version": "3.0.4",
450 + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz",
451 + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==",
452 + "dev": true,
453 + "funding": [
454 + {
455 + "type": "github",
456 + "url": "https://github.com/sponsors/csstools"
457 + },
458 + {
459 + "type": "opencollective",
460 + "url": "https://opencollective.com/csstools"
461 + }
462 + ],
463 + "license": "MIT",
464 + "engines": {
465 + "node": ">=18"
466 + }
467 + },
468 + "node_modules/@esbuild/aix-ppc64": {
469 + "version": "0.21.5",
470 + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
471 + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",
472 + "cpu": [
473 + "ppc64"
474 + ],
475 + "dev": true,
476 + "license": "MIT",
477 + "optional": true,
478 + "os": [
479 + "aix"
480 + ],
481 + "engines": {
482 + "node": ">=12"
483 + }
484 + },
485 + "node_modules/@esbuild/android-arm": {
486 + "version": "0.21.5",
487 + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",
488 + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",
489 + "cpu": [
490 + "arm"
491 + ],
492 + "dev": true,
493 + "license": "MIT",
494 + "optional": true,
495 + "os": [
496 + "android"
497 + ],
498 + "engines": {
499 + "node": ">=12"
500 + }
501 + },
502 + "node_modules/@esbuild/android-arm64": {
503 + "version": "0.21.5",
504 + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",
505 + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",
506 + "cpu": [
507 + "arm64"
508 + ],
509 + "dev": true,
510 + "license": "MIT",
511 + "optional": true,
512 + "os": [
513 + "android"
514 + ],
515 + "engines": {
516 + "node": ">=12"
517 + }
518 + },
519 + "node_modules/@esbuild/android-x64": {
520 + "version": "0.21.5",
521 + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",
522 + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",
523 + "cpu": [
524 + "x64"
525 + ],
526 + "dev": true,
527 + "license": "MIT",
528 + "optional": true,
529 + "os": [
530 + "android"
531 + ],
532 + "engines": {
533 + "node": ">=12"
534 + }
535 + },
536 + "node_modules/@esbuild/darwin-arm64": {
537 + "version": "0.21.5",
538 + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",
539 + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",
540 + "cpu": [
541 + "arm64"
542 + ],
543 + "dev": true,
544 + "license": "MIT",
545 + "optional": true,
546 + "os": [
547 + "darwin"
548 + ],
549 + "engines": {
550 + "node": ">=12"
551 + }
552 + },
553 + "node_modules/@esbuild/darwin-x64": {
554 + "version": "0.21.5",
555 + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",
556 + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",
557 + "cpu": [
558 + "x64"
559 + ],
560 + "dev": true,
561 + "license": "MIT",
562 + "optional": true,
563 + "os": [
564 + "darwin"
565 + ],
566 + "engines": {
567 + "node": ">=12"
568 + }
569 + },
570 + "node_modules/@esbuild/freebsd-arm64": {
571 + "version": "0.21.5",
572 + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",
573 + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",
574 + "cpu": [
575 + "arm64"
576 + ],
577 + "dev": true,
578 + "license": "MIT",
579 + "optional": true,
580 + "os": [
581 + "freebsd"
582 + ],
583 + "engines": {
584 + "node": ">=12"
585 + }
586 + },
587 + "node_modules/@esbuild/freebsd-x64": {
588 + "version": "0.21.5",
589 + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",
590 + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",
591 + "cpu": [
592 + "x64"
593 + ],
594 + "dev": true,
595 + "license": "MIT",
596 + "optional": true,
597 + "os": [
598 + "freebsd"
599 + ],
600 + "engines": {
601 + "node": ">=12"
602 + }
603 + },
604 + "node_modules/@esbuild/linux-arm": {
605 + "version": "0.21.5",
606 + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",
607 + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",
608 + "cpu": [
609 + "arm"
610 + ],
611 + "dev": true,
612 + "license": "MIT",
613 + "optional": true,
614 + "os": [
615 + "linux"
616 + ],
617 + "engines": {
618 + "node": ">=12"
619 + }
620 + },
621 + "node_modules/@esbuild/linux-arm64": {
622 + "version": "0.21.5",
623 + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
624 + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
625 + "cpu": [
626 + "arm64"
627 + ],
628 + "dev": true,
629 + "license": "MIT",
630 + "optional": true,
631 + "os": [
632 + "linux"
633 + ],
634 + "engines": {
635 + "node": ">=12"
636 + }
637 + },
638 + "node_modules/@esbuild/linux-ia32": {
639 + "version": "0.21.5",
640 + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",
641 + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",
642 + "cpu": [
643 + "ia32"
644 + ],
645 + "dev": true,
646 + "license": "MIT",
647 + "optional": true,
648 + "os": [
649 + "linux"
650 + ],
651 + "engines": {
652 + "node": ">=12"
653 + }
654 + },
655 + "node_modules/@esbuild/linux-loong64": {
656 + "version": "0.21.5",
657 + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",
658 + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",
659 + "cpu": [
660 + "loong64"
661 + ],
662 + "dev": true,
663 + "license": "MIT",
664 + "optional": true,
665 + "os": [
666 + "linux"
667 + ],
668 + "engines": {
669 + "node": ">=12"
670 + }
671 + },
672 + "node_modules/@esbuild/linux-mips64el": {
673 + "version": "0.21.5",
674 + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",
675 + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",
676 + "cpu": [
677 + "mips64el"
678 + ],
679 + "dev": true,
680 + "license": "MIT",
681 + "optional": true,
682 + "os": [
683 + "linux"
684 + ],
685 + "engines": {
686 + "node": ">=12"
687 + }
688 + },
689 + "node_modules/@esbuild/linux-ppc64": {
690 + "version": "0.21.5",
691 + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",
692 + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",
693 + "cpu": [
694 + "ppc64"
695 + ],
696 + "dev": true,
697 + "license": "MIT",
698 + "optional": true,
699 + "os": [
700 + "linux"
701 + ],
702 + "engines": {
703 + "node": ">=12"
704 + }
705 + },
706 + "node_modules/@esbuild/linux-riscv64": {
707 + "version": "0.21.5",
708 + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",
709 + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",
710 + "cpu": [
711 + "riscv64"
712 + ],
713 + "dev": true,
714 + "license": "MIT",
715 + "optional": true,
716 + "os": [
717 + "linux"
718 + ],
719 + "engines": {
720 + "node": ">=12"
721 + }
722 + },
723 + "node_modules/@esbuild/linux-s390x": {
724 + "version": "0.21.5",
725 + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",
726 + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",
727 + "cpu": [
728 + "s390x"
729 + ],
730 + "dev": true,
731 + "license": "MIT",
732 + "optional": true,
733 + "os": [
734 + "linux"
735 + ],
736 + "engines": {
737 + "node": ">=12"
738 + }
739 + },
740 + "node_modules/@esbuild/linux-x64": {
741 + "version": "0.21.5",
742 + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",
743 + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",
744 + "cpu": [
745 + "x64"
746 + ],
747 + "dev": true,
748 + "license": "MIT",
749 + "optional": true,
750 + "os": [
751 + "linux"
752 + ],
753 + "engines": {
754 + "node": ">=12"
755 + }
756 + },
757 + "node_modules/@esbuild/netbsd-x64": {
758 + "version": "0.21.5",
759 + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
760 + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",
761 + "cpu": [
762 + "x64"
763 + ],
764 + "dev": true,
765 + "license": "MIT",
766 + "optional": true,
767 + "os": [
768 + "netbsd"
769 + ],
770 + "engines": {
771 + "node": ">=12"
772 + }
773 + },
774 + "node_modules/@esbuild/openbsd-x64": {
775 + "version": "0.21.5",
776 + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
777 + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",
778 + "cpu": [
779 + "x64"
780 + ],
781 + "dev": true,
782 + "license": "MIT",
783 + "optional": true,
784 + "os": [
785 + "openbsd"
786 + ],
787 + "engines": {
788 + "node": ">=12"
789 + }
790 + },
791 + "node_modules/@esbuild/sunos-x64": {
792 + "version": "0.21.5",
793 + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
794 + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",
795 + "cpu": [
796 + "x64"
797 + ],
798 + "dev": true,
799 + "license": "MIT",
800 + "optional": true,
801 + "os": [
802 + "sunos"
803 + ],
804 + "engines": {
805 + "node": ">=12"
806 + }
807 + },
808 + "node_modules/@esbuild/win32-arm64": {
809 + "version": "0.21.5",
810 + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",
811 + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",
812 + "cpu": [
813 + "arm64"
814 + ],
815 + "dev": true,
816 + "license": "MIT",
817 + "optional": true,
818 + "os": [
819 + "win32"
820 + ],
821 + "engines": {
822 + "node": ">=12"
823 + }
824 + },
825 + "node_modules/@esbuild/win32-ia32": {
826 + "version": "0.21.5",
827 + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",
828 + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",
829 + "cpu": [
830 + "ia32"
831 + ],
832 + "dev": true,
833 + "license": "MIT",
834 + "optional": true,
835 + "os": [
836 + "win32"
837 + ],
838 + "engines": {
839 + "node": ">=12"
840 + }
841 + },
842 + "node_modules/@esbuild/win32-x64": {
843 + "version": "0.21.5",
844 + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",
845 + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",
846 + "cpu": [
847 + "x64"
848 + ],
849 + "dev": true,
850 + "license": "MIT",
851 + "optional": true,
852 + "os": [
853 + "win32"
854 + ],
855 + "engines": {
856 + "node": ">=12"
857 + }
858 + },
859 + "node_modules/@eslint-community/eslint-utils": {
860 + "version": "4.10.1",
861 + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
862 + "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==",
863 + "dev": true,
864 + "license": "MIT",
865 + "dependencies": {
866 + "eslint-visitor-keys": "^3.4.3"
867 + },
868 + "engines": {
869 + "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
870 + },
871 + "funding": {
872 + "url": "https://opencollective.com/eslint"
873 + },
874 + "peerDependencies": {
875 + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"
876 + }
877 + },
878 + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": {
879 + "version": "3.4.3",
880 + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",
881 + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",
882 + "dev": true,
883 + "license": "Apache-2.0",
884 + "engines": {
885 + "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
886 + },
887 + "funding": {
888 + "url": "https://opencollective.com/eslint"
889 + }
890 + },
891 + "node_modules/@eslint-community/regexpp": {
892 + "version": "4.12.4",
893 + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.4.tgz",
894 + "integrity": "sha512-1qH3WeISXHFS8P3QI0lntHlMrlfTh1OarxlRbPNDEkSCqoyXC3apBE7MDyRKOL8HpuW48aQtff30wvEFww/4ww==",
895 + "dev": true,
896 + "license": "MIT",
897 + "engines": {
898 + "node": "^12.0.0 || ^14.0.0 || >=16.0.0"
899 + }
900 + },
901 + "node_modules/@eslint/config-array": {
902 + "version": "0.21.2",
903 + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz",
904 + "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==",
905 + "dev": true,
906 + "license": "Apache-2.0",
907 + "dependencies": {
908 + "@eslint/object-schema": "^2.1.7",
909 + "debug": "^4.3.1",
910 + "minimatch": "^3.1.5"
911 + },
912 + "engines": {
913 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
914 + }
915 + },
916 + "node_modules/@eslint/config-helpers": {
917 + "version": "0.4.2",
918 + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz",
919 + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==",
920 + "dev": true,
921 + "license": "Apache-2.0",
922 + "dependencies": {
923 + "@eslint/core": "^0.17.0"
924 + },
925 + "engines": {
926 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
927 + }
928 + },
929 + "node_modules/@eslint/core": {
930 + "version": "0.17.0",
931 + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz",
932 + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==",
933 + "dev": true,
934 + "license": "Apache-2.0",
935 + "dependencies": {
936 + "@types/json-schema": "^7.0.15"
937 + },
938 + "engines": {
939 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
940 + }
941 + },
942 + "node_modules/@eslint/eslintrc": {
943 + "version": "3.3.7",
944 + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.7.tgz",
945 + "integrity": "sha512-F42g89Qd5oAWtp0k0nnSrjziAKza7w8SVT4mStc18LZMaRb4J1HQAHLCalEtDCxrTuksx7NU9qsmeLwpOfPqWw==",
946 + "dev": true,
947 + "license": "MIT",
948 + "dependencies": {
949 + "ajv": "^6.14.0",
950 + "debug": "^4.3.2",
951 + "espree": "^10.0.1",
952 + "globals": "^14.0.0",
953 + "ignore": "^5.2.0",
954 + "import-fresh": "^3.2.1",
955 + "js-yaml": "^4.3.2",
956 + "minimatch": "^3.1.5",
957 + "strip-json-comments": "^3.1.1"
958 + },
959 + "engines": {
960 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
961 + },
962 + "funding": {
963 + "url": "https://opencollective.com/eslint"
964 + }
965 + },
966 + "node_modules/@eslint/eslintrc/node_modules/globals": {
967 + "version": "14.0.0",
968 + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",
969 + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",
970 + "dev": true,
971 + "license": "MIT",
972 + "engines": {
973 + "node": ">=18"
974 + },
975 + "funding": {
976 + "url": "https://github.com/sponsors/sindresorhus"
977 + }
978 + },
979 + "node_modules/@eslint/js": {
980 + "version": "9.39.5",
981 + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.5.tgz",
982 + "integrity": "sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A==",
983 + "dev": true,
984 + "license": "MIT",
985 + "engines": {
986 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
987 + },
988 + "funding": {
989 + "url": "https://eslint.org/donate"
990 + }
991 + },
992 + "node_modules/@eslint/object-schema": {
993 + "version": "2.1.7",
994 + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz",
995 + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==",
996 + "dev": true,
997 + "license": "Apache-2.0",
998 + "engines": {
999 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1000 + }
1001 + },
1002 + "node_modules/@eslint/plugin-kit": {
1003 + "version": "0.4.1",
1004 + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz",
1005 + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==",
1006 + "dev": true,
1007 + "license": "Apache-2.0",
1008 + "dependencies": {
1009 + "@eslint/core": "^0.17.0",
1010 + "levn": "^0.4.1"
1011 + },
1012 + "engines": {
1013 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1014 + }
1015 + },
1016 + "node_modules/@humanfs/core": {
1017 + "version": "0.19.2",
1018 + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
1019 + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==",
1020 + "dev": true,
1021 + "license": "Apache-2.0",
1022 + "dependencies": {
1023 + "@humanfs/types": "^0.15.0"
1024 + },
1025 + "engines": {
1026 + "node": ">=18.18.0"
1027 + }
1028 + },
1029 + "node_modules/@humanfs/node": {
1030 + "version": "0.16.8",
1031 + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz",
1032 + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==",
1033 + "dev": true,
1034 + "license": "Apache-2.0",
1035 + "dependencies": {
1036 + "@humanfs/core": "^0.19.2",
1037 + "@humanfs/types": "^0.15.0",
1038 + "@humanwhocodes/retry": "^0.4.0"
1039 + },
1040 + "engines": {
1041 + "node": ">=18.18.0"
1042 + }
1043 + },
1044 + "node_modules/@humanfs/types": {
1045 + "version": "0.15.0",
1046 + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz",
1047 + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==",
1048 + "dev": true,
1049 + "license": "Apache-2.0",
1050 + "engines": {
1051 + "node": ">=18.18.0"
1052 + }
1053 + },
1054 + "node_modules/@humanwhocodes/module-importer": {
1055 + "version": "1.0.1",
1056 + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
1057 + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",
1058 + "dev": true,
1059 + "license": "Apache-2.0",
1060 + "engines": {
1061 + "node": ">=12.22"
1062 + },
1063 + "funding": {
1064 + "type": "github",
1065 + "url": "https://github.com/sponsors/nzakas"
1066 + }
1067 + },
1068 + "node_modules/@humanwhocodes/retry": {
1069 + "version": "0.4.3",
1070 + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz",
1071 + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==",
1072 + "dev": true,
1073 + "license": "Apache-2.0",
1074 + "engines": {
1075 + "node": ">=18.18"
1076 + },
1077 + "funding": {
1078 + "type": "github",
1079 + "url": "https://github.com/sponsors/nzakas"
1080 + }
1081 + },
1082 + "node_modules/@isaacs/nonrecursive-glob-match": {
1083 + "version": "1.1.0",
1084 + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
1085 + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
1086 + "dev": true,
1087 + "license": "BlueOak-1.0.0"
1088 + },
1089 + "node_modules/@jridgewell/gen-mapping": {
1090 + "version": "0.3.13",
1091 + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
1092 + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
1093 + "dev": true,
1094 + "license": "MIT",
1095 + "dependencies": {
1096 + "@jridgewell/sourcemap-codec": "^1.5.0",
1097 + "@jridgewell/trace-mapping": "^0.3.24"
1098 + }
1099 + },
1100 + "node_modules/@jridgewell/remapping": {
1101 + "version": "2.3.5",
1102 + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
1103 + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
1104 + "dev": true,
1105 + "license": "MIT",
1106 + "dependencies": {
1107 + "@jridgewell/gen-mapping": "^0.3.5",
1108 + "@jridgewell/trace-mapping": "^0.3.24"
1109 + }
1110 + },
1111 + "node_modules/@jridgewell/resolve-uri": {
1112 + "version": "3.1.3",
1113 + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz",
1114 + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==",
1115 + "dev": true,
1116 + "license": "MIT",
1117 + "engines": {
1118 + "node": ">=6.0.0"
1119 + }
1120 + },
1121 + "node_modules/@jridgewell/sourcemap-codec": {
1122 + "version": "1.6.0",
1123 + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
1124 + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
1125 + "dev": true,
1126 + "license": "MIT"
1127 + },
1128 + "node_modules/@jridgewell/trace-mapping": {
1129 + "version": "0.3.31",
1130 + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
1131 + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
1132 + "dev": true,
1133 + "license": "MIT",
1134 + "dependencies": {
1135 + "@jridgewell/resolve-uri": "^3.1.0",
1136 + "@jridgewell/sourcemap-codec": "^1.4.14"
1137 + }
1138 + },
1139 + "node_modules/@playwright/test": {
1140 + "version": "1.65.2",
1141 + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.2.tgz",
1142 + "integrity": "sha512-YCNiTHPXCL7V3SOXfjAW27WcmwhqtInvsSbz8by1nRKZ7n6/GGgZfXtEx2ALLs+yUpiMptPFCT9V4HskTVw8Tg==",
1143 + "dev": true,
1144 + "license": "Apache-2.0",
1145 + "dependencies": {
1146 + "playwright": "1.65.2"
1147 + },
1148 + "bin": {
1149 + "playwright": "cli.js"
1150 + },
1151 + "engines": {
1152 + "node": ">=20"
1153 + }
1154 + },
1155 + "node_modules/@rolldown/pluginutils": {
1156 + "version": "1.0.0-beta.27",
1157 + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
1158 + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==",
1159 + "dev": true,
1160 + "license": "MIT"
1161 + },
1162 + "node_modules/@rollup/rollup-android-arm-eabi": {
1163 + "version": "4.69.3",
1164 + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.69.3.tgz",
1165 + "integrity": "sha512-WDG3WNktJVR+OTqdP/OrBg2b+JXXIgIZ+Ppzp7gjaRK9C59fn3vcFhUqjtxiscE9lygTYP3EFxY9xTLUfEFRaw==",
1166 + "cpu": [
1167 + "arm"
1168 + ],
1169 + "dev": true,
1170 + "license": "MIT",
1171 + "optional": true,
1172 + "os": [
1173 + "android"
1174 + ]
1175 + },
1176 + "node_modules/@rollup/rollup-android-arm64": {
1177 + "version": "4.69.3",
1178 + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.69.3.tgz",
1179 + "integrity": "sha512-D5NgwE943sMSNRGoWFg9r2jPUG7EWk0/BYNgG3C/lIHAqY1M+GTA7EvQtCAJxKUv6gtb4lBOvx/0+8GS6yOIdA==",
1180 + "cpu": [
1181 + "arm64"
1182 + ],
1183 + "dev": true,
1184 + "license": "MIT",
1185 + "optional": true,
1186 + "os": [
1187 + "android"
1188 + ]
1189 + },
1190 + "node_modules/@rollup/rollup-android-x64": {
1191 + "version": "4.69.3",
1192 + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.69.3.tgz",
1193 + "integrity": "sha512-qT8AKzfYdZfAsoI/UFggqr1ghJfhW9GgGgDHTrYDviKvgGzqcteSjfaK0AwwJtbnbLu+FrMGF7RlGXfrZ1uFuA==",
1194 + "cpu": [
1195 + "x64"
1196 + ],
1197 + "dev": true,
1198 + "license": "MIT",
1199 + "optional": true,
1200 + "os": [
1201 + "android"
1202 + ]
1203 + },
1204 + "node_modules/@rollup/rollup-darwin-arm64": {
1205 + "version": "4.69.3",
1206 + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.69.3.tgz",
1207 + "integrity": "sha512-UdQ9EDKcIyJEyQ7rKcxwfTVZt4SoM4o2NxTEWb6WFSK2SDEJKMEXjkEd6csGOfzKnr8xBUAtOLN7WnocRSjqdQ==",
1208 + "cpu": [
1209 + "arm64"
1210 + ],
1211 + "dev": true,
1212 + "license": "MIT",
1213 + "optional": true,
1214 + "os": [
1215 + "darwin"
1216 + ]
1217 + },
1218 + "node_modules/@rollup/rollup-darwin-x64": {
1219 + "version": "4.69.3",
1220 + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.69.3.tgz",
1221 + "integrity": "sha512-i1a4Erge+lLWo3sSlwX9LU/KK4CkaLZe7kvCc6Fc8NNKiW6mRcXcebRze9pPdGyfdA5SVcnl9pxekXK4O+Gbcw==",
1222 + "cpu": [
1223 + "x64"
1224 + ],
1225 + "dev": true,
1226 + "license": "MIT",
1227 + "optional": true,
1228 + "os": [
1229 + "darwin"
1230 + ]
1231 + },
1232 + "node_modules/@rollup/rollup-freebsd-arm64": {
1233 + "version": "4.69.3",
1234 + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.69.3.tgz",
1235 + "integrity": "sha512-w30OkToJS0ed5UEqXBu61gg8/adzmcnvOc7qoZi+92FsOYtVmLlQGHeVqBn9GGiruk2aiDJpd1fMHwZhOhj8rw==",
1236 + "cpu": [
1237 + "arm64"
1238 + ],
1239 + "dev": true,
1240 + "license": "MIT",
1241 + "optional": true,
1242 + "os": [
1243 + "freebsd"
1244 + ]
1245 + },
1246 + "node_modules/@rollup/rollup-freebsd-x64": {
1247 + "version": "4.69.3",
1248 + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.69.3.tgz",
1249 + "integrity": "sha512-Ze4Bo4axd2xzxG72ltgQtOcRuY1zyw47Z8bye5gDwgehBglMA0AQwGy2dL1MZ4ZutjdImwVc8jbL/geawm3wjA==",
1250 + "cpu": [
1251 + "x64"
1252 + ],
1253 + "dev": true,
1254 + "license": "MIT",
1255 + "optional": true,
1256 + "os": [
1257 + "freebsd"
1258 + ]
1259 + },
1260 + "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
1261 + "version": "4.69.3",
1262 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.69.3.tgz",
1263 + "integrity": "sha512-hzMaEmx1VYvlfesicuLSI58962aaPvwK+J8Ksi1Qqy6GfM/Nsq8IDKYzw/Mg3DI5JlCwnuEcPj9ymzsAtk+sPA==",
1264 + "cpu": [
1265 + "arm"
1266 + ],
1267 + "dev": true,
1268 + "license": "MIT",
1269 + "optional": true,
1270 + "os": [
1271 + "linux"
1272 + ]
1273 + },
1274 + "node_modules/@rollup/rollup-linux-arm-musleabihf": {
1275 + "version": "4.69.3",
1276 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.69.3.tgz",
1277 + "integrity": "sha512-EZRv+RnscDTuXinvItllk8VNO81mdYjWlupt1QexTPOuSt9UDkRHH6C2ArJBiNyaHqxA/dDAuK3vWAFKLmMgAA==",
1278 + "cpu": [
1279 + "arm"
1280 + ],
1281 + "dev": true,
1282 + "license": "MIT",
1283 + "optional": true,
1284 + "os": [
1285 + "linux"
1286 + ]
1287 + },
1288 + "node_modules/@rollup/rollup-linux-arm64-gnu": {
1289 + "version": "4.69.3",
1290 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.69.3.tgz",
1291 + "integrity": "sha512-8TNXGRkMqZ7QIL3KvpL0MXGE1ueqWnm1I40CQijo6G/CCKzoMUOsMdVmfgjPGl/G22+FtQMb3+6Moc6obmZ5vQ==",
1292 + "cpu": [
1293 + "arm64"
1294 + ],
1295 + "dev": true,
1296 + "license": "MIT",
1297 + "optional": true,
1298 + "os": [
1299 + "linux"
1300 + ]
1301 + },
1302 + "node_modules/@rollup/rollup-linux-arm64-musl": {
1303 + "version": "4.69.3",
1304 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.69.3.tgz",
1305 + "integrity": "sha512-VWRKTMZq9N9EWxDRYgLAxE4Ory+O9ZO7+m0RjWlTjhtEF9V9ts/fnfgEjDisF2wYmmJA40c98HuREBlIT29S+w==",
1306 + "cpu": [
1307 + "arm64"
1308 + ],
1309 + "dev": true,
1310 + "license": "MIT",
1311 + "optional": true,
1312 + "os": [
1313 + "linux"
1314 + ]
1315 + },
1316 + "node_modules/@rollup/rollup-linux-loong64-gnu": {
1317 + "version": "4.69.3",
1318 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.69.3.tgz",
1319 + "integrity": "sha512-UNm9BN6OuckVOAYvsDT0JHGQF3Lt7gjcrZL5JzmR8JvzfMb4SGjUcWtBL+fkUjdwT81vsBvUyZMZCman6dwNxw==",
1320 + "cpu": [
1321 + "loong64"
1322 + ],
1323 + "dev": true,
1324 + "license": "MIT",
1325 + "optional": true,
1326 + "os": [
1327 + "linux"
1328 + ]
1329 + },
1330 + "node_modules/@rollup/rollup-linux-loong64-musl": {
1331 + "version": "4.69.3",
1332 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.69.3.tgz",
1333 + "integrity": "sha512-8w6fC76ChAodM1ZAEdpNlIkV7jq+HDHpa1xawVfOdwFsgWVWQkKcYa36bFlo58PWxfinMEuMWnyyWl4Ro3mjZA==",
1334 + "cpu": [
1335 + "loong64"
1336 + ],
1337 + "dev": true,
1338 + "license": "MIT",
1339 + "optional": true,
1340 + "os": [
1341 + "linux"
1342 + ]
1343 + },
1344 + "node_modules/@rollup/rollup-linux-ppc64-gnu": {
1345 + "version": "4.69.3",
1346 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.69.3.tgz",
1347 + "integrity": "sha512-5J/hPeDhQ8hZLRpmaNpzI5G4fT0qQQC47uj1dwCdJwd8/yk8v0aiZJ0V+Sw4HGiScgMBANKVZyrzedHqRCilIQ==",
1348 + "cpu": [
1349 + "ppc64"
1350 + ],
1351 + "dev": true,
1352 + "license": "MIT",
1353 + "optional": true,
1354 + "os": [
1355 + "linux"
1356 + ]
1357 + },
1358 + "node_modules/@rollup/rollup-linux-ppc64-musl": {
1359 + "version": "4.69.3",
1360 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.69.3.tgz",
1361 + "integrity": "sha512-MBOWof2RZbbM2gTUagZsEwmIUAesxvB2zxnX3Af4M69NVdqDvGEXGkV8zYfXjLoJjiU7J1mzDHABmXhz5jMlZQ==",
1362 + "cpu": [
1363 + "ppc64"
1364 + ],
1365 + "dev": true,
1366 + "license": "MIT",
1367 + "optional": true,
1368 + "os": [
1369 + "linux"
1370 + ]
1371 + },
1372 + "node_modules/@rollup/rollup-linux-riscv64-gnu": {
1373 + "version": "4.69.3",
1374 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.69.3.tgz",
1375 + "integrity": "sha512-pzpggub9hyhZ89uAcXORCg6loWFoQOoTFatNpcJuiCqRdQvQa1oK37eG+vnVdFbULAzIuRlMZu23l3433OZi1g==",
1376 + "cpu": [
1377 + "riscv64"
1378 + ],
1379 + "dev": true,
1380 + "license": "MIT",
1381 + "optional": true,
1382 + "os": [
1383 + "linux"
1384 + ]
1385 + },
1386 + "node_modules/@rollup/rollup-linux-riscv64-musl": {
1387 + "version": "4.69.3",
1388 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.69.3.tgz",
1389 + "integrity": "sha512-kUlaRxOwQKcdLSo2CrHpTVFZaKrrEONZz6yDmX2UUgzSsIUvNPGlgGEQ6mxBwCYWzIrXWtu0nILkYIc+5dZWDA==",
1390 + "cpu": [
1391 + "riscv64"
1392 + ],
1393 + "dev": true,
1394 + "license": "MIT",
1395 + "optional": true,
1396 + "os": [
1397 + "linux"
1398 + ]
1399 + },
1400 + "node_modules/@rollup/rollup-linux-s390x-gnu": {
1401 + "version": "4.69.3",
1402 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.69.3.tgz",
1403 + "integrity": "sha512-N/xL1PKN8D+CIX6/Mdnkr/T5FuZVzov5JbzQiGGaMlsVdPBi9If0qN8E91p3ex/JT9nCYKe9WNrKeml7xi87lg==",
1404 + "cpu": [
1405 + "s390x"
1406 + ],
1407 + "dev": true,
1408 + "license": "MIT",
1409 + "optional": true,
1410 + "os": [
1411 + "linux"
1412 + ]
1413 + },
1414 + "node_modules/@rollup/rollup-linux-x64-gnu": {
1415 + "version": "4.69.3",
1416 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.69.3.tgz",
1417 + "integrity": "sha512-uBpTadP1uQZZvVe+AV4dsTwNfs1H92Ra231OcHW2PVOYdW83PS899Wr3bXGbJO5erxWVfiZ70oPnhCPJ5utL3A==",
1418 + "cpu": [
1419 + "x64"
1420 + ],
1421 + "dev": true,
1422 + "license": "MIT",
1423 + "optional": true,
1424 + "os": [
1425 + "linux"
1426 + ]
1427 + },
1428 + "node_modules/@rollup/rollup-linux-x64-musl": {
1429 + "version": "4.69.3",
1430 + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.69.3.tgz",
1431 + "integrity": "sha512-4MWQvR0w9Ao4REGwJoFZxKKtU//Bd6vl0wIexJaG0EhxbrzMdIKotNkih+qJxlZjdJHf6/W3ETZ0CrEXeNTTcQ==",
1432 + "cpu": [
1433 + "x64"
1434 + ],
1435 + "dev": true,
1436 + "license": "MIT",
1437 + "optional": true,
1438 + "os": [
1439 + "linux"
1440 + ]
1441 + },
1442 + "node_modules/@rollup/rollup-openbsd-x64": {
1443 + "version": "4.69.3",
1444 + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.69.3.tgz",
1445 + "integrity": "sha512-GC5b98fZgnb4MD0GSO/7XFVK7z2m/geaVS4CATdb7QA1VetuXhQJxTdlJblk4uriCmS9oexARH2fVbWR+FQOLA==",
1446 + "cpu": [
1447 + "x64"
1448 + ],
1449 + "dev": true,
1450 + "license": "MIT",
1451 + "optional": true,
1452 + "os": [
1453 + "openbsd"
1454 + ]
1455 + },
1456 + "node_modules/@rollup/rollup-openharmony-arm64": {
1457 + "version": "4.69.3",
1458 + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.69.3.tgz",
1459 + "integrity": "sha512-jrsZxYM1Zyr0QXuHVHoRGC6tvqakkr96Vvy2eM8HYqxtmlWpjITW7pCEzDkg/X/IjLuUdyGJ693E4WJ5NcUXxQ==",
1460 + "cpu": [
1461 + "arm64"
1462 + ],
1463 + "dev": true,
1464 + "license": "MIT",
1465 + "optional": true,
1466 + "os": [
1467 + "openharmony"
1468 + ]
1469 + },
1470 + "node_modules/@rollup/rollup-win32-arm64-msvc": {
1471 + "version": "4.69.3",
1472 + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.69.3.tgz",
1473 + "integrity": "sha512-SnAwiYVNy5lfxVL7BQhtg3UbrAvAhSSonI342A5JbrznG6t8VvvkCDyLRXypQsRBvxIBVDrelpgR9yDIAlwS4w==",
1474 + "cpu": [
1475 + "arm64"
1476 + ],
1477 + "dev": true,
1478 + "license": "MIT",
1479 + "optional": true,
1480 + "os": [
1481 + "win32"
1482 + ]
1483 + },
1484 + "node_modules/@rollup/rollup-win32-ia32-msvc": {
1485 + "version": "4.69.3",
1486 + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.69.3.tgz",
1487 + "integrity": "sha512-85tt4vmTGSq04BsY0FKnYif4JHD2aR+MeoC1cUbdZkTvjOIYO3iHmPTpOf2nOympL6yZngvJjLmeoBzUsGUJmA==",
1488 + "cpu": [
1489 + "ia32"
1490 + ],
1491 + "dev": true,
1492 + "license": "MIT",
1493 + "optional": true,
1494 + "os": [
1495 + "win32"
1496 + ]
1497 + },
1498 + "node_modules/@rollup/rollup-win32-x64-gnu": {
1499 + "version": "4.69.3",
1500 + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.69.3.tgz",
1501 + "integrity": "sha512-IpRuzCYcIfSNxcqHertICkJ7JSHM74TeN5lGleOE1jGK9dPphyIB2EfFud/8oZRrt3CVd3z10UIRzLJQflnVcg==",
1502 + "cpu": [
1503 + "x64"
1504 + ],
1505 + "dev": true,
1506 + "license": "MIT",
1507 + "optional": true,
1508 + "os": [
1509 + "win32"
1510 + ]
1511 + },
1512 + "node_modules/@rollup/rollup-win32-x64-msvc": {
1513 + "version": "4.69.3",
1514 + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.69.3.tgz",
1515 + "integrity": "sha512-dyv+ETPjCDTn03T5ZAnk+OvB+4+yg1onKgTb7jjv9LQ8KEwcvUkZmIPtNTdreULsKX0Amaod6C2W1iSFseTiwQ==",
1516 + "cpu": [
1517 + "x64"
1518 + ],
1519 + "dev": true,
1520 + "license": "MIT",
1521 + "optional": true,
1522 + "os": [
1523 + "win32"
1524 + ]
1525 + },
1526 + "node_modules/@testing-library/dom": {
1527 + "version": "10.4.2",
1528 + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz",
1529 + "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==",
1530 + "dev": true,
1531 + "license": "MIT",
1532 + "peer": true,
1533 + "dependencies": {
1534 + "@babel/code-frame": "^7.10.4",
1535 + "@babel/runtime": "^7.12.5",
1536 + "@types/aria-query": "^5.0.1",
1537 + "aria-query": "5.3.0",
1538 + "dom-accessibility-api": "^0.5.9",
1539 + "lz-string": "^1.5.0",
1540 + "picocolors": "1.1.1",
1541 + "pretty-format": "^27.0.2"
1542 + },
1543 + "engines": {
1544 + "node": ">=18"
1545 + }
1546 + },
1547 + "node_modules/@testing-library/jest-dom": {
1548 + "version": "6.9.1",
1549 + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz",
1550 + "integrity": "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==",
1551 + "dev": true,
1552 + "license": "MIT",
1553 + "dependencies": {
1554 + "@adobe/css-tools": "^4.4.0",
1555 + "aria-query": "^5.0.0",
1556 + "css.escape": "^1.5.1",
1557 + "dom-accessibility-api": "^0.6.3",
1558 + "picocolors": "^1.1.1",
1559 + "redent": "^3.0.0"
1560 + },
1561 + "engines": {
1562 + "node": ">=14",
1563 + "npm": ">=6",
1564 + "yarn": ">=1"
1565 + }
1566 + },
1567 + "node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": {
1568 + "version": "0.6.3",
1569 + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz",
1570 + "integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==",
1571 + "dev": true,
1572 + "license": "MIT"
1573 + },
1574 + "node_modules/@testing-library/react": {
1575 + "version": "16.3.3",
1576 + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.3.tgz",
1577 + "integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==",
1578 + "dev": true,
1579 + "license": "MIT",
1580 + "dependencies": {
1581 + "@babel/runtime": "^7.12.5"
1582 + },
1583 + "engines": {
1584 + "node": ">=18"
1585 + },
1586 + "peerDependencies": {
1587 + "@testing-library/dom": "^10.0.0",
1588 + "@types/react": "^18.0.0 || ^19.0.0",
1589 + "@types/react-dom": "^18.0.0 || ^19.0.0",
1590 + "react": "^18.0.0 || ^19.0.0",
1591 + "react-dom": "^18.0.0 || ^19.0.0"
1592 + },
1593 + "peerDependenciesMeta": {
1594 + "@types/react": {
1595 + "optional": true
1596 + },
1597 + "@types/react-dom": {
1598 + "optional": true
1599 + }
1600 + }
1601 + },
1602 + "node_modules/@types/aria-query": {
1603 + "version": "5.0.4",
1604 + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
1605 + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
1606 + "dev": true,
1607 + "license": "MIT",
1608 + "peer": true
1609 + },
1610 + "node_modules/@types/babel__core": {
1611 + "version": "7.20.5",
1612 + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
1613 + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",
1614 + "dev": true,
1615 + "license": "MIT",
1616 + "dependencies": {
1617 + "@babel/parser": "^7.20.7",
1618 + "@babel/types": "^7.20.7",
1619 + "@types/babel__generator": "*",
1620 + "@types/babel__template": "*",
1621 + "@types/babel__traverse": "*"
1622 + }
1623 + },
1624 + "node_modules/@types/babel__generator": {
1625 + "version": "7.27.0",
1626 + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz",
1627 + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",
1628 + "dev": true,
1629 + "license": "MIT",
1630 + "dependencies": {
1631 + "@babel/types": "^7.0.0"
1632 + }
1633 + },
1634 + "node_modules/@types/babel__template": {
1635 + "version": "7.4.4",
1636 + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",
1637 + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",
1638 + "dev": true,
1639 + "license": "MIT",
1640 + "dependencies": {
1641 + "@babel/parser": "^7.1.0",
1642 + "@babel/types": "^7.0.0"
1643 + }
1644 + },
1645 + "node_modules/@types/babel__traverse": {
1646 + "version": "7.28.0",
1647 + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",
1648 + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",
1649 + "dev": true,
1650 + "license": "MIT",
1651 + "dependencies": {
1652 + "@babel/types": "^7.28.2"
1653 + }
1654 + },
1655 + "node_modules/@types/estree": {
1656 + "version": "1.0.11",
1657 + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.11.tgz",
1658 + "integrity": "sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg==",
1659 + "dev": true,
1660 + "license": "MIT"
1661 + },
1662 + "node_modules/@types/json-schema": {
1663 + "version": "7.0.15",
1664 + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
1665 + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
1666 + "dev": true,
1667 + "license": "MIT"
1668 + },
1669 + "node_modules/@types/node": {
1670 + "version": "22.20.7",
1671 + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.7.tgz",
1672 + "integrity": "sha512-F/Mcc4pD3YwXQCG50hb8BjB5RmrOere6hge7n2XHf0V8tpkZOVEjwYv9Ql7n0MpMn8Bv7+q12P9w6UHsBm0Sfw==",
1673 + "dev": true,
1674 + "license": "MIT",
1675 + "dependencies": {
1676 + "undici-types": "~6.21.0"
1677 + }
1678 + },
1679 + "node_modules/@types/prop-types": {
1680 + "version": "15.7.15",
1681 + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
1682 + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
1683 + "dev": true,
1684 + "license": "MIT"
1685 + },
1686 + "node_modules/@types/react": {
1687 + "version": "18.3.32",
1688 + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.32.tgz",
1689 + "integrity": "sha512-hKTeN+STHjfr2eS1uLImPsGpmIQD5SD8DUTQ+14zSne5CTwRpYh25ggOKG/pFIs2r0JmNYrSv4ZqIL07ipSvOA==",
1690 + "dev": true,
1691 + "license": "MIT",
1692 + "dependencies": {
1693 + "@types/prop-types": "*",
1694 + "csstype": "^3.2.2"
1695 + }
1696 + },
1697 + "node_modules/@types/react-dom": {
1698 + "version": "18.3.7",
1699 + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
1700 + "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
1701 + "dev": true,
1702 + "license": "MIT",
1703 + "peerDependencies": {
1704 + "@types/react": "^18.0.0"
1705 + }
1706 + },
1707 + "node_modules/@typescript-eslint/eslint-plugin": {
1708 + "version": "8.74.0",
1709 + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.74.0.tgz",
1710 + "integrity": "sha512-z3KXk1+Vm+d82ZRplOoC89ho4Rf1da5ju6sx8//92GnN532U62DGPjECXkkVqtYzIv0zoJlpO39SX2Z9tk6LVw==",
1711 + "dev": true,
1712 + "license": "MIT",
1713 + "dependencies": {
1714 + "@eslint-community/regexpp": "^4.12.2",
1715 + "@typescript-eslint/scope-manager": "8.74.0",
1716 + "@typescript-eslint/type-utils": "8.74.0",
1717 + "@typescript-eslint/utils": "8.74.0",
1718 + "@typescript-eslint/visitor-keys": "8.74.0",
1719 + "ignore": "^7.0.5",
1720 + "natural-compare": "^1.4.0",
1721 + "ts-api-utils": "^2.5.0"
1722 + },
1723 + "engines": {
1724 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1725 + },
1726 + "funding": {
1727 + "type": "opencollective",
1728 + "url": "https://opencollective.com/typescript-eslint"
1729 + },
1730 + "peerDependencies": {
1731 + "@typescript-eslint/parser": "^8.74.0",
1732 + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
1733 + "typescript": ">=4.8.4 <6.1.0"
1734 + }
1735 + },
1736 + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
1737 + "version": "7.0.17",
1738 + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.17.tgz",
1739 + "integrity": "sha512-0c3zcBRlWmcKhcIQWckzkYncJRv5HHB8O32wO/FcWL8DDXWDJgiEF6SX9ThbTv5h/eZ+xJK+VvDjjQ+cQJhp3Q==",
1740 + "dev": true,
1741 + "license": "MIT",
1742 + "engines": {
1743 + "node": ">= 4"
1744 + }
1745 + },
1746 + "node_modules/@typescript-eslint/parser": {
1747 + "version": "8.74.0",
1748 + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.74.0.tgz",
1749 + "integrity": "sha512-ecr8AYdig7avVkxaHdQvxHnIJ/mOyliO4Gv/uWF8q69vBew/z3sexqBwHUZX5Vql+Ns0w4sH6gBLkICGbOvJkA==",
1750 + "dev": true,
1751 + "license": "MIT",
1752 + "dependencies": {
1753 + "@typescript-eslint/scope-manager": "8.74.0",
1754 + "@typescript-eslint/types": "8.74.0",
1755 + "@typescript-eslint/typescript-estree": "8.74.0",
1756 + "@typescript-eslint/visitor-keys": "8.74.0",
1757 + "debug": "^4.4.3"
1758 + },
1759 + "engines": {
1760 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1761 + },
1762 + "funding": {
1763 + "type": "opencollective",
1764 + "url": "https://opencollective.com/typescript-eslint"
1765 + },
1766 + "peerDependencies": {
1767 + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
1768 + "typescript": ">=4.8.4 <6.1.0"
1769 + }
1770 + },
1771 + "node_modules/@typescript-eslint/project-service": {
1772 + "version": "8.74.0",
1773 + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.74.0.tgz",
1774 + "integrity": "sha512-z/mymuE+JlEeSFIv3Mo70EvgG1Zz74Hl0IDfExfXutARAP834bt+MppTD7mVAwmZO0GdxdOAi0jbTam749eH6g==",
1775 + "dev": true,
1776 + "license": "MIT",
1777 + "dependencies": {
1778 + "@typescript-eslint/tsconfig-utils": "^8.74.0",
1779 + "@typescript-eslint/types": "^8.74.0",
1780 + "debug": "^4.4.3"
1781 + },
1782 + "engines": {
1783 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1784 + },
1785 + "funding": {
1786 + "type": "opencollective",
1787 + "url": "https://opencollective.com/typescript-eslint"
1788 + },
1789 + "peerDependencies": {
1790 + "typescript": ">=4.8.4 <6.1.0"
1791 + }
1792 + },
1793 + "node_modules/@typescript-eslint/scope-manager": {
1794 + "version": "8.74.0",
1795 + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.74.0.tgz",
1796 + "integrity": "sha512-kpOdpu4CpWN5U38ox3f727DwWRBtUAVhyUJtqTBYe5gf2wYoxac7PgKP14txrxN7ICVtcjlLdzjqfRgpSnDKvQ==",
1797 + "dev": true,
1798 + "license": "MIT",
1799 + "dependencies": {
1800 + "@typescript-eslint/types": "8.74.0",
1801 + "@typescript-eslint/visitor-keys": "8.74.0"
1802 + },
1803 + "engines": {
1804 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1805 + },
1806 + "funding": {
1807 + "type": "opencollective",
1808 + "url": "https://opencollective.com/typescript-eslint"
1809 + }
1810 + },
1811 + "node_modules/@typescript-eslint/tsconfig-utils": {
1812 + "version": "8.74.0",
1813 + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.74.0.tgz",
1814 + "integrity": "sha512-p07wAuaS6BjCYgOSXKJi4YhvTnAf7fiG37e9THcpnYaQEt2QiTTYZWKwUFNgeRiywiMudazhzgddAirZ0GgHtQ==",
1815 + "dev": true,
1816 + "license": "MIT",
1817 + "engines": {
1818 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1819 + },
1820 + "funding": {
1821 + "type": "opencollective",
1822 + "url": "https://opencollective.com/typescript-eslint"
1823 + },
1824 + "peerDependencies": {
1825 + "typescript": ">=4.8.4 <6.1.0"
1826 + }
1827 + },
1828 + "node_modules/@typescript-eslint/type-utils": {
1829 + "version": "8.74.0",
1830 + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.74.0.tgz",
1831 + "integrity": "sha512-CV3Y3la8l3F9ANfxcfpgSSiQgJTe4IeLEoZV4O/gcW86Ugp8X6SKiQ0vm+QegXaRIbbDMokZZSF3A1CgiU/kPw==",
1832 + "dev": true,
1833 + "license": "MIT",
1834 + "dependencies": {
1835 + "@typescript-eslint/types": "8.74.0",
1836 + "@typescript-eslint/typescript-estree": "8.74.0",
1837 + "@typescript-eslint/utils": "8.74.0",
1838 + "debug": "^4.4.3",
1839 + "ts-api-utils": "^2.5.0"
1840 + },
1841 + "engines": {
1842 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1843 + },
1844 + "funding": {
1845 + "type": "opencollective",
1846 + "url": "https://opencollective.com/typescript-eslint"
1847 + },
1848 + "peerDependencies": {
1849 + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
1850 + "typescript": ">=4.8.4 <6.1.0"
1851 + }
1852 + },
1853 + "node_modules/@typescript-eslint/types": {
1854 + "version": "8.74.0",
1855 + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.74.0.tgz",
1856 + "integrity": "sha512-MpnMrJCVNpP1iVL8NiHkQZgQqIMBH5ewDGUPBh1pqQXwFtMFjsl1M03QcYPXmv6stCKEiF0PN7CGbU1ZbXFzEA==",
1857 + "dev": true,
1858 + "license": "MIT",
1859 + "engines": {
1860 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1861 + },
1862 + "funding": {
1863 + "type": "opencollective",
1864 + "url": "https://opencollective.com/typescript-eslint"
1865 + }
1866 + },
1867 + "node_modules/@typescript-eslint/typescript-estree": {
1868 + "version": "8.74.0",
1869 + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.74.0.tgz",
1870 + "integrity": "sha512-wL348k6l92DNG+kPP5rVpKwNBoz7a3xRZy3TPKc1uymQttd7u7gcMv3eENmcuh4CjC4mO3FTM0DYstFXMyDLuw==",
1871 + "dev": true,
1872 + "license": "MIT",
1873 + "dependencies": {
1874 + "@typescript-eslint/project-service": "8.74.0",
1875 + "@typescript-eslint/tsconfig-utils": "8.74.0",
1876 + "@typescript-eslint/types": "8.74.0",
1877 + "@typescript-eslint/visitor-keys": "8.74.0",
1878 + "debug": "^4.4.3",
1879 + "minimatch": "^11.0.1",
1880 + "semver": "^7.7.3",
1881 + "tinyglobby": "^0.2.15",
1882 + "ts-api-utils": "^2.5.0"
1883 + },
1884 + "engines": {
1885 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1886 + },
1887 + "funding": {
1888 + "type": "opencollective",
1889 + "url": "https://opencollective.com/typescript-eslint"
1890 + },
1891 + "peerDependencies": {
1892 + "@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev",
1893 + "typescript": ">=4.8.4 <6.1.0"
1894 + },
1895 + "peerDependenciesMeta": {
1896 + "@typescript/native": {
1897 + "optional": true
1898 + }
1899 + }
1900 + },
1901 + "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": {
1902 + "version": "4.0.4",
1903 + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
1904 + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
1905 + "dev": true,
1906 + "license": "MIT",
1907 + "engines": {
1908 + "node": "18 || 20 || >=22"
1909 + }
1910 + },
1911 + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
1912 + "version": "5.1.2",
1913 + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.1.2.tgz",
1914 + "integrity": "sha512-ELhY3JEerIBbhgW+rh0/8glkZAaMqn1x3BAvp3yTULSEGozMK/5PT6WTdBgsdvJqwwmv7MAQNOydfYbvK1Vgfw==",
1915 + "dev": true,
1916 + "license": "MIT",
1917 + "dependencies": {
1918 + "balanced-match": "^4.0.2"
1919 + },
1920 + "engines": {
1921 + "node": "20 || >=22"
1922 + }
1923 + },
1924 + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
1925 + "version": "11.0.10",
1926 + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.10.tgz",
1927 + "integrity": "sha512-L3/cjhQ5E6lft0VCp/2mO3Ic74RnutKy3rz7iGwp/6w1hKcO262g2rbfacFyw6eBig5OdI0nu5PpuA0/WQs9Tw==",
1928 + "dev": true,
1929 + "license": "BlueOak-1.0.0",
1930 + "dependencies": {
1931 + "@isaacs/nonrecursive-glob-match": "^1.1.0",
1932 + "brace-expansion": "^5.0.12"
1933 + },
1934 + "engines": {
1935 + "node": "20 || >=22"
1936 + },
1937 + "funding": {
1938 + "url": "https://github.com/sponsors/isaacs"
1939 + }
1940 + },
1941 + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": {
1942 + "version": "7.8.6",
1943 + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
1944 + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
1945 + "dev": true,
1946 + "license": "ISC",
1947 + "bin": {
1948 + "semver": "bin/semver.js"
1949 + },
1950 + "engines": {
1951 + "node": ">=10"
1952 + }
1953 + },
1954 + "node_modules/@typescript-eslint/utils": {
1955 + "version": "8.74.0",
1956 + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.74.0.tgz",
1957 + "integrity": "sha512-IpWXPxXXomzxyTcvjhZJexgdvtTR1TooLAPpuxzaGqQ8BHll1lf4Ysp/BTE/l0U5TJ+x1j7B4bEM8pLRrvY+XA==",
1958 + "dev": true,
1959 + "license": "MIT",
1960 + "dependencies": {
1961 + "@eslint-community/eslint-utils": "^4.9.1",
1962 + "@typescript-eslint/scope-manager": "8.74.0",
1963 + "@typescript-eslint/types": "8.74.0",
1964 + "@typescript-eslint/typescript-estree": "8.74.0"
1965 + },
1966 + "engines": {
1967 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1968 + },
1969 + "funding": {
1970 + "type": "opencollective",
1971 + "url": "https://opencollective.com/typescript-eslint"
1972 + },
1973 + "peerDependencies": {
1974 + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
1975 + "typescript": ">=4.8.4 <6.1.0"
1976 + }
1977 + },
1978 + "node_modules/@typescript-eslint/visitor-keys": {
1979 + "version": "8.74.0",
1980 + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.74.0.tgz",
1981 + "integrity": "sha512-XSZmOtMUbWCBIM+2BK134FyMFxmll1mW2mPLk/PSwYQYzGIPMgJAqL929U4qXVizLv7Xq5b7r41/o7Ombuwk0g==",
1982 + "dev": true,
1983 + "license": "MIT",
1984 + "dependencies": {
1985 + "@typescript-eslint/types": "8.74.0",
1986 + "eslint-visitor-keys": "^5.0.0"
1987 + },
1988 + "engines": {
1989 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
1990 + },
1991 + "funding": {
1992 + "type": "opencollective",
1993 + "url": "https://opencollective.com/typescript-eslint"
1994 + }
1995 + },
1996 + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": {
1997 + "version": "5.0.1",
1998 + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz",
1999 + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==",
2000 + "dev": true,
2001 + "license": "Apache-2.0",
2002 + "engines": {
2003 + "node": "^20.19.0 || ^22.13.0 || >=24"
2004 + },
2005 + "funding": {
2006 + "url": "https://opencollective.com/eslint"
2007 + }
2008 + },
2009 + "node_modules/@vitejs/plugin-react": {
2010 + "version": "4.7.0",
2011 + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",
2012 + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==",
2013 + "dev": true,
2014 + "license": "MIT",
2015 + "dependencies": {
2016 + "@babel/core": "^7.28.0",
2017 + "@babel/plugin-transform-react-jsx-self": "^7.27.1",
2018 + "@babel/plugin-transform-react-jsx-source": "^7.27.1",
2019 + "@rolldown/pluginutils": "1.0.0-beta.27",
2020 + "@types/babel__core": "^7.20.5",
2021 + "react-refresh": "^0.17.0"
2022 + },
2023 + "engines": {
2024 + "node": "^14.18.0 || >=16.0.0"
2025 + },
2026 + "peerDependencies": {
2027 + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
2028 + }
2029 + },
2030 + "node_modules/@vitest/expect": {
2031 + "version": "2.1.9",
2032 + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
2033 + "integrity": "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==",
2034 + "dev": true,
2035 + "license": "MIT",
2036 + "dependencies": {
2037 + "@vitest/spy": "2.1.9",
2038 + "@vitest/utils": "2.1.9",
2039 + "chai": "^5.1.2",
2040 + "tinyrainbow": "^1.2.0"
2041 + },
2042 + "funding": {
2043 + "url": "https://opencollective.com/vitest"
2044 + }
2045 + },
2046 + "node_modules/@vitest/mocker": {
2047 + "version": "2.1.9",
2048 + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-2.1.9.tgz",
2049 + "integrity": "sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==",
2050 + "dev": true,
2051 + "license": "MIT",
2052 + "dependencies": {
2053 + "@vitest/spy": "2.1.9",
2054 + "estree-walker": "^3.0.3",
2055 + "magic-string": "^0.30.12"
2056 + },
2057 + "funding": {
2058 + "url": "https://opencollective.com/vitest"
2059 + },
2060 + "peerDependencies": {
2061 + "msw": "^2.4.9",
2062 + "vite": "^5.0.0"
2063 + },
2064 + "peerDependenciesMeta": {
2065 + "msw": {
2066 + "optional": true
2067 + },
2068 + "vite": {
2069 + "optional": true
2070 + }
2071 + }
2072 + },
2073 + "node_modules/@vitest/pretty-format": {
2074 + "version": "2.1.9",
2075 + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
2076 + "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
2077 + "dev": true,
2078 + "license": "MIT",
2079 + "dependencies": {
2080 + "tinyrainbow": "^1.2.0"
2081 + },
2082 + "funding": {
2083 + "url": "https://opencollective.com/vitest"
2084 + }
2085 + },
2086 + "node_modules/@vitest/runner": {
2087 + "version": "2.1.9",
2088 + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-2.1.9.tgz",
2089 + "integrity": "sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==",
2090 + "dev": true,
2091 + "license": "MIT",
2092 + "dependencies": {
2093 + "@vitest/utils": "2.1.9",
2094 + "pathe": "^1.1.2"
2095 + },
2096 + "funding": {
2097 + "url": "https://opencollective.com/vitest"
2098 + }
2099 + },
2100 + "node_modules/@vitest/snapshot": {
2101 + "version": "2.1.9",
2102 + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz",
2103 + "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",
2104 + "dev": true,
2105 + "license": "MIT",
2106 + "dependencies": {
2107 + "@vitest/pretty-format": "2.1.9",
2108 + "magic-string": "^0.30.12",
2109 + "pathe": "^1.1.2"
2110 + },
2111 + "funding": {
2112 + "url": "https://opencollective.com/vitest"
2113 + }
2114 + },
2115 + "node_modules/@vitest/spy": {
2116 + "version": "2.1.9",
2117 + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.9.tgz",
2118 + "integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==",
2119 + "dev": true,
2120 + "license": "MIT",
2121 + "dependencies": {
2122 + "tinyspy": "^3.0.2"
2123 + },
2124 + "funding": {
2125 + "url": "https://opencollective.com/vitest"
2126 + }
2127 + },
2128 + "node_modules/@vitest/utils": {
2129 + "version": "2.1.9",
2130 + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.9.tgz",
2131 + "integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==",
2132 + "dev": true,
2133 + "license": "MIT",
2134 + "dependencies": {
2135 + "@vitest/pretty-format": "2.1.9",
2136 + "loupe": "^3.1.2",
2137 + "tinyrainbow": "^1.2.0"
2138 + },
2139 + "funding": {
2140 + "url": "https://opencollective.com/vitest"
2141 + }
2142 + },
2143 + "node_modules/acorn": {
2144 + "version": "8.19.0",
2145 + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz",
2146 + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==",
2147 + "dev": true,
2148 + "license": "MIT",
2149 + "bin": {
2150 + "acorn": "bin/acorn"
2151 + },
2152 + "engines": {
2153 + "node": ">=0.4.0"
2154 + }
2155 + },
2156 + "node_modules/acorn-jsx": {
2157 + "version": "5.3.2",
2158 + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
2159 + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
2160 + "dev": true,
2161 + "license": "MIT",
2162 + "peerDependencies": {
2163 + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
2164 + }
2165 + },
2166 + "node_modules/agent-base": {
2167 + "version": "7.1.4",
2168 + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
2169 + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
2170 + "dev": true,
2171 + "license": "MIT",
2172 + "engines": {
2173 + "node": ">= 14"
2174 + }
2175 + },
2176 + "node_modules/ajv": {
2177 + "version": "6.15.0",
2178 + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
2179 + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==",
2180 + "dev": true,
2181 + "license": "MIT",
2182 + "dependencies": {
2183 + "fast-deep-equal": "^3.1.1",
2184 + "fast-json-stable-stringify": "^2.0.0",
2185 + "json-schema-traverse": "^0.4.1",
2186 + "uri-js": "^4.2.2"
2187 + },
2188 + "funding": {
2189 + "type": "github",
2190 + "url": "https://github.com/sponsors/epoberezkin"
2191 + }
2192 + },
2193 + "node_modules/ansi-regex": {
2194 + "version": "5.0.1",
2195 + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
2196 + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
2197 + "dev": true,
2198 + "license": "MIT",
2199 + "peer": true,
2200 + "engines": {
2201 + "node": ">=8"
2202 + }
2203 + },
2204 + "node_modules/ansi-styles": {
2205 + "version": "4.3.0",
2206 + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
2207 + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
2208 + "dev": true,
2209 + "license": "MIT",
2210 + "dependencies": {
2211 + "color-convert": "^2.0.1"
2212 + },
2213 + "engines": {
2214 + "node": ">=8"
2215 + },
2216 + "funding": {
2217 + "url": "https://github.com/chalk/ansi-styles?sponsor=1"
2218 + }
2219 + },
2220 + "node_modules/argparse": {
2221 + "version": "2.0.1",
2222 + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
2223 + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
2224 + "dev": true,
2225 + "license": "Python-2.0"
2226 + },
2227 + "node_modules/aria-query": {
2228 + "version": "5.3.0",
2229 + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz",
2230 + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==",
2231 + "dev": true,
2232 + "license": "Apache-2.0",
2233 + "dependencies": {
2234 + "dequal": "^2.0.3"
2235 + }
2236 + },
2237 + "node_modules/assertion-error": {
2238 + "version": "2.0.1",
2239 + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
2240 + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
2241 + "dev": true,
2242 + "license": "MIT",
2243 + "engines": {
2244 + "node": ">=12"
2245 + }
2246 + },
2247 + "node_modules/asynckit": {
2248 + "version": "0.4.0",
2249 + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
2250 + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
2251 + "dev": true,
2252 + "license": "MIT"
2253 + },
2254 + "node_modules/balanced-match": {
2255 + "version": "1.0.2",
2256 + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
2257 + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
2258 + "dev": true,
2259 + "license": "MIT"
2260 + },
2261 + "node_modules/baseline-browser-mapping": {
2262 + "version": "2.11.41",
2263 + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.41.tgz",
2264 + "integrity": "sha512-yjL/sZCpbpL0ocwmrUe1YFUelyMcifcByF4UYCBDyubFXQRs3lUjo9VoPKdjoFFhmzLAAGNJb1GBBCQJ6B4eyg==",
2265 + "dev": true,
2266 + "license": "Apache-2.0",
2267 + "bin": {
2268 + "baseline-browser-mapping": "dist/cli.cjs"
2269 + },
2270 + "engines": {
2271 + "node": ">=6.0.0"
2272 + }
2273 + },
2274 + "node_modules/brace-expansion": {
2275 + "version": "1.1.22",
2276 + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.22.tgz",
2277 + "integrity": "sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==",
2278 + "dev": true,
2279 + "license": "MIT",
2280 + "dependencies": {
2281 + "balanced-match": "^1.0.0",
2282 + "concat-map": "0.0.1"
2283 + }
2284 + },
2285 + "node_modules/browserslist": {
2286 + "version": "4.29.6",
2287 + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz",
2288 + "integrity": "sha512-CmVVIQ3RVc5HxYEc9X84GvxK/C8C1wH8TlKAiO7uTxF8PDwt7r8t9Qk3J9NkMOVzX5O/HbLv3yzxZg9HPrnI9w==",
2289 + "dev": true,
2290 + "funding": [
2291 + {
2292 + "type": "opencollective",
2293 + "url": "https://opencollective.com/browserslist"
2294 + },
2295 + {
2296 + "type": "tidelift",
2297 + "url": "https://tidelift.com/funding/github/npm/browserslist"
2298 + },
2299 + {
2300 + "type": "github",
2301 + "url": "https://github.com/sponsors/ai"
2302 + }
2303 + ],
2304 + "license": "MIT",
2305 + "dependencies": {
2306 + "baseline-browser-mapping": "^2.11.37",
2307 + "caniuse-lite": "^1.0.30001826",
2308 + "electron-to-chromium": "^1.5.486",
2309 + "node-releases": "^2.0.64",
2310 + "update-browserslist-db": "^1.4.0"
2311 + },
2312 + "bin": {
2313 + "browserslist": "cli.js"
2314 + },
2315 + "engines": {
2316 + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
2317 + }
2318 + },
2319 + "node_modules/cac": {
2320 + "version": "6.7.14",
2321 + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
2322 + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",
2323 + "dev": true,
2324 + "license": "MIT",
2325 + "engines": {
2326 + "node": ">=8"
2327 + }
2328 + },
2329 + "node_modules/call-bind-apply-helpers": {
2330 + "version": "1.0.2",
2331 + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
2332 + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
2333 + "dev": true,
2334 + "license": "MIT",
2335 + "dependencies": {
2336 + "es-errors": "^1.3.0",
2337 + "function-bind": "^1.1.2"
2338 + },
2339 + "engines": {
2340 + "node": ">= 0.4"
2341 + }
2342 + },
2343 + "node_modules/callsites": {
2344 + "version": "3.1.0",
2345 + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
2346 + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",
2347 + "dev": true,
2348 + "license": "MIT",
2349 + "engines": {
2350 + "node": ">=6"
2351 + }
2352 + },
2353 + "node_modules/caniuse-lite": {
2354 + "version": "1.0.30001829",
2355 + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001829.tgz",
2356 + "integrity": "sha512-FeVvlaVr3r+cdHIYXyZhtVkqroSYjYaoNxItxQNjusurUE+IqODawDsbzk02HJgi2RdKiaGGFm+EKbXku+yITg==",
2357 + "dev": true,
2358 + "funding": [
2359 + {
2360 + "type": "opencollective",
2361 + "url": "https://opencollective.com/browserslist"
2362 + },
2363 + {
2364 + "type": "tidelift",
2365 + "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
2366 + },
2367 + {
2368 + "type": "github",
2369 + "url": "https://github.com/sponsors/ai"
2370 + }
2371 + ],
2372 + "license": "CC-BY-4.0"
2373 + },
2374 + "node_modules/chai": {
2375 + "version": "5.3.3",
2376 + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
2377 + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
2378 + "dev": true,
2379 + "license": "MIT",
2380 + "dependencies": {
2381 + "assertion-error": "^2.0.1",
2382 + "check-error": "^2.1.1",
2383 + "deep-eql": "^5.0.1",
2384 + "loupe": "^3.1.0",
2385 + "pathval": "^2.0.0"
2386 + },
2387 + "engines": {
2388 + "node": ">=18"
2389 + }
2390 + },
2391 + "node_modules/chalk": {
2392 + "version": "4.1.2",
2393 + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
2394 + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
2395 + "dev": true,
2396 + "license": "MIT",
2397 + "dependencies": {
2398 + "ansi-styles": "^4.1.0",
2399 + "supports-color": "^7.1.0"
2400 + },
2401 + "engines": {
2402 + "node": ">=10"
2403 + },
2404 + "funding": {
2405 + "url": "https://github.com/chalk/chalk?sponsor=1"
2406 + }
2407 + },
2408 + "node_modules/check-error": {
2409 + "version": "2.1.3",
2410 + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
2411 + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
2412 + "dev": true,
2413 + "license": "MIT",
2414 + "engines": {
2415 + "node": ">= 16"
2416 + }
2417 + },
2418 + "node_modules/color-convert": {
2419 + "version": "2.0.1",
2420 + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
2421 + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
2422 + "dev": true,
2423 + "license": "MIT",
2424 + "dependencies": {
2425 + "color-name": "~1.1.4"
2426 + },
2427 + "engines": {
2428 + "node": ">=7.0.0"
2429 + }
2430 + },
2431 + "node_modules/color-name": {
2432 + "version": "1.1.4",
2433 + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
2434 + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
2435 + "dev": true,
2436 + "license": "MIT"
2437 + },
2438 + "node_modules/combined-stream": {
2439 + "version": "1.0.8",
2440 + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
2441 + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
2442 + "dev": true,
2443 + "license": "MIT",
2444 + "dependencies": {
2445 + "delayed-stream": "~1.0.0"
2446 + },
2447 + "engines": {
2448 + "node": ">= 0.8"
2449 + }
2450 + },
2451 + "node_modules/concat-map": {
2452 + "version": "0.0.1",
2453 + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
2454 + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
2455 + "dev": true,
2456 + "license": "MIT"
2457 + },
2458 + "node_modules/convert-source-map": {
2459 + "version": "2.0.0",
2460 + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
2461 + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
2462 + "dev": true,
2463 + "license": "MIT"
2464 + },
2465 + "node_modules/cross-spawn": {
2466 + "version": "7.1.2",
2467 + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.1.2.tgz",
2468 + "integrity": "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==",
2469 + "dev": true,
2470 + "license": "MIT",
2471 + "dependencies": {
2472 + "path-key": "^3.1.0",
2473 + "shebang-command": "^2.0.0",
2474 + "which": "^2.0.1"
2475 + },
2476 + "engines": {
2477 + "node": ">= 8"
2478 + }
2479 + },
2480 + "node_modules/css.escape": {
2481 + "version": "1.5.1",
2482 + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz",
2483 + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==",
2484 + "dev": true,
2485 + "license": "MIT"
2486 + },
2487 + "node_modules/cssstyle": {
2488 + "version": "4.6.0",
2489 + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz",
2490 + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==",
2491 + "dev": true,
2492 + "license": "MIT",
2493 + "dependencies": {
2494 + "@asamuzakjp/css-color": "^3.2.0",
2495 + "rrweb-cssom": "^0.8.0"
2496 + },
2497 + "engines": {
2498 + "node": ">=18"
2499 + }
2500 + },
2501 + "node_modules/cssstyle/node_modules/rrweb-cssom": {
2502 + "version": "0.8.0",
2503 + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz",
2504 + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==",
2505 + "dev": true,
2506 + "license": "MIT"
2507 + },
2508 + "node_modules/csstype": {
2509 + "version": "3.2.4",
2510 + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz",
2511 + "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==",
2512 + "dev": true,
2513 + "license": "MIT"
2514 + },
2515 + "node_modules/data-urls": {
2516 + "version": "5.0.0",
2517 + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",
2518 + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==",
2519 + "dev": true,
2520 + "license": "MIT",
2521 + "dependencies": {
2522 + "whatwg-mimetype": "^4.0.0",
2523 + "whatwg-url": "^14.0.0"
2524 + },
2525 + "engines": {
2526 + "node": ">=18"
2527 + }
2528 + },
2529 + "node_modules/debug": {
2530 + "version": "4.4.3",
2531 + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
2532 + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
2533 + "dev": true,
2534 + "license": "MIT",
2535 + "dependencies": {
2536 + "ms": "^2.1.3"
2537 + },
2538 + "engines": {
2539 + "node": ">=6.0"
2540 + },
2541 + "peerDependenciesMeta": {
2542 + "supports-color": {
2543 + "optional": true
2544 + }
2545 + }
2546 + },
2547 + "node_modules/decimal.js": {
2548 + "version": "10.6.0",
2549 + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
2550 + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
2551 + "dev": true,
2552 + "license": "MIT"
2553 + },
2554 + "node_modules/deep-eql": {
2555 + "version": "5.0.2",
2556 + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
2557 + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
2558 + "dev": true,
2559 + "license": "MIT",
2560 + "engines": {
2561 + "node": ">=6"
2562 + }
2563 + },
2564 + "node_modules/deep-is": {
2565 + "version": "0.1.4",
2566 + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
2567 + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",
2568 + "dev": true,
2569 + "license": "MIT"
2570 + },
2571 + "node_modules/delayed-stream": {
2572 + "version": "1.0.0",
2573 + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
2574 + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
2575 + "dev": true,
2576 + "license": "MIT",
2577 + "engines": {
2578 + "node": ">=0.4.0"
2579 + }
2580 + },
2581 + "node_modules/dequal": {
2582 + "version": "2.0.3",
2583 + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
2584 + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
2585 + "dev": true,
2586 + "license": "MIT",
2587 + "engines": {
2588 + "node": ">=6"
2589 + }
2590 + },
2591 + "node_modules/dom-accessibility-api": {
2592 + "version": "0.5.16",
2593 + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
2594 + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
2595 + "dev": true,
2596 + "license": "MIT",
2597 + "peer": true
2598 + },
2599 + "node_modules/dunder-proto": {
2600 + "version": "1.0.1",
2601 + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
2602 + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
2603 + "dev": true,
2604 + "license": "MIT",
2605 + "dependencies": {
2606 + "call-bind-apply-helpers": "^1.0.1",
2607 + "es-errors": "^1.3.0",
2608 + "gopd": "^1.2.0"
2609 + },
2610 + "engines": {
2611 + "node": ">= 0.4"
2612 + }
2613 + },
2614 + "node_modules/electron-to-chromium": {
2615 + "version": "1.5.497",
2616 + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.497.tgz",
2617 + "integrity": "sha512-6AOdatCqk0KqRbYrO2+ZfyE6I4ukT07lGc0uXBPapvIg4vZ00hg+8kdO19nL7PVfS2pQBTb9yzdt1efkz02vvw==",
2618 + "dev": true,
2619 + "license": "ISC"
2620 + },
2621 + "node_modules/entities": {
2622 + "version": "6.0.1",
2623 + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",
2624 + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",
2625 + "dev": true,
2626 + "license": "BSD-2-Clause",
2627 + "engines": {
2628 + "node": ">=0.12"
2629 + },
2630 + "funding": {
2631 + "url": "https://github.com/fb55/entities?sponsor=1"
2632 + }
2633 + },
2634 + "node_modules/es-define-property": {
2635 + "version": "1.0.1",
2636 + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
2637 + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
2638 + "dev": true,
2639 + "license": "MIT",
2640 + "engines": {
2641 + "node": ">= 0.4"
2642 + }
2643 + },
2644 + "node_modules/es-errors": {
2645 + "version": "1.3.0",
2646 + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
2647 + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
2648 + "dev": true,
2649 + "license": "MIT",
2650 + "engines": {
2651 + "node": ">= 0.4"
2652 + }
2653 + },
2654 + "node_modules/es-module-lexer": {
2655 + "version": "1.7.0",
2656 + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
2657 + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",
2658 + "dev": true,
2659 + "license": "MIT"
2660 + },
2661 + "node_modules/es-object-atoms": {
2662 + "version": "1.1.2",
2663 + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
2664 + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
2665 + "dev": true,
2666 + "license": "MIT",
2667 + "dependencies": {
2668 + "es-errors": "^1.3.0"
2669 + },
2670 + "engines": {
2671 + "node": ">= 0.4"
2672 + }
2673 + },
2674 + "node_modules/es-set-tostringtag": {
2675 + "version": "2.1.0",
2676 + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
2677 + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
2678 + "dev": true,
2679 + "license": "MIT",
2680 + "dependencies": {
2681 + "es-errors": "^1.3.0",
2682 + "get-intrinsic": "^1.2.6",
2683 + "has-tostringtag": "^1.0.2",
2684 + "hasown": "^2.0.2"
2685 + },
2686 + "engines": {
2687 + "node": ">= 0.4"
2688 + }
2689 + },
2690 + "node_modules/esbuild": {
2691 + "version": "0.21.5",
2692 + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
2693 + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
2694 + "dev": true,
2695 + "hasInstallScript": true,
2696 + "license": "MIT",
2697 + "bin": {
2698 + "esbuild": "bin/esbuild"
2699 + },
2700 + "engines": {
2701 + "node": ">=12"
2702 + },
2703 + "optionalDependencies": {
2704 + "@esbuild/aix-ppc64": "0.21.5",
2705 + "@esbuild/android-arm": "0.21.5",
2706 + "@esbuild/android-arm64": "0.21.5",
2707 + "@esbuild/android-x64": "0.21.5",
2708 + "@esbuild/darwin-arm64": "0.21.5",
2709 + "@esbuild/darwin-x64": "0.21.5",
2710 + "@esbuild/freebsd-arm64": "0.21.5",
2711 + "@esbuild/freebsd-x64": "0.21.5",
2712 + "@esbuild/linux-arm": "0.21.5",
2713 + "@esbuild/linux-arm64": "0.21.5",
2714 + "@esbuild/linux-ia32": "0.21.5",
2715 + "@esbuild/linux-loong64": "0.21.5",
2716 + "@esbuild/linux-mips64el": "0.21.5",
2717 + "@esbuild/linux-ppc64": "0.21.5",
2718 + "@esbuild/linux-riscv64": "0.21.5",
2719 + "@esbuild/linux-s390x": "0.21.5",
2720 + "@esbuild/linux-x64": "0.21.5",
2721 + "@esbuild/netbsd-x64": "0.21.5",
2722 + "@esbuild/openbsd-x64": "0.21.5",
2723 + "@esbuild/sunos-x64": "0.21.5",
2724 + "@esbuild/win32-arm64": "0.21.5",
2725 + "@esbuild/win32-ia32": "0.21.5",
2726 + "@esbuild/win32-x64": "0.21.5"
2727 + }
2728 + },
2729 + "node_modules/escalade": {
2730 + "version": "3.2.0",
2731 + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
2732 + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
2733 + "dev": true,
2734 + "license": "MIT",
2735 + "engines": {
2736 + "node": ">=6"
2737 + }
2738 + },
2739 + "node_modules/escape-string-regexp": {
2740 + "version": "4.0.0",
2741 + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
2742 + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
2743 + "dev": true,
2744 + "license": "MIT",
2745 + "engines": {
2746 + "node": ">=10"
2747 + },
2748 + "funding": {
2749 + "url": "https://github.com/sponsors/sindresorhus"
2750 + }
2751 + },
2752 + "node_modules/eslint": {
2753 + "version": "9.39.5",
2754 + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.5.tgz",
2755 + "integrity": "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw==",
2756 + "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.",
2757 + "dev": true,
2758 + "license": "MIT",
2759 + "dependencies": {
2760 + "@eslint-community/eslint-utils": "^4.8.0",
2761 + "@eslint-community/regexpp": "^4.12.1",
2762 + "@eslint/config-array": "^0.21.2",
2763 + "@eslint/config-helpers": "^0.4.2",
2764 + "@eslint/core": "^0.17.0",
2765 + "@eslint/eslintrc": "^3.3.6",
2766 + "@eslint/js": "9.39.5",
2767 + "@eslint/plugin-kit": "^0.4.1",
2768 + "@humanfs/node": "^0.16.6",
2769 + "@humanwhocodes/module-importer": "^1.0.1",
2770 + "@humanwhocodes/retry": "^0.4.2",
2771 + "@types/estree": "^1.0.6",
2772 + "ajv": "^6.14.0",
2773 + "chalk": "^4.0.0",
2774 + "cross-spawn": "^7.0.6",
2775 + "debug": "^4.3.2",
2776 + "escape-string-regexp": "^4.0.0",
2777 + "eslint-scope": "^8.4.0",
2778 + "eslint-visitor-keys": "^4.2.1",
2779 + "espree": "^10.4.0",
2780 + "esquery": "^1.5.0",
2781 + "esutils": "^2.0.2",
2782 + "fast-deep-equal": "^3.1.3",
2783 + "file-entry-cache": "^8.0.0",
2784 + "find-up": "^5.0.0",
2785 + "glob-parent": "^6.0.2",
2786 + "ignore": "^5.2.0",
2787 + "imurmurhash": "^0.1.4",
2788 + "is-glob": "^4.0.0",
2789 + "json-stable-stringify-without-jsonify": "^1.0.1",
2790 + "lodash.merge": "^4.6.2",
2791 + "minimatch": "^3.1.5",
2792 + "natural-compare": "^1.4.0",
2793 + "optionator": "^0.9.3"
2794 + },
2795 + "bin": {
2796 + "eslint": "bin/eslint.js"
2797 + },
2798 + "engines": {
2799 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
2800 + },
2801 + "funding": {
2802 + "url": "https://eslint.org/donate"
2803 + },
2804 + "peerDependencies": {
2805 + "jiti": "*"
2806 + },
2807 + "peerDependenciesMeta": {
2808 + "jiti": {
2809 + "optional": true
2810 + }
2811 + }
2812 + },
2813 + "node_modules/eslint-plugin-react-hooks": {
2814 + "version": "5.2.0",
2815 + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-5.2.0.tgz",
2816 + "integrity": "sha512-+f15FfK64YQwZdJNELETdn5ibXEUQmW1DZL6KXhNnc2heoy/sg9VJJeT7n8TlMWouzWqSWavFkIhHyIbIAEapg==",
2817 + "dev": true,
2818 + "license": "MIT",
2819 + "engines": {
2820 + "node": ">=10"
2821 + },
2822 + "peerDependencies": {
2823 + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0"
2824 + }
2825 + },
2826 + "node_modules/eslint-scope": {
2827 + "version": "8.4.0",
2828 + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz",
2829 + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==",
2830 + "dev": true,
2831 + "license": "BSD-2-Clause",
2832 + "dependencies": {
2833 + "esrecurse": "^4.3.0",
2834 + "estraverse": "^5.2.0"
2835 + },
2836 + "engines": {
2837 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
2838 + },
2839 + "funding": {
2840 + "url": "https://opencollective.com/eslint"
2841 + }
2842 + },
2843 + "node_modules/eslint-visitor-keys": {
2844 + "version": "4.2.1",
2845 + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",
2846 + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",
2847 + "dev": true,
2848 + "license": "Apache-2.0",
2849 + "engines": {
2850 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
2851 + },
2852 + "funding": {
2853 + "url": "https://opencollective.com/eslint"
2854 + }
2855 + },
2856 + "node_modules/espree": {
2857 + "version": "10.4.0",
2858 + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",
2859 + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==",
2860 + "dev": true,
2861 + "license": "BSD-2-Clause",
2862 + "dependencies": {
2863 + "acorn": "^8.15.0",
2864 + "acorn-jsx": "^5.3.2",
2865 + "eslint-visitor-keys": "^4.2.1"
2866 + },
2867 + "engines": {
2868 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
2869 + },
2870 + "funding": {
2871 + "url": "https://opencollective.com/eslint"
2872 + }
2873 + },
2874 + "node_modules/esquery": {
2875 + "version": "1.7.0",
2876 + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz",
2877 + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==",
2878 + "dev": true,
2879 + "license": "BSD-3-Clause",
2880 + "dependencies": {
2881 + "estraverse": "^5.1.0"
2882 + },
2883 + "engines": {
2884 + "node": ">=0.10"
2885 + }
2886 + },
2887 + "node_modules/esrecurse": {
2888 + "version": "4.3.0",
2889 + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",
2890 + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",
2891 + "dev": true,
2892 + "license": "BSD-2-Clause",
2893 + "dependencies": {
2894 + "estraverse": "^5.2.0"
2895 + },
2896 + "engines": {
2897 + "node": ">=4.0"
2898 + }
2899 + },
2900 + "node_modules/estraverse": {
2901 + "version": "5.3.0",
2902 + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
2903 + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
2904 + "dev": true,
2905 + "license": "BSD-2-Clause",
2906 + "engines": {
2907 + "node": ">=4.0"
2908 + }
2909 + },
2910 + "node_modules/estree-walker": {
2911 + "version": "3.0.3",
2912 + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
2913 + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
2914 + "dev": true,
2915 + "license": "MIT",
2916 + "dependencies": {
2917 + "@types/estree": "^1.0.0"
2918 + }
2919 + },
2920 + "node_modules/esutils": {
2921 + "version": "2.0.3",
2922 + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
2923 + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
2924 + "dev": true,
2925 + "license": "BSD-2-Clause",
2926 + "engines": {
2927 + "node": ">=0.10.0"
2928 + }
2929 + },
2930 + "node_modules/expect-type": {
2931 + "version": "1.4.0",
2932 + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
2933 + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
2934 + "dev": true,
2935 + "license": "Apache-2.0",
2936 + "engines": {
2937 + "node": ">=12.0.0"
2938 + }
2939 + },
2940 + "node_modules/fast-deep-equal": {
2941 + "version": "3.1.3",
2942 + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
2943 + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
2944 + "dev": true,
2945 + "license": "MIT"
2946 + },
2947 + "node_modules/fast-json-stable-stringify": {
2948 + "version": "2.1.0",
2949 + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
2950 + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
2951 + "dev": true,
2952 + "license": "MIT"
2953 + },
2954 + "node_modules/fast-levenshtein": {
2955 + "version": "2.0.6",
2956 + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",
2957 + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",
2958 + "dev": true,
2959 + "license": "MIT"
2960 + },
2961 + "node_modules/fdir": {
2962 + "version": "6.5.0",
2963 + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
2964 + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
2965 + "dev": true,
2966 + "license": "MIT",
2967 + "engines": {
2968 + "node": ">=12.0.0"
2969 + },
2970 + "peerDependencies": {
2971 + "picomatch": "^3 || ^4"
2972 + },
2973 + "peerDependenciesMeta": {
2974 + "picomatch": {
2975 + "optional": true
2976 + }
2977 + }
2978 + },
2979 + "node_modules/file-entry-cache": {
2980 + "version": "8.0.0",
2981 + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
2982 + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==",
2983 + "dev": true,
2984 + "license": "MIT",
2985 + "dependencies": {
2986 + "flat-cache": "^4.0.0"
2987 + },
2988 + "engines": {
2989 + "node": ">=16.0.0"
2990 + }
2991 + },
2992 + "node_modules/find-up": {
2993 + "version": "5.0.0",
2994 + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",
2995 + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",
2996 + "dev": true,
2997 + "license": "MIT",
2998 + "dependencies": {
2999 + "locate-path": "^6.0.0",
3000 + "path-exists": "^4.0.0"
3001 + },
3002 + "engines": {
3003 + "node": ">=10"
3004 + },
3005 + "funding": {
3006 + "url": "https://github.com/sponsors/sindresorhus"
3007 + }
3008 + },
3009 + "node_modules/flat-cache": {
3010 + "version": "4.0.1",
3011 + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz",
3012 + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==",
3013 + "dev": true,
3014 + "license": "MIT",
3015 + "dependencies": {
3016 + "flatted": "^3.2.9",
3017 + "keyv": "^4.5.4"
3018 + },
3019 + "engines": {
3020 + "node": ">=16"
3021 + }
3022 + },
3023 + "node_modules/flatted": {
3024 + "version": "3.5.1",
3025 + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.5.1.tgz",
3026 + "integrity": "sha512-qzp88St5qssOkS6hnWEvsFqE6SGoQtamMc6ghNo2s2idGn3rvHl/mdmLKQr5egZeVcqHfVCXtPoY+DP0flzPTg==",
3027 + "dev": true,
3028 + "license": "ISC"
3029 + },
3030 + "node_modules/form-data": {
3031 + "version": "4.0.6",
3032 + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
3033 + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",
3034 + "dev": true,
3035 + "license": "MIT",
3036 + "dependencies": {
3037 + "asynckit": "^0.4.0",
3038 + "combined-stream": "^1.0.8",
3039 + "es-set-tostringtag": "^2.1.0",
3040 + "hasown": "^2.0.4",
3041 + "mime-types": "^2.1.35"
3042 + },
3043 + "engines": {
3044 + "node": ">= 6"
3045 + }
3046 + },
3047 + "node_modules/fsevents": {
3048 + "version": "2.3.3",
3049 + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
3050 + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
3051 + "dev": true,
3052 + "hasInstallScript": true,
3053 + "license": "MIT",
3054 + "optional": true,
3055 + "os": [
3056 + "darwin"
3057 + ],
3058 + "engines": {
3059 + "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
3060 + }
3061 + },
3062 + "node_modules/function-bind": {
3063 + "version": "1.1.2",
3064 + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
3065 + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
3066 + "dev": true,
3067 + "license": "MIT",
3068 + "funding": {
3069 + "url": "https://github.com/sponsors/ljharb"
3070 + }
3071 + },
3072 + "node_modules/gensync": {
3073 + "version": "1.0.0-beta.2",
3074 + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
3075 + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
3076 + "dev": true,
3077 + "license": "MIT",
3078 + "engines": {
3079 + "node": ">=6.9.0"
3080 + }
3081 + },
3082 + "node_modules/get-intrinsic": {
3083 + "version": "1.3.0",
3084 + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
3085 + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
3086 + "dev": true,
3087 + "license": "MIT",
3088 + "dependencies": {
3089 + "call-bind-apply-helpers": "^1.0.2",
3090 + "es-define-property": "^1.0.1",
3091 + "es-errors": "^1.3.0",
3092 + "es-object-atoms": "^1.1.1",
3093 + "function-bind": "^1.1.2",
3094 + "get-proto": "^1.0.1",
3095 + "gopd": "^1.2.0",
3096 + "has-symbols": "^1.1.0",
3097 + "hasown": "^2.0.2",
3098 + "math-intrinsics": "^1.1.0"
3099 + },
3100 + "engines": {
3101 + "node": ">= 0.4"
3102 + },
3103 + "funding": {
3104 + "url": "https://github.com/sponsors/ljharb"
3105 + }
3106 + },
3107 + "node_modules/get-proto": {
3108 + "version": "1.0.1",
3109 + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
3110 + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
3111 + "dev": true,
3112 + "license": "MIT",
3113 + "dependencies": {
3114 + "dunder-proto": "^1.0.1",
3115 + "es-object-atoms": "^1.0.0"
3116 + },
3117 + "engines": {
3118 + "node": ">= 0.4"
3119 + }
3120 + },
3121 + "node_modules/glob-parent": {
3122 + "version": "6.0.2",
3123 + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
3124 + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",
3125 + "dev": true,
3126 + "license": "ISC",
3127 + "dependencies": {
3128 + "is-glob": "^4.0.3"
3129 + },
3130 + "engines": {
3131 + "node": ">=10.13.0"
3132 + }
3133 + },
3134 + "node_modules/globals": {
3135 + "version": "15.15.0",
3136 + "resolved": "https://registry.npmjs.org/globals/-/globals-15.15.0.tgz",
3137 + "integrity": "sha512-7ACyT3wmyp3I61S4fG682L0VA2RGD9otkqGJIwNUMF1SWUombIIk+af1unuDYgMm082aHYwD+mzJvv9Iu8dsgg==",
3138 + "dev": true,
3139 + "license": "MIT",
3140 + "engines": {
3141 + "node": ">=18"
3142 + },
3143 + "funding": {
3144 + "url": "https://github.com/sponsors/sindresorhus"
3145 + }
3146 + },
3147 + "node_modules/gopd": {
3148 + "version": "1.2.0",
3149 + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
3150 + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
3151 + "dev": true,
3152 + "license": "MIT",
3153 + "engines": {
3154 + "node": ">= 0.4"
3155 + },
3156 + "funding": {
3157 + "url": "https://github.com/sponsors/ljharb"
3158 + }
3159 + },
3160 + "node_modules/has-flag": {
3161 + "version": "4.0.0",
3162 + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
3163 + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
3164 + "dev": true,
3165 + "license": "MIT",
3166 + "engines": {
3167 + "node": ">=8"
3168 + }
3169 + },
3170 + "node_modules/has-symbols": {
3171 + "version": "1.1.0",
3172 + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
3173 + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
3174 + "dev": true,
3175 + "license": "MIT",
3176 + "engines": {
3177 + "node": ">= 0.4"
3178 + },
3179 + "funding": {
3180 + "url": "https://github.com/sponsors/ljharb"
3181 + }
3182 + },
3183 + "node_modules/has-tostringtag": {
3184 + "version": "1.0.2",
3185 + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
3186 + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
3187 + "dev": true,
3188 + "license": "MIT",
3189 + "dependencies": {
3190 + "has-symbols": "^1.0.3"
3191 + },
3192 + "engines": {
3193 + "node": ">= 0.4"
3194 + },
3195 + "funding": {
3196 + "url": "https://github.com/sponsors/ljharb"
3197 + }
3198 + },
3199 + "node_modules/hasown": {
3200 + "version": "2.0.4",
3201 + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
3202 + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
3203 + "dev": true,
3204 + "license": "MIT",
3205 + "dependencies": {
3206 + "function-bind": "^1.1.2"
3207 + },
3208 + "engines": {
3209 + "node": ">= 0.4"
3210 + }
3211 + },
3212 + "node_modules/html-encoding-sniffer": {
3213 + "version": "4.0.0",
3214 + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz",
3215 + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==",
3216 + "dev": true,
3217 + "license": "MIT",
3218 + "dependencies": {
3219 + "whatwg-encoding": "^3.1.1"
3220 + },
3221 + "engines": {
3222 + "node": ">=18"
3223 + }
3224 + },
3225 + "node_modules/http-proxy-agent": {
3226 + "version": "7.0.2",
3227 + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
3228 + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
3229 + "dev": true,
3230 + "license": "MIT",
3231 + "dependencies": {
3232 + "agent-base": "^7.1.0",
3233 + "debug": "^4.3.4"
3234 + },
3235 + "engines": {
3236 + "node": ">= 14"
3237 + }
3238 + },
3239 + "node_modules/https-proxy-agent": {
3240 + "version": "7.0.6",
3241 + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
3242 + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
3243 + "dev": true,
3244 + "license": "MIT",
3245 + "dependencies": {
3246 + "agent-base": "^7.1.2",
3247 + "debug": "4"
3248 + },
3249 + "engines": {
3250 + "node": ">= 14"
3251 + }
3252 + },
3253 + "node_modules/iconv-lite": {
3254 + "version": "0.6.3",
3255 + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
3256 + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
3257 + "dev": true,
3258 + "license": "MIT",
3259 + "dependencies": {
3260 + "safer-buffer": ">= 2.1.2 < 3.0.0"
3261 + },
3262 + "engines": {
3263 + "node": ">=0.10.0"
3264 + }
3265 + },
3266 + "node_modules/ignore": {
3267 + "version": "5.3.2",
3268 + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
3269 + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
3270 + "dev": true,
3271 + "license": "MIT",
3272 + "engines": {
3273 + "node": ">= 4"
3274 + }
3275 + },
3276 + "node_modules/import-fresh": {
3277 + "version": "3.3.1",
3278 + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
3279 + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",
3280 + "dev": true,
3281 + "license": "MIT",
3282 + "dependencies": {
3283 + "parent-module": "^1.0.0",
3284 + "resolve-from": "^4.0.0"
3285 + },
3286 + "engines": {
3287 + "node": ">=6"
3288 + },
3289 + "funding": {
3290 + "url": "https://github.com/sponsors/sindresorhus"
3291 + }
3292 + },
3293 + "node_modules/imurmurhash": {
3294 + "version": "0.1.4",
3295 + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
3296 + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",
3297 + "dev": true,
3298 + "license": "MIT",
3299 + "engines": {
3300 + "node": ">=0.8.19"
3301 + }
3302 + },
3303 + "node_modules/indent-string": {
3304 + "version": "4.0.0",
3305 + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz",
3306 + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==",
3307 + "dev": true,
3308 + "license": "MIT",
3309 + "engines": {
3310 + "node": ">=8"
3311 + }
3312 + },
3313 + "node_modules/is-extglob": {
3314 + "version": "2.1.1",
3315 + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
3316 + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
3317 + "dev": true,
3318 + "license": "MIT",
3319 + "engines": {
3320 + "node": ">=0.10.0"
3321 + }
3322 + },
3323 + "node_modules/is-glob": {
3324 + "version": "4.0.3",
3325 + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
3326 + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
3327 + "dev": true,
3328 + "license": "MIT",
3329 + "dependencies": {
3330 + "is-extglob": "^2.1.1"
3331 + },
3332 + "engines": {
3333 + "node": ">=0.10.0"
3334 + }
3335 + },
3336 + "node_modules/is-potential-custom-element-name": {
3337 + "version": "1.0.1",
3338 + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
3339 + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
3340 + "dev": true,
3341 + "license": "MIT"
3342 + },
3343 + "node_modules/isexe": {
3344 + "version": "2.0.0",
3345 + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
3346 + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
3347 + "dev": true,
3348 + "license": "ISC"
3349 + },
3350 + "node_modules/js-tokens": {
3351 + "version": "4.0.0",
3352 + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
3353 + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
3354 + "license": "MIT"
3355 + },
3356 + "node_modules/js-yaml": {
3357 + "version": "4.3.2",
3358 + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
3359 + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==",
3360 + "dev": true,
3361 + "funding": [
3362 + {
3363 + "type": "github",
3364 + "url": "https://github.com/sponsors/puzrin"
3365 + },
3366 + {
3367 + "type": "github",
3368 + "url": "https://github.com/sponsors/nodeca"
3369 + }
3370 + ],
3371 + "license": "MIT",
3372 + "dependencies": {
3373 + "argparse": "^2.0.1"
3374 + },
3375 + "bin": {
3376 + "js-yaml": "bin/js-yaml.js"
3377 + }
3378 + },
3379 + "node_modules/jsdom": {
3380 + "version": "25.0.1",
3381 + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-25.0.1.tgz",
3382 + "integrity": "sha512-8i7LzZj7BF8uplX+ZyOlIz86V6TAsSs+np6m1kpW9u0JWi4z/1t+FzcK1aek+ybTnAC4KhBL4uXCNT0wcUIeCw==",
3383 + "dev": true,
3384 + "license": "MIT",
3385 + "dependencies": {
3386 + "cssstyle": "^4.1.0",
3387 + "data-urls": "^5.0.0",
3388 + "decimal.js": "^10.4.3",
3389 + "form-data": "^4.0.0",
3390 + "html-encoding-sniffer": "^4.0.0",
3391 + "http-proxy-agent": "^7.0.2",
3392 + "https-proxy-agent": "^7.0.5",
3393 + "is-potential-custom-element-name": "^1.0.1",
3394 + "nwsapi": "^2.2.12",
3395 + "parse5": "^7.1.2",
3396 + "rrweb-cssom": "^0.7.1",
3397 + "saxes": "^6.0.0",
3398 + "symbol-tree": "^3.2.4",
3399 + "tough-cookie": "^5.0.0",
3400 + "w3c-xmlserializer": "^5.0.0",
3401 + "webidl-conversions": "^7.0.0",
3402 + "whatwg-encoding": "^3.1.1",
3403 + "whatwg-mimetype": "^4.0.0",
3404 + "whatwg-url": "^14.0.0",
3405 + "ws": "^8.18.0",
3406 + "xml-name-validator": "^5.0.0"
3407 + },
3408 + "engines": {
3409 + "node": ">=18"
3410 + },
3411 + "peerDependencies": {
3412 + "canvas": "^2.11.2"
3413 + },
3414 + "peerDependenciesMeta": {
3415 + "canvas": {
3416 + "optional": true
3417 + }
3418 + }
3419 + },
3420 + "node_modules/jsesc": {
3421 + "version": "3.1.0",
3422 + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
3423 + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
3424 + "dev": true,
3425 + "license": "MIT",
3426 + "bin": {
3427 + "jsesc": "bin/jsesc"
3428 + },
3429 + "engines": {
3430 + "node": ">=6"
3431 + }
3432 + },
3433 + "node_modules/json-buffer": {
3434 + "version": "3.0.1",
3435 + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
3436 + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",
3437 + "dev": true,
3438 + "license": "MIT"
3439 + },
3440 + "node_modules/json-schema-traverse": {
3441 + "version": "0.4.1",
3442 + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
3443 + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
3444 + "dev": true,
3445 + "license": "MIT"
3446 + },
3447 + "node_modules/json-stable-stringify-without-jsonify": {
3448 + "version": "1.0.1",
3449 + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",
3450 + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==",
3451 + "dev": true,
3452 + "license": "MIT"
3453 + },
3454 + "node_modules/json5": {
3455 + "version": "2.2.3",
3456 + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
3457 + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
3458 + "dev": true,
3459 + "license": "MIT",
3460 + "bin": {
3461 + "json5": "lib/cli.js"
3462 + },
3463 + "engines": {
3464 + "node": ">=6"
3465 + }
3466 + },
3467 + "node_modules/keyv": {
3468 + "version": "4.5.4",
3469 + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
3470 + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",
3471 + "dev": true,
3472 + "license": "MIT",
3473 + "dependencies": {
3474 + "json-buffer": "3.0.1"
3475 + }
3476 + },
3477 + "node_modules/levn": {
3478 + "version": "0.4.1",
3479 + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
3480 + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",
3481 + "dev": true,
3482 + "license": "MIT",
3483 + "dependencies": {
3484 + "prelude-ls": "^1.2.1",
3485 + "type-check": "~0.4.0"
3486 + },
3487 + "engines": {
3488 + "node": ">= 0.8.0"
3489 + }
3490 + },
3491 + "node_modules/locate-path": {
3492 + "version": "6.0.0",
3493 + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
3494 + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",
3495 + "dev": true,
3496 + "license": "MIT",
3497 + "dependencies": {
3498 + "p-locate": "^5.0.0"
3499 + },
3500 + "engines": {
3501 + "node": ">=10"
3502 + },
3503 + "funding": {
3504 + "url": "https://github.com/sponsors/sindresorhus"
3505 + }
3506 + },
3507 + "node_modules/lodash.merge": {
3508 + "version": "4.6.2",
3509 + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
3510 + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==",
3511 + "dev": true,
3512 + "license": "MIT"
3513 + },
3514 + "node_modules/loose-envify": {
3515 + "version": "1.4.0",
3516 + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
3517 + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
3518 + "license": "MIT",
3519 + "dependencies": {
3520 + "js-tokens": "^3.0.0 || ^4.0.0"
3521 + },
3522 + "bin": {
3523 + "loose-envify": "cli.js"
3524 + }
3525 + },
3526 + "node_modules/loupe": {
3527 + "version": "3.2.1",
3528 + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
3529 + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
3530 + "dev": true,
3531 + "license": "MIT"
3532 + },
3533 + "node_modules/lru-cache": {
3534 + "version": "5.1.1",
3535 + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
3536 + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
3537 + "dev": true,
3538 + "license": "ISC",
3539 + "dependencies": {
3540 + "yallist": "^3.0.2"
3541 + }
3542 + },
3543 + "node_modules/lz-string": {
3544 + "version": "1.5.0",
3545 + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
3546 + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
3547 + "dev": true,
3548 + "license": "MIT",
3549 + "peer": true,
3550 + "bin": {
3551 + "lz-string": "bin/bin.js"
3552 + }
3553 + },
3554 + "node_modules/magic-string": {
3555 + "version": "0.30.21",
3556 + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
3557 + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
3558 + "dev": true,
3559 + "license": "MIT",
3560 + "dependencies": {
3561 + "@jridgewell/sourcemap-codec": "^1.5.5"
3562 + }
3563 + },
3564 + "node_modules/math-intrinsics": {
3565 + "version": "1.1.0",
3566 + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
3567 + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
3568 + "dev": true,
3569 + "license": "MIT",
3570 + "engines": {
3571 + "node": ">= 0.4"
3572 + }
3573 + },
3574 + "node_modules/mime-db": {
3575 + "version": "1.52.0",
3576 + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
3577 + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
3578 + "dev": true,
3579 + "license": "MIT",
3580 + "engines": {
3581 + "node": ">= 0.6"
3582 + }
3583 + },
3584 + "node_modules/mime-types": {
3585 + "version": "2.1.35",
3586 + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
3587 + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
3588 + "dev": true,
3589 + "license": "MIT",
3590 + "dependencies": {
3591 + "mime-db": "1.52.0"
3592 + },
3593 + "engines": {
3594 + "node": ">= 0.6"
3595 + }
3596 + },
3597 + "node_modules/min-indent": {
3598 + "version": "1.0.1",
3599 + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz",
3600 + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==",
3601 + "dev": true,
3602 + "license": "MIT",
3603 + "engines": {
3604 + "node": ">=4"
3605 + }
3606 + },
3607 + "node_modules/minimatch": {
3608 + "version": "3.1.5",
3609 + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
3610 + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
3611 + "dev": true,
3612 + "license": "ISC",
3613 + "dependencies": {
3614 + "brace-expansion": "^1.1.7"
3615 + },
3616 + "engines": {
3617 + "node": "*"
3618 + }
3619 + },
3620 + "node_modules/ms": {
3621 + "version": "2.1.3",
3622 + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
3623 + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
3624 + "dev": true,
3625 + "license": "MIT"
3626 + },
3627 + "node_modules/nanoid": {
3628 + "version": "3.3.20",
3629 + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
3630 + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
3631 + "dev": true,
3632 + "funding": [
3633 + {
3634 + "type": "github",
3635 + "url": "https://github.com/sponsors/ai"
3636 + }
3637 + ],
3638 + "license": "MIT",
3639 + "bin": {
3640 + "nanoid": "bin/nanoid.cjs"
3641 + },
3642 + "engines": {
3643 + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
3644 + }
3645 + },
3646 + "node_modules/natural-compare": {
3647 + "version": "1.4.0",
3648 + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
3649 + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",
3650 + "dev": true,
3651 + "license": "MIT"
3652 + },
3653 + "node_modules/node-releases": {
3654 + "version": "2.0.67",
3655 + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.67.tgz",
3656 + "integrity": "sha512-qgSZT38oj+YV4qyFmdPQEGRFQRP1l8a0wccOECrcrdGl9KldZlCXrEz7uOviThiOWR1KyqiQYeLrf7M9xRi1bg==",
3657 + "dev": true,
3658 + "license": "MIT",
3659 + "engines": {
3660 + "node": ">=18"
3661 + }
3662 + },
3663 + "node_modules/nwsapi": {
3664 + "version": "2.2.28",
3665 + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz",
3666 + "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==",
3667 + "dev": true,
3668 + "license": "MIT"
3669 + },
3670 + "node_modules/optionator": {
3671 + "version": "0.9.4",
3672 + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
3673 + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==",
3674 + "dev": true,
3675 + "license": "MIT",
3676 + "dependencies": {
3677 + "deep-is": "^0.1.3",
3678 + "fast-levenshtein": "^2.0.6",
3679 + "levn": "^0.4.1",
3680 + "prelude-ls": "^1.2.1",
3681 + "type-check": "^0.4.0",
3682 + "word-wrap": "^1.2.5"
3683 + },
3684 + "engines": {
3685 + "node": ">= 0.8.0"
3686 + }
3687 + },
3688 + "node_modules/p-limit": {
3689 + "version": "3.1.0",
3690 + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
3691 + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
3692 + "dev": true,
3693 + "license": "MIT",
3694 + "dependencies": {
3695 + "yocto-queue": "^0.1.0"
3696 + },
3697 + "engines": {
3698 + "node": ">=10"
3699 + },
3700 + "funding": {
3701 + "url": "https://github.com/sponsors/sindresorhus"
3702 + }
3703 + },
3704 + "node_modules/p-locate": {
3705 + "version": "5.0.0",
3706 + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",
3707 + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",
3708 + "dev": true,
3709 + "license": "MIT",
3710 + "dependencies": {
3711 + "p-limit": "^3.0.2"
3712 + },
3713 + "engines": {
3714 + "node": ">=10"
3715 + },
3716 + "funding": {
3717 + "url": "https://github.com/sponsors/sindresorhus"
3718 + }
3719 + },
3720 + "node_modules/parent-module": {
3721 + "version": "1.0.1",
3722 + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
3723 + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",
3724 + "dev": true,
3725 + "license": "MIT",
3726 + "dependencies": {
3727 + "callsites": "^3.0.0"
3728 + },
3729 + "engines": {
3730 + "node": ">=6"
3731 + }
3732 + },
3733 + "node_modules/parse5": {
3734 + "version": "7.3.0",
3735 + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",
3736 + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",
3737 + "dev": true,
3738 + "license": "MIT",
3739 + "dependencies": {
3740 + "entities": "^6.0.0"
3741 + },
3742 + "funding": {
3743 + "url": "https://github.com/inikulin/parse5?sponsor=1"
3744 + }
3745 + },
3746 + "node_modules/path-exists": {
3747 + "version": "4.0.0",
3748 + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
3749 + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
3750 + "dev": true,
3751 + "license": "MIT",
3752 + "engines": {
3753 + "node": ">=8"
3754 + }
3755 + },
3756 + "node_modules/path-key": {
3757 + "version": "3.1.1",
3758 + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
3759 + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
3760 + "dev": true,
3761 + "license": "MIT",
3762 + "engines": {
3763 + "node": ">=8"
3764 + }
3765 + },
3766 + "node_modules/pathe": {
3767 + "version": "1.1.2",
3768 + "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
3769 + "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
3770 + "dev": true,
3771 + "license": "MIT"
3772 + },
3773 + "node_modules/pathval": {
3774 + "version": "2.0.1",
3775 + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
3776 + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
3777 + "dev": true,
3778 + "license": "MIT",
3779 + "engines": {
3780 + "node": ">= 14.16"
3781 + }
3782 + },
3783 + "node_modules/picocolors": {
3784 + "version": "1.1.1",
3785 + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
3786 + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
3787 + "dev": true,
3788 + "license": "ISC"
3789 + },
3790 + "node_modules/picomatch": {
3791 + "version": "4.0.7",
3792 + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
3793 + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
3794 + "dev": true,
3795 + "license": "MIT",
3796 + "engines": {
3797 + "node": ">=12"
3798 + },
3799 + "funding": {
3800 + "url": "https://github.com/sponsors/jonschlinkert"
3801 + }
3802 + },
3803 + "node_modules/playwright": {
3804 + "version": "1.65.2",
3805 + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.2.tgz",
3806 + "integrity": "sha512-Bfg9lfUnqknFzjWrvz2GMckl656TWYwDHiR+T8MQK1V+Sp1D+ODuxpcsnMQ31BYH+LBiKs6kXRMInesqO8F41w==",
3807 + "dev": true,
3808 + "license": "Apache-2.0",
3809 + "dependencies": {
3810 + "playwright-core": "1.65.2"
3811 + },
3812 + "bin": {
3813 + "playwright": "cli.js"
3814 + },
3815 + "engines": {
3816 + "node": ">=20"
3817 + }
3818 + },
3819 + "node_modules/playwright-core": {
3820 + "version": "1.65.2",
3821 + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.2.tgz",
3822 + "integrity": "sha512-aHu9F46Mx5ha9iiB+VLZMUUtex3PBw4am9MHptc0IXaJhz++6YXsH96eEyThwCwMkIUiB8TdZcwXqnb3xKDzmA==",
3823 + "dev": true,
3824 + "license": "Apache-2.0",
3825 + "bin": {
3826 + "playwright-core": "cli.js"
3827 + },
3828 + "engines": {
3829 + "node": ">=20"
3830 + }
3831 + },
3832 + "node_modules/postcss": {
3833 + "version": "8.5.34",
3834 + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.34.tgz",
3835 + "integrity": "sha512-P1Qzj0XXZjMda74C7qiVnBG90UKNbyNUAOeQRBW8X63RsIMV57gevRqjnkELdwtZ/S2/uQFksJhmwuN8xShLPw==",
3836 + "dev": true,
3837 + "funding": [
3838 + {
3839 + "type": "opencollective",
3840 + "url": "https://opencollective.com/postcss/"
3841 + },
3842 + {
3843 + "type": "tidelift",
3844 + "url": "https://tidelift.com/funding/github/npm/postcss"
3845 + },
3846 + {
3847 + "type": "github",
3848 + "url": "https://github.com/sponsors/ai"
3849 + }
3850 + ],
3851 + "license": "MIT",
3852 + "dependencies": {
3853 + "nanoid": "^3.3.20",
3854 + "picocolors": "^1.1.1",
3855 + "source-map-js": "^1.2.4"
3856 + },
3857 + "engines": {
3858 + "node": "^10 || ^12 || >=14"
3859 + }
3860 + },
3861 + "node_modules/prelude-ls": {
3862 + "version": "1.2.1",
3863 + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
3864 + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",
3865 + "dev": true,
3866 + "license": "MIT",
3867 + "engines": {
3868 + "node": ">= 0.8.0"
3869 + }
3870 + },
3871 + "node_modules/pretty-format": {
3872 + "version": "27.5.1",
3873 + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
3874 + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
3875 + "dev": true,
3876 + "license": "MIT",
3877 + "peer": true,
3878 + "dependencies": {
3879 + "ansi-regex": "^5.0.1",
3880 + "ansi-styles": "^5.0.0",
3881 + "react-is": "^17.0.1"
3882 + },
3883 + "engines": {
3884 + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"
3885 + }
3886 + },
3887 + "node_modules/pretty-format/node_modules/ansi-styles": {
3888 + "version": "5.2.0",
3889 + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
3890 + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
3891 + "dev": true,
3892 + "license": "MIT",
3893 + "peer": true,
3894 + "engines": {
3895 + "node": ">=10"
3896 + },
3897 + "funding": {
3898 + "url": "https://github.com/chalk/ansi-styles?sponsor=1"
3899 + }
3900 + },
3901 + "node_modules/punycode": {
3902 + "version": "2.3.1",
3903 + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
3904 + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
3905 + "dev": true,
3906 + "license": "MIT",
3907 + "engines": {
3908 + "node": ">=6"
3909 + }
3910 + },
3911 + "node_modules/react": {
3912 + "version": "18.3.1",
3913 + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
3914 + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
3915 + "license": "MIT",
3916 + "dependencies": {
3917 + "loose-envify": "^1.1.0"
3918 + },
3919 + "engines": {
3920 + "node": ">=0.10.0"
3921 + }
3922 + },
3923 + "node_modules/react-dom": {
3924 + "version": "18.3.1",
3925 + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
3926 + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
3927 + "license": "MIT",
3928 + "dependencies": {
3929 + "loose-envify": "^1.1.0",
3930 + "scheduler": "^0.23.2"
3931 + },
3932 + "peerDependencies": {
3933 + "react": "^18.3.1"
3934 + }
3935 + },
3936 + "node_modules/react-is": {
3937 + "version": "17.0.2",
3938 + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
3939 + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
3940 + "dev": true,
3941 + "license": "MIT",
3942 + "peer": true
3943 + },
3944 + "node_modules/react-refresh": {
3945 + "version": "0.17.0",
3946 + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",
3947 + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==",
3948 + "dev": true,
3949 + "license": "MIT",
3950 + "engines": {
3951 + "node": ">=0.10.0"
3952 + }
3953 + },
3954 + "node_modules/redent": {
3955 + "version": "3.0.0",
3956 + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz",
3957 + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==",
3958 + "dev": true,
3959 + "license": "MIT",
3960 + "dependencies": {
3961 + "indent-string": "^4.0.0",
3962 + "strip-indent": "^3.0.0"
3963 + },
3964 + "engines": {
3965 + "node": ">=8"
3966 + }
3967 + },
3968 + "node_modules/resolve-from": {
3969 + "version": "4.0.0",
3970 + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
3971 + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",
3972 + "dev": true,
3973 + "license": "MIT",
3974 + "engines": {
3975 + "node": ">=4"
3976 + }
3977 + },
3978 + "node_modules/rollup": {
3979 + "version": "4.69.3",
3980 + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.69.3.tgz",
3981 + "integrity": "sha512-IvHhlznYBMqePMsPb0Z5QLJIweHo4L6gQb5XC1cfmRDMNLfnx3bCLzcepRQFjVi5jXer4areo5CjcqSvab5ftA==",
3982 + "dev": true,
3983 + "license": "MIT",
3984 + "dependencies": {
3985 + "@types/estree": "^1.0.10"
3986 + },
3987 + "bin": {
3988 + "rollup": "dist/bin/rollup"
3989 + },
3990 + "engines": {
3991 + "node": ">=18.0.0",
3992 + "npm": ">=8.0.0"
3993 + },
3994 + "optionalDependencies": {
3995 + "@rollup/rollup-android-arm-eabi": "4.69.3",
3996 + "@rollup/rollup-android-arm64": "4.69.3",
3997 + "@rollup/rollup-android-x64": "4.69.3",
3998 + "@rollup/rollup-darwin-arm64": "4.69.3",
3999 + "@rollup/rollup-darwin-x64": "4.69.3",
4000 + "@rollup/rollup-freebsd-arm64": "4.69.3",
4001 + "@rollup/rollup-freebsd-x64": "4.69.3",
4002 + "@rollup/rollup-linux-arm-gnueabihf": "4.69.3",
4003 + "@rollup/rollup-linux-arm-musleabihf": "4.69.3",
4004 + "@rollup/rollup-linux-arm64-gnu": "4.69.3",
4005 + "@rollup/rollup-linux-arm64-musl": "4.69.3",
4006 + "@rollup/rollup-linux-loong64-gnu": "4.69.3",
4007 + "@rollup/rollup-linux-loong64-musl": "4.69.3",
4008 + "@rollup/rollup-linux-ppc64-gnu": "4.69.3",
4009 + "@rollup/rollup-linux-ppc64-musl": "4.69.3",
4010 + "@rollup/rollup-linux-riscv64-gnu": "4.69.3",
4011 + "@rollup/rollup-linux-riscv64-musl": "4.69.3",
4012 + "@rollup/rollup-linux-s390x-gnu": "4.69.3",
4013 + "@rollup/rollup-linux-x64-gnu": "4.69.3",
4014 + "@rollup/rollup-linux-x64-musl": "4.69.3",
4015 + "@rollup/rollup-openbsd-x64": "4.69.3",
4016 + "@rollup/rollup-openharmony-arm64": "4.69.3",
4017 + "@rollup/rollup-win32-arm64-msvc": "4.69.3",
4018 + "@rollup/rollup-win32-ia32-msvc": "4.69.3",
4019 + "@rollup/rollup-win32-x64-gnu": "4.69.3",
4020 + "@rollup/rollup-win32-x64-msvc": "4.69.3",
4021 + "fsevents": "~2.3.2"
4022 + }
4023 + },
4024 + "node_modules/rrweb-cssom": {
4025 + "version": "0.7.1",
4026 + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.7.1.tgz",
4027 + "integrity": "sha512-TrEMa7JGdVm0UThDJSx7ddw5nVm3UJS9o9CCIZ72B1vSyEZoziDqBYP3XIoi/12lKrJR8rE3jeFHMok2F/Mnsg==",
4028 + "dev": true,
4029 + "license": "MIT"
4030 + },
4031 + "node_modules/safer-buffer": {
4032 + "version": "2.1.2",
4033 + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
4034 + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
4035 + "dev": true,
4036 + "license": "MIT"
4037 + },
4038 + "node_modules/saxes": {
4039 + "version": "6.0.0",
4040 + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
4041 + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
4042 + "dev": true,
4043 + "license": "ISC",
4044 + "dependencies": {
4045 + "xmlchars": "^2.2.0"
4046 + },
4047 + "engines": {
4048 + "node": ">=v12.22.7"
4049 + }
4050 + },
4051 + "node_modules/scheduler": {
4052 + "version": "0.23.2",
4053 + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
4054 + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
4055 + "license": "MIT",
4056 + "dependencies": {
4057 + "loose-envify": "^1.1.0"
4058 + }
4059 + },
4060 + "node_modules/semver": {
4061 + "version": "6.3.2",
4062 + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz",
4063 + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==",
4064 + "dev": true,
4065 + "license": "ISC",
4066 + "bin": {
4067 + "semver": "bin/semver.js"
4068 + }
4069 + },
4070 + "node_modules/shebang-command": {
4071 + "version": "2.0.0",
4072 + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
4073 + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
4074 + "dev": true,
4075 + "license": "MIT",
4076 + "dependencies": {
4077 + "shebang-regex": "^3.0.0"
4078 + },
4079 + "engines": {
4080 + "node": ">=8"
4081 + }
4082 + },
4083 + "node_modules/shebang-regex": {
4084 + "version": "3.0.0",
4085 + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
4086 + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
4087 + "dev": true,
4088 + "license": "MIT",
4089 + "engines": {
4090 + "node": ">=8"
4091 + }
4092 + },
4093 + "node_modules/siginfo": {
4094 + "version": "2.0.0",
4095 + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
4096 + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
4097 + "dev": true,
4098 + "license": "ISC"
4099 + },
4100 + "node_modules/source-map-js": {
4101 + "version": "1.3.0",
4102 + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.3.0.tgz",
4103 + "integrity": "sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q==",
4104 + "dev": true,
4105 + "license": "BSD-3-Clause",
4106 + "engines": {
4107 + "node": ">=6.0.0"
4108 + }
4109 + },
4110 + "node_modules/stackback": {
4111 + "version": "0.0.2",
4112 + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
4113 + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
4114 + "dev": true,
4115 + "license": "MIT"
4116 + },
4117 + "node_modules/std-env": {
4118 + "version": "3.10.0",
4119 + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
4120 + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
4121 + "dev": true,
4122 + "license": "MIT"
4123 + },
4124 + "node_modules/strip-indent": {
4125 + "version": "3.0.0",
4126 + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz",
4127 + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==",
4128 + "dev": true,
4129 + "license": "MIT",
4130 + "dependencies": {
4131 + "min-indent": "^1.0.0"
4132 + },
4133 + "engines": {
4134 + "node": ">=8"
4135 + }
4136 + },
4137 + "node_modules/strip-json-comments": {
4138 + "version": "3.1.1",
4139 + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
4140 + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",
4141 + "dev": true,
4142 + "license": "MIT",
4143 + "engines": {
4144 + "node": ">=8"
4145 + },
4146 + "funding": {
4147 + "url": "https://github.com/sponsors/sindresorhus"
4148 + }
4149 + },
4150 + "node_modules/supports-color": {
4151 + "version": "7.2.0",
4152 + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
4153 + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
4154 + "dev": true,
4155 + "license": "MIT",
4156 + "dependencies": {
4157 + "has-flag": "^4.0.0"
4158 + },
4159 + "engines": {
4160 + "node": ">=8"
4161 + }
4162 + },
4163 + "node_modules/symbol-tree": {
4164 + "version": "3.2.4",
4165 + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
4166 + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
4167 + "dev": true,
4168 + "license": "MIT"
4169 + },
4170 + "node_modules/tinybench": {
4171 + "version": "2.9.0",
4172 + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
4173 + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
4174 + "dev": true,
4175 + "license": "MIT"
4176 + },
4177 + "node_modules/tinyexec": {
4178 + "version": "0.3.2",
4179 + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",
4180 + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",
4181 + "dev": true,
4182 + "license": "MIT"
4183 + },
4184 + "node_modules/tinyglobby": {
4185 + "version": "0.2.17",
4186 + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
4187 + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
4188 + "dev": true,
4189 + "license": "MIT",
4190 + "dependencies": {
4191 + "fdir": "^6.5.0",
4192 + "picomatch": "^4.0.4"
4193 + },
4194 + "engines": {
4195 + "node": ">=12.0.0"
4196 + },
4197 + "funding": {
4198 + "url": "https://github.com/sponsors/SuperchupuDev"
4199 + }
4200 + },
4201 + "node_modules/tinypool": {
4202 + "version": "1.1.1",
4203 + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",
4204 + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",
4205 + "dev": true,
4206 + "license": "MIT",
4207 + "engines": {
4208 + "node": "^18.0.0 || >=20.0.0"
4209 + }
4210 + },
4211 + "node_modules/tinyrainbow": {
4212 + "version": "1.2.0",
4213 + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
4214 + "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
4215 + "dev": true,
4216 + "license": "MIT",
4217 + "engines": {
4218 + "node": ">=14.0.0"
4219 + }
4220 + },
4221 + "node_modules/tinyspy": {
4222 + "version": "3.0.2",
4223 + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz",
4224 + "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==",
4225 + "dev": true,
4226 + "license": "MIT",
4227 + "engines": {
4228 + "node": ">=14.0.0"
4229 + }
4230 + },
4231 + "node_modules/tldts": {
4232 + "version": "6.1.86",
4233 + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz",
4234 + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==",
4235 + "dev": true,
4236 + "license": "MIT",
4237 + "dependencies": {
4238 + "tldts-core": "^6.1.86"
4239 + },
4240 + "bin": {
4241 + "tldts": "bin/cli.js"
4242 + }
4243 + },
4244 + "node_modules/tldts-core": {
4245 + "version": "6.1.86",
4246 + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz",
4247 + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==",
4248 + "dev": true,
4249 + "license": "MIT"
4250 + },
4251 + "node_modules/tough-cookie": {
4252 + "version": "5.1.2",
4253 + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz",
4254 + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==",
4255 + "dev": true,
4256 + "license": "BSD-3-Clause",
4257 + "dependencies": {
4258 + "tldts": "^6.1.32"
4259 + },
4260 + "engines": {
4261 + "node": ">=16"
4262 + }
4263 + },
4264 + "node_modules/tr46": {
4265 + "version": "5.1.1",
4266 + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
4267 + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
4268 + "dev": true,
4269 + "license": "MIT",
4270 + "dependencies": {
4271 + "punycode": "^2.3.1"
4272 + },
4273 + "engines": {
4274 + "node": ">=18"
4275 + }
4276 + },
4277 + "node_modules/ts-api-utils": {
4278 + "version": "2.5.0",
4279 + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",
4280 + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==",
4281 + "dev": true,
4282 + "license": "MIT",
4283 + "engines": {
4284 + "node": ">=18.12"
4285 + },
4286 + "peerDependencies": {
4287 + "typescript": ">=4.8.4"
4288 + }
4289 + },
4290 + "node_modules/type-check": {
4291 + "version": "0.4.0",
4292 + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
4293 + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",
4294 + "dev": true,
4295 + "license": "MIT",
4296 + "dependencies": {
4297 + "prelude-ls": "^1.2.1"
4298 + },
4299 + "engines": {
4300 + "node": ">= 0.8.0"
4301 + }
4302 + },
4303 + "node_modules/typescript": {
4304 + "version": "5.9.3",
4305 + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
4306 + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
4307 + "dev": true,
4308 + "license": "Apache-2.0",
4309 + "bin": {
4310 + "tsc": "bin/tsc",
4311 + "tsserver": "bin/tsserver"
4312 + },
4313 + "engines": {
4314 + "node": ">=14.17"
4315 + }
4316 + },
4317 + "node_modules/typescript-eslint": {
4318 + "version": "8.74.0",
4319 + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.74.0.tgz",
4320 + "integrity": "sha512-OsWQlsedt1ZpZXfZZMNK3m4SoQONFFcy4h/uRznsCeRfVuEic3gh4KGUs2pJJ5o0Jj0Jr7keUHQGN1Ns9aDw7Q==",
4321 + "dev": true,
4322 + "license": "MIT",
4323 + "dependencies": {
4324 + "@typescript-eslint/eslint-plugin": "8.74.0",
4325 + "@typescript-eslint/parser": "8.74.0",
4326 + "@typescript-eslint/typescript-estree": "8.74.0",
4327 + "@typescript-eslint/utils": "8.74.0"
4328 + },
4329 + "engines": {
4330 + "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
4331 + },
4332 + "funding": {
4333 + "type": "opencollective",
4334 + "url": "https://opencollective.com/typescript-eslint"
4335 + },
4336 + "peerDependencies": {
4337 + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
4338 + "typescript": ">=4.8.4 <6.1.0"
4339 + }
4340 + },
4341 + "node_modules/undici-types": {
4342 + "version": "6.21.0",
4343 + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
4344 + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
4345 + "dev": true,
4346 + "license": "MIT"
4347 + },
4348 + "node_modules/update-browserslist-db": {
4349 + "version": "1.4.0",
4350 + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.4.0.tgz",
4351 + "integrity": "sha512-WPJuOnjI9FWDct4fB+ej4Mz8opLaw5CDcZ2t44tFZ0vIQVYWzBhWR3mkixuUj/A7+vY4V9+ApOZ2YYLwdgq46w==",
4352 + "dev": true,
4353 + "funding": [
4354 + {
4355 + "type": "opencollective",
4356 + "url": "https://opencollective.com/browserslist"
4357 + },
4358 + {
4359 + "type": "tidelift",
4360 + "url": "https://tidelift.com/funding/github/npm/browserslist"
4361 + },
4362 + {
4363 + "type": "github",
4364 + "url": "https://github.com/sponsors/ai"
4365 + }
4366 + ],
4367 + "license": "MIT",
4368 + "dependencies": {
4369 + "escalade": "^3.2.0",
4370 + "picocolors": "^1.1.1"
4371 + },
4372 + "bin": {
4373 + "update-browserslist-db": "cli.js"
4374 + },
4375 + "peerDependencies": {
4376 + "browserslist": ">= 4.21.0"
4377 + }
4378 + },
4379 + "node_modules/uri-js": {
4380 + "version": "4.4.1",
4381 + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
4382 + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
4383 + "dev": true,
4384 + "license": "BSD-2-Clause",
4385 + "dependencies": {
4386 + "punycode": "^2.1.0"
4387 + }
4388 + },
4389 + "node_modules/vite": {
4390 + "version": "5.4.21",
4391 + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
4392 + "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
4393 + "dev": true,
4394 + "license": "MIT",
4395 + "dependencies": {
4396 + "esbuild": "^0.21.3",
4397 + "postcss": "^8.4.43",
4398 + "rollup": "^4.20.0"
4399 + },
4400 + "bin": {
4401 + "vite": "bin/vite.js"
4402 + },
4403 + "engines": {
4404 + "node": "^18.0.0 || >=20.0.0"
4405 + },
4406 + "funding": {
4407 + "url": "https://github.com/vitejs/vite?sponsor=1"
4408 + },
4409 + "optionalDependencies": {
4410 + "fsevents": "~2.3.3"
4411 + },
4412 + "peerDependencies": {
4413 + "@types/node": "^18.0.0 || >=20.0.0",
4414 + "less": "*",
4415 + "lightningcss": "^1.21.0",
4416 + "sass": "*",
4417 + "sass-embedded": "*",
4418 + "stylus": "*",
4419 + "sugarss": "*",
4420 + "terser": "^5.4.0"
4421 + },
4422 + "peerDependenciesMeta": {
4423 + "@types/node": {
4424 + "optional": true
4425 + },
4426 + "less": {
4427 + "optional": true
4428 + },
4429 + "lightningcss": {
4430 + "optional": true
4431 + },
4432 + "sass": {
4433 + "optional": true
4434 + },
4435 + "sass-embedded": {
4436 + "optional": true
4437 + },
4438 + "stylus": {
4439 + "optional": true
4440 + },
4441 + "sugarss": {
4442 + "optional": true
4443 + },
4444 + "terser": {
4445 + "optional": true
4446 + }
4447 + }
4448 + },
4449 + "node_modules/vite-node": {
4450 + "version": "2.1.9",
4451 + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-2.1.9.tgz",
4452 + "integrity": "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==",
4453 + "dev": true,
4454 + "license": "MIT",
4455 + "dependencies": {
4456 + "cac": "^6.7.14",
4457 + "debug": "^4.3.7",
4458 + "es-module-lexer": "^1.5.4",
4459 + "pathe": "^1.1.2",
4460 + "vite": "^5.0.0"
4461 + },
4462 + "bin": {
4463 + "vite-node": "vite-node.mjs"
4464 + },
4465 + "engines": {
4466 + "node": "^18.0.0 || >=20.0.0"
4467 + },
4468 + "funding": {
4469 + "url": "https://opencollective.com/vitest"
4470 + }
4471 + },
4472 + "node_modules/vitest": {
4473 + "version": "2.1.9",
4474 + "resolved": "https://registry.npmjs.org/vitest/-/vitest-2.1.9.tgz",
4475 + "integrity": "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==",
4476 + "dev": true,
4477 + "license": "MIT",
4478 + "dependencies": {
4479 + "@vitest/expect": "2.1.9",
4480 + "@vitest/mocker": "2.1.9",
4481 + "@vitest/pretty-format": "^2.1.9",
4482 + "@vitest/runner": "2.1.9",
4483 + "@vitest/snapshot": "2.1.9",
4484 + "@vitest/spy": "2.1.9",
4485 + "@vitest/utils": "2.1.9",
4486 + "chai": "^5.1.2",
4487 + "debug": "^4.3.7",
4488 + "expect-type": "^1.1.0",
4489 + "magic-string": "^0.30.12",
4490 + "pathe": "^1.1.2",
4491 + "std-env": "^3.8.0",
4492 + "tinybench": "^2.9.0",
4493 + "tinyexec": "^0.3.1",
4494 + "tinypool": "^1.0.1",
4495 + "tinyrainbow": "^1.2.0",
4496 + "vite": "^5.0.0",
4497 + "vite-node": "2.1.9",
4498 + "why-is-node-running": "^2.3.0"
4499 + },
4500 + "bin": {
4501 + "vitest": "vitest.mjs"
4502 + },
4503 + "engines": {
4504 + "node": "^18.0.0 || >=20.0.0"
4505 + },
4506 + "funding": {
4507 + "url": "https://opencollective.com/vitest"
4508 + },
4509 + "peerDependencies": {
4510 + "@edge-runtime/vm": "*",
4511 + "@types/node": "^18.0.0 || >=20.0.0",
4512 + "@vitest/browser": "2.1.9",
4513 + "@vitest/ui": "2.1.9",
4514 + "happy-dom": "*",
4515 + "jsdom": "*"
4516 + },
4517 + "peerDependenciesMeta": {
4518 + "@edge-runtime/vm": {
4519 + "optional": true
4520 + },
4521 + "@types/node": {
4522 + "optional": true
4523 + },
4524 + "@vitest/browser": {
4525 + "optional": true
4526 + },
4527 + "@vitest/ui": {
4528 + "optional": true
4529 + },
4530 + "happy-dom": {
4531 + "optional": true
4532 + },
4533 + "jsdom": {
4534 + "optional": true
4535 + }
4536 + }
4537 + },
4538 + "node_modules/w3c-xmlserializer": {
4539 + "version": "5.0.0",
4540 + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
4541 + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
4542 + "dev": true,
4543 + "license": "MIT",
4544 + "dependencies": {
4545 + "xml-name-validator": "^5.0.0"
4546 + },
4547 + "engines": {
4548 + "node": ">=18"
4549 + }
4550 + },
4551 + "node_modules/webidl-conversions": {
4552 + "version": "7.0.0",
4553 + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
4554 + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
4555 + "dev": true,
4556 + "license": "BSD-2-Clause",
4557 + "engines": {
4558 + "node": ">=12"
4559 + }
4560 + },
4561 + "node_modules/whatwg-encoding": {
4562 + "version": "3.1.1",
4563 + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
4564 + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",
4565 + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation",
4566 + "dev": true,
4567 + "license": "MIT",
4568 + "dependencies": {
4569 + "iconv-lite": "0.6.3"
4570 + },
4571 + "engines": {
4572 + "node": ">=18"
4573 + }
4574 + },
4575 + "node_modules/whatwg-mimetype": {
4576 + "version": "4.0.0",
4577 + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",
4578 + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",
4579 + "dev": true,
4580 + "license": "MIT",
4581 + "engines": {
4582 + "node": ">=18"
4583 + }
4584 + },
4585 + "node_modules/whatwg-url": {
4586 + "version": "14.2.0",
4587 + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
4588 + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
4589 + "dev": true,
4590 + "license": "MIT",
4591 + "dependencies": {
4592 + "tr46": "^5.1.0",
4593 + "webidl-conversions": "^7.0.0"
4594 + },
4595 + "engines": {
4596 + "node": ">=18"
4597 + }
4598 + },
4599 + "node_modules/which": {
4600 + "version": "2.0.2",
4601 + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
4602 + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
4603 + "dev": true,
4604 + "license": "ISC",
4605 + "dependencies": {
4606 + "isexe": "^2.0.0"
4607 + },
4608 + "bin": {
4609 + "node-which": "bin/node-which"
4610 + },
4611 + "engines": {
4612 + "node": ">= 8"
4613 + }
4614 + },
4615 + "node_modules/why-is-node-running": {
4616 + "version": "2.3.0",
4617 + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
4618 + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
4619 + "dev": true,
4620 + "license": "MIT",
4621 + "dependencies": {
4622 + "siginfo": "^2.0.0",
4623 + "stackback": "0.0.2"
4624 + },
4625 + "bin": {
4626 + "why-is-node-running": "cli.js"
4627 + },
4628 + "engines": {
4629 + "node": ">=8"
4630 + }
4631 + },
4632 + "node_modules/word-wrap": {
4633 + "version": "1.2.5",
4634 + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
4635 + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==",
4636 + "dev": true,
4637 + "license": "MIT",
4638 + "engines": {
4639 + "node": ">=0.10.0"
4640 + }
4641 + },
4642 + "node_modules/ws": {
4643 + "version": "8.23.1",
4644 + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.1.tgz",
4645 + "integrity": "sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==",
4646 + "dev": true,
4647 + "license": "MIT",
4648 + "engines": {
4649 + "node": ">=10.0.0"
4650 + },
4651 + "peerDependencies": {
4652 + "bufferutil": "^4.0.1",
4653 + "utf-8-validate": ">=5.0.2"
4654 + },
4655 + "peerDependenciesMeta": {
4656 + "bufferutil": {
4657 + "optional": true
4658 + },
4659 + "utf-8-validate": {
4660 + "optional": true
4661 + }
4662 + }
4663 + },
4664 + "node_modules/xml-name-validator": {
4665 + "version": "5.0.0",
4666 + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
4667 + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
4668 + "dev": true,
4669 + "license": "Apache-2.0",
4670 + "engines": {
4671 + "node": ">=18"
4672 + }
4673 + },
4674 + "node_modules/xmlchars": {
4675 + "version": "2.2.0",
4676 + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
4677 + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
4678 + "dev": true,
4679 + "license": "MIT"
4680 + },
4681 + "node_modules/yallist": {
4682 + "version": "3.1.1",
4683 + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
4684 + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
4685 + "dev": true,
4686 + "license": "ISC"
4687 + },
4688 + "node_modules/yocto-queue": {
4689 + "version": "0.1.0",
4690 + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
4691 + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
4692 + "dev": true,
4693 + "license": "MIT",
4694 + "engines": {
4695 + "node": ">=10"
4696 + },
4697 + "funding": {
4698 + "url": "https://github.com/sponsors/sindresorhus"
4699 + }
4700 + }
4701 + }
4702 +}
frontend/package.json new
+1
@@ -0,0 +1 @@
1 +{"name":"aram-frontend","private":true,"version":"0.1.0","type":"module","scripts":{"dev":"vite","build":"tsc --noEmit && vite build","preview":"vite preview","lint":"eslint .","typecheck":"tsc --noEmit","test":"vitest run","test:watch":"vitest","test:e2e":"playwright test"},"dependencies":{"react":"^18.3.1","react-dom":"^18.3.1"},"devDependencies":{"@eslint/js":"^9.13.0","@playwright/test":"^1.48.2","@testing-library/jest-dom":"^6.6.2","@testing-library/react":"^16.0.1","@types/node":"^22.20.7","@types/react":"^18.3.12","@types/react-dom":"^18.3.1","@vitejs/plugin-react":"^4.3.3","eslint":"^9.13.0","eslint-plugin-react-hooks":"^5.0.0","globals":"^15.11.0","jsdom":"^25.0.1","typescript":"^5.6.3","typescript-eslint":"^8.11.0","vite":"^5.4.10","vitest":"^2.1.4"}}
\ No newline at end of file
frontend/playwright.config.ts new
+18
@@ -0,0 +1,18 @@
1 +import { defineConfig, devices } from '@playwright/test'
2 +
3 +export default defineConfig({
4 + testDir: './e2e',
5 + fullyParallel: true,
6 + reporter: 'list',
7 + use: {
8 + baseURL: 'http://127.0.0.1:5173',
9 + trace: 'on-first-retry',
10 + },
11 + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
12 + webServer: {
13 + command: 'npm run dev -- --host 127.0.0.1 --port 5173',
14 + url: 'http://127.0.0.1:5173',
15 + reuseExistingServer: true,
16 + timeout: 120000,
17 + },
18 +})
frontend/src/App.test.tsx new
+53
@@ -0,0 +1,53 @@
1 +import { render, screen } from '@testing-library/react'
2 +import { describe, expect, it, vi } from 'vitest'
3 +import App from './App'
4 +
5 +vi.mock('./api/client', async () => {
6 + const actual = await vi.importActual<typeof import('./api/client')>('./api/client')
7 + return {
8 + ...actual,
9 + api: {
10 + createCompany: vi.fn(),
11 + uploadLedger: vi.fn(),
12 + unknownAccounts: vi.fn().mockResolvedValue({ count: 0, accounts: [] }),
13 + listStatements: vi.fn().mockResolvedValue({ statements: [], section_labels_fa: {} }),
14 + buildStatements: vi.fn(),
15 + drillDown: vi.fn(),
16 + preflight: vi.fn(),
17 + approve: vi.fn(),
18 + createNote: vi.fn(),
19 + createMapping: vi.fn(),
20 + importMappings: vi.fn(),
21 + exportMappingsUrl: (id: number) => `/api/v1/years/${id}/mappings/export`,
22 + exportStatementsUrl: (id: number, format: string) =>
23 + `/api/v1/years/${id}/statements/export?format=${format}`,
24 + listNotes: vi.fn().mockResolvedValue({ notes: [] }),
25 + listMappings: vi.fn().mockResolvedValue({ mappings: [] }),
26 + updateNote: vi.fn(),
27 + deleteNote: vi.fn(),
28 + deleteMapping: vi.fn(),
29 + login: vi.fn(),
30 + createUser: vi.fn(),
31 + auditVerify: vi.fn(),
32 + lockYear: vi.fn(),
33 + requestReopen: vi.fn(),
34 + approveReopen: vi.fn(),
35 + reopenYear: vi.fn(),
36 + backup: vi.fn(),
37 + verifyBackup: vi.fn(),
38 + },
39 + }
40 +})
41 +
42 +describe('App', () => {
43 + it('renders the Persian RTL workbench heading', () => {
44 + render(<App />)
45 + expect(screen.getByRole('heading', { name: /آرام — میز کار/ })).toBeInTheDocument()
46 + })
47 +
48 + it('shows the company setup form before a year exists', () => {
49 + render(<App />)
50 + expect(screen.getByRole('button', { name: 'ایجاد' })).toBeInTheDocument()
51 + expect(screen.queryByText('بارگذاری دفتر کل')).not.toBeInTheDocument()
52 + })
53 +})
frontend/src/App.tsx new
+46
@@ -0,0 +1,46 @@
1 +import { useState } from 'react'
2 +import type { CompanyResult } from './api/types'
3 +import AdminPanel from './components/AdminPanel'
4 +import ApprovalPanel from './components/ApprovalPanel'
5 +import CompanySetup from './components/CompanySetup'
6 +import LedgerUpload from './components/LedgerUpload'
7 +import MappingPanel from './components/MappingPanel'
8 +import NotesManager from './components/NotesManager'
9 +import StatementView from './components/StatementView'
10 +import { faNumber } from './lib/format'
11 +
12 +/**
13 + * Aram workbench (Phase 5): company/year setup -> ledger import -> mapping ->
14 + * statements with source drill-down -> controls and approval. RTL Persian UI;
15 + * all data flows through the relative /api/v1 backend (no runtime network).
16 + */
17 +export default function App() {
18 + const [company, setCompany] = useState<CompanyResult | null>(null)
19 + const [statementRefresh, setStatementRefresh] = useState(0)
20 +
21 + return (
22 + <main dir="rtl" lang="fa" className="app">
23 + <header className="app-header">
24 + <h1>آرام — میز کار صورت‌های مالی</h1>
25 + {company && (
26 + <p className="muted">
27 + سال مالی {faNumber(company.year)} · وضعیت {company.status}
28 + </p>
29 + )}
30 + </header>
31 +
32 + <CompanySetup onCreated={setCompany} />
33 +
34 + {company && (
35 + <>
36 + <LedgerUpload yearId={company.year_id} onImported={() => setStatementRefresh((k) => k + 1)} />
37 + <MappingPanel yearId={company.year_id} />
38 + <NotesManager yearId={company.year_id} refreshKey={statementRefresh} />
39 + <StatementView yearId={company.year_id} refreshKey={statementRefresh} />
40 + <ApprovalPanel yearId={company.year_id} />
41 + <AdminPanel yearId={company.year_id} />
42 + </>
43 + )}
44 + </main>
45 + )
46 +}
frontend/src/api/client.test.ts new
+37
@@ -0,0 +1,37 @@
1 +import { afterEach, describe, expect, it, vi } from 'vitest'
2 +import { api, ApiError } from './client'
3 +
4 +afterEach(() => {
5 + vi.restoreAllMocks()
6 +})
7 +
8 +describe('api client', () => {
9 + it('posts company creation as JSON and returns the parsed result', async () => {
10 + const fetchMock = vi.fn().mockResolvedValue({
11 + ok: true,
12 + json: async () => ({ company_id: 1, year_id: 2, year: 1404, status: 'Draft' }),
13 + })
14 + vi.stubGlobal('fetch', fetchMock)
15 +
16 + const result = await api.createCompany('C1', 'شرکت نمونه', 1404)
17 +
18 + expect(result.year_id).toBe(2)
19 + const [url, init] = fetchMock.mock.calls[0]
20 + expect(url).toBe('/api/v1/companies')
21 + expect(init.method).toBe('POST')
22 + expect(JSON.parse(init.body)).toEqual({ code: 'C1', name: 'شرکت نمونه', year: 1404 })
23 + })
24 +
25 + it('throws ApiError with the backend detail on failure', async () => {
26 + vi.stubGlobal(
27 + 'fetch',
28 + vi.fn().mockResolvedValue({ ok: false, status: 422, json: async () => ({ detail: 'سال یافت نشد' }) }),
29 + )
30 + await expect(api.preflight(999)).rejects.toMatchObject({ status: 422, message: 'سال یافت نشد' })
31 + await expect(api.preflight(999)).rejects.toBeInstanceOf(ApiError)
32 + })
33 +
34 + it('builds the relative export URL', () => {
35 + expect(api.exportMappingsUrl(7)).toBe('/api/v1/years/7/mappings/export')
36 + })
37 +})
frontend/src/api/client.ts new
+138
@@ -0,0 +1,138 @@
1 +import type {
2 + ApproveResult,
3 + BuildResult,
4 + CompanyResult,
5 + DrillDownResult,
6 + LedgerImportResult,
7 + MappingImportResult,
8 + MappingResult,
9 + NoteResult,
10 + PreflightResult,
11 + StatementsResult,
12 + UnknownAccountsResult,
13 +} from './types'
14 +
15 +const BASE = '/api/v1'
16 +
17 +export class ApiError extends Error {
18 + status: number
19 + constructor(status: number, message: string) {
20 + super(message)
21 + this.status = status
22 + this.name = 'ApiError'
23 + }
24 +}
25 +
26 +async function request<T>(path: string, init?: RequestInit): Promise<T> {
27 + const res = await fetch(`${BASE}${path}`, init)
28 + if (!res.ok) {
29 + let detail = `HTTP ${res.status}`
30 + try {
31 + const body = (await res.json()) as { detail?: unknown }
32 + if (body.detail !== undefined) {
33 + detail = typeof body.detail === 'string' ? body.detail : JSON.stringify(body.detail)
34 + }
35 + } catch {
36 + /* keep default detail */
37 + }
38 + throw new ApiError(res.status, detail)
39 + }
40 + return (await res.json()) as T
41 +}
42 +
43 +function json(body: unknown): RequestInit {
44 + return {
45 + method: 'POST',
46 + headers: { 'Content-Type': 'application/json' },
47 + body: JSON.stringify(body),
48 + }
49 +}
50 +
51 +function multipart(file: File): RequestInit {
52 + const form = new FormData()
53 + form.append('file', file)
54 + return { method: 'POST', body: form }
55 +}
56 +
57 +export const api = {
58 + createCompany: (code: string, name: string, year: number) =>
59 + request<CompanyResult>('/companies', json({ code, name, year })),
60 +
61 + uploadLedger: (yearId: number, file: File) =>
62 + request<LedgerImportResult>(`/years/${yearId}/ledger`, multipart(file)),
63 +
64 + createNote: (yearId: number, noteNumber: string, title: string, statement: string, section: string) =>
65 + request<NoteResult>(`/years/${yearId}/notes`, json({ note_number: noteNumber, title, statement, section })),
66 +
67 + createMapping: (yearId: number, accountCode: string, targetNoteId: number) =>
68 + request<MappingResult>(`/years/${yearId}/mappings`, json({ account_code: accountCode, target_note_id: targetNoteId })),
69 +
70 + buildStatements: (yearId: number) => request<BuildResult>(`/years/${yearId}/statements/build`, { method: 'POST' }),
71 +
72 + listStatements: (yearId: number) => request<StatementsResult>(`/years/${yearId}/statements`),
73 +
74 + drillDown: (lineId: number) => request<DrillDownResult>(`/statement-lines/${lineId}/drilldown`),
75 +
76 + preflight: (yearId: number) => request<PreflightResult>(`/years/${yearId}/preflight`),
77 +
78 + approve: (yearId: number, actor: string) => request<ApproveResult>(`/years/${yearId}/approve`, json({ actor })),
79 +
80 + unknownAccounts: (yearId: number) => request<UnknownAccountsResult>(`/years/${yearId}/unknown-accounts`),
81 +
82 + importMappings: (yearId: number, file: File) =>
83 + request<MappingImportResult>(`/years/${yearId}/mappings/import`, multipart(file)),
84 +
85 + exportMappingsUrl: (yearId: number) => `${BASE}/years/${yearId}/mappings/export`,
86 +
87 + exportStatementsUrl: (yearId: number, format: 'xlsx' | 'json') =>
88 + `${BASE}/years/${yearId}/statements/export?format=${format}`,
89 +
90 + listNotes: (yearId: number) =>
91 + request<{ notes: { note_id: number; note_number: string; title: string; statement: string; section: string }[] }>(
92 + `/years/${yearId}/notes`,
93 + ),
94 +
95 + listMappings: (yearId: number) =>
96 + request<{ mappings: { mapping_id: number; account_code: string; target_note_id: number; mapping_type: string }[] }>(
97 + `/years/${yearId}/mappings`,
98 + ),
99 +
100 + updateNote: (yearId: number, noteId: number, patch: { title?: string; note_number?: string; statement?: string; section?: string }) =>
101 + request<{ note_id: number; note_number: string; title: string }>(`/years/${yearId}/notes/${noteId}`, {
102 + method: 'PUT',
103 + headers: { 'Content-Type': 'application/json' },
104 + body: JSON.stringify(patch),
105 + }),
106 +
107 + deleteNote: (yearId: number, noteId: number) =>
108 + request<{ deleted: number }>(`/years/${yearId}/notes/${noteId}`, { method: 'DELETE' }),
109 +
110 + deleteMapping: (yearId: number, mappingId: number) =>
111 + request<{ deleted: number }>(`/years/${yearId}/mappings/${mappingId}`, { method: 'DELETE' }),
112 +
113 + login: (username: string, password: string) =>
114 + request<{ username: string; display_name: string; role: string }>('/auth/login', json({ username, password })),
115 +
116 + createUser: (username: string, password: string, role: string, actor: string) =>
117 + request<{ username: string; role: string }>('/users', json({ username, password, role, actor })),
118 +
119 + auditVerify: () => request<{ chain_valid: boolean }>('/audit/verify'),
120 +
121 + lockYear: (yearId: number, actor: string) =>
122 + request<{ year_id: number; status: string }>(`/years/${yearId}/lock`, json({ actor })),
123 +
124 + requestReopen: (yearId: number, reason: string, actor: string) =>
125 + request<{ request_id: number; status: string }>(`/years/${yearId}/reopen/request`, json({ reason, actor })),
126 +
127 + approveReopen: (requestId: number, actor: string) =>
128 + request<{ request_id: number; status: string }>(`/reopen/${requestId}/approve`, json({ actor })),
129 +
130 + reopenYear: (yearId: number, actor: string) =>
131 + request<{ year_id: number; status: string }>(`/years/${yearId}/reopen`, json({ actor })),
132 +
133 + backup: (dest: string, actor: string) =>
134 + request<{ dest: string; manifest: { audit_chain_valid: boolean } }>('/backup', json({ dest, actor })),
135 +
136 + verifyBackup: (dest: string, actor: string) =>
137 + request<{ valid: boolean; source_files: number; audit_entries: number }>('/backup/verify', json({ dest, actor })),
138 +}
frontend/src/api/types.ts new
+109
@@ -0,0 +1,109 @@
1 +export interface CompanyResult {
2 + company_id: number
3 + year_id: number
4 + year: number
5 + status: string
6 +}
7 +
8 +export interface LedgerImportResult {
9 + source_document_id: number
10 + file_hash: string
11 + import_version: number
12 + accounts_imported: number
13 + rows_for_year: number
14 +}
15 +
16 +export interface StatementLine {
17 + id: number
18 + line_order: number
19 + label: string
20 + mapped_total: string | null
21 + target_note_id: number | null
22 +}
23 +
24 +export interface Statement {
25 + id: number
26 + type: string
27 + label_fa: string
28 + version: number
29 + lines: StatementLine[]
30 +}
31 +
32 +export interface StatementsResult {
33 + statements: Statement[]
34 + section_labels_fa: Record<string, string>
35 +}
36 +
37 +export interface BuildResult {
38 + statements: { id: number; type: string; version: number }[]
39 + unmapped_accounts: string[]
40 +}
41 +
42 +export interface DrillDownAccount {
43 + account_full_code: string
44 + account_name: string
45 + closing: string
46 + statement_balance: string | null
47 + effective_balance: string
48 + source: {
49 + filename: string | null
50 + file_hash: string | null
51 + sheet: string | null
52 + row: number
53 + }
54 +}
55 +
56 +export interface DrillDownResult {
57 + line_id: number
58 + line_label: string
59 + mapped_total: string | null
60 + note: { id: number; note_number: string; title: string } | null
61 + accounts: DrillDownAccount[]
62 +}
63 +
64 +export interface ControlResult {
65 + code: string
66 + severity: string
67 + passed: boolean
68 + message_fa: string
69 +}
70 +
71 +export interface PreflightResult {
72 + year: number
73 + can_approve: boolean
74 + controls: ControlResult[]
75 +}
76 +
77 +export interface ApproveResult {
78 + approved: boolean
79 + status?: string
80 + blocking?: { code: string; message_fa: string }[]
81 +}
82 +
83 +export interface UnknownAccount {
84 + account_full_code: string
85 + account_name: string
86 + closing: string
87 + row_count: number
88 +}
89 +
90 +export interface UnknownAccountsResult {
91 + count: number
92 + accounts: UnknownAccount[]
93 +}
94 +
95 +export interface NoteResult {
96 + note_id: number
97 + note_number: string
98 +}
99 +
100 +export interface MappingResult {
101 + mapping_id: number
102 + account_code: string
103 +}
104 +
105 +export interface MappingImportResult {
106 + created: number
107 + notes_created: number
108 + errors: string[]
109 +}
frontend/src/components/AdminPanel.tsx new
+178
@@ -0,0 +1,178 @@
1 +import { useState } from 'react'
2 +import { api, ApiError } from '../api/client'
3 +
4 +interface Props {
5 + yearId: number
6 +}
7 +
8 +interface Session {
9 + username: string
10 + role: string
11 +}
12 +
13 +export default function AdminPanel({ yearId }: Props) {
14 + const [session, setSession] = useState<Session | null>(null)
15 + const [username, setUsername] = useState('')
16 + const [password, setPassword] = useState('')
17 + const [message, setMessage] = useState<string | null>(null)
18 + const [error, setError] = useState<string | null>(null)
19 + const [busy, setBusy] = useState(false)
20 + const [backupDest, setBackupDest] = useState('')
21 + const [reopenReason, setReopenReason] = useState('')
22 + const [lastRequestId, setLastRequestId] = useState<number | null>(null)
23 +
24 + async function run(fn: () => Promise<string>) {
25 + setBusy(true)
26 + setError(null)
27 + setMessage(null)
28 + try {
29 + setMessage(await fn())
30 + } catch (err) {
31 + setError(err instanceof ApiError ? err.message : String(err))
32 + } finally {
33 + setBusy(false)
34 + }
35 + }
36 +
37 + async function login(e: React.FormEvent) {
38 + e.preventDefault()
39 + setBusy(true)
40 + setError(null)
41 + try {
42 + const res = await api.login(username.trim(), password)
43 + setSession({ username: res.username, role: res.role })
44 + setPassword('')
45 + } catch (err) {
46 + setError(err instanceof ApiError ? err.message : String(err))
47 + } finally {
48 + setBusy(false)
49 + }
50 + }
51 +
52 + const actor = session?.username ?? ''
53 +
54 + return (
55 + <section className="card">
56 + <h2>مدیریت، ممیزی و پشتیبان‌گیری</h2>
57 +
58 + {!session ? (
59 + <form className="row" onSubmit={login}>
60 + <label>
61 + نام کاربری
62 + <input value={username} onChange={(e) => setUsername(e.target.value)} required />
63 + </label>
64 + <label>
65 + گذرواژه
66 + <input
67 + type="password"
68 + value={password}
69 + onChange={(e) => setPassword(e.target.value)}
70 + required
71 + />
72 + </label>
73 + <button type="submit" disabled={busy}>
74 + ورود
75 + </button>
76 + </form>
77 + ) : (
78 + <p className="ok">
79 + وارد شده: {session.username} ({session.role})
80 + </p>
81 + )}
82 +
83 + {session && (
84 + <>
85 + <div className="row">
86 + <button
87 + type="button"
88 + disabled={busy}
89 + onClick={() =>
90 + run(async () => {
91 + const r = await api.auditVerify()
92 + return r.chain_valid ? 'زنجیرهٔ ممیزی سالم است.' : 'زنجیرهٔ ممیزی مخدوش است!'
93 + })
94 + }
95 + >
96 + بررسی زنجیرهٔ ممیزی
97 + </button>
98 + <button
99 + type="button"
100 + disabled={busy}
101 + onClick={() => run(async () => `سال قفل شد: ${(await api.lockYear(yearId, actor)).status}`)}
102 + >
103 + قفل سال
104 + </button>
105 + </div>
106 +
107 + <div className="row">
108 + <label>
109 + دلیل بازگشایی
110 + <input value={reopenReason} onChange={(e) => setReopenReason(e.target.value)} />
111 + </label>
112 + <button
113 + type="button"
114 + disabled={busy || !reopenReason}
115 + onClick={() =>
116 + run(async () => {
117 + const r = await api.requestReopen(yearId, reopenReason, actor)
118 + setLastRequestId(r.request_id)
119 + return `درخواست بازگشایی ثبت شد (${r.request_id}).`
120 + })
121 + }
122 + >
123 + درخواست بازگشایی
124 + </button>
125 + <button
126 + type="button"
127 + disabled={busy || lastRequestId === null}
128 + onClick={() =>
129 + run(async () => {
130 + if (lastRequestId === null) return ''
131 + await api.approveReopen(lastRequestId, actor)
132 + const r = await api.reopenYear(yearId, actor)
133 + return `سال بازگشایی شد: ${r.status}`
134 + })
135 + }
136 + >
137 + تصویب و بازگشایی
138 + </button>
139 + </div>
140 +
141 + <div className="row">
142 + <label>
143 + مسیر پشتیبان
144 + <input value={backupDest} onChange={(e) => setBackupDest(e.target.value)} />
145 + </label>
146 + <button
147 + type="button"
148 + disabled={busy || !backupDest}
149 + onClick={() =>
150 + run(async () => {
151 + const r = await api.backup(backupDest, actor)
152 + return `پشتیبان ساخته شد (زنجیرهٔ ممیزی: ${r.manifest.audit_chain_valid ? 'سالم' : 'مخدوش'}).`
153 + })
154 + }
155 + >
156 + پشتیبان‌گیری
157 + </button>
158 + <button
159 + type="button"
160 + disabled={busy || !backupDest}
161 + onClick={() =>
162 + run(async () => {
163 + const r = await api.verifyBackup(backupDest, actor)
164 + return `پشتیبان ${r.valid ? 'سالم' : 'مخدوش'} است (${r.source_files} فایل، ${r.audit_entries} ممیزی).`
165 + })
166 + }
167 + >
168 + بررسی پشتیبان
169 + </button>
170 + </div>
171 + </>
172 + )}
173 +
174 + {message && <p className="ok">{message}</p>}
175 + {error && <p className="error">{error}</p>}
176 + </section>
177 + )
178 +}
frontend/src/components/ApprovalPanel.tsx new
+106
@@ -0,0 +1,106 @@
1 +import { useState } from 'react'
2 +import { api, ApiError } from '../api/client'
3 +import type { ApproveResult, PreflightResult } from '../api/types'
4 +
5 +interface Props {
6 + yearId: number
7 +}
8 +
9 +export default function ApprovalPanel({ yearId }: Props) {
10 + const [preflight, setPreflight] = useState<PreflightResult | null>(null)
11 + const [approveResult, setApproveResult] = useState<ApproveResult | null>(null)
12 + const [actor, setActor] = useState('')
13 + const [busy, setBusy] = useState(false)
14 + const [error, setError] = useState<string | null>(null)
15 +
16 + async function runPreflight() {
17 + setBusy(true)
18 + setError(null)
19 + try {
20 + setPreflight(await api.preflight(yearId))
21 + } catch (err) {
22 + setError(err instanceof ApiError ? err.message : String(err))
23 + } finally {
24 + setBusy(false)
25 + }
26 + }
27 +
28 + async function approve() {
29 + setBusy(true)
30 + setError(null)
31 + try {
32 + setApproveResult(await api.approve(yearId, actor.trim()))
33 + } catch (err) {
34 + setError(err instanceof ApiError ? err.message : String(err))
35 + } finally {
36 + setBusy(false)
37 + }
38 + }
39 +
40 + return (
41 + <section className="card">
42 + <h2>کنترل‌ها و تصویب</h2>
43 + <div className="row">
44 + <button type="button" onClick={runPreflight} disabled={busy}>
45 + اجرای کنترل‌ها
46 + </button>
47 + <label>
48 + تصویب‌کننده
49 + <input value={actor} onChange={(e) => setActor(e.target.value)} maxLength={128} />
50 + </label>
51 + <button type="button" onClick={approve} disabled={busy}>
52 + تصویب سال
53 + </button>
54 + </div>
55 +
56 + {preflight && (
57 + <div>
58 + <p className={preflight.can_approve ? 'ok' : 'error'}>
59 + {preflight.can_approve ? 'همهٔ کنترل‌های حیاتی قبول شدند.' : 'کنترل‌های حیاتی رد شدند — تصویب مسدود است.'}
60 + </p>
61 + <table>
62 + <thead>
63 + <tr>
64 + <th>کد</th>
65 + <th>شدت</th>
66 + <th>وضعیت</th>
67 + <th>پیام</th>
68 + </tr>
69 + </thead>
70 + <tbody>
71 + {preflight.controls.map((c) => (
72 + <tr key={c.code}>
73 + <td className="mono">{c.code}</td>
74 + <td>{c.severity}</td>
75 + <td className={c.passed ? 'ok' : 'error'}>{c.passed ? 'قبول' : 'رد'}</td>
76 + <td>{c.message_fa}</td>
77 + </tr>
78 + ))}
79 + </tbody>
80 + </table>
81 + </div>
82 + )}
83 +
84 + {approveResult && (
85 + <div>
86 + {approveResult.approved ? (
87 + <p className="ok">سال تصویب شد.</p>
88 + ) : (
89 + <div className="error">
90 + <p>تصویب مسدود شد:</p>
91 + <ul>
92 + {approveResult.blocking?.map((b) => (
93 + <li key={b.code}>
94 + {b.code}: {b.message_fa}
95 + </li>
96 + ))}
97 + </ul>
98 + </div>
99 + )}
100 + </div>
101 + )}
102 +
103 + {error && <p className="error">{error}</p>}
104 + </section>
105 + )
106 +}
frontend/src/components/CompanySetup.test.tsx new
+29
@@ -0,0 +1,29 @@
1 +import { fireEvent, render, screen, waitFor } from '@testing-library/react'
2 +import { describe, expect, it, vi } from 'vitest'
3 +import { api } from '../api/client'
4 +import CompanySetup from './CompanySetup'
5 +
6 +vi.mock('../api/client', async () => {
7 + const actual = await vi.importActual<typeof import('../api/client')>('../api/client')
8 + return { ...actual, api: { createCompany: vi.fn() } }
9 +})
10 +
11 +describe('CompanySetup', () => {
12 + it('creates a company and reports the result', async () => {
13 + vi.mocked(api.createCompany).mockResolvedValue({
14 + company_id: 1,
15 + year_id: 2,
16 + year: 1404,
17 + status: 'Draft',
18 + })
19 + const onCreated = vi.fn()
20 + render(<CompanySetup onCreated={onCreated} />)
21 +
22 + fireEvent.change(screen.getByLabelText('کد شرکت'), { target: { value: 'C1' } })
23 + fireEvent.change(screen.getByLabelText('نام شرکت'), { target: { value: 'شرکت نمونه' } })
24 + fireEvent.click(screen.getByRole('button', { name: 'ایجاد' }))
25 +
26 + await waitFor(() => expect(onCreated).toHaveBeenCalledWith(expect.objectContaining({ year_id: 2 })))
27 + expect(api.createCompany).toHaveBeenCalledWith('C1', 'شرکت نمونه', 1404)
28 + })
29 +})
frontend/src/components/CompanySetup.tsx new
+59
@@ -0,0 +1,59 @@
1 +import { useState } from 'react'
2 +import { api, ApiError } from '../api/client'
3 +import type { CompanyResult } from '../api/types'
4 +
5 +interface Props {
6 + onCreated: (result: CompanyResult) => void
7 +}
8 +
9 +export default function CompanySetup({ onCreated }: Props) {
10 + const [code, setCode] = useState('')
11 + const [name, setName] = useState('')
12 + const [year, setYear] = useState('1404')
13 + const [busy, setBusy] = useState(false)
14 + const [error, setError] = useState<string | null>(null)
15 +
16 + async function submit(e: React.FormEvent) {
17 + e.preventDefault()
18 + setBusy(true)
19 + setError(null)
20 + try {
21 + const result = await api.createCompany(code.trim(), name.trim(), Number(year))
22 + onCreated(result)
23 + } catch (err) {
24 + setError(err instanceof ApiError ? err.message : String(err))
25 + } finally {
26 + setBusy(false)
27 + }
28 + }
29 +
30 + return (
31 + <form className="card" onSubmit={submit}>
32 + <h2>شرکت و سال مالی</h2>
33 + <div className="row">
34 + <label>
35 + کد شرکت
36 + <input value={code} onChange={(e) => setCode(e.target.value)} required maxLength={64} />
37 + </label>
38 + <label>
39 + نام شرکت
40 + <input value={name} onChange={(e) => setName(e.target.value)} required maxLength={256} />
41 + </label>
42 + <label>
43 + سال مالی
44 + <input
45 + value={year}
46 + onChange={(e) => setYear(e.target.value)}
47 + required
48 + inputMode="numeric"
49 + pattern="[0-9]+"
50 + />
51 + </label>
52 + <button type="submit" disabled={busy}>
53 + {busy ? 'در حال ایجاد…' : 'ایجاد'}
54 + </button>
55 + </div>
56 + {error && <p className="error">{error}</p>}
57 + </form>
58 + )
59 +}
frontend/src/components/DrillDown.test.tsx new
+30
@@ -0,0 +1,30 @@
1 +import { render, screen } from '@testing-library/react'
2 +import { describe, expect, it, vi } from 'vitest'
3 +import type { DrillDownResult } from '../api/types'
4 +import DrillDown from './DrillDown'
5 +
6 +const result: DrillDownResult = {
7 + line_id: 1,
8 + line_label: '۱۰ — دارایی‌های جاری',
9 + mapped_total: '673740637',
10 + note: { id: 5, note_number: '10', title: 'دارایی‌های جاری' },
11 + accounts: [
12 + {
13 + account_full_code: '1101',
14 + account_name: 'نقد و بانک',
15 + closing: '0',
16 + statement_balance: '673740637',
17 + effective_balance: '673740637',
18 + source: { filename: 'source_1404.xlsx', file_hash: 'abc', sheet: 'Sheet1', row: 42 },
19 + },
20 + ],
21 +}
22 +
23 +describe('DrillDown', () => {
24 + it('renders the source file and row for traceability', () => {
25 + render(<DrillDown result={result} onClose={vi.fn()} />)
26 + expect(screen.getByText('source_1404.xlsx')).toBeInTheDocument()
27 + expect(screen.getByText('42')).toBeInTheDocument()
28 + expect(screen.getByText('نقد و بانک')).toBeInTheDocument()
29 + })
30 +})
frontend/src/components/DrillDown.tsx new
+55
@@ -0,0 +1,55 @@
1 +import type { DrillDownResult } from '../api/types'
2 +import { formatRial } from '../lib/format'
3 +
4 +interface Props {
5 + result: DrillDownResult
6 + onClose: () => void
7 +}
8 +
9 +export default function DrillDown({ result, onClose }: Props) {
10 + return (
11 + <div className="drilldown">
12 + <div className="row spread">
13 + <h3>
14 + ریشه‌یابی: {result.line_label}
15 + {result.note && <span className="muted"> — یادداشت {result.note.note_number}</span>}
16 + </h3>
17 + <button type="button" onClick={onClose}>
18 + بستن
19 + </button>
20 + </div>
21 + <p className="muted">مبلغ نگاشت‌شده: {formatRial(result.mapped_total)} ریال</p>
22 + <table>
23 + <thead>
24 + <tr>
25 + <th>کد حساب</th>
26 + <th>نام حساب</th>
27 + <th>مبلغ مؤثر (ریال)</th>
28 + <th>فایل منبع</th>
29 + <th>برگه</th>
30 + <th>ردیف</th>
31 + </tr>
32 + </thead>
33 + <tbody>
34 + {result.accounts.map((acc, i) => (
35 + <tr key={`${acc.account_full_code}-${acc.source.row}-${i}`}>
36 + <td className="mono">{acc.account_full_code}</td>
37 + <td>{acc.account_name}</td>
38 + <td className="num">{formatRial(acc.effective_balance)}</td>
39 + <td className="mono">{acc.source.filename ?? '—'}</td>
40 + <td>{acc.source.sheet ?? '—'}</td>
41 + <td className="num">{acc.source.row}</td>
42 + </tr>
43 + ))}
44 + {result.accounts.length === 0 && (
45 + <tr>
46 + <td colSpan={6} className="muted">
47 + حساب منبعی برای این خط یافت نشد.
48 + </td>
49 + </tr>
50 + )}
51 + </tbody>
52 + </table>
53 + </div>
54 + )
55 +}
frontend/src/components/LedgerUpload.tsx new
+51
@@ -0,0 +1,51 @@
1 +import { useRef, useState } from 'react'
2 +import { api, ApiError } from '../api/client'
3 +import type { LedgerImportResult } from '../api/types'
4 +import { faNumber } from '../lib/format'
5 +
6 +interface Props {
7 + yearId: number
8 + onImported: (result: LedgerImportResult) => void
9 +}
10 +
11 +export default function LedgerUpload({ yearId, onImported }: Props) {
12 + const inputRef = useRef<HTMLInputElement>(null)
13 + const [busy, setBusy] = useState(false)
14 + const [error, setError] = useState<string | null>(null)
15 + const [result, setResult] = useState<LedgerImportResult | null>(null)
16 +
17 + async function upload() {
18 + const file = inputRef.current?.files?.[0]
19 + if (!file) return
20 + setBusy(true)
21 + setError(null)
22 + try {
23 + const res = await api.uploadLedger(yearId, file)
24 + setResult(res)
25 + onImported(res)
26 + } catch (err) {
27 + setError(err instanceof ApiError ? err.message : String(err))
28 + } finally {
29 + setBusy(false)
30 + }
31 + }
32 +
33 + return (
34 + <section className="card">
35 + <h2>بارگذاری دفتر کل</h2>
36 + <div className="row">
37 + <input ref={inputRef} type="file" accept=".xlsx,.xls,.csv" />
38 + <button type="button" onClick={upload} disabled={busy}>
39 + {busy ? 'در حال درون‌ریزی…' : 'درون‌ریزی'}
40 + </button>
41 + </div>
42 + {result && (
43 + <p className="ok">
44 + {faNumber(result.rows_for_year)} ردیف سال جاری از {faNumber(result.accounts_imported)} حساب
45 + درون‌ریزی شد (نسخهٔ {faNumber(result.import_version)}).
46 + </p>
47 + )}
48 + {error && <p className="error">{error}</p>}
49 + </section>
50 + )
51 +}
frontend/src/components/MappingPanel.tsx new
+153
@@ -0,0 +1,153 @@
1 +import { useCallback, useEffect, useRef, useState } from 'react'
2 +import { api, ApiError } from '../api/client'
3 +import type { UnknownAccount } from '../api/types'
4 +import { faNumber, formatRial } from '../lib/format'
5 +
6 +interface Props {
7 + yearId: number
8 +}
9 +
10 +export default function MappingPanel({ yearId }: Props) {
11 + const [queue, setQueue] = useState<UnknownAccount[]>([])
12 + const [noteNumber, setNoteNumber] = useState('')
13 + const [noteTitle, setNoteTitle] = useState('')
14 + const [statement, setStatement] = useState('BS')
15 + const [section, setSection] = useState('Assets')
16 + const [targetCode, setTargetCode] = useState('')
17 + const [busy, setBusy] = useState(false)
18 + const [message, setMessage] = useState<string | null>(null)
19 + const [error, setError] = useState<string | null>(null)
20 + const importRef = useRef<HTMLInputElement>(null)
21 +
22 + const refresh = useCallback(async () => {
23 + try {
24 + const res = await api.unknownAccounts(yearId)
25 + setQueue(res.accounts)
26 + } catch (err) {
27 + setError(err instanceof ApiError ? err.message : String(err))
28 + }
29 + }, [yearId])
30 +
31 + useEffect(() => {
32 + void refresh()
33 + }, [refresh])
34 +
35 + async function mapAccount(code: string) {
36 + setBusy(true)
37 + setError(null)
38 + setMessage(null)
39 + try {
40 + const note = await api.createNote(yearId, noteNumber.trim(), noteTitle.trim(), statement, section)
41 + await api.createMapping(yearId, code, note.note_id)
42 + setMessage(`حساب ${code} به یادداشت ${noteNumber} نگاشت شد.`)
43 + await refresh()
44 + } catch (err) {
45 + setError(err instanceof ApiError ? err.message : String(err))
46 + } finally {
47 + setBusy(false)
48 + }
49 + }
50 +
51 + async function importMappings() {
52 + const file = importRef.current?.files?.[0]
53 + if (!file) return
54 + setBusy(true)
55 + setError(null)
56 + try {
57 + const res = await api.importMappings(yearId, file)
58 + setMessage(`${faNumber(res.created)} نگاشت و ${faNumber(res.notes_created)} یادداشت ایجاد شد.`)
59 + if (res.errors.length) setError(res.errors.join('؛ '))
60 + await refresh()
61 + } catch (err) {
62 + setError(err instanceof ApiError ? err.message : String(err))
63 + } finally {
64 + setBusy(false)
65 + }
66 + }
67 +
68 + return (
69 + <section className="card">
70 + <h2>نگاشت حساب‌ها به یادداشت‌ها</h2>
71 +
72 + <div className="row">
73 + <label>
74 + شمارهٔ یادداشت
75 + <input value={noteNumber} onChange={(e) => setNoteNumber(e.target.value)} />
76 + </label>
77 + <label>
78 + عنوان یادداشت
79 + <input value={noteTitle} onChange={(e) => setNoteTitle(e.target.value)} />
80 + </label>
81 + <label>
82 + صورت مالی
83 + <select value={statement} onChange={(e) => setStatement(e.target.value)}>
84 + <option value="BS">ترازنامه</option>
85 + <option value="IS">سود و زیان</option>
86 + <option value="CF">جریان‌های نقدی</option>
87 + <option value="EQ">حقوق مالکانه</option>
88 + </select>
89 + </label>
90 + <label>
91 + بخش
92 + <input value={section} onChange={(e) => setSection(e.target.value)} />
93 + </label>
94 + </div>
95 +
96 + <div className="row">
97 + <input ref={importRef} type="file" accept=".xlsx" />
98 + <button type="button" onClick={importMappings} disabled={busy}>
99 + درون‌ریزی نگاشت‌ها
100 + </button>
101 + <a className="button" href={api.exportMappingsUrl(yearId)} download>
102 + برون‌بری نگاشت‌ها
103 + </a>
104 + </div>
105 +
106 + {message && <p className="ok">{message}</p>}
107 + {error && <p className="error">{error}</p>}
108 +
109 + <h3>صف حساب‌های نگاشت‌نشده ({faNumber(queue.length)})</h3>
110 + <table>
111 + <thead>
112 + <tr>
113 + <th>کد حساب</th>
114 + <th>نام حساب</th>
115 + <th>مانده (ریال)</th>
116 + <th>ردیف‌ها</th>
117 + <th>عملیات</th>
118 + </tr>
119 + </thead>
120 + <tbody>
121 + {queue.map((acc) => (
122 + <tr key={acc.account_full_code}>
123 + <td className="mono">{acc.account_full_code}</td>
124 + <td>{acc.account_name}</td>
125 + <td className="num">{formatRial(acc.closing)}</td>
126 + <td className="num">{faNumber(acc.row_count)}</td>
127 + <td>
128 + <button
129 + type="button"
130 + disabled={busy || !noteNumber || !noteTitle}
131 + onClick={() => {
132 + setTargetCode(acc.account_full_code)
133 + void mapAccount(acc.account_full_code)
134 + }}
135 + >
136 + نگاشت به یادداشت بالا
137 + </button>
138 + {targetCode === acc.account_full_code && <span className="muted"> ✓</span>}
139 + </td>
140 + </tr>
141 + ))}
142 + {queue.length === 0 && (
143 + <tr>
144 + <td colSpan={5} className="muted">
145 + حساب نگاشت‌نشده‌ای وجود ندارد.
146 + </td>
147 + </tr>
148 + )}
149 + </tbody>
150 + </table>
151 + </section>
152 + )
153 +}
frontend/src/components/NotesManager.tsx new
+157
@@ -0,0 +1,157 @@
1 +import { useCallback, useEffect, useState } from 'react'
2 +import { api, ApiError } from '../api/client'
3 +import { faNumber } from '../lib/format'
4 +
5 +interface Props {
6 + yearId: number
7 + refreshKey: number
8 +}
9 +
10 +interface NoteRow {
11 + note_id: number
12 + note_number: string
13 + title: string
14 + statement: string
15 + section: string
16 +}
17 +
18 +interface MappingRow {
19 + mapping_id: number
20 + account_code: string
21 + target_note_id: number
22 + mapping_type: string
23 +}
24 +
25 +export default function NotesManager({ yearId, refreshKey }: Props) {
26 + const [notes, setNotes] = useState<NoteRow[]>([])
27 + const [mappings, setMappings] = useState<MappingRow[]>([])
28 + const [edits, setEdits] = useState<Record<number, string>>({})
29 + const [error, setError] = useState<string | null>(null)
30 + const [message, setMessage] = useState<string | null>(null)
31 +
32 + const load = useCallback(async () => {
33 + try {
34 + const [n, m] = await Promise.all([api.listNotes(yearId), api.listMappings(yearId)])
35 + setNotes(n.notes)
36 + setMappings(m.mappings)
37 + } catch (err) {
38 + setError(err instanceof ApiError ? err.message : String(err))
39 + }
40 + }, [yearId])
41 +
42 + useEffect(() => {
43 + void load()
44 + }, [load, refreshKey])
45 +
46 + async function act(fn: () => Promise<unknown>, ok: string) {
47 + setError(null)
48 + setMessage(null)
49 + try {
50 + await fn()
51 + setMessage(ok)
52 + await load()
53 + } catch (err) {
54 + setError(err instanceof ApiError ? err.message : String(err))
55 + }
56 + }
57 +
58 + const noteNumber = (id: number) => notes.find((n) => n.note_id === id)?.note_number ?? String(id)
59 +
60 + return (
61 + <section className="card">
62 + <h2>مدیریت یادداشت‌ها و نگاشت‌ها</h2>
63 + {message && <p className="ok">{message}</p>}
64 + {error && <p className="error">{error}</p>}
65 +
66 + <h3>یادداشت‌ها ({faNumber(notes.length)})</h3>
67 + <table>
68 + <thead>
69 + <tr>
70 + <th>شماره</th>
71 + <th>عنوان</th>
72 + <th>صورت/بخش</th>
73 + <th>عملیات</th>
74 + </tr>
75 + </thead>
76 + <tbody>
77 + {notes.map((n) => (
78 + <tr key={n.note_id}>
79 + <td className="mono">{n.note_number}</td>
80 + <td>
81 + <input
82 + value={edits[n.note_id] ?? n.title}
83 + onChange={(e) => setEdits((s) => ({ ...s, [n.note_id]: e.target.value }))}
84 + />
85 + </td>
86 + <td className="muted">
87 + {n.statement}/{n.section}
88 + </td>
89 + <td>
90 + <button
91 + type="button"
92 + onClick={() =>
93 + act(
94 + () => api.updateNote(yearId, n.note_id, { title: edits[n.note_id] ?? n.title }),
95 + 'عنوان یادداشت به‌روز شد.',
96 + )
97 + }
98 + >
99 + ذخیره
100 + </button>{' '}
101 + <button
102 + type="button"
103 + onClick={() => act(() => api.deleteNote(yearId, n.note_id), 'یادداشت حذف شد.')}
104 + >
105 + حذف
106 + </button>
107 + </td>
108 + </tr>
109 + ))}
110 + {notes.length === 0 && (
111 + <tr>
112 + <td colSpan={4} className="muted">
113 + یادداشتی وجود ندارد.
114 + </td>
115 + </tr>
116 + )}
117 + </tbody>
118 + </table>
119 +
120 + <h3>نگاشت‌ها ({faNumber(mappings.length)})</h3>
121 + <table>
122 + <thead>
123 + <tr>
124 + <th>کد حساب</th>
125 + <th>یادداشت مقصد</th>
126 + <th>نوع</th>
127 + <th>عملیات</th>
128 + </tr>
129 + </thead>
130 + <tbody>
131 + {mappings.map((m) => (
132 + <tr key={m.mapping_id}>
133 + <td className="mono">{m.account_code}</td>
134 + <td>{noteNumber(m.target_note_id)}</td>
135 + <td className="muted">{m.mapping_type}</td>
136 + <td>
137 + <button
138 + type="button"
139 + onClick={() => act(() => api.deleteMapping(yearId, m.mapping_id), 'نگاشت حذف شد.')}
140 + >
141 + حذف
142 + </button>
143 + </td>
144 + </tr>
145 + ))}
146 + {mappings.length === 0 && (
147 + <tr>
148 + <td colSpan={4} className="muted">
149 + نگاشتی وجود ندارد.
150 + </td>
151 + </tr>
152 + )}
153 + </tbody>
154 + </table>
155 + </section>
156 + )
157 +}
frontend/src/components/StatementView.tsx new
+129
@@ -0,0 +1,129 @@
1 +import { useCallback, useEffect, useState } from 'react'
2 +import { api, ApiError } from '../api/client'
3 +import type { DrillDownResult, Statement } from '../api/types'
4 +import { faNumber, formatRial } from '../lib/format'
5 +import DrillDown from './DrillDown'
6 +
7 +interface Props {
8 + yearId: number
9 + refreshKey: number
10 +}
11 +
12 +export default function StatementView({ yearId, refreshKey }: Props) {
13 + const [statements, setStatements] = useState<Statement[]>([])
14 + const [active, setActive] = useState<string>('BS')
15 + const [busy, setBusy] = useState(false)
16 + const [error, setError] = useState<string | null>(null)
17 + const [unmapped, setUnmapped] = useState<string[]>([])
18 + const [drill, setDrill] = useState<DrillDownResult | null>(null)
19 +
20 + const load = useCallback(async () => {
21 + try {
22 + const res = await api.listStatements(yearId)
23 + setStatements(res.statements)
24 + } catch (err) {
25 + setError(err instanceof ApiError ? err.message : String(err))
26 + }
27 + }, [yearId])
28 +
29 + useEffect(() => {
30 + void load()
31 + }, [load, refreshKey])
32 +
33 + async function build() {
34 + setBusy(true)
35 + setError(null)
36 + try {
37 + const res = await api.buildStatements(yearId)
38 + setUnmapped(res.unmapped_accounts)
39 + await load()
40 + } catch (err) {
41 + setError(err instanceof ApiError ? err.message : String(err))
42 + } finally {
43 + setBusy(false)
44 + }
45 + }
46 +
47 + async function openDrill(lineId: number) {
48 + setError(null)
49 + try {
50 + setDrill(await api.drillDown(lineId))
51 + } catch (err) {
52 + setError(err instanceof ApiError ? err.message : String(err))
53 + }
54 + }
55 +
56 + const current = statements.find((s) => s.type === active)
57 +
58 + return (
59 + <section className="card">
60 + <h2>صورت‌های مالی</h2>
61 + <div className="row">
62 + <button type="button" onClick={build} disabled={busy}>
63 + {busy ? 'در حال ساخت…' : 'ساخت صورت‌های مالی'}
64 + </button>
65 + <a className="button" href={api.exportStatementsUrl(yearId, 'xlsx')} download>
66 + خروجی اکسل
67 + </a>
68 + <a className="button" href={api.exportStatementsUrl(yearId, 'json')} download>
69 + خروجی JSON
70 + </a>
71 + <div className="tabs">
72 + {['BS', 'IS', 'CF', 'EQ'].map((t) => (
73 + <button
74 + key={t}
75 + type="button"
76 + className={active === t ? 'tab active' : 'tab'}
77 + onClick={() => setActive(t)}
78 + >
79 + {t}
80 + </button>
81 + ))}
82 + </div>
83 + </div>
84 +
85 + {unmapped.length > 0 && (
86 + <p className="error">حساب‌های نگاشت‌نشده: {unmapped.join('، ')}</p>
87 + )}
88 + {error && <p className="error">{error}</p>}
89 +
90 + {current ? (
91 + <table>
92 + <thead>
93 + <tr>
94 + <th>ردیف</th>
95 + <th>شرح</th>
96 + <th>مبلغ (ریال)</th>
97 + <th>ریشه‌یابی</th>
98 + </tr>
99 + </thead>
100 + <tbody>
101 + {current.lines.map((line) => (
102 + <tr key={line.id}>
103 + <td className="num">{faNumber(line.line_order)}</td>
104 + <td>{line.label}</td>
105 + <td className="num">{formatRial(line.mapped_total)}</td>
106 + <td>
107 + <button type="button" onClick={() => void openDrill(line.id)}>
108 + مشاهدهٔ منبع
109 + </button>
110 + </td>
111 + </tr>
112 + ))}
113 + {current.lines.length === 0 && (
114 + <tr>
115 + <td colSpan={4} className="muted">
116 + این صورت هنوز ساخته نشده است.
117 + </td>
118 + </tr>
119 + )}
120 + </tbody>
121 + </table>
122 + ) : (
123 + <p className="muted">صورتی برای نمایش وجود ندارد؛ ابتدا «ساخت صورت‌های مالی» را بزنید.</p>
124 + )}
125 +
126 + {drill && <DrillDown result={drill} onClose={() => setDrill(null)} />}
127 + </section>
128 + )
129 +}
frontend/src/index.css new
+169
@@ -0,0 +1,169 @@
1 +:root {
2 + font-family: Vazirmatn, system-ui, -apple-system, sans-serif;
3 + direction: rtl;
4 + color-scheme: light;
5 + --border: #d4dae2;
6 + --muted: #6b7684;
7 + --ok: #1a7f4b;
8 + --error: #b3261e;
9 + --accent: #2456a6;
10 +}
11 +
12 +* {
13 + box-sizing: border-box;
14 +}
15 +
16 +body {
17 + margin: 0;
18 + background: #f4f6f8;
19 + color: #1c2430;
20 + line-height: 1.7;
21 +}
22 +
23 +.app {
24 + max-width: 1080px;
25 + margin: 0 auto;
26 + padding: 1.5rem 1.25rem 4rem;
27 +}
28 +
29 +.app-header h1 {
30 + margin: 0 0 0.25rem;
31 + font-size: 1.5rem;
32 +}
33 +
34 +.card {
35 + background: #fff;
36 + border: 1px solid var(--border);
37 + border-radius: 0.75rem;
38 + padding: 1.25rem;
39 + margin: 1rem 0;
40 +}
41 +
42 +.card h2 {
43 + margin: 0 0 0.75rem;
44 + font-size: 1.15rem;
45 +}
46 +
47 +.card h3 {
48 + margin: 1rem 0 0.5rem;
49 + font-size: 1rem;
50 +}
51 +
52 +.row {
53 + display: flex;
54 + flex-wrap: wrap;
55 + gap: 0.75rem;
56 + align-items: flex-end;
57 + margin-bottom: 0.75rem;
58 +}
59 +
60 +.row.spread {
61 + justify-content: space-between;
62 +}
63 +
64 +label {
65 + display: flex;
66 + flex-direction: column;
67 + gap: 0.25rem;
68 + font-size: 0.85rem;
69 + color: var(--muted);
70 +}
71 +
72 +input,
73 +select {
74 + font: inherit;
75 + padding: 0.45rem 0.6rem;
76 + border: 1px solid var(--border);
77 + border-radius: 0.5rem;
78 + background: #fff;
79 + min-width: 8rem;
80 +}
81 +
82 +button,
83 +.button {
84 + font: inherit;
85 + padding: 0.5rem 1rem;
86 + border-radius: 0.5rem;
87 + border: 1px solid var(--accent);
88 + background: var(--accent);
89 + color: #fff;
90 + cursor: pointer;
91 + text-decoration: none;
92 + display: inline-block;
93 +}
94 +
95 +button:disabled {
96 + opacity: 0.5;
97 + cursor: not-allowed;
98 +}
99 +
100 +.button {
101 + background: #fff;
102 + color: var(--accent);
103 +}
104 +
105 +.tabs {
106 + display: flex;
107 + gap: 0.25rem;
108 +}
109 +
110 +.tab {
111 + background: #fff;
112 + color: var(--accent);
113 + border: 1px solid var(--border);
114 +}
115 +
116 +.tab.active {
117 + background: var(--accent);
118 + color: #fff;
119 +}
120 +
121 +table {
122 + width: 100%;
123 + border-collapse: collapse;
124 + margin-top: 0.5rem;
125 + font-size: 0.9rem;
126 +}
127 +
128 +th,
129 +td {
130 + border: 1px solid var(--border);
131 + padding: 0.4rem 0.6rem;
132 + text-align: right;
133 +}
134 +
135 +th {
136 + background: #eef1f5;
137 +}
138 +
139 +.num {
140 + text-align: left;
141 + font-variant-numeric: tabular-nums;
142 + direction: ltr;
143 +}
144 +
145 +.mono {
146 + font-family: ui-monospace, monospace;
147 + direction: ltr;
148 + text-align: left;
149 +}
150 +
151 +.muted {
152 + color: var(--muted);
153 +}
154 +
155 +.ok {
156 + color: var(--ok);
157 +}
158 +
159 +.error {
160 + color: var(--error);
161 +}
162 +
163 +.drilldown {
164 + margin-top: 1rem;
165 + border: 1px dashed var(--accent);
166 + border-radius: 0.5rem;
167 + padding: 1rem;
168 + background: #f8faff;
169 +}
frontend/src/lib/format.test.ts new
+29
@@ -0,0 +1,29 @@
1 +import { describe, expect, it } from 'vitest'
2 +import { faNumber, formatRial } from './format'
3 +
4 +describe('formatRial', () => {
5 + it('returns a dash for empty values', () => {
6 + expect(formatRial(null)).toBe('—')
7 + expect(formatRial(undefined)).toBe('—')
8 + expect(formatRial('')).toBe('—')
9 + })
10 +
11 + it('groups thousands with Persian digits', () => {
12 + const out = formatRial('1234567')
13 + // fa-IR renders Persian digits (۱۲۳۵۶۷) with the ٬ separator.
14 + expect(out).toContain('۱')
15 + expect(out).toContain('۲۳')
16 + expect(out).toContain('۵۶')
17 + expect(out).not.toContain('1234567')
18 + })
19 +
20 + it('passes through non-numeric strings', () => {
21 + expect(formatRial('abc')).toBe('abc')
22 + })
23 +})
24 +
25 +describe('faNumber', () => {
26 + it('renders an integer without grouping', () => {
27 + expect(faNumber(1404)).toHaveLength(4)
28 + })
29 +})
frontend/src/lib/format.ts new
+12
@@ -0,0 +1,12 @@
1 +/** Format an exact integer-rial string with Persian-locale thousands separators. */
2 +export function formatRial(value: string | null | undefined): string {
3 + if (value === null || value === undefined || value === '') return '—'
4 + const n = Number(value)
5 + if (!Number.isFinite(n)) return value
6 + return n.toLocaleString('fa-IR')
7 +}
8 +
9 +/** Persian digits for a plain integer (counts, years). */
10 +export function faNumber(value: number): string {
11 + return value.toLocaleString('fa-IR', { useGrouping: false })
12 +}
frontend/src/main.tsx new
+13
@@ -0,0 +1,13 @@
1 +import { StrictMode } from 'react'
2 +import { createRoot } from 'react-dom/client'
3 +import App from './App'
4 +import './index.css'
5 +
6 +const root = document.getElementById('root')
7 +if (root) {
8 + createRoot(root).render(
9 + <StrictMode>
10 + <App />
11 + </StrictMode>,
12 + )
13 +}
frontend/src/setupTests.ts new
+1
@@ -0,0 +1 @@
1 +import '@testing-library/jest-dom'
frontend/src/vite-env.d.ts new
+1
@@ -0,0 +1 @@
1 +/// <reference types="vite/client" />
frontend/tsconfig.json new
+1
@@ -0,0 +1 @@
1 +{"compilerOptions": {"target": "ES2022", "useDefineForClassFields": true, "lib": ["ES2022", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "moduleDetection": "force", "noEmit": true, "jsx": "react-jsx", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "types": ["vitest/globals", "@testing-library/jest-dom", "node"]}, "include": ["src", "vite.config.ts", "playwright.config.ts", "e2e"]}
\ No newline at end of file
frontend/vite.config.ts new
+25
@@ -0,0 +1,25 @@
1 +import react from '@vitejs/plugin-react'
2 +import { defineConfig } from 'vitest/config'
3 +
4 +export default defineConfig({
5 + plugins: [react()],
6 + server: {
7 + host: '127.0.0.1',
8 + port: 5173,
9 + // Allow the Arena live-preview proxy host (and any host in dev).
10 + allowedHosts: true,
11 + proxy: {
12 + // Browser-facing code uses relative /api URLs; the dev server forwards
13 + // them to the FastAPI backend (never localhost from the browser).
14 + '/api': { target: 'http://127.0.0.1:8000', changeOrigin: true },
15 + },
16 + },
17 + test: {
18 + environment: 'jsdom',
19 + globals: true,
20 + setupFiles: ['./src/setupTests.ts'],
21 + css: false,
22 + include: ['src/**/*.{test,spec}.{ts,tsx}'],
23 + exclude: ['node_modules', 'dist', 'e2e/**'],
24 + },
25 +})
packaging/README.md new
+47
@@ -0,0 +1,47 @@
1 +# Aram desktop packaging (Phase 8)
2 +
3 +Offline Windows desktop app: FastAPI backend + bundled React workbench on
4 +`127.0.0.1` only, local SQLite + content-addressed source store, zero runtime
5 +network. See `docs/adr/ADR-024-desktop-packaging.md`.
6 +
7 +## Build (reproducible)
8 +
9 +On Windows (for the Windows package):
10 +
11 +```bat
12 +python packaging\build_desktop.py
13 +```
14 +
15 +This builds `frontend/dist` (npm ci + build) and runs PyInstaller with
16 +`packaging/aram.spec`, producing `dist\Aram\Aram.exe`.
17 +
18 +Options:
19 +
20 +```bat
21 +python packaging\build_desktop.py --skip-frontend :: reuse existing frontend/dist
22 +python packaging\build_desktop.py --skip-pyinstaller :: only build the frontend
23 +```
24 +
25 +Manual PyInstaller (after the frontend is built):
26 +
27 +```bat
28 +pip install pyinstaller
29 +pyinstaller packaging\aram.spec --noconfirm
30 +```
31 +
32 +## Run
33 +
34 +```bat
35 +dist\Aram\Aram.exe
36 +```
37 +
38 +Then open `http://127.0.0.1:8765/`. Data lives under `%APPDATA%\Aram`
39 +(override with `ARAM_DATA_DIR`; port with `ARAM_PORT`).
40 +
41 +## Notes
42 +
43 +- The executable/ZIP is a **build artifact** and is never committed (booklet §19).
44 + CI/release builds it from this recipe; the spec + build script are the reviewable
45 + source of truth.
46 +- Loopback-only binding; no network interface is exposed.
47 +- First launch creates the schema + immutability triggers idempotently.
packaging/aram.spec new
+95
@@ -0,0 +1,95 @@
1 +# -*- mode: python ; coding: utf-8 -*-
2 +"""PyInstaller spec for the Aram offline desktop app (Phase 8, ADR-024).
3 +
4 +Build (from the repo root, after `python packaging/build_desktop.py` prepares
5 +frontend/dist):
6 +
7 + pyinstaller packaging/aram.spec --noconfirm
8 +
9 +Produces a one-folder Windows package `dist/Aram/` whose `Aram.exe` runs the
10 +FastAPI backend + bundled React workbench on 127.0.0.1 only. No runtime network.
11 +The binary is a build artifact and is NOT committed (booklet §19); CI/release
12 +builds it from this reproducible recipe.
13 +"""
14 +
15 +import sys
16 +from pathlib import Path
17 +
18 +from PyInstaller.utils.hooks import collect_data_files, collect_submodules
19 +
20 +ROOT = Path(SPECPATH).resolve().parent
21 +BACKEND_SRC = ROOT / "backend" / "src"
22 +FRONTEND_DIST = ROOT / "frontend" / "dist"
23 +
24 +block_cipher = None
25 +
26 +# Bundle the built React workbench as frontend_dist (served at / by desktop.py).
27 +datas = []
28 +if FRONTEND_DIST.exists():
29 + datas.append((str(FRONTEND_DIST), "frontend_dist"))
30 +# Bundle Alembic migrations + config for upgrade paths.
31 +migrations = ROOT / "backend" / "migrations"
32 +if migrations.exists():
33 + datas.append((str(migrations), "migrations"))
34 +alembic_ini = ROOT / "backend" / "alembic.ini"
35 +if alembic_ini.exists():
36 + datas.append((str(alembic_ini), "."))
37 +# openpyxl / sqlalchemy / uvicorn data files.
38 +datas += collect_data_files("openpyxl")
39 +datas += collect_data_files("uvicorn")
40 +
41 +hiddenimports = []
42 +hiddenimports += collect_submodules("aram_backend")
43 +hiddenimports += collect_submodules("sqlalchemy")
44 +hiddenimports += collect_submodules("uvicorn")
45 +hiddenimports += [
46 + "sqlalchemy.dialects.sqlite",
47 + "sqlite3",
48 + "multipart",
49 + "python_multipart",
50 +]
51 +
52 +a = Analysis(
53 + [str(BACKEND_SRC / "aram_backend" / "desktop.py")],
54 + pathex=[str(BACKEND_SRC)],
55 + binaries=[],
56 + datas=datas,
57 + hiddenimports=hiddenimports,
58 + hookspath=[],
59 + hooksconfig={},
60 + runtime_hooks=[],
61 + excludes=["tkinter", "pytest", "hypothesis", "mypy", "ruff"],
62 + win_no_prefer_redirects=False,
63 + win_private_assemblies=False,
64 + cipher=block_cipher,
65 + noarchive=False,
66 +)
67 +pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
68 +
69 +exe = EXE(
70 + pyz,
71 + a.scripts,
72 + [],
73 + exclude_binaries=True,
74 + name="Aram",
75 + debug=False,
76 + bootloader_ignore_signals=False,
77 + strip=False,
78 + upx=False,
79 + console=True, # keep logs visible for review; flip to False for a windowed build
80 + disable_windowed_traceback=False,
81 + argv_emulation=False,
82 + target_arch=None,
83 + codesign_identity=None,
84 + entitlements_file=None,
85 +)
86 +coll = COLLECT(
87 + exe,
88 + a.binaries,
89 + a.zipfiles,
90 + a.datas,
91 + strip=False,
92 + upx=False,
93 + upx_exclude=[],
94 + name="Aram",
95 +)
packaging/build_desktop.py new
+68
@@ -0,0 +1,68 @@
1 +#!/usr/bin/env python3
2 +"""Reproducible desktop build (Phase 8, ADR-024).
3 +
4 +Steps:
5 + 1. Build the React workbench (frontend/dist) with npm.
6 + 2. Run PyInstaller with packaging/aram.spec to produce dist/Aram/.
7 +
8 +Run on Windows to produce the Windows package (Aram.exe). The binary is a build
9 +artifact and is never committed (booklet §19). Use --skip-frontend to reuse an
10 +existing frontend/dist, and --skip-pyinstaller to only build the frontend.
11 +
12 +Usage:
13 + python packaging/build_desktop.py
14 + python packaging/build_desktop.py --skip-frontend
15 +"""
16 +
17 +from __future__ import annotations
18 +
19 +import argparse
20 +import shutil
21 +import subprocess
22 +import sys
23 +from pathlib import Path
24 +
25 +ROOT = Path(__file__).resolve().parents[1]
26 +FRONTEND = ROOT / "frontend"
27 +SPEC = ROOT / "packaging" / "aram.spec"
28 +
29 +
30 +def _run(cmd: list[str], cwd: Path) -> None:
31 + print("+", " ".join(cmd), flush=True)
32 + subprocess.run(cmd, cwd=cwd, check=True)
33 +
34 +
35 +def build_frontend() -> None:
36 + npm = shutil.which("npm")
37 + if npm is None:
38 + raise SystemExit("npm is required to build the frontend")
39 + _run([npm, "ci", "--no-audit", "--no-fund"], FRONTEND)
40 + _run([npm, "run", "build"], FRONTEND)
41 + if not (FRONTEND / "dist" / "index.html").exists():
42 + raise SystemExit("frontend build did not produce dist/index.html")
43 +
44 +
45 +def build_package() -> None:
46 + pyinstaller = shutil.which("pyinstaller")
47 + if pyinstaller is None:
48 + raise SystemExit("pyinstaller is required (pip install pyinstaller)")
49 + _run([pyinstaller, str(SPEC), "--noconfirm"], ROOT)
50 + out = ROOT / "dist" / "Aram"
51 + print(f"Package built: {out}")
52 + if sys.platform == "win32":
53 + print(f"Windows executable: {out / 'Aram.exe'}")
54 +
55 +
56 +def main() -> None:
57 + parser = argparse.ArgumentParser(description=__doc__)
58 + parser.add_argument("--skip-frontend", action="store_true")
59 + parser.add_argument("--skip-pyinstaller", action="store_true")
60 + args = parser.parse_args()
61 + if not args.skip_frontend:
62 + build_frontend()
63 + if not args.skip_pyinstaller:
64 + build_package()
65 +
66 +
67 +if __name__ == "__main__":
68 + main()
scripts/build_webapp.py new
+51
@@ -0,0 +1,51 @@
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()
scripts/uat_real_data.py new
+218
@@ -0,0 +1,218 @@
1 +#!/usr/bin/env python3
2 +"""Phase 9 user-acceptance test against the real 1404 ledger (booklet §15/§18).
3 +
4 +Exercises the full persistent pipeline end-to-end on canonical source data and
5 +records reviewable evidence:
6 +
7 + 1. Initialize a fresh local SQLite DB (schema + D-07 triggers).
8 + 2. Register + tolerant-import source_1404.xlsx (raw rows preserved).
9 + 3. Auto-map accounts to their embedded note numbers (source column یادداشت کل).
10 + 4. Build BS/IS/CF/EQ from the persisted ledger + mappings.
11 + 5. Reconcile the built balance sheet against the official workbook (golden).
12 + 6. Run the approval controls (the gate blocks while accounts are unmapped).
13 + 7. Export XLSX + JSON; create + verify a backup; verify the audit chain.
14 +
15 +Writes a JSON report (path printed) and a human summary. Read-only on source data;
16 +the report is evidence, not a committed financial artifact. No network.
17 +
18 +Usage: python scripts/uat_real_data.py [--year 1404] [--out /tmp/aram-uat]
19 +"""
20 +
21 +from __future__ import annotations
22 +
23 +import argparse
24 +import json
25 +import sys
26 +import tempfile
27 +from decimal import Decimal
28 +from pathlib import Path
29 +
30 +ROOT = Path(__file__).resolve().parents[1]
31 +sys.path.insert(0, str(ROOT / "backend" / "src"))
32 +
33 +from openpyxl import load_workbook # noqa: E402
34 +
35 +from aram_backend.database import Base, build_engine, ensure_triggers # noqa: E402
36 +from aram_backend.domain.hierarchy import canonical_full_code, ledger_to_pilot # noqa: E402
37 +from aram_backend.domain.normalization import normalize_fa # noqa: E402
38 +from aram_backend.ingestion import register_source_document # noqa: E402
39 +from aram_backend.ledger_parser import parse_ledger # noqa: E402
40 +from aram_backend.models import ( # noqa: E402
41 + Company,
42 + FiscalYear,
43 + MappingRule,
44 + NoteDefinition,
45 +)
46 +from aram_backend.services.approval import approve_year # noqa: E402
47 +from aram_backend.services.audit import verify_chain # noqa: E402
48 +from aram_backend.services.backup import create_backup, verify_backup # noqa: E402
49 +from aram_backend.services.golden import compare_year # noqa: E402
50 +from aram_backend.services.ledger_import import import_ledger_balances # noqa: E402
51 +from aram_backend.services.source_store import SourceStore # noqa: E402
52 +from aram_backend.services.statement_build import build_statements # noqa: E402
53 +from aram_backend.services.statement_export import ( # noqa: E402
54 + export_statements_json,
55 + export_statements_workbook,
56 +)
57 +from sqlalchemy.orm import sessionmaker # noqa: E402
58 +
59 +_MILLION = Decimal(1_000_000)
60 +
61 +
62 +def _source_note_map(source_path: Path, year: int) -> dict[str, set[str]]:
63 + """note number -> set of canonical account codes, from the embedded mapping."""
64 + wb = load_workbook(source_path, read_only=True, data_only=True, keep_links=False)
65 + try:
66 + ws = wb["Source"]
67 + rows = ws.iter_rows(values_only=True)
68 + next(rows) # title row
69 + header = next(rows)
70 + idx = {normalize_fa(str(h)): i for i, h in enumerate(header) if h is not None}
71 + note_i = idx.get(normalize_fa("یادداشت کل"))
72 + year_i = idx.get(normalize_fa("year"))
73 + kol_i = idx.get(normalize_fa("kol"))
74 + hesab_i = idx.get(normalize_fa("حساب"))
75 + t1_i = idx.get(normalize_fa("T1_CODE"))
76 + t2_i = idx.get(normalize_fa("T2_CODE"))
77 + t3_i = idx.get(normalize_fa("T3_CODE"))
78 + t4_i = idx.get(normalize_fa("T4_CODE"))
79 + mapping: dict[str, set[str]] = {}
80 +
81 + def cell(vals, i):
82 + return vals[i] if i is not None and i < len(vals) else None
83 +
84 + for vals in rows:
85 + if not any(v is not None for v in vals):
86 + continue
87 + if str(cell(vals, year_i)) != str(year):
88 + continue
89 + note = cell(vals, note_i)
90 + note = str(note).strip() if note is not None else ""
91 + if not note or note in {"-", "#N/A", "None"}:
92 + continue
93 + levels = ledger_to_pilot(
94 + kol=str(cell(vals, kol_i)) if cell(vals, kol_i) is not None else None,
95 + hesab=str(cell(vals, hesab_i)) if cell(vals, hesab_i) is not None else "",
96 + t1=str(cell(vals, t1_i)) if cell(vals, t1_i) is not None else None,
97 + t2=str(cell(vals, t2_i)) if cell(vals, t2_i) is not None else None,
98 + t3=str(cell(vals, t3_i)) if cell(vals, t3_i) is not None else None,
99 + t4=str(cell(vals, t4_i)) if cell(vals, t4_i) is not None else None,
100 + row=0,
101 + )
102 + mapping.setdefault(note, set()).add(canonical_full_code(levels))
103 + return mapping
104 + finally:
105 + wb.close()
106 +
107 +
108 +def main() -> None:
109 + parser = argparse.ArgumentParser(description=__doc__)
110 + parser.add_argument("--year", type=int, default=1404)
111 + parser.add_argument("--out", default=None)
112 + args = parser.parse_args()
113 + year = args.year
114 +
115 + out = Path(args.out) if args.out else Path(tempfile.mkdtemp(prefix="aram-uat-"))
116 + out.mkdir(parents=True, exist_ok=True)
117 + source_path = ROOT / "data" / "source_ledgers" / f"source_{year}.xlsx"
118 + official_path = ROOT / "data" / "official_statements" / f"financial_{year}.xlsx"
119 +
120 + engine = build_engine(f"sqlite:///{out / 'uat.db'}")
121 + Base.metadata.create_all(engine)
122 + ensure_triggers(engine)
123 + factory = sessionmaker(bind=engine, expire_on_commit=False)
124 + store = SourceStore(str(out / "source_store"))
125 +
126 + report: dict[str, object] = {"year": year, "source": str(source_path)}
127 + with factory() as session:
128 + company = Company(code="UAT", name="شرکت آزمون پذیرش")
129 + session.add(company)
130 + session.flush()
131 + fy = FiscalYear(company_id=company.id, year=year)
132 + session.add(fy)
133 + session.flush()
134 + year_id = fy.id
135 +
136 + content = source_path.read_bytes()
137 + source = register_source_document(
138 + session, year_id=year_id, filename=source_path.name,
139 + document_type="general_ledger", content=content, store=store,
140 + )
141 + skipped = []
142 + records = [r for r in parse_ledger(content, source_path.name, tolerant=True, skipped=skipped)
143 + if r.source_year == year]
144 + imported = import_ledger_balances(
145 + session, year_id=year_id, source_document_id=source.id,
146 + records=records, import_version=1,
147 + )
148 + report["import"] = {"rows_imported": imported, "rows_skipped": len(skipped)}
149 +
150 + # Auto-map embedded notes.
151 + note_map = _source_note_map(source_path, year)
152 + notes_created = 0
153 + mappings_created = 0
154 + for note_number, codes in sorted(note_map.items()):
155 + note = NoteDefinition(
156 + year_id=year_id, note_number=note_number, title=f"یادداشت {note_number}",
157 + configuration_json={"statement": "BS", "section": "Assets"},
158 + )
159 + session.add(note)
160 + session.flush()
161 + notes_created += 1
162 + for code in sorted(codes):
163 + session.add(MappingRule(
164 + year_id=year_id, rule_key=f"{code}->{note.id}", account_code=code,
165 + target_note_id=note.id, mapping_type="closing",
166 + ))
167 + mappings_created += 1
168 + session.flush()
169 + report["mapping"] = {"notes_created": notes_created, "mappings_created": mappings_created}
170 +
171 + built = build_statements(session, year_id, statement_types=("BS", "IS", "CF", "EQ"))
172 + report["build"] = {
173 + "statements": [s.statement_type.value for s in built.statements],
174 + "unmapped_accounts": len(built.unmapped_accounts),
175 + }
176 +
177 + # Golden reconciliation (source vs official), independent of the build.
178 + comparisons = compare_year(source_path, official_path, year)
179 + bs = [c for c in comparisons if c.statement == "BS"]
180 + report["golden"] = {
181 + "total": len(comparisons),
182 + "matched": sum(1 for c in comparisons if c.match),
183 + "bs_total": len(bs),
184 + "bs_matched": sum(1 for c in bs if c.match),
185 + "bs_matches": [
186 + {"note": c.note, "million": c.official_million} for c in bs if c.match
187 + ],
188 + }
189 +
190 + # Approval gate (real data has unmapped ordinary rows -> gate blocks).
191 + approval = approve_year(session, year_id, actor="uat")
192 + report["approval"] = {
193 + "approved": approval.approved,
194 + "blocking_codes": sorted({r.code for r in approval.blocking}),
195 + }
196 +
197 + # Export + backup + audit.
198 + xlsx = export_statements_workbook(session, year_id)
199 + (out / "statements.xlsx").write_bytes(xlsx)
200 + payload = export_statements_json(session, year_id)
201 + (out / "statements.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
202 + report["export"] = {"xlsx_bytes": len(xlsx), "lineage_rows": len(payload["lineage"])}
203 +
204 + session.commit()
205 + backup_dir = out / "backup"
206 + manifest = create_backup(session, backup_dir, store_root=out / "source_store")
207 + verified = verify_backup(backup_dir)
208 + report["backup"] = {"chain_valid": manifest["audit_chain_valid"], "verified": verified["valid"]}
209 + report["audit_chain_valid"] = verify_chain(session)
210 +
211 + engine.dispose()
212 + (out / "uat_report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
213 + print(json.dumps(report, ensure_ascii=False, indent=2))
214 + print(f"\nUAT report: {out / 'uat_report.json'}")
215 +
216 +
217 +if __name__ == "__main__":
218 + main()
webapp/README.md new
+50
@@ -0,0 +1,50 @@
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 new
+692
@@ -0,0 +1,692 @@
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 new
+207
@@ -0,0 +1,207 @@
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 new
+139
@@ -0,0 +1,139 @@
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 new
+293
@@ -0,0 +1,293 @@
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 /dev/null and b/webapp/vendor/et_xmlfile-2.0.0-py3-none-any.whl differ
webapp/vendor/openpyxl-3.1.5-py2.py3-none-any.whl
Binary files /dev/null and b/webapp/vendor/openpyxl-3.1.5-py2.py3-none-any.whl differ