Fix data fetch 2

This commit is contained in:
Urtzi Alfaro
2025-07-27 20:20:09 +02:00
parent 4684235111
commit a627b566d2
6 changed files with 179 additions and 115 deletions

View File

@@ -15,13 +15,11 @@ from app.services.traffic_service import TrafficService
from app.services.messaging import data_publisher
from app.schemas.external import (
TrafficDataResponse,
LocationRequest,
DateRangeRequest
HistoricalTrafficRequest
)
from shared.auth.decorators import (
get_current_user_dep,
get_current_tenant_id_dep
get_current_user_dep
)
router = APIRouter(tags=["traffic"])
@@ -71,37 +69,34 @@ async def get_current_traffic(
logger.error("Traffic API traceback", traceback=traceback.format_exc())
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
@router.get("/tenants/{tenant_id}/traffic/historical", response_model=List[TrafficDataResponse])
@router.post("/tenants/{tenant_id}/traffic/historical")
async def get_historical_traffic(
latitude: float = Query(..., description="Latitude"),
longitude: float = Query(..., description="Longitude"),
start_date: datetime = Query(..., description="Start date"),
end_date: datetime = Query(..., description="End date"),
request: HistoricalTrafficRequest,
db: AsyncSession = Depends(get_db),
tenant_id: UUID = Path(..., description="Tenant ID"),
current_user: Dict[str, Any] = Depends(get_current_user_dep),
):
"""Get historical traffic data"""
"""Get historical traffic data with date range in payload"""
try:
# Validate date range
if end_date <= start_date:
if request.end_date <= request.start_date:
raise HTTPException(status_code=400, detail="End date must be after start date")
if (end_date - start_date).days > 90:
if (request.end_date - request.start_date).days > 90:
raise HTTPException(status_code=400, detail="Date range cannot exceed 90 days")
historical_data = await traffic_service.get_historical_traffic(
latitude, longitude, start_date, end_date, db
request.latitude, request.longitude, request.start_date, request.end_date, db
)
# Publish event (with error handling)
try:
await data_publisher.publish_traffic_updated({
"type": "historical_requested",
"latitude": latitude,
"longitude": longitude,
"start_date": start_date.isoformat(),
"end_date": end_date.isoformat(),
"latitude": request.latitude,
"longitude": request.longitude,
"start_date": request.start_date.isoformat(),
"end_date": request.end_date.isoformat(),
"records_count": len(historical_data),
"timestamp": datetime.utcnow().isoformat()
})
@@ -112,49 +107,7 @@ async def get_historical_traffic(
return historical_data
except HTTPException:
# Re-raise HTTP exceptions
raise
except Exception as e:
logger.error("Unexpected error in historical traffic API", error=str(e))
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
@router.post("/tenants/{tenant_id}/traffic/store")
async def store_traffic_data(
latitude: float = Query(..., description="Latitude"),
longitude: float = Query(..., description="Longitude"),
db: AsyncSession = Depends(get_db),
tenant_id: UUID = Path(..., description="Tenant ID"),
current_user: Dict[str, Any] = Depends(get_current_user_dep)
):
"""Store current traffic data to database"""
try:
# Get current traffic data
traffic = await traffic_service.get_current_traffic(latitude, longitude)
if not traffic:
raise HTTPException(status_code=404, detail="No traffic data to store")
# Convert to dict for storage
traffic_dict = {
"date": traffic.date,
"traffic_volume": traffic.traffic_volume,
"pedestrian_count": traffic.pedestrian_count,
"congestion_level": traffic.congestion_level,
"average_speed": traffic.average_speed,
"source": traffic.source
}
success = await traffic_service.store_traffic_data(
latitude, longitude, traffic_dict, db
)
if success:
return {"status": "success", "message": "Traffic data stored successfully"}
else:
raise HTTPException(status_code=500, detail="Failed to store traffic data")
except HTTPException:
raise
except Exception as e:
logger.error("Error storing traffic data", error=str(e))
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")