fix(admin): 优化管理控制台

This commit is contained in:
sophie committed 2026-07-15 08:51:32 +08:00
1 parent ea9a96b2fb
commit e8255f5943
8 files changed
+101 -18

No files matched your search

+31 -3
View File
@@ -30,6 +30,10 @@ APPLICATION_REPORT_SORT_KEYS = frozenset({
'tokens_used',
})
DEFAULT_APPLICATION_SORT = 'chat_count'
# 运营提醒:启用应用在范围内对话次数 ≤ 该阈值视为低使用(含零使用)
USAGE_LOW_AGENT_MAX_CHATS = 2
# 运营提醒:低使用应用最多返回条数
USAGE_LOW_AGENT_LIST_LIMIT = 5
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
USAGE_RANGE_DAYS = {
@@ -65,7 +69,8 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
"""
聊天使用分析报表(按应用 / 按用户),限定时间范围内的 ChatLog。
核心逻辑:按 Agent / User 聚合 ChatLog 次数;按用户统计同时返回 username 与 real_name。
核心逻辑:按 Agent / User 聚合 ChatLog 次数;按用户统计同时返回 username 与 real_name;
另对启用 Agent 左连接对话量,产出含零使用的低使用应用列表(与应用运营口径对齐)。
Args:
user_page: 按用户统计分页页码。
@@ -73,7 +78,7 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
range_key: 时间范围 key,见 USAGE_RANGE_DAYS。
Returns:
含 total / by_user(username、real_name、count)/ by_agent 及用户分页字段的字典。
含 total / by_user / by_agent / by_day / low_agents 及用户分页字段的字典。
"""
normalized_range, since = resolve_usage_range_start(range_key)
base_filter = ChatLog.created_at >= since
@@ -95,9 +100,29 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
.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 1] 按用户聚合对话量,一并选出真实姓名供管理端展示
# [STEP 3] 按用户聚合对话量,一并选出真实姓名供管理端展示
by_user_top = (
db.session.query(User.username, User.real_name, func.count(ChatLog.id))
.join(ChatLog)
@@ -121,6 +146,9 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
],
'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,
@@ -1,7 +1,7 @@
"""
tests/services/admin/test_report_service.py
用途:report_service 报表聚合单元测试(使用分析、应用运营、反馈)。
用途:report_service 报表聚合单元测试(使用分析含零使用低使用应用、应用运营、反馈)。
"""
from app import db
from app.models import Agent, ChatLog, Feedback, User
@@ -32,6 +32,37 @@ def test_build_usage_report(app):
assert data['by_day'][0]['count'] == 1
def test_build_usage_report_low_agents_includes_zero_usage(app):
"""
低使用应用须含启用且零对话的 Agent(与应用运营零使用对齐)。
断言:cold-app 出现在 low_agents 且 count=0;停用应用不计入。
"""
with app.app_context():
used = Agent(name='hot-app', type='api', dify_app_id='app-hot', dify_api_key='key-hot', is_active=True)
cold = Agent(name='cold-app', type='api', dify_app_id='app-cold', dify_api_key='key-cold', is_active=True)
inactive = Agent(
name='off-app',
type='api',
dify_app_id='app-off',
dify_api_key='key-off',
is_active=False,
)
user = User(username='low-user', email='low@example.com', role='user')
db.session.add_all([used, cold, inactive, user])
db.session.flush()
db.session.add(ChatLog(user_id=user.id, agent_id=used.id, query='hi', answer='ok', tokens_used=1))
db.session.commit()
data = report_service.build_usage_report(user_page=1, user_page_size=10, range_key='30d')
# by_agent 仅含有对话的应用
assert all(item['agent'] != 'cold-app' for item in data['by_agent'])
low_names = {item['agent']: item['count'] for item in data['low_agents']}
assert low_names.get('cold-app') == 0
assert 'off-app' not in low_names
assert data['low_agent_max_chats'] == report_service.USAGE_LOW_AGENT_MAX_CHATS
assert data['low_agent_list_limit'] == report_service.USAGE_LOW_AGENT_LIST_LIMIT
def test_build_usage_report_excludes_outside_range(app):
"""超出所选时间范围的聊天日志不计入统计。"""
from datetime import datetime, timedelta
@@ -2,7 +2,8 @@
* features/admin/modules/reports/composables/useReportsAdmin.ts
* 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除、使用分析与应用运营看板)。
* 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime、vue-router。
* 逻辑:ReportsPage 调用本 composable;使用分析按用户服务端分页、按应用前端分页,均复用 PaginationBar。
* 逻辑:ReportsPage 调用本 composable;使用分析按用户服务端分页、按应用前端分页,均复用 PaginationBar;
* 低使用应用优先消费后端 low_agents(含零使用启用应用),与应用运营口径对齐。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -252,9 +253,9 @@ export function useReportsAdmin() {
const usageUserTopLimit = computed(() => usageReport.value?.user_top_limit ?? 50);
const usageActiveAgentCount = computed(() => usageReport.value?.by_agent.length ?? 0);
const usageTrendMax = computed(() => Math.max(1, ...(usageReport.value?.by_day || []).map((item) => item.count)));
/** 低使用应用:范围内对话次数 ≤ 该阈值 */
/** 低使用应用:范围内对话次数 ≤ 该阈值(兜底;优先用后端返回值) */
const USAGE_LOW_AGENT_MAX_CHATS = 2;
/** 低使用应用提醒最多展示条数 */
/** 低使用应用提醒最多展示条数(兜底;优先用后端返回值) */
const USAGE_LOW_AGENT_LIST_LIMIT = 5;
/** 异常高峰:单日对话量下限(与日均倍数取较大者) */
const USAGE_SPIKE_DAY_MIN_CHATS = 5;
@@ -262,12 +263,26 @@ export function useReportsAdmin() {
const USAGE_SPIKE_DAY_AVG_MULTIPLIER = 2;
/** 异常高峰日期最多展示条数 */
const USAGE_SPIKE_DAY_LIST_LIMIT = 3;
const usageLowAgentItems = computed(() =>
[...(usageReport.value?.by_agent || [])]
.filter((item) => item.count <= USAGE_LOW_AGENT_MAX_CHATS)
.sort((a, b) => a.count - b.count || a.agent.localeCompare(b.agent))
.slice(0, USAGE_LOW_AGENT_LIST_LIMIT),
const usageLowAgentMaxChats = computed(
() => usageReport.value?.low_agent_max_chats ?? USAGE_LOW_AGENT_MAX_CHATS,
);
const usageLowAgentListLimit = computed(
() => usageReport.value?.low_agent_list_limit ?? USAGE_LOW_AGENT_LIST_LIMIT,
);
/**
* 低使用应用列表:优先用后端 low_agents(含零使用启用应用);
* 旧接口无该字段时回退到 by_agent 过滤(不含零使用)。
*/
const usageLowAgentItems = computed(() => {
const fromApi = usageReport.value?.low_agents;
if (Array.isArray(fromApi)) {
return fromApi;
}
return [...(usageReport.value?.by_agent || [])]
.filter((item) => item.count <= usageLowAgentMaxChats.value)
.sort((a, b) => a.count - b.count || a.agent.localeCompare(b.agent))
.slice(0, usageLowAgentListLimit.value);
});
const usageSpikeDayItems = computed(() => {
const days = usageReport.value?.by_day || [];
if (days.length === 0) return [];
@@ -1162,8 +1177,8 @@ watch([reportPageSize, sortedTableData], () => {
usageUserTopLimit,
usageActiveAgentCount,
usageTrendMax,
usageLowAgentMaxChats: USAGE_LOW_AGENT_MAX_CHATS,
usageLowAgentListLimit: USAGE_LOW_AGENT_LIST_LIMIT,
usageLowAgentMaxChats,
usageLowAgentListLimit,
usageSpikeDayMinChats: USAGE_SPIKE_DAY_MIN_CHATS,
usageSpikeDayAvgMultiplier: USAGE_SPIKE_DAY_AVG_MULTIPLIER,
usageSpikeDayListLimit: USAGE_SPIKE_DAY_LIST_LIMIT,
@@ -16,6 +16,15 @@ export interface UsageReport {
by_agent: { agent: string; count: number }[];
/** 当前范围内按自然日聚合的对话趋势,用于使用分析柱状图。 */
by_day?: { date: string; count: number }[];
/**
* 运营提醒:启用应用中范围内对话次数 ≤ low_agent_max_chats 的列表(含零使用)。
* 由后端以 Agent 主表左连接统计,与应用运营「零使用」口径对齐。
*/
low_agents?: { agent: string; count: number }[];
/** 低使用对话次数上限(后端常量) */
low_agent_max_chats?: number;
/** 低使用列表条数上限(后端常量) */
low_agent_list_limit?: number;
user_total: number;
user_page: number;
user_page_size: number;
+1 -1
View File
@@ -908,7 +908,7 @@
"usageTrendEmpty": "No trend data yet",
"usageInsights": "Operational alerts",
"usageLowAgents": "Low-usage apps",
"usageLowAgentsHint": "Apps with ≤ {max} chats in the selected range, sorted ascending, showing up to {limit}.",
"usageLowAgentsHint": "Enabled apps with ≤ {max} chats in the selected range (including zero), sorted ascending, up to {limit}.",
"usageLowAgentsHintAria": "Show low-usage app selection rule",
"usageLowAgentsEmpty": "No low-usage apps in this range",
"usageSpikeDays": "Spike days",
+1 -1
View File
@@ -892,7 +892,7 @@
"usageTrendEmpty": "ยังไม่มีข้อมูลแนวโน้ม",
"usageInsights": "การแจ้งเตือนการดำเนินงาน",
"usageLowAgents": "แอปที่ใช้น้อย",
"usageLowAgentsHint": "แอปที่มีแชท ≤ {max} ครั้งในช่วงที่เลือก เรียงจากน้อยไปมาก แสดงสูงสุด {limit} รายการ",
"usageLowAgentsHint": "แอปที่เปิดใช้และมีแชท ≤ {max} ครั้งในช่วงที่เลือก (รวมศูนย์ครั้ง) เรียงจากน้อยไปมาก แสดงสูงสุด {limit} รายการ",
"usageLowAgentsHintAria": "ดูเกณฑ์การคัดเลือกแอปที่ใช้น้อย",
"usageLowAgentsEmpty": "ไม่มีแอปที่ใช้น้อยในช่วงนี้",
"usageSpikeDays": "วันที่มีการใช้งานพุ่งสูง",
+1 -1
View File
@@ -888,7 +888,7 @@
"usageTrendEmpty": "暂无趋势数据",
"usageInsights": "运营提醒",
"usageLowAgents": "低使用应用",
"usageLowAgentsHint": "统计范围内对话次数 ≤ {max} 的应用,按对话量升序最多展示 {limit} 个。",
"usageLowAgentsHint": "启用应用中,统计范围内对话次数 ≤ {max}(含零使用),按对话量升序最多展示 {limit} 个。",
"usageLowAgentsHintAria": "查看低使用应用选取规则",
"usageLowAgentsEmpty": "当前范围内暂无低使用应用",
"usageSpikeDays": "异常高峰日期",
+1 -1
View File
@@ -892,7 +892,7 @@
"usageTrendEmpty": "暫無趨勢資料",
"usageInsights": "營運提醒",
"usageLowAgents": "低使用應用",
"usageLowAgentsHint": "統計範圍內對話次數 ≤ {max} 的應用,按對話量升序最多展示 {limit} 個。",
"usageLowAgentsHint": "啟用應用中,統計範圍內對話次數 ≤ {max}(含零使用),按對話量升序最多展示 {limit} 個。",
"usageLowAgentsHintAria": "查看低使用應用選取規則",
"usageLowAgentsEmpty": "目前範圍內暫無低使用應用",
"usageSpikeDays": "異常高峰日期",