urmi-ai/backend/app/routes_analytics.py
2026-10-02 11:22:40 +05:30

50 lines
1.9 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from .analytics_service import DEFAULT_GROUP_BY, SERVICE_GROUP_BY, build_usage_analytics
from .auth import current_user
from .database import get_db
from .models import UserAccount
router = APIRouter(prefix="/api/v1/analytics", tags=["analytics"])
PERIODS = frozenset({"weekly", "monthly", "quarterly"})
SERVICES = frozenset({"sms", "inbound", "outbound", "otp"})
@router.get("/usage")
def usage_analytics(
period: str = Query(default="weekly"),
service: str = Query(default="outbound"),
group_by: str | None = Query(default=None),
db: Session = Depends(get_db),
user: UserAccount = Depends(current_user),
) -> dict:
normalized_period = period.strip().lower()
normalized_service = service.strip().lower()
normalized_group = (group_by or DEFAULT_GROUP_BY.get(normalized_service, "did")).strip().lower()
if normalized_period not in PERIODS:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"period must be one of: {', '.join(sorted(PERIODS))}",
)
if normalized_service not in SERVICES:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"service must be one of: {', '.join(sorted(SERVICES))}",
)
if normalized_group not in SERVICE_GROUP_BY[normalized_service]:
allowed = ", ".join(sorted(SERVICE_GROUP_BY[normalized_service]))
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"group_by for {normalized_service} must be one of: {allowed}",
)
return build_usage_analytics(
db,
user,
period=normalized_period, # type: ignore[arg-type]
service=normalized_service, # type: ignore[arg-type]
group_by=normalized_group, # type: ignore[arg-type]
)