195 lines
6.7 KiB
Python
195 lines
6.7 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
|
|
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
|
|
|
|
|
|
def build_usage_report(*, user_page: int, user_page_size: int) -> dict:
|
|
"""聊天使用分析报表。"""
|
|
total = db.session.query(ChatLog).count()
|
|
by_agent = (
|
|
db.session.query(Agent.name, func.count(ChatLog.id))
|
|
.join(ChatLog)
|
|
.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)
|
|
.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,
|
|
'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)}
|