diff --git a/backend/app/routers/puck.py b/backend/app/routers/puck.py index 6f08479..c616103 100644 --- a/backend/app/routers/puck.py +++ b/backend/app/routers/puck.py @@ -3,7 +3,7 @@ from sqlalchemy.orm import Session from typing import List import uuid from app.schemas import Puck as PuckSchema, PuckCreate, PuckUpdate, SetTellPosition, PuckEvent -from app.models import Puck as PuckModel, Sample as SampleModel, PuckEvent as PuckEventModel, Slot as SlotModel +from app.models import Puck as PuckModel, Sample as SampleModel, PuckEvent as PuckEventModel, Slot as SlotModel, LogisticsEvent as LogisticsEventModel from app.dependencies import get_db from datetime import datetime @@ -128,22 +128,37 @@ async def get_last_tell_position(puck_id: str, db: Session = Depends(get_db)): "timestamp": last_event.timestamp, } -@router.get("/pucks/slot/{slot_id}", response_model=List[PuckSchema]) -async def get_pucks_by_dewar_slot(slot_id: int, db: Session = Depends(get_db)): +@router.get("/slot/{slot_id}", response_model=List[PuckSchema]) +async def get_pucks_by_latest_dewar_slot(slot_id: int, db: Session = Depends(get_db)): """ - Retrieve all pucks for a given slot_id by finding the associated dewar. + Retrieve all pucks for the most recent dewar associated with the given slot_id. """ - # Query the Slot table to get the associated dewar based on slot_id + # Query the Slot table to ensure the slot exists slot = db.query(SlotModel).filter(SlotModel.id == slot_id).first() if not slot: raise HTTPException(status_code=404, detail="Slot not found") - # Check if the slot has a dewar associated + # Check if this slot has an associated dewar if not slot.dewar: - return [] # Return an empty list if no dewar is associated + raise HTTPException(status_code=404, detail="No dewar associated with the given slot") - # Retrieve all pucks associated with the dewar - pucks = db.query(PuckModel).filter(PuckModel.dewar_id == slot.dewar.id).all() + # Find the most recent slot for the associated dewar (using a timestamp or event record) + # Query related `LogisticsEvent` or the latest assignment of this dewar + recent_slot = ( + db.query(SlotModel) + .join(LogisticsEventModel, + SlotModel.id == LogisticsEventModel.slot_id) # Assumes LogisticsEvent tracks slot changes + .filter(SlotModel.dewar_unique_id == slot.dewar_unique_id) # Match slots by dewar's unique ID + .order_by(LogisticsEventModel.timestamp.desc()) # Most recent event + .first() + ) - # Return the list of pucks (empty if no pucks are found) - return pucks \ No newline at end of file + # Confirm if a recent slot association exists + if not recent_slot or not recent_slot.dewar: + raise HTTPException(status_code=404, detail="No recent slot association found for the dewar") + + # Retrieve all pucks from the dewar currently in the recent slot + pucks = db.query(PuckModel).filter(PuckModel.dewar_id == recent_slot.dewar.id).all() + + # Return the list of pucks + return pucks