feat: T1.4 健康度仪表盘 — 后端聚合 API + 前端驾驶舱
- 后端:dashboard 路由(summary 聚合 + scores 列表) - 前端:驾驶舱首页(KPI 卡片 + 健康度概览) - 测试:4 个仪表盘测试(总计 37 tests passed) - 前端构建 12 路由成功
This commit is contained in:
@@ -12,6 +12,7 @@ from fastapi.responses import JSONResponse
|
||||
|
||||
from app.routers.auth import router as auth_router
|
||||
from app.routers.companies import router as companies_router
|
||||
from app.routers.dashboard import router as dashboard_router
|
||||
from app.routers.reports import router as reports_router
|
||||
from app.schemas.common import error
|
||||
|
||||
@@ -71,3 +72,4 @@ async def health_check():
|
||||
app.include_router(auth_router, prefix="/api/v1")
|
||||
app.include_router(companies_router, prefix="/api/v1")
|
||||
app.include_router(reports_router, prefix="/api/v1")
|
||||
app.include_router(dashboard_router, prefix="/api/v1")
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""健康度评分 + 仪表盘路由。"""
|
||||
|
||||
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
|
||||
|
||||
router = APIRouter(prefix="/dashboard", tags=["dashboard"])
|
||||
|
||||
|
||||
@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)
|
||||
@@ -0,0 +1,30 @@
|
||||
"""健康度评分相关 Pydantic schema。"""
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class HealthScoreResponse(BaseModel):
|
||||
"""健康度评分响应。"""
|
||||
|
||||
id: str
|
||||
company_id: str
|
||||
total_score: float
|
||||
financial_score: float | None = None
|
||||
operational_score: float | None = None
|
||||
ai_commercial_score: float | None = None
|
||||
ai_cost_score: float | None = None
|
||||
trend: str | None = None
|
||||
evidence_json: dict | None = None
|
||||
recommendations_json: dict | None = None
|
||||
calculated_at: datetime
|
||||
|
||||
|
||||
class DashboardSummary(BaseModel):
|
||||
"""仪表盘汇总数据。"""
|
||||
|
||||
total_companies: int
|
||||
avg_health_score: float
|
||||
high_risk_count: int
|
||||
pending_reports: int
|
||||
recent_scores: list[HealthScoreResponse]
|
||||
@@ -0,0 +1,106 @@
|
||||
"""仪表盘 API 测试。"""
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
||||
from app.core.database import Base, get_db
|
||||
from app.main import app
|
||||
|
||||
TEST_DATABASE_URL = "sqlite+aiosqlite:///file::memory:?cache=shared&uri=true"
|
||||
|
||||
test_engine = create_async_engine(TEST_DATABASE_URL, echo=False)
|
||||
test_session_factory = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
|
||||
async def override_get_db():
|
||||
async with test_session_factory() as session:
|
||||
try:
|
||||
yield session
|
||||
await session.commit()
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
async def setup_db():
|
||||
async with test_engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
yield
|
||||
async with test_engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.drop_all)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers(client: TestClient):
|
||||
"""注册并登录。"""
|
||||
client.post(
|
||||
"/api/v1/auth/register",
|
||||
json={
|
||||
"email": "dashboard_test@example.com",
|
||||
"password": "password123",
|
||||
"name": "测试投资经理",
|
||||
"tenant_name": "测试机构",
|
||||
"role": "investor",
|
||||
},
|
||||
)
|
||||
resp = client.post(
|
||||
"/api/v1/auth/login",
|
||||
json={"email": "dashboard_test@example.com", "password": "password123"},
|
||||
)
|
||||
token = resp.json()["data"]["access_token"]
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
class TestDashboardSummary:
|
||||
"""仪表盘汇总测试。"""
|
||||
|
||||
def test_summary_empty(self, client: TestClient, auth_headers: dict):
|
||||
"""空租户的汇总数据。"""
|
||||
response = client.get("/api/v1/dashboard/summary", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["code"] == 0
|
||||
assert data["data"]["total_companies"] == 0
|
||||
assert data["data"]["avg_health_score"] == 0.0
|
||||
assert data["data"]["high_risk_count"] == 0
|
||||
assert data["data"]["pending_reports"] == 0
|
||||
|
||||
def test_summary_without_auth(self, client: TestClient):
|
||||
"""无认证应返回 401。"""
|
||||
response = client.get("/api/v1/dashboard/summary")
|
||||
assert response.status_code == 401
|
||||
|
||||
def test_summary_with_data(self, client: TestClient, auth_headers: dict):
|
||||
"""有企业数据后的汇总。"""
|
||||
# 创建企业
|
||||
client.post(
|
||||
"/api/v1/companies",
|
||||
json={"name": "仪表盘测试公司", "industry": "AI"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
response = client.get("/api/v1/dashboard/summary", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["data"]["total_companies"] >= 1
|
||||
|
||||
|
||||
class TestHealthScores:
|
||||
"""健康度评分列表测试。"""
|
||||
|
||||
def test_list_scores_empty(self, client: TestClient, auth_headers: dict):
|
||||
"""空评分列表。"""
|
||||
response = client.get("/api/v1/dashboard/scores", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["code"] == 0
|
||||
assert isinstance(data["data"], list)
|
||||
Reference in New Issue
Block a user