61 lines
1.9 KiB
Python
61 lines
1.9 KiB
Python
# backend/app/routers/achats.py
|
|
from typing import List, Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
from sqlmodel import Session, select
|
|
from app.database import get_session
|
|
from app.models.intrant import AchatIntrant
|
|
|
|
router = APIRouter(tags=["intrants"])
|
|
|
|
|
|
@router.get("/achats", response_model=List[AchatIntrant])
|
|
def list_achats(
|
|
categorie: Optional[str] = Query(None),
|
|
jardin_id: Optional[int] = Query(None),
|
|
session: Session = Depends(get_session),
|
|
):
|
|
q = select(AchatIntrant)
|
|
if categorie:
|
|
q = q.where(AchatIntrant.categorie == categorie)
|
|
if jardin_id:
|
|
q = q.where(AchatIntrant.jardin_id == jardin_id)
|
|
return session.exec(q.order_by(AchatIntrant.created_at.desc())).all()
|
|
|
|
|
|
@router.post("/achats", response_model=AchatIntrant, status_code=status.HTTP_201_CREATED)
|
|
def create_achat(a: AchatIntrant, session: Session = Depends(get_session)):
|
|
session.add(a)
|
|
session.commit()
|
|
session.refresh(a)
|
|
return a
|
|
|
|
|
|
@router.get("/achats/{id}", response_model=AchatIntrant)
|
|
def get_achat(id: int, session: Session = Depends(get_session)):
|
|
a = session.get(AchatIntrant, id)
|
|
if not a:
|
|
raise HTTPException(404, "Achat introuvable")
|
|
return a
|
|
|
|
|
|
@router.put("/achats/{id}", response_model=AchatIntrant)
|
|
def update_achat(id: int, data: AchatIntrant, session: Session = Depends(get_session)):
|
|
a = session.get(AchatIntrant, id)
|
|
if not a:
|
|
raise HTTPException(404, "Achat introuvable")
|
|
for k, v in data.model_dump(exclude_unset=True, exclude={"id", "created_at"}).items():
|
|
setattr(a, k, v)
|
|
session.add(a)
|
|
session.commit()
|
|
session.refresh(a)
|
|
return a
|
|
|
|
|
|
@router.delete("/achats/{id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_achat(id: int, session: Session = Depends(get_session)):
|
|
a = session.get(AchatIntrant, id)
|
|
if not a:
|
|
raise HTTPException(404, "Achat introuvable")
|
|
session.delete(a)
|
|
session.commit()
|