Files
jardin/backend/app/routers/plantings.py
2026-03-01 07:21:46 +01:00

77 lines
2.7 KiB
Python

from datetime import datetime, timezone
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlmodel import Session, select
from app.database import get_session
from app.models.planting import Planting, PlantingCreate, PlantingEvent
router = APIRouter(tags=["plantations"])
@router.get("/plantings", response_model=List[Planting])
def list_plantings(session: Session = Depends(get_session)):
return session.exec(select(Planting)).all()
@router.post("/plantings", response_model=Planting, status_code=status.HTTP_201_CREATED)
def create_planting(data: PlantingCreate, session: Session = Depends(get_session)):
d = data.model_dump()
# Rétro-compatibilité : cell_id = première zone sélectionnée
if d.get("cell_ids") and not d.get("cell_id"):
d["cell_id"] = d["cell_ids"][0]
p = Planting(**d)
session.add(p)
session.commit()
session.refresh(p)
return p
@router.get("/plantings/{id}", response_model=Planting)
def get_planting(id: int, session: Session = Depends(get_session)):
p = session.get(Planting, id)
if not p:
raise HTTPException(status_code=404, detail="Plantation introuvable")
return p
@router.put("/plantings/{id}", response_model=Planting)
def update_planting(id: int, data: PlantingCreate, session: Session = Depends(get_session)):
p = session.get(Planting, id)
if not p:
raise HTTPException(status_code=404, detail="Plantation introuvable")
d = data.model_dump(exclude_unset=True)
# Rétro-compatibilité : cell_id = première zone sélectionnée
if "cell_ids" in d:
ids = d["cell_ids"] or []
d["cell_id"] = ids[0] if ids else None
for k, v in d.items():
setattr(p, k, v)
p.updated_at = datetime.now(timezone.utc)
session.add(p)
session.commit()
session.refresh(p)
return p
@router.delete("/plantings/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_planting(id: int, session: Session = Depends(get_session)):
p = session.get(Planting, id)
if not p:
raise HTTPException(status_code=404, detail="Plantation introuvable")
session.delete(p)
session.commit()
@router.get("/plantings/{id}/events", response_model=List[PlantingEvent])
def list_events(id: int, session: Session = Depends(get_session)):
return session.exec(select(PlantingEvent).where(PlantingEvent.planting_id == id)).all()
@router.post("/plantings/{id}/events", response_model=PlantingEvent, status_code=status.HTTP_201_CREATED)
def create_event(id: int, e: PlantingEvent, session: Session = Depends(get_session)):
e.planting_id = id
session.add(e)
session.commit()
session.refresh(e)
return e