codex/aram-analyst-review-workbook-20261031
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 | """Explicit opt-in, nonofficial local analyst-review workbook export. |
| 2 | |
| 3 | Every financial value is written as a text cell to preserve exact Decimal |
| 4 | scale and prevent spreadsheet formula injection. Existing paths are never |
| 5 | overwritten. This is an evidence/review pack, not an issued financial report. |
| 6 | """ |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | from io import BytesIO |
| 10 | import os |
| 11 | from pathlib import Path |
| 12 | import unicodedata |
| 13 | |
| 14 | from openpyxl import Workbook |
| 15 | from openpyxl.cell import WriteOnlyCell |
| 16 | from openpyxl.styles import Font, PatternFill |
| 17 | from openpyxl.utils import get_column_letter |
| 18 | |
| 19 | from aram_backend.coverage_preview import CoverageError |
| 20 | from aram_backend.desktop_five_statement_details import build_preview_details |
| 21 | from aram_backend.desktop_five_statement_figures import build_preview_figures |
| 22 | from aram_backend.desktop_five_statement_integrity import validate_desktop_pipeline_result |
| 23 | from aram_backend.five_statement_pipeline import FiveStatementPipelineResult |
| 24 | |
| 25 | DISCLAIMER = ( |
| 26 | "غیررسمی — بسته بررسی کارشناسی — فاقد تأیید حسابداری و مجوز انتشار؛ " |
| 27 | "بهعنوان صورت مالی رسمی استفاده نشود" |
| 28 | ) |
| 29 | MAX_REVIEW_WORKBOOK_BYTES = 40 * 1024 * 1024 |
| 30 | MAX_EXPORT_FINDINGS = 10_000 |
| 31 | |
| 32 | SHEETS = ( |
| 33 | ("اطلاعات", "metadata"), |
| 34 | ("خلاصه مبالغ", "summary"), |
| 35 | ("ترازنامه", "ترازنامه"), |
| 36 | ("سود و زیان", "سود و زیان"), |
| 37 | ("حقوق مالکانه", "تغییرات حقوق مالکانه"), |
| 38 | ("جریان نقد", "جریان وجوه نقد"), |
| 39 | ("تراز آزمایشی", "تراز آزمایشی"), |
| 40 | ("کنترلها", "controls"), |
| 41 | ) |
| 42 | DETAIL_HEADERS = ( |
| 43 | "صورت مالی", "شرح / حساب / فعالیت", "یادداشت / شناسه", |
| 44 | "مواجهه / ردیف منبع", "افتتاحیه / منبع", "بدهکار / ورودی", |
| 45 | "بستانکار / خروجی", "تغییر", "اختتامیه / ارائه", |
| 46 | "مدرک / سیاست / ردگیری", "وضعیت", |
| 47 | ) |
| 48 | HEADER_FONT = Font(bold=True, color="FFFFFF") |
| 49 | HEADER_FILL = PatternFill(fill_type="solid", fgColor="1F4E78") |
| 50 | DISCLAIMER_FONT = Font(bold=True, color="9C0006") |
| 51 | |
| 52 | |
| 53 | def _safe_text(value: object) -> str: |
| 54 | if not isinstance(value, str) or len(value) > 32_767: |
| 55 | raise CoverageError("REVIEW_EXPORT_TEXT_INVALID") |
| 56 | for char in value: |
| 57 | category = unicodedata.category(char) |
| 58 | codepoint = ord(char) |
| 59 | if (category in {"Cc", "Cs"} |
| 60 | or (category == "Cf" and codepoint not in {0x200C, 0x200D})): |
| 61 | raise CoverageError("REVIEW_EXPORT_TEXT_CONTROL_INVALID") |
| 62 | return value |
| 63 | |
| 64 | |
| 65 | def _cell(sheet, value: object, *, style: str = ""): |
| 66 | text = _safe_text(value) |
| 67 | cell = WriteOnlyCell(sheet, value=text) |
| 68 | # openpyxl treats leading '=' as a formula by default. Force every |
| 69 | # workbook field to a literal string, including labels/evidence IDs. |
| 70 | cell.data_type = "s" |
| 71 | if style == "header": |
| 72 | cell.font = HEADER_FONT |
| 73 | cell.fill = HEADER_FILL |
| 74 | elif style == "disclaimer": |
| 75 | cell.font = DISCLAIMER_FONT |
| 76 | return cell |
| 77 | |
| 78 | |
| 79 | def _append(sheet, values, *, style: str = "") -> None: |
| 80 | sheet.append([_cell(sheet, value, style=style) for value in values]) |
| 81 | |
| 82 | |
| 83 | def _new_sheet(workbook: Workbook, title: str, metadata: str, headers: tuple[str, ...]): |
| 84 | sheet = workbook.create_sheet(title) |
| 85 | sheet.sheet_view.rightToLeft = True |
| 86 | sheet.freeze_panes = "A4" |
| 87 | _append(sheet, (DISCLAIMER,), style="disclaimer") |
| 88 | _append(sheet, (metadata,)) |
| 89 | sheet.append([]) |
| 90 | _append(sheet, headers, style="header") |
| 91 | widths = (18, 30, 28, 28, 20, 20, 20, 20, 22, 55, 24) |
| 92 | for index, width in enumerate(widths[:len(headers)], 1): |
| 93 | sheet.column_dimensions[get_column_letter(index)].width = width |
| 94 | return sheet |
| 95 | |
| 96 | |
| 97 | def _metadata_rows(result: FiveStatementPipelineResult) -> tuple[tuple[str, str], ...]: |
| 98 | state = ( |
| 99 | "قابل بررسی کارشناسی؛ غیررسمی" |
| 100 | if result.eligible_for_analyst_review else "مسدود؛ صرفاً تشخیصی" |
| 101 | ) |
| 102 | return ( |
| 103 | ("نوع خروجی", "UNAPPROVED_ANALYST_REVIEW_PACK"), |
| 104 | ("شرکت", _safe_text(result.company_code)), |
| 105 | ("سال مالی", str(result.fiscal_year)), |
| 106 | ("واحد", _safe_text(result.cash_flow.unit)), |
| 107 | ("ارز", _safe_text(result.cash_flow.currency)), |
| 108 | ("وضعیت کلی", state), |
| 109 | ("SHA256 فایل اکسل", result.source_sha256), |
| 110 | ("SHA256 مراجع یادداشت", result.balance_sheet.note_references_sha256), |
| 111 | ("SHA256 سیاست ترازنامه", result.balance_sheet.presentation_policies_sha256), |
| 112 | ("SHA256 سیاست سود و زیان", result.income_statement.presentation_policies_sha256), |
| 113 | ("SHA256 سیاست حقوق مالکانه", result.equity_changes.presentation_policies_sha256), |
| 114 | ("SHA256 دفتر تراکنش نقد", result.cash_flow.transaction_ledger_sha256), |
| 115 | ("SHA256 سیاست طبقهبندی نقد", result.cash_flow.classification_policies_sha256), |
| 116 | ("SHA256 انتخاب یادداشت نقد", result.reconciliation.cash_note_selection_sha256), |
| 117 | ("کاملبودن دفتر کل اثبات شده", "خیر"), |
| 118 | ("سیاست حسابداری تأیید شده", "خیر"), |
| 119 | ("بازبینی مستقل انجام شده", "خیر"), |
| 120 | ("صورت مالی رسمی", "خیر"), |
| 121 | ("مجوز انتشار", "خیر"), |
| 122 | ("محدودیت", DISCLAIMER), |
| 123 | ) |
| 124 | |
| 125 | |
| 126 | def build_review_workbook_bytes(result: FiveStatementPipelineResult) -> bytes: |
| 127 | """Build a bounded workbook entirely in memory; never touch source files.""" |
| 128 | validate_desktop_pipeline_result(result) |
| 129 | figures = build_preview_figures(result) |
| 130 | details = build_preview_details(result) |
| 131 | findings = result.findings |
| 132 | if not isinstance(findings, tuple) or len(findings) > MAX_EXPORT_FINDINGS: |
| 133 | raise CoverageError("REVIEW_EXPORT_FINDINGS_LIMIT") |
| 134 | |
| 135 | workbook = Workbook(write_only=True) |
| 136 | workbook.properties.title = "ARAM — UNOFFICIAL ANALYST REVIEW PACK" |
| 137 | workbook.properties.subject = DISCLAIMER |
| 138 | workbook.properties.creator = "ARAM Desktop Pilot" |
| 139 | workbook.properties.description = DISCLAIMER |
| 140 | |
| 141 | info = _new_sheet( |
| 142 | workbook, "اطلاعات", "مشخصات منبع و محدودیتهای بسته بررسی", |
| 143 | ("فیلد", "مقدار"), |
| 144 | ) |
| 145 | for label, value in _metadata_rows(result): |
| 146 | _append(info, (label, value)) |
| 147 | |
| 148 | summary = _new_sheet( |
| 149 | workbook, "خلاصه مبالغ", "۲۸ شاخص دقیق؛ مقادیر متنی و بدون گردکردن", |
| 150 | ("صورت مالی", "شاخص", "مبلغ", "وضعیت"), |
| 151 | ) |
| 152 | for figure in figures: |
| 153 | _append(summary, ( |
| 154 | figure.statement, figure.label, figure.value, figure.state, |
| 155 | )) |
| 156 | |
| 157 | for title, statement in SHEETS[2:7]: |
| 158 | sheet = _new_sheet( |
| 159 | workbook, title, |
| 160 | "ریز اقلام منبع و ارائه — صرفاً پیشنویس غیررسمی", |
| 161 | DETAIL_HEADERS, |
| 162 | ) |
| 163 | for detail in details: |
| 164 | if detail.statement == statement: |
| 165 | _append(sheet, detail.values()) |
| 166 | |
| 167 | controls = _new_sheet( |
| 168 | workbook, "کنترلها", "نتیجه کنترلهای حسابی؛ بدون تأیید یا مجوز انتشار", |
| 169 | ("کنترل", "مقدار", "وضعیت"), |
| 170 | ) |
| 171 | reconciliation = result.reconciliation |
| 172 | control_rows = ( |
| 173 | ("تطبیق ترازنامه", reconciliation.balance_sheet_difference, |
| 174 | "معتبر" if reconciliation.balance_sheet_difference == "0" else "مغایرت"), |
| 175 | ("اختلاف حقوق مالکانه", reconciliation.balance_sheet_equity_difference, |
| 176 | "معتبر" if reconciliation.balance_sheet_equity_difference == "0" else "مغایرت"), |
| 177 | ("اختلاف سود خالص", reconciliation.net_profit_equity_difference, |
| 178 | "معتبر" if reconciliation.net_profit_equity_difference == "0" else "مغایرت"), |
| 179 | ("اختلاف وجه نقد", reconciliation.balance_sheet_cash_difference, |
| 180 | "معتبر" if reconciliation.balance_sheet_cash_difference == "0" else "مغایرت"), |
| 181 | ("تطبیق سود و زیان", "بله" if reconciliation.income_statement_bridge_valid else "خیر", |
| 182 | "کنترل حسابی"), |
| 183 | ("تطبیق جریان نقد", "بله" if reconciliation.cash_flow_bridge_valid else "خیر", |
| 184 | "کنترل حسابی"), |
| 185 | ("گردش حقوق مالکانه", "بله" if reconciliation.equity_rollforward_valid else "خیر", |
| 186 | "کنترل حسابی"), |
| 187 | ("تراز آزمایشی", "بله" if reconciliation.trial_balance_arithmetic_valid else "خیر", |
| 188 | "کنترل حسابی"), |
| 189 | ("حسابهای نقد با تراز آزمایشی", "بله" if reconciliation.cash_accounts_match_trial_balance else "خیر", |
| 190 | "کنترل حسابی"), |
| 191 | ("جمع حسابهای نقد", "بله" if reconciliation.cash_account_totals_valid else "خیر", |
| 192 | "کنترل حسابی"), |
| 193 | ("منبع یکسان", "بله" if reconciliation.same_source_snapshot else "خیر", |
| 194 | "کنترل منبع"), |
| 195 | ("نتیجه کلی", "قابل بررسی" if result.eligible_for_analyst_review else "مسدود", |
| 196 | "غیررسمی"), |
| 197 | ) |
| 198 | for row in control_rows: |
| 199 | _append(controls, row) |
| 200 | _append(controls, ("مغایرتها", "کد", "وضعیت"), style="header") |
| 201 | for finding in findings: |
| 202 | _append(controls, ("یافته", _safe_text(finding), "نیازمند بررسی")) |
| 203 | |
| 204 | buffer = BytesIO() |
| 205 | try: |
| 206 | workbook.save(buffer) |
| 207 | finally: |
| 208 | workbook.close() |
| 209 | content = buffer.getvalue() |
| 210 | if not content or len(content) > MAX_REVIEW_WORKBOOK_BYTES: |
| 211 | raise CoverageError("REVIEW_EXPORT_SIZE_INVALID") |
| 212 | return content |
| 213 | |
| 214 | |
| 215 | def write_review_workbook( |
| 216 | path_value: str | os.PathLike[str], |
| 217 | result: FiveStatementPipelineResult, |
| 218 | ) -> Path: |
| 219 | """Create a new local review workbook; fail rather than overwrite any path.""" |
| 220 | try: |
| 221 | target = Path(path_value) |
| 222 | except (TypeError, ValueError, OSError) as exc: |
| 223 | raise CoverageError("REVIEW_EXPORT_PATH_INVALID") from exc |
| 224 | if target.suffix.lower() != ".xlsx": |
| 225 | raise CoverageError("REVIEW_EXPORT_EXTENSION_INVALID") |
| 226 | if not target.parent.is_dir(): |
| 227 | raise CoverageError("REVIEW_EXPORT_PARENT_INVALID") |
| 228 | if target.exists() or target.is_symlink(): |
| 229 | raise CoverageError("REVIEW_EXPORT_TARGET_EXISTS") |
| 230 | |
| 231 | content = build_review_workbook_bytes(result) |
| 232 | flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL |
| 233 | flags |= getattr(os, "O_BINARY", 0) |
| 234 | try: |
| 235 | descriptor = os.open(str(target), flags, 0o600) |
| 236 | except FileExistsError as exc: |
| 237 | raise CoverageError("REVIEW_EXPORT_TARGET_EXISTS") from exc |
| 238 | except (OSError, ValueError) as exc: |
| 239 | raise CoverageError("REVIEW_EXPORT_PATH_INVALID") from exc |
| 240 | |
| 241 | try: |
| 242 | with os.fdopen(descriptor, "wb") as stream: |
| 243 | stream.write(content) |
| 244 | stream.flush() |
| 245 | os.fsync(stream.fileno()) |
| 246 | except Exception as exc: |
| 247 | try: |
| 248 | target.unlink() |
| 249 | except OSError: |
| 250 | pass |
| 251 | raise CoverageError("REVIEW_EXPORT_WRITE_FAILED") from exc |
| 252 | return target |