Files

1428 lines
57 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
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
import re
from datetime import date, datetime, timedelta
from typing import Any
from sqlalchemy import asc, desc, func, or_
from app import db
from app.core.errors import NotFoundError
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, 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',
'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 hour_of_day_expr():
"""
构造按小时分桶的 SQL 表达式(值域 0-23),兼容 PostgreSQL 与 SQLite。
用途:使用分析「时段热力图」聚合。Postgres 用 extract(hour ...),SQLite 用 strftime。
Returns:
SQLAlchemy 表达式,供 group_by 使用。
"""
dialect = getattr(db.engine, 'dialect', None)
name = getattr(dialect, 'name', 'sqlite') if dialect is not None else 'sqlite'
if name == 'postgresql':
return func.cast(func.extract('hour', ChatLog.created_at), db.Integer)
return func.cast(func.strftime('%H', ChatLog.created_at), db.Integer)
def weekday_iso_expr():
"""
构造工作日索引 SQL 表达式(ISO:周一=0 .. 周日=6),兼容 PostgreSQL 与 SQLite。
用途:使用分析「工作日 x 时段热力图」纵轴聚合。
Returns:
SQLAlchemy 表达式,供 group_by 使用。
"""
dialect = getattr(db.engine, 'dialect', None)
name = getattr(dialect, 'name', 'sqlite') if dialect is not None else 'sqlite'
if name == 'postgresql':
# EXTRACT(DOW): 0=日 .. 6=六;转换为 ISO 0=一 .. 6=日
return (func.cast(func.extract('dow', ChatLog.created_at), db.Integer) + 6) % 7
# SQLite strftime('%w'): 0=日 .. 6=六
return (func.cast(func.strftime('%w', ChatLog.created_at), db.Integer) + 6) % 7
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 resolve_usage_period(
range_key: str | None,
start_date: str | None = None,
end_date: str | None = None,
) -> tuple[str, datetime, datetime | None]:
"""
解析报表统计范围:优先使用自定义起止日期(start_date/end_date,YYYY-MM-DD),否则回退 range key。
用途:运营总览 / 使用分析 / 应用运营统一由「年月日选择」驱动统计范围。
Args:
range_key: 预设范围 key(7d/30d/90d/...),仅当未提供自定义日期时生效。
start_date: 开始日期 YYYY-MM-DD(当天 00:00 起)。
end_date: 结束日期 YYYY-MM-DD(当天 23:59:59 止)。
Returns:
(normalized_key, since, until);until 为 None 表示不设上界(自定义日期下始终有值)。
"""
start_dt = _parse_datetime((start_date or '').strip(), end_of_day=False)
end_dt = _parse_datetime((end_date or '').strip(), end_of_day=True)
if start_dt is None and end_dt is None:
key, since = resolve_usage_range_start(range_key)
return key, since, None
if start_dt is None:
# 只给了结束日期:默认向前回溯一月
start_dt = end_dt - timedelta(days=30)
if end_dt is None:
# 只给了开始日期:默认统计至今
end_dt = datetime.utcnow()
return 'custom', start_dt, end_dt
def normalize_report_day(day: Any) -> str:
"""
将报表按日聚合的日期统一为 yyyy-mm-dd,避免未补零或带时间后缀导致前端横轴乱序。
核心逻辑:优先用 date/datetime.isoformat;字符串则截取并补零月日。
Args:
day: SQLAlchemy func.date 结果(date / datetime / str)。
Returns:
标准 yyyy-mm-dd 字符串。
"""
if isinstance(day, datetime):
return day.date().isoformat()
if isinstance(day, date):
return day.isoformat()
raw = str(day or '').strip()
if not raw:
return ''
# 兼容 "2026-7-1" / "2026-07-01 00:00:00"
head = raw.split(' ')[0].replace('/', '-')
parts = head.split('-')
if len(parts) >= 3:
try:
year, month, day_n = int(parts[0]), int(parts[1]), int(parts[2][:2])
return f'{year:04d}-{month:02d}-{day_n:02d}'
except ValueError:
return head[:10]
return head[:10]
def build_usage_report(
*,
user_page: int,
user_page_size: int,
range_key: str | None = None,
start_date: str | None = None,
end_date: 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(与 start_date/end_date 互斥,自定义日期优先)。
start_date: 自定义开始日期 YYYY-MM-DD。
end_date: 自定义结束日期 YYYY-MM-DD。
Returns:
含 total / by_user / by_agent / by_day / low_agents 及用户分页字段的字典。
"""
normalized_range, since, until = resolve_usage_period(range_key, start_date, end_date)
base_filter = ChatLog.created_at >= since
if until is not None:
base_filter = base_filter & (ChatLog.created_at <= until)
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 1.5] 人员/部门排行:按部门聚合对话量与去重用户数(人员统计按部门+姓名口径)
by_department = (
db.session.query(User.department, func.count(ChatLog.id), func.count(func.distinct(ChatLog.user_id)))
.join(User, User.id == ChatLog.user_id)
.filter(base_filter)
.group_by(User.department)
.order_by(desc(func.count(ChatLog.id)), User.department)
.all()
)
# [STEP 1.6] 工作日 x 时段热力图:横轴=小时,纵轴=工作日(周一..周五),格子颜色深浅=该日该时段对话量
weekday_col = weekday_iso_expr()
hour_col = hour_of_day_expr()
heat_rows = (
db.session.query(weekday_col.label('weekday'), hour_col.label('hour'), func.count(ChatLog.id))
.filter(base_filter)
.group_by(weekday_col, hour_col)
.all()
)
heat_map: dict[int, dict[int, int]] = {}
for wd, hr, cnt in heat_rows:
heat_map.setdefault(int(wd), {})[int(hr)] = int(cnt)
# 纵轴取一周 7 天(周一..周日,ISO 0..6)
workday_indices = list(range(7))
hours = list(range(24))
hour_heatmap = {
'weekdays': [wd + 1 for wd in workday_indices], # ISO 1=周一 .. 7=周日
'hours': hours,
'cells': [[heat_map.get(wd, {}).get(hr, 0) for hr in hours] for wd in workday_indices],
}
# [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': normalize_report_day(day), 'count': c} for day, c in by_day],
'by_department': [
{'department': dept or '', 'chat_count': int(cc), 'user_count': int(uc)}
for dept, cc, uc in by_department
],
'hour_heatmap': hour_heatmap,
'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,
start_date: str | None = None,
end_date: 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 统计授权人数;
Feedback JOIN ChatLog 统计均分;不含 API Key 等配置敏感字段。
Args:
range_key: 时间范围 key(7d/30d/90d/180d/365d),非法值回退近一月(自定义日期优先)。
start_date: 自定义开始日期 YYYY-MM-DD。
end_date: 自定义结束日期 YYYY-MM-DD。
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, until = resolve_usage_period(range_key, start_date, end_date)
period_filter = ChatLog.created_at >= since
if until is not None:
period_filter = period_filter & (ChatLog.created_at <= until)
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', 'unused_authorized'}:
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(period_filter)
.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()
)
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(period_filter)
.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)
tokens_col = func.coalesce(chat_stats.c.tokens_used, 0)
# [STEP 2] Agent 左连接各聚合(基础未过滤查询,用于稳定汇总卡)
base_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'),
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(feedback_stats, feedback_stats.c.agent_id == Agent.id)
)
# [STEP 3] 汇总卡不随应用筛选变化:始终基于全部应用计算(点击 1/2/3/4 不改变汇总统计)
base_rows = list(base_query.all())
summary_agent_total = len(base_rows)
summary_active = sum(1 for row in base_rows if row.is_active)
summary_used = sum(1 for row in base_rows if int(row.chat_count or 0) > 0)
summary_unused = summary_agent_total - summary_used
# 「已授权未使用」应用:已授权给用户但范围内无任何对话
summary_authorized_unused = sum(
1 for row in base_rows
if int(row.authorized_users or 0) > 0 and int(row.chat_count or 0) == 0
)
# [STEP 4] 列表查询:应用状态 / 使用 / 搜索筛选
filtered_query = base_query
if status_key == 'active':
filtered_query = filtered_query.filter(Agent.is_active.is_(True))
elif status_key == 'inactive':
filtered_query = filtered_query.filter(Agent.is_active.is_(False))
if usage_key == 'used':
filtered_query = filtered_query.filter(chat_count_col > 0)
elif usage_key == 'unused':
filtered_query = filtered_query.filter(or_(chat_stats.c.chat_count.is_(None), chat_stats.c.chat_count == 0))
elif usage_key == 'unused_authorized':
filtered_query = filtered_query.filter(
or_(chat_stats.c.chat_count.is_(None), chat_stats.c.chat_count == 0)
).filter(authorized_col > 0)
if keyword:
filtered_query = filtered_query.filter(Agent.name.ilike(f'%{keyword}%'))
filtered_rows = list(filtered_query.all())
agent_total = len(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', '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),
'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,
# 「已授权未使用」标识:已授权用户但范围内无对话
'authorized_unused': bool(int(row.authorized_users or 0) > 0 and int(row.chat_count or 0) == 0),
})
return {
'range': normalized_range,
'status': status_key,
'usage': usage_key,
'q': keyword,
'sort': sort_key,
'order': order_key,
'summary': {
'agent_total': summary_agent_total,
'active_agents': summary_active,
'used_agents': summary_used,
'unused_agents': summary_unused,
'authorized_unused_count': summary_authorized_unused,
},
'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', 'created_from', 'created_to'}
# 时间范围:意见反馈按提交时间(created_at)过滤(服务端,避免前端只滤已加载子集)
created_from = (query_params.get('created_from') or '').strip()
created_to = (query_params.get('created_to') or '').strip()
if created_from:
dt = _parse_datetime(created_from, end_of_day=False)
if dt:
query = query.filter(GeneralFeedback.created_at >= dt)
if created_to:
dt = _parse_datetime(created_to, end_of_day=True)
if dt:
query = query.filter(GeneralFeedback.created_at <= dt)
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 _apply_feedback_date_filter(query, query_params: dict[str, str]):
"""仅按 created_at 时间范围过滤通用反馈(供「最多反馈应用」等统计复用)。"""
created_from = (query_params.get('created_from') or '').strip()
created_to = (query_params.get('created_to') or '').strip()
if created_from:
dt = _parse_datetime(created_from, end_of_day=False)
if dt:
query = query.filter(GeneralFeedback.created_at >= dt)
if created_to:
dt = _parse_datetime(created_to, end_of_day=True)
if dt:
query = query.filter(GeneralFeedback.created_at <= dt)
return query
def build_feedback_summary(query_params: dict[str, str]) -> dict:
"""
用户反馈概览:待处理 / 本月已关闭 / 最多反馈应用(支撑三张概览卡)。
口径:
- 待处理:status == 'pending' 的反馈数(按当前识别条件)。
- 本月已关闭:status == 'closed' 且 closed_at 落在当前月(UTC)的反馈数。
- 最多反馈应用:通过 反馈→聊天日志→应用 关联,按应用名聚合取最多的一条;
无关联 chat_log 的反馈不计入应用归属。
Returns:
{'pending_count': int, 'closed_this_month': int, 'top_app': {'name': str, 'count': int}}
"""
# 待处理:应用当前筛选(时间范围/类型/来源页/模块等)
pending_base = _apply_general_feedback_filters(db.session.query(GeneralFeedback), query_params)
pending_count = int(pending_base.filter(GeneralFeedback.status == 'pending').count())
# 本月已关闭:按 closed_at 所在自然月(UTC),不随 created_at 日期筛选
month_start = datetime.utcnow().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
closed_this_month = int(
db.session.query(GeneralFeedback)
.filter(
GeneralFeedback.status == 'closed',
GeneralFeedback.closed_at >= month_start,
)
.count()
)
# 最多反馈应用
top_query = (
db.session.query(Agent.name.label('app'), func.count(GeneralFeedback.id).label('cnt'))
.join(ChatLog, ChatLog.id == GeneralFeedback.chat_log_id)
.join(Agent, Agent.id == ChatLog.agent_id)
.filter(GeneralFeedback.chat_log_id.isnot(None))
.group_by(Agent.name)
.order_by(desc(func.count(GeneralFeedback.id)))
)
top_query = _apply_feedback_date_filter(top_query, query_params)
top = top_query.first()
top_app = {'name': top.app or '未关联', 'count': int(top.cnt or 0)} if top else {'name': '未关联', 'count': 0}
return {
'pending_count': pending_count,
'closed_this_month': closed_this_month,
'top_app': top_app,
}
def mark_general_feedback_closed(feedback_id: int) -> dict:
""""把一条意见反馈标记为已关闭(status='closed', closed_at=now)。"""
feedback = db.session.get(GeneralFeedback, feedback_id)
if not feedback:
raise NotFoundError('feedback not found')
feedback.status = 'closed'
feedback.closed_at = datetime.utcnow()
db.session.commit()
return {'id': feedback_id, 'status': feedback.status, 'closed_at': feedback.closed_at.isoformat()}
# ───────────────────────── 聊天日志风险判定配置 ─────────────────────────
# 与产品规则/前端保持一致:透明分数规则用于判断哪些对话需要关注。
# - 空回答 或 系统失败:+3
# - 低评分(评分 <= LOW_SCORE_THRESHOLD):+3
# - 负面反馈(存在关联通用意见反馈):+2
# - 完全重复提问(同用户同提问出现 >= 2 次):+1
# - 总分 >= 3:需要关注;1-2:待人工抽查;0:已响应
CHAT_LOG_LOW_SCORE_THRESHOLD = 2
# 系统失败启发式:空回答 且 耗时 >= 该阈值(毫秒)判为系统失败(超时/链路异常)
CHAT_LOG_SYSTEM_FAILURE_LATENCY_MS = 30_000
# 完全重复提问:同用户同提问出现次数下限
CHAT_LOG_DUPLICATE_MIN_COUNT = 2
# 高频问题:同提问出现次数 >= 该值即视为高频(用于「优先人工复核」建议)
CHAT_LOG_HF_QUESTION_MIN_COUNT = 3
# 风险分数计算与排序的内存上限(避免一次拉取全表;风险状态过滤在内存内完成)
CHAT_LOG_RISK_SCAN_LIMIT = 5000
# 风险状态枚举(供前端展示/筛选)
CHAT_LOG_RISK_ATTENTION = 'attention' # 需要关注(>=3)
CHAT_LOG_RISK_REVIEW = 'review' # 待人工抽查(1-2)
CHAT_LOG_RISK_RESPONDED = 'responded' # 已响应(0)
# 问题分析:判定原因 → 建议检查项(仅提示方向,不代结论)
_CHAT_LOG_REASON_CHECK_MAP = {
'empty_answer': ('check_chain',), # 检查模型、接口、工具链路
'system_failure': ('check_chain',), # 检查模型、接口、工具链路
'low_score': ('check_answer',), # 人工抽查回答内容
'negative_feedback': ('check_kb',), # 检查知识库和资料有效期
'duplicate': ('check_key_info',), # 检查回答是否遗漏关键信息
}
def _parse_datetime(value: str | None, *, end_of_day: bool = False) -> datetime | None:
"""解析 YYYY-MM-DD(可带时间)为 datetime;end_of_day=True 时补 23:59:59.999999。"""
if not value:
return None
raw = str(value).strip()
if not raw:
return None
try:
if 'T' in raw or ' ' in raw:
dt = datetime.fromisoformat(raw.replace('Z', '+00:00'))
return dt.replace(tzinfo=None)
day = datetime.strptime(raw[:10], '%Y-%m-%d')
except ValueError:
return None
if end_of_day:
return day.replace(hour=23, minute=59, second=59, microsecond=999999)
return day
def _parse_int(value: str | None) -> int | None:
if value is None:
return None
raw = str(value).strip()
if not raw:
return None
try:
return int(raw)
except (TypeError, ValueError):
return None
def _query_bool(value: str | None) -> bool:
return str(value or '').strip().lower() in ('1', 'true', 'yes', 'on')
def _risk_status_from_score(score: int) -> str:
if score >= 3:
return CHAT_LOG_RISK_ATTENTION
if score >= 1:
return CHAT_LOG_RISK_REVIEW
return CHAT_LOG_RISK_RESPONDED
# 风险状态:前端列头/筛选中允许按本地化文案搜索,这里做 文案→枚举码 归一化(多语言兜底)
_RISK_STATUS_LABEL_TO_CODE = {
'attention': CHAT_LOG_RISK_ATTENTION,
'need': CHAT_LOG_RISK_ATTENTION,
'needs_attention': CHAT_LOG_RISK_ATTENTION,
'needs attention': CHAT_LOG_RISK_ATTENTION,
'\u9700\u8981\u5173\u6ce8': CHAT_LOG_RISK_ATTENTION,
'\u9700\u8981\u95dc\u6ce8': CHAT_LOG_RISK_ATTENTION,
'review': CHAT_LOG_RISK_REVIEW,
'pending_review': CHAT_LOG_RISK_REVIEW,
'pending manual review': CHAT_LOG_RISK_REVIEW,
'\u5f85\u4eba\u5de5\u62bd\u67e5': CHAT_LOG_RISK_REVIEW,
'\u5f85\u4eba\u5de5\u62bd\u67e5': CHAT_LOG_RISK_REVIEW,
'responded': CHAT_LOG_RISK_RESPONDED,
'\u5df2\u54cd\u5e94': CHAT_LOG_RISK_RESPONDED,
'\u5df2\u97ff\u61c9': CHAT_LOG_RISK_RESPONDED,
'responded ': CHAT_LOG_RISK_RESPONDED,
}
def _normalize_risk_status(value: str | None) -> str | None:
"""将用户输入的风险状态(码或本地化文案)归一化为枚举码;无法识别返回 None。"""
raw = str(value or '').strip()
if not raw:
return None
key = raw.lower().replace('-', '_').replace(' ', '_')
direct = _RISK_STATUS_LABEL_TO_CODE.get(raw) or _RISK_STATUS_LABEL_TO_CODE.get(key)
if direct:
return direct
# 兜底:若本身就是枚举码
if raw in (CHAT_LOG_RISK_ATTENTION, CHAT_LOG_RISK_REVIEW, CHAT_LOG_RISK_RESPONDED):
return raw
return None
def _chat_log_risk_metrics(
*,
answer: str | None,
latency: int | None,
feedback_score: int | None,
negative_feedback: bool,
duplicate: bool,
query: Any,
dup_count: int,
) -> dict:
"""计算单条聊天日志的风险分、风险状态、判定原因、建议检查项。"""
empty_answer = not (str(answer or '').strip())
system_failure = empty_answer and int(latency or 0) >= CHAT_LOG_SYSTEM_FAILURE_LATENCY_MS
low_score = feedback_score is not None and int(feedback_score) <= CHAT_LOG_LOW_SCORE_THRESHOLD
negative = bool(negative_feedback)
score = 0
reasons: list[str] = []
if empty_answer: # 空回答 或 系统失败 只计一次 +3(原因按系统失败优先)
score += 3
reasons.append('system_failure' if system_failure else 'empty_answer')
if low_score:
score += 3
reasons.append('low_score')
if negative:
score += 2
reasons.append('negative_feedback')
if duplicate:
score += 1
reasons.append('duplicate')
checks: list[str] = []
seen: set[str] = set()
for reason in reasons:
for check in _CHAT_LOG_REASON_CHECK_MAP.get(reason, ('check_answer',)):
if check not in seen:
seen.add(check)
checks.append(check)
# 高频问题 + 多条风险信号 → 优先人工复核该问题
if dup_count >= CHAT_LOG_HF_QUESTION_MIN_COUNT and len(reasons) >= 2:
if 'priority_review' not in seen:
seen.add('priority_review')
checks.append('priority_review')
return {
'risk_score': score,
'risk_status': _risk_status_from_score(score),
'risk_reasons': reasons,
'risk_checks': checks,
'is_empty_answer': empty_answer,
'is_system_failure': system_failure,
'is_duplicate': duplicate,
}
def chat_logs_report_query():
"""ChatLog JOIN User、Agent、Feedback(反馈唯一,左连接安全)。"""
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)
.outerjoin(Feedback, Feedback.chat_log_id == ChatLog.id)
)
def apply_chat_logs_report_filters(query, query_params: dict[str, str]):
"""对聊天日志报表查询应用筛选:基础列 + 时间范围/应用/用户 + 风险原始谓词。
注意:risk_status 需在风险分计算后再过滤(由 _scan_chat_log_risk_rows 负责)。
"""
reserved = {
'limit', 'offset', 'page', 'page_size', 'risk_status',
'min_score', 'max_score', 'is_empty_answer', 'is_system_failure',
'created_from', 'created_to', 'range',
}
# 统一时间范围(7d/30d/90d):与自定义日期互不冲突,取交集
range_key = (query_params.get('range') or '').strip()
if range_key:
_, since = resolve_usage_range_start(range_key)
query = query.filter(ChatLog.created_at >= since)
# 时间范围(自定义日期)
created_from = (query_params.get('created_from') or '').strip()
created_to = (query_params.get('created_to') or '').strip()
if created_from:
dt = _parse_datetime(created_from, end_of_day=False)
if dt:
query = query.filter(ChatLog.created_at >= dt)
if created_to:
dt = _parse_datetime(created_to, end_of_day=True)
if dt:
query = query.filter(ChatLog.created_at <= dt)
# 风险原始谓词(可直接下推的);"0/no" 表示取反
is_empty_raw = (query_params.get('is_empty_answer') or '').strip()
if is_empty_raw:
empty_expr = func.trim(func.coalesce(ChatLog.answer, '')) == ''
query = query.filter(empty_expr if _query_bool(is_empty_raw) else ~empty_expr)
is_fail_raw = (query_params.get('is_system_failure') or '').strip()
if is_fail_raw:
fail_expr = (func.trim(func.coalesce(ChatLog.answer, '')) == '') & (ChatLog.latency >= CHAT_LOG_SYSTEM_FAILURE_LATENCY_MS)
query = query.filter(fail_expr if _query_bool(is_fail_raw) else ~fail_expr)
min_score = _parse_int(query_params.get('min_score'))
max_score = _parse_int(query_params.get('max_score'))
if min_score is not None or max_score is not None:
# 评分区间只作用于「有评分记录」的聊天,避免未评分记录(NULL)被 coalesce 误伤或整表清空
query = query.filter(Feedback.score.isnot(None))
if min_score is not None:
query = query.filter(Feedback.score >= min_score)
if max_score is not None:
query = query.filter(Feedback.score <= max_score)
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 == 'id' and value.isdigit():
# 关联跳转落点:按聊天日志 ID 精确过滤,避免 ILIKE 误匹配(如 16 命中 160)
query = query.filter(ChatLog.id == int(value))
elif key == 'user_id' and value.isdigit():
query = query.filter(ChatLog.user_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 _scan_chat_log_risk_rows(query_params: dict[str, str]) -> list[dict]:
"""扫描聊天日志明细,计算风险分/状态/原因/检查项,并按 risk_status 过滤。
返回按 创建时间倒序 的风险结果(最多 CHAT_LOG_RISK_SCAN_LIMIT 条)。
"""
general_fb_count = (
db.session.query(func.count(GeneralFeedback.id))
.filter(GeneralFeedback.chat_log_id == ChatLog.id)
.correlate(ChatLog)
.scalar_subquery()
)
query = (
db.session.query(
ChatLog,
User.username.label('username'),
User.real_name.label('real_name'),
Agent.name.label('agent_name'),
Feedback.score.label('feedback_score'),
Feedback.comment.label('feedback_comment'),
general_fb_count.label('negative_feedback_count'),
)
.join(User, User.id == ChatLog.user_id)
.join(Agent, Agent.id == ChatLog.agent_id)
.outerjoin(Feedback, Feedback.chat_log_id == ChatLog.id)
)
query = apply_chat_logs_report_filters(query, query_params)
items = query.order_by(desc(ChatLog.created_at), desc(ChatLog.id)).limit(CHAT_LOG_RISK_SCAN_LIMIT).all()
# 提取风险分计算所需的原始列,避免在列表推导中重复取对象属性
raw_rows: list[dict] = []
for log, username, real_name, agent_name, feedback_score, feedback_comment, negative_feedback_count in items:
raw_rows.append({
'id': log.id,
'user_id': log.user_id,
'agent_id': log.agent_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,
'latency': log.latency,
'feedback_score': feedback_score,
'feedback_comment': feedback_comment,
'negative_feedback_count': int(negative_feedback_count or 0),
})
# 完全重复提问:同用户同提问(归一化后)出现次数 —— 用库级 GROUP BY,避免受扫描上限/分页影响
dup_counts: dict[tuple[int, str], int] = {}
dup_rows = (
db.session.query(
ChatLog.user_id,
func.lower(func.trim(ChatLog.query)).label('nq'),
func.count(ChatLog.id).label('cnt'),
)
.group_by(ChatLog.user_id, func.lower(func.trim(ChatLog.query)))
.having(func.count(ChatLog.id) >= CHAT_LOG_DUPLICATE_MIN_COUNT)
.all()
)
for uid, nq, cnt in dup_rows:
dup_counts[(int(uid or 0), str(nq or '').strip().lower())] = int(cnt)
risk_status_query = _normalize_risk_status(query_params.get('risk_status'))
# 风险分列表头筛选:支持精确值与区间("3" 或 "3-5")
risk_score_query = (query_params.get('risk_score') or '').strip()
risk_score_min: int | None = None
risk_score_max: int | None = None
if risk_score_query:
if '-' in risk_score_query:
lo, _, hi = risk_score_query.partition('-')
risk_score_min = _parse_int(lo or None)
risk_score_max = _parse_int(hi or None)
else:
risk_score_min = _parse_int(risk_score_query)
risk_score_max = _parse_int(risk_score_query)
enriched: list[dict] = []
for row in raw_rows:
key = (int(row['user_id'] or 0), str(row['query'] or '').strip().lower())
dup_count = dup_counts.get(key, 0)
duplicate = dup_count >= CHAT_LOG_DUPLICATE_MIN_COUNT
metrics = _chat_log_risk_metrics(
answer=row['answer'],
latency=row['latency'],
feedback_score=row['feedback_score'],
negative_feedback=bool(row['negative_feedback_count']),
duplicate=duplicate,
query=row['query'],
dup_count=dup_count,
)
row.update(metrics)
if risk_status_query and row['risk_status'] != risk_status_query:
continue
if risk_score_min is not None and row['risk_score'] < risk_score_min:
continue
if risk_score_max is not None and row['risk_score'] > risk_score_max:
continue
enriched.append(row)
return enriched
def serialize_chat_log_report_row(
log: ChatLog,
username: str | None,
real_name: str | None,
agent_name: str | None,
) -> dict:
"""ChatLog 报表行序列化(保留兼容;风险字段由 _scan_chat_log_risk_rows 提供)。"""
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 list_chat_logs_report(query_params: dict[str, str]) -> list[dict]:
"""聊天日志报表列表(含风险分/状态/原因/检查项,最多 100 条)。"""
rows = _scan_chat_log_risk_rows(query_params)
try:
limit = max(1, min(int(query_params.get('limit', 100)), 1000))
except (TypeError, ValueError):
limit = 100
return rows[:limit]
def count_chat_logs_report(query_params: dict[str, str]) -> dict:
"""聊天日志报表计数(按当前筛选与风险状态过滤后的条数)。"""
total = len(_scan_chat_log_risk_rows(query_params))
return {'table': 'chat_logs', 'total': int(total or 0)}
# ───────────────────────── 聊天日志 Top 提问/回答内容 ─────────────────────────
# 复用 FAQ 已有的问句归一化逻辑(normalize_faq_query)保证口径一致;
# 仅按「直接提问数据」统计,不做聚类(图1 的「演示聚类」已取消)。
CHAT_LOG_TOP_LIMIT_DEFAULT = 5
CHAT_LOG_TOP_SCAN_LIMIT = 2000
def _chat_log_top_scope(query_params: dict[str, str]):
"""构造 Top 统计的 ChatLog 查询:仅时间范围 + 应用 + 用户等识别条件,不套风险谓词。"""
query = db.session.query(ChatLog)
# 统一时间范围(7d/30d/90d)
range_key = (query_params.get('range') or '').strip()
if range_key:
_, since = resolve_usage_range_start(range_key)
query = query.filter(ChatLog.created_at >= since)
created_from = (query_params.get('created_from') or '').strip()
created_to = (query_params.get('created_to') or '').strip()
if created_from:
dt = _parse_datetime(created_from, end_of_day=False)
if dt:
query = query.filter(ChatLog.created_at >= dt)
if created_to:
dt = _parse_datetime(created_to, end_of_day=True)
if dt:
query = query.filter(ChatLog.created_at <= dt)
username = (query_params.get('username') or '').strip()
real_name = (query_params.get('real_name') or '').strip()
agent_name = (query_params.get('agent_name') or '').strip()
if username or real_name:
query = query.join(User, User.id == ChatLog.user_id)
if agent_name:
query = query.join(Agent, Agent.id == ChatLog.agent_id)
if username:
query = query.filter(User.username.cast(db.String).ilike(f'%{username}%'))
if real_name:
query = query.filter(User.real_name.cast(db.String).ilike(f'%{real_name}%'))
if agent_name:
query = query.filter(Agent.name.cast(db.String).ilike(f'%{agent_name}%'))
agent_id = (query_params.get('agent_id') or '').strip()
if agent_id.isdigit():
query = query.filter(ChatLog.agent_id == int(agent_id))
user_id = (query_params.get('user_id') or '').strip()
if user_id.isdigit():
query = query.filter(ChatLog.user_id == int(user_id))
return query
def build_chat_log_top_content(query_params: dict[str, str]) -> dict:
"""
聊天日志 Top 提问内容 / Top 回答内容(直接按 ChatLog 明细统计)。
核心逻辑:
- 提问:用 normalize_faq_query(去空白/标点/小写)归一化后按次数排序,取前 N。
代表性展示文本取最近一次原始提问,保证可读。
- 回答:按去除多余空白的原文聚合计数,取前 N。
Args:
query_params: 列筛选项(仅消费时间范围/应用/用户等识别条件)。
Returns:
{'questions': [{'label': str, 'count': int}], 'answers': [{'label': str, 'count': int}]}
"""
from app.services.faq_text_utils import normalize_faq_query
try:
limit = max(1, min(int(query_params.get('top_limit') or CHAT_LOG_TOP_LIMIT_DEFAULT), 20))
except (TypeError, ValueError):
limit = CHAT_LOG_TOP_LIMIT_DEFAULT
scope = (
_chat_log_top_scope(query_params)
.with_entities(ChatLog.query, ChatLog.answer)
.limit(CHAT_LOG_TOP_SCAN_LIMIT)
.all()
)
q_buckets: dict[str, dict] = {}
a_buckets: dict[str, int] = {}
for query, answer in scope:
if query:
nq = normalize_faq_query(query)
if nq:
bucket = q_buckets.setdefault(nq, {'count': 0, 'label': ''})
bucket['count'] += 1
bucket['label'] = str(query)
if answer:
na = re.sub(r'\s+', ' ', str(answer)).strip()
if na:
a_buckets[na] = a_buckets.get(na, 0) + 1
questions = sorted(q_buckets.values(), key=lambda x: (-x['count'], x['label']))[:limit]
answers = [
{'label': label, 'count': count}
for label, count in sorted(a_buckets.items(), key=lambda x: (-x[1], x[0]))[:limit]
]
return {'questions': questions, 'answers': answers}
def build_issue_analysis_report(query_params: dict[str, str], top_n: int = 10) -> dict:
"""
问题分析:基于聊天日志风险规则聚合高频问题簇,输出 KPI + 优先处理问题。
复用规则(与聊天日志一致):
- _scan_chat_log_risk_rows:每轮算 risk_score / risk_status(attention|review|responded) /
risk_reasons / risk_checks / is_empty_answer / is_system_failure。
- normalize_faq_query:问句归一化,聚合同一提问。
核心逻辑:把明细按归一化问句聚类,聚合出现次数/涉及应用/需要关注数/判定原因/建议检查项,
并按「需要关注数」优先排序取前 N。
Returns:
{'kpi': {...}, 'total_questions': int, 'questions': [...]}
"""
from app.services.faq_text_utils import normalize_faq_query
try:
top_n = max(1, min(int(top_n), 50))
except (TypeError, ValueError):
top_n = 10
rows = _scan_chat_log_risk_rows(query_params)
total = len(rows)
if total == 0:
empty_kpi = {
'high_freq_clusters': 0,
'attention_signals': 0,
'review_signals': 0,
'empty_answers': 0,
'top10_ratio': 0,
'top_risk_app': {'name': '未关联', 'signal_count': 0, 'attention_ratio': 0},
}
return {'kpi': empty_kpi, 'total_questions': 0, 'questions': []}
clusters: dict[str, dict] = {}
att_total = 0
review_total = 0
empty_total = 0
app_signals: dict[str, dict] = {}
for r in rows:
nq = normalize_faq_query(r['query'])
if not nq:
continue
c = clusters.setdefault(nq, {
'topic': '', 'count': 0, 'attention': 0,
'apps': set(), 'reasons': set(), 'checks': set(),
})
c['count'] += 1
c['topic'] = str(r['query'])
c['apps'].add(r.get('agent_name') or '未关联')
c['reasons'].update(r.get('risk_reasons') or [])
c['checks'].update(r.get('risk_checks') or [])
status = r.get('risk_status')
if status == 'attention':
c['attention'] += 1
att_total += 1
if status == 'review':
review_total += 1
if r.get('is_empty_answer'):
empty_total += 1
app = r.get('agent_name') or '未关联'
sig = app_signals.setdefault(app, {'signals': 0, 'attention': 0})
if (r.get('risk_score') or 0) > 0:
sig['signals'] += 1
if status == 'attention':
sig['attention'] += 1
# 高频问题簇:出现 >= 2 次的归一化问句组
high_freq_clusters = sum(1 for c in clusters.values() if c['count'] >= 2)
# Top 10 聚类占全部提问比例
top10 = sorted(clusters.values(), key=lambda x: -x['count'])[:10]
top10_sum = sum(x['count'] for x in top10)
top10_ratio = round(top10_sum / total * 100, 1) if total else 0
# 风险信号最多的应用(按需要关注数优先,其次信号数)
top_app_name, top_app = max(
app_signals.items(),
key=lambda kv: (kv[1]['attention'], kv[1]['signals']),
default=('未关联', {'signals': 0, 'attention': 0}),
)
att_ratio = round(top_app['attention'] / att_total * 100, 1) if att_total else 0
questions = [
{
'topic': c['topic'],
'count': c['count'],
'apps': '、'.join(sorted(c['apps'])),
'attention_count': c['attention'],
'reasons': sorted(c['reasons']),
'checks': sorted(c['checks']),
}
for c in clusters.values()
]
questions.sort(key=lambda x: (-x['attention_count'], -x['count']))
questions = questions[:top_n]
return {
'kpi': {
'high_freq_clusters': high_freq_clusters,
'attention_signals': att_total,
'review_signals': review_total,
'empty_answers': empty_total,
'top_risk_app': {
'name': top_app_name,
'signal_count': top_app['signals'],
'attention_ratio': att_ratio,
},
'top10_ratio': top10_ratio,
},
'total_questions': total,
'questions': questions,
}
def build_ops_overview_report(
range_key: str | None = None,
start_date: str | None = None,
end_date: str | None = None,
) -> dict:
"""
运营总览报表:聚合对话量 / 活跃用户 / 活跃应用 / 好评率 / 趋势环比 / Top 与低使用应用 / 低评分回答 / 未处理反馈。
核心逻辑:复用 chat_logs、feedbacks、general_feedbacks、agents、user_agent_permissions。
口径约定:
- 对话量按 ChatLog 记录数(一问一答 = 1 条)。
- 好评率 = 范围内评分 >=4 的 Feedback 数 / 范围内 Feedback 总数。
- 低评分回答 = 范围内评分 <=2 的 Feedback 数。
- 未处理反馈 = 范围内 GeneralFeedback 记录数(无处理状态字段,按「提交即待处理」口径)。
- 活跃应用 = 范围内有对话的 Agent 去重数;活跃用户 = 范围内去重用户数。
- 环比 = 当前范围对话量 vs 上等长周期对话量。
Args:
range_key: 时间范围 key(7d/30d/90d/180d/365d),非法值回退近一月(自定义日期优先)。
start_date: 自定义开始日期 YYYY-MM-DD。
end_date: 自定义结束日期 YYYY-MM-DD。
Returns:
含 kpi / trend / top_apps / low_use_apps 的字典。
"""
normalized_range, since, until = resolve_usage_period(range_key, start_date, end_date)
base_filter = ChatLog.created_at >= since
if until is not None:
base_filter = base_filter & (ChatLog.created_at <= until)
period_end = until or datetime.utcnow()
days = max(1, (period_end - since).days + 1)
prev_since = since - timedelta(days=days)
total_chats = db.session.query(ChatLog).filter(base_filter).count()
active_users = db.session.query(func.count(func.distinct(ChatLog.user_id))).filter(base_filter).scalar() or 0
active_agents = db.session.query(func.count(func.distinct(ChatLog.agent_id))).filter(base_filter).scalar() or 0
# [STEP 1 已移除] 好评率/低评分回答卡片已下线(保留 feedback_stats 用于应用运营均分)
# [STEP 2] 待跟进反馈:status=pending 的通用意见反馈数(与「用户反馈与回答评价」的待处理一致)
pending_feedback = db.session.query(GeneralFeedback).filter(GeneralFeedback.status == 'pending').count()
# [STEP 3] 环比:上等长周期对话量
prev_total = db.session.query(ChatLog).filter(
ChatLog.created_at >= prev_since,
ChatLog.created_at < since,
).count()
change_pct = round((total_chats - prev_total) / prev_total * 100, 1) if prev_total else None
# [STEP 4] 对话每日趋势
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 5] 聚合子查询:对话/授权/评分
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'),
)
.filter(base_filter)
.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()
)
feedback_stats = (
db.session.query(
ChatLog.agent_id.label('agent_id'),
func.avg(Feedback.score).label('avg_score'),
)
.join(Feedback, Feedback.chat_log_id == ChatLog.id)
.filter(base_filter)
.group_by(ChatLog.agent_id)
.subquery()
)
# [STEP 6] Top 应用(范围内有对话,按对话量降序取前 5)
top_apps_rows = (
db.session.query(
Agent.id,
Agent.name,
chat_stats.c.chat_count.label('chat_count'),
chat_stats.c.unique_users.label('unique_users'),
feedback_stats.c.avg_score.label('avg_score'),
)
.join(chat_stats, chat_stats.c.agent_id == Agent.id)
.outerjoin(feedback_stats, feedback_stats.c.agent_id == Agent.id)
.order_by(desc(chat_stats.c.chat_count), Agent.name)
.limit(5)
.all()
)
top_apps = [
{
'agent_id': row.id,
'name': row.name,
'chat_count': int(row.chat_count),
'unique_users': int(row.unique_users or 0),
'avg_score': round(float(row.avg_score), 2) if row.avg_score is not None else None,
}
for row in top_apps_rows
]
# [STEP 7] 低使用应用(启用应用按对话量升序取后 5,含零使用)
chat_count_col = func.coalesce(chat_stats.c.chat_count, 0)
authorized_col = func.coalesce(auth_stats.c.authorized_users, 0)
low_apps_rows = (
db.session.query(
Agent.id,
Agent.name,
chat_count_col.label('chat_count'),
authorized_col.label('authorized_users'),
)
.outerjoin(chat_stats, chat_stats.c.agent_id == Agent.id)
.outerjoin(auth_stats, auth_stats.c.agent_id == Agent.id)
.filter(Agent.is_active.is_(True))
.order_by(asc(chat_count_col), Agent.name)
.limit(5)
.all()
)
low_use_apps = [
{
'agent_id': row.id,
'name': row.name,
'chat_count': int(row.chat_count),
'authorized_users': int(row.authorized_users or 0),
}
for row in low_apps_rows
]
return {
'range': normalized_range,
'kpi': {
'total_chats': int(total_chats),
'active_users': int(active_users),
'active_agents': int(active_agents),
'pending_feedback': int(pending_feedback),
},
'trend': {
'by_day': [{'date': normalize_report_day(day), 'count': c} for day, c in by_day],
'total': int(total_chats),
'prev_total': int(prev_total),
'change_pct': change_pct,
'range_days': days,
},
'top_apps': top_apps,
'low_use_apps': low_use_apps,
}