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

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

Synced Dec 4, 00:30 UTC

feat/gate3-governed-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 332 lines 15.4 KB
Raw
1 """Governed, isolated mapping decisions for a single company and fiscal year.
2
3 No approval is inferred from an imported workbook. All transitions are explicit
4 and append-only audit entries; caller owns durable storage and transactionality.
5 """
6 from __future__ import annotations
7
8 from collections.abc import Iterable
9 from dataclasses import dataclass, replace
10 from datetime import UTC, datetime
11 from io import BytesIO
12
13 from openpyxl import Workbook, load_workbook
14
15 from aram_backend.pilot_workbook import SHEET_HEADERS, preflight_pilot_workbook
16
17
18 class MappingWorkflowError(ValueError):
19 pass
20
21
22 @dataclass(frozen=True)
23 class MappingDecision:
24 mapping_id: str
25 company_code: str
26 fiscal_year: int
27 account_full_code: str
28 target_statement: str
29 statement_section: str
30 note_number: str
31 subnote_code: str | None
32 version: int
33 status: str
34 reviewer: str | None
35 source: str
36 review_date: str | None = None
37
38
39 @dataclass(frozen=True)
40 class MappingAuditEvent:
41 mapping_id: str
42 company_code: str
43 fiscal_year: int
44 previous_status: str | None
45 new_status: str
46 actor: str
47 timestamp: str
48 previous_version: int | None
49 new_version: int
50
51
52 class MappingWorkspace:
53 """In-memory transaction boundary; never crosses the selected company/year."""
54
55 def __init__(self, company_code: str, fiscal_year: int):
56 if not isinstance(company_code, str) or not company_code.strip():
57 raise MappingWorkflowError("company_code is required")
58 if isinstance(fiscal_year, bool) or not isinstance(fiscal_year, int) or fiscal_year <= 0:
59 raise MappingWorkflowError("fiscal_year must be a positive integer")
60 self.company_code = company_code.strip()
61 self.fiscal_year = fiscal_year
62 self._decisions: dict[str, MappingDecision] = {}
63 self._audit: list[MappingAuditEvent] = []
64
65 @property
66 def decisions(self) -> tuple[MappingDecision, ...]:
67 return tuple(self._decisions[key] for key in sorted(self._decisions))
68
69 @property
70 def audit(self) -> tuple[MappingAuditEvent, ...]:
71 return tuple(self._audit)
72
73 def _check_scope(self, decision: MappingDecision) -> None:
74 if (decision.company_code, decision.fiscal_year) != (self.company_code, self.fiscal_year):
75 raise MappingWorkflowError("company/year isolation violation")
76
77 def _record(self, old: MappingDecision | None, new: MappingDecision, actor: str) -> None:
78 self._decisions[new.mapping_id] = new
79 self._audit.append(MappingAuditEvent(
80 new.mapping_id, new.company_code, new.fiscal_year,
81 old.status if old else None, new.status, actor,
82 datetime.now(UTC).isoformat(),
83 old.version if old else None, new.version,
84 ))
85
86 def propose(self, decision: MappingDecision, *, actor: str) -> MappingDecision:
87 self._check_scope(decision)
88 if not actor.strip() or not decision.mapping_id.strip() or not decision.account_full_code.strip():
89 raise MappingWorkflowError("actor, mapping_id and account are required")
90 if (decision.status != "Draft" or decision.version != 1
91 or decision.reviewer is not None or decision.review_date is not None):
92 raise MappingWorkflowError("new decisions must begin as unreviewed Draft v1")
93 if decision.mapping_id in self._decisions:
94 raise MappingWorkflowError("mapping_id already exists; use revise")
95 if not decision.note_number or not decision.target_statement or not decision.statement_section:
96 raise MappingWorkflowError("target statement, section and note are required")
97 self._record(None, decision, actor)
98 return decision
99
100 def transition(self, mapping_id: str, status: str, *, actor: str) -> MappingDecision:
101 old = self._decisions.get(mapping_id)
102 if old is None:
103 raise MappingWorkflowError("unknown mapping_id")
104 allowed = {"Draft": "Reviewed", "Reviewed": "Approved"}
105 if allowed.get(old.status) != status:
106 raise MappingWorkflowError("invalid mapping lifecycle transition")
107 if not actor.strip():
108 raise MappingWorkflowError("reviewer identity required")
109 if status == "Reviewed" and any(
110 event.mapping_id == mapping_id and event.new_status == "Draft"
111 and event.actor == actor for event in self._audit
112 ):
113 raise MappingWorkflowError("maker cannot review own mapping")
114 if status == "Approved" and (actor == old.reviewer or any(
115 event.mapping_id == mapping_id and event.new_status == "Draft"
116 and event.actor == actor for event in self._audit
117 )):
118 raise MappingWorkflowError("approval requires independent maker and reviewer")
119 new = replace(old, status=status, reviewer=actor,
120 review_date=datetime.now(UTC).date().isoformat(),
121 version=old.version + 1)
122 self._record(old, new, actor)
123 return new
124
125 def revise(self, mapping_id: str, *, actor: str, target_statement: str,
126 statement_section: str, note_number: str, subnote_code: str | None) -> MappingDecision:
127 old = self._decisions.get(mapping_id)
128 if old is None:
129 raise MappingWorkflowError("unknown mapping_id")
130 if not actor.strip() or not target_statement or not statement_section or not note_number:
131 raise MappingWorkflowError("actor and complete target are required")
132 new = replace(old, target_statement=target_statement,
133 statement_section=statement_section, note_number=note_number,
134 subnote_code=subnote_code, status="Draft", reviewer=None,
135 review_date=None,
136 version=old.version + 1)
137 self._record(old, new, actor)
138 return new
139
140 def carry_forward(self, previous: Iterable[MappingDecision], *, actor: str) -> int:
141 if not actor.strip():
142 raise MappingWorkflowError("actor required")
143 candidates = tuple(previous)
144 ids = [d.mapping_id for d in candidates]
145 if len(ids) != len(set(ids)) or any(i in self._decisions for i in ids):
146 raise MappingWorkflowError("duplicate carry-forward mapping_id")
147 for d in candidates:
148 if d.company_code != self.company_code or d.fiscal_year != self.fiscal_year - 1:
149 raise MappingWorkflowError("carry-forward source company/year mismatch")
150 if d.status != "Approved":
151 raise MappingWorkflowError("only approved mappings may be carried forward")
152 for d in candidates:
153 self.propose(replace(d, fiscal_year=self.fiscal_year, status="Draft",
154 reviewer=None, review_date=None, version=1,
155 source="CarryForward"), actor=actor)
156 return len(candidates)
157
158
159 def import_mapping_workbook(content: bytes, company_code: str, fiscal_year: int) -> tuple[MappingDecision, ...]:
160 """Read only preflight-valid mapping rows; reject any out-of-scope rows."""
161 report = preflight_pilot_workbook(content)
162 if not report.valid:
163 raise MappingWorkflowError(f"workbook preflight failed: {report.issues[0].code}")
164 workbook = load_workbook(BytesIO(content), read_only=True, data_only=False)
165 try:
166 columns = SHEET_HEADERS["Mapping"]
167 decisions: list[MappingDecision] = []
168 for values in workbook["Mapping"].iter_rows(min_row=2, values_only=True):
169 if not any(v is not None for v in values):
170 continue
171 row = dict(zip(columns, values))
172 if (row["company_code"], row["fiscal_year"]) != (company_code, fiscal_year):
173 raise MappingWorkflowError("import includes foreign company/year")
174 decisions.append(MappingDecision(
175 row["mapping_id"], row["company_code"], row["fiscal_year"],
176 row["account_full_code"], row["target_statement"],
177 row["statement_section"], row["note_number"], row["subnote_code"],
178 row["mapping_version"], row["approval_status"], row["reviewer"],
179 row["source"], row["review_date"],
180 ))
181 return tuple(decisions)
182 finally:
183 workbook.close()
184
185
186 def export_mapping_rows(decisions: Iterable[MappingDecision]) -> bytes:
187 """Export mapping decisions to a standalone review sheet (not an approved Pilot input)."""
188 workbook = Workbook()
189 sheet = workbook.active
190 sheet.title = "Mapping"
191 columns = ("mapping_id", "company_code", "fiscal_year", "account_full_code",
192 "target_statement", "statement_section", "note_number", "subnote_code",
193 "mapping_version", "approval_status", "reviewer", "source")
194 sheet.append(columns)
195 for decision in decisions:
196 sheet.append((decision.mapping_id, decision.company_code, decision.fiscal_year,
197 decision.account_full_code, decision.target_statement,
198 decision.statement_section, decision.note_number, decision.subnote_code,
199 decision.version, decision.status, decision.reviewer, decision.source))
200 buffer = BytesIO()
201 workbook.save(buffer)
202 workbook.close()
203 return buffer.getvalue()
204
205
206 @dataclass(frozen=True)
207 class UnknownAccount:
208 company_code: str
209 fiscal_year: int
210 account_full_code: str
211
212
213 def unknown_account_queue(
214 accounts: Iterable[tuple[str, int, str]],
215 decisions: Iterable[MappingDecision],
216 *,
217 company_code: str,
218 fiscal_year: int,
219 ) -> tuple[UnknownAccount, ...]:
220 """Return unapproved/unmapped accounts, deduplicated and deterministically sorted.
221
222 A Draft or Reviewed mapping does not remove an account from the queue.
223 Foreign-scope account input fails closed rather than silently disappearing.
224 """
225 if not company_code.strip() or isinstance(fiscal_year, bool) or fiscal_year <= 0:
226 raise MappingWorkflowError("invalid queue company/year")
227 approved: set[str] = set()
228 for decision in decisions:
229 if (decision.company_code, decision.fiscal_year) != (company_code, fiscal_year):
230 raise MappingWorkflowError("foreign mapping in unknown-account queue")
231 if decision.status == "Approved":
232 approved.add(decision.account_full_code)
233 unknown: set[str] = set()
234 for company, year, account in accounts:
235 if (company, year) != (company_code, fiscal_year):
236 raise MappingWorkflowError("foreign account in unknown-account queue")
237 if not isinstance(account, str) or not account.strip():
238 raise MappingWorkflowError("invalid account code in unknown-account queue")
239 if account not in approved:
240 unknown.add(account)
241 return tuple(UnknownAccount(company_code, fiscal_year, account)
242 for account in sorted(unknown))
243
244
245 def export_pilot_mapping_workbook(
246 source: bytes, decisions: Iterable[MappingDecision], *,
247 company_code: str, fiscal_year: int,
248 ) -> bytes:
249 """Produce a complete Pilot workbook, validated for re-import."""
250 check = preflight_pilot_workbook(source)
251 if not check.valid:
252 raise MappingWorkflowError("source workbook failed preflight")
253 workbook = load_workbook(BytesIO(source))
254 try:
255 headers = SHEET_HEADERS["Mapping"]
256 mapping_sheet = workbook["Mapping"]
257 accounts = {}
258 for values in workbook["Accounts"].iter_rows(min_row=2, values_only=True):
259 if any(v is not None for v in values):
260 row = dict(zip(SHEET_HEADERS["Accounts"], values))
261 accounts[(row["company_code"], row["fiscal_year"], row["account_full_code"])] = row
262 notes = set()
263 for values in workbook["Notes"].iter_rows(min_row=2, values_only=True):
264 if any(v is not None for v in values):
265 row = dict(zip(SHEET_HEADERS["Notes"], values))
266 notes.add((row["company_code"], row["fiscal_year"], row["statement"],
267 row["statement_section"], row["note_number"], row["subnote_code"]))
268 previous = {}
269 foreign_rows = []
270 for values in mapping_sheet.iter_rows(min_row=2, values_only=True):
271 if any(v is not None for v in values):
272 row = dict(zip(headers, values))
273 previous[row["mapping_id"]] = row
274 if (row["company_code"], row["fiscal_year"]) != (company_code, fiscal_year):
275 foreign_rows.append(tuple(row[field] for field in headers))
276 replacements = []
277 seen = set()
278 for d in decisions:
279 if (d.company_code, d.fiscal_year) != (company_code, fiscal_year):
280 raise MappingWorkflowError("foreign company/year in export")
281 if d.mapping_id in seen or any(
282 existing[0] == d.mapping_id for existing in foreign_rows
283 ):
284 raise MappingWorkflowError("duplicate mapping ID in export")
285 seen.add(d.mapping_id)
286 account = accounts.get((company_code, fiscal_year, d.account_full_code))
287 if account is None:
288 raise MappingWorkflowError("unknown account in export")
289 if (company_code, fiscal_year, d.target_statement, d.statement_section,
290 d.note_number, d.subnote_code) not in notes:
291 raise MappingWorkflowError("unknown note/subnote in export")
292 if d.status not in {"Draft", "Reviewed", "Approved"}:
293 raise MappingWorkflowError("invalid mapping status")
294 if d.status != "Draft" and (not d.reviewer or not d.review_date):
295 raise MappingWorkflowError("review evidence required")
296 row = {field: None for field in headers}
297 row.update({
298 "mapping_id": d.mapping_id, "company_code": company_code,
299 "fiscal_year": fiscal_year, "account_full_code": d.account_full_code,
300 "account_level": next(
301 level for field, level in (
302 ("detail4_code", "Detail4"), ("detail3_code", "Detail3"),
303 ("detail2_code", "Detail2"), ("detail1_code", "Detail1"),
304 ("subsidiary_code", "Subsidiary"), ("general_code", "General"),
305 ) if account[field] is not None
306 ),
307 "notes": previous.get(d.mapping_id, {}).get("notes"),
308 "target_statement": d.target_statement,
309 "statement_section": d.statement_section,
310 "note_number": d.note_number, "subnote_code": d.subnote_code,
311 "mapping_version": d.version, "approval_status": d.status,
312 "source": d.source, "reviewer": d.reviewer,
313 "review_date": d.review_date,
314 "validation_status": "Valid" if d.status == "Approved" else "Pending",
315 })
316 for field in ("general_code", "subsidiary_code", "detail1_code",
317 "detail2_code", "detail3_code", "detail4_code"):
318 row[field] = account[field]
319 replacements.append(tuple(row[field] for field in headers))
320 if mapping_sheet.max_row > 1:
321 mapping_sheet.delete_rows(2, mapping_sheet.max_row - 1)
322 for values in foreign_rows + replacements:
323 mapping_sheet.append(values)
324 stream = BytesIO()
325 workbook.save(stream)
326 output = stream.getvalue()
327 finally:
328 workbook.close()
329 validation = preflight_pilot_workbook(output)
330 if not validation.valid:
331 raise MappingWorkflowError(f"export preflight failed: {validation.issues[0].code}")
332 return output