Files
leleka/scripts/e2e/codex/tasks/fixbug-ledger/seed/ledger/importer.py
T

166 lines
5.6 KiB
Python

"""Import bank statements from CSV text."""
from __future__ import annotations
import csv
import datetime as dt
import io
import re
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from typing import List, Optional
from .money import Money
from .transactions import Transaction
_CURRENCY_MARKS = "\u20ac$\u00a3"
_NUMERIC = re.compile(r"[0-9.,]*[0-9][0-9.,]*")
_DATE_FORMATS = ("%Y-%m-%d", "%d.%m.%Y", "%m/%d/%Y")
class ImportFormatError(ValueError):
"""Raised for malformed statement files; ``line`` is the 1-based line number."""
def __init__(self, line: int, message: str) -> None:
super().__init__("line %d: %s" % (line, message))
self.line = line
@dataclass(frozen=True)
class StatementRow:
line: int
date: dt.date
description: str
amount: Decimal
category: str
def _lone_mark(s: str, mark: str) -> Optional[str]:
"""Decide what the only kind of separator in ``s`` means.
Returns ``mark`` if it is a decimal mark and ``None`` if it only groups
thousands. A mark that repeats, or that is followed by exactly three digits
after a leading group of one to three digits ("1,234", "12.345"), groups
thousands; anything else ("12,5", "0.125", "1234.567") is a decimal mark.
"""
if s.count(mark) > 1:
return None
head, _, tail = s.partition(mark)
if len(tail) == 3 and 1 <= len(head) <= 3 and head != "0":
return None
return mark
def _normalise_separators(s: str) -> str:
"""Rewrite ``s`` with no grouping separators and at most one ``.`` as decimal mark."""
last_dot, last_comma = s.rfind("."), s.rfind(",")
if last_dot < 0 and last_comma < 0:
return s
if last_dot >= 0 and last_comma >= 0:
decimal_mark: Optional[str] = "." if last_dot > last_comma else ","
elif last_comma >= 0:
# a lone comma is the European decimal mark
decimal_mark = ","
else:
decimal_mark = _lone_mark(s, ".")
if decimal_mark is None:
return s.replace(".", "").replace(",", "")
head, _, tail = s.rpartition(decimal_mark)
return head.replace(".", "").replace(",", "") + "." + tail
def parse_amount(text: str) -> Decimal:
"""Parse an amount as it appears in a bank statement.
Handles a leading or trailing minus, accounting-style negatives in
parentheses ("(1,234.50)"), currency marks, spaces as thousands
separators, and both "1,234.50" and "1.234,50" notation.
"""
s = text.strip()
negative = False
if s.startswith("(") and s.endswith(")"):
negative = True
s = s[1:-1].strip()
for mark in _CURRENCY_MARKS:
s = s.replace(mark, "")
s = s.replace("\u00a0", "").replace(" ", "")
if s.endswith("-"):
negative = True
s = s[:-1]
elif s.startswith("-"):
negative = True
s = s[1:]
elif s.startswith("+"):
s = s[1:]
if not _NUMERIC.fullmatch(s):
raise ValueError("not an amount: %r" % text)
try:
value = Decimal(_normalise_separators(s))
except InvalidOperation:
raise ValueError("not an amount: %r" % text) from None
return -value if negative else value
def parse_date(text: str) -> dt.date:
"""Parse ``YYYY-MM-DD``, ``DD.MM.YYYY`` or ``MM/DD/YYYY``."""
s = text.strip()
for fmt in _DATE_FORMATS:
try:
return dt.datetime.strptime(s, fmt).date()
except ValueError:
continue
raise ValueError("unrecognised date: %r" % text)
def read_rows(text: str, delimiter: str = ",") -> List[StatementRow]:
"""Read ``date, description, amount[, category]`` rows; the first line is the header."""
reader = csv.reader(io.StringIO(text), delimiter=delimiter)
try:
header = [name.strip().lower() for name in next(reader)]
except StopIteration:
raise ImportFormatError(1, "empty file") from None
missing = [name for name in ("date", "description", "amount") if name not in header]
if missing:
raise ImportFormatError(1, "missing columns: %s" % ", ".join(missing))
rows: List[StatementRow] = []
for record in reader:
if not any(cell.strip() for cell in record):
continue
fields = dict(zip(header, record))
try:
rows.append(
StatementRow(
line=reader.line_num,
date=parse_date(fields["date"]),
description=fields["description"].strip(),
amount=parse_amount(fields["amount"]),
category=fields.get("category", "").strip(),
)
)
except (KeyError, ValueError) as exc:
raise ImportFormatError(reader.line_num, str(exc)) from None
return rows
def to_transactions(
rows: List[StatementRow],
bank: str = "1000",
currency: str = "EUR",
income: str = "4900",
expense: str = "5900",
) -> List[Transaction]:
"""Turn statement rows into transfers between ``bank`` and the row's category account."""
transactions = []
for number, row in enumerate(rows, start=1):
counter = row.category or (income if row.amount >= 0 else expense)
amount = Money(row.amount, currency).rounded()
transactions.append(
Transaction.transfer("imp-%04d" % number, row.date, row.description, bank, counter, amount)
)
return transactions
def load_statement(text: str, delimiter: str = ",", **options: str) -> List[Transaction]:
"""Parse CSV text straight into transactions; keyword options go to :func:`to_transactions`."""
return to_transactions(read_rows(text, delimiter), **options)