from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session, joinedload from typing import List from database import get_db from models import Batch, Variety from schemas import BatchCreate, BatchUpdate, BatchOut router = APIRouter(prefix="/batches", tags=["batches"]) @router.get("/", response_model=List[BatchOut]) def list_batches(db: Session = Depends(get_db)): return ( db.query(Batch) .options(joinedload(Batch.variety)) .order_by(Batch.sow_date.desc().nullslast(), Batch.created_at.desc()) .all() ) @router.get("/{batch_id}", response_model=BatchOut) def get_batch(batch_id: int, db: Session = Depends(get_db)): b = db.query(Batch).options(joinedload(Batch.variety)).filter(Batch.id == batch_id).first() if not b: raise HTTPException(status_code=404, detail="Batch not found") return b @router.post("/", response_model=BatchOut, status_code=201) def create_batch(data: BatchCreate, db: Session = Depends(get_db)): if not db.query(Variety).filter(Variety.id == data.variety_id).first(): raise HTTPException(status_code=404, detail="Variety not found") b = Batch(**data.model_dump()) db.add(b) db.commit() db.refresh(b) return db.query(Batch).options(joinedload(Batch.variety)).filter(Batch.id == b.id).first() @router.put("/{batch_id}", response_model=BatchOut) def update_batch(batch_id: int, data: BatchUpdate, db: Session = Depends(get_db)): b = db.query(Batch).filter(Batch.id == batch_id).first() if not b: raise HTTPException(status_code=404, detail="Batch not found") for field, value in data.model_dump().items(): setattr(b, field, value) db.commit() db.refresh(b) return db.query(Batch).options(joinedload(Batch.variety)).filter(Batch.id == b.id).first() @router.delete("/{batch_id}", status_code=204) def delete_batch(batch_id: int, db: Session = Depends(get_db)): b = db.query(Batch).filter(Batch.id == batch_id).first() if not b: raise HTTPException(status_code=404, detail="Batch not found") db.delete(b) db.commit()