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-26 18:46:52 +02:00
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, BackgroundTasks, Path
|
2025-07-21 13:09:30 +02:00
|
|
|
from typing import List, Optional, Dict, Any
|
|
|
|
|
from datetime import datetime, date
|
2025-07-19 12:09:10 +02:00
|
|
|
import structlog
|
2025-07-26 18:46:52 +02:00
|
|
|
from uuid import UUID
|
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
|
|
|
|
2025-07-27 20:20:09 +02:00
|
|
|
from app.schemas.external import (
|
|
|
|
|
HistoricalWeatherRequest
|
|
|
|
|
)
|
|
|
|
|
|
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-27 20:20:09 +02:00
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
from app.core.database import get_db
|
|
|
|
|
|
2025-07-26 18:46:52 +02:00
|
|
|
router = APIRouter(tags=["weather"])
|
2025-07-19 12:09:10 +02:00
|
|
|
logger = structlog.get_logger()
|
2025-07-27 20:20:09 +02:00
|
|
|
weather_service = WeatherService()
|
2025-07-18 11:51:43 +02:00
|
|
|
|
2025-07-27 20:20:09 +02:00
|
|
|
@router.get("/tenants/{tenant_id}/weather/current", response_model=WeatherDataResponse)
|
2025-07-18 11:51:43 +02:00
|
|
|
async def get_current_weather(
|
|
|
|
|
latitude: float = Query(..., description="Latitude"),
|
|
|
|
|
longitude: float = Query(..., description="Longitude"),
|
2025-07-26 18:46:52 +02:00
|
|
|
tenant_id: UUID = Path(..., description="Tenant ID"),
|
2025-07-21 13:09:30 +02:00
|
|
|
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-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
|
|
|
|
2025-07-27 19:30:42 +02:00
|
|
|
@router.get("/tenants/{tenant_id}/weather/forecast", response_model=List[WeatherForecastResponse])
|
2025-07-18 11:51:43 +02:00
|
|
|
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-26 18:46:52 +02:00
|
|
|
tenant_id: UUID = Path(..., description="Tenant ID"),
|
2025-07-21 13:09:30 +02:00
|
|
|
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-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-27 20:20:09 +02:00
|
|
|
@router.post("/tenants/{tenant_id}/weather/historical")
|
|
|
|
|
async def get_historical_weather(
|
|
|
|
|
request: HistoricalWeatherRequest,
|
|
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
tenant_id: UUID = Path(..., description="Tenant ID"),
|
|
|
|
|
current_user: Dict[str, Any] = Depends(get_current_user_dep),
|
2025-07-18 11:51:43 +02:00
|
|
|
):
|
2025-07-27 20:20:09 +02:00
|
|
|
"""Get historical weather data with date range in payload"""
|
2025-07-18 11:51:43 +02:00
|
|
|
try:
|
2025-07-27 20:20:09 +02:00
|
|
|
# Validate date range
|
|
|
|
|
if request.end_date <= request.start_date:
|
|
|
|
|
raise HTTPException(status_code=400, detail="End date must be after start date")
|
2025-07-21 13:09:30 +02:00
|
|
|
|
2025-07-27 21:44:18 +02:00
|
|
|
if (request.end_date - request.start_date).days > 1000:
|
2025-07-27 20:20:09 +02:00
|
|
|
raise HTTPException(status_code=400, detail="Date range cannot exceed 90 days")
|
|
|
|
|
|
|
|
|
|
historical_data = await weather_service.get_historical_weather(
|
|
|
|
|
request.latitude, request.longitude, request.start_date, request.end_date, db
|
2025-07-21 13:09:30 +02:00
|
|
|
)
|
2025-07-18 11:51:43 +02:00
|
|
|
|
2025-07-27 20:20:09 +02:00
|
|
|
# Publish event (with error handling)
|
|
|
|
|
try:
|
|
|
|
|
await publish_weather_updated({
|
|
|
|
|
"type": "historical_requested",
|
|
|
|
|
"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()
|
|
|
|
|
})
|
|
|
|
|
except Exception as pub_error:
|
|
|
|
|
logger.warning("Failed to publish historical weather event", error=str(pub_error))
|
|
|
|
|
# Continue processing
|
2025-07-18 11:51:43 +02:00
|
|
|
|
2025-07-27 20:20:09 +02:00
|
|
|
return historical_data
|
|
|
|
|
|
|
|
|
|
except HTTPException:
|
|
|
|
|
raise
|
2025-07-21 13:09:30 +02:00
|
|
|
except Exception as e:
|
2025-07-27 20:20:09 +02:00
|
|
|
logger.error("Unexpected error in historical weather API", error=str(e))
|
2025-07-21 13:09:30 +02:00
|
|
|
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|
|
|
|
|
|
2025-07-27 19:30:42 +02:00
|
|
|
@router.post("/tenants/{tenant_id}weather/sync")
|
2025-07-21 13:09:30 +02:00
|
|
|
async def sync_weather_data(
|
|
|
|
|
background_tasks: BackgroundTasks,
|
|
|
|
|
force: bool = Query(False, description="Force sync even if recently synced"),
|
2025-07-26 18:46:52 +02:00
|
|
|
tenant_id: UUID = Path(..., description="Tenant ID"),
|
2025-07-21 13:09:30 +02:00
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
# 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)}")
|