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

@@ -1,14 +1,16 @@
/**
* features/admin/modules/reports/ReportsPage.vue
* 用途:管理后台报表独立页面(多表浏览、列筛选、聊天日志批量操作)。
* 依赖:useReportsAdmin、DeleteConfirmDialog。
* 逻辑:路由 /admin/reports/:table?;列宽由 composable 默认值与本地偏好控制。
* 用途:管理后台报表独立页面(使用分析、应用运营、多表浏览与聊天日志批量操作)。
* 依赖:useReportsAdmin、DeleteConfirmDialog、lucide 图标。
* 逻辑:路由 /admin/reports/:table?;agents 表渲染应用运营看板而非配置 dump。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
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 { formatLocalDateTime } from '@/shared/utils/dateTime';
import type { ApplicationSortKey } from '@/features/admin/types/report.types';
import { useReportsAdmin } from './composables/useReportsAdmin';
const { t } = useI18n();
@@ -31,16 +33,34 @@ const {
usageReport,
usageRange,
usageRangeOptions,
usageUserPage,
usageUserPageSize,
usageUserPageSizeOptions,
usageUserTotal,
usageUserTotalPages,
usageUserTopLimit,
usageUserPageButtons,
goToUsageUserPage,
prevUsageUserPage,
nextUsageUserPage,
usageActiveAgentCount,
usageTrendMax,
usageLowAgentItems,
usageSpikeDayItems,
usageTopUserItems,
usageTopAgentItems,
applicationRange,
applicationStatus,
applicationUsage,
applicationQuery,
applicationPage,
applicationPageSize,
applicationPageSizeOptions,
applicationSummary,
applicationItems,
applicationTotal,
applicationTotalPages,
applicationPageButtons,
goToApplicationPage,
prevApplicationPage,
nextApplicationPage,
onApplicationSortClick,
getApplicationSortMark,
handleApplicationSearchChange,
openApplicationChatLogs,
openApplicationPermissionRequests,
isLoading,
currentTable,
tableData,
@@ -58,6 +78,8 @@ const {
reportPageSizeOptions,
chatLogsColumns,
chatLogsSortRules,
isUsageAnalysisTable,
isApplicationOpsTable,
isChatLogsTable,
showReportTable,
visibleReportKeys,
@@ -99,6 +121,68 @@ const {
confirmDelete,
} = 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(() => {
void loadAll();
});
@@ -130,13 +214,17 @@ onMounted(() => {
<span v-if="isChatLogsTable" class="admin-report-badge admin-report-badge--info font-semibold">
{{ t('admin.report.totalRows', { total: chatLogsTotal }) }}
</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 }) }}
</span>
</div>
</div>
<div class="flex flex-wrap items-center gap-2 md:gap-3">
<button
v-if="!isApplicationOpsTable"
@click="showChatLogsColumnPanel = !showChatLogsColumnPanel"
class="btn-secondary text-sm font-semibold"
:title="t('admin.report.columnSettings')"
@@ -180,8 +268,298 @@ onMounted(() => {
</div>
<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
v-if="showChatLogsColumnPanel"
v-if="showChatLogsColumnPanel && !isApplicationOpsTable"
class="admin-report-panel"
>
<div class="flex items-center justify-between mb-3">
@@ -259,7 +637,7 @@ onMounted(() => {
</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>
</div>
@@ -391,97 +769,6 @@ onMounted(() => {
</button>
</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>
</section>
@@ -1,15 +1,16 @@
/**
* features/admin/modules/reports/composables/useReportsAdmin.ts
* 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除与带时间范围的用量图表)。
* 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime。
* 逻辑:ReportsPage 调用本 composable;使用分析默认近一月,可切换 7d/30d/90d/180d/365d。
* 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除、使用分析与应用运营看板)。
* 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime、vue-router。
* 逻辑:ReportsPage 调用本 composable;agents 表走应用运营专用接口,不再浏览原始配置。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { useRoute, useRouter } from 'vue-router';
import * as XLSX from 'xlsx';
import {
batchDeleteAdminChatLogs,
getAdminApplicationReport,
getAdminReportTable,
getAdminReportTableCount,
getAdminUsageReport,
@@ -20,6 +21,11 @@ import { useMessage } from '@/shared/composables/useMessage';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { ADMIN_REPORT_TABLES } from '@/features/admin/constants/modules';
import type {
ApplicationReport,
ApplicationReportItem,
ApplicationSortKey,
ApplicationStatusFilter,
ApplicationUsageFilter,
ChatLogsLayoutPref,
ReportColumnConfig,
SortRule,
@@ -72,6 +78,7 @@ export function useReportsAdmin() {
const { t, locale } = useI18n();
const msg = useMessage();
const route = useRoute();
const router = useRouter();
const usageReport = ref<UsageReport | null>(null);
const usageUserPage = ref(1);
@@ -81,6 +88,19 @@ export function useReportsAdmin() {
const usageRange = ref<UsageRangeKey>('30d');
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> => {
try {
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 usageUserTotal = computed(() => usageReport.value?.user_total ?? 0);
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(() =>
buildOffsetPageButtons(usageUserPage.value, usageUserTotalPages.value),
);
@@ -145,7 +309,7 @@ export function useReportsAdmin() {
if (typeof table === 'string' && (ADMIN_REPORT_TABLES as readonly string[]).includes(table)) {
return table as AdminReportTableId;
}
return 'users';
return 'usage_analysis';
};
const currentTable = ref<AdminReportTableId>(resolveTableFromRoute());
@@ -180,26 +344,55 @@ const resizingColumnKey = ref<string | null>(null);
let resizeStartX = 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 () => {
// 应用运营页不走通用配置表
if (currentTable.value === 'agents') {
tableData.value = [];
selectedReportRowIds.value = [];
chatLogsColumns.value = [];
await loadApplicationReport();
return;
}
const params = new URLSearchParams();
for (const [key, value] of Object.entries(columnFilters.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/database/${currentTable.value}?${params.toString()}`;
: `/api/admin/database/${table}?${params.toString()}`;
try {
tableData.value = await getAdminReportTable(url);
if (tableData.value.length > 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))
: rowKeys;
initChatLogsColumns(columnKeys);
}
if (currentTable.value === 'chat_logs') {
if (dataSourceTable.value === 'chat_logs') {
const validIds = new Set(
tableData.value
.map((row: any) => Number(row?.id))
@@ -229,7 +422,7 @@ const saveChatLogsColumns = () => {
const initChatLogsColumns = (keys: string[]) => {
chatLogsWrapEnabled.value = false;
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) => ({
key: k,
visible: hideByDefault ? k !== 'id' : true,
@@ -246,7 +439,7 @@ const initChatLogsColumns = (keys: string[]) => {
const missing = keys.filter((k) => !order.includes(k));
merged = [...order, ...missing].map((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),
}));
if (!Array.isArray(parsed)) {
@@ -272,7 +465,7 @@ const resetChatLogsColumns = () => {
chatLogsSortRules.value = [];
reportHeaderSort.value = null;
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))
: rowKeys;
initChatLogsColumns(columnKeys);
@@ -353,6 +546,10 @@ const loadTableCount = async (table: string) => {
};
const exportToExcel = () => {
if (currentTable.value === 'agents') {
exportApplicationReport();
return;
}
if (tableData.value.length === 0) return;
const keys = visibleReportKeys.value;
const rows = tableData.value.map((row) => {
@@ -377,10 +574,14 @@ const handleFilterChange = () => {
}, 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(
() => tableData.value.length > 0 || chatLogsColumns.value.length > 0,
() =>
!isApplicationOpsTable.value
&& (tableData.value.length > 0 || chatLogsColumns.value.length > 0),
);
const visibleReportKeys = computed(() => {
let keys: string[];
@@ -406,7 +607,7 @@ const visibleReportKeys = computed(() => {
return feedbackFixedOrder.filter((k) => available.has(k));
}
if (currentTable.value === 'chat_logs') {
if (dataSourceTable.value === 'chat_logs') {
const available = new Set(keys);
return CHAT_LOGS_REPORT_KEYS.filter((k) => available.has(k));
}
@@ -819,7 +1020,7 @@ const batchDeleteChatLogs = async () => {
};
watch(currentTable, async () => {
columnFilters.value = {}; // Reset filters on table change
applyRouteQueryFilters();
chatLogsColumns.value = [];
selectedReportRowIds.value = [];
showChatLogsColumnPanel.value = false;
@@ -827,7 +1028,7 @@ watch(currentTable, async () => {
reportCurrentPage.value = 1;
await loadTableData();
reportHeaderSort.value = null;
if (currentTable.value === 'chat_logs') {
if (dataSourceTable.value === 'chat_logs' && !isApplicationOpsTable.value) {
chatLogsTotal.value = await loadTableCount('chat_logs');
}
});
@@ -865,6 +1066,13 @@ watch(usageRange, () => {
void loadUsageReport();
});
watch([applicationRange, applicationStatus, applicationUsage, applicationPageSize], () => {
applicationPage.value = 1;
if (isApplicationOpsTable.value) {
void loadApplicationReport();
}
});
watch([reportPageSize, sortedTableData], () => {
if (reportCurrentPage.value > reportTotalPages.value) {
reportCurrentPage.value = reportTotalPages.value;
@@ -877,14 +1085,14 @@ watch([reportPageSize, sortedTableData], () => {
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadReports();
columnFilters.value = {};
applyRouteQueryFilters();
selectedReportRowIds.value = [];
showChatLogsColumnPanel.value = false;
showChatLogsSelection.value = false;
reportCurrentPage.value = 1;
reportHeaderSort.value = null;
await loadTableData();
if (currentTable.value === 'chat_logs') {
if (dataSourceTable.value === 'chat_logs' && !isApplicationOpsTable.value) {
chatLogsTotal.value = await loadTableCount('chat_logs');
} else {
showChatLogsSelection.value = false;
@@ -902,10 +1110,39 @@ watch([reportPageSize, sortedTableData], () => {
usageUserTotal,
usageUserTotalPages,
usageUserTopLimit,
usageActiveAgentCount,
usageTrendMax,
usageLowAgentItems,
usageSpikeDayItems,
usageTopUserItems,
usageTopAgentItems,
usageUserPageButtons,
goToUsageUserPage,
prevUsageUserPage,
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,
currentTable,
tableData,
@@ -925,6 +1162,8 @@ watch([reportPageSize, sortedTableData], () => {
chatLogsSortRules,
reportHeaderSort,
draggingColumnKey,
isUsageAnalysisTable,
isApplicationOpsTable,
isChatLogsTable,
showReportTable,
visibleReportKeys,