codex/gate3-mapping-batch-review-20261030
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 193 lines 7.55 KB
Raw
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 from unicodedata import category
12
13 from sqlalchemy.orm import Session
14
15 from aram_backend.mapping_change_preview import (
16 MappingChangePreview, MappingNoChange, _require_clean_mapping_state,
17 preview_mapping_change,
18 )
19 from aram_backend.mapping_service import MappingValidationError
20 from aram_backend.models import FiscalYear, FiscalYearStatus
21
22 MAX_BATCH_ROWS = 10_000
23 MAX_LOCATOR_LENGTH = 256
24
25
26 @dataclass(frozen=True)
27 class ProposedMappingRow:
28 source_locator: str
29 rule_key: str
30 account_code: str
31 target_note_id: int
32 mapping_type: str
33 expected_base_version: int
34
35
36 @dataclass(frozen=True)
37 class MappingBatchRowResult:
38 source_locator: str
39 rule_key: str
40 status: str
41 preview: MappingChangePreview | None = None
42 duplicate_of: str | None = None
43 reason: str | None = None
44
45
46 @dataclass(frozen=True)
47 class MappingBatchPreview:
48 year_id: int
49 rows: tuple[MappingBatchRowResult, ...]
50 fingerprint: str
51
52 @property
53 def counts(self) -> dict[str, int]:
54 counts: dict[str, int] = {}
55 for item in self.rows:
56 counts[item.status] = counts.get(item.status, 0) + 1
57 return counts
58
59 @property
60 def has_changes(self) -> bool:
61 return any(item.status in ("new", "changed") for item in self.rows)
62
63 @property
64 def ready_for_review(self) -> bool:
65 return self.has_changes and all(
66 item.status in ("new", "changed", "unchanged", "coalesced")
67 for item in self.rows
68 )
69
70
71 def _row_content(row: ProposedMappingRow) -> tuple[object, ...]:
72 # Python considers True == 1. Financial identity comparisons must not
73 # coalesce malformed booleans with valid numeric IDs or versions.
74 values = (row.account_code, row.target_note_id, row.mapping_type, row.expected_base_version)
75 return tuple((type(value).__name__, value) for value in values)
76
77
78 def _validate_envelope(rows: object) -> tuple[ProposedMappingRow, ...]:
79 if type(rows) not in (list, tuple) or not 0 < len(rows) <= MAX_BATCH_ROWS:
80 raise MappingValidationError("mapping batch requires 1 to 10000 rows")
81 locators: set[str] = set()
82 for row in rows:
83 if not isinstance(row, ProposedMappingRow):
84 raise MappingValidationError("mapping batch entries must be typed proposals")
85 locator = row.source_locator
86 if (not isinstance(locator, str) or not locator or
87 len(locator) > MAX_LOCATOR_LENGTH or locator != locator.strip()
88 or any(category(char) in ("Cc", "Cf", "Cs") for char in locator)):
89 raise MappingValidationError("invalid source locator")
90 if locator in locators:
91 raise MappingValidationError("duplicate source locator")
92 locators.add(locator)
93 return tuple(rows)
94
95
96 def preview_mapping_batch(
97 session: Session, *, year_id: int, rows: list[ProposedMappingRow] | tuple[ProposedMappingRow, ...],
98 ) -> MappingBatchPreview:
99 """Classify every row; conflict/invalid entries block the WHOLE batch.
100
101 A successful preview is *not* an approval token or a transaction lock.
102 No mapping is automatically committed, and excluded source rules are not
103 interpreted as removals. Explicit reviewer approval/apply is not built yet.
104 """
105 if type(year_id) is not int or year_id <= 0:
106 raise MappingValidationError("year_id must be a positive integer")
107 entries = _validate_envelope(rows)
108
109 with session.no_autoflush:
110 _require_clean_mapping_state(session)
111 year = session.get(FiscalYear, year_id, populate_existing=True)
112 if year is None or year.status is not FiscalYearStatus.DRAFT:
113 raise MappingValidationError("fiscal year must exist and be Draft")
114
115 by_key: dict[str, list[int]] = {}
116 for index, entry in enumerate(entries):
117 # Invalid key types are reported as invalid rows; they never
118 # participate in accidental equality-based coalescing.
119 if isinstance(entry.rule_key, str):
120 by_key.setdefault(entry.rule_key, []).append(index)
121
122 conflicting: set[int] = set()
123 for group in by_key.values():
124 if len(group) > 1 and any(
125 _row_content(entries[position]) != _row_content(entries[group[0]])
126 for position in group[1:]
127 ):
128 conflicting.update(group)
129
130 first_by_key: dict[str, MappingBatchRowResult] = {}
131 results: list[MappingBatchRowResult] = []
132 for index, entry in enumerate(entries):
133 source = entry.source_locator
134 if index in conflicting:
135 result = MappingBatchRowResult(
136 source, str(entry.rule_key), "conflict",
137 reason="conflicting source rows for the same rule key",
138 )
139 elif isinstance(entry.rule_key, str) and entry.rule_key in first_by_key:
140 original = first_by_key[entry.rule_key]
141 if original.status == "invalid":
142 result = MappingBatchRowResult(
143 source, entry.rule_key, "invalid",
144 reason=f"duplicate of invalid {original.source_locator}: {original.reason}",
145 )
146 else:
147 result = MappingBatchRowResult(
148 source, entry.rule_key, "coalesced",
149 duplicate_of=original.source_locator,
150 )
151 else:
152 try:
153 preview = preview_mapping_change(
154 session, year_id=year_id, rule_key=entry.rule_key,
155 account_code=entry.account_code,
156 target_note_id=entry.target_note_id,
157 mapping_type=entry.mapping_type,
158 expected_base_version=entry.expected_base_version,
159 )
160 except MappingNoChange:
161 result = MappingBatchRowResult(source, str(entry.rule_key), "unchanged")
162 except MappingValidationError as exc:
163 result = MappingBatchRowResult(
164 source, str(entry.rule_key), "invalid", reason=str(exc),
165 )
166 else:
167 result = MappingBatchRowResult(
168 source, entry.rule_key,
169 "new" if preview.before is None else "changed",
170 preview=preview,
171 )
172 if isinstance(entry.rule_key, str):
173 first_by_key.setdefault(entry.rule_key, result)
174 results.append(result)
175
176 stable = [
177 {
178 "source_locator": item.source_locator,
179 "rule_key": item.rule_key,
180 "status": item.status,
181 "duplicate_of": item.duplicate_of,
182 "reason": item.reason,
183 "preview": asdict(item.preview) if item.preview is not None else None,
184 }
185 for item in results
186 ]
187 fingerprint = sha256(
188 json.dumps(
189 {"year_id": year_id, "rows": stable},
190 sort_keys=True, separators=(",", ":"), ensure_ascii=True,
191 ).encode("utf-8")
192 ).hexdigest()
193 return MappingBatchPreview(year_id=year_id, rows=tuple(results), fingerprint=fingerprint)