507 lines
19 KiB
Python
507 lines
19 KiB
Python
"""
|
||
backend/app/services/admin/report_service.py
|
||
|
||
用途:管理后台报表(使用分析、应用运营、反馈、聊天日志)数据聚合。
|
||
依赖:models、SQLAlchemy func、user_agent_permissions。
|
||
逻辑:由 api/admin/reports.py、database_admin_service 调用。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import math
|
||
from datetime import datetime, timedelta
|
||
from typing import Any
|
||
|
||
from sqlalchemy import asc, desc, func, or_
|
||
|
||
from app import db
|
||
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, PermissionRequest, User
|
||
from app.models.base import user_agent_permissions
|
||
|
||
USAGE_BY_USER_TOP_LIMIT = 50
|
||
APPLICATION_REPORT_PAGE_SIZE_MAX = 100
|
||
APPLICATION_REPORT_SORT_KEYS = frozenset({
|
||
'name',
|
||
'chat_count',
|
||
'unique_users',
|
||
'last_active_at',
|
||
'authorized_users',
|
||
'pending_requests',
|
||
'avg_score',
|
||
'tokens_used',
|
||
})
|
||
DEFAULT_APPLICATION_SORT = 'chat_count'
|
||
# 运营提醒:启用应用在范围内对话次数 ≤ 该阈值视为低使用(含零使用)
|
||
USAGE_LOW_AGENT_MAX_CHATS = 2
|
||
# 运营提醒:低使用应用最多返回条数
|
||
USAGE_LOW_AGENT_LIST_LIMIT = 5
|
||
|
||
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
|
||
USAGE_RANGE_DAYS = {
|
||
'7d': 7,
|
||
'30d': 30,
|
||
'90d': 90,
|
||
'180d': 180,
|
||
'365d': 365,
|
||
}
|
||
DEFAULT_USAGE_RANGE = '30d'
|
||
|
||
|
||
def resolve_usage_range_start(range_key: str | None) -> tuple[str, datetime]:
|
||
"""
|
||
解析使用分析时间范围,返回规范化 key 与起始 UTC 时间。
|
||
|
||
Args:
|
||
range_key: 前端传入的 range(7d/30d/90d/180d/365d),非法值回退近一月。
|
||
|
||
Returns:
|
||
(normalized_key, since_utc)
|
||
"""
|
||
key = (range_key or DEFAULT_USAGE_RANGE).strip().lower()
|
||
days = USAGE_RANGE_DAYS.get(key)
|
||
if days is None:
|
||
key = DEFAULT_USAGE_RANGE
|
||
days = USAGE_RANGE_DAYS[key]
|
||
since = datetime.utcnow() - timedelta(days=days)
|
||
return key, since
|
||
|
||
|
||
def build_usage_report(*, user_page: int, user_page_size: int, range_key: str | None = None) -> dict:
|
||
"""
|
||
聊天使用分析报表(按应用 / 按用户),限定时间范围内的 ChatLog。
|
||
|
||
核心逻辑:按 Agent / User 聚合 ChatLog 次数;按用户统计同时返回 username 与 real_name;
|
||
另对启用 Agent 左连接对话量,产出含零使用的低使用应用列表(与应用运营口径对齐)。
|
||
|
||
Args:
|
||
user_page: 按用户统计分页页码。
|
||
user_page_size: 每页条数(上限 USAGE_BY_USER_TOP_LIMIT)。
|
||
range_key: 时间范围 key,见 USAGE_RANGE_DAYS。
|
||
|
||
Returns:
|
||
含 total / by_user / by_agent / by_day / low_agents 及用户分页字段的字典。
|
||
"""
|
||
normalized_range, since = resolve_usage_range_start(range_key)
|
||
base_filter = ChatLog.created_at >= since
|
||
|
||
total = db.session.query(ChatLog).filter(base_filter).count()
|
||
by_agent = (
|
||
db.session.query(Agent.name, func.count(ChatLog.id))
|
||
.join(ChatLog)
|
||
.filter(base_filter)
|
||
.group_by(Agent.name)
|
||
.order_by(desc(func.count(ChatLog.id)), Agent.name)
|
||
.all()
|
||
)
|
||
# [STEP 1] 按日期聚合趋势,供管理端判断近几天是否出现使用高峰或低谷。
|
||
by_day = (
|
||
db.session.query(func.date(ChatLog.created_at), func.count(ChatLog.id))
|
||
.filter(base_filter)
|
||
.group_by(func.date(ChatLog.created_at))
|
||
.order_by(asc(func.date(ChatLog.created_at)))
|
||
.all()
|
||
)
|
||
# [STEP 2] 低使用应用:以启用 Agent 为主表左连接范围内对话量,含零使用(by_agent 只有有对话的应用)
|
||
agent_chat_counts = (
|
||
db.session.query(
|
||
ChatLog.agent_id.label('agent_id'),
|
||
func.count(ChatLog.id).label('chat_count'),
|
||
)
|
||
.filter(base_filter)
|
||
.group_by(ChatLog.agent_id)
|
||
.subquery()
|
||
)
|
||
chat_count_col = func.coalesce(agent_chat_counts.c.chat_count, 0)
|
||
low_agents = (
|
||
db.session.query(Agent.name, chat_count_col.label('count'))
|
||
.outerjoin(agent_chat_counts, agent_chat_counts.c.agent_id == Agent.id)
|
||
.filter(Agent.is_active.is_(True))
|
||
.filter(chat_count_col <= USAGE_LOW_AGENT_MAX_CHATS)
|
||
.order_by(asc(chat_count_col), Agent.name)
|
||
.limit(USAGE_LOW_AGENT_LIST_LIMIT)
|
||
.all()
|
||
)
|
||
user_page = max(1, user_page)
|
||
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
|
||
# [STEP 3] 按用户聚合对话量,一并选出真实姓名供管理端展示
|
||
by_user_top = (
|
||
db.session.query(User.username, User.real_name, func.count(ChatLog.id))
|
||
.join(ChatLog)
|
||
.filter(base_filter)
|
||
.group_by(User.username, User.real_name)
|
||
.order_by(desc(func.count(ChatLog.id)), User.username)
|
||
.limit(USAGE_BY_USER_TOP_LIMIT)
|
||
.all()
|
||
)
|
||
user_total = len(by_user_top)
|
||
user_pages = max(1, math.ceil(user_total / user_page_size)) if user_total else 1
|
||
user_page = min(user_page, user_pages)
|
||
offset = (user_page - 1) * user_page_size
|
||
by_user_page = by_user_top[offset:offset + user_page_size]
|
||
return {
|
||
'total': total,
|
||
'range': normalized_range,
|
||
'by_user': [
|
||
{'username': u, 'real_name': rn or '', 'count': c}
|
||
for u, rn, c in by_user_page
|
||
],
|
||
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
|
||
'by_day': [{'date': str(day), 'count': c} for day, c in by_day],
|
||
'low_agents': [{'agent': a, 'count': int(c)} for a, c in low_agents],
|
||
'low_agent_max_chats': USAGE_LOW_AGENT_MAX_CHATS,
|
||
'low_agent_list_limit': USAGE_LOW_AGENT_LIST_LIMIT,
|
||
'user_total': user_total,
|
||
'user_page': user_page,
|
||
'user_page_size': user_page_size,
|
||
'user_pages': user_pages,
|
||
'user_top_limit': USAGE_BY_USER_TOP_LIMIT,
|
||
}
|
||
|
||
|
||
def build_feedback_report() -> dict:
|
||
"""反馈评分分布报表。"""
|
||
total = db.session.query(Feedback).count()
|
||
avg = db.session.query(func.avg(Feedback.score)).scalar() or 0
|
||
dist = db.session.query(Feedback.score, func.count(Feedback.id)).group_by(Feedback.score).all()
|
||
return {
|
||
'total': total,
|
||
'avg_score': float(avg),
|
||
'distribution': [{'score': s, 'count': c} for s, c in dist],
|
||
}
|
||
|
||
|
||
def build_application_report(
|
||
*,
|
||
range_key: str | None = None,
|
||
status: str | None = None,
|
||
usage: str | None = None,
|
||
q: str | None = None,
|
||
sort: str | None = None,
|
||
order: str | None = None,
|
||
page: int = 1,
|
||
page_size: int = 20,
|
||
) -> dict:
|
||
"""
|
||
应用运营报表:以 Agent 为主表,聚合时间范围内的使用 / 权限 / 评分指标。
|
||
|
||
核心逻辑:ChatLog 聚合对话与用户;user_agent_permissions 统计授权人数;
|
||
PermissionRequest 统计待审;Feedback JOIN ChatLog 统计均分。不含 API Key 等配置敏感字段。
|
||
|
||
Args:
|
||
range_key: 时间范围 key(7d/30d/90d/180d/365d),非法值回退近一月。
|
||
status: all | active | inactive,按 is_active 过滤。
|
||
usage: all | used | unused,按时间范围内是否有对话过滤。
|
||
q: 应用名称模糊搜索。
|
||
sort: 排序字段,见 APPLICATION_REPORT_SORT_KEYS。
|
||
order: asc | desc,默认 desc。
|
||
page: 页码(从 1 起)。
|
||
page_size: 每页条数,上限 APPLICATION_REPORT_PAGE_SIZE_MAX。
|
||
|
||
Returns:
|
||
含 summary / items / 分页字段的字典。
|
||
"""
|
||
normalized_range, since = resolve_usage_range_start(range_key)
|
||
status_key = (status or 'all').strip().lower()
|
||
if status_key not in {'all', 'active', 'inactive'}:
|
||
status_key = 'all'
|
||
usage_key = (usage or 'all').strip().lower()
|
||
if usage_key not in {'all', 'used', 'unused'}:
|
||
usage_key = 'all'
|
||
sort_key = (sort or DEFAULT_APPLICATION_SORT).strip().lower()
|
||
if sort_key not in APPLICATION_REPORT_SORT_KEYS:
|
||
sort_key = DEFAULT_APPLICATION_SORT
|
||
order_key = (order or 'desc').strip().lower()
|
||
if order_key not in {'asc', 'desc'}:
|
||
order_key = 'desc'
|
||
page = max(1, int(page or 1))
|
||
page_size = max(1, min(int(page_size or 20), APPLICATION_REPORT_PAGE_SIZE_MAX))
|
||
keyword = (q or '').strip()
|
||
|
||
# [STEP 1] 子查询:时间范围内对话 / 授权 / 待审 / 评分
|
||
chat_stats = (
|
||
db.session.query(
|
||
ChatLog.agent_id.label('agent_id'),
|
||
func.count(ChatLog.id).label('chat_count'),
|
||
func.count(func.distinct(ChatLog.user_id)).label('unique_users'),
|
||
func.max(ChatLog.created_at).label('last_active_at'),
|
||
func.coalesce(func.sum(ChatLog.tokens_used), 0).label('tokens_used'),
|
||
func.avg(ChatLog.latency).label('avg_latency_ms'),
|
||
)
|
||
.filter(ChatLog.created_at >= since)
|
||
.group_by(ChatLog.agent_id)
|
||
.subquery()
|
||
)
|
||
auth_stats = (
|
||
db.session.query(
|
||
user_agent_permissions.c.agent_id.label('agent_id'),
|
||
func.count(user_agent_permissions.c.user_id).label('authorized_users'),
|
||
)
|
||
.group_by(user_agent_permissions.c.agent_id)
|
||
.subquery()
|
||
)
|
||
pending_stats = (
|
||
db.session.query(
|
||
PermissionRequest.agent_id.label('agent_id'),
|
||
func.count(PermissionRequest.id).label('pending_requests'),
|
||
)
|
||
.filter(PermissionRequest.status == 'pending')
|
||
.group_by(PermissionRequest.agent_id)
|
||
.subquery()
|
||
)
|
||
feedback_stats = (
|
||
db.session.query(
|
||
ChatLog.agent_id.label('agent_id'),
|
||
func.avg(Feedback.score).label('avg_score'),
|
||
func.count(Feedback.id).label('feedback_count'),
|
||
)
|
||
.join(Feedback, Feedback.chat_log_id == ChatLog.id)
|
||
.filter(ChatLog.created_at >= since)
|
||
.group_by(ChatLog.agent_id)
|
||
.subquery()
|
||
)
|
||
|
||
chat_count_col = func.coalesce(chat_stats.c.chat_count, 0)
|
||
unique_users_col = func.coalesce(chat_stats.c.unique_users, 0)
|
||
authorized_col = func.coalesce(auth_stats.c.authorized_users, 0)
|
||
pending_col = func.coalesce(pending_stats.c.pending_requests, 0)
|
||
tokens_col = func.coalesce(chat_stats.c.tokens_used, 0)
|
||
|
||
# [STEP 2] Agent 左连接各聚合,应用筛选
|
||
query = (
|
||
db.session.query(
|
||
Agent.id,
|
||
Agent.name,
|
||
Agent.is_active,
|
||
Agent.category,
|
||
chat_count_col.label('chat_count'),
|
||
unique_users_col.label('unique_users'),
|
||
chat_stats.c.last_active_at,
|
||
authorized_col.label('authorized_users'),
|
||
pending_col.label('pending_requests'),
|
||
feedback_stats.c.avg_score,
|
||
func.coalesce(feedback_stats.c.feedback_count, 0).label('feedback_count'),
|
||
tokens_col.label('tokens_used'),
|
||
chat_stats.c.avg_latency_ms,
|
||
)
|
||
.outerjoin(chat_stats, chat_stats.c.agent_id == Agent.id)
|
||
.outerjoin(auth_stats, auth_stats.c.agent_id == Agent.id)
|
||
.outerjoin(pending_stats, pending_stats.c.agent_id == Agent.id)
|
||
.outerjoin(feedback_stats, feedback_stats.c.agent_id == Agent.id)
|
||
.filter(Agent.exposure_mode == 'workspace')
|
||
)
|
||
if status_key == 'active':
|
||
query = query.filter(Agent.is_active.is_(True))
|
||
elif status_key == 'inactive':
|
||
query = query.filter(Agent.is_active.is_(False))
|
||
if usage_key == 'used':
|
||
query = query.filter(chat_count_col > 0)
|
||
elif usage_key == 'unused':
|
||
query = query.filter(or_(chat_stats.c.chat_count.is_(None), chat_stats.c.chat_count == 0))
|
||
if keyword:
|
||
query = query.filter(Agent.name.ilike(f'%{keyword}%'))
|
||
|
||
# [STEP 3] 一次拉取筛选结果,内存排序分页(应用数量通常较小;兼容 SQLite 测试)
|
||
filtered_rows = list(query.all())
|
||
agent_total = len(filtered_rows)
|
||
active_agents = sum(1 for row in filtered_rows if row.is_active)
|
||
used_agents = sum(1 for row in filtered_rows if int(row.chat_count or 0) > 0)
|
||
unused_agents = agent_total - used_agents
|
||
pending_permission_total = sum(int(row.pending_requests or 0) for row in filtered_rows)
|
||
|
||
def _row_sort_key(row: Any) -> tuple:
|
||
"""
|
||
构造排序键:(是否空值, 业务值, 名称, id)。
|
||
空值(无最近活跃 / 无评分)始终排在末尾。
|
||
"""
|
||
if sort_key == 'name':
|
||
return (0, (row.name or '').lower(), row.name or '', row.id)
|
||
if sort_key in {'chat_count', 'unique_users', 'authorized_users', 'pending_requests', 'tokens_used'}:
|
||
return (0, int(getattr(row, sort_key) or 0), row.name or '', row.id)
|
||
raw = getattr(row, sort_key, None)
|
||
if raw is None:
|
||
return (1, None, row.name or '', row.id)
|
||
if sort_key == 'avg_score':
|
||
return (0, float(raw), row.name or '', row.id)
|
||
return (0, raw, row.name or '', row.id)
|
||
|
||
reverse = order_key == 'desc'
|
||
non_null = [r for r in filtered_rows if _row_sort_key(r)[0] == 0]
|
||
nulls = [r for r in filtered_rows if _row_sort_key(r)[0] == 1]
|
||
non_null.sort(key=_row_sort_key, reverse=reverse)
|
||
nulls.sort(key=lambda r: (r.name or '', r.id))
|
||
filtered_rows = non_null + nulls
|
||
|
||
pages = max(1, math.ceil(agent_total / page_size)) if agent_total else 1
|
||
page = min(page, pages)
|
||
offset = (page - 1) * page_size
|
||
page_rows = filtered_rows[offset:offset + page_size]
|
||
|
||
items = []
|
||
for row in page_rows:
|
||
avg_score = float(row.avg_score) if row.avg_score is not None else None
|
||
avg_latency = float(row.avg_latency_ms) if row.avg_latency_ms is not None else None
|
||
last_active = row.last_active_at.isoformat() if row.last_active_at else None
|
||
items.append({
|
||
'agent_id': row.id,
|
||
'name': row.name,
|
||
'is_active': bool(row.is_active),
|
||
'category': row.category or '',
|
||
'chat_count': int(row.chat_count or 0),
|
||
'unique_users': int(row.unique_users or 0),
|
||
'last_active_at': last_active,
|
||
'authorized_users': int(row.authorized_users or 0),
|
||
'pending_requests': int(row.pending_requests or 0),
|
||
'avg_score': round(avg_score, 2) if avg_score is not None else None,
|
||
'feedback_count': int(row.feedback_count or 0),
|
||
'tokens_used': int(row.tokens_used or 0),
|
||
'avg_latency_ms': round(avg_latency, 1) if avg_latency is not None else None,
|
||
})
|
||
|
||
return {
|
||
'range': normalized_range,
|
||
'status': status_key,
|
||
'usage': usage_key,
|
||
'q': keyword,
|
||
'sort': sort_key,
|
||
'order': order_key,
|
||
'summary': {
|
||
'agent_total': agent_total,
|
||
'active_agents': active_agents,
|
||
'used_agents': used_agents,
|
||
'unused_agents': unused_agents,
|
||
'pending_permission_total': pending_permission_total,
|
||
},
|
||
'items': items,
|
||
'total': agent_total,
|
||
'page': page,
|
||
'page_size': page_size,
|
||
'pages': pages,
|
||
}
|
||
|
||
|
||
def _apply_general_feedback_filters(query, query_params: dict[str, str]):
|
||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||
for key, value in query_params.items():
|
||
if key in reserved or not value:
|
||
continue
|
||
if hasattr(GeneralFeedback, key):
|
||
col = getattr(GeneralFeedback, key)
|
||
elif key == 'real_name':
|
||
col = User.real_name
|
||
elif key == 'department':
|
||
col = User.department
|
||
else:
|
||
continue
|
||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||
return query
|
||
|
||
|
||
def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
||
"""通用反馈列表(报表页)。"""
|
||
query = (
|
||
db.session.query(
|
||
GeneralFeedback,
|
||
User.real_name.label('real_name'),
|
||
User.department.label('department'),
|
||
)
|
||
.outerjoin(User, User.id == GeneralFeedback.user_id)
|
||
)
|
||
query = _apply_general_feedback_filters(query, query_params)
|
||
query = query.order_by(desc(GeneralFeedback.created_at), desc(GeneralFeedback.id))
|
||
try:
|
||
limit = int(query_params.get('limit', 200))
|
||
except (TypeError, ValueError):
|
||
limit = 200
|
||
limit = max(1, min(limit, 1000))
|
||
items = query.limit(limit).all()
|
||
rows = []
|
||
for item, real_name, department in items:
|
||
row = {}
|
||
for col in item.__table__.columns:
|
||
val = getattr(item, col.name)
|
||
if isinstance(val, datetime):
|
||
val = val.isoformat()
|
||
row[col.name] = val
|
||
row['real_name'] = real_name
|
||
row['department'] = department
|
||
rows.append(row)
|
||
return rows
|
||
|
||
|
||
def count_general_feedbacks_report(query_params: dict[str, str]) -> dict:
|
||
"""通用反馈计数。"""
|
||
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
|
||
query = _apply_general_feedback_filters(query, query_params)
|
||
total = query.count()
|
||
return {'table': 'general_feedbacks', 'total': int(total)}
|
||
|
||
|
||
def chat_logs_report_query():
|
||
"""ChatLog JOIN User、Agent 基础查询。"""
|
||
return (
|
||
db.session.query(
|
||
ChatLog,
|
||
User.username.label('username'),
|
||
User.real_name.label('real_name'),
|
||
Agent.name.label('agent_name'),
|
||
)
|
||
.join(User, User.id == ChatLog.user_id)
|
||
.join(Agent, Agent.id == ChatLog.agent_id)
|
||
)
|
||
|
||
|
||
def serialize_chat_log_report_row(
|
||
log: ChatLog,
|
||
username: str | None,
|
||
real_name: str | None,
|
||
agent_name: str | None,
|
||
) -> dict:
|
||
"""ChatLog 报表行序列化。"""
|
||
return {
|
||
'id': log.id,
|
||
'agent_name': agent_name or '',
|
||
'username': username or '',
|
||
'real_name': real_name or '',
|
||
'created_at': log.created_at.isoformat() if log.created_at else None,
|
||
'query': log.query,
|
||
'answer': log.answer,
|
||
'tokens_used': log.tokens_used,
|
||
}
|
||
|
||
|
||
def apply_chat_logs_report_filters(query, query_params: dict[str, str]):
|
||
"""对聊天日志报表查询应用列筛选。"""
|
||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||
for key, value in query_params.items():
|
||
if key in reserved or not value:
|
||
continue
|
||
if key == 'agent_name':
|
||
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
|
||
elif key == 'agent_id' and value.isdigit():
|
||
query = query.filter(ChatLog.agent_id == int(value))
|
||
elif key == 'username':
|
||
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
|
||
elif key == 'real_name':
|
||
query = query.filter(User.real_name.cast(db.String).ilike(f'%{value}%'))
|
||
elif hasattr(ChatLog, key):
|
||
col = getattr(ChatLog, key)
|
||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||
return query
|
||
|
||
|
||
def list_chat_logs_report(query_params: dict[str, str]) -> list[dict]:
|
||
"""聊天日志报表列表(最多 100 条)。"""
|
||
query = apply_chat_logs_report_filters(chat_logs_report_query(), query_params)
|
||
query = query.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
|
||
items = query.limit(100).all()
|
||
return [
|
||
serialize_chat_log_report_row(log, username, real_name, agent_name)
|
||
for log, username, real_name, agent_name in items
|
||
]
|
||
|
||
|
||
def count_chat_logs_report(query_params: dict[str, str]) -> dict:
|
||
"""聊天日志报表计数。"""
|
||
query = apply_chat_logs_report_filters(chat_logs_report_query(), query_params)
|
||
total = query.count()
|
||
return {'table': 'chat_logs', 'total': int(total or 0)}
|