Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 17:00 UTC
feat(mapping): add deterministic mapping row classifier
davoodmehraban89 committed
Nov 1, 2026 at 15:05 UTC
a6d2e4abd99deb02bb41d1724482151ba6b8bb08
1 file changed
+205
backend/src/aram_backend/mapping_matcher.py
new
+205
@@ -0,0 +1,205 @@
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
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
+ for result in results:
154
+ if result.status not in counts:
155
+ raise MappingMatchError(f"unknown result status: {result.status}")
156
+ total_rows += 1
157
+ source_closing += result.closing
158
+ counts[result.status] += 1
159
+ amounts[result.status] += result.closing
160
+
161
+ return MappingCoverageSummary(
162
+ total_source_rows=total_rows,
163
+ eligible_rows=total_rows - counts["EXCLUDED"],
164
+ excluded_rows=counts["EXCLUDED"],
165
+ unique_rows=counts["UNIQUE"],
166
+ ambiguous_rows=counts["AMBIGUOUS"],
167
+ unmapped_rows=counts["UNMAPPED"],
168
+ source_closing=source_closing,
169
+ eligible_closing=source_closing - amounts["EXCLUDED"],
170
+ unique_closing=amounts["UNIQUE"],
171
+ ambiguous_closing=amounts["AMBIGUOUS"],
172
+ unmapped_closing=amounts["UNMAPPED"],
173
+ )
174
+
175
+
176
+def _matches(ledger: LedgerRecord, rule: MappingRule) -> bool:
177
+ ledger_dimensions = {
178
+ "T1_CODE": ledger.t1_code,
179
+ "جاري / سرمایه ای": None,
180
+ "T4_CODE": ledger.t4_code,
181
+ }
182
+ for header, rule_value in rule.dimensions:
183
+ if rule_value is None:
184
+ continue
185
+ ledger_value = ledger_dimensions[header]
186
+ if ledger_value is None or ledger_value != rule_value:
187
+ return False
188
+ return True
189
+
190
+
191
+def _dimension_value(value: object, row_number: int, header: str) -> str | None:
192
+ if value is None:
193
+ return None
194
+ if isinstance(value, bool):
195
+ raise MappingMatchError(
196
+ f"mapping row {row_number}: {header} must be text or a code"
197
+ )
198
+ if isinstance(value, float):
199
+ if not value.is_integer():
200
+ raise MappingMatchError(
201
+ f"mapping row {row_number}: {header} must be an integer code"
202
+ )
203
+ return str(int(value))
204
+ text = str(value).strip()
205
+ return text or None