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