72 lines
2.4 KiB
Python
72 lines
2.4 KiB
Python
"""
|
|
backend/app/services/admin/dashboard_service.py
|
|
|
|
用途:管理后台仪表盘统计与侧栏角标聚合。
|
|
依赖:models、SQLAlchemy func。
|
|
逻辑:由 api/admin/dashboard.py 调用。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from sqlalchemy import func
|
|
|
|
from app import db
|
|
from app.models import Agent, ChatLog, Feedback, PermissionRequest, User
|
|
|
|
|
|
def compute_dashboard_summary() -> dict:
|
|
"""
|
|
聚合仪表盘四张卡片所需的统计值(仅 COUNT/AVG,不返回列表)。
|
|
Returns:
|
|
agent_count、user_count、total_conversations、avg_score。
|
|
"""
|
|
total_users = db.session.query(func.count(User.id)).scalar() or 0
|
|
active_agents = (
|
|
db.session.query(func.count(Agent.id))
|
|
.filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace')
|
|
.scalar()
|
|
or 0
|
|
)
|
|
total_conversations = db.session.query(func.count(ChatLog.id)).scalar() or 0
|
|
avg_score = db.session.query(func.avg(Feedback.score)).scalar()
|
|
avg_score = round(float(avg_score), 1) if avg_score else 0.0
|
|
return {
|
|
'agent_count': active_agents,
|
|
'user_count': total_users,
|
|
'total_conversations': total_conversations,
|
|
'avg_score': avg_score,
|
|
}
|
|
|
|
|
|
def compute_dashboard_badges() -> dict:
|
|
"""
|
|
聚合侧栏角标所需的待办数量。
|
|
Returns:
|
|
pending_approvals、pending_requests。
|
|
"""
|
|
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0
|
|
pending_requests = (
|
|
db.session.query(func.count(PermissionRequest.id))
|
|
.join(Agent, Agent.id == PermissionRequest.agent_id)
|
|
.filter(PermissionRequest.status == 'pending', Agent.exposure_mode == 'workspace')
|
|
.scalar()
|
|
or 0
|
|
)
|
|
return {
|
|
'pending_approvals': pending_approvals,
|
|
'pending_requests': pending_requests,
|
|
}
|
|
|
|
|
|
def compute_legacy_dashboard_stats() -> dict:
|
|
"""遗留 /dashboard 接口响应(summary + badges 字段名兼容早期前端)。"""
|
|
summary = compute_dashboard_summary()
|
|
badges = compute_dashboard_badges()
|
|
return {
|
|
'total_users': summary['user_count'],
|
|
'active_agents': summary['agent_count'],
|
|
'total_conversations': summary['total_conversations'],
|
|
'avg_score': summary['avg_score'],
|
|
'pending_approvals': badges['pending_approvals'],
|
|
'pending_requests': badges['pending_requests'],
|
|
}
|