from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from app.auth.dependencies import get_current_user, require_role from app.database import get_db from app.models.currency import Currency from app.schemas.currency import CurrencyCreate, CurrencyUpdate, CurrencyOut router = APIRouter(prefix="/currencies", tags=["currencies"]) require_accountant = require_role("accountant") @router.get("", response_model=list[CurrencyOut]) def list_currencies(db: Session = Depends(get_db), _=Depends(get_current_user)): return db.query(Currency).order_by(Currency.code).all() @router.get("/{currency_id}", response_model=CurrencyOut) def get_currency(currency_id: int, db: Session = Depends(get_db), _=Depends(get_current_user)): obj = db.get(Currency, currency_id) if not obj: raise HTTPException(status_code=404, detail="Currency not found") return obj @router.post("", response_model=CurrencyOut, status_code=status.HTTP_201_CREATED) def create_currency(body: CurrencyCreate, db: Session = Depends(get_db), _=Depends(require_accountant)): if db.query(Currency).filter(Currency.code == body.code.upper()).first(): raise HTTPException(status_code=400, detail="Currency code already exists") obj = Currency(**body.model_dump(), code=body.code.upper()) db.add(obj) db.commit() db.refresh(obj) return obj @router.patch("/{currency_id}", response_model=CurrencyOut) def update_currency(currency_id: int, body: CurrencyUpdate, db: Session = Depends(get_db), _=Depends(require_accountant)): obj = db.get(Currency, currency_id) if not obj: raise HTTPException(status_code=404, detail="Currency not found") for field, value in body.model_dump(exclude_none=True).items(): setattr(obj, field, value) db.commit() db.refresh(obj) return obj @router.delete("/{currency_id}", status_code=status.HTTP_204_NO_CONTENT) def delete_currency(currency_id: int, db: Session = Depends(get_db), _=Depends(require_accountant)): obj = db.get(Currency, currency_id) if not obj: raise HTTPException(status_code=404, detail="Currency not found") db.delete(obj) db.commit()