Files
bakery-ia/services/data/app/api/weather.py

178 lines
6.5 KiB
Python
Raw Normal View History

2025-07-21 13:09:30 +02:00
# services/data/app/api/weather.py - UPDATED WITH UNIFIED AUTH
"""Weather data API endpoints with unified authentication"""
2025-07-18 11:51:43 +02:00
2025-07-21 13:09:30 +02:00
from fastapi import APIRouter, Depends, HTTPException, Query, BackgroundTasks
from typing import List, Optional, Dict, Any
from datetime import datetime, date
2025-07-19 12:09:10 +02:00
import structlog
2025-07-18 11:51:43 +02:00
2025-07-21 14:41:33 +02:00
from app.schemas.external import (
2025-07-21 13:09:30 +02:00
WeatherDataResponse,
2025-07-21 14:41:33 +02:00
WeatherForecastResponse
2025-07-21 13:09:30 +02:00
)
2025-07-18 11:51:43 +02:00
from app.services.weather_service import WeatherService
2025-07-19 12:51:28 +02:00
from app.services.messaging import publish_weather_updated
2025-07-21 13:09:30 +02:00
# Import unified authentication from shared library
from shared.auth.decorators import (
get_current_user_dep,
get_current_tenant_id_dep
2025-07-18 11:51:43 +02:00
)
2025-07-21 13:09:30 +02:00
router = APIRouter(prefix="/weather", tags=["weather"])
2025-07-19 12:09:10 +02:00
logger = structlog.get_logger()
2025-07-18 11:51:43 +02:00
@router.get("/current", response_model=WeatherDataResponse)
async def get_current_weather(
latitude: float = Query(..., description="Latitude"),
longitude: float = Query(..., description="Longitude"),
2025-07-21 13:09:30 +02:00
tenant_id: str = Depends(get_current_tenant_id_dep),
current_user: Dict[str, Any] = Depends(get_current_user_dep),
2025-07-18 11:51:43 +02:00
):
2025-07-21 13:09:30 +02:00
"""Get current weather data for location"""
2025-07-18 11:51:43 +02:00
try:
2025-07-21 13:09:30 +02:00
logger.debug("Getting current weather",
lat=latitude,
lon=longitude,
tenant_id=tenant_id,
user_id=current_user["user_id"])
2025-07-19 12:09:10 +02:00
2025-07-21 13:09:30 +02:00
weather_service = WeatherService()
2025-07-18 11:51:43 +02:00
weather = await weather_service.get_current_weather(latitude, longitude)
2025-07-19 12:09:10 +02:00
2025-07-18 11:51:43 +02:00
if not weather:
raise HTTPException(status_code=404, detail="Weather data not available")
2025-07-21 13:09:30 +02:00
# Publish event
try:
await publish_weather_updated({
"type": "current_weather_requested",
"tenant_id": tenant_id,
"latitude": latitude,
"longitude": longitude,
"requested_by": current_user["user_id"],
"timestamp": datetime.utcnow().isoformat()
})
except Exception as e:
logger.warning("Failed to publish weather event", error=str(e))
2025-07-18 11:51:43 +02:00
return weather
2025-07-19 12:09:10 +02:00
except HTTPException:
raise
2025-07-18 11:51:43 +02:00
except Exception as e:
2025-07-21 13:09:30 +02:00
logger.error("Failed to get current weather", error=str(e))
2025-07-19 12:09:10 +02:00
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
2025-07-18 11:51:43 +02:00
@router.get("/forecast", response_model=List[WeatherForecastResponse])
async def get_weather_forecast(
latitude: float = Query(..., description="Latitude"),
longitude: float = Query(..., description="Longitude"),
days: int = Query(7, description="Number of forecast days", ge=1, le=14),
2025-07-21 13:09:30 +02:00
tenant_id: str = Depends(get_current_tenant_id_dep),
current_user: Dict[str, Any] = Depends(get_current_user_dep),
2025-07-18 11:51:43 +02:00
):
"""Get weather forecast for location"""
try:
2025-07-21 13:09:30 +02:00
logger.debug("Getting weather forecast",
lat=latitude,
lon=longitude,
days=days,
tenant_id=tenant_id)
2025-07-19 12:09:10 +02:00
2025-07-21 13:09:30 +02:00
weather_service = WeatherService()
2025-07-18 11:51:43 +02:00
forecast = await weather_service.get_weather_forecast(latitude, longitude, days)
2025-07-19 12:09:10 +02:00
if not forecast:
raise HTTPException(status_code=404, detail="Weather forecast not available")
2025-07-21 13:09:30 +02:00
# Publish event
2025-07-19 12:09:10 +02:00
try:
2025-07-19 12:51:28 +02:00
await publish_weather_updated({
2025-07-19 12:09:10 +02:00
"type": "forecast_requested",
2025-07-21 13:09:30 +02:00
"tenant_id": tenant_id,
2025-07-19 12:09:10 +02:00
"latitude": latitude,
"longitude": longitude,
"days": days,
2025-07-21 13:09:30 +02:00
"requested_by": current_user["user_id"],
2025-07-19 12:09:10 +02:00
"timestamp": datetime.utcnow().isoformat()
})
2025-07-21 13:09:30 +02:00
except Exception as e:
logger.warning("Failed to publish forecast event", error=str(e))
2025-07-18 11:51:43 +02:00
return forecast
2025-07-19 12:09:10 +02:00
except HTTPException:
raise
2025-07-18 11:51:43 +02:00
except Exception as e:
2025-07-21 13:09:30 +02:00
logger.error("Failed to get weather forecast", error=str(e))
2025-07-19 12:09:10 +02:00
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
2025-07-18 11:51:43 +02:00
2025-07-21 13:09:30 +02:00
@router.get("/history", response_model=List[WeatherDataResponse])
async def get_weather_history(
start_date: date = Query(..., description="Start date"),
end_date: date = Query(..., description="End date"),
2025-07-18 11:51:43 +02:00
latitude: float = Query(..., description="Latitude"),
longitude: float = Query(..., description="Longitude"),
2025-07-21 13:09:30 +02:00
tenant_id: str = Depends(get_current_tenant_id_dep),
current_user: Dict[str, Any] = Depends(get_current_user_dep),
2025-07-18 11:51:43 +02:00
):
"""Get historical weather data"""
try:
2025-07-21 13:09:30 +02:00
logger.debug("Getting weather history",
start_date=start_date,
end_date=end_date,
tenant_id=tenant_id)
weather_service = WeatherService()
history = await weather_service.get_weather_history(
latitude, longitude, start_date, end_date
)
2025-07-18 11:51:43 +02:00
2025-07-21 13:09:30 +02:00
return history
2025-07-18 11:51:43 +02:00
2025-07-21 13:09:30 +02:00
except Exception as e:
logger.error("Failed to get weather history", error=str(e))
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
@router.post("/sync")
async def sync_weather_data(
background_tasks: BackgroundTasks,
force: bool = Query(False, description="Force sync even if recently synced"),
tenant_id: str = Depends(get_current_tenant_id_dep),
current_user: Dict[str, Any] = Depends(get_current_user_dep),
2025-07-19 12:09:10 +02:00
):
2025-07-21 13:09:30 +02:00
"""Manually trigger weather data synchronization"""
2025-07-19 12:09:10 +02:00
try:
2025-07-21 13:09:30 +02:00
logger.info("Weather sync requested",
tenant_id=tenant_id,
user_id=current_user["user_id"],
force=force)
weather_service = WeatherService()
# Check if user has permission to sync (could be admin only)
if current_user.get("role") not in ["admin", "manager"]:
raise HTTPException(
status_code=403,
detail="Insufficient permissions to sync weather data"
)
# Schedule background sync
background_tasks.add_task(
weather_service.sync_weather_data,
tenant_id=tenant_id,
force=force
)
2025-07-19 12:09:10 +02:00
2025-07-21 13:09:30 +02:00
return {
"message": "Weather sync initiated",
"status": "processing",
"initiated_by": current_user["user_id"]
2025-07-19 12:09:10 +02:00
}
except HTTPException:
raise
2025-07-18 11:51:43 +02:00
except Exception as e:
2025-07-21 13:09:30 +02:00
logger.error("Failed to initiate weather sync", error=str(e))
2025-07-19 12:09:10 +02:00
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")