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

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

Synced Dec 3, 20:45 UTC

codex/aram-multidimensional-mapping-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 207 lines 6.64 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 missing = set(dimension_headers).difference(raw)
78 if missing:
79 raise MappingMatchError(
80 f"mapping row {row.row_number}: missing dimension headers {sorted(missing)}"
81 )
82 dimensions = tuple(
83 (header, _dimension_value(raw[header], row.row_number, header))
84 for header in dimension_headers
85 )
86 rules.append(
87 MappingRule(
88 source_row=row.row_number,
89 account_code=row.account_code,
90 mapping_type=row.mapping_type,
91 note_code=row.note_code,
92 note_description=row.note_description,
93 dimensions=dimensions,
94 )
95 )
96 return tuple(rules)
97
98
99 def classify_ledger_rows(
100 ledger_rows: Iterable[LedgerRecord],
101 mapping_rules: Iterable[MappingRule],
102 *,
103 excluded_account_codes: frozenset[str] = DEFAULT_EXCLUDED_ACCOUNT_CODES,
104 ) -> Iterator[LedgerMappingResult]:
105 """Stream each ledger row into unique, ambiguous, unmapped, or excluded.
106
107 Mapping rows are indexed by account. Each nonblank rule dimension is an
108 exact constraint; each blank rule dimension is an explicit wildcard.
109 Multiple matching source rows remain ambiguous, including duplicate rules.
110 """
111 by_account: dict[str, list[MappingRule]] = defaultdict(list)
112 for rule in mapping_rules:
113 by_account[rule.account_code].append(rule)
114
115 for ledger in ledger_rows:
116 if ledger.account_code in excluded_account_codes:
117 yield LedgerMappingResult(
118 ledger_row=ledger.row_number,
119 account_code=ledger.account_code,
120 status="EXCLUDED",
121 matching_mapping_rows=(),
122 closing=ledger.closing,
123 )
124 continue
125
126 matches = tuple(
127 rule.source_row
128 for rule in by_account.get(ledger.account_code, ())
129 if _matches(ledger, rule)
130 )
131 status = (
132 "UNMAPPED" if not matches
133 else "UNIQUE" if len(matches) == 1
134 else "AMBIGUOUS"
135 )
136 yield LedgerMappingResult(
137 ledger_row=ledger.row_number,
138 account_code=ledger.account_code,
139 status=status,
140 matching_mapping_rows=matches,
141 closing=ledger.closing,
142 )
143
144
145 def summarize_mapping_coverage(
146 results: Iterable[LedgerMappingResult],
147 ) -> MappingCoverageSummary:
148 """Aggregate row counts and closing exposure without rounding."""
149 counts = {"EXCLUDED": 0, "UNIQUE": 0, "AMBIGUOUS": 0, "UNMAPPED": 0}
150 amounts = {key: Decimal(0) for key in counts}
151 total_rows = 0
152 source_closing = Decimal(0)
153 with localcontext() as context:
154 context.prec = 1000
155 for result in results:
156 if result.status not in counts:
157 raise MappingMatchError(f"unknown result status: {result.status}")
158 total_rows += 1
159 source_closing += result.closing
160 counts[result.status] += 1
161 amounts[result.status] += result.closing
162
163 return MappingCoverageSummary(
164 total_source_rows=total_rows,
165 eligible_rows=total_rows - counts["EXCLUDED"],
166 excluded_rows=counts["EXCLUDED"],
167 unique_rows=counts["UNIQUE"],
168 ambiguous_rows=counts["AMBIGUOUS"],
169 unmapped_rows=counts["UNMAPPED"],
170 source_closing=source_closing,
171 eligible_closing=source_closing - amounts["EXCLUDED"],
172 unique_closing=amounts["UNIQUE"],
173 ambiguous_closing=amounts["AMBIGUOUS"],
174 unmapped_closing=amounts["UNMAPPED"],
175 )
176
177
178 def _matches(ledger: LedgerRecord, rule: MappingRule) -> bool:
179 ledger_dimensions = {
180 "T1_CODE": ledger.t1_code,
181 "جاري / سرمایه ای": None,
182 "T4_CODE": ledger.t4_code,
183 }
184 for header, rule_value in rule.dimensions:
185 if rule_value is None:
186 continue
187 ledger_value = ledger_dimensions[header]
188 if ledger_value is None or ledger_value != rule_value:
189 return False
190 return True
191
192
193 def _dimension_value(value: object, row_number: int, header: str) -> str | None:
194 if value is None:
195 return None
196 if isinstance(value, bool):
197 raise MappingMatchError(
198 f"mapping row {row_number}: {header} must be text or a code"
199 )
200 if isinstance(value, float):
201 if not value.is_integer():
202 raise MappingMatchError(
203 f"mapping row {row_number}: {header} must be an integer code"
204 )
205 return str(int(value))
206 text = str(value).strip()
207 return text or None