@davoodmehraban89 / Aram-1 / commits / 271aa64
Fork 0

feat(gate3): add scoped mapping decisions and audited lifecycle

Davood Mehraban committed Nov 1, 2026 at 21:18 UTC 271aa64416ccfce9a2b416e02f039082e6e6e755
2 files changed +289
backend/src/aram_backend/mapping_workflow.py new
+188
@@ -0,0 +1,188 @@
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 dataclasses import dataclass, replace
9 +from datetime import datetime, timezone
10 +from io import BytesIO
11 +from typing import Iterable
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 +
37 +
38 +@dataclass(frozen=True)
39 +class MappingAuditEvent:
40 + mapping_id: str
41 + company_code: str
42 + fiscal_year: int
43 + previous_status: str | None
44 + new_status: str
45 + actor: str
46 + timestamp: str
47 + previous_version: int | None
48 + new_version: int
49 +
50 +
51 +class MappingWorkspace:
52 + """In-memory transaction boundary; never crosses the selected company/year."""
53 +
54 + def __init__(self, company_code: str, fiscal_year: int):
55 + if not isinstance(company_code, str) or not company_code.strip():
56 + raise MappingWorkflowError("company_code is required")
57 + if isinstance(fiscal_year, bool) or not isinstance(fiscal_year, int) or fiscal_year <= 0:
58 + raise MappingWorkflowError("fiscal_year must be a positive integer")
59 + self.company_code = company_code.strip()
60 + self.fiscal_year = fiscal_year
61 + self._decisions: dict[str, MappingDecision] = {}
62 + self._audit: list[MappingAuditEvent] = []
63 +
64 + @property
65 + def decisions(self) -> tuple[MappingDecision, ...]:
66 + return tuple(self._decisions[key] for key in sorted(self._decisions))
67 +
68 + @property
69 + def audit(self) -> tuple[MappingAuditEvent, ...]:
70 + return tuple(self._audit)
71 +
72 + def _check_scope(self, decision: MappingDecision) -> None:
73 + if (decision.company_code, decision.fiscal_year) != (self.company_code, self.fiscal_year):
74 + raise MappingWorkflowError("company/year isolation violation")
75 +
76 + def _record(self, old: MappingDecision | None, new: MappingDecision, actor: str) -> None:
77 + self._decisions[new.mapping_id] = new
78 + self._audit.append(MappingAuditEvent(
79 + new.mapping_id, new.company_code, new.fiscal_year,
80 + old.status if old else None, new.status, actor,
81 + datetime.now(timezone.utc).isoformat(),
82 + old.version if old else None, new.version,
83 + ))
84 +
85 + def propose(self, decision: MappingDecision, *, actor: str) -> MappingDecision:
86 + self._check_scope(decision)
87 + if not actor.strip() or not decision.mapping_id.strip() or not decision.account_full_code.strip():
88 + raise MappingWorkflowError("actor, mapping_id and account are required")
89 + if decision.status != "Draft" or decision.version != 1 or decision.reviewer is not None:
90 + raise MappingWorkflowError("new decisions must begin as unreviewed Draft v1")
91 + if decision.mapping_id in self._decisions:
92 + raise MappingWorkflowError("mapping_id already exists; use revise")
93 + if not decision.note_number or not decision.target_statement or not decision.statement_section:
94 + raise MappingWorkflowError("target statement, section and note are required")
95 + self._record(None, decision, actor)
96 + return decision
97 +
98 + def transition(self, mapping_id: str, status: str, *, actor: str) -> MappingDecision:
99 + old = self._decisions.get(mapping_id)
100 + if old is None:
101 + raise MappingWorkflowError("unknown mapping_id")
102 + allowed = {"Draft": "Reviewed", "Reviewed": "Approved"}
103 + if allowed.get(old.status) != status:
104 + raise MappingWorkflowError("invalid mapping lifecycle transition")
105 + if not actor.strip():
106 + raise MappingWorkflowError("reviewer identity required")
107 + if status == "Approved" and actor == old.reviewer:
108 + raise MappingWorkflowError("approval requires independent reviewer")
109 + new = replace(old, status=status, reviewer=actor, version=old.version + 1)
110 + self._record(old, new, actor)
111 + return new
112 +
113 + def revise(self, mapping_id: str, *, actor: str, target_statement: str,
114 + statement_section: str, note_number: str, subnote_code: str | None) -> MappingDecision:
115 + old = self._decisions.get(mapping_id)
116 + if old is None:
117 + raise MappingWorkflowError("unknown mapping_id")
118 + if not actor.strip() or not target_statement or not statement_section or not note_number:
119 + raise MappingWorkflowError("actor and complete target are required")
120 + new = replace(old, target_statement=target_statement,
121 + statement_section=statement_section, note_number=note_number,
122 + subnote_code=subnote_code, status="Draft", reviewer=None,
123 + version=old.version + 1)
124 + self._record(old, new, actor)
125 + return new
126 +
127 + def carry_forward(self, previous: Iterable[MappingDecision], *, actor: str) -> int:
128 + if not actor.strip():
129 + raise MappingWorkflowError("actor required")
130 + candidates = tuple(previous)
131 + ids = [d.mapping_id for d in candidates]
132 + if len(ids) != len(set(ids)) or any(i in self._decisions for i in ids):
133 + raise MappingWorkflowError("duplicate carry-forward mapping_id")
134 + for d in candidates:
135 + if d.company_code != self.company_code or d.fiscal_year != self.fiscal_year - 1:
136 + raise MappingWorkflowError("carry-forward source company/year mismatch")
137 + if d.status != "Approved":
138 + raise MappingWorkflowError("only approved mappings may be carried forward")
139 + for d in candidates:
140 + self.propose(replace(d, fiscal_year=self.fiscal_year, status="Draft",
141 + reviewer=None, version=1, source="CarryForward"), actor=actor)
142 + return len(candidates)
143 +
144 +
145 +def import_mapping_workbook(content: bytes, company_code: str, fiscal_year: int) -> tuple[MappingDecision, ...]:
146 + """Read only preflight-valid mapping rows; reject any out-of-scope rows."""
147 + report = preflight_pilot_workbook(content)
148 + if not report.valid:
149 + raise MappingWorkflowError(f"workbook preflight failed: {report.issues[0].code}")
150 + workbook = load_workbook(BytesIO(content), read_only=True, data_only=False)
151 + try:
152 + columns = SHEET_HEADERS["Mapping"]
153 + decisions: list[MappingDecision] = []
154 + for values in workbook["Mapping"].iter_rows(min_row=2, values_only=True):
155 + if not any(v is not None for v in values):
156 + continue
157 + row = dict(zip(columns, values))
158 + if (row["company_code"], row["fiscal_year"]) != (company_code, fiscal_year):
159 + raise MappingWorkflowError("import includes foreign company/year")
160 + decisions.append(MappingDecision(
161 + row["mapping_id"], row["company_code"], row["fiscal_year"],
162 + row["account_full_code"], row["target_statement"],
163 + row["statement_section"], row["note_number"], row["subnote_code"],
164 + row["mapping_version"], row["approval_status"], row["reviewer"], row["source"],
165 + ))
166 + return tuple(decisions)
167 + finally:
168 + workbook.close()
169 +
170 +
171 +def export_mapping_rows(decisions: Iterable[MappingDecision]) -> bytes:
172 + """Export mapping decisions to a standalone review sheet (not an approved Pilot input)."""
173 + workbook = Workbook()
174 + sheet = workbook.active
175 + sheet.title = "Mapping"
176 + columns = ("mapping_id", "company_code", "fiscal_year", "account_full_code",
177 + "target_statement", "statement_section", "note_number", "subnote_code",
178 + "mapping_version", "approval_status", "reviewer", "source")
179 + sheet.append(columns)
180 + for decision in decisions:
181 + sheet.append((decision.mapping_id, decision.company_code, decision.fiscal_year,
182 + decision.account_full_code, decision.target_statement,
183 + decision.statement_section, decision.note_number, decision.subnote_code,
184 + decision.version, decision.status, decision.reviewer, decision.source))
185 + buffer = BytesIO()
186 + workbook.save(buffer)
187 + workbook.close()
188 + return buffer.getvalue()
backend/tests/test_mapping_workflow.py new
+101
@@ -0,0 +1,101 @@
1 +from dataclasses import replace
2 +from io import BytesIO
3 +
4 +import pytest
5 +from openpyxl import load_workbook
6 +
7 +from aram_backend.mapping_workflow import (
8 + MappingDecision, MappingWorkflowError, MappingWorkspace, export_mapping_rows,
9 + import_mapping_workbook,
10 +)
11 +from test_pilot_workbook import valid_rows, workbook_bytes
12 +
13 +
14 +def sample(*, year=1405, company="001", status="Draft"):
15 + return MappingDecision("M001", company, year, "0010", "BS", "Assets",
16 + "01", "001", 1, status, None, "Manual")
17 +
18 +
19 +def test_lifecycle_requires_distinct_approver_and_records_audit():
20 + space = MappingWorkspace("001", 1405)
21 + space.propose(sample(), actor="maker")
22 + reviewed = space.transition("M001", "Reviewed", actor="reviewer")
23 + assert reviewed.version == 2
24 + with pytest.raises(MappingWorkflowError, match="independent"):
25 + space.transition("M001", "Approved", actor="reviewer")
26 + approved = space.transition("M001", "Approved", actor="approver")
27 + assert approved.version == 3
28 + assert [e.new_status for e in space.audit] == ["Draft", "Reviewed", "Approved"]
29 + assert space.audit[-1].previous_version == 2
30 + assert all(e.timestamp for e in space.audit)
31 +
32 +
33 +def test_illegal_transitions_fail_closed():
34 + space = MappingWorkspace("001", 1405)
35 + with pytest.raises(MappingWorkflowError):
36 + space.transition("missing", "Approved", actor="a")
37 + space.propose(sample(), actor="a")
38 + for status in ("Approved", "Draft", "Deleted"):
39 + with pytest.raises(MappingWorkflowError):
40 + space.transition("M001", status, actor="b")
41 + with pytest.raises(MappingWorkflowError):
42 + space.propose(sample(), actor="a")
43 + assert len(space.audit) == 1
44 +
45 +
46 +def test_revision_resets_approval_and_keeps_history():
47 + space = MappingWorkspace("001", 1405)
48 + space.propose(sample(), actor="a")
49 + space.transition("M001", "Reviewed", actor="b")
50 + space.transition("M001", "Approved", actor="c")
51 + updated = space.revise("M001", actor="a", target_statement="IS",
52 + statement_section="Revenue", note_number="02",
53 + subnote_code=None)
54 + assert updated.status == "Draft" and updated.reviewer is None
55 + assert updated.version == 4
56 + assert len(space.audit) == 4
57 + assert space.audit[-1].previous_status == "Approved"
58 +
59 +
60 +def test_company_year_isolation_and_atomic_carry_forward_validation():
61 + space = MappingWorkspace("001", 1405)
62 + with pytest.raises(MappingWorkflowError, match="isolation"):
63 + space.propose(sample(company="002"), actor="a")
64 + with pytest.raises(MappingWorkflowError, match="isolation"):
65 + space.propose(sample(year=1404), actor="a")
66 + good = replace(sample(year=1404, status="Approved"), reviewer="r")
67 + bad = replace(sample(year=1404, company="002", status="Approved"),
68 + mapping_id="M002")
69 + with pytest.raises(MappingWorkflowError):
70 + space.carry_forward([good, bad], actor="a")
71 + assert not space.decisions and not space.audit
72 + assert space.carry_forward([good], actor="a") == 1
73 + assert space.decisions[0].status == "Draft"
74 + assert space.decisions[0].source == "CarryForward"
75 + assert space.decisions[0].fiscal_year == 1405
76 +
77 +
78 +def test_invalid_scope_and_actor():
79 + for company, year in (("", 1405), ("001", 0), ("001", True)):
80 + with pytest.raises(MappingWorkflowError):
81 + MappingWorkspace(company, year)
82 + space = MappingWorkspace("001", 1405)
83 + with pytest.raises(MappingWorkflowError):
84 + space.propose(sample(), actor="")
85 +
86 +
87 +def test_import_preflight_and_export_review_rows():
88 + source = workbook_bytes(valid_rows())
89 + imported = import_mapping_workbook(source, "001", 1405)
90 + assert len(imported) == 1 and imported[0].mapping_id == "M001"
91 + with pytest.raises(MappingWorkflowError, match="foreign"):
92 + import_mapping_workbook(source, "002", 1405)
93 + with pytest.raises(MappingWorkflowError, match="preflight"):
94 + import_mapping_workbook(b"invalid", "001", 1405)
95 + exported = export_mapping_rows(imported)
96 + book = load_workbook(BytesIO(exported), read_only=True)
97 + try:
98 + assert book["Mapping"]["A2"].value == "M001"
99 + assert book["Mapping"]["C2"].value == 1405
100 + finally:
101 + book.close()