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

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

Synced Dec 3, 17:00 UTC

codex/aram-mapping-source-parser-20261101
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 219 lines 7.37 KB
Raw
1 from __future__ import annotations
2
3 from collections import defaultdict
4 from collections.abc import Iterable, Iterator, Mapping
5 from dataclasses import dataclass
6 from decimal import Decimal, localcontext
7
8 from aram_backend.ledger_parser import LedgerRecord
9 from aram_backend.mapping_source_parser import MappingSourceRow
10
11
12 DIMENSION_HEADERS = ("T1_CODE", "جاری / سرمایه ای", "T4_CODE")
13 DEFAULT_EXCLUDED_ACCOUNT_CODES = frozenset({"8999"})
14
15
16 class MappingMatchError(ValueError):
17 """Raised when source mapping dimensions are missing or malformed."""
18
19
20 @dataclass(frozen=True)
21 class MappingRule:
22 source_row: int
23 account_code: str
24 mapping_type: str
25 note_code: str
26 note_description: str
27 dimensions: tuple[tuple[str, str | None], ...]
28
29 @property
30 def dimension_map(self) -> Mapping[str, str | None]:
31 return dict(self.dimensions)
32
33
34 @dataclass(frozen=True)
35 class LedgerMappingResult:
36 ledger_row: int
37 account_code: str
38 status: str
39 matching_mapping_rows: tuple[int, ...]
40 closing: Decimal
41
42
43 @dataclass(frozen=True)
44 class MappingCoverageSummary:
45 total_source_rows: int
46 eligible_rows: int
47 excluded_rows: int
48 unique_rows: int
49 ambiguous_rows: int
50 unmapped_rows: int
51 source_closing: Decimal
52 eligible_closing: Decimal
53 unique_closing: Decimal
54 ambiguous_closing: Decimal
55 unmapped_closing: Decimal
56
57 @property
58 def any_match_rows(self) -> int:
59 return self.unique_rows + self.ambiguous_rows
60
61
62 def build_mapping_rules(
63 rows: Iterable[MappingSourceRow],
64 *,
65 dimension_headers: tuple[str, ...] = DIMENSION_HEADERS,
66 ) -> tuple[MappingRule, ...]:
67 """Convert parsed mapping source rows into explicit wildcard-capable rules.
68
69 Blank mapping dimensions are wildcards. A populated rule dimension must
70 equal the corresponding ledger dimension after whitespace trimming.
71 A populated mapping dimension never matches a missing ledger dimension.
72 No ranking, precedence, formula execution, or approval is inferred.
73 """
74 rules: list[MappingRule] = []
75 for row in rows:
76 raw = dict(row.source_values)
77 legacy_dimension = "جاري / سرمایه ای"
78 canonical_dimension = "جاری / سرمایه ای"
79 if legacy_dimension in raw and canonical_dimension in raw:
80 legacy_value = _dimension_value(raw[legacy_dimension], row.row_number, legacy_dimension)
81 canonical_value = _dimension_value(raw[canonical_dimension], row.row_number, canonical_dimension)
82 if legacy_value != canonical_value:
83 raise MappingMatchError(
84 f"mapping row {row.row_number}: conflicting current/capital dimension aliases"
85 )
86 elif legacy_dimension in raw:
87 raw[canonical_dimension] = raw[legacy_dimension]
88 missing = set(dimension_headers).difference(raw)
89 if missing:
90 raise MappingMatchError(
91 f"mapping row {row.row_number}: missing dimension headers {sorted(missing)}"
92 )
93 dimensions = tuple(
94 (header, _dimension_value(raw[header], row.row_number, header))
95 for header in dimension_headers
96 )
97 rules.append(
98 MappingRule(
99 source_row=row.row_number,
100 account_code=row.account_code,
101 mapping_type=row.mapping_type,
102 note_code=row.note_code,
103 note_description=row.note_description,
104 dimensions=dimensions,
105 )
106 )
107 return tuple(rules)
108
109
110 def classify_ledger_rows(
111 ledger_rows: Iterable[LedgerRecord],
112 mapping_rules: Iterable[MappingRule],
113 *,
114 excluded_account_codes: frozenset[str] = DEFAULT_EXCLUDED_ACCOUNT_CODES,
115 ) -> Iterator[LedgerMappingResult]:
116 """Stream each ledger row into unique, ambiguous, unmapped, or excluded.
117
118 Mapping rows are indexed by account. Each nonblank rule dimension is an
119 exact constraint; each blank rule dimension is an explicit wildcard.
120 Multiple matching source rows remain ambiguous, including duplicate rules.
121 """
122 by_account: dict[str, list[MappingRule]] = defaultdict(list)
123 for rule in mapping_rules:
124 by_account[rule.account_code].append(rule)
125
126 for ledger in ledger_rows:
127 if ledger.account_code in excluded_account_codes:
128 yield LedgerMappingResult(
129 ledger_row=ledger.row_number,
130 account_code=ledger.account_code,
131 status="EXCLUDED",
132 matching_mapping_rows=(),
133 closing=ledger.closing,
134 )
135 continue
136
137 matches = tuple(
138 rule.source_row
139 for rule in by_account.get(ledger.account_code, ())
140 if _matches(ledger, rule)
141 )
142 status = (
143 "UNMAPPED" if not matches
144 else "UNIQUE" if len(matches) == 1
145 else "AMBIGUOUS"
146 )
147 yield LedgerMappingResult(
148 ledger_row=ledger.row_number,
149 account_code=ledger.account_code,
150 status=status,
151 matching_mapping_rows=matches,
152 closing=ledger.closing,
153 )
154
155
156 def summarize_mapping_coverage(
157 results: Iterable[LedgerMappingResult],
158 ) -> MappingCoverageSummary:
159 """Aggregate row counts and closing exposure without rounding."""
160 counts = {"EXCLUDED": 0, "UNIQUE": 0, "AMBIGUOUS": 0, "UNMAPPED": 0}
161 amounts = {key: Decimal(0) for key in counts}
162 total_rows = 0
163 source_closing = Decimal(0)
164 with localcontext() as context:
165 context.prec = 1000
166 for result in results:
167 if result.status not in counts:
168 raise MappingMatchError(f"unknown result status: {result.status}")
169 total_rows += 1
170 source_closing += result.closing
171 counts[result.status] += 1
172 amounts[result.status] += result.closing
173 eligible_closing = source_closing - amounts["EXCLUDED"]
174
175 return MappingCoverageSummary(
176 total_source_rows=total_rows,
177 eligible_rows=total_rows - counts["EXCLUDED"],
178 excluded_rows=counts["EXCLUDED"],
179 unique_rows=counts["UNIQUE"],
180 ambiguous_rows=counts["AMBIGUOUS"],
181 unmapped_rows=counts["UNMAPPED"],
182 source_closing=source_closing,
183 eligible_closing=eligible_closing,
184 unique_closing=amounts["UNIQUE"],
185 ambiguous_closing=amounts["AMBIGUOUS"],
186 unmapped_closing=amounts["UNMAPPED"],
187 )
188
189
190 def _matches(ledger: LedgerRecord, rule: MappingRule) -> bool:
191 ledger_dimensions = {
192 "T1_CODE": ledger.t1_code,
193 "جاری / سرمایه ای": None,
194 "T4_CODE": ledger.t4_code,
195 }
196 for header, rule_value in rule.dimensions:
197 if rule_value is None:
198 continue
199 ledger_value = ledger_dimensions[header]
200 if ledger_value is None or ledger_value != rule_value:
201 return False
202 return True
203
204
205 def _dimension_value(value: object, row_number: int, header: str) -> str | None:
206 if value is None:
207 return None
208 if isinstance(value, bool):
209 raise MappingMatchError(
210 f"mapping row {row_number}: {header} must be text or a code"
211 )
212 if isinstance(value, float):
213 if not value.is_integer():
214 raise MappingMatchError(
215 f"mapping row {row_number}: {header} must be an integer code"
216 )
217 return str(int(value))
218 text = str(value).strip()
219 return text or None