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,137 @@
|
||||
"""Konten inkl. Erkennungs-Identifikatoren. Alles owner-gescoped."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..deps import get_current_user, get_owned
|
||||
from ..models import Account, AccountIdentifier, User
|
||||
from ..schemas import AccountCreate, AccountIdentifierOut, AccountOut, AccountUpdate
|
||||
from ..services import balances
|
||||
from .settings import BASE_CURRENCY_KEY, get_user_setting
|
||||
|
||||
router = APIRouter(prefix="/accounts", tags=["accounts"])
|
||||
|
||||
|
||||
def normalize_identifier(value: str) -> str:
|
||||
"""Vereinheitlicht IBAN/Nummer für den Abgleich: Großbuchstaben, nur alphanumerisch."""
|
||||
return "".join(ch for ch in value.upper() if ch.isalnum())
|
||||
|
||||
|
||||
def base_currency(db: Session, user: User) -> str:
|
||||
return get_user_setting(db, user, BASE_CURRENCY_KEY) or "EUR"
|
||||
|
||||
|
||||
def to_out(db: Session, acc: Account, base: str, on: date) -> AccountOut:
|
||||
return AccountOut(
|
||||
id=acc.id,
|
||||
name=acc.name,
|
||||
type=acc.type,
|
||||
currency=acc.currency,
|
||||
icon=acc.icon,
|
||||
color=acc.color,
|
||||
opening_balance_cents=acc.opening_balance_cents,
|
||||
opening_date=acc.opening_date,
|
||||
is_archived=acc.is_archived,
|
||||
position=acc.position,
|
||||
identifiers=[
|
||||
AccountIdentifierOut(id=i.id, kind=i.kind, value=i.value) for i in acc.identifiers
|
||||
],
|
||||
balance_cents=balances.account_balance_cents(db, acc),
|
||||
balance_base_cents=balances.account_balance_base_cents(db, acc, base, on),
|
||||
)
|
||||
|
||||
|
||||
def _set_identifiers(acc: Account, items) -> None:
|
||||
"""Ersetzt die Identifikator-Liste (dedupliziert nach Art + Normalform)."""
|
||||
acc.identifiers.clear()
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for it in items:
|
||||
norm = normalize_identifier(it.value)
|
||||
key = (it.kind.value, norm)
|
||||
if not norm or key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
acc.identifiers.append(
|
||||
AccountIdentifier(kind=it.kind, value=it.value.strip(), value_norm=norm)
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=list[AccountOut])
|
||||
def list_accounts(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
base = base_currency(db, user)
|
||||
today = date.today()
|
||||
accounts = (
|
||||
db.query(Account)
|
||||
.filter(Account.owner_id == user.id)
|
||||
.order_by(Account.position, Account.name)
|
||||
.all()
|
||||
)
|
||||
return [to_out(db, a, base, today) for a in accounts]
|
||||
|
||||
|
||||
@router.post("", response_model=AccountOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_account(
|
||||
payload: AccountCreate, db: Session = Depends(get_db), user: User = Depends(get_current_user)
|
||||
):
|
||||
max_pos = (
|
||||
db.query(Account.position)
|
||||
.filter(Account.owner_id == user.id)
|
||||
.order_by(Account.position.desc())
|
||||
.first()
|
||||
)
|
||||
acc = Account(
|
||||
owner_id=user.id,
|
||||
name=payload.name.strip(),
|
||||
type=payload.type,
|
||||
currency=payload.currency,
|
||||
icon=payload.icon,
|
||||
color=payload.color,
|
||||
opening_balance_cents=payload.opening_balance_cents,
|
||||
opening_date=payload.opening_date,
|
||||
position=(max_pos[0] + 1) if max_pos else 0,
|
||||
)
|
||||
_set_identifiers(acc, payload.identifiers)
|
||||
db.add(acc)
|
||||
db.commit()
|
||||
db.refresh(acc)
|
||||
return to_out(db, acc, base_currency(db, user), date.today())
|
||||
|
||||
|
||||
@router.get("/{account_id}", response_model=AccountOut)
|
||||
def get_account(
|
||||
account_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)
|
||||
):
|
||||
acc = get_owned(db, Account, account_id, user)
|
||||
return to_out(db, acc, base_currency(db, user), date.today())
|
||||
|
||||
|
||||
@router.patch("/{account_id}", response_model=AccountOut)
|
||||
def update_account(
|
||||
account_id: int,
|
||||
payload: AccountUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
acc = get_owned(db, Account, account_id, user)
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
identifiers = data.pop("identifiers", None)
|
||||
for key, value in data.items():
|
||||
if value is not None or key in ("opening_date",):
|
||||
setattr(acc, key, value)
|
||||
if identifiers is not None:
|
||||
_set_identifiers(acc, payload.identifiers)
|
||||
db.commit()
|
||||
db.refresh(acc)
|
||||
return to_out(db, acc, base_currency(db, user), date.today())
|
||||
|
||||
|
||||
@router.delete("/{account_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_account(
|
||||
account_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)
|
||||
):
|
||||
acc = get_owned(db, Account, account_id, user)
|
||||
db.delete(acc)
|
||||
db.commit()
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Kategorie-Gruppen und Kategorien (zweistufig). Alles owner-gescoped.
|
||||
|
||||
Eine Kategorie erbt ihre Art (Einnahme/Ausgabe) von ihrer Gruppe.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..deps import get_current_user, get_owned
|
||||
from ..models import Category, CategoryGroup, User
|
||||
from ..schemas import (
|
||||
CategoryCreate,
|
||||
CategoryGroupCreate,
|
||||
CategoryGroupOut,
|
||||
CategoryGroupUpdate,
|
||||
CategoryOut,
|
||||
CategoryUpdate,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/categories", tags=["categories"])
|
||||
|
||||
|
||||
def group_out(g: CategoryGroup) -> CategoryGroupOut:
|
||||
cats = sorted(g.categories, key=lambda c: (c.position, c.name.lower()))
|
||||
return CategoryGroupOut(
|
||||
id=g.id,
|
||||
name=g.name,
|
||||
kind=g.kind,
|
||||
icon=g.icon,
|
||||
color=g.color,
|
||||
position=g.position,
|
||||
is_builtin=g.is_builtin,
|
||||
categories=[CategoryOut.model_validate(c) for c in cats],
|
||||
)
|
||||
|
||||
|
||||
def _next_position(db: Session, model, **filters) -> int:
|
||||
q = db.query(model.position)
|
||||
for k, v in filters.items():
|
||||
q = q.filter(getattr(model, k) == v)
|
||||
row = q.order_by(model.position.desc()).first()
|
||||
return (row[0] + 1) if row else 0
|
||||
|
||||
|
||||
@router.get("", response_model=list[CategoryGroupOut])
|
||||
def list_categories(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
groups = (
|
||||
db.query(CategoryGroup)
|
||||
.filter(CategoryGroup.owner_id == user.id)
|
||||
.order_by(CategoryGroup.position, CategoryGroup.name)
|
||||
.all()
|
||||
)
|
||||
return [group_out(g) for g in groups]
|
||||
|
||||
|
||||
# --- Gruppen ---------------------------------------------------------------
|
||||
|
||||
|
||||
@router.post("/groups", response_model=CategoryGroupOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_group(
|
||||
payload: CategoryGroupCreate, db: Session = Depends(get_db), user: User = Depends(get_current_user)
|
||||
):
|
||||
g = CategoryGroup(
|
||||
owner_id=user.id,
|
||||
name=payload.name.strip(),
|
||||
kind=payload.kind,
|
||||
icon=payload.icon,
|
||||
color=payload.color,
|
||||
position=_next_position(db, CategoryGroup, owner_id=user.id),
|
||||
)
|
||||
db.add(g)
|
||||
db.commit()
|
||||
db.refresh(g)
|
||||
return group_out(g)
|
||||
|
||||
|
||||
@router.patch("/groups/{group_id}", response_model=CategoryGroupOut)
|
||||
def update_group(
|
||||
group_id: int,
|
||||
payload: CategoryGroupUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
g = get_owned(db, CategoryGroup, group_id, user)
|
||||
for key, value in payload.model_dump(exclude_unset=True).items():
|
||||
if value is not None:
|
||||
setattr(g, key, value)
|
||||
db.commit()
|
||||
db.refresh(g)
|
||||
return group_out(g)
|
||||
|
||||
|
||||
@router.delete("/groups/{group_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_group(
|
||||
group_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)
|
||||
):
|
||||
g = get_owned(db, CategoryGroup, group_id, user)
|
||||
db.delete(g)
|
||||
db.commit()
|
||||
|
||||
|
||||
# --- Kategorien ------------------------------------------------------------
|
||||
|
||||
|
||||
@router.post("", response_model=CategoryOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_category(
|
||||
payload: CategoryCreate, db: Session = Depends(get_db), user: User = Depends(get_current_user)
|
||||
):
|
||||
group = get_owned(db, CategoryGroup, payload.group_id, user)
|
||||
cat = Category(
|
||||
owner_id=user.id,
|
||||
group_id=group.id,
|
||||
name=payload.name.strip(),
|
||||
type=group.kind, # erbt die Art der Gruppe
|
||||
icon=payload.icon,
|
||||
color=payload.color,
|
||||
position=_next_position(db, Category, owner_id=user.id, group_id=group.id),
|
||||
)
|
||||
db.add(cat)
|
||||
db.commit()
|
||||
db.refresh(cat)
|
||||
return CategoryOut.model_validate(cat)
|
||||
|
||||
|
||||
@router.patch("/{category_id}", response_model=CategoryOut)
|
||||
def update_category(
|
||||
category_id: int,
|
||||
payload: CategoryUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
cat = get_owned(db, Category, category_id, user)
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
new_group_id = data.pop("group_id", None)
|
||||
if new_group_id is not None:
|
||||
group = get_owned(db, CategoryGroup, new_group_id, user)
|
||||
cat.group_id = group.id
|
||||
cat.type = group.kind # Art an die neue Gruppe angleichen
|
||||
for key, value in data.items():
|
||||
if value is not None or key == "is_archived":
|
||||
setattr(cat, key, value)
|
||||
db.commit()
|
||||
db.refresh(cat)
|
||||
return CategoryOut.model_validate(cat)
|
||||
|
||||
|
||||
@router.delete("/{category_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_category(
|
||||
category_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)
|
||||
):
|
||||
cat = get_owned(db, Category, category_id, user)
|
||||
db.delete(cat)
|
||||
db.commit()
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Wechselkurse: Status und Umrechnungs-Vorschau (für das Buchungsformular)."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..deps import get_current_user
|
||||
from ..models import ExchangeRate, User
|
||||
from ..schemas import ConversionOut, RateStatus
|
||||
from ..services import currency
|
||||
|
||||
router = APIRouter(prefix="/rates", tags=["rates"])
|
||||
|
||||
|
||||
@router.get("/status", response_model=list[RateStatus])
|
||||
def status(db: Session = Depends(get_db), _: User = Depends(get_current_user)):
|
||||
out: list[RateStatus] = []
|
||||
currencies = [
|
||||
row[0] for row in db.query(ExchangeRate.currency).distinct().order_by(ExchangeRate.currency)
|
||||
]
|
||||
for ccy in currencies:
|
||||
agg = db.query(
|
||||
func.count(ExchangeRate.date),
|
||||
func.min(ExchangeRate.date),
|
||||
func.max(ExchangeRate.date),
|
||||
).filter(ExchangeRate.currency == ccy).one()
|
||||
latest = (
|
||||
db.query(ExchangeRate)
|
||||
.filter(ExchangeRate.currency == ccy)
|
||||
.order_by(ExchangeRate.date.desc())
|
||||
.first()
|
||||
)
|
||||
out.append(
|
||||
RateStatus(
|
||||
currency=ccy,
|
||||
count=agg[0] or 0,
|
||||
min_date=agg[1],
|
||||
max_date=agg[2],
|
||||
latest_rate=float(latest.rate_per_eur) if latest else None,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/convert", response_model=ConversionOut)
|
||||
def convert(
|
||||
amount_cents: int,
|
||||
from_currency: str,
|
||||
to_currency: str,
|
||||
on: date | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user),
|
||||
):
|
||||
on = on or date.today()
|
||||
from_currency = from_currency.upper()
|
||||
to_currency = to_currency.upper()
|
||||
converted = currency.convert(db, amount_cents, from_currency, to_currency, on)
|
||||
# Anzeige-Kurs: EZB-Kurs der Nicht-EUR-Währung (Einheiten je 1 EUR).
|
||||
non_eur = to_currency if to_currency != "EUR" else from_currency
|
||||
rate = currency.rate_on(db, non_eur, on)
|
||||
return ConversionOut(
|
||||
amount_cents=amount_cents,
|
||||
from_currency=from_currency,
|
||||
to_currency=to_currency,
|
||||
date=on,
|
||||
converted_cents=converted,
|
||||
rate=float(rate) if rate is not None else None,
|
||||
)
|
||||
@@ -0,0 +1,219 @@
|
||||
"""Transaktionen: Ausgabe, Einnahme, interner Transfer. Owner-gescoped.
|
||||
|
||||
Beim Speichern wird der eingefrorene EUR-Wert (``amount_eur_cents``) zum
|
||||
Buchungsdatum berechnet (Pivot für Budget/Dashboard). Ein manuell gesetzter
|
||||
Kurs (``fx_rate``) hat Vorrang vor dem EZB-Kurs.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..deps import get_current_user, get_owned
|
||||
from ..models import Account, Category, Transaction, TxnType, User
|
||||
from ..schemas import TransactionCreate, TransactionOut, TransactionUpdate
|
||||
from ..services import currency
|
||||
from .accounts import base_currency
|
||||
|
||||
router = APIRouter(prefix="/transactions", tags=["transactions"])
|
||||
|
||||
|
||||
def _fx(txn: Transaction) -> float | None:
|
||||
return float(txn.fx_rate) if txn.fx_rate is not None else None
|
||||
|
||||
|
||||
def _recompute(db: Session, txn: Transaction, from_acc: Account, to_acc: Account | None) -> None:
|
||||
"""Setzt amount_eur_cents und (bei Transfers) to_amount_cents neu."""
|
||||
txn.amount_eur_cents = currency.compute_amount_eur_cents(
|
||||
db, txn.amount_cents, from_acc.currency, txn.date, _fx(txn)
|
||||
)
|
||||
if txn.type == TxnType.transfer and to_acc is not None:
|
||||
if txn.to_amount_cents is None:
|
||||
if to_acc.currency == from_acc.currency:
|
||||
txn.to_amount_cents = txn.amount_cents
|
||||
else:
|
||||
conv = currency.convert(
|
||||
db, txn.amount_cents, from_acc.currency, to_acc.currency, txn.date, _fx(txn)
|
||||
)
|
||||
txn.to_amount_cents = conv if conv is not None else txn.amount_cents
|
||||
else:
|
||||
txn.to_amount_cents = None
|
||||
|
||||
|
||||
def to_out(db: Session, txn: Transaction, base: str, ccy_by_account: dict[int, str]) -> TransactionOut:
|
||||
acc_ccy = ccy_by_account.get(txn.account_id, "EUR")
|
||||
if base == "EUR":
|
||||
amount_base = txn.amount_eur_cents
|
||||
else:
|
||||
conv = currency.from_eur_cents(db, txn.amount_eur_cents, base, txn.date)
|
||||
amount_base = conv if conv is not None else txn.amount_eur_cents
|
||||
return TransactionOut(
|
||||
id=txn.id,
|
||||
type=txn.type,
|
||||
date=txn.date,
|
||||
time=txn.time,
|
||||
account_id=txn.account_id,
|
||||
to_account_id=txn.to_account_id,
|
||||
account_currency=acc_ccy,
|
||||
amount_cents=txn.amount_cents,
|
||||
to_amount_cents=txn.to_amount_cents,
|
||||
fx_rate=_fx(txn),
|
||||
amount_eur_cents=txn.amount_eur_cents,
|
||||
amount_base_cents=amount_base,
|
||||
category_id=txn.category_id,
|
||||
budget_treatment=txn.budget_treatment,
|
||||
budget_category_id=txn.budget_category_id,
|
||||
payee=txn.payee,
|
||||
description=txn.description,
|
||||
notes=txn.notes,
|
||||
)
|
||||
|
||||
|
||||
def _currency_map(db: Session, user: User) -> dict[int, str]:
|
||||
rows = db.query(Account.id, Account.currency).filter(Account.owner_id == user.id).all()
|
||||
return {row[0]: row[1] for row in rows}
|
||||
|
||||
|
||||
def _validate_category(db: Session, user: User, category_id: int | None) -> None:
|
||||
if category_id is not None:
|
||||
get_owned(db, Category, category_id, user)
|
||||
|
||||
|
||||
@router.get("", response_model=list[TransactionOut])
|
||||
def list_transactions(
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
account_id: int | None = None,
|
||||
category_id: int | None = None,
|
||||
type: TxnType | None = None,
|
||||
date_from: date | None = None,
|
||||
date_to: date | None = None,
|
||||
limit: int = Query(default=200, le=1000),
|
||||
offset: int = 0,
|
||||
):
|
||||
q = db.query(Transaction).filter(Transaction.owner_id == user.id)
|
||||
if account_id is not None:
|
||||
q = q.filter(
|
||||
(Transaction.account_id == account_id) | (Transaction.to_account_id == account_id)
|
||||
)
|
||||
if category_id is not None:
|
||||
q = q.filter(Transaction.category_id == category_id)
|
||||
if type is not None:
|
||||
q = q.filter(Transaction.type == type)
|
||||
if date_from is not None:
|
||||
q = q.filter(Transaction.date >= date_from)
|
||||
if date_to is not None:
|
||||
q = q.filter(Transaction.date <= date_to)
|
||||
rows = q.order_by(Transaction.date.desc(), Transaction.id.desc()).limit(limit).offset(offset).all()
|
||||
base = base_currency(db, user)
|
||||
ccy = _currency_map(db, user)
|
||||
return [to_out(db, t, base, ccy) for t in rows]
|
||||
|
||||
|
||||
@router.post("", response_model=TransactionOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_transaction(
|
||||
payload: TransactionCreate, db: Session = Depends(get_db), user: User = Depends(get_current_user)
|
||||
):
|
||||
from_acc = get_owned(db, Account, payload.account_id, user)
|
||||
to_acc = None
|
||||
category_id = payload.category_id
|
||||
|
||||
if payload.type == TxnType.transfer:
|
||||
if payload.to_account_id is None or payload.to_account_id == payload.account_id:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Transfer braucht ein anderes Zielkonto")
|
||||
to_acc = get_owned(db, Account, payload.to_account_id, user)
|
||||
category_id = None # Transfers werden nicht regulär kategorisiert
|
||||
else:
|
||||
if payload.to_account_id is not None:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Nur Transfers haben ein Zielkonto")
|
||||
_validate_category(db, user, category_id)
|
||||
|
||||
_validate_category(db, user, payload.budget_category_id)
|
||||
|
||||
txn = Transaction(
|
||||
owner_id=user.id,
|
||||
type=payload.type,
|
||||
date=payload.date,
|
||||
time=payload.time,
|
||||
account_id=from_acc.id,
|
||||
to_account_id=to_acc.id if to_acc else None,
|
||||
amount_cents=payload.amount_cents,
|
||||
to_amount_cents=payload.to_amount_cents,
|
||||
fx_rate=payload.fx_rate,
|
||||
category_id=category_id,
|
||||
budget_treatment=payload.budget_treatment,
|
||||
budget_category_id=payload.budget_category_id,
|
||||
payee=(payload.payee or None),
|
||||
description=(payload.description or None),
|
||||
notes=(payload.notes or None),
|
||||
)
|
||||
_recompute(db, txn, from_acc, to_acc)
|
||||
db.add(txn)
|
||||
db.commit()
|
||||
db.refresh(txn)
|
||||
return to_out(db, txn, base_currency(db, user), _currency_map(db, user))
|
||||
|
||||
|
||||
@router.get("/{txn_id}", response_model=TransactionOut)
|
||||
def get_transaction(
|
||||
txn_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)
|
||||
):
|
||||
txn = get_owned(db, Transaction, txn_id, user)
|
||||
return to_out(db, txn, base_currency(db, user), _currency_map(db, user))
|
||||
|
||||
|
||||
@router.patch("/{txn_id}", response_model=TransactionOut)
|
||||
def update_transaction(
|
||||
txn_id: int,
|
||||
payload: TransactionUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
txn = get_owned(db, Transaction, txn_id, user)
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
|
||||
for key in ("type", "date", "time", "amount_cents", "to_amount_cents", "fx_rate",
|
||||
"budget_treatment", "payee", "description", "notes"):
|
||||
if key in data:
|
||||
setattr(txn, key, data[key])
|
||||
|
||||
if "account_id" in data and data["account_id"] is not None:
|
||||
get_owned(db, Account, data["account_id"], user)
|
||||
txn.account_id = data["account_id"]
|
||||
if "to_account_id" in data:
|
||||
if data["to_account_id"] is not None:
|
||||
get_owned(db, Account, data["to_account_id"], user)
|
||||
txn.to_account_id = data["to_account_id"]
|
||||
if "category_id" in data:
|
||||
_validate_category(db, user, data["category_id"])
|
||||
txn.category_id = data["category_id"]
|
||||
if "budget_category_id" in data:
|
||||
_validate_category(db, user, data["budget_category_id"])
|
||||
txn.budget_category_id = data["budget_category_id"]
|
||||
|
||||
# Konsistenz je nach Typ + Neuberechnung der abgeleiteten Werte.
|
||||
from_acc = get_owned(db, Account, txn.account_id, user)
|
||||
to_acc = None
|
||||
if txn.type == TxnType.transfer:
|
||||
if txn.to_account_id is None or txn.to_account_id == txn.account_id:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Transfer braucht ein anderes Zielkonto")
|
||||
to_acc = get_owned(db, Account, txn.to_account_id, user)
|
||||
txn.category_id = None
|
||||
else:
|
||||
txn.to_account_id = None
|
||||
_recompute(db, txn, from_acc, to_acc)
|
||||
|
||||
db.commit()
|
||||
db.refresh(txn)
|
||||
return to_out(db, txn, base_currency(db, user), _currency_map(db, user))
|
||||
|
||||
|
||||
@router.delete("/{txn_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_transaction(
|
||||
txn_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)
|
||||
):
|
||||
txn = get_owned(db, Transaction, txn_id, user)
|
||||
db.delete(txn)
|
||||
db.commit()
|
||||
@@ -8,6 +8,7 @@ from ..deps import require_admin
|
||||
from ..models import Role, User
|
||||
from ..schemas import UserCreate, UserOut, UserUpdate
|
||||
from ..security import hash_password
|
||||
from ..seed import ensure_starter_categories
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"], dependencies=[Depends(require_admin)])
|
||||
|
||||
@@ -33,6 +34,8 @@ def create_user(payload: UserCreate, db: Session = Depends(get_db)) -> User:
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
# Neuen Nutzern die Startkategorien mitgeben.
|
||||
ensure_starter_categories(db, user)
|
||||
return user
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user