import uuid from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.api.deps import require_roles from app.db.session import get_db from app.models.auth import RolleTyp from app.models.fehlbestand import Fehlbestand from app.schemas.fehlbestand import ( FehlbestandRead, NachfuellungCreate, NachfuellungRead, NachfuellungResponse, ) from app.services.fehlbestand import FehlbestandBereitsErledigtError, nachfuellen router = APIRouter() _mitarbeiter_plus = require_roles( RolleTyp.mitarbeiter, RolleTyp.materialverantwortlicher, RolleTyp.leitungsverantwortlicher, RolleTyp.administration, ) _verantwortliche = require_roles( RolleTyp.administration, RolleTyp.materialverantwortlicher, RolleTyp.leitungsverantwortlicher ) @router.get("/fehlbestaende", response_model=list[FehlbestandRead]) async def liste_fehlbestaende( status_filter: str | None = None, db: AsyncSession = Depends(get_db), _=Depends(_verantwortliche), ) -> list[Fehlbestand]: """Vollständige Filterung nach Zuständigkeit/Standort folgt Sprint 6 (Dashboard).""" stmt = select(Fehlbestand) if status_filter is not None: stmt = stmt.where(Fehlbestand.status == status_filter) result = await db.execute(stmt) return list(result.scalars().all()) @router.get("/fehlbestaende/{fehlbestand_id}", response_model=FehlbestandRead) async def hole_fehlbestand( fehlbestand_id: uuid.UUID, db: AsyncSession = Depends(get_db), _=Depends(_mitarbeiter_plus) ) -> Fehlbestand: fehlbestand = await db.get(Fehlbestand, fehlbestand_id) if fehlbestand is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Fehlbestand nicht gefunden") return fehlbestand @router.post( "/fehlbestaende/{fehlbestand_id}/nachfuellungen", response_model=NachfuellungResponse, status_code=status.HTTP_201_CREATED, ) async def erfasse_nachfuellung( fehlbestand_id: uuid.UUID, payload: NachfuellungCreate, db: AsyncSession = Depends(get_db), current_user=Depends(_mitarbeiter_plus), ) -> NachfuellungResponse: """Prompt 02.3/02.5: deckt Sofort-Nachfüllung während der Kontrolle (Karte 07) und spätere/externe Nachfüllung gleichermaßen ab.""" fehlbestand = await db.get(Fehlbestand, fehlbestand_id) if fehlbestand is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Fehlbestand nicht gefunden") try: nachfuellung, ueberbestand = await nachfuellen( db, fehlbestand=fehlbestand, menge=payload.menge, benutzer_id=current_user.id ) except FehlbestandBereitsErledigtError as exc: raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail="Fehlbestand ist bereits erledigt" ) from exc return NachfuellungResponse( nachfuellung=NachfuellungRead.model_validate(nachfuellung), fehlbestand=FehlbestandRead.model_validate(fehlbestand), ueberbestand=ueberbestand, )