Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 04:15 UTC
docs+uat: Phase 9 real-data UAT script + status/log for Phases 5-9 (§0/§18)
scripts/uat_real_data.py exercises the full persistent pipeline on source_1404 (read-only): import->auto-map->build->golden reconcile->approval gate->export-> backup->audit. Records reviewable evidence; report is not a committed artifact. PROJECT_STATUS + PROJECT_LOG updated with Phases 5-9 and UAT results. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
davoodmehraban89 committed
Dec 3, 2026 at 11:58 UTC
969f6083959c1fd17b9676e86c4114dc8818c0bf
3 files changed
+268
-5
PROJECT_STATUS.md
+31
-5
@@ -115,11 +115,37 @@ Continuation on branch `arena/094f314c-aram` (base `7dc864fd`). Per §17 the age
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 | IN_PROGRESS | frontend scaffold (Vite+React+TS RTL) committed; full screens next |
119
-
120
-Local evidence at head `accf1cc`: backend **281 tests passed**; ruff clean; mypy domain strict + services clean; frontend lint/tsc/vitest/build pass; Playwright `--list` validates 2 specs. Migration 20261203_05 up/down/up verified (SQLite). No canonical `data/` or `samples/` file changed.
121
-
122
-ADRs added in this stretch: 021 (golden comparison scale/column resolution).
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
docs/PROJECT_LOG.md
+19
@@ -318,3 +318,22 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
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
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()