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):
64
"closing": "CLOSING",
65
}
66
67
+_STATEMENT_BALANCE_HEADER = "مانده صورت مالی"
68
+
69
_CSV_ENCODINGS = ("utf-8-sig", "utf-8", "cp1256")
70
71
61
-def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
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)
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
91
- yield _build_record(values, indexes, kol_index, row_number)
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
96
-def parse_general_ledger_csv(content: bytes) -> Iterator[LedgerRecord]:
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]
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
122
- yield _build_record(values, indexes, kol_index, row_number)
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
125
-def parse_ledger(content: bytes, filename: str) -> Iterator[LedgerRecord]:
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"):
129
- return parse_general_ledger_csv(content)
179
+ return parse_general_ledger_csv(content, tolerant=tolerant, skipped=skipped)
180
if lower.endswith(".xlsx"):
131
- return parse_general_ledger(content)
181
+ return parse_general_ledger(content, tolerant=tolerant, skipped=skipped)
182
raise LedgerParseError("only .xlsx and .csv ledger files are supported")
183
184
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: