""" Dashboard statistics endpoints. Provides overview statistics for the admin dashboard. """ import logging from typing import Annotated from fastapi import APIRouter, Depends from fastapi.responses import JSONResponse from sqlalchemy import select, func from sqlalchemy.ext.asyncio import AsyncSession from app.core.database import get_session from app.core.exceptions import MissingTenantIdException from app.core.tenant import get_tenant_id from app.models import ErrorResponse from app.models.entities import ChatMessage, ChatSession, Document, KnowledgeBase logger = logging.getLogger(__name__) router = APIRouter(prefix="/admin/dashboard", tags=["Dashboard"]) def get_current_tenant_id() -> str: """Dependency to get current tenant ID or raise exception.""" tenant_id = get_tenant_id() if not tenant_id: raise MissingTenantIdException() return tenant_id @router.get( "/stats", operation_id="getDashboardStats", summary="Get dashboard statistics", description="Get overview statistics for the admin dashboard.", responses={ 200: {"description": "Dashboard statistics"}, 401: {"description": "Unauthorized", "model": ErrorResponse}, 403: {"description": "Forbidden", "model": ErrorResponse}, }, ) async def get_dashboard_stats( tenant_id: Annotated[str, Depends(get_current_tenant_id)], session: Annotated[AsyncSession, Depends(get_session)], ) -> JSONResponse: """ Get dashboard statistics including knowledge bases, messages, and activity. """ logger.info(f"Getting dashboard stats: tenant={tenant_id}") kb_count_stmt = select(func.count()).select_from(KnowledgeBase).where( KnowledgeBase.tenant_id == tenant_id ) kb_result = await session.execute(kb_count_stmt) kb_count = kb_result.scalar() or 0 msg_count_stmt = select(func.count()).select_from(ChatMessage).where( ChatMessage.tenant_id == tenant_id ) msg_result = await session.execute(msg_count_stmt) msg_count = msg_result.scalar() or 0 doc_count_stmt = select(func.count()).select_from(Document).where( Document.tenant_id == tenant_id ) doc_result = await session.execute(doc_count_stmt) doc_count = doc_result.scalar() or 0 session_count_stmt = select(func.count()).select_from(ChatSession).where( ChatSession.tenant_id == tenant_id ) session_result = await session.execute(session_count_stmt) session_count = session_result.scalar() or 0 return JSONResponse( content={ "knowledgeBases": kb_count, "totalMessages": msg_count, "totalDocuments": doc_count, "totalSessions": session_count, } )