Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 14:15 UTC
dependabot/github_actions/actions/setup-node-6
add-index-html-10623938925177053894
arena/094f314c-aram
arena/2d4eda07-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
dependabot/github_actions/actions/checkout-7
dependabot/github_actions/actions/setup-node-6
dependabot/github_actions/actions/setup-python-7
dependabot/github_actions/actions/upload-artifact-7
dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1
dependabot/npm_and_yarn/frontend/globals-17.15.0
dependabot/npm_and_yarn/frontend/vite-8.4.0
dependabot/npm_and_yarn/frontend/vitest-5.1.2
dependabot/npm_and_yarn/frontend/vitest/coverage-v8-5.1.2
dependabot/pip/backend/mypy-gte-1.13-and-lt-3
dependabot/pip/backend/pytest-cov-gte-6.0-and-lt-8
dependabot/pip/backend/setuptools-gte-75-and-lt-85
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 | """Blocking financial controls C-01..C-15 (booklet 1 section 7; R2 of booklet 2.1). |
| 2 | |
| 3 | Pure, deterministic functions over balance rows and active mappings. Each |
| 4 | returns a :class:`ControlResult` with a Persian message and the affected |
| 5 | accounts/rows. ERROR severity blocks approval (P-09); these are not ignorable |
| 6 | warnings. Sign convention is debit-positive (ADR-013, evidence: 252892/252898 |
| 7 | canonical rows satisfy C-01 under debit-positive vs 37% under credit-positive). |
| 8 | |
| 9 | R2 rule (booklet 2.1): a control whose inputs are unavailable reports |
| 10 | "اجرا نشد: <دلیل>" and **blocks approval** — an unrun ERROR control is never |
| 11 | treated as a pass. Optional inputs travel in :class:`ControlContext`. |
| 12 | """ |
| 13 | |
| 14 | from __future__ import annotations |
| 15 | |
| 16 | from dataclasses import dataclass, field |
| 17 | from decimal import Decimal |
| 18 | |
| 19 | _ZERO = Decimal(0) |
| 20 | |
| 21 | |
| 22 | @dataclass(frozen=True) |
| 23 | class BalanceRow: |
| 24 | """One ledger balance row (all amounts exact Decimal rial). |
| 25 | |
| 26 | ``statement_balance`` is the reclassified figure some source rows carry |
| 27 | instead of CLOSING. Like CLOSING it is debit-positive, so the section display |
| 28 | sign applies to it too (ADR-032, measured: BS 16/16 against the official |
| 29 | 1404 balance sheet). C-01/C-02 still audit the raw debit/credit columns. |
| 30 | """ |
| 31 | |
| 32 | row_number: int |
| 33 | account_code: str |
| 34 | opening: Decimal |
| 35 | debit: Decimal |
| 36 | credit: Decimal |
| 37 | closing: Decimal |
| 38 | statement_balance: Decimal | None = None |
| 39 | source_note: str = "" |
| 40 | |
| 41 | def display(self, sign: Decimal, basis: str = "auto") -> Decimal: |
| 42 | """The figure a statement line shows for this row under ``sign``. |
| 43 | |
| 44 | Mirrors ``build_statements`` exactly (ADR-032). ``basis`` is decided by |
| 45 | the import, not guessed per row: when a source provides statement |
| 46 | balances at all, that column is the statement figure and a row without |
| 47 | one contributes nothing (falling back to CLOSING there contaminated the |
| 48 | official comparison); otherwise CLOSING is the figure. |
| 49 | """ |
| 50 | if basis == "statement_balance": |
| 51 | figure = self.statement_balance if self.statement_balance is not None else _ZERO |
| 52 | elif basis == "closing": |
| 53 | figure = self.closing |
| 54 | else: |
| 55 | figure = self.statement_balance if self.statement_balance is not None else self.closing |
| 56 | return figure * sign |
| 57 | |
| 58 | |
| 59 | @dataclass(frozen=True) |
| 60 | class MappingTarget: |
| 61 | """One active mapping target for an account; weight is a percentage.""" |
| 62 | |
| 63 | target: str |
| 64 | weight: Decimal = Decimal(100) |
| 65 | |
| 66 | |
| 67 | @dataclass(frozen=True) |
| 68 | class ControlResult: |
| 69 | code: str |
| 70 | severity: str |
| 71 | passed: bool |
| 72 | message_fa: str |
| 73 | affected: tuple[str, ...] = field(default_factory=tuple) |
| 74 | ran: bool = True |
| 75 | |
| 76 | |
| 77 | @dataclass(frozen=True) |
| 78 | class EquityMovement: |
| 79 | """One equity row: opening + changes must equal closing (C-09).""" |
| 80 | |
| 81 | label: str |
| 82 | opening: Decimal |
| 83 | changes: Decimal |
| 84 | closing: Decimal |
| 85 | |
| 86 | |
| 87 | @dataclass(frozen=True) |
| 88 | class OfficialComparison: |
| 89 | """One (statement, note) comparison against the official statements (C-13).""" |
| 90 | |
| 91 | key: str |
| 92 | ours: Decimal |
| 93 | official: Decimal |
| 94 | |
| 95 | |
| 96 | @dataclass(frozen=True) |
| 97 | class ControlContext: |
| 98 | """Optional inputs for C-05..C-15. ``None`` means "not available". |
| 99 | |
| 100 | Every unavailable input makes its control report «اجرا نشد» and block |
| 101 | approval, so a year can never be approved on an incomplete control set. |
| 102 | """ |
| 103 | |
| 104 | prior_closing: dict[str, Decimal] | None = None |
| 105 | bs_sections: dict[str, Decimal] | None = None |
| 106 | note_totals: dict[str, Decimal] | None = None |
| 107 | line_totals: dict[str, Decimal] | None = None |
| 108 | is_net_profit: Decimal | None = None |
| 109 | eq_retained_change: Decimal | None = None |
| 110 | explicit_adjustments: Decimal = _ZERO |
| 111 | eq_movements: tuple[EquityMovement, ...] | None = None |
| 112 | cf_net_change: Decimal | None = None |
| 113 | cash_opening: Decimal | None = None |
| 114 | cash_closing: Decimal | None = None |
| 115 | known_codes: frozenset[str] | None = None |
| 116 | natures: dict[str, str] | None = None |
| 117 | note_ids: frozenset[str] | None = None |
| 118 | official: tuple[OfficialComparison, ...] | None = None |
| 119 | mode: str = "ui" # "ci" makes C-13 ERROR; "ui" makes it INFO (booklet 1 §7) |
| 120 | change_threshold_pct: Decimal = Decimal(50) |
| 121 | basis: str = "auto" # statement figure basis of the import (ADR-032) |
| 122 | |
| 123 | |
| 124 | def _not_run(code: str, severity: str, reason: str) -> ControlResult: |
| 125 | """An unrun control never passes: it blocks and says why (booklet 2.1 R2).""" |
| 126 | return ControlResult( |
| 127 | code=code, severity=severity, passed=False, message_fa=f"اجرا نشد: {reason}", ran=False |
| 128 | ) |
| 129 | |
| 130 | |
| 131 | def _result(code: str, severity: str, bad: tuple[str, ...], ok: str, fail: str) -> ControlResult: |
| 132 | return ControlResult( |
| 133 | code=code, |
| 134 | severity=severity, |
| 135 | passed=not bad, |
| 136 | message_fa=ok if not bad else fail, |
| 137 | affected=bad, |
| 138 | ) |
| 139 | |
| 140 | |
| 141 | def _aggregate(rows: list[BalanceRow]) -> dict[str, dict[str, Decimal]]: |
| 142 | totals: dict[str, dict[str, Decimal]] = {} |
| 143 | for row in rows: |
| 144 | bucket = totals.setdefault( |
| 145 | row.account_code, |
| 146 | {"opening": _ZERO, "debit": _ZERO, "credit": _ZERO, "closing": _ZERO}, |
| 147 | ) |
| 148 | bucket["opening"] += row.opening |
| 149 | bucket["debit"] += row.debit |
| 150 | bucket["credit"] += row.credit |
| 151 | bucket["closing"] += row.closing |
| 152 | return totals |
| 153 | |
| 154 | |
| 155 | def check_c01(rows: list[BalanceRow]) -> ControlResult: |
| 156 | """C-01: every row satisfies opening + debit - credit - closing = 0.""" |
| 157 | bad = tuple( |
| 158 | str(r.row_number) for r in rows if r.opening + r.debit - r.credit - r.closing != _ZERO |
| 159 | ) |
| 160 | return ControlResult( |
| 161 | code="C-01", |
| 162 | severity="ERROR", |
| 163 | passed=not bad, |
| 164 | message_fa=( |
| 165 | "همهٔ ردیفها: ابتدای دوره + بدهکار − بستانکار − پایان دوره = ۰" |
| 166 | if not bad |
| 167 | else f"{len(bad)} ردیف معادلهٔ مانده را نقض میکنند" |
| 168 | ), |
| 169 | affected=bad, |
| 170 | ) |
| 171 | |
| 172 | |
| 173 | def check_c02(rows: list[BalanceRow]) -> ControlResult: |
| 174 | """C-02: trial balance — total debit == total credit and sum(closing) == 0.""" |
| 175 | total_debit = sum((r.debit for r in rows), _ZERO) |
| 176 | total_credit = sum((r.credit for r in rows), _ZERO) |
| 177 | total_closing = sum((r.closing for r in rows), _ZERO) |
| 178 | passed = total_debit == total_credit and total_closing == _ZERO |
| 179 | return ControlResult( |
| 180 | code="C-02", |
| 181 | severity="ERROR", |
| 182 | passed=passed, |
| 183 | message_fa=( |
| 184 | "تراز کل برقرار است: جمع بدهکار = جمع بستانکار و جمع ماندهها صفر" |
| 185 | if passed |
| 186 | else "تراز کل نقض شده است: جمع بدهکار ≠ جمع بستانکار یا جمع ماندهها ≠ صفر" |
| 187 | ), |
| 188 | affected=() if passed else ("trial_balance",), |
| 189 | ) |
| 190 | |
| 191 | |
| 192 | def _is_active(bucket: dict[str, Decimal]) -> bool: |
| 193 | return any(bucket[k] != _ZERO for k in ("opening", "debit", "credit", "closing")) |
| 194 | |
| 195 | |
| 196 | def check_c03(rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]) -> ControlResult: |
| 197 | """C-03: each active account has exactly one active mapping (or 100% split).""" |
| 198 | bad: list[str] = [] |
| 199 | for code, bucket in sorted(_aggregate(rows).items()): |
| 200 | if not _is_active(bucket): |
| 201 | continue |
| 202 | targets = mappings.get(code, []) |
| 203 | if len(targets) == 0: |
| 204 | bad.append(code) |
| 205 | elif len(targets) > 1: |
| 206 | if sum((t.weight for t in targets), _ZERO) != Decimal(100): |
| 207 | bad.append(code) |
| 208 | return ControlResult( |
| 209 | code="C-03", |
| 210 | severity="ERROR", |
| 211 | passed=not bad, |
| 212 | message_fa=( |
| 213 | "هر حساب فعال دقیقاً یک نگاشت فعال دارد (یا تقسیم ۱۰۰٪)" |
| 214 | if not bad |
| 215 | else f"{len(bad)} حساب فعال نگاشت معتبر ندارند" |
| 216 | ), |
| 217 | affected=tuple(bad), |
| 218 | ) |
| 219 | |
| 220 | |
| 221 | def check_c04(rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]) -> ControlResult: |
| 222 | """C-04: unmapped active accounts enter the unknown queue and block approval.""" |
| 223 | queue = tuple( |
| 224 | code |
| 225 | for code, bucket in sorted(_aggregate(rows).items()) |
| 226 | if _is_active(bucket) and not mappings.get(code) |
| 227 | ) |
| 228 | return ControlResult( |
| 229 | code="C-04", |
| 230 | severity="ERROR", |
| 231 | passed=not queue, |
| 232 | message_fa=( |
| 233 | "صف حسابهای ناشناخته خالی است" |
| 234 | if not queue |
| 235 | else f"{len(queue)} حساب بدون نگاشت در صف ناشناخته؛ تا تعیین تکلیف مانع تأیید" |
| 236 | ), |
| 237 | affected=queue, |
| 238 | ) |
| 239 | |
| 240 | |
| 241 | def check_c05(rows: list[BalanceRow], prior_closing: dict[str, Decimal] | None) -> ControlResult: |
| 242 | """C-05: prior-year closing == current-year opening, account by account.""" |
| 243 | if prior_closing is None: |
| 244 | return _not_run("C-05", "ERROR", "مانده پایان سال مالی قبل در دسترس نیست") |
| 245 | opening = {code: b["opening"] for code, b in _aggregate(rows).items()} |
| 246 | bad = tuple( |
| 247 | code |
| 248 | for code in sorted(set(opening) | set(prior_closing)) |
| 249 | if opening.get(code, _ZERO) != prior_closing.get(code, _ZERO) |
| 250 | ) |
| 251 | return _result( |
| 252 | "C-05", |
| 253 | "ERROR", |
| 254 | bad, |
| 255 | "مانده پایان سال قبل با مانده ابتدای سال جاری برای همهٔ حسابها برابر است", |
| 256 | f"{len(bad)} حساب مانده ابتدای سالشان با پایان سال قبل نمیخواند", |
| 257 | ) |
| 258 | |
| 259 | |
| 260 | def check_c06(bs_sections: dict[str, Decimal] | None) -> ControlResult: |
| 261 | """C-06: assets == liabilities + equity on the balance sheet.""" |
| 262 | if bs_sections is None: |
| 263 | return _not_run("C-06", "ERROR", "صورت وضعیت مالی ساخته نشده است") |
| 264 | missing = [k for k in ("Assets", "Liabilities", "Equity") if k not in bs_sections] |
| 265 | if missing: |
| 266 | return _not_run("C-06", "ERROR", f"بخشهای غایب در ترازنامه: {'، '.join(missing)}") |
| 267 | assets = bs_sections["Assets"] |
| 268 | other = bs_sections["Liabilities"] + bs_sections["Equity"] |
| 269 | return _result( |
| 270 | "C-06", |
| 271 | "ERROR", |
| 272 | () if assets == other else ("balance_sheet",), |
| 273 | "معادلهٔ ترازنامه برقرار است: داراییها = بدهیها + حقوق مالکانه", |
| 274 | "معادلهٔ ترازنامه نقض شده است: داراییها ≠ بدهیها + حقوق مالکانه", |
| 275 | ) |
| 276 | |
| 277 | |
| 278 | def check_c07( |
| 279 | note_totals: dict[str, Decimal] | None, line_totals: dict[str, Decimal] | None |
| 280 | ) -> ControlResult: |
| 281 | """C-07: each note total equals its statement line, keyed by (statement, note).""" |
| 282 | if note_totals is None or line_totals is None: |
| 283 | return _not_run("C-07", "ERROR", "جمع یادداشتها یا سطرهای صورت در دسترس نیست") |
| 284 | bad = tuple( |
| 285 | key |
| 286 | for key in sorted(set(note_totals) | set(line_totals)) |
| 287 | if note_totals.get(key, _ZERO) != line_totals.get(key, _ZERO) |
| 288 | ) |
| 289 | return _result( |
| 290 | "C-07", |
| 291 | "ERROR", |
| 292 | bad, |
| 293 | "جمع هر یادداشت با سطر متناظر در صورت برابر است", |
| 294 | f"{len(bad)} یادداشت جمعشان با سطر متناظر صورت نمیخواند", |
| 295 | ) |
| 296 | |
| 297 | |
| 298 | def check_c08( |
| 299 | is_net_profit: Decimal | None, |
| 300 | eq_retained_change: Decimal | None, |
| 301 | explicit_adjustments: Decimal = _ZERO, |
| 302 | ) -> ControlResult: |
| 303 | """C-08: IS net result == change in retained earnings (EQ) + explicit adjustments.""" |
| 304 | if is_net_profit is None or eq_retained_change is None: |
| 305 | return _not_run("C-08", "ERROR", "سود خالص یا تغییر سود انباشته در دسترس نیست") |
| 306 | passed = is_net_profit == eq_retained_change + explicit_adjustments |
| 307 | return _result( |
| 308 | "C-08", |
| 309 | "ERROR", |
| 310 | () if passed else ("retained_earnings",), |
| 311 | "سود و زیان خالص با تغییر سود انباشته (با اصلاحات صریح) برابر است", |
| 312 | "سود و زیان خالص با تغییر سود انباشته نمیخواند", |
| 313 | ) |
| 314 | |
| 315 | |
| 316 | def check_c09(eq_movements: tuple[EquityMovement, ...] | None) -> ControlResult: |
| 317 | """C-09: for every equity row, opening + changes == closing.""" |
| 318 | if eq_movements is None: |
| 319 | return _not_run("C-09", "ERROR", "صورت تغییرات حقوق مالکانه ساخته نشده است") |
| 320 | if not eq_movements: |
| 321 | return _not_run("C-09", "ERROR", "هیچ ردیف حقوق مالکانهای برای بررسی وجود ندارد") |
| 322 | bad = tuple(m.label for m in eq_movements if m.opening + m.changes != m.closing) |
| 323 | return _result( |
| 324 | "C-09", |
| 325 | "ERROR", |
| 326 | bad, |
| 327 | "برای هر ردیف حقوق مالکانه: مانده ابتدا + تغییرات = مانده پایان", |
| 328 | f"{len(bad)} ردیف حقوق مالکانه معادلهٔ مانده را نقض میکنند", |
| 329 | ) |
| 330 | |
| 331 | |
| 332 | def check_c10( |
| 333 | cf_net_change: Decimal | None, cash_opening: Decimal | None, cash_closing: Decimal | None |
| 334 | ) -> ControlResult: |
| 335 | """C-10: CF net change in cash == closing cash - opening cash (per BS).""" |
| 336 | if cf_net_change is None or cash_opening is None or cash_closing is None: |
| 337 | return _not_run("C-10", "ERROR", "جریان نقدی یا ماندههای نقد ترازنامه در دسترس نیست") |
| 338 | passed = cf_net_change == cash_closing - cash_opening |
| 339 | return _result( |
| 340 | "C-10", |
| 341 | "ERROR", |
| 342 | () if passed else ("cash_flow",), |
| 343 | "تغییر خالص وجه نقد با تفاضل مانده نقد پایان و ابتدا برابر است", |
| 344 | "تغییر خالص وجه نقد با تفاضل مانده نقد ترازنامه نمیخواند", |
| 345 | ) |
| 346 | |
| 347 | |
| 348 | def check_c11(rows: list[BalanceRow], known_codes: frozenset[str] | None) -> ControlResult: |
| 349 | """C-11: every subsidiary has its general parent; children sum to a posted parent. |
| 350 | |
| 351 | Canonical identity is general + subsidiary (ADR-014), so the parent of a |
| 352 | subsidiary code is its leading general code. |
| 353 | """ |
| 354 | if known_codes is None: |
| 355 | return _not_run("C-11", "ERROR", "فهرست کدهای حساب سال در دسترس نیست") |
| 356 | totals = _aggregate(rows) |
| 357 | bad: list[str] = [] |
| 358 | children: dict[str, Decimal] = {} |
| 359 | for code, bucket in sorted(totals.items()): |
| 360 | if len(code) <= 2: |
| 361 | continue |
| 362 | parent = code[:2] |
| 363 | if parent not in known_codes: |
| 364 | bad.append(code) |
| 365 | continue |
| 366 | children[parent] = children.get(parent, _ZERO) + bucket["closing"] |
| 367 | for parent, total in sorted(children.items()): |
| 368 | if parent in totals and totals[parent]["closing"] != total: |
| 369 | bad.append(parent) |
| 370 | return _result( |
| 371 | "C-11", |
| 372 | "ERROR", |
| 373 | tuple(bad), |
| 374 | "سلسلهمراتب حسابها برقرار است: والد موجود و جمع فرزندان = والد", |
| 375 | f"{len(bad)} کد سلسلهمراتب را نقض میکنند (والد غایب یا جمع ناسازگار)", |
| 376 | ) |
| 377 | |
| 378 | |
| 379 | def check_c12( |
| 380 | mappings: dict[str, list[MappingTarget]], note_ids: frozenset[str] | None |
| 381 | ) -> ControlResult: |
| 382 | """C-12: no note without a mapping, and no mapping to a nonexistent note.""" |
| 383 | if note_ids is None: |
| 384 | return _not_run("C-12", "ERROR", "فهرست یادداشتهای سال در دسترس نیست") |
| 385 | targets = {t.target for targets in mappings.values() for t in targets} |
| 386 | orphan_notes = tuple(sorted(note_ids - targets)) |
| 387 | dangling = tuple(sorted(targets - note_ids)) |
| 388 | bad = orphan_notes + dangling |
| 389 | return _result( |
| 390 | "C-12", |
| 391 | "ERROR", |
| 392 | bad, |
| 393 | "هر یادداشت نگاشت دارد و هیچ نگاشتی به یادداشت ناموجود اشاره نمیکند", |
| 394 | f"{len(orphan_notes)} یادداشت بدون نگاشت و {len(dangling)} نگاشت به یادداشت ناموجود", |
| 395 | ) |
| 396 | |
| 397 | |
| 398 | def check_c13(official: tuple[OfficialComparison, ...] | None, mode: str = "ui") -> ControlResult: |
| 399 | """C-13: agreement with the official statements — ERROR in CI, INFO in the UI.""" |
| 400 | severity = "ERROR" if mode == "ci" else "INFO" |
| 401 | if official is None: |
| 402 | return _not_run("C-13", severity, "صورتهای رسمی برای مقایسه در دسترس نیست") |
| 403 | bad = tuple(c.key for c in official if c.ours != c.official) |
| 404 | return _result( |
| 405 | "C-13", |
| 406 | severity, |
| 407 | bad, |
| 408 | "خروجی با صورتهای رسمی مطابقت دارد", |
| 409 | f"{len(bad)} قلم با صورتهای رسمی اختلاف دارد", |
| 410 | ) |
| 411 | |
| 412 | |
| 413 | def check_c14( |
| 414 | rows: list[BalanceRow], |
| 415 | prior_closing: dict[str, Decimal] | None, |
| 416 | threshold_pct: Decimal = Decimal(50), |
| 417 | ) -> ControlResult: |
| 418 | """C-14 (WARN): movement beyond the threshold relative to the prior year.""" |
| 419 | if prior_closing is None: |
| 420 | return _not_run("C-14", "WARN", "مانده سال قبل برای تحلیل تغییر در دسترس نیست") |
| 421 | bad: list[str] = [] |
| 422 | for code, bucket in sorted(_aggregate(rows).items()): |
| 423 | prior = prior_closing.get(code, _ZERO) |
| 424 | if prior == _ZERO: |
| 425 | continue |
| 426 | change_pct = abs(bucket["closing"] - prior) / abs(prior) * Decimal(100) |
| 427 | if change_pct > threshold_pct: |
| 428 | bad.append(code) |
| 429 | return _result( |
| 430 | "C-14", |
| 431 | "WARN", |
| 432 | tuple(bad), |
| 433 | "تغییر ناگهانی بیش از آستانه نسبت به سال قبل دیده نشد", |
| 434 | f"{len(bad)} حساب تغییر بیش از آستانه نسبت به سال قبل دارند (نیازمند توضیح)", |
| 435 | ) |
| 436 | |
| 437 | |
| 438 | def check_c15(rows: list[BalanceRow], natures: dict[str, str] | None) -> ControlResult: |
| 439 | """C-15 (WARN): an account carrying a balance contrary to its nature.""" |
| 440 | if natures is None: |
| 441 | return _not_run("C-15", "WARN", "ماهیت حسابها در دسترس نیست") |
| 442 | bad: list[str] = [] |
| 443 | for code, bucket in sorted(_aggregate(rows).items()): |
| 444 | nature = (natures.get(code) or "").strip().lower() |
| 445 | closing = bucket["closing"] |
| 446 | if nature in {"debit", "بدهکار"} and closing < _ZERO: |
| 447 | bad.append(code) |
| 448 | elif nature in {"credit", "بستانکار"} and closing > _ZERO: |
| 449 | bad.append(code) |
| 450 | return _result( |
| 451 | "C-15", |
| 452 | "WARN", |
| 453 | tuple(bad), |
| 454 | "هیچ حسابی مانده خلاف ماهیت ندارد", |
| 455 | f"{len(bad)} حساب مانده خلاف ماهیت دارند (نیازمند توضیح)", |
| 456 | ) |
| 457 | |
| 458 | |
| 459 | def run_controls( |
| 460 | rows: list[BalanceRow], |
| 461 | mappings: dict[str, list[MappingTarget]], |
| 462 | context: ControlContext | None = None, |
| 463 | ) -> list[ControlResult]: |
| 464 | """Run the full C-01..C-15 set in stable order. |
| 465 | |
| 466 | Without a context every context-dependent control reports «اجرا نشد» and |
| 467 | blocks approval, so an incomplete control set can never approve a year. |
| 468 | """ |
| 469 | ctx = context or ControlContext() |
| 470 | return [ |
| 471 | check_c01(rows), |
| 472 | check_c02(rows), |
| 473 | check_c03(rows, mappings), |
| 474 | check_c04(rows, mappings), |
| 475 | check_c05(rows, ctx.prior_closing), |
| 476 | check_c06(ctx.bs_sections), |
| 477 | check_c07(ctx.note_totals, ctx.line_totals), |
| 478 | check_c08(ctx.is_net_profit, ctx.eq_retained_change, ctx.explicit_adjustments), |
| 479 | check_c09(ctx.eq_movements), |
| 480 | check_c10(ctx.cf_net_change, ctx.cash_opening, ctx.cash_closing), |
| 481 | check_c11(rows, ctx.known_codes), |
| 482 | check_c12(mappings, ctx.note_ids), |
| 483 | check_c13(ctx.official, ctx.mode), |
| 484 | check_c14(rows, ctx.prior_closing, ctx.change_threshold_pct), |
| 485 | check_c15(rows, ctx.natures), |
| 486 | ] |
| 487 | |
| 488 | |
| 489 | __all__ = [ |
| 490 | "BalanceRow", |
| 491 | "ControlContext", |
| 492 | "ControlResult", |
| 493 | "EquityMovement", |
| 494 | "MappingTarget", |
| 495 | "OfficialComparison", |
| 496 | "check_c01", |
| 497 | "check_c02", |
| 498 | "check_c03", |
| 499 | "check_c04", |
| 500 | "check_c05", |
| 501 | "check_c06", |
| 502 | "check_c07", |
| 503 | "check_c08", |
| 504 | "check_c09", |
| 505 | "check_c10", |
| 506 | "check_c11", |
| 507 | "check_c12", |
| 508 | "check_c13", |
| 509 | "check_c14", |
| 510 | "check_c15", |
| 511 | "run_controls", |
| 512 | ] |