Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 18:15 UTC
feat(mapping): classify proposed batches without writes or silent duplicate precedence
davoodmehraban89 committed
Oct 30, 2026 at 19:01 UTC
2d30a93e01b14d2cf84ff88207c8ef73642f14bd
1 file changed
+188
backend/src/aram_backend/mapping_batch_review.py
new
+188
@@ -0,0 +1,188 @@
1
+"""Read-only Mapping batch classification: no writes, identities or approvals.
2
+
3
+Rows here are canonical proposal entries supplied by a trusted future adapter,
4
+not evidence that an XLSX is authorized. The module MUST NOT call save_mapping_rule.
5
+"""
6
+from __future__ import annotations
7
+
8
+from dataclasses import asdict, dataclass
9
+from hashlib import sha256
10
+import json
11
+
12
+from sqlalchemy.orm import Session
13
+
14
+from aram_backend.mapping_change_preview import (
15
+ MappingChangePreview, MappingNoChange, _require_clean_mapping_state,
16
+ preview_mapping_change,
17
+)
18
+from aram_backend.mapping_service import MappingValidationError
19
+from aram_backend.models import FiscalYear, FiscalYearStatus
20
+
21
+MAX_BATCH_ROWS = 10_000
22
+MAX_LOCATOR_LENGTH = 256
23
+
24
+
25
+@dataclass(frozen=True)
26
+class ProposedMappingRow:
27
+ source_locator: str
28
+ rule_key: str
29
+ account_code: str
30
+ target_note_id: int
31
+ mapping_type: str
32
+ expected_base_version: int
33
+
34
+
35
+@dataclass(frozen=True)
36
+class MappingBatchRowResult:
37
+ source_locator: str
38
+ rule_key: str
39
+ status: str
40
+ preview: MappingChangePreview | None = None
41
+ duplicate_of: str | None = None
42
+ reason: str | None = None
43
+
44
+
45
+@dataclass(frozen=True)
46
+class MappingBatchPreview:
47
+ year_id: int
48
+ rows: tuple[MappingBatchRowResult, ...]
49
+ fingerprint: str
50
+
51
+ @property
52
+ def counts(self) -> dict[str, int]:
53
+ counts: dict[str, int] = {}
54
+ for item in self.rows:
55
+ counts[item.status] = counts.get(item.status, 0) + 1
56
+ return counts
57
+
58
+ @property
59
+ def has_changes(self) -> bool:
60
+ return any(item.status in ("new", "changed") for item in self.rows)
61
+
62
+ @property
63
+ def ready_for_review(self) -> bool:
64
+ return self.has_changes and all(
65
+ item.status in ("new", "changed", "unchanged", "coalesced")
66
+ for item in self.rows
67
+ )
68
+
69
+
70
+def _row_content(row: ProposedMappingRow) -> tuple[object, ...]:
71
+ return (row.account_code, row.target_note_id, row.mapping_type, row.expected_base_version)
72
+
73
+
74
+def _validate_envelope(rows: object) -> tuple[ProposedMappingRow, ...]:
75
+ if type(rows) not in (list, tuple) or not 0 < len(rows) <= MAX_BATCH_ROWS:
76
+ raise MappingValidationError("mapping batch requires 1 to 10000 rows")
77
+ locators: set[str] = set()
78
+ for row in rows:
79
+ if not isinstance(row, ProposedMappingRow):
80
+ raise MappingValidationError("mapping batch entries must be typed proposals")
81
+ locator = row.source_locator
82
+ if (not isinstance(locator, str) or not locator or
83
+ len(locator) > MAX_LOCATOR_LENGTH or locator != locator.strip()):
84
+ raise MappingValidationError("invalid source locator")
85
+ if locator in locators:
86
+ raise MappingValidationError("duplicate source locator")
87
+ locators.add(locator)
88
+ return tuple(rows)
89
+
90
+
91
+def preview_mapping_batch(
92
+ session: Session, *, year_id: int, rows: list[ProposedMappingRow] | tuple[ProposedMappingRow, ...],
93
+) -> MappingBatchPreview:
94
+ """Classify every row; conflict/invalid entries block the WHOLE batch.
95
+
96
+ A successful preview is *not* an approval token or a transaction lock.
97
+ No mapping is automatically committed, and excluded source rules are not
98
+ interpreted as removals. Explicit reviewer approval/apply is not built yet.
99
+ """
100
+ if type(year_id) is not int or year_id <= 0:
101
+ raise MappingValidationError("year_id must be a positive integer")
102
+ entries = _validate_envelope(rows)
103
+
104
+ with session.no_autoflush:
105
+ _require_clean_mapping_state(session)
106
+ year = session.get(FiscalYear, year_id, populate_existing=True)
107
+ if year is None or year.status is not FiscalYearStatus.DRAFT:
108
+ raise MappingValidationError("fiscal year must exist and be Draft")
109
+
110
+ by_key: dict[str, list[int]] = {}
111
+ for index, entry in enumerate(entries):
112
+ # Invalid key types are reported as invalid rows; they never
113
+ # participate in accidental equality-based coalescing.
114
+ if isinstance(entry.rule_key, str):
115
+ by_key.setdefault(entry.rule_key, []).append(index)
116
+
117
+ conflicting: set[int] = set()
118
+ for group in by_key.values():
119
+ if len(group) > 1 and any(
120
+ _row_content(entries[position]) != _row_content(entries[group[0]])
121
+ for position in group[1:]
122
+ ):
123
+ conflicting.update(group)
124
+
125
+ first_by_key: dict[str, MappingBatchRowResult] = {}
126
+ results: list[MappingBatchRowResult] = []
127
+ for index, entry in enumerate(entries):
128
+ source = entry.source_locator
129
+ if index in conflicting:
130
+ result = MappingBatchRowResult(
131
+ source, str(entry.rule_key), "conflict",
132
+ reason="conflicting source rows for the same rule key",
133
+ )
134
+ elif isinstance(entry.rule_key, str) and entry.rule_key in first_by_key:
135
+ original = first_by_key[entry.rule_key]
136
+ if original.status == "invalid":
137
+ result = MappingBatchRowResult(
138
+ source, entry.rule_key, "invalid",
139
+ reason=f"duplicate of invalid {original.source_locator}: {original.reason}",
140
+ )
141
+ else:
142
+ result = MappingBatchRowResult(
143
+ source, entry.rule_key, "coalesced",
144
+ duplicate_of=original.source_locator,
145
+ )
146
+ else:
147
+ try:
148
+ preview = preview_mapping_change(
149
+ session, year_id=year_id, rule_key=entry.rule_key,
150
+ account_code=entry.account_code,
151
+ target_note_id=entry.target_note_id,
152
+ mapping_type=entry.mapping_type,
153
+ expected_base_version=entry.expected_base_version,
154
+ )
155
+ except MappingNoChange:
156
+ result = MappingBatchRowResult(source, str(entry.rule_key), "unchanged")
157
+ except MappingValidationError as exc:
158
+ result = MappingBatchRowResult(
159
+ source, str(entry.rule_key), "invalid", reason=str(exc),
160
+ )
161
+ else:
162
+ result = MappingBatchRowResult(
163
+ source, entry.rule_key,
164
+ "new" if preview.before is None else "changed",
165
+ preview=preview,
166
+ )
167
+ if isinstance(entry.rule_key, str):
168
+ first_by_key.setdefault(entry.rule_key, result)
169
+ results.append(result)
170
+
171
+ stable = [
172
+ {
173
+ "source_locator": item.source_locator,
174
+ "rule_key": item.rule_key,
175
+ "status": item.status,
176
+ "duplicate_of": item.duplicate_of,
177
+ "reason": item.reason,
178
+ "preview": asdict(item.preview) if item.preview is not None else None,
179
+ }
180
+ for item in results
181
+ ]
182
+ fingerprint = sha256(
183
+ json.dumps(
184
+ {"year_id": year_id, "rows": stable},
185
+ sort_keys=True, separators=(",", ":"), ensure_ascii=True,
186
+ ).encode("utf-8")
187
+ ).hexdigest()
188
+ return MappingBatchPreview(year_id=year_id, rows=tuple(results), fingerprint=fingerprint)