huibao/backend/app/routers/stats.py

43 lines
1.5 KiB
Python

from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, desc
from sqlalchemy.orm import selectinload
from app.database import get_db
from app.models import Company, Report, AnalysisResult
router = APIRouter(prefix="/api/stats", tags=["统计数据"])
@router.get("/dashboard")
async def get_dashboard_stats(db: AsyncSession = Depends(get_db)):
"""获取仪表盘统计数据"""
# 统计公司数
company_count = await db.scalar(select(func.count(Company.id)))
# 统计报告数
report_count = await db.scalar(select(func.count(Report.id)))
# 统计已分析数
analyzed_count = await db.scalar(select(func.count(Report.id)).where(Report.is_analyzed == True))
# 获取最新的一条分析完成的报告
stmt = select(Report).where(Report.is_analyzed == True).order_by(desc(Report.updated_at)).limit(1).options(selectinload(Report.company))
result = await db.execute(stmt)
latest_report = result.scalar_one_or_none()
latest_insight = None
if latest_report:
latest_insight = {
"id": latest_report.id,
"title": f"{latest_report.company.short_name or latest_report.company.company_name} - {latest_report.title}",
"date": latest_report.updated_at.strftime("%Y/%m/%d")
}
return {
"company_count": company_count or 0,
"report_count": report_count or 0,
"analyzed_count": analyzed_count or 0,
"latest_insight": latest_insight
}