237 lines
8.0 KiB
Python
237 lines
8.0 KiB
Python
"""
|
||
backend/app/services/admin/report_service.py
|
||
|
||
用途:管理后台报表(使用分析、反馈、聊天日志)数据聚合。
|
||
依赖:models、SQLAlchemy func。
|
||
逻辑:由 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 desc, func
|
||
|
||
from app import db
|
||
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
|
||
|
||
USAGE_BY_USER_TOP_LIMIT = 50
|
||
|
||
# 使用分析时间范围: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。
|
||
|
||
Args:
|
||
user_page: 按用户统计分页页码。
|
||
user_page_size: 每页条数(上限 USAGE_BY_USER_TOP_LIMIT)。
|
||
range_key: 时间范围 key,见 USAGE_RANGE_DAYS。
|
||
"""
|
||
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()
|
||
)
|
||
user_page = max(1, user_page)
|
||
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
|
||
by_user_top = (
|
||
db.session.query(User.username, func.count(ChatLog.id))
|
||
.join(ChatLog)
|
||
.filter(base_filter)
|
||
.group_by(User.username)
|
||
.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, 'count': c} for u, c in by_user_page],
|
||
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
|
||
'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 _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 == '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)}
|