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

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

Synced Dec 4, 14:15 UTC

dependabot/github_actions/actions/upload-artifact-7
add-index-html-10623938925177053894 arena/094f314c-aram arena/2d4eda07-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 dependabot/github_actions/actions/checkout-7 dependabot/github_actions/actions/setup-node-6 dependabot/github_actions/actions/setup-python-7 dependabot/github_actions/actions/upload-artifact-7 dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1 dependabot/npm_and_yarn/frontend/globals-17.15.0 dependabot/npm_and_yarn/frontend/vite-8.4.0 dependabot/npm_and_yarn/frontend/vitest-5.1.2 dependabot/npm_and_yarn/frontend/vitest/coverage-v8-5.1.2 dependabot/pip/backend/mypy-gte-1.13-and-lt-3 dependabot/pip/backend/pytest-cov-gte-6.0-and-lt-8 dependabot/pip/backend/setuptools-gte-75-and-lt-85 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 157 lines 5.51 KB
Raw
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 ]