Files
finanz-cockpit/src/models.py
T
2026-09-06 12:25:37 +02:00

95 lines
2.6 KiB
Python

from datetime import date
from decimal import Decimal
from enum import Enum
from pydantic import BaseModel, Field, field_validator
IBAN_PATTERN = r"^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$"
class Currency(str, Enum):
EUR = "EUR"
USD = "USD"
GBP = "GBP"
CHF = "CHF"
def __str__(self):
return self.value
def __repr__(self):
return f"Currency.{self.name}"
class Sign(str, Enum):
DEBIT = "DBIT"
CREDIT = "CRDT"
def __str__(self):
return self.value
def __repr__(self):
return f"Sign.{self.name}"
def to_sign(self) -> int:
return -1 if self is Sign.DEBIT else 1
class B4wExport(BaseModel):
id: int = Field(alias="Id1", description="internal B4w ID")
account_iban: str = Field(alias="OwnrAcctIBAN", pattern=IBAN_PATTERN)
account_currency: Currency = Field(alias="OwnrAcctCcy")
date_valid: date = Field(alias="ValDt")
date_book: date = Field(alias="BookgDt")
amount: Decimal = Field(alias="Amt")
amount_currency: Currency = Field(alias="AmtCcy")
sign: Sign = Field(alias="CdtDbtInd")
reference: str = Field(alias="RmtInf")
other_name: str = Field(alias="RmtdNm")
other_iban: str = Field(alias="RmtdAcctIBAN")
category: Category | None = Field(alias="Category")
notes: str = Field(alias="Notes")
@property
def amount_signed(self) -> Decimal:
return self.amount * self.sign.to_sign()
@field_validator("category", mode="before")
@classmethod
def category_str_is_parsable(
cls, category_in: str | Category | None
) -> Category | None:
if category_in is None or category_in == "":
return None
if isinstance(category_in, Category):
return category_in
category = Category.from_str(category_in)
if category is None or category.to_str() != category_in:
raise ValueError(f"Category string cannot be parsed: {category_in!r}")
return category
class Category(BaseModel):
name: str = Field(pattern=r"[^:\r\n]+")
parent: Category | None = None
@classmethod
def from_str(cls, s: str) -> Category | None:
if not s:
return
components = s.split(":")
name = components[-1]
rest = ":".join(components[:-1])
return cls(name=name, parent=cls.from_str(rest))
def to_str(self) -> str | None:
if not self.parent:
return self.name
else:
return f"{self.parent.to_str()}:{self.name}"
def __str__(self):
return self.to_str()
def __repr__(self):
return f'Category.from_str("{self.__str__()}")'