Files
AIPortPilot/backend/app/routers/dashboard.py
T
selfrelease fad458b2a7 docs(uiux): UIUX 设计方案大改 + 5 份作业指导书对齐 + 开发任务文档
- UIUX 文档:填充 19 个缺口(多主体画像/健康度/AI+看板/增长域/洞察域/创始人端/OODA/助推/商密)
- UIUX 文档:插入 6 个新章节(十四~十九),旧章节重编号为二十~三十一,更新目录和交叉引用
- 作业指导书 x5:导航改为 6 域分组,新增 Context Bar/工作模式/Insight Rail/决策线程/多工作区等 UI 概念
- 新建 docs/2-task-uiux.md:50 个代码落地开发任务,按 P0-P6 分优先级 + 8 Sprint 规划
- 后端/前端:大量新增模型、路由、组件(来自之前 Phase 开发)
2026-07-19 11:53:38 +08:00

254 lines
9.0 KiB
Python

"""健康度评分 + 仪表盘路由。"""
from fastapi import APIRouter, Depends, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.models.company import Company
from app.models.health_score import HealthScore
from app.models.report import MonthlyReport
from app.models.risk import RiskEvent
from app.models.user import User
from app.schemas.common import ApiResponse, success
from app.schemas.health_score import DashboardSummary, HealthScoreResponse
from app.services.predictor import predict_trend, detect_anomalies
router = APIRouter(prefix="/dashboard", tags=["dashboard"])
# 14 维度 key 列表
_DIMENSION_KEYS = [
"financial_score", "operational_score", "ai_commercial_score", "ai_cost_score",
"org_talent_score", "product_tech_score", "market_compete_score", "governance_score",
"financing_score", "synergy_score", "ai_model_product_score",
"data_compliance_score", "team_tech_score", "customer_success_score",
]
@router.get("/summary", response_model=ApiResponse[DashboardSummary])
async def get_dashboard_summary(
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
):
"""获取仪表盘汇总数据。"""
tenant_id = user.tenant_id
# 企业总数
companies_result = await db.execute(
select(func.count()).select_from(Company).where(Company.tenant_id == tenant_id)
)
total_companies = companies_result.scalar_one()
# 平均健康度
avg_result = await db.execute(
select(func.avg(HealthScore.total_score))
.join(Company, HealthScore.company_id == Company.id)
.where(Company.tenant_id == tenant_id)
)
avg_score = avg_result.scalar_one()
avg_health_score = float(avg_score) if avg_score else 0.0
# 高风险事件数
risk_result = await db.execute(
select(func.count())
.select_from(RiskEvent)
.join(Company, RiskEvent.company_id == Company.id)
.where(Company.tenant_id == tenant_id, RiskEvent.status.in_(["open", "assigned", "in_progress"]))
)
high_risk_count = risk_result.scalar_one()
# 待审阅月报数
pending_result = await db.execute(
select(func.count())
.select_from(MonthlyReport)
.join(Company, MonthlyReport.company_id == Company.id)
.where(Company.tenant_id == tenant_id, MonthlyReport.status.in_(["submitted", "ai_parsed"]))
)
pending_reports = pending_result.scalar_one()
# 最近评分(最多 10 条)
recent_result = await db.execute(
select(HealthScore)
.join(Company, HealthScore.company_id == Company.id)
.where(Company.tenant_id == tenant_id)
.order_by(HealthScore.calculated_at.desc())
.limit(10)
)
recent_scores = [
HealthScoreResponse.model_validate(s, from_attributes=True)
for s in recent_result.scalars().all()
]
return success(
data=DashboardSummary(
total_companies=total_companies,
avg_health_score=round(avg_health_score, 1),
high_risk_count=high_risk_count,
pending_reports=pending_reports,
recent_scores=recent_scores,
)
)
@router.get("/scores", response_model=ApiResponse[list[HealthScoreResponse]])
async def list_health_scores(
company_id: str | None = Query(default=None),
limit: int = Query(default=20, ge=1, le=100),
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
):
"""获取健康度评分列表。"""
query = (
select(HealthScore)
.join(Company, HealthScore.company_id == Company.id)
.where(Company.tenant_id == user.tenant_id)
)
if company_id:
query = query.where(HealthScore.company_id == company_id)
query = query.order_by(HealthScore.calculated_at.desc()).limit(limit)
result = await db.execute(query)
scores = [
HealthScoreResponse.model_validate(s, from_attributes=True)
for s in result.scalars().all()
]
return success(data=scores)
@router.get("/heatmap", response_model=ApiResponse[list[dict]])
async def get_health_heatmap(
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
):
"""获取健康度热力图数据 — 企业 × 维度评分矩阵。
返回格式:[{ company_id, company_name, scores: { dimension: score } }]
"""
# 获取租户下所有企业
companies_result = await db.execute(
select(Company).where(Company.tenant_id == user.tenant_id).order_by(Company.name)
)
companies = companies_result.scalars().all()
# 获取每个企业最新评分
heatmap = []
for company in companies:
score_result = await db.execute(
select(HealthScore)
.where(HealthScore.company_id == company.id)
.order_by(HealthScore.calculated_at.desc())
.limit(1)
)
score = score_result.scalar_one_or_none()
scores_dict = {}
if score:
for dim_key in _DIMENSION_KEYS:
val = getattr(score, dim_key, None)
if val is not None:
scores_dict[dim_key] = val
heatmap.append({
"company_id": company.id,
"company_name": company.name,
"total_score": score.total_score if score else None,
"scores": scores_dict,
})
return success(data=heatmap)
@router.get("/trends", response_model=ApiResponse[list[dict]])
async def get_health_trends(
company_id: str | None = Query(default=None, description="指定企业 ID,不传则汇总"),
months: int = Query(default=6, ge=1, le=24, description="趋势月数"),
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
):
"""获取健康度趋势对比数据 — 按月汇总评分变化。
返回格式:[{ period, avg_score, company_count, dimension_avgs: { dimension: avg } }]
"""
query = (
select(HealthScore)
.join(Company, HealthScore.company_id == Company.id)
.where(Company.tenant_id == user.tenant_id)
)
if company_id:
query = query.where(HealthScore.company_id == company_id)
query = query.order_by(HealthScore.calculated_at.desc()).limit(months * 50)
result = await db.execute(query)
scores = result.scalars().all()
# 按月分组
monthly: dict[str, list[HealthScore]] = {}
for s in scores:
period = s.calculated_at.strftime("%Y-%m")
monthly.setdefault(period, []).append(s)
trends = []
for period in sorted(monthly.keys()):
month_scores = monthly[period]
count = len(month_scores)
avg_total = sum(s.total_score for s in month_scores) / count if count else 0
dim_avgs = {}
for dim_key in _DIMENSION_KEYS:
vals = [getattr(s, dim_key) for s in month_scores if getattr(s, dim_key) is not None]
if vals:
dim_avgs[dim_key] = round(sum(vals) / len(vals), 1)
trends.append({
"period": period,
"avg_score": round(avg_total, 1),
"company_count": count,
"dimension_avgs": dim_avgs,
})
return success(data=trends)
@router.get("/forecasts", response_model=ApiResponse[dict])
async def get_health_forecasts(
company_id: str | None = Query(default=None, description="指定企业 ID,不传则汇总全租户"),
months_ahead: int = Query(default=3, ge=1, le=6, description="预测月数"),
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
):
"""获取健康度预测数据 — 基于历史评分预测未来趋势 + 异常检测。
返回格式:{ predictions: [...], trend_direction, confidence, anomalies: [...] }
"""
query = (
select(HealthScore)
.join(Company, HealthScore.company_id == Company.id)
.where(Company.tenant_id == user.tenant_id)
)
if company_id:
query = query.where(HealthScore.company_id == company_id)
query = query.order_by(HealthScore.calculated_at.asc()).limit(24)
result = await db.execute(query)
scores = result.scalars().all()
historical = [s.total_score for s in scores]
forecast = predict_trend(historical, months_ahead)
# 异常检测 — 各维度
anomalies_by_dim: dict[str, list[int]] = {}
for dim_key in _DIMENSION_KEYS:
dim_values = [getattr(s, dim_key) for s in scores if getattr(s, dim_key) is not None]
if len(dim_values) >= 3:
dim_anomalies = detect_anomalies(dim_values)
if dim_anomalies:
anomalies_by_dim[dim_key] = dim_anomalies
return success(data={
"predictions": forecast.get("predicted", []),
"slope": forecast.get("slope", 0),
"confidence": forecast.get("confidence", 0),
"trend_direction": "up" if forecast.get("slope", 0) > 1 else "down" if forecast.get("slope", 0) < -1 else "stable",
"anomalies": anomalies_by_dim,
"historical_count": len(historical),
})