arena/094f314c-aram
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 | """Bounded, thread-safe in-memory session store for the Pilot workbench. |
| 2 | |
| 3 | Each session holds a mutable WorkingModel (company, accounts, notes, mappings) |
| 4 | plus an append-only audit trail. Source workbook bytes are never retained. |
| 5 | Everything disappears on restart by design; the durable artifacts are the |
| 6 | exported Excel report and the re-uploadable "save workspace" workbook. |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import threading |
| 12 | import uuid |
| 13 | from dataclasses import dataclass, field |
| 14 | from datetime import UTC, datetime |
| 15 | |
| 16 | from aram_backend.pilot_editing import ( |
| 17 | SYNTHETIC_SOURCE_ROW_BASE, |
| 18 | DuplicateAccountError, |
| 19 | DuplicateNoteError, |
| 20 | NoteInUseError, |
| 21 | UnknownNoteError, |
| 22 | make_account, |
| 23 | ) |
| 24 | from aram_backend.pilot_engine import ( |
| 25 | MappingEntry, |
| 26 | NoteTarget, |
| 27 | PilotAccount, |
| 28 | PilotCompany, |
| 29 | PilotModel, |
| 30 | WorkingModel, |
| 31 | ) |
| 32 | |
| 33 | MAX_SESSIONS = 32 |
| 34 | |
| 35 | |
| 36 | def _now() -> str: |
| 37 | return datetime.now(UTC).isoformat(timespec="seconds") |
| 38 | |
| 39 | |
| 40 | def _mapping_summary(entry: MappingEntry | None) -> str: |
| 41 | if entry is None: |
| 42 | return "(بدون نگاشت)" |
| 43 | return ( |
| 44 | f"{entry.statement}/{entry.section}/{entry.note_number}" |
| 45 | + (f"/{entry.subnote_code}" if entry.subnote_code else "") |
| 46 | + f" [{entry.approval_status}]" |
| 47 | ) |
| 48 | |
| 49 | |
| 50 | def _account_summary(account: PilotAccount | None) -> str: |
| 51 | if account is None: |
| 52 | return "(حذف شد)" |
| 53 | return f"{account.full_code} {account.name} | مانده {account.closing}" |
| 54 | |
| 55 | |
| 56 | def _note_summary(note: NoteTarget | None) -> str: |
| 57 | if note is None: |
| 58 | return "(حذف شد)" |
| 59 | return ( |
| 60 | f"{note.statement}/{note.section}/{note.note_number}" |
| 61 | + (f"/{note.subnote_code}" if note.subnote_code else "") |
| 62 | + f" — {note.note_title}" |
| 63 | ) |
| 64 | |
| 65 | |
| 66 | def _company_summary(company: PilotCompany) -> str: |
| 67 | return f"{company.code} {company.name} | سال {company.fiscal_year} | {company.unit}" |
| 68 | |
| 69 | |
| 70 | @dataclass |
| 71 | class PilotSession: |
| 72 | id: str |
| 73 | working: WorkingModel |
| 74 | source: str |
| 75 | filename: str |
| 76 | created_at: str = field(default_factory=_now) |
| 77 | audit_trail: list[dict] = field(default_factory=list) |
| 78 | synthetic_counter: int = 0 |
| 79 | |
| 80 | # Compatibility surface: report/table/export functions accept WorkingModel. |
| 81 | @property |
| 82 | def model(self) -> WorkingModel: |
| 83 | return self.working |
| 84 | |
| 85 | @property |
| 86 | def mappings(self) -> dict[str, MappingEntry]: |
| 87 | return self.working.mappings |
| 88 | |
| 89 | |
| 90 | class UnknownSessionError(KeyError): |
| 91 | pass |
| 92 | |
| 93 | |
| 94 | class UnknownAccountError(KeyError): |
| 95 | pass |
| 96 | |
| 97 | |
| 98 | class UnknownTargetError(ValueError): |
| 99 | pass |
| 100 | |
| 101 | |
| 102 | class InvalidApprovalError(ValueError): |
| 103 | pass |
| 104 | |
| 105 | |
| 106 | class PilotSessionStore: |
| 107 | def __init__(self, max_sessions: int = MAX_SESSIONS) -> None: |
| 108 | self._sessions: dict[str, PilotSession] = {} |
| 109 | self._order: list[str] = [] |
| 110 | self._lock = threading.RLock() |
| 111 | self._max = max_sessions |
| 112 | |
| 113 | # ------------------------------------------------------------------ core |
| 114 | def create(self, model: PilotModel, source: str, filename: str) -> PilotSession: |
| 115 | session = PilotSession( |
| 116 | id=uuid.uuid4().hex, |
| 117 | working=WorkingModel.from_model(model), |
| 118 | source=source, |
| 119 | filename=filename, |
| 120 | ) |
| 121 | with self._lock: |
| 122 | self._sessions[session.id] = session |
| 123 | self._order.append(session.id) |
| 124 | while len(self._order) > self._max: |
| 125 | oldest = self._order.pop(0) |
| 126 | self._sessions.pop(oldest, None) |
| 127 | return session |
| 128 | |
| 129 | def get(self, session_id: str) -> PilotSession: |
| 130 | with self._lock: |
| 131 | session = self._sessions.get(session_id) |
| 132 | if session is None: |
| 133 | raise UnknownSessionError(session_id) |
| 134 | return session |
| 135 | |
| 136 | def snapshot(self, session_id: str) -> tuple[PilotSession, WorkingModel, list]: |
| 137 | """Consistent working-model copy + trail for lock-free report building.""" |
| 138 | session = self.get(session_id) |
| 139 | with self._lock: |
| 140 | return session, session.working.copy(), list(session.audit_trail) |
| 141 | |
| 142 | def delete(self, session_id: str) -> None: |
| 143 | with self._lock: |
| 144 | if session_id not in self._sessions: |
| 145 | raise UnknownSessionError(session_id) |
| 146 | del self._sessions[session_id] |
| 147 | self._order.remove(session_id) |
| 148 | |
| 149 | def _audit(self, session: PilotSession, actor: str, account_code: str, |
| 150 | action: str, before: str, after: str) -> None: |
| 151 | session.audit_trail.append({ |
| 152 | "at": _now(), |
| 153 | "actor": actor.strip() or "workbench-user", |
| 154 | "account_code": account_code, |
| 155 | "action": action, |
| 156 | "before": before, |
| 157 | "after": after, |
| 158 | }) |
| 159 | |
| 160 | # -------------------------------------------------------------- mappings |
| 161 | def set_mapping( |
| 162 | self, session_id: str, account_code: str, *, statement: str, section: str, |
| 163 | note_number: str, subnote_code: str = "", approval_status: str = "Draft", |
| 164 | reviewer: str = "", actor: str = "workbench-user", |
| 165 | ) -> PilotSession: |
| 166 | session = self.get(session_id) |
| 167 | with self._lock: |
| 168 | if account_code not in session.working.accounts: |
| 169 | raise UnknownAccountError(account_code) |
| 170 | key = (statement, section, note_number, subnote_code) |
| 171 | if key not in session.working.notes: |
| 172 | raise UnknownTargetError( |
| 173 | "Target statement/section/note/sub-note does not exist in Notes." |
| 174 | ) |
| 175 | if approval_status not in {"Draft", "Reviewed", "Approved"}: |
| 176 | raise InvalidApprovalError("Allowed approval statuses: Draft, Reviewed, Approved.") |
| 177 | if approval_status in {"Reviewed", "Approved"} and not reviewer.strip(): |
| 178 | raise InvalidApprovalError( |
| 179 | "Reviewed/Approved mappings require a reviewer name as evidence." |
| 180 | ) |
| 181 | before = session.mappings.get(account_code) |
| 182 | entry = MappingEntry( |
| 183 | account_code=account_code, statement=statement, section=section, |
| 184 | note_number=note_number, subnote_code=subnote_code, |
| 185 | approval_status=approval_status, reviewer=reviewer.strip(), |
| 186 | source="workbench", mapping_id=f"WB-{uuid.uuid4().hex[:10]}", |
| 187 | ) |
| 188 | session.mappings[account_code] = entry |
| 189 | session.working.conflicts.pop(account_code, None) |
| 190 | self._audit(session, actor, account_code, "set_mapping", |
| 191 | _mapping_summary(before), |
| 192 | _mapping_summary(entry) |
| 193 | + (f" بازبین: {entry.reviewer}" if entry.reviewer else "")) |
| 194 | return session |
| 195 | |
| 196 | def clear_mapping(self, session_id: str, account_code: str, |
| 197 | actor: str = "workbench-user") -> PilotSession: |
| 198 | session = self.get(session_id) |
| 199 | with self._lock: |
| 200 | if account_code not in session.working.accounts: |
| 201 | raise UnknownAccountError(account_code) |
| 202 | before = session.mappings.pop(account_code, None) |
| 203 | self._audit(session, actor, account_code, "clear_mapping", |
| 204 | _mapping_summary(before), "(بدون نگاشت)") |
| 205 | return session |
| 206 | |
| 207 | # -------------------------------------------------------------- accounts |
| 208 | def add_account( |
| 209 | self, session_id: str, *, full_code: str, name: str, general_code: str, |
| 210 | general_name: str, opening, debit, credit, source_row: int | None = None, |
| 211 | row_status: str = "Draft", subsidiary_code: str = "", subsidiary_name: str = "", |
| 212 | actor: str = "workbench-user", |
| 213 | ) -> PilotSession: |
| 214 | session = self.get(session_id) |
| 215 | with self._lock: |
| 216 | code = (full_code or "").strip() |
| 217 | if code in session.working.accounts: |
| 218 | raise DuplicateAccountError(f"حساب با کد {code} از قبل وجود دارد.") |
| 219 | if source_row is None: |
| 220 | session.synthetic_counter += 1 |
| 221 | source_row = SYNTHETIC_SOURCE_ROW_BASE + session.synthetic_counter |
| 222 | account = make_account( |
| 223 | full_code=code, name=name, general_code=general_code, |
| 224 | general_name=general_name, opening=opening, debit=debit, credit=credit, |
| 225 | source_row=source_row, row_status=row_status, |
| 226 | subsidiary_code=subsidiary_code, subsidiary_name=subsidiary_name, |
| 227 | ) |
| 228 | session.working.accounts[account.full_code] = account |
| 229 | session.working.accounts = dict(sorted(session.working.accounts.items())) |
| 230 | self._audit(session, actor, account.full_code, "add_account", |
| 231 | "(وجود نداشت)", _account_summary(account)) |
| 232 | return session |
| 233 | |
| 234 | def update_account( |
| 235 | self, session_id: str, code: str, *, name: str, general_code: str, |
| 236 | general_name: str, opening, debit, credit, row_status: str = "Draft", |
| 237 | subsidiary_code: str = "", subsidiary_name: str = "", |
| 238 | actor: str = "workbench-user", |
| 239 | ) -> PilotSession: |
| 240 | session = self.get(session_id) |
| 241 | with self._lock: |
| 242 | existing = session.working.accounts.get(code) |
| 243 | if existing is None: |
| 244 | raise UnknownAccountError(code) |
| 245 | account = make_account( |
| 246 | full_code=code, name=name, general_code=general_code, |
| 247 | general_name=general_name, opening=opening, debit=debit, credit=credit, |
| 248 | source_row=existing.source_row, row_status=row_status, |
| 249 | subsidiary_code=subsidiary_code, subsidiary_name=subsidiary_name, |
| 250 | ) |
| 251 | session.working.accounts[code] = account |
| 252 | self._audit(session, actor, code, "update_account", |
| 253 | _account_summary(existing), _account_summary(account)) |
| 254 | return session |
| 255 | |
| 256 | def rename_account(self, session_id: str, old_code: str, new_code: str, |
| 257 | actor: str = "workbench-user") -> PilotSession: |
| 258 | session = self.get(session_id) |
| 259 | with self._lock: |
| 260 | existing = session.working.accounts.get(old_code) |
| 261 | if existing is None: |
| 262 | raise UnknownAccountError(old_code) |
| 263 | new_code = (new_code or "").strip() |
| 264 | if not new_code or new_code.startswith("="): |
| 265 | raise DuplicateAccountError("کد جدید باید متن ساده و غیرخالی باشد.") |
| 266 | if new_code != old_code and new_code in session.working.accounts: |
| 267 | raise DuplicateAccountError(f"حساب با کد {new_code} از قبل وجود دارد.") |
| 268 | from dataclasses import replace |
| 269 | renamed = replace(existing, full_code=new_code) |
| 270 | del session.working.accounts[old_code] |
| 271 | session.working.accounts[new_code] = renamed |
| 272 | session.working.accounts = dict(sorted(session.working.accounts.items())) |
| 273 | mapping = session.mappings.pop(old_code, None) |
| 274 | if mapping is not None: |
| 275 | session.mappings[new_code] = replace(mapping, account_code=new_code) |
| 276 | conflict = session.working.conflicts.pop(old_code, None) |
| 277 | if conflict is not None: |
| 278 | session.working.conflicts[new_code] = tuple( |
| 279 | replace(item, account_code=new_code) for item in conflict |
| 280 | ) |
| 281 | self._audit(session, actor, new_code, "rename_account", |
| 282 | f"کد قبلی: {old_code}", f"کد جدید: {new_code} (نگاشت منتقل شد)") |
| 283 | return session |
| 284 | |
| 285 | def delete_account(self, session_id: str, code: str, |
| 286 | actor: str = "workbench-user") -> PilotSession: |
| 287 | session = self.get(session_id) |
| 288 | with self._lock: |
| 289 | existing = session.working.accounts.pop(code, None) |
| 290 | if existing is None: |
| 291 | raise UnknownAccountError(code) |
| 292 | session.mappings.pop(code, None) |
| 293 | session.working.conflicts.pop(code, None) |
| 294 | self._audit(session, actor, code, "delete_account", |
| 295 | _account_summary(existing), "(حذف شد)") |
| 296 | return session |
| 297 | |
| 298 | # ----------------------------------------------------------------- notes |
| 299 | def add_note(self, session_id: str, note: NoteTarget, |
| 300 | actor: str = "workbench-user") -> PilotSession: |
| 301 | session = self.get(session_id) |
| 302 | with self._lock: |
| 303 | if note.key in session.working.notes: |
| 304 | raise DuplicateNoteError("این یادداشت/زیریادداشت از قبل وجود دارد.") |
| 305 | session.working.notes[note.key] = note |
| 306 | self._audit(session, actor, "", "add_note", "(وجود نداشت)", _note_summary(note)) |
| 307 | return session |
| 308 | |
| 309 | def update_note(self, session_id: str, key: tuple, note: NoteTarget, |
| 310 | actor: str = "workbench-user") -> PilotSession: |
| 311 | session = self.get(session_id) |
| 312 | with self._lock: |
| 313 | existing = session.working.notes.get(key) |
| 314 | if existing is None: |
| 315 | raise UnknownNoteError("یادداشت مورد نظر یافت نشد.") |
| 316 | if note.key != key: |
| 317 | raise UnknownNoteError("کلید یادداشت قابل تغییر نیست؛ فقط عنوان ویرایش میشود.") |
| 318 | session.working.notes[key] = note |
| 319 | self._audit(session, actor, "", "update_note", |
| 320 | _note_summary(existing), _note_summary(note)) |
| 321 | return session |
| 322 | |
| 323 | def delete_note(self, session_id: str, key: tuple, |
| 324 | actor: str = "workbench-user") -> PilotSession: |
| 325 | session = self.get(session_id) |
| 326 | with self._lock: |
| 327 | existing = session.working.notes.get(key) |
| 328 | if existing is None: |
| 329 | raise UnknownNoteError("یادداشت مورد نظر یافت نشد.") |
| 330 | in_use = [code for code, m in session.mappings.items() if m.target_key == key] |
| 331 | if in_use: |
| 332 | raise NoteInUseError( |
| 333 | f"این یادداشت مقصد {len(in_use)} نگاشت است؛ ابتدا نگاشتها را جابهجا کنید." |
| 334 | ) |
| 335 | del session.working.notes[key] |
| 336 | self._audit(session, actor, "", "delete_note", _note_summary(existing), "(حذف شد)") |
| 337 | return session |
| 338 | |
| 339 | # --------------------------------------------------------------- company |
| 340 | def update_company(self, session_id: str, company: PilotCompany, |
| 341 | actor: str = "workbench-user") -> PilotSession: |
| 342 | session = self.get(session_id) |
| 343 | with self._lock: |
| 344 | before = session.working.company |
| 345 | session.working.company = company |
| 346 | self._audit(session, actor, "", "update_company", |
| 347 | _company_summary(before), _company_summary(company)) |
| 348 | return session |
| 349 | |
| 350 | |
| 351 | store = PilotSessionStore() |