"""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, )