Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 04:15 UTC
source-data-cleanup
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 | """Persistent, audited statement build + drill-down lineage (Phase 1, ADR-018). |
| 2 | |
| 3 | Turns imported LedgerBalance rows + active mappings/notes into versioned |
| 4 | FinancialStatement/StatementLine records with exact integer-rial totals and a |
| 5 | full lineage back to the source file/sheet/row. Display signs follow ADR-013 |
| 6 | (debit-positive closing; display = sign x closing). |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | from dataclasses import dataclass |
| 12 | from decimal import Decimal |
| 13 | |
| 14 | from sqlalchemy import func, select |
| 15 | from sqlalchemy.orm import Session |
| 16 | |
| 17 | from aram_backend.models import ( |
| 18 | FinancialStatement, |
| 19 | FiscalYear, |
| 20 | LedgerBalance, |
| 21 | MappingRule, |
| 22 | NoteDefinition, |
| 23 | SourceDocument, |
| 24 | StatementLine, |
| 25 | StatementType, |
| 26 | ) |
| 27 | |
| 28 | _ZERO = Decimal(0) |
| 29 | |
| 30 | # Display sign policy (ADR-013/018). Closing is debit-positive. |
| 31 | SECTION_POLICY: dict[str, dict[str, int]] = { |
| 32 | "BS": {"Assets": 1, "Liabilities": -1, "Equity": -1}, |
| 33 | "IS": {"Revenue": -1, "Expenses": 1}, |
| 34 | "CF": {"Operating": 1, "Investing": 1, "Financing": 1}, |
| 35 | "EQ": {"Equity": -1}, |
| 36 | } |
| 37 | SECTION_ORDER: dict[str, list[str]] = { |
| 38 | "BS": ["Assets", "Liabilities", "Equity"], |
| 39 | "IS": ["Revenue", "Expenses"], |
| 40 | "CF": ["Operating", "Investing", "Financing"], |
| 41 | "EQ": ["Equity"], |
| 42 | } |
| 43 | STATEMENT_LABELS_FA = { |
| 44 | "BS": "ترازنامه", |
| 45 | "IS": "صورت سود و زیان", |
| 46 | "CF": "صورت جریانهای نقدی", |
| 47 | "EQ": "صورت تغییرات حقوق مالکانه", |
| 48 | } |
| 49 | SECTION_LABELS_FA = { |
| 50 | "Assets": "داراییها", |
| 51 | "Liabilities": "بدهیها", |
| 52 | "Equity": "حقوق مالکانه", |
| 53 | "Revenue": "درآمدها", |
| 54 | "Expenses": "هزینهها", |
| 55 | "Operating": "عملیاتی", |
| 56 | "Investing": "سرمایهگذاری", |
| 57 | "Financing": "تأمین مالی", |
| 58 | } |
| 59 | RENDERED_STATEMENTS = ("BS", "IS") |
| 60 | ALL_STATEMENTS = ("BS", "IS", "CF", "EQ") |
| 61 | |
| 62 | |
| 63 | class StatementBuildError(ValueError): |
| 64 | """Raised when a statement cannot be built safely.""" |
| 65 | |
| 66 | |
| 67 | @dataclass(frozen=True) |
| 68 | class BuildResult: |
| 69 | statements: tuple[FinancialStatement, ...] |
| 70 | unmapped_accounts: tuple[str, ...] |
| 71 | |
| 72 | |
| 73 | def _effective_balance(balance: LedgerBalance) -> Decimal: |
| 74 | """The figure that contributes to a statement line. |
| 75 | |
| 76 | Reclassified source rows carry only ``مانده صورت مالی`` (statement_balance) |
| 77 | and leave CLOSING empty; that signed figure is authoritative for statement |
| 78 | presentation (Phase 4 golden). Ordinary rows use the debit-positive closing. |
| 79 | """ |
| 80 | if balance.statement_balance is not None: |
| 81 | return balance.statement_balance |
| 82 | return balance.closing |
| 83 | |
| 84 | |
| 85 | def _latest_import_version(session: Session, year_id: int) -> int | None: |
| 86 | return session.scalar( |
| 87 | select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id) |
| 88 | ) |
| 89 | |
| 90 | |
| 91 | def _latest_balances(session: Session, year_id: int) -> list[LedgerBalance]: |
| 92 | version = _latest_import_version(session, year_id) |
| 93 | if version is None: |
| 94 | return [] |
| 95 | return list( |
| 96 | session.scalars( |
| 97 | select(LedgerBalance).where( |
| 98 | LedgerBalance.year_id == year_id, |
| 99 | LedgerBalance.import_version == version, |
| 100 | ) |
| 101 | ).all() |
| 102 | ) |
| 103 | |
| 104 | |
| 105 | def _next_statement_version(session: Session, year_id: int, stype: StatementType) -> int: |
| 106 | current = session.scalar( |
| 107 | select(func.max(FinancialStatement.version)).where( |
| 108 | FinancialStatement.year_id == year_id, |
| 109 | FinancialStatement.statement_type == stype, |
| 110 | ) |
| 111 | ) |
| 112 | return (current or 0) + 1 |
| 113 | |
| 114 | |
| 115 | def build_statements( |
| 116 | session: Session, |
| 117 | year_id: int, |
| 118 | *, |
| 119 | statement_types: tuple[str, ...] = RENDERED_STATEMENTS, |
| 120 | ) -> BuildResult: |
| 121 | """Build persisted, versioned statements for a Draft year. |
| 122 | |
| 123 | Aggregates the latest ledger import per mapped note, applies the display sign |
| 124 | policy, and writes a new FinancialStatement version per requested type. |
| 125 | Unmapped active accounts are surfaced (they block approval via preflight). |
| 126 | """ |
| 127 | year = session.get(FiscalYear, year_id) |
| 128 | if year is None: |
| 129 | raise StatementBuildError(f"fiscal year {year_id} does not exist") |
| 130 | |
| 131 | balances = _latest_balances(session, year_id) |
| 132 | notes = { |
| 133 | n.id: n |
| 134 | for n in session.scalars( |
| 135 | select(NoteDefinition).where(NoteDefinition.year_id == year_id) |
| 136 | ).all() |
| 137 | } |
| 138 | rules = session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all() |
| 139 | |
| 140 | account_to_notes: dict[str, list[int]] = {} |
| 141 | for rule in rules: |
| 142 | account_to_notes.setdefault(rule.account_code, []).append(rule.target_note_id) |
| 143 | |
| 144 | # Per-note display sign (ADR-013). Reclassified rows already carry a |
| 145 | # presentation-signed statement_balance, so the sign is applied only to |
| 146 | # ordinary closing-based rows; this reproduces the Phase-4 golden exactly. |
| 147 | note_sign: dict[int, int] = {} |
| 148 | for note in notes.values(): |
| 149 | stype_code = str(note.configuration_json.get("statement") or "") |
| 150 | section = str(note.configuration_json.get("section") or "") |
| 151 | note_sign[note.id] = SECTION_POLICY.get(stype_code, {}).get(section, 1) |
| 152 | |
| 153 | note_totals: dict[int, Decimal] = {} |
| 154 | unmapped: list[str] = [] |
| 155 | for balance in balances: |
| 156 | targets = account_to_notes.get(balance.account_full_code, []) |
| 157 | if not targets: |
| 158 | if _effective_balance(balance) != _ZERO: |
| 159 | unmapped.append(balance.account_full_code) |
| 160 | continue |
| 161 | for note_id in targets: |
| 162 | if balance.statement_balance is not None: |
| 163 | contribution = balance.statement_balance |
| 164 | else: |
| 165 | contribution = note_sign.get(note_id, 1) * balance.closing |
| 166 | note_totals[note_id] = note_totals.get(note_id, _ZERO) + contribution |
| 167 | |
| 168 | built: list[FinancialStatement] = [] |
| 169 | for stype_code in statement_types: |
| 170 | if stype_code not in SECTION_POLICY: |
| 171 | raise StatementBuildError(f"unknown statement type {stype_code}") |
| 172 | stype = StatementType(stype_code) |
| 173 | policy = SECTION_POLICY[stype_code] |
| 174 | order = SECTION_ORDER[stype_code] |
| 175 | |
| 176 | member_notes = [ |
| 177 | n for n in notes.values() if n.configuration_json.get("statement") == stype_code |
| 178 | ] |
| 179 | |
| 180 | def _sort_key(n: NoteDefinition, order: list[str] = order) -> tuple[int, str]: |
| 181 | section = str(n.configuration_json.get("section") or "") |
| 182 | return (order.index(section) if section in order else len(order), n.note_number) |
| 183 | |
| 184 | member_notes.sort(key=_sort_key) |
| 185 | |
| 186 | statement = FinancialStatement( |
| 187 | year_id=year_id, |
| 188 | statement_type=stype, |
| 189 | version=_next_statement_version(session, year_id, stype), |
| 190 | ) |
| 191 | session.add(statement) |
| 192 | session.flush() |
| 193 | |
| 194 | for line_order, note in enumerate(member_notes): |
| 195 | section = note.configuration_json.get("section", "") |
| 196 | sign = policy.get(section) |
| 197 | if sign is None: |
| 198 | raise StatementBuildError( |
| 199 | f"note {note.note_number}: section '{section}' has no sign policy for {stype_code}" |
| 200 | ) |
| 201 | # note_totals already carries the presentation sign (statement_balance |
| 202 | # rows are pre-signed; closing rows were signed during accumulation). |
| 203 | total = note_totals.get(note.id, _ZERO) |
| 204 | session.add( |
| 205 | StatementLine( |
| 206 | statement_id=statement.id, |
| 207 | line_order=line_order, |
| 208 | line_label=f"{note.note_number} — {note.title}", |
| 209 | target_note_id=note.id, |
| 210 | mapped_total=total, |
| 211 | ) |
| 212 | ) |
| 213 | built.append(statement) |
| 214 | |
| 215 | session.flush() |
| 216 | return BuildResult(statements=tuple(built), unmapped_accounts=tuple(sorted(set(unmapped)))) |
| 217 | |
| 218 | |
| 219 | def drill_down(session: Session, statement_line_id: int) -> dict[str, object]: |
| 220 | """Return the full lineage of a statement line to source file/sheet/row.""" |
| 221 | line = session.get(StatementLine, statement_line_id) |
| 222 | if line is None: |
| 223 | raise StatementBuildError(f"statement line {statement_line_id} does not exist") |
| 224 | note = line.target_note |
| 225 | if note is None: |
| 226 | return {"line_id": line.id, "note": None, "accounts": []} |
| 227 | |
| 228 | rules = session.scalars(select(MappingRule).where(MappingRule.target_note_id == note.id)).all() |
| 229 | codes = sorted({r.account_code for r in rules}) |
| 230 | version = _latest_import_version(session, note.year_id) |
| 231 | balances = ( |
| 232 | session.scalars( |
| 233 | select(LedgerBalance).where( |
| 234 | LedgerBalance.year_id == note.year_id, |
| 235 | LedgerBalance.import_version == version, |
| 236 | LedgerBalance.account_full_code.in_(codes), |
| 237 | ) |
| 238 | ).all() |
| 239 | if version is not None and codes |
| 240 | else [] |
| 241 | ) |
| 242 | |
| 243 | accounts = [] |
| 244 | for balance in balances: |
| 245 | source = session.get(SourceDocument, balance.source_document_id) |
| 246 | accounts.append( |
| 247 | { |
| 248 | "account_full_code": balance.account_full_code, |
| 249 | "account_name": balance.account_name, |
| 250 | "closing": str(balance.closing), |
| 251 | "statement_balance": str(balance.statement_balance) |
| 252 | if balance.statement_balance is not None |
| 253 | else None, |
| 254 | "effective_balance": str(_effective_balance(balance)), |
| 255 | "source": { |
| 256 | "filename": source.filename if source else None, |
| 257 | "file_hash": source.file_hash if source else None, |
| 258 | "sheet": balance.source_sheet, |
| 259 | "row": balance.source_row, |
| 260 | }, |
| 261 | } |
| 262 | ) |
| 263 | return { |
| 264 | "line_id": line.id, |
| 265 | "line_label": line.line_label, |
| 266 | "mapped_total": str(line.mapped_total) if line.mapped_total is not None else None, |
| 267 | "note": {"id": note.id, "note_number": note.note_number, "title": note.title}, |
| 268 | "accounts": accounts, |
| 269 | } |
| 270 | |
| 271 | |
| 272 | __all__ = [ |
| 273 | "build_statements", |
| 274 | "drill_down", |
| 275 | "BuildResult", |
| 276 | "StatementBuildError", |
| 277 | "SECTION_POLICY", |
| 278 | "SECTION_ORDER", |
| 279 | "STATEMENT_LABELS_FA", |
| 280 | "SECTION_LABELS_FA", |
| 281 | "RENDERED_STATEMENTS", |
| 282 | "ALL_STATEMENTS", |
| 283 | ] |