fix(admin): 优化管理控制台报表显示

This commit is contained in:
sophie committed 2026-07-13 16:20:29 +08:00
1 parent 1ee4c69dee
commit b2fa2688a3
16 files changed
+1326 -157

No files matched your search

+30 -1
View File
@@ -3,7 +3,7 @@ backend/app/api/admin/reports.py
用途:管理后台报表 API(薄路由层)。 用途:管理后台报表 API(薄路由层)。
依赖:admin.blueprint、services/admin/report_service。 依赖:admin.blueprint、services/admin/report_service。
逻辑:/reports/* 路由。 逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
""" """
from flask import jsonify, request from flask import jsonify, request
@@ -38,6 +38,35 @@ def usage_report():
) )
@admin_bp.route('/reports/applications', methods=['GET'])
@require_admin
def applications_report():
"""
应用运营报表:按应用聚合使用 / 权限 / 评分。
Query: range, status, usage, q, sort, order, page, page_size。
"""
try:
page = int(request.args.get('page', 1))
except (TypeError, ValueError):
page = 1
try:
page_size = int(request.args.get('page_size', 20))
except (TypeError, ValueError):
page_size = 20
return jsonify(
report_service.build_application_report(
range_key=request.args.get('range'),
status=request.args.get('status'),
usage=request.args.get('usage'),
q=request.args.get('q'),
sort=request.args.get('sort'),
order=request.args.get('order'),
page=page,
page_size=page_size,
)
)
@admin_bp.route('/reports/feedback', methods=['GET']) @admin_bp.route('/reports/feedback', methods=['GET'])
@require_admin @require_admin
def feedback_report(): def feedback_report():
@@ -3,7 +3,7 @@ backend/app/services/admin/database_admin_service.py
用途:管理后台通用数据表浏览与 chat_logs 批量删除。 用途:管理后台通用数据表浏览与 chat_logs 批量删除。
依赖:models、report_service(chat_logs 报表复用)。 依赖:models、report_service(chat_logs 报表复用)。
逻辑:由 api/admin/database.py 调用。 逻辑:由 api/admin/database.py 调用;整型筛选字段对纯数字条件使用等值匹配。
""" """
from __future__ import annotations from __future__ import annotations
@@ -66,7 +66,12 @@ def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
for key, value in query_params.items(): for key, value in query_params.items():
if hasattr(model, key) and value: if hasattr(model, key) and value:
col = getattr(model, key) col = getattr(model, key)
query = query.filter(col.cast(db.String).ilike(f'%{value}%')) col_type = getattr(col, 'type', None)
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
query = query.filter(col == int(value))
else:
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
items = query.limit(100).all() items = query.limit(100).all()
return [_serialize_model_row(item) for item in items] return [_serialize_model_row(item) for item in items]
+236 -4
View File
@@ -1,8 +1,8 @@
""" """
backend/app/services/admin/report_service.py backend/app/services/admin/report_service.py
用途:管理后台报表(使用分析、反馈、聊天日志)数据聚合。 用途:管理后台报表(使用分析、应用运营、反馈、聊天日志)数据聚合。
依赖:models、SQLAlchemy func。 依赖:models、SQLAlchemy func、user_agent_permissions。
逻辑:由 api/admin/reports.py、database_admin_service 调用。 逻辑:由 api/admin/reports.py、database_admin_service 调用。
""" """
from __future__ import annotations from __future__ import annotations
@@ -11,12 +11,25 @@ import math
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Any from typing import Any
from sqlalchemy import desc, func from sqlalchemy import asc, desc, func, or_
from app import db from app import db
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User from app.models import Agent, ChatLog, Feedback, GeneralFeedback, PermissionRequest, User
from app.models.base import user_agent_permissions
USAGE_BY_USER_TOP_LIMIT = 50 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'
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致) # 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
USAGE_RANGE_DAYS = { USAGE_RANGE_DAYS = {
@@ -74,6 +87,14 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
.order_by(desc(func.count(ChatLog.id)), Agent.name) .order_by(desc(func.count(ChatLog.id)), Agent.name)
.all() .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()
)
user_page = max(1, user_page) user_page = max(1, user_page)
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT)) user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
# [STEP 1] 按用户聚合对话量,一并选出真实姓名供管理端展示 # [STEP 1] 按用户聚合对话量,一并选出真实姓名供管理端展示
@@ -99,6 +120,7 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
for u, rn, c in by_user_page for u, rn, c in by_user_page
], ],
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent], '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],
'user_total': user_total, 'user_total': user_total,
'user_page': user_page, 'user_page': user_page,
'user_page_size': user_page_size, 'user_page_size': user_page_size,
@@ -119,6 +141,214 @@ def build_feedback_report() -> dict:
} }
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)
)
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]): def _apply_general_feedback_filters(query, query_params: dict[str, str]):
reserved = {'limit', 'offset', 'page', 'page_size'} reserved = {'limit', 'offset', 'page', 'page_size'}
for key, value in query_params.items(): for key, value in query_params.items():
@@ -217,6 +447,8 @@ def apply_chat_logs_report_filters(query, query_params: dict[str, str]):
continue continue
if key == 'agent_name': if key == 'agent_name':
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%')) 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': elif key == 'username':
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%')) query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
elif key == 'real_name': elif key == 'real_name':
@@ -1,7 +1,7 @@
""" """
tests/services/admin/test_report_service.py tests/services/admin/test_report_service.py
用途:report_service 报表聚合单元测试。 用途:report_service 报表聚合单元测试(使用分析、应用运营、反馈)。
""" """
from app import db from app import db
from app.models import Agent, ChatLog, Feedback, User from app.models import Agent, ChatLog, Feedback, User
@@ -29,6 +29,7 @@ def test_build_usage_report(app):
assert data['by_user'][0]['username'] == 'report-user' assert data['by_user'][0]['username'] == 'report-user'
assert data['by_user'][0]['real_name'] == '报表用户' assert data['by_user'][0]['real_name'] == '报表用户'
assert data['by_agent'][0]['agent'] == 'report-agent' assert data['by_agent'][0]['agent'] == 'report-agent'
assert data['by_day'][0]['count'] == 1
def test_build_usage_report_excludes_outside_range(app): def test_build_usage_report_excludes_outside_range(app):
@@ -58,11 +59,66 @@ def test_build_usage_report_excludes_outside_range(app):
def test_build_feedback_report(app): def test_build_feedback_report(app):
with app.app_context(): with app.app_context():
db.session.add(Feedback(score=5)) agent = Agent(name='fb-agent', type='api', dify_app_id='app-fb', dify_api_key='key-fb')
db.session.add(Feedback(score=3)) user = User(username='fb-user', email='fb@example.com', role='user')
db.session.add_all([agent, user])
db.session.flush()
log1 = ChatLog(user_id=user.id, agent_id=agent.id, query='a', answer='b', tokens_used=1)
log2 = ChatLog(user_id=user.id, agent_id=agent.id, query='c', answer='d', tokens_used=1)
db.session.add_all([log1, log2])
db.session.flush()
db.session.add(Feedback(chat_log_id=log1.id, score=5))
db.session.add(Feedback(chat_log_id=log2.id, score=3))
db.session.commit() db.session.commit()
data = report_service.build_feedback_report() data = report_service.build_feedback_report()
assert data['total'] == 2 assert data['total'] == 2
assert data['avg_score'] == 4.0 assert data['avg_score'] == 4.0
assert len(data['distribution']) == 2 assert len(data['distribution']) == 2
def test_build_application_report(app):
"""应用运营报表应聚合对话 / 授权 / 待审 / 评分,且不含配置敏感字段。"""
from app.models import PermissionRequest
from app.models.base import user_agent_permissions
with app.app_context():
hot = Agent(name='hot-app', type='api', dify_app_id='app-hot', dify_api_key='secret-key', is_active=True)
cold = Agent(name='cold-app', type='api', dify_app_id='app-cold', dify_api_key='secret-key-2', is_active=True)
user = User(username='app-ops-user', email='app-ops@example.com', role='user', real_name='运营用户')
db.session.add_all([hot, cold, user])
db.session.flush()
log = ChatLog(user_id=user.id, agent_id=hot.id, query='hi', answer='ok', tokens_used=10, latency=1200)
db.session.add(log)
db.session.flush()
db.session.add(Feedback(chat_log_id=log.id, score=4))
db.session.execute(
user_agent_permissions.insert().values(user_id=user.id, agent_id=hot.id)
)
db.session.add(
PermissionRequest(user_id=user.id, agent_id=cold.id, reason='need', status='pending')
)
db.session.commit()
data = report_service.build_application_report(range_key='30d', sort='chat_count', order='desc')
assert data['range'] == '30d'
assert data['summary']['agent_total'] >= 2
assert data['summary']['used_agents'] >= 1
assert data['summary']['unused_agents'] >= 1
assert data['summary']['pending_permission_total'] >= 1
by_name = {item['name']: item for item in data['items']}
assert 'hot-app' in by_name
assert by_name['hot-app']['chat_count'] == 1
assert by_name['hot-app']['unique_users'] == 1
assert by_name['hot-app']['authorized_users'] == 1
assert by_name['hot-app']['avg_score'] == 4.0
assert by_name['cold-app']['chat_count'] == 0
assert by_name['cold-app']['pending_requests'] == 1
# 断言:导出字段不含 API Key
assert 'dify_api_key' not in by_name['hot-app']
assert 'api_base_url' not in by_name['hot-app']
unused = report_service.build_application_report(range_key='30d', usage='unused')
assert all(item['chat_count'] == 0 for item in unused['items'])
assert any(item['name'] == 'cold-app' for item in unused['items'])
+12 -3
View File
@@ -451,9 +451,18 @@
--- ---
## 7. 移动端适配功能清单 ## 7. 管理端功能清单
### 7.1 功能总览 | 功能项 | 说明 | 状态 | 优先级 |
| --- | --- | --- | --- |
| 管理端使用分析 | 管理控制台「数据报表」首项由原始用户表替换为「使用分析」,展示对话总量、活跃用户/应用、按日趋势、应用/用户排行、低使用应用与异常高峰提醒,并保留聊天明细追溯与导出 | 已实现 | P1 |
| 管理端应用运营报表 | 「数据报表 > 应用」由 agents 配置表替换为应用运营看板:按应用聚合对话/用户/最近活跃/授权/待审/均分,支持时间范围与状态筛选、Excel 导出,并可下钻聊天日志与权限申请 | 已实现 | P1 |
---
## 8. 移动端适配功能清单
### 8.1 功能总览
| 功能项 | 说明 | 状态 | 优先级 | | 功能项 | 说明 | 状态 | 优先级 |
| --- | --- | --- | --- | | --- | --- | --- | --- |
@@ -467,7 +476,7 @@
| 右上角个人设置按钮 | UserCircle 图标按钮,点击进入 /profile | 已完成 | P0 | | 右上角个人设置按钮 | UserCircle 图标按钮,点击进入 /profile | 已完成 | P0 |
| ProfileView 移动端返回 | 返回按钮手机端回 Chat,PC 端回 Workspace | 已完成 | P1 | | ProfileView 移动端返回 | 返回按钮手机端回 Chat,PC 端回 Workspace | 已完成 | P1 |
### 7.2 验收清单 ### 8.2 验收清单
- 手机竖屏访问时自动进入适配布局 - 手机竖屏访问时自动进入适配布局
- 未登录时正确显示登录页 - 未登录时正确显示登录页
+41 -1
View File
@@ -7,7 +7,14 @@ import { requestJson } from '@/shared/api/client';
import type { AdminUserRow } from '../types/admin.types'; import type { AdminUserRow } from '../types/admin.types';
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types'; import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
import type { PaginatedResult } from '@/shared/types/pagination.types'; import type { PaginatedResult } from '@/shared/types/pagination.types';
import type { UsageReport, UsageRangeKey } from '../types/report.types'; import type {
ApplicationReport,
ApplicationSortKey,
ApplicationStatusFilter,
ApplicationUsageFilter,
UsageReport,
UsageRangeKey,
} from '../types/report.types';
const auth = () => ({ headers: getAuthHeaders() }); const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } }); const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
@@ -275,6 +282,39 @@ export const getAdminUsageReport = (params: AdminUsageReportParams = {}) => {
auth(), auth(),
); );
}; };
export interface AdminApplicationReportParams {
range?: UsageRangeKey;
status?: ApplicationStatusFilter;
usage?: ApplicationUsageFilter;
q?: string;
sort?: ApplicationSortKey;
order?: 'asc' | 'desc';
page?: number;
page_size?: number;
}
/**
* 拉取应用运营报表(按应用聚合使用 / 权限 / 评分)。
* @param params - 时间范围、状态、使用筛选、搜索与排序分页
*/
export const getAdminApplicationReport = (params: AdminApplicationReportParams = {}) => {
const qs = new URLSearchParams();
if (params.range) qs.set('range', params.range);
if (params.status && params.status !== 'all') qs.set('status', params.status);
if (params.usage && params.usage !== 'all') qs.set('usage', params.usage);
if (params.q?.trim()) qs.set('q', params.q.trim());
if (params.sort) qs.set('sort', params.sort);
if (params.order) qs.set('order', params.order);
if (params.page != null) qs.set('page', String(params.page));
if (params.page_size != null) qs.set('page_size', String(params.page_size));
const query = qs.toString();
return requestJson<ApplicationReport>(
`/api/admin/reports/applications${query ? `?${query}` : ''}`,
auth(),
);
};
export const getAdminFeedbackReport = () => requestJson<any>('/api/admin/reports/feedback', auth()); export const getAdminFeedbackReport = () => requestJson<any>('/api/admin/reports/feedback', auth());
export const getAdminReportTable = (url: string) => requestJson<any[]>(url, auth()); export const getAdminReportTable = (url: string) => requestJson<any[]>(url, auth());
export const getAdminReportTableCount = (url: string) => requestJson<{ total: number }>(url, auth()); export const getAdminReportTableCount = (url: string) => requestJson<{ total: number }>(url, auth());
@@ -35,9 +35,9 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
]; ];
export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [ export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [
'users', 'usage_analysis',
'agents',
'chat_logs', 'chat_logs',
'agents',
'permission_requests', 'permission_requests',
'general_feedbacks', 'general_feedbacks',
'feedbacks', 'feedbacks',
@@ -1,14 +1,16 @@
/** /**
* features/admin/modules/reports/ReportsPage.vue * features/admin/modules/reports/ReportsPage.vue
* 用途:管理后台报表独立页面(多表浏览、列筛选、聊天日志批量操作)。 * 用途:管理后台报表独立页面(使用分析、应用运营、多表浏览与聊天日志批量操作)。
* 依赖:useReportsAdmin、DeleteConfirmDialog。 * 依赖:useReportsAdmin、DeleteConfirmDialog、lucide 图标。
* 逻辑:路由 /admin/reports/:table?;列宽由 composable 默认值与本地偏好控制。 * 逻辑:路由 /admin/reports/:table?;agents 表渲染应用运营看板而非配置 dump。
*/ */
<script setup lang="ts"> <script setup lang="ts">
import { onMounted } from 'vue'; import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { BarChart2, Download, Settings2 } from 'lucide-vue-next'; import { Activity, AlertTriangle, BarChart2, Download, LineChart, Settings2, Trophy } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue'; import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import type { ApplicationSortKey } from '@/features/admin/types/report.types';
import { useReportsAdmin } from './composables/useReportsAdmin'; import { useReportsAdmin } from './composables/useReportsAdmin';
const { t } = useI18n(); const { t } = useI18n();
@@ -31,16 +33,34 @@ const {
usageReport, usageReport,
usageRange, usageRange,
usageRangeOptions, usageRangeOptions,
usageUserPage,
usageUserPageSize,
usageUserPageSizeOptions,
usageUserTotal, usageUserTotal,
usageUserTotalPages,
usageUserTopLimit, usageUserTopLimit,
usageUserPageButtons, usageActiveAgentCount,
goToUsageUserPage, usageTrendMax,
prevUsageUserPage, usageLowAgentItems,
nextUsageUserPage, usageSpikeDayItems,
usageTopUserItems,
usageTopAgentItems,
applicationRange,
applicationStatus,
applicationUsage,
applicationQuery,
applicationPage,
applicationPageSize,
applicationPageSizeOptions,
applicationSummary,
applicationItems,
applicationTotal,
applicationTotalPages,
applicationPageButtons,
goToApplicationPage,
prevApplicationPage,
nextApplicationPage,
onApplicationSortClick,
getApplicationSortMark,
handleApplicationSearchChange,
openApplicationChatLogs,
openApplicationPermissionRequests,
isLoading, isLoading,
currentTable, currentTable,
tableData, tableData,
@@ -58,6 +78,8 @@ const {
reportPageSizeOptions, reportPageSizeOptions,
chatLogsColumns, chatLogsColumns,
chatLogsSortRules, chatLogsSortRules,
isUsageAnalysisTable,
isApplicationOpsTable,
isChatLogsTable, isChatLogsTable,
showReportTable, showReportTable,
visibleReportKeys, visibleReportKeys,
@@ -99,6 +121,68 @@ const {
confirmDelete, confirmDelete,
} = useReportsAdmin(); } = useReportsAdmin();
/** 应用运营可点击排序的列 */
const applicationSortableKeys: ApplicationSortKey[] = [
'name',
'chat_count',
'unique_users',
'last_active_at',
'authorized_users',
'pending_requests',
'avg_score',
];
/** 数值类列右对齐,避免表头与数字看起来错位 */
const applicationNumericKeys = new Set<ApplicationSortKey>([
'chat_count',
'unique_users',
'authorized_users',
'pending_requests',
'avg_score',
'last_active_at',
]);
/**
* 判断应用运营列是否按数值样式右对齐。
* @param key - 列字段
*/
function isApplicationNumericKey(key: ApplicationSortKey): boolean {
return applicationNumericKeys.has(key);
}
/**
* 点击摘要卡快速切换「有使用 / 零使用」筛选。
* @param usage - used | unused | all
*/
function setApplicationUsageFilter(usage: 'all' | 'used' | 'unused'): void {
applicationUsage.value = usage;
}
/**
* 计算使用趋势柱状条高度,避免低数据量时图表完全不可见。
* 核心逻辑:按当前范围最大日对话量归一化,最小保留 12% 高度用于视觉识别。
* @param count - 单日对话量
* @returns CSS height 百分比
*/
function getUsageTrendBarHeight(count: number): string {
const ratio = Math.max(0.12, count / usageTrendMax.value);
return `${Math.round(ratio * 100)}%`;
}
/**
* 格式化趋势日期标签,供紧凑柱状图展示。
* 核心逻辑:保留月日,避免长日期挤压图表横向空间。
* @param date - 后端返回的 yyyy-mm-dd 日期
* @returns 月/日短标签
*/
function formatUsageDayLabel(date: string): string {
const parts = String(date).split('-');
if (parts.length >= 3) {
return `${Number(parts[1])}/${Number(parts[2])}`;
}
return date;
}
onMounted(() => { onMounted(() => {
void loadAll(); void loadAll();
}); });
@@ -130,13 +214,17 @@ onMounted(() => {
<span v-if="isChatLogsTable" class="admin-report-badge admin-report-badge--info font-semibold"> <span v-if="isChatLogsTable" class="admin-report-badge admin-report-badge--info font-semibold">
{{ t('admin.report.totalRows', { total: chatLogsTotal }) }} {{ t('admin.report.totalRows', { total: chatLogsTotal }) }}
</span> </span>
<span class="admin-report-badge admin-report-badge--indigo font-semibold"> <span v-if="isApplicationOpsTable" class="admin-report-badge admin-report-badge--info font-semibold">
{{ t('admin.report.totalRows', { total: applicationTotal }) }}
</span>
<span v-if="!isApplicationOpsTable" class="admin-report-badge admin-report-badge--indigo font-semibold">
{{ t('admin.report.showingRange', { start: reportRangeStart, end: reportRangeEnd, total: reportTotalRows }) }} {{ t('admin.report.showingRange', { start: reportRangeStart, end: reportRangeEnd, total: reportTotalRows }) }}
</span> </span>
</div> </div>
</div> </div>
<div class="flex flex-wrap items-center gap-2 md:gap-3"> <div class="flex flex-wrap items-center gap-2 md:gap-3">
<button <button
v-if="!isApplicationOpsTable"
@click="showChatLogsColumnPanel = !showChatLogsColumnPanel" @click="showChatLogsColumnPanel = !showChatLogsColumnPanel"
class="btn-secondary text-sm font-semibold" class="btn-secondary text-sm font-semibold"
:title="t('admin.report.columnSettings')" :title="t('admin.report.columnSettings')"
@@ -180,8 +268,298 @@ onMounted(() => {
</div> </div>
<div class="p-5 md:p-8 space-y-5"> <div class="p-5 md:p-8 space-y-5">
<div v-if="isUsageAnalysisTable && usageReport" class="space-y-5">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h3 class="section-title text-lg">{{ t('admin.report.usage') }}</h3>
<p class="mt-1 text-sm text-secondary">{{ t('admin.report.usageIntro') }}</p>
</div>
<label class="flex items-center gap-2 text-sm text-secondary">
<span class="whitespace-nowrap">{{ t('admin.report.usageRangeLabel') }}</span>
<select v-model="usageRange" class="admin-table-filter-input min-w-[8rem]">
<option v-for="key in usageRangeOptions" :key="key" :value="key">
{{ t(`admin.report.usageRanges.${key}`) }}
</option>
</select>
</label>
</div>
<div class="grid grid-cols-1 gap-3 md:grid-cols-3">
<div class="rounded-xl border border-default bg-surface p-4">
<div class="flex items-center justify-between">
<span class="text-sm text-muted">{{ t('admin.report.usageTotalSessions') }}</span>
<Activity class="h-4 w-4 text-brand-600" />
</div>
<div class="mt-3 text-2xl font-bold text-primary">{{ usageReport.total }}</div>
</div>
<div class="rounded-xl border border-default bg-surface p-4">
<div class="flex items-center justify-between">
<span class="text-sm text-muted">{{ t('admin.report.usageActiveUsers') }}</span>
<Trophy class="h-4 w-4 text-emerald-600" />
</div>
<div class="mt-3 text-2xl font-bold text-primary">{{ usageUserTotal }}</div>
<div class="mt-1 text-xs text-muted">{{ t('admin.report.usageByUserTopHint', { limit: usageUserTopLimit }) }}</div>
</div>
<div class="rounded-xl border border-default bg-surface p-4">
<div class="flex items-center justify-between">
<span class="text-sm text-muted">{{ t('admin.report.usageActiveAgents') }}</span>
<BarChart2 class="h-4 w-4 text-sky-600" />
</div>
<div class="mt-3 text-2xl font-bold text-primary">{{ usageActiveAgentCount }}</div>
</div>
</div>
<div class="grid grid-cols-1 gap-5 xl:grid-cols-3">
<div class="rounded-xl border border-default bg-surface p-5 xl:col-span-2">
<div class="mb-4 flex items-center justify-between">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.usageTrend') }}</h4>
<LineChart class="h-4 w-4 text-brand-600" />
</div>
<div v-if="usageReport.by_day?.length" class="flex h-44 items-end gap-2 border-b border-subtle pb-3">
<div
v-for="day in usageReport.by_day"
:key="day.date"
class="flex min-w-7 flex-1 flex-col items-center justify-end gap-2"
:title="`${day.date}: ${day.count}`"
>
<div class="w-full max-w-8 rounded-t bg-brand-500/80" :style="{ height: getUsageTrendBarHeight(day.count) }" />
<span class="text-[10px] text-muted">{{ formatUsageDayLabel(day.date) }}</span>
</div>
</div>
<div v-else class="py-14 text-center text-sm text-muted">{{ t('admin.report.usageTrendEmpty') }}</div>
</div>
<div class="rounded-xl border border-default bg-surface p-5">
<div class="mb-4 flex items-center justify-between">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.usageInsights') }}</h4>
<AlertTriangle class="h-4 w-4 text-amber-600" />
</div>
<div class="space-y-3">
<div class="rounded-lg bg-surface-soft p-3">
<div class="text-xs font-semibold text-secondary">{{ t('admin.report.usageLowAgents') }}</div>
<div v-if="usageLowAgentItems.length" class="mt-2 space-y-2">
<div v-for="item in usageLowAgentItems" :key="item.agent" class="flex items-center justify-between gap-3 text-sm">
<span class="truncate text-secondary" :title="item.agent">{{ item.agent }}</span>
<span class="admin-report-badge">{{ item.count }}</span>
</div>
</div>
<div v-else class="mt-2 text-xs text-muted">{{ t('admin.report.usageLowAgentsEmpty') }}</div>
</div>
<div class="rounded-lg bg-surface-soft p-3">
<div class="text-xs font-semibold text-secondary">{{ t('admin.report.usageSpikeDays') }}</div>
<div v-if="usageSpikeDayItems.length" class="mt-2 space-y-2">
<div v-for="item in usageSpikeDayItems" :key="item.date" class="flex items-center justify-between gap-3 text-sm">
<span class="text-secondary">{{ item.date }}</span>
<span class="admin-report-badge admin-report-badge--info">{{ item.count }}</span>
</div>
</div>
<div v-else class="mt-2 text-xs text-muted">{{ t('admin.report.usageSpikeDaysEmpty') }}</div>
</div>
</div>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<div class="rounded-xl border border-default bg-surface p-5">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byAgent') }}</h4>
<div class="space-y-3">
<div v-for="a in usageTopAgentItems" :key="a.agent" class="flex items-center justify-between p-3 bg-surface-soft rounded-lg">
<span class="font-medium text-secondary truncate" :title="a.agent">{{ a.agent }}</span>
<span class="admin-report-badge admin-report-badge--info font-bold">{{ a.count }}</span>
</div>
<div v-if="usageTopAgentItems.length === 0" class="text-center text-muted text-sm py-6">
{{ t('admin.report.usageByAgentEmpty') }}
</div>
</div>
</div>
<div class="rounded-xl border border-default bg-surface p-5 flex flex-col">
<div class="mb-4">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.byUser') }}</h4>
<p class="mt-1 text-xs text-muted">{{ t('admin.report.usageActiveUserHint') }}</p>
</div>
<div class="space-y-3 flex-1">
<div v-for="u in usageTopUserItems" :key="u.username" class="flex items-center justify-between gap-3 p-3 bg-surface-soft rounded-lg">
<span class="font-medium text-secondary truncate" :title="formatUsageUserLabel(u)">{{ formatUsageUserLabel(u) }}</span>
<span class="admin-report-badge admin-report-badge--info font-bold shrink-0">{{ u.count }}</span>
</div>
<div v-if="usageTopUserItems.length === 0" class="text-center text-muted text-sm py-6">
{{ t('admin.report.usageByUserEmpty') }}
</div>
</div>
</div>
</div>
</div>
<div v-if="isApplicationOpsTable" class="space-y-5">
<div class="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
<div>
<h3 class="section-title text-lg">{{ t('admin.report.appOps.title') }}</h3>
<p class="mt-1 text-sm text-secondary">{{ t('admin.report.appOps.intro') }}</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<label class="flex items-center gap-2 text-sm text-secondary">
<span class="whitespace-nowrap">{{ t('admin.report.usageRangeLabel') }}</span>
<select v-model="applicationRange" class="admin-table-filter-input min-w-[8rem]">
<option v-for="key in usageRangeOptions" :key="`app-range-${key}`" :value="key">
{{ t(`admin.report.usageRanges.${key}`) }}
</option>
</select>
</label>
<label class="flex items-center gap-2 text-sm text-secondary">
<span class="whitespace-nowrap">{{ t('admin.report.appOps.statusLabel') }}</span>
<select v-model="applicationStatus" class="admin-table-filter-input min-w-[7rem]">
<option value="all">{{ t('admin.report.appOps.statusAll') }}</option>
<option value="active">{{ t('admin.report.appOps.statusActive') }}</option>
<option value="inactive">{{ t('admin.report.appOps.statusInactive') }}</option>
</select>
</label>
<label class="flex items-center gap-2 text-sm text-secondary">
<span class="whitespace-nowrap">{{ t('admin.report.appOps.usageLabel') }}</span>
<select v-model="applicationUsage" class="admin-table-filter-input min-w-[7rem]">
<option value="all">{{ t('admin.report.appOps.usageAll') }}</option>
<option value="used">{{ t('admin.report.appOps.usageUsed') }}</option>
<option value="unused">{{ t('admin.report.appOps.usageUnused') }}</option>
</select>
</label>
<input
v-model="applicationQuery"
type="search"
class="admin-table-filter-input min-w-[10rem]"
:placeholder="t('admin.report.appOps.searchPlaceholder')"
@input="handleApplicationSearchChange"
/>
</div>
</div>
<div v-if="applicationSummary" class="grid grid-cols-2 gap-3 md:grid-cols-4">
<button type="button" class="rounded-xl border border-default bg-surface p-4 text-left" @click="setApplicationUsageFilter('all')">
<div class="text-sm text-muted">{{ t('admin.report.appOps.summaryActive') }}</div>
<div class="mt-2 text-2xl font-bold text-primary">{{ applicationSummary.active_agents }}</div>
<div class="mt-1 text-xs text-muted">{{ t('admin.report.appOps.summaryTotal', { total: applicationSummary.agent_total }) }}</div>
</button>
<button type="button" class="rounded-xl border border-default bg-surface p-4 text-left" @click="setApplicationUsageFilter('used')">
<div class="text-sm text-muted">{{ t('admin.report.appOps.summaryUsed') }}</div>
<div class="mt-2 text-2xl font-bold text-primary">{{ applicationSummary.used_agents }}</div>
</button>
<button type="button" class="rounded-xl border border-default bg-surface p-4 text-left" @click="setApplicationUsageFilter('unused')">
<div class="text-sm text-muted">{{ t('admin.report.appOps.summaryUnused') }}</div>
<div class="mt-2 text-2xl font-bold text-primary">{{ applicationSummary.unused_agents }}</div>
</button>
<div class="rounded-xl border border-default bg-surface p-4">
<div class="text-sm text-muted">{{ t('admin.report.appOps.summaryPending') }}</div>
<div class="mt-2 text-2xl font-bold text-primary">{{ applicationSummary.pending_permission_total }}</div>
</div>
</div>
<div class="admin-report-table-wrap">
<table class="admin-report-table admin-report-table--app-ops w-full border-collapse">
<thead>
<tr>
<th
v-for="key in applicationSortableKeys"
:key="`app-h-${key}`"
class="px-3 py-3 whitespace-nowrap"
:class="isApplicationNumericKey(key) ? 'text-right' : 'text-left'"
>
<button
type="button"
class="admin-report-app-ops-sort-btn"
:class="isApplicationNumericKey(key) ? 'justify-end' : 'justify-start'"
@click="onApplicationSortClick(key)"
>
<span>{{ t(`admin.report.appOps.columns.${key}`) }}</span>
<span class="admin-report-app-ops-sort-mark" aria-hidden="true">{{ getApplicationSortMark(key) || ' ' }}</span>
</button>
</th>
<th class="px-3 py-3 whitespace-nowrap text-left">{{ t('admin.report.appOps.columns.category') }}</th>
<th class="px-3 py-3 whitespace-nowrap text-left">{{ t('admin.report.appOps.columns.is_active') }}</th>
<th class="px-3 py-3 whitespace-nowrap text-left">{{ t('admin.report.appOps.columns.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="applicationItems.length === 0">
<td colspan="10" class="text-center text-muted py-12">
{{ t('admin.report.appOps.empty') }}
</td>
</tr>
<tr v-for="row in applicationItems" :key="row.agent_id">
<td class="px-3 py-3 font-medium text-secondary truncate max-w-[12rem]" :title="row.name">{{ row.name }}</td>
<td class="px-3 py-3 font-mono text-right tabular-nums">{{ row.chat_count }}</td>
<td class="px-3 py-3 font-mono text-right tabular-nums">{{ row.unique_users }}</td>
<td class="px-3 py-3 font-mono text-xs text-right whitespace-nowrap">
{{ row.last_active_at ? formatLocalDateTime(row.last_active_at) : '-' }}
</td>
<td class="px-3 py-3 font-mono text-right tabular-nums">{{ row.authorized_users }}</td>
<td class="px-3 py-3 font-mono text-right tabular-nums">{{ row.pending_requests }}</td>
<td class="px-3 py-3 font-mono text-right tabular-nums whitespace-nowrap">
{{ row.avg_score == null ? '-' : row.avg_score }}
<span v-if="row.feedback_count" class="text-xs text-muted">({{ row.feedback_count }})</span>
</td>
<td class="px-3 py-3 text-secondary">{{ row.category || '-' }}</td>
<td class="px-3 py-3">
<span class="admin-report-badge" :class="row.is_active ? 'admin-report-badge--info' : ''">
{{ row.is_active ? t('admin.report.appOps.statusActive') : t('admin.report.appOps.statusInactive') }}
</span>
</td>
<td class="px-3 py-3">
<div class="flex flex-wrap gap-1">
<button type="button" class="btn-secondary text-xs px-2 py-1" @click="openApplicationChatLogs(row)">
{{ t('admin.report.appOps.actionLogs') }}
</button>
<button type="button" class="btn-secondary text-xs px-2 py-1" @click="openApplicationPermissionRequests(row)">
{{ t('admin.report.appOps.actionRequests') }}
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="flex flex-col gap-3 rounded-2xl border border-default bg-surface px-4 py-3 md:flex-row md:items-center md:justify-between">
<div class="text-sm text-secondary">
{{ t('admin.report.paginationSummary', { total: applicationTotal, page: applicationPage, pages: applicationTotalPages }) }}
</div>
<div class="flex flex-wrap items-center gap-2">
<label class="flex items-center gap-2 text-xs text-secondary">
<span>{{ t('admin.report.perPage') }}</span>
<select v-model.number="applicationPageSize" class="admin-table-filter-input appearance-none pl-2 pr-7 py-1 text-xs leading-5">
<option v-for="size in applicationPageSizeOptions" :key="`app-size-${size}`" :value="size">{{ size }}</option>
</select>
<span>{{ t('admin.report.itemsUnit') }}</span>
</label>
<button type="button" class="admin-report-page-btn" :disabled="applicationPage <= 1" @click="prevApplicationPage">
{{ t('admin.report.prevPage') }}
</button>
<button
v-for="btn in applicationPageButtons"
:key="`app-page-${btn}`"
type="button"
class="admin-report-page-btn"
:disabled="btn === -1"
:class="btn === -1
? 'border-transparent text-muted cursor-default opacity-100'
: btn === applicationPage
? 'admin-report-page-btn--active'
: ''"
@click="btn !== -1 && goToApplicationPage(btn)"
>
{{ btn === -1 ? '...' : btn }}
</button>
<button
type="button"
class="admin-report-page-btn"
:disabled="applicationPage >= applicationTotalPages"
@click="nextApplicationPage"
>
{{ t('admin.report.nextPage') }}
</button>
</div>
</div>
</div>
<div <div
v-if="showChatLogsColumnPanel" v-if="showChatLogsColumnPanel && !isApplicationOpsTable"
class="admin-report-panel" class="admin-report-panel"
> >
<div class="flex items-center justify-between mb-3"> <div class="flex items-center justify-between mb-3">
@@ -259,7 +637,7 @@ onMounted(() => {
</div> </div>
</div> </div>
<div v-if="!showReportTable" class="text-center text-muted py-20 bg-surface-soft rounded-2xl border border-dashed border-default"> <div v-if="!showReportTable && !isUsageAnalysisTable && !isApplicationOpsTable" class="text-center text-muted py-20 bg-surface-soft rounded-2xl border border-dashed border-default">
<p>{{ t('admin.report.noData', { table: getReportTableLabel(currentTable) }) }}</p> <p>{{ t('admin.report.noData', { table: getReportTableLabel(currentTable) }) }}</p>
</div> </div>
@@ -391,97 +769,6 @@ onMounted(() => {
</button> </button>
</div> </div>
</div> </div>
<!-- Statistics Charts -->
<div v-if="currentTable === 'chat_logs' && usageReport" class="mt-10 border-t border-default pt-10">
<div class="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<h3 class="section-title text-lg">{{ t('admin.report.usage') }}</h3>
<label class="flex items-center gap-2 text-sm text-secondary">
<span class="whitespace-nowrap">{{ t('admin.report.usageRangeLabel') }}</span>
<select v-model="usageRange" class="admin-table-filter-input min-w-[8rem]">
<option v-for="key in usageRangeOptions" :key="key" :value="key">
{{ t(`admin.report.usageRanges.${key}`) }}
</option>
</select>
</label>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-8">
<div class="card p-6">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byAgent') }}</h4>
<div class="space-y-3">
<div v-for="a in usageReport.by_agent" :key="a.agent" class="flex items-center justify-between p-3 bg-surface-soft rounded-xl">
<span class="font-medium text-secondary">{{ a.agent }}</span>
<span class="admin-report-badge admin-report-badge--info font-bold">{{ a.count }}</span>
</div>
</div>
</div>
<div class="card p-6 flex flex-col">
<div class="mb-4">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.byUser') }}</h4>
<p class="mt-1 text-xs text-muted">{{ t('admin.report.usageByUserTopHint', { limit: usageUserTopLimit }) }}</p>
</div>
<div class="space-y-3 flex-1">
<div v-for="u in usageReport.by_user" :key="u.username" class="flex items-center justify-between gap-3 p-3 bg-surface-soft rounded-xl">
<span class="font-medium text-secondary truncate" :title="formatUsageUserLabel(u)">{{ formatUsageUserLabel(u) }}</span>
<span class="admin-report-badge admin-report-badge--info font-bold shrink-0">{{ u.count }}</span>
</div>
<div v-if="usageReport.by_user.length === 0" class="text-center text-muted text-sm py-6">
{{ t('admin.report.usageByUserEmpty') }}
</div>
</div>
<div v-if="usageUserTotal > 0" class="mt-4 flex flex-col gap-3 border-t border-default pt-4">
<div class="text-xs text-secondary">
{{ t('admin.report.paginationSummary', { total: usageUserTotal, page: usageUserPage, pages: usageUserTotalPages }) }}
</div>
<div class="flex flex-wrap items-center gap-2">
<label class="flex items-center gap-2 text-xs text-secondary">
<span>{{ t('admin.report.perPage') }}</span>
<span class="relative inline-flex items-center">
<select
v-model.number="usageUserPageSize"
class="admin-table-filter-input appearance-none pl-2 pr-7 py-1 text-xs leading-5"
>
<option v-for="size in usageUserPageSizeOptions" :key="`usage-user-size-${size}`" :value="size">{{ size }}</option>
</select>
<svg class="pointer-events-none absolute right-2 h-3.5 w-3.5 text-muted" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z" clip-rule="evenodd" />
</svg>
</span>
<span>{{ t('admin.report.itemsUnit') }}</span>
</label>
<button
@click="prevUsageUserPage"
:disabled="usageUserPage <= 1"
class="admin-report-page-btn"
>
{{ t('admin.report.prevPage') }}
</button>
<button
v-for="btn in usageUserPageButtons"
:key="`usage-user-page-btn-${btn}`"
:disabled="btn === -1"
@click="btn !== -1 && goToUsageUserPage(btn)"
class="admin-report-page-btn"
:class="btn === -1
? 'border-transparent text-muted cursor-default opacity-100'
: btn === usageUserPage
? 'admin-report-page-btn--active'
: ''"
>
{{ btn === -1 ? '...' : btn }}
</button>
<button
@click="nextUsageUserPage"
:disabled="usageUserPage >= usageUserTotalPages"
class="admin-report-page-btn"
>
{{ t('admin.report.nextPage') }}
</button>
</div>
</div>
</div>
</div>
</div>
</div> </div>
</section> </section>
@@ -1,15 +1,16 @@
/** /**
* features/admin/modules/reports/composables/useReportsAdmin.ts * features/admin/modules/reports/composables/useReportsAdmin.ts
* 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除与带时间范围的用量图表)。 * 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除、使用分析与应用运营看板)。
* 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime。 * 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime、vue-router。
* 逻辑:ReportsPage 调用本 composable;使用分析默认近一月,可切换 7d/30d/90d/180d/365d。 * 逻辑:ReportsPage 调用本 composable;agents 表走应用运营专用接口,不再浏览原始配置。
*/ */
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import * as XLSX from 'xlsx'; import * as XLSX from 'xlsx';
import { import {
batchDeleteAdminChatLogs, batchDeleteAdminChatLogs,
getAdminApplicationReport,
getAdminReportTable, getAdminReportTable,
getAdminReportTableCount, getAdminReportTableCount,
getAdminUsageReport, getAdminUsageReport,
@@ -20,6 +21,11 @@ import { useMessage } from '@/shared/composables/useMessage';
import { formatLocalDateTime } from '@/shared/utils/dateTime'; import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { ADMIN_REPORT_TABLES } from '@/features/admin/constants/modules'; import { ADMIN_REPORT_TABLES } from '@/features/admin/constants/modules';
import type { import type {
ApplicationReport,
ApplicationReportItem,
ApplicationSortKey,
ApplicationStatusFilter,
ApplicationUsageFilter,
ChatLogsLayoutPref, ChatLogsLayoutPref,
ReportColumnConfig, ReportColumnConfig,
SortRule, SortRule,
@@ -72,6 +78,7 @@ export function useReportsAdmin() {
const { t, locale } = useI18n(); const { t, locale } = useI18n();
const msg = useMessage(); const msg = useMessage();
const route = useRoute(); const route = useRoute();
const router = useRouter();
const usageReport = ref<UsageReport | null>(null); const usageReport = ref<UsageReport | null>(null);
const usageUserPage = ref(1); const usageUserPage = ref(1);
@@ -81,6 +88,19 @@ export function useReportsAdmin() {
const usageRange = ref<UsageRangeKey>('30d'); const usageRange = ref<UsageRangeKey>('30d');
const usageRangeOptions: UsageRangeKey[] = ['7d', '30d', '90d', '180d', '365d']; const usageRangeOptions: UsageRangeKey[] = ['7d', '30d', '90d', '180d', '365d'];
/** 应用运营看板状态(替换原 agents 配置表浏览) */
const applicationReport = ref<ApplicationReport | null>(null);
const applicationRange = ref<UsageRangeKey>('30d');
const applicationStatus = ref<ApplicationStatusFilter>('all');
const applicationUsage = ref<ApplicationUsageFilter>('all');
const applicationQuery = ref('');
const applicationSort = ref<ApplicationSortKey>('chat_count');
const applicationOrder = ref<'asc' | 'desc'>('desc');
const applicationPage = ref(1);
const applicationPageSize = ref(20);
const applicationPageSizeOptions = [10, 20, 50, 100];
let applicationSearchTimer: ReturnType<typeof setTimeout> | null = null;
const loadUsageReport = async (): Promise<void> => { const loadUsageReport = async (): Promise<void> => {
try { try {
usageReport.value = await getAdminUsageReport({ usageReport.value = await getAdminUsageReport({
@@ -97,9 +117,153 @@ export function useReportsAdmin() {
} }
}; };
/**
* 加载应用运营报表。
* 核心逻辑:调用 /reports/applications,按当前筛选与排序拉取分页数据。
*/
const loadApplicationReport = async (): Promise<void> => {
try {
applicationReport.value = await getAdminApplicationReport({
range: applicationRange.value,
status: applicationStatus.value,
usage: applicationUsage.value,
q: applicationQuery.value,
sort: applicationSort.value,
order: applicationOrder.value,
page: applicationPage.value,
page_size: applicationPageSize.value,
});
const pages = applicationReport.value?.pages ?? 1;
if (applicationPage.value > pages) {
applicationPage.value = pages;
}
} catch (e) {
console.error('Error loading application report:', e);
applicationReport.value = null;
}
};
const applicationSummary = computed(() => applicationReport.value?.summary ?? null);
const applicationItems = computed(() => applicationReport.value?.items ?? []);
const applicationTotal = computed(() => applicationReport.value?.total ?? 0);
const applicationTotalPages = computed(() => Math.max(1, applicationReport.value?.pages ?? 1));
const applicationPageButtons = computed(() =>
buildOffsetPageButtons(applicationPage.value, applicationTotalPages.value),
);
const goToApplicationPage = (page: number): void => {
applicationPage.value = Math.min(Math.max(1, page), applicationTotalPages.value);
void loadApplicationReport();
};
const prevApplicationPage = () => goToApplicationPage(applicationPage.value - 1);
const nextApplicationPage = () => goToApplicationPage(applicationPage.value + 1);
/**
* 切换应用运营表头排序;同列再次点击翻转升降序。
* @param key - 可排序字段
*/
const onApplicationSortClick = (key: ApplicationSortKey): void => {
if (applicationSort.value === key) {
applicationOrder.value = applicationOrder.value === 'asc' ? 'desc' : 'asc';
} else {
applicationSort.value = key;
applicationOrder.value = key === 'name' ? 'asc' : 'desc';
}
applicationPage.value = 1;
void loadApplicationReport();
};
const getApplicationSortMark = (key: ApplicationSortKey): string => {
if (applicationSort.value !== key) return '';
return applicationOrder.value === 'asc' ? '^' : 'v';
};
/**
* 应用名称搜索防抖,避免输入过程中频繁打接口。
*/
const handleApplicationSearchChange = (): void => {
if (applicationSearchTimer) clearTimeout(applicationSearchTimer);
applicationSearchTimer = setTimeout(() => {
applicationPage.value = 1;
void loadApplicationReport();
}, 400);
};
/**
* 下钻到聊天日志,按 agent_id 精确过滤。
* @param row - 应用运营行
*/
const openApplicationChatLogs = (row: ApplicationReportItem): void => {
void router.push({
name: 'AdminReports',
params: { table: 'chat_logs' },
query: { agent_id: String(row.agent_id), agent_name: row.name },
});
};
/**
* 下钻到权限申请列表,按 agent_id 精确过滤。
* @param row - 应用运营行
*/
const openApplicationPermissionRequests = (row: ApplicationReportItem): void => {
void router.push({
name: 'AdminReports',
params: { table: 'permission_requests' },
query: { agent_id: String(row.agent_id) },
});
};
/**
* 导出应用运营报表 Excel(仅运营字段)。
*/
const exportApplicationReport = (): void => {
const items = applicationItems.value;
if (items.length === 0) return;
const rows = items.map((row) => ({
[t('admin.report.appOps.columns.name')]: row.name,
[t('admin.report.appOps.columns.is_active')]: row.is_active
? t('admin.report.appOps.statusActive')
: t('admin.report.appOps.statusInactive'),
[t('admin.report.appOps.columns.category')]: row.category || '-',
[t('admin.report.appOps.columns.chat_count')]: row.chat_count,
[t('admin.report.appOps.columns.unique_users')]: row.unique_users,
[t('admin.report.appOps.columns.last_active_at')]: row.last_active_at
? formatLocalDateTime(row.last_active_at)
: '-',
[t('admin.report.appOps.columns.authorized_users')]: row.authorized_users,
[t('admin.report.appOps.columns.pending_requests')]: row.pending_requests,
[t('admin.report.appOps.columns.avg_score')]: row.avg_score ?? '-',
[t('admin.report.appOps.columns.feedback_count')]: row.feedback_count,
[t('admin.report.appOps.columns.tokens_used')]: row.tokens_used,
}));
const ws = XLSX.utils.json_to_sheet(rows);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'applications');
XLSX.writeFile(wb, `applications_ops_${new Date().toISOString().split('T')[0]}.xlsx`);
};
const usageUserTotalPages = computed(() => Math.max(1, usageReport.value?.user_pages ?? 1)); const usageUserTotalPages = computed(() => Math.max(1, usageReport.value?.user_pages ?? 1));
const usageUserTotal = computed(() => usageReport.value?.user_total ?? 0); const usageUserTotal = computed(() => usageReport.value?.user_total ?? 0);
const usageUserTopLimit = computed(() => usageReport.value?.user_top_limit ?? 50); 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 usageLowAgentItems = computed(() =>
[...(usageReport.value?.by_agent || [])]
.filter((item) => item.count <= 2)
.sort((a, b) => a.count - b.count || a.agent.localeCompare(b.agent))
.slice(0, 5),
);
const usageSpikeDayItems = computed(() => {
const days = usageReport.value?.by_day || [];
if (days.length === 0) return [];
const average = days.reduce((sum, item) => sum + item.count, 0) / days.length;
return days
.filter((item) => item.count >= Math.max(5, average * 2))
.sort((a, b) => b.count - a.count)
.slice(0, 3);
});
const usageTopUserItems = computed(() => usageReport.value?.by_user.slice(0, 3) ?? []);
const usageTopAgentItems = computed(() => usageReport.value?.by_agent.slice(0, 5) ?? []);
const usageUserPageButtons = computed(() => const usageUserPageButtons = computed(() =>
buildOffsetPageButtons(usageUserPage.value, usageUserTotalPages.value), buildOffsetPageButtons(usageUserPage.value, usageUserTotalPages.value),
); );
@@ -145,7 +309,7 @@ export function useReportsAdmin() {
if (typeof table === 'string' && (ADMIN_REPORT_TABLES as readonly string[]).includes(table)) { if (typeof table === 'string' && (ADMIN_REPORT_TABLES as readonly string[]).includes(table)) {
return table as AdminReportTableId; return table as AdminReportTableId;
} }
return 'users'; return 'usage_analysis';
}; };
const currentTable = ref<AdminReportTableId>(resolveTableFromRoute()); const currentTable = ref<AdminReportTableId>(resolveTableFromRoute());
@@ -180,26 +344,55 @@ const resizingColumnKey = ref<string | null>(null);
let resizeStartX = 0; let resizeStartX = 0;
let resizeStartWidth = 0; let resizeStartWidth = 0;
/** 使用分析 / 应用运营是菜单层虚拟页,明细表仍复用对应数据源。 */
const dataSourceTable = computed<Exclude<AdminReportTableId, 'usage_analysis'>>(() => {
if (currentTable.value === 'usage_analysis') return 'chat_logs';
return currentTable.value as Exclude<AdminReportTableId, 'usage_analysis'>;
});
/**
* 从路由 query 灌入列筛选(用于应用运营下钻到聊天日志 / 权限申请)。
*/
const applyRouteQueryFilters = (): void => {
const next: Record<string, string> = {};
for (const [key, value] of Object.entries(route.query)) {
if (typeof value === 'string' && value.trim()) {
next[key] = value.trim();
}
}
columnFilters.value = next;
};
const loadTableData = async () => { const loadTableData = async () => {
// 应用运营页不走通用配置表
if (currentTable.value === 'agents') {
tableData.value = [];
selectedReportRowIds.value = [];
chatLogsColumns.value = [];
await loadApplicationReport();
return;
}
const params = new URLSearchParams(); const params = new URLSearchParams();
for (const [key, value] of Object.entries(columnFilters.value)) { for (const [key, value] of Object.entries(columnFilters.value)) {
if (value) params.append(key, value); if (value) params.append(key, value);
} }
const url = currentTable.value === 'general_feedbacks' const table = dataSourceTable.value;
const url = table === 'general_feedbacks'
? `/api/admin/reports/general-feedbacks?${params.toString()}` ? `/api/admin/reports/general-feedbacks?${params.toString()}`
: `/api/admin/database/${currentTable.value}?${params.toString()}`; : `/api/admin/database/${table}?${params.toString()}`;
try { try {
tableData.value = await getAdminReportTable(url); tableData.value = await getAdminReportTable(url);
if (tableData.value.length > 0) { if (tableData.value.length > 0) {
const rowKeys = Object.keys(tableData.value[0] || {}); const rowKeys = Object.keys(tableData.value[0] || {});
const columnKeys = currentTable.value === 'chat_logs' const columnKeys = dataSourceTable.value === 'chat_logs'
? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k)) ? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k))
: rowKeys; : rowKeys;
initChatLogsColumns(columnKeys); initChatLogsColumns(columnKeys);
} }
if (currentTable.value === 'chat_logs') { if (dataSourceTable.value === 'chat_logs') {
const validIds = new Set( const validIds = new Set(
tableData.value tableData.value
.map((row: any) => Number(row?.id)) .map((row: any) => Number(row?.id))
@@ -229,7 +422,7 @@ const saveChatLogsColumns = () => {
const initChatLogsColumns = (keys: string[]) => { const initChatLogsColumns = (keys: string[]) => {
chatLogsWrapEnabled.value = false; chatLogsWrapEnabled.value = false;
chatLogsWrapMaxHeight.value = 120; chatLogsWrapMaxHeight.value = 120;
const hideByDefault = currentTable.value === 'chat_logs' && keys.includes('id'); const hideByDefault = dataSourceTable.value === 'chat_logs' && keys.includes('id');
const defaults: ReportColumnConfig[] = keys.map((k) => ({ const defaults: ReportColumnConfig[] = keys.map((k) => ({
key: k, key: k,
visible: hideByDefault ? k !== 'id' : true, visible: hideByDefault ? k !== 'id' : true,
@@ -246,7 +439,7 @@ const initChatLogsColumns = (keys: string[]) => {
const missing = keys.filter((k) => !order.includes(k)); const missing = keys.filter((k) => !order.includes(k));
merged = [...order, ...missing].map((k) => ({ merged = [...order, ...missing].map((k) => ({
key: k, key: k,
visible: savedMap.get(k)?.visible ?? (currentTable.value === 'chat_logs' && k === 'id' ? false : true), visible: savedMap.get(k)?.visible ?? (dataSourceTable.value === 'chat_logs' && k === 'id' ? false : true),
width: savedMap.get(k)?.width ?? defaultChatLogsColumnWidth(k), width: savedMap.get(k)?.width ?? defaultChatLogsColumnWidth(k),
})); }));
if (!Array.isArray(parsed)) { if (!Array.isArray(parsed)) {
@@ -272,7 +465,7 @@ const resetChatLogsColumns = () => {
chatLogsSortRules.value = []; chatLogsSortRules.value = [];
reportHeaderSort.value = null; reportHeaderSort.value = null;
const rowKeys = Object.keys(tableData.value[0] || {}); const rowKeys = Object.keys(tableData.value[0] || {});
const columnKeys = currentTable.value === 'chat_logs' const columnKeys = dataSourceTable.value === 'chat_logs'
? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k)) ? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k))
: rowKeys; : rowKeys;
initChatLogsColumns(columnKeys); initChatLogsColumns(columnKeys);
@@ -353,6 +546,10 @@ const loadTableCount = async (table: string) => {
}; };
const exportToExcel = () => { const exportToExcel = () => {
if (currentTable.value === 'agents') {
exportApplicationReport();
return;
}
if (tableData.value.length === 0) return; if (tableData.value.length === 0) return;
const keys = visibleReportKeys.value; const keys = visibleReportKeys.value;
const rows = tableData.value.map((row) => { const rows = tableData.value.map((row) => {
@@ -377,10 +574,14 @@ const handleFilterChange = () => {
}, 500); }, 500);
}; };
const isChatLogsTable = computed(() => currentTable.value === 'chat_logs'); const isUsageAnalysisTable = computed(() => currentTable.value === 'usage_analysis');
/** 列已初始化后(含筛选无结果)仍展示表头与筛选框,避免用户无法修改条件 */ const isApplicationOpsTable = computed(() => currentTable.value === 'agents');
const isChatLogsTable = computed(() => dataSourceTable.value === 'chat_logs');
/** 列已初始化后(含筛选无结果)仍展示表头与筛选框;应用运营页用专用看板,不展示通用表 */
const showReportTable = computed( const showReportTable = computed(
() => tableData.value.length > 0 || chatLogsColumns.value.length > 0, () =>
!isApplicationOpsTable.value
&& (tableData.value.length > 0 || chatLogsColumns.value.length > 0),
); );
const visibleReportKeys = computed(() => { const visibleReportKeys = computed(() => {
let keys: string[]; let keys: string[];
@@ -406,7 +607,7 @@ const visibleReportKeys = computed(() => {
return feedbackFixedOrder.filter((k) => available.has(k)); return feedbackFixedOrder.filter((k) => available.has(k));
} }
if (currentTable.value === 'chat_logs') { if (dataSourceTable.value === 'chat_logs') {
const available = new Set(keys); const available = new Set(keys);
return CHAT_LOGS_REPORT_KEYS.filter((k) => available.has(k)); return CHAT_LOGS_REPORT_KEYS.filter((k) => available.has(k));
} }
@@ -819,7 +1020,7 @@ const batchDeleteChatLogs = async () => {
}; };
watch(currentTable, async () => { watch(currentTable, async () => {
columnFilters.value = {}; // Reset filters on table change applyRouteQueryFilters();
chatLogsColumns.value = []; chatLogsColumns.value = [];
selectedReportRowIds.value = []; selectedReportRowIds.value = [];
showChatLogsColumnPanel.value = false; showChatLogsColumnPanel.value = false;
@@ -827,7 +1028,7 @@ watch(currentTable, async () => {
reportCurrentPage.value = 1; reportCurrentPage.value = 1;
await loadTableData(); await loadTableData();
reportHeaderSort.value = null; reportHeaderSort.value = null;
if (currentTable.value === 'chat_logs') { if (dataSourceTable.value === 'chat_logs' && !isApplicationOpsTable.value) {
chatLogsTotal.value = await loadTableCount('chat_logs'); chatLogsTotal.value = await loadTableCount('chat_logs');
} }
}); });
@@ -865,6 +1066,13 @@ watch(usageRange, () => {
void loadUsageReport(); void loadUsageReport();
}); });
watch([applicationRange, applicationStatus, applicationUsage, applicationPageSize], () => {
applicationPage.value = 1;
if (isApplicationOpsTable.value) {
void loadApplicationReport();
}
});
watch([reportPageSize, sortedTableData], () => { watch([reportPageSize, sortedTableData], () => {
if (reportCurrentPage.value > reportTotalPages.value) { if (reportCurrentPage.value > reportTotalPages.value) {
reportCurrentPage.value = reportTotalPages.value; reportCurrentPage.value = reportTotalPages.value;
@@ -877,14 +1085,14 @@ watch([reportPageSize, sortedTableData], () => {
const loadAll = async (): Promise<void> => { const loadAll = async (): Promise<void> => {
isLoading.value = true; isLoading.value = true;
await loadReports(); await loadReports();
columnFilters.value = {}; applyRouteQueryFilters();
selectedReportRowIds.value = []; selectedReportRowIds.value = [];
showChatLogsColumnPanel.value = false; showChatLogsColumnPanel.value = false;
showChatLogsSelection.value = false; showChatLogsSelection.value = false;
reportCurrentPage.value = 1; reportCurrentPage.value = 1;
reportHeaderSort.value = null; reportHeaderSort.value = null;
await loadTableData(); await loadTableData();
if (currentTable.value === 'chat_logs') { if (dataSourceTable.value === 'chat_logs' && !isApplicationOpsTable.value) {
chatLogsTotal.value = await loadTableCount('chat_logs'); chatLogsTotal.value = await loadTableCount('chat_logs');
} else { } else {
showChatLogsSelection.value = false; showChatLogsSelection.value = false;
@@ -902,10 +1110,39 @@ watch([reportPageSize, sortedTableData], () => {
usageUserTotal, usageUserTotal,
usageUserTotalPages, usageUserTotalPages,
usageUserTopLimit, usageUserTopLimit,
usageActiveAgentCount,
usageTrendMax,
usageLowAgentItems,
usageSpikeDayItems,
usageTopUserItems,
usageTopAgentItems,
usageUserPageButtons, usageUserPageButtons,
goToUsageUserPage, goToUsageUserPage,
prevUsageUserPage, prevUsageUserPage,
nextUsageUserPage, nextUsageUserPage,
applicationReport,
applicationRange,
applicationStatus,
applicationUsage,
applicationQuery,
applicationSort,
applicationOrder,
applicationPage,
applicationPageSize,
applicationPageSizeOptions,
applicationSummary,
applicationItems,
applicationTotal,
applicationTotalPages,
applicationPageButtons,
goToApplicationPage,
prevApplicationPage,
nextApplicationPage,
onApplicationSortClick,
getApplicationSortMark,
handleApplicationSearchChange,
openApplicationChatLogs,
openApplicationPermissionRequests,
isLoading, isLoading,
currentTable, currentTable,
tableData, tableData,
@@ -925,6 +1162,8 @@ watch([reportPageSize, sortedTableData], () => {
chatLogsSortRules, chatLogsSortRules,
reportHeaderSort, reportHeaderSort,
draggingColumnKey, draggingColumnKey,
isUsageAnalysisTable,
isApplicationOpsTable,
isChatLogsTable, isChatLogsTable,
showReportTable, showReportTable,
visibleReportKeys, visibleReportKeys,
@@ -20,6 +20,7 @@ export type AdminModuleId =
| 'reports'; | 'reports';
export type AdminReportTableId = export type AdminReportTableId =
| 'usage_analysis'
| 'users' | 'users'
| 'agents' | 'agents'
| 'chat_logs' | 'chat_logs'
@@ -1,6 +1,6 @@
/** /**
* features/admin/types/report.types.ts * features/admin/types/report.types.ts
* 用途:报表模块类型(使用分析、列配置、排序规则)。 * 用途:报表模块类型(使用分析、应用运营、列配置、排序规则)。
* 依赖:无。 * 依赖:无。
* 逻辑:useReportsAdmin / admin.api 共用。 * 逻辑:useReportsAdmin / admin.api 共用。
*/ */
@@ -14,6 +14,7 @@ export interface UsageReport {
range?: UsageRangeKey; range?: UsageRangeKey;
by_user: { username: string; real_name?: string; count: number }[]; by_user: { username: string; real_name?: string; count: number }[];
by_agent: { agent: string; count: number }[]; by_agent: { agent: string; count: number }[];
/** 当前范围内按自然日聚合的对话趋势,用于使用分析柱状图。 */
by_day?: { date: string; count: number }[]; by_day?: { date: string; count: number }[];
user_total: number; user_total: number;
user_page: number; user_page: number;
@@ -22,6 +23,62 @@ export interface UsageReport {
user_top_limit: number; user_top_limit: number;
} }
/** 应用运营报表:启用状态筛选 */
export type ApplicationStatusFilter = 'all' | 'active' | 'inactive';
/** 应用运营报表:是否有使用筛选 */
export type ApplicationUsageFilter = 'all' | 'used' | 'unused';
/** 应用运营报表可排序字段 */
export type ApplicationSortKey =
| 'name'
| 'chat_count'
| 'unique_users'
| 'last_active_at'
| 'authorized_users'
| 'pending_requests'
| 'avg_score'
| 'tokens_used';
export interface ApplicationReportItem {
agent_id: number;
name: string;
is_active: boolean;
category: string;
chat_count: number;
unique_users: number;
last_active_at: string | null;
authorized_users: number;
pending_requests: number;
avg_score: number | null;
feedback_count: number;
tokens_used: number;
avg_latency_ms: number | null;
}
export interface ApplicationReportSummary {
agent_total: number;
active_agents: number;
used_agents: number;
unused_agents: number;
pending_permission_total: number;
}
export interface ApplicationReport {
range: UsageRangeKey;
status: ApplicationStatusFilter;
usage: ApplicationUsageFilter;
q: string;
sort: ApplicationSortKey;
order: 'asc' | 'desc';
summary: ApplicationReportSummary;
items: ApplicationReportItem[];
total: number;
page: number;
page_size: number;
pages: number;
}
export interface ReportColumnConfig { export interface ReportColumnConfig {
key: string; key: string;
visible: boolean; visible: boolean;
+52 -3
View File
@@ -761,7 +761,7 @@
}, },
"report": { "report": {
"title": "Data Reports: {table}", "title": "Data Reports: {table}",
"subtitle": "Raw data view and statistics", "subtitle": "Operational analytics and detail tracing",
"export": "Export Excel", "export": "Export Excel",
"columnSettings": "Column Settings", "columnSettings": "Column Settings",
"showSelection": "Show Selection", "showSelection": "Show Selection",
@@ -878,8 +878,9 @@
"general_feedbacks": "Feedback", "general_feedbacks": "Feedback",
"feedbacks": "Answer Rating", "feedbacks": "Answer Rating",
"departments": "Departments", "departments": "Departments",
"agents": "Agents", "agents": "App Ops",
"permission_requests": "Permission Requests" "permission_requests": "Permission Requests",
"usage_analysis": "Usage Analytics"
}, },
"feedbackValues": { "feedbackValues": {
"types": { "types": {
@@ -898,6 +899,54 @@
"chat": "Chat", "chat": "Chat",
"unknown": "Unknown" "unknown": "Unknown"
} }
},
"usageIntro": "Review AI app trends, active users, low-usage apps, and unusual spikes.",
"usageTotalSessions": "Total chats",
"usageActiveUsers": "Active users",
"usageActiveAgents": "Active apps",
"usageTrend": "Recent trend",
"usageTrendEmpty": "No trend data yet",
"usageInsights": "Operational alerts",
"usageLowAgents": "Low-usage apps",
"usageLowAgentsEmpty": "No low-usage apps in this range",
"usageSpikeDays": "Spike days",
"usageSpikeDaysEmpty": "No clear spikes in this range",
"usageByAgentEmpty": "No app chat activity yet",
"usageActiveUserHint": "Showing the top 3 active users on this page",
"appOps": {
"title": "App Operations",
"intro": "Per-app usage, authorization, pending requests, and ratings — with drill-down to chat logs and permission requests.",
"statusLabel": "Status",
"statusAll": "All",
"statusActive": "Active",
"statusInactive": "Inactive",
"usageLabel": "Usage",
"usageAll": "All",
"usageUsed": "Used",
"usageUnused": "Unused",
"searchPlaceholder": "Search app name…",
"summaryActive": "Active apps",
"summaryTotal": "{total} total",
"summaryUsed": "Used",
"summaryUnused": "Unused",
"summaryPending": "Pending permissions",
"empty": "No application ops data. Try adjusting filters.",
"actionLogs": "Logs",
"actionRequests": "Requests",
"columns": {
"name": "App",
"is_active": "Status",
"category": "Category",
"chat_count": "Chats",
"unique_users": "Users",
"last_active_at": "Last active",
"authorized_users": "Authorized",
"pending_requests": "Pending",
"avg_score": "Avg score",
"feedback_count": "Ratings",
"tokens_used": "Tokens",
"actions": "Actions"
}
} }
}, },
"batchEdit": { "batchEdit": {
+53 -4
View File
@@ -766,7 +766,7 @@
}, },
"report": { "report": {
"title": "รายงานข้อมูล: {table}", "title": "รายงานข้อมูล: {table}",
"subtitle": "มุมมองข้อมูลดิบและสถิติ", "subtitle": "การวิเคราะห์การใช้งานและรายละเอียดย้อนหลัง",
"export": "ส่งออก Excel", "export": "ส่งออก Excel",
"columnSettings": "ตั้งค่าคอลัมน์", "columnSettings": "ตั้งค่าคอลัมน์",
"showSelection": "แสดงการเลือก", "showSelection": "แสดงการเลือก",
@@ -797,7 +797,7 @@
"exitFullscreen": "ออกจากเต็มหน้าจอ", "exitFullscreen": "ออกจากเต็มหน้าจอ",
"noData": "ไม่มีข้อมูลสำหรับ {table}", "noData": "ไม่มีข้อมูลสำหรับ {table}",
"noFilterResults": "ไม่พบข้อมูลที่ตรงกับเงื่อนไข โปรดปรับตัวกรอง", "noFilterResults": "ไม่พบข้อมูลที่ตรงกับเงื่อนไข โปรดปรับตัวกรอง",
"usage": "การวิเคราะห์การใช้งาน", "usage": "วิเคราะห์การใช้งาน",
"usageRangeLabel": "ช่วงเวลา", "usageRangeLabel": "ช่วงเวลา",
"usageRanges": { "usageRanges": {
"7d": "7 วันล่าสุด", "7d": "7 วันล่าสุด",
@@ -880,8 +880,57 @@
"general_feedbacks": "ข้อเสนอแนะทั่วไป", "general_feedbacks": "ข้อเสนอแนะทั่วไป",
"feedbacks": "การประเมินคำตอบ", "feedbacks": "การประเมินคำตอบ",
"departments": "แผนก", "departments": "แผนก",
"agents": "ตัวแทน", "agents": "แอปปฏิบัติการ",
"permission_requests": "คำขอสิทธิ์" "permission_requests": "คำขอสิทธิ์",
"usage_analysis": "วิเคราะห์การใช้งาน"
},
"usageIntro": "ดูแนวโน้มการเรียกใช้แอป AI ผู้ใช้ที่ใช้งาน แอปที่ใช้น้อย และช่วงพีคผิดปกติ",
"usageTotalSessions": "จำนวนแชทรวม",
"usageActiveUsers": "ผู้ใช้ที่ใช้งาน",
"usageActiveAgents": "แอปที่ใช้งาน",
"usageTrend": "แนวโน้มล่าสุด",
"usageTrendEmpty": "ยังไม่มีข้อมูลแนวโน้ม",
"usageInsights": "การแจ้งเตือนการดำเนินงาน",
"usageLowAgents": "แอปที่ใช้น้อย",
"usageLowAgentsEmpty": "ไม่มีแอปที่ใช้น้อยในช่วงนี้",
"usageSpikeDays": "วันที่มีการใช้งานพุ่งสูง",
"usageSpikeDaysEmpty": "ไม่พบช่วงพีคที่ชัดเจนในช่วงนี้",
"usageByAgentEmpty": "ยังไม่มีประวัติแชทของแอป",
"usageActiveUserHint": "แสดงผู้ใช้ที่ใช้งานสูงสุด 3 อันดับในหน้านี้",
"appOps": {
"title": "แอปปฏิบัติการ",
"intro": "ดูปริมาณการใช้ สิทธิ์ คำขอที่รอ และคะแนนรายแอป พร้อมเจาะลงบันทึกแชทและคำขอสิทธิ์",
"statusLabel": "สถานะ",
"statusAll": "ทั้งหมด",
"statusActive": "เปิดใช้",
"statusInactive": "ปิดใช้",
"usageLabel": "การใช้งาน",
"usageAll": "ทั้งหมด",
"usageUsed": "มีการใช้",
"usageUnused": "ไม่มีการใช้",
"searchPlaceholder": "ค้นหาชื่อแอป…",
"summaryActive": "แอปที่เปิดใช้",
"summaryTotal": "ทั้งหมด {total}",
"summaryUsed": "มีการใช้",
"summaryUnused": "ไม่มีการใช้",
"summaryPending": "สิทธิ์รอดำเนินการ",
"empty": "ไม่มีข้อมูลแอปปฏิบัติการ ลองปรับตัวกรอง",
"actionLogs": "บันทึก",
"actionRequests": "คำขอ",
"columns": {
"name": "แอป",
"is_active": "สถานะ",
"category": "หมวด",
"chat_count": "แชท",
"unique_users": "ผู้ใช้",
"last_active_at": "ใช้งานล่าสุด",
"authorized_users": "ได้รับสิทธิ์",
"pending_requests": "รอดำเนินการ",
"avg_score": "คะแนนเฉลี่ย",
"feedback_count": "จำนวนคะแนน",
"tokens_used": "Token",
"actions": "การทำงาน"
}
} }
}, },
"batchEdit": { "batchEdit": {
+52 -3
View File
@@ -762,7 +762,7 @@
}, },
"report": { "report": {
"title": "数据报表: {table}", "title": "数据报表: {table}",
"subtitle": "原始数据与统计视图", "subtitle": "运营分析与明细追溯",
"export": "导出 Excel", "export": "导出 Excel",
"columnSettings": "列设置", "columnSettings": "列设置",
"showSelection": "显示选择", "showSelection": "显示选择",
@@ -876,8 +876,57 @@
"general_feedbacks": "意见反馈", "general_feedbacks": "意见反馈",
"feedbacks": "回答评价", "feedbacks": "回答评价",
"departments": "部门", "departments": "部门",
"agents": "应用", "agents": "应用运营",
"permission_requests": "权限申请" "permission_requests": "权限申请",
"usage_analysis": "使用分析"
},
"usageIntro": "查看 AI 应用调用趋势、活跃用户、低使用应用与异常高峰。",
"usageTotalSessions": "对话总量",
"usageActiveUsers": "活跃用户",
"usageActiveAgents": "活跃应用",
"usageTrend": "近段趋势",
"usageTrendEmpty": "暂无趋势数据",
"usageInsights": "运营提醒",
"usageLowAgents": "低使用应用",
"usageLowAgentsEmpty": "当前范围内暂无低使用应用",
"usageSpikeDays": "异常高峰日期",
"usageSpikeDaysEmpty": "当前范围内未发现明显高峰",
"usageByAgentEmpty": "暂无应用对话记录",
"usageActiveUserHint": "展示当前页活跃用户前三名",
"appOps": {
"title": "应用运营",
"intro": "按应用查看使用量、授权、待审与评分,支持下钻聊天日志与权限申请。",
"statusLabel": "状态",
"statusAll": "全部",
"statusActive": "启用",
"statusInactive": "停用",
"usageLabel": "使用",
"usageAll": "全部",
"usageUsed": "有使用",
"usageUnused": "零使用",
"searchPlaceholder": "搜索应用名称…",
"summaryActive": "启用应用",
"summaryTotal": "共 {total} 个",
"summaryUsed": "有使用",
"summaryUnused": "零使用",
"summaryPending": "待审权限",
"empty": "暂无应用运营数据,请调整筛选条件",
"actionLogs": "日志",
"actionRequests": "申请",
"columns": {
"name": "应用",
"is_active": "状态",
"category": "分类",
"chat_count": "对话",
"unique_users": "用户",
"last_active_at": "最近活跃",
"authorized_users": "授权",
"pending_requests": "待审",
"avg_score": "均分",
"feedback_count": "评价数",
"tokens_used": "Token",
"actions": "操作"
}
} }
}, },
"batchEdit": { "batchEdit": {
+53 -4
View File
@@ -765,8 +765,8 @@
"reject": "拒絕" "reject": "拒絕"
}, },
"report": { "report": {
"title": "數據報表: {table}", "title": "資料報表: {table}",
"subtitle": "原始數據與統計視圖", "subtitle": "營運分析與明細追溯",
"export": "導出 Excel", "export": "導出 Excel",
"columnSettings": "列設置", "columnSettings": "列設置",
"showSelection": "顯示選擇", "showSelection": "顯示選擇",
@@ -880,8 +880,57 @@
"general_feedbacks": "意見反饋", "general_feedbacks": "意見反饋",
"feedbacks": "回答評價", "feedbacks": "回答評價",
"departments": "部門", "departments": "部門",
"agents": "應用", "agents": "應用運營",
"permission_requests": "權限申請" "permission_requests": "權限申請",
"usage_analysis": "使用分析"
},
"usageIntro": "查看 AI 應用呼叫趨勢、活躍使用者、低使用應用與異常高峰。",
"usageTotalSessions": "對話總量",
"usageActiveUsers": "活躍使用者",
"usageActiveAgents": "活躍應用",
"usageTrend": "近段趨勢",
"usageTrendEmpty": "暫無趨勢資料",
"usageInsights": "營運提醒",
"usageLowAgents": "低使用應用",
"usageLowAgentsEmpty": "目前範圍內暫無低使用應用",
"usageSpikeDays": "異常高峰日期",
"usageSpikeDaysEmpty": "目前範圍內未發現明顯高峰",
"usageByAgentEmpty": "暫無應用對話記錄",
"usageActiveUserHint": "顯示目前頁活躍使用者前三名",
"appOps": {
"title": "應用運營",
"intro": "按應用查看使用量、授權、待審與評分,支援下鑽聊天日誌與權限申請。",
"statusLabel": "狀態",
"statusAll": "全部",
"statusActive": "啟用",
"statusInactive": "停用",
"usageLabel": "使用",
"usageAll": "全部",
"usageUsed": "有使用",
"usageUnused": "零使用",
"searchPlaceholder": "搜尋應用名稱…",
"summaryActive": "啟用應用",
"summaryTotal": "共 {total} 個",
"summaryUsed": "有使用",
"summaryUnused": "零使用",
"summaryPending": "待審權限",
"empty": "暫無應用運營資料,請調整篩選條件",
"actionLogs": "日誌",
"actionRequests": "申請",
"columns": {
"name": "應用",
"is_active": "狀態",
"category": "分類",
"chat_count": "對話",
"unique_users": "使用者",
"last_active_at": "最近活躍",
"authorized_users": "授權",
"pending_requests": "待審",
"avg_score": "均分",
"feedback_count": "評價數",
"tokens_used": "Token",
"actions": "操作"
}
} }
}, },
"batchEdit": { "batchEdit": {
@@ -467,6 +467,24 @@
@apply text-left transition-colors text-secondary hover:text-brand-600; @apply text-left transition-colors text-secondary hover:text-brand-600;
} }
/* 应用运营表:取消 uppercase/tracking,避免中文表头被拉开导致与数据列视觉错位 */
.admin-report-table--app-ops thead {
@apply normal-case tracking-normal;
}
.admin-report-table--app-ops thead th,
.admin-report-table--app-ops tbody td {
@apply align-middle;
}
.admin-report-app-ops-sort-btn {
@apply inline-flex w-full items-center gap-1 text-xs font-semibold text-secondary transition-colors hover:text-brand-600;
}
.admin-report-app-ops-sort-mark {
@apply inline-block w-2.5 shrink-0 text-[10px] text-brand-500;
}
.admin-report-page-btn { .admin-report-page-btn {
@apply rounded-lg border border-default px-2.5 py-1.5 text-xs text-secondary transition-colors; @apply rounded-lg border border-default px-2.5 py-1.5 text-xs text-secondary transition-colors;
} }