codex/aram-five-statement-cli-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 | """Read-only trial balance diagnostic for an authorized Pilot XLSX snapshot. |
| 2 | |
| 3 | This checks source account arithmetic and debit/credit equality within an |
| 4 | explicit company-year scope. It does not perform financial postings, issue |
| 5 | audited statements, or assert that the provided ledger is complete. |
| 6 | """ |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | from dataclasses import asdict, dataclass |
| 10 | from hashlib import sha256 |
| 11 | from io import BytesIO |
| 12 | from typing import Any |
| 13 | |
| 14 | from openpyxl import load_workbook |
| 15 | |
| 16 | from aram_backend.coverage_preview import ( |
| 17 | CoverageError, MAX_INPUT_BYTES, _assert_visible, _guard_archive, |
| 18 | ) |
| 19 | from aram_backend.pilot_workbook import SHEET_HEADERS, preflight_pilot_workbook |
| 20 | from aram_backend.reconciliation_review import _money, _sum_exact |
| 21 | |
| 22 | |
| 23 | @dataclass(frozen=True) |
| 24 | class TrialBalanceAccount: |
| 25 | account_code: str |
| 26 | account_name: str |
| 27 | excel_row: int |
| 28 | source_row: int |
| 29 | opening: str |
| 30 | debit: str |
| 31 | credit: str |
| 32 | closing: str |
| 33 | debit_net_movement: str |
| 34 | |
| 35 | |
| 36 | @dataclass(frozen=True) |
| 37 | class TrialBalanceDiagnostic: |
| 38 | company_code: str |
| 39 | fiscal_year: int |
| 40 | source_sha256: str |
| 41 | account_count: int |
| 42 | opening_debit_net_total: str |
| 43 | debit_turnover_total: str |
| 44 | credit_turnover_total: str |
| 45 | closing_debit_net_total: str |
| 46 | movement_difference: str |
| 47 | opening_to_closing_difference: str |
| 48 | findings: tuple[str, ...] |
| 49 | accounts: tuple[TrialBalanceAccount, ...] |
| 50 | balanced_for_analyst_review: bool |
| 51 | kind: str = "UNAPPROVED_TRIAL_BALANCE_DIAGNOSTIC" |
| 52 | source_ledger_completeness_verified: bool = False |
| 53 | accounting_policies_verified: bool = False |
| 54 | official_financial_statement: bool = False |
| 55 | independently_reviewed: bool = False |
| 56 | releasable: bool = False |
| 57 | |
| 58 | def to_dict(self) -> dict[str, Any]: |
| 59 | return asdict(self) |
| 60 | |
| 61 | |
| 62 | def _scoped(row: dict[str, Any], *, company: str, fiscal_year: int) -> bool: |
| 63 | return ( |
| 64 | isinstance(row.get("company_code"), str) |
| 65 | and row["company_code"].strip() == company |
| 66 | and type(row.get("fiscal_year")) is int |
| 67 | and row["fiscal_year"] == fiscal_year |
| 68 | ) |
| 69 | |
| 70 | |
| 71 | def _read_records(sheet: Any, columns: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]: |
| 72 | records: list[tuple[int, dict[str, Any]]] = [] |
| 73 | for row_number, values in enumerate( |
| 74 | sheet.iter_rows(min_row=2, values_only=True), 2 |
| 75 | ): |
| 76 | row = dict(zip(columns, values)) |
| 77 | if any(cell is not None and str(cell).strip() for cell in row.values()): |
| 78 | records.append((row_number, row)) |
| 79 | return records |
| 80 | |
| 81 | |
| 82 | def analyze_trial_balance( |
| 83 | workbook_bytes: bytes, *, company_code: str, fiscal_year: int, |
| 84 | ) -> TrialBalanceDiagnostic: |
| 85 | """Reconcile row and column totals without claiming source completeness. |
| 86 | |
| 87 | The check assumes opening and closing figures are *debit-net*, meaning a |
| 88 | credit-net account has a negative balance. It does not infer the sign from |
| 89 | an account label. Incorrectly signed input can appear balanced, so the |
| 90 | result is NEVER sufficient for financial authorization or release. |
| 91 | """ |
| 92 | if (not isinstance(company_code, str) or not company_code.strip() |
| 93 | or len(company_code) > 64): |
| 94 | raise CoverageError("TRIAL_BALANCE_COMPANY_SCOPE_INVALID") |
| 95 | if type(fiscal_year) is not int or fiscal_year <= 0: |
| 96 | raise CoverageError("TRIAL_BALANCE_YEAR_SCOPE_INVALID") |
| 97 | if (not isinstance(workbook_bytes, bytes) |
| 98 | or not 0 < len(workbook_bytes) <= MAX_INPUT_BYTES): |
| 99 | raise CoverageError("TRIAL_BALANCE_SIZE_INVALID") |
| 100 | _guard_archive(workbook_bytes) |
| 101 | try: |
| 102 | preflight = preflight_pilot_workbook(workbook_bytes) |
| 103 | except Exception as exc: |
| 104 | raise CoverageError("TRIAL_BALANCE_WORKBOOK_INVALID") from exc |
| 105 | if not preflight.valid: |
| 106 | raise CoverageError("TRIAL_BALANCE_WORKBOOK_INVALID") |
| 107 | |
| 108 | try: |
| 109 | book = load_workbook( |
| 110 | BytesIO(workbook_bytes), read_only=False, |
| 111 | data_only=False, keep_links=False, |
| 112 | ) |
| 113 | except Exception as exc: |
| 114 | raise CoverageError("TRIAL_BALANCE_WORKBOOK_INVALID") from exc |
| 115 | try: |
| 116 | for sheet in book.worksheets: |
| 117 | _assert_visible(sheet) |
| 118 | for name, expected in SHEET_HEADERS.items(): |
| 119 | if name not in book or tuple(cell.value for cell in book[name][1]) != expected: |
| 120 | raise CoverageError("TRIAL_BALANCE_WORKBOOK_INVALID") |
| 121 | |
| 122 | company = company_code.strip() |
| 123 | scope = {"company": company, "fiscal_year": fiscal_year} |
| 124 | companies = [ |
| 125 | row for _, row in _read_records(book["Company"], SHEET_HEADERS["Company"]) |
| 126 | if _scoped(row, **scope) |
| 127 | ] |
| 128 | if len(companies) != 1: |
| 129 | raise CoverageError("TRIAL_BALANCE_COMPANY_NOT_FOUND") |
| 130 | |
| 131 | accounts: list[TrialBalanceAccount] = [] |
| 132 | openings = [] |
| 133 | debits = [] |
| 134 | credits = [] |
| 135 | closings = [] |
| 136 | net_movements = [] |
| 137 | codes: set[str] = set() |
| 138 | |
| 139 | for row_number, row in _read_records(book["Accounts"], SHEET_HEADERS["Accounts"]): |
| 140 | if not _scoped(row, **scope): |
| 141 | continue |
| 142 | code = row.get("account_full_code") |
| 143 | if not isinstance(code, str) or not code.strip(): |
| 144 | raise CoverageError("TRIAL_BALANCE_ACCOUNT_CODE_INVALID") |
| 145 | code = code.strip() |
| 146 | if code in codes: |
| 147 | raise CoverageError("TRIAL_BALANCE_DUPLICATE_ACCOUNT") |
| 148 | codes.add(code) |
| 149 | opening, debit, credit, closing = ( |
| 150 | _money(str(row[key])) for key in ("opening", "debit", "credit", "closing") |
| 151 | ) |
| 152 | movement = _sum_exact([debit, -credit]) |
| 153 | if _sum_exact([opening, movement, -closing]) != 0: |
| 154 | raise CoverageError("TRIAL_BALANCE_ROW_DELTA_INVALID") |
| 155 | if debit < 0 or credit < 0: |
| 156 | raise CoverageError("TRIAL_BALANCE_NEGATIVE_TURNOVER") |
| 157 | if row.get("source_row") is None or type(row["source_row"]) is not int: |
| 158 | raise CoverageError("TRIAL_BALANCE_SOURCE_ROW_INVALID") |
| 159 | accounts.append(TrialBalanceAccount( |
| 160 | account_code=code, account_name=str(row["account_name"]), |
| 161 | excel_row=row_number, source_row=row["source_row"], |
| 162 | opening=str(opening), debit=str(debit), credit=str(credit), |
| 163 | closing=str(closing), debit_net_movement=str(movement), |
| 164 | )) |
| 165 | openings.append(opening) |
| 166 | debits.append(debit) |
| 167 | credits.append(credit) |
| 168 | closings.append(closing) |
| 169 | net_movements.append(movement) |
| 170 | |
| 171 | if not accounts: |
| 172 | raise CoverageError("TRIAL_BALANCE_NO_ACCOUNTS") |
| 173 | opening_total = _sum_exact(openings) |
| 174 | debit_total = _sum_exact(debits) |
| 175 | credit_total = _sum_exact(credits) |
| 176 | closing_total = _sum_exact(closings) |
| 177 | net_total = _sum_exact(net_movements) |
| 178 | movement_diff = _sum_exact([debit_total, -credit_total]) |
| 179 | rolling_diff = _sum_exact([opening_total, net_total, -closing_total]) |
| 180 | findings: list[str] = [] |
| 181 | if opening_total != 0: |
| 182 | findings.append("OPENING_DEBIT_NET_UNBALANCED") |
| 183 | if movement_diff != 0: |
| 184 | findings.append("DEBIT_CREDIT_TURNOVER_UNBALANCED") |
| 185 | if closing_total != 0: |
| 186 | findings.append("CLOSING_DEBIT_NET_UNBALANCED") |
| 187 | if rolling_diff != 0: |
| 188 | findings.append("ROLL_FORWARD_INCONSISTENT") |
| 189 | |
| 190 | return TrialBalanceDiagnostic( |
| 191 | company_code=company, fiscal_year=fiscal_year, |
| 192 | source_sha256=sha256(workbook_bytes).hexdigest(), |
| 193 | account_count=len(accounts), |
| 194 | opening_debit_net_total=str(opening_total), |
| 195 | debit_turnover_total=str(debit_total), |
| 196 | credit_turnover_total=str(credit_total), |
| 197 | closing_debit_net_total=str(closing_total), |
| 198 | movement_difference=str(movement_diff), |
| 199 | opening_to_closing_difference=str(rolling_diff), |
| 200 | findings=tuple(findings), |
| 201 | accounts=tuple(sorted(accounts, key=lambda acc: acc.account_code)), |
| 202 | balanced_for_analyst_review=not findings, |
| 203 | ) |
| 204 | finally: |
| 205 | book.close() |