feat: Phase 1 – Konten, Kategorien, Transaktionen, EZB-Währungsumrechnung
Backend: - Modelle + Migration 0002: accounts, account_identifiers, category_groups, categories, transactions, exchange_rates (alle owner-gescoped). - EZB-Kursdienst (90-Tage/Historie) + Backfill-Skript; Umrechnung EUR<->CHF zum Buchungsdatum mit lokalem Cache und manueller Übersteuerung; EUR-Pivot (amount_eur_cents) eingefroren. - Kontostände + Netto-Vermögen (Umrechnung in Hauptwährung). - Router: accounts (inkl. IBAN-Identifikatoren), categories (Gruppen+Kategorien), transactions (Ausgabe/Einnahme/Transfer, cross-currency), rates. - Gruppierte Standard-Kategorien je Nutzer beim Anlegen. - pytest-Suite: Währung, Salden, Cross-Currency-Transfer, Nutzer-Isolation. Frontend: - Seiten Konten, Kategorien, Buchungen; Icon-Chip, Geldbetrag mit Umrechnung, Icon-/Farbwähler, Modal; erweitertes SVG-Icon-Set (Konto-/Kategorie-Icons). - Währungs-/Datumsformatierung (EUR de-DE, CHF de-CH), i18n DE/EN erweitert. - Live-Umrechnungs-Vorschau im Transfer-Formular. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
"""Kontostände (in Kontowährung) und Umrechnung in die Hauptwährung.
|
||||
|
||||
Saldo = Anfangssaldo + Einnahmen - Ausgaben - Transfers-raus + Transfers-rein.
|
||||
Transfers werden in der jeweiligen Kontowährung verrechnet (bei währungsüber-
|
||||
greifenden Transfers am Zielkonto der gutgeschriebene Betrag ``to_amount_cents``).
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import Account, Transaction, TxnType
|
||||
from . import currency
|
||||
|
||||
|
||||
def _sum(query) -> int:
|
||||
return int(query.scalar() or 0)
|
||||
|
||||
|
||||
def account_balance_cents(db: Session, account: Account) -> int:
|
||||
income = _sum(
|
||||
db.query(func.sum(Transaction.amount_cents)).filter(
|
||||
Transaction.account_id == account.id, Transaction.type == TxnType.income
|
||||
)
|
||||
)
|
||||
expense = _sum(
|
||||
db.query(func.sum(Transaction.amount_cents)).filter(
|
||||
Transaction.account_id == account.id, Transaction.type == TxnType.expense
|
||||
)
|
||||
)
|
||||
transfer_out = _sum(
|
||||
db.query(func.sum(Transaction.amount_cents)).filter(
|
||||
Transaction.account_id == account.id, Transaction.type == TxnType.transfer
|
||||
)
|
||||
)
|
||||
transfer_in = _sum(
|
||||
db.query(
|
||||
func.sum(func.coalesce(Transaction.to_amount_cents, Transaction.amount_cents))
|
||||
).filter(
|
||||
Transaction.to_account_id == account.id, Transaction.type == TxnType.transfer
|
||||
)
|
||||
)
|
||||
return account.opening_balance_cents + income - expense - transfer_out + transfer_in
|
||||
|
||||
|
||||
def account_balance_base_cents(
|
||||
db: Session, account: Account, base_currency: str, on: date
|
||||
) -> int:
|
||||
"""Saldo in die Hauptwährung umgerechnet (aktueller Kurs). Fällt auf den
|
||||
nativen Wert zurück, wenn kein Kurs verfügbar ist."""
|
||||
native = account_balance_cents(db, account)
|
||||
if account.currency == base_currency:
|
||||
return native
|
||||
conv = currency.convert(db, native, account.currency, base_currency, on)
|
||||
return conv if conv is not None else native
|
||||
|
||||
|
||||
def net_worth_cents(db: Session, accounts: list[Account], base_currency: str, on: date) -> int:
|
||||
return sum(
|
||||
account_balance_base_cents(db, a, base_currency, on)
|
||||
for a in accounts
|
||||
if not a.is_archived
|
||||
)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Währungsumrechnung EUR<->CHF über die lokal gecachten EZB-Referenzkurse.
|
||||
|
||||
Kurse werden als ``rate_per_eur`` gespeichert: wie viele Einheiten der Währung
|
||||
ein Euro wert war (EUR ist implizit 1.0). Umgerechnet wird immer mit dem Kurs zum
|
||||
Buchungsdatum; fehlt ein Kurs für genau diesen Tag (Wochenende/Feiertag), wird der
|
||||
letzte verfügbare Börsentag davor genommen.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import ExchangeRate
|
||||
|
||||
|
||||
def rate_on(db: Session, currency: str, on: date) -> Decimal | None:
|
||||
"""Kurs (Währungseinheiten je 1 EUR) am Tag ``on`` oder dem letzten davor."""
|
||||
if currency == "EUR":
|
||||
return Decimal(1)
|
||||
row = (
|
||||
db.query(ExchangeRate)
|
||||
.filter(ExchangeRate.currency == currency, ExchangeRate.date <= on)
|
||||
.order_by(ExchangeRate.date.desc())
|
||||
.first()
|
||||
)
|
||||
return Decimal(str(row.rate_per_eur)) if row is not None else None
|
||||
|
||||
|
||||
def _round_cents(value: Decimal) -> int:
|
||||
return int(value.quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
def to_eur_cents(
|
||||
db: Session, amount_cents: int, currency: str, on: date, fx_rate: float | None = None
|
||||
) -> int | None:
|
||||
"""Rechnet einen Betrag in Kontowährung in EUR-Cent um.
|
||||
|
||||
``fx_rate`` (Kontowährung je 1 EUR) hat Vorrang vor dem EZB-Kurs. Gibt None
|
||||
zurück, wenn kein Kurs verfügbar ist (Aufrufer entscheidet über Fallback)."""
|
||||
if currency == "EUR":
|
||||
return amount_cents
|
||||
rate = Decimal(str(fx_rate)) if fx_rate else rate_on(db, currency, on)
|
||||
if not rate or rate == 0:
|
||||
return None
|
||||
return _round_cents(Decimal(amount_cents) / rate)
|
||||
|
||||
|
||||
def from_eur_cents(db: Session, eur_cents: int, currency: str, on: date) -> int | None:
|
||||
"""Rechnet EUR-Cent in die Zielwährung um (Kurs zum Tag ``on``)."""
|
||||
if currency == "EUR":
|
||||
return eur_cents
|
||||
rate = rate_on(db, currency, on)
|
||||
if rate is None:
|
||||
return None
|
||||
return _round_cents(Decimal(eur_cents) * rate)
|
||||
|
||||
|
||||
def convert(
|
||||
db: Session,
|
||||
amount_cents: int,
|
||||
from_ccy: str,
|
||||
to_ccy: str,
|
||||
on: date,
|
||||
fx_rate: float | None = None,
|
||||
) -> int | None:
|
||||
"""Rechnet zwischen zwei Währungen um (über EUR als Pivot)."""
|
||||
if from_ccy == to_ccy:
|
||||
return amount_cents
|
||||
eur = to_eur_cents(db, amount_cents, from_ccy, on, fx_rate)
|
||||
if eur is None:
|
||||
return None
|
||||
return from_eur_cents(db, eur, to_ccy, on)
|
||||
|
||||
|
||||
def compute_amount_eur_cents(
|
||||
db: Session, amount_cents: int, currency: str, on: date, fx_rate: float | None = None
|
||||
) -> int:
|
||||
"""Eingefrorener EUR-Wert für eine Transaktion. Fällt notfalls (kein Kurs
|
||||
verfügbar) auf 1:1 zurück, damit das Speichern nie scheitert."""
|
||||
eur = to_eur_cents(db, amount_cents, currency, on, fx_rate)
|
||||
return eur if eur is not None else amount_cents
|
||||
@@ -0,0 +1,82 @@
|
||||
"""EZB-Referenzkurse laden und lokal cachen.
|
||||
|
||||
Die EZB veröffentlicht die Euro-Referenzkurse werktäglich als XML: ein Tages-Feed,
|
||||
ein 90-Tage-Feed und die volle Historie seit 1999. Wir brauchen nur CHF. Historische
|
||||
Kurse ändern sich nicht – vorhandene Zeilen werden daher nicht überschrieben.
|
||||
"""
|
||||
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import httpx
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import ExchangeRate
|
||||
|
||||
FEED_90D = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml"
|
||||
FEED_FULL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml"
|
||||
|
||||
# Welche Währungen wir speichern (Hauptwährungen des Nutzers: EUR ist Pivot).
|
||||
CURRENCIES = {"CHF"}
|
||||
|
||||
|
||||
def _parse(xml_bytes: bytes) -> list[tuple[date, str, str]]:
|
||||
"""Extrahiert (Datum, Währung, Kurs) aus dem EZB-XML (namespace-tolerant)."""
|
||||
root = ET.fromstring(xml_bytes)
|
||||
rows: list[tuple[date, str, str]] = []
|
||||
for elem in root.iter():
|
||||
t = elem.attrib.get("time")
|
||||
if not t:
|
||||
continue
|
||||
try:
|
||||
d = date.fromisoformat(t)
|
||||
except ValueError:
|
||||
continue
|
||||
for child in elem:
|
||||
ccy = child.attrib.get("currency")
|
||||
rate = child.attrib.get("rate")
|
||||
if ccy in CURRENCIES and rate:
|
||||
rows.append((d, ccy, rate))
|
||||
return rows
|
||||
|
||||
|
||||
def _fetch(url: str, timeout: float = 15.0) -> bytes:
|
||||
with httpx.Client(timeout=timeout, follow_redirects=True) as client:
|
||||
resp = client.get(url)
|
||||
resp.raise_for_status()
|
||||
return resp.content
|
||||
|
||||
|
||||
def _upsert(db: Session, rows: list[tuple[date, str, str]]) -> int:
|
||||
added = 0
|
||||
for d, ccy, rate in rows:
|
||||
if db.get(ExchangeRate, (d, ccy)) is None:
|
||||
db.add(ExchangeRate(date=d, currency=ccy, rate_per_eur=Decimal(rate), source="ecb"))
|
||||
added += 1
|
||||
if added:
|
||||
db.commit()
|
||||
return added
|
||||
|
||||
|
||||
def refresh_recent(db: Session) -> int:
|
||||
"""Lädt die letzten ~90 Tage (schnell) und ergänzt fehlende Tage."""
|
||||
return _upsert(db, _parse(_fetch(FEED_90D)))
|
||||
|
||||
|
||||
def backfill_full(db: Session) -> int:
|
||||
"""Lädt die komplette Historie (einmalig, größer)."""
|
||||
return _upsert(db, _parse(_fetch(FEED_FULL)))
|
||||
|
||||
|
||||
def ensure_rates_on_startup(db: Session, enabled: bool) -> None:
|
||||
"""Beim App-Start best-effort die aktuellen Kurse nachladen.
|
||||
|
||||
Blockiert nie hart: Ohne Internet läuft die App weiter, nur ohne frische Kurse.
|
||||
Die volle Historie holt das Install-Skript / der systemd-Timer separat."""
|
||||
if not enabled:
|
||||
return
|
||||
try:
|
||||
refresh_recent(db)
|
||||
except Exception: # noqa: BLE001 – bewusst tolerant (Netz weg etc.)
|
||||
pass
|
||||
Reference in New Issue
Block a user