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

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

Synced Dec 3, 18:15 UTC

source-data-cleanup
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 218 lines 9.32 KB
Raw
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()