Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 15:45 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 | from __future__ import annotations |
| 2 | |
| 3 | import csv |
| 4 | import io |
| 5 | from collections.abc import Iterator |
| 6 | from dataclasses import dataclass |
| 7 | from decimal import Decimal |
| 8 | from io import BytesIO |
| 9 | |
| 10 | from openpyxl import load_workbook |
| 11 | |
| 12 | from aram_backend.domain.normalization import ( |
| 13 | NormalizationError, |
| 14 | decimal_from_cell, |
| 15 | normalize_code, |
| 16 | normalize_fa, |
| 17 | ) |
| 18 | from aram_backend.workbook_inspection import inspect_xlsx |
| 19 | |
| 20 | |
| 21 | @dataclass(frozen=True) |
| 22 | class LedgerRecord: |
| 23 | row_number: int |
| 24 | account_code: str |
| 25 | general_code: str | None |
| 26 | account_name: str |
| 27 | source_year: int |
| 28 | entry_type: str |
| 29 | t1_code: str | None |
| 30 | t2_code: str | None |
| 31 | t3_code: str | None |
| 32 | t4_code: str | None |
| 33 | opening: Decimal |
| 34 | debit: Decimal |
| 35 | credit: Decimal |
| 36 | closing: Decimal |
| 37 | statement_balance: Decimal | None = None |
| 38 | |
| 39 | |
| 40 | @dataclass(frozen=True) |
| 41 | class SkippedRow: |
| 42 | """A source row that could not be imported, with the reason (fail-loud report).""" |
| 43 | |
| 44 | row_number: int |
| 45 | reason: str |
| 46 | |
| 47 | |
| 48 | class LedgerParseError(ValueError): |
| 49 | """Raised when a source ledger row cannot be represented safely.""" |
| 50 | |
| 51 | |
| 52 | _FIELDS = { |
| 53 | "account_code": "حساب", |
| 54 | "account_name": "ACCOUNT_NAME", |
| 55 | "source_year": "year", |
| 56 | "entry_type": "نوع", |
| 57 | "t1_code": "T1_CODE", |
| 58 | "t2_code": "T2_CODE", |
| 59 | "t3_code": "T3_CODE", |
| 60 | "t4_code": "T4_CODE", |
| 61 | "opening": "OPENING", |
| 62 | "debit": "Debit", |
| 63 | "credit": "Credit", |
| 64 | "closing": "CLOSING", |
| 65 | } |
| 66 | |
| 67 | _STATEMENT_BALANCE_HEADER = "مانده صورت مالی" |
| 68 | |
| 69 | _CSV_ENCODINGS = ("utf-8-sig", "utf-8", "cp1256") |
| 70 | |
| 71 | |
| 72 | def parse_general_ledger( |
| 73 | content: bytes, *, tolerant: bool = False, skipped: list[SkippedRow] | None = None |
| 74 | ) -> Iterator[LedgerRecord]: |
| 75 | """Stream typed XLSX ledger rows without persisting or calculating values. |
| 76 | |
| 77 | Codes are normalized as text (leading zeros preserved, P-03/D-04) and money |
| 78 | is decoded to exact Decimal via the shortest round-trip repr (D-04). Header |
| 79 | matching is Persian-normalized (D-05). |
| 80 | |
| 81 | With ``tolerant=True`` (real-ledger import) reclassified rows whose money |
| 82 | cells are empty are kept with exact zero, ``مانده صورت مالی`` is captured as |
| 83 | ``statement_balance``, and anomalous rows are skipped into ``skipped``. |
| 84 | """ |
| 85 | inspection = inspect_xlsx(content, document_type="general_ledger") |
| 86 | workbook = load_workbook(BytesIO(content), read_only=True, data_only=True, keep_links=False) |
| 87 | try: |
| 88 | worksheet = workbook[inspection.data_sheet] |
| 89 | header_values = next( |
| 90 | worksheet.iter_rows( |
| 91 | min_row=inspection.header_row, |
| 92 | max_row=inspection.header_row, |
| 93 | values_only=True, |
| 94 | ) |
| 95 | ) |
| 96 | indexes = { |
| 97 | normalize_fa(str(value)): index |
| 98 | for index, value in enumerate(header_values) |
| 99 | if value is not None |
| 100 | } |
| 101 | kol_index = indexes.get(normalize_fa("kol")) |
| 102 | statement_index = indexes.get(normalize_fa(_STATEMENT_BALANCE_HEADER)) |
| 103 | for row_number, values in enumerate( |
| 104 | worksheet.iter_rows(min_row=inspection.header_row + 1, values_only=True), |
| 105 | start=inspection.header_row + 1, |
| 106 | ): |
| 107 | if not any(value is not None for value in values): |
| 108 | continue |
| 109 | if tolerant: |
| 110 | record, skip = _build_record_tolerant( |
| 111 | values, indexes, kol_index, statement_index, row_number |
| 112 | ) |
| 113 | if skip is not None: |
| 114 | if skipped is not None: |
| 115 | skipped.append(skip) |
| 116 | continue |
| 117 | if record is not None: |
| 118 | yield record |
| 119 | else: |
| 120 | yield _build_record(values, indexes, kol_index, row_number) |
| 121 | finally: |
| 122 | workbook.close() |
| 123 | |
| 124 | |
| 125 | def parse_general_ledger_csv( |
| 126 | content: bytes, *, tolerant: bool = False, skipped: list[SkippedRow] | None = None |
| 127 | ) -> Iterator[LedgerRecord]: |
| 128 | """Stream typed CSV ledger rows (D-06, booklet §8). |
| 129 | |
| 130 | Supports UTF-8, UTF-8-BOM and Windows-1256; sniffs the delimiter; applies the |
| 131 | same Persian normalization and exact-money rules as the XLSX path. Reading is |
| 132 | streaming (csv.reader over the decoded text), never materializing all rows. |
| 133 | With ``tolerant=True`` the same reclassified-row handling as XLSX applies. |
| 134 | """ |
| 135 | text = _decode_csv(content) |
| 136 | sample = text[:4096] |
| 137 | try: |
| 138 | dialect = csv.Sniffer().sniff(sample, delimiters=",\t;") |
| 139 | except csv.Error: |
| 140 | dialect = csv.excel |
| 141 | reader = csv.reader(io.StringIO(text), dialect) |
| 142 | header = next(reader, None) |
| 143 | if header is None: |
| 144 | raise LedgerParseError("CSV ledger is empty") |
| 145 | indexes = {normalize_fa(name): i for i, name in enumerate(header) if name.strip()} |
| 146 | required = {normalize_fa(name) for name in _FIELDS.values()} |
| 147 | missing = required.difference(indexes) |
| 148 | if missing: |
| 149 | raise LedgerParseError(f"CSV ledger is missing required headers: {sorted(missing)}") |
| 150 | kol_index = indexes.get(normalize_fa("kol")) |
| 151 | statement_index = indexes.get(normalize_fa(_STATEMENT_BALANCE_HEADER)) |
| 152 | for row_number, values in enumerate(reader, start=2): |
| 153 | if not any(value.strip() for value in values): |
| 154 | continue |
| 155 | if tolerant: |
| 156 | record, skip = _build_record_tolerant( |
| 157 | values, indexes, kol_index, statement_index, row_number |
| 158 | ) |
| 159 | if skip is not None: |
| 160 | if skipped is not None: |
| 161 | skipped.append(skip) |
| 162 | continue |
| 163 | if record is not None: |
| 164 | yield record |
| 165 | else: |
| 166 | yield _build_record(values, indexes, kol_index, row_number) |
| 167 | |
| 168 | |
| 169 | def parse_ledger( |
| 170 | content: bytes, |
| 171 | filename: str, |
| 172 | *, |
| 173 | tolerant: bool = False, |
| 174 | skipped: list[SkippedRow] | None = None, |
| 175 | ) -> Iterator[LedgerRecord]: |
| 176 | """Route to the XLSX or CSV parser by file extension (D-06).""" |
| 177 | lower = filename.lower() |
| 178 | if lower.endswith(".csv"): |
| 179 | return parse_general_ledger_csv(content, tolerant=tolerant, skipped=skipped) |
| 180 | if lower.endswith(".xlsx"): |
| 181 | return parse_general_ledger(content, tolerant=tolerant, skipped=skipped) |
| 182 | raise LedgerParseError("only .xlsx and .csv ledger files are supported") |
| 183 | |
| 184 | |
| 185 | def _decode_csv(content: bytes) -> str: |
| 186 | for encoding in _CSV_ENCODINGS: |
| 187 | try: |
| 188 | return content.decode(encoding) |
| 189 | except UnicodeDecodeError: |
| 190 | continue |
| 191 | raise LedgerParseError("CSV encoding must be UTF-8, UTF-8-BOM, or Windows-1256") |
| 192 | |
| 193 | |
| 194 | def _build_record(values, indexes, kol_index, row_number) -> LedgerRecord: |
| 195 | def value(field: str): |
| 196 | i = indexes[normalize_fa(_FIELDS[field])] |
| 197 | return values[i] if i < len(values) else None |
| 198 | |
| 199 | return LedgerRecord( |
| 200 | row_number=row_number, |
| 201 | account_code=_required_code(value("account_code"), row_number, "حساب"), |
| 202 | general_code=( |
| 203 | _optional_code(values[kol_index], row_number, "kol") |
| 204 | if kol_index is not None and kol_index < len(values) |
| 205 | else None |
| 206 | ), |
| 207 | account_name=_required_text(value("account_name"), row_number, "ACCOUNT_NAME"), |
| 208 | source_year=_required_year(value("source_year"), row_number), |
| 209 | entry_type=_required_text(value("entry_type"), row_number, "نوع"), |
| 210 | t1_code=_optional_code(value("t1_code"), row_number, "T1_CODE"), |
| 211 | t2_code=_optional_code(value("t2_code"), row_number, "T2_CODE"), |
| 212 | t3_code=_optional_code(value("t3_code"), row_number, "T3_CODE"), |
| 213 | t4_code=_optional_code(value("t4_code"), row_number, "T4_CODE"), |
| 214 | opening=_required_decimal(value("opening"), row_number, "OPENING"), |
| 215 | debit=_required_decimal(value("debit"), row_number, "Debit"), |
| 216 | credit=_required_decimal(value("credit"), row_number, "Credit"), |
| 217 | closing=_required_decimal(value("closing"), row_number, "CLOSING"), |
| 218 | ) |
| 219 | |
| 220 | |
| 221 | def _build_record_tolerant( |
| 222 | values, indexes, kol_index, statement_index, row_number |
| 223 | ) -> tuple[LedgerRecord | None, SkippedRow | None]: |
| 224 | """Build a record for real-ledger import. |
| 225 | |
| 226 | Reclassified source rows carry only ``مانده صورت مالی`` and leave the |
| 227 | OPENING/Debit/Credit/CLOSING cells empty; those are stored as exact zero |
| 228 | (the row is preserved for drill-down, D3). A *non-numeric* money cell is a |
| 229 | genuine anomaly: the row is skipped and reported (fail-loud, never invented). |
| 230 | Identity fields (account code/name/year/type) remain strictly required. |
| 231 | """ |
| 232 | |
| 233 | def value(field: str): |
| 234 | i = indexes[normalize_fa(_FIELDS[field])] |
| 235 | return values[i] if i < len(values) else None |
| 236 | |
| 237 | def money(field: str, header: str) -> Decimal: |
| 238 | raw = value(field) |
| 239 | if raw is None or (isinstance(raw, str) and not raw.strip()): |
| 240 | return Decimal(0) |
| 241 | return _required_decimal(raw, row_number, header) |
| 242 | |
| 243 | try: |
| 244 | account_code = _required_code(value("account_code"), row_number, "حساب") |
| 245 | account_name = _required_text(value("account_name"), row_number, "ACCOUNT_NAME") |
| 246 | source_year = _required_year(value("source_year"), row_number) |
| 247 | entry_type = _required_text(value("entry_type"), row_number, "نوع") |
| 248 | opening = money("opening", "OPENING") |
| 249 | debit = money("debit", "Debit") |
| 250 | credit = money("credit", "Credit") |
| 251 | closing = money("closing", "CLOSING") |
| 252 | except LedgerParseError as exc: |
| 253 | return None, SkippedRow(row_number=row_number, reason=str(exc)) |
| 254 | |
| 255 | statement_balance: Decimal | None = None |
| 256 | if statement_index is not None and statement_index < len(values): |
| 257 | raw = values[statement_index] |
| 258 | if raw is not None and not (isinstance(raw, str) and not raw.strip()): |
| 259 | try: |
| 260 | statement_balance = _required_decimal(raw, row_number, _STATEMENT_BALANCE_HEADER) |
| 261 | except LedgerParseError: |
| 262 | statement_balance = None |
| 263 | |
| 264 | record = LedgerRecord( |
| 265 | row_number=row_number, |
| 266 | account_code=account_code, |
| 267 | general_code=( |
| 268 | _optional_code(values[kol_index], row_number, "kol") |
| 269 | if kol_index is not None and kol_index < len(values) |
| 270 | else None |
| 271 | ), |
| 272 | account_name=account_name, |
| 273 | source_year=source_year, |
| 274 | entry_type=entry_type, |
| 275 | t1_code=_optional_code(value("t1_code"), row_number, "T1_CODE"), |
| 276 | t2_code=_optional_code(value("t2_code"), row_number, "T2_CODE"), |
| 277 | t3_code=_optional_code(value("t3_code"), row_number, "T3_CODE"), |
| 278 | t4_code=_optional_code(value("t4_code"), row_number, "T4_CODE"), |
| 279 | opening=opening, |
| 280 | debit=debit, |
| 281 | credit=credit, |
| 282 | closing=closing, |
| 283 | statement_balance=statement_balance, |
| 284 | ) |
| 285 | return record, None |
| 286 | |
| 287 | |
| 288 | def _required_text(value: object, row_number: int, field: str) -> str: |
| 289 | text = normalize_fa(str(value)) if value is not None else "" |
| 290 | if not text: |
| 291 | raise LedgerParseError(f"row {row_number}: {field} is required") |
| 292 | return text |
| 293 | |
| 294 | |
| 295 | def _required_year(value: object, row_number: int) -> int: |
| 296 | parsed = _required_decimal(value, row_number, "year") |
| 297 | if parsed != parsed.to_integral_value() or parsed <= 0: |
| 298 | raise LedgerParseError(f"row {row_number}: year must be a positive integer") |
| 299 | return int(parsed) |
| 300 | |
| 301 | |
| 302 | def _required_code(value: object, row_number: int, field: str) -> str: |
| 303 | code = _optional_code(value, row_number, field) |
| 304 | if code is None: |
| 305 | raise LedgerParseError(f"row {row_number}: {field} is required") |
| 306 | return code |
| 307 | |
| 308 | |
| 309 | def _optional_code(value: object, row_number: int, field: str) -> str | None: |
| 310 | if value is None: |
| 311 | return None |
| 312 | if isinstance(value, str) and not value.strip(): |
| 313 | return None |
| 314 | try: |
| 315 | return normalize_code(value, row=row_number, field=field) |
| 316 | except NormalizationError as exc: |
| 317 | raise LedgerParseError(str(exc)) from exc |
| 318 | |
| 319 | |
| 320 | def _required_decimal(value: object, row_number: int, field: str) -> Decimal: |
| 321 | try: |
| 322 | return decimal_from_cell(value, row=row_number, field=field) |
| 323 | except NormalizationError as exc: |
| 324 | raise LedgerParseError(str(exc)) from exc |