58 lines
2.4 KiB
Python
58 lines
2.4 KiB
Python
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from ..database import get_db
|
|
from ..models.address import Address
|
|
from ..models.report import ServiceRating
|
|
from ..schemas.eta import ETAResponse, RouteScheduleResponse, ServiceRatingCreate
|
|
from ..services import eta_service
|
|
from .deps import get_current_user
|
|
|
|
router = APIRouter(prefix="/eta", tags=["eta"])
|
|
|
|
|
|
def _get_owned_address(address_id: int, user, db: Session) -> Address:
|
|
address = db.query(Address).filter(Address.id == address_id, Address.user_id == user.id).first()
|
|
if not address:
|
|
raise HTTPException(status_code=404, detail="Domicilio no encontrado")
|
|
if not address.route_id:
|
|
raise HTTPException(status_code=422, detail="Este domicilio no tiene una ruta asignada todavía")
|
|
return address
|
|
|
|
|
|
@router.get("/address/{address_id}", response_model=ETAResponse)
|
|
def get_eta_for_address(address_id: int, db: Session = Depends(get_db), user=Depends(get_current_user)):
|
|
"""
|
|
Returns the ETA for the garbage truck to reach the user's registered address.
|
|
Privacy-by-design: never exposes truck coordinates or other users' routes.
|
|
"""
|
|
address = _get_owned_address(address_id, user, db)
|
|
result = eta_service.get_eta(address.route_id, address.lat, address.lng)
|
|
return result
|
|
|
|
|
|
@router.get("/schedule/{address_id}", response_model=RouteScheduleResponse)
|
|
def get_schedule_for_address(address_id: int, db: Session = Depends(get_db), user=Depends(get_current_user)):
|
|
address = _get_owned_address(address_id, user, db)
|
|
schedule = eta_service.get_route_schedule(address.route_id)
|
|
if not schedule:
|
|
raise HTTPException(status_code=404, detail="Horario no disponible")
|
|
return schedule
|
|
|
|
|
|
@router.post("/rate", status_code=201)
|
|
def rate_service(data: ServiceRatingCreate, db: Session = Depends(get_db), user=Depends(get_current_user)):
|
|
address = db.query(Address).filter(Address.id == data.address_id, Address.user_id == user.id).first()
|
|
if not address:
|
|
raise HTTPException(status_code=404, detail="Domicilio no encontrado")
|
|
if not 1 <= data.rating <= 5:
|
|
raise HTTPException(status_code=400, detail="La calificación debe ser entre 1 y 5")
|
|
rating = ServiceRating(
|
|
user_id=user.id,
|
|
address_id=data.address_id,
|
|
rating=data.rating,
|
|
comment=data.comment,
|
|
)
|
|
db.add(rating)
|
|
db.commit()
|
|
return {"message": "Gracias por tu calificación"}
|