Merge branch 'dev' into hugo-shipping-notice
This commit is contained in:
commit
bc86720744
49 files changed
+2950
-458
No files matched your search
@@ -7,7 +7,14 @@ import { requestJson } from '@/shared/api/client';
|
||||
import type { AdminUserRow } from '../types/admin.types';
|
||||
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.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 jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
@@ -275,6 +282,39 @@ export const getAdminUsageReport = (params: AdminUsageReportParams = {}) => {
|
||||
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 getAdminReportTable = (url: string) => requestJson<any[]>(url, auth());
|
||||
export const getAdminReportTableCount = (url: string) => requestJson<{ total: number }>(url, auth());
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/**
|
||||
* features/admin/components/AdminNav.vue
|
||||
* 管理后台左侧导航,使用子路由跳转。
|
||||
* 依赖:admin-nav.store、modules 常量、vue-router。
|
||||
* 逻辑:报表/企微子菜单默认折叠;当前路由落在对应模块时自动展开以便看到激活项。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { computed, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import {
|
||||
@@ -76,6 +78,25 @@ const navigateModule = (routeName: string): void => {
|
||||
const navigateReport = (table: string): void => {
|
||||
router.push({ name: 'AdminReports', params: { table } });
|
||||
};
|
||||
|
||||
/**
|
||||
* 进入报表/企微模块时自动展开子菜单,避免当前页在折叠状态下不可见。
|
||||
*/
|
||||
watch(
|
||||
isReportsActive,
|
||||
(active) => {
|
||||
if (active) navStore.reportsExpanded = true;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
isWecomActive,
|
||||
(active) => {
|
||||
if (active) navStore.wecomExpanded = true;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -35,9 +35,9 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
];
|
||||
|
||||
export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [
|
||||
'users',
|
||||
'agents',
|
||||
'usage_analysis',
|
||||
'chat_logs',
|
||||
'agents',
|
||||
'permission_requests',
|
||||
'general_feedbacks',
|
||||
'feedbacks',
|
||||
|
||||
@@ -232,8 +232,12 @@ onMounted(() => {
|
||||
<td class="px-4 py-4 align-middle">
|
||||
<div class="agent-list-cell">
|
||||
<p class="truncate text-sm font-semibold text-primary" :title="agent.name">{{ agent.name }}</p>
|
||||
<p class="truncate text-xs text-muted" :title="agent.description || ''">
|
||||
{{ agent.description || '—' }}
|
||||
<p
|
||||
v-if="agent.description"
|
||||
class="truncate text-xs text-muted"
|
||||
:title="agent.description"
|
||||
>
|
||||
{{ agent.description }}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
@@ -1,32 +1,80 @@
|
||||
/**
|
||||
* features/admin/modules/reports/ReportsPage.vue
|
||||
* 用途:管理后台报表独立页面(多表浏览、列筛选、聊天日志批量操作)。
|
||||
* 依赖:useReportsAdmin、DeleteConfirmDialog。
|
||||
* 逻辑:路由 /admin/reports/:table?;列宽由 composable 默认值与本地偏好控制。
|
||||
* 用途:管理后台报表独立页面(使用分析、应用运营、多表浏览与聊天日志批量操作)。
|
||||
* 依赖:useReportsAdmin、DeleteConfirmDialog、PaginationBar、lucide 图标。
|
||||
* 逻辑:路由 /admin/reports/:table?;分页统一复用 shared/PaginationBar。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BarChart2, Download, Settings2 } from 'lucide-vue-next';
|
||||
import { Activity, AlertTriangle, BarChart2, CircleHelp, Download, LineChart, Settings2, Trophy } from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import type { ApplicationSortKey } from '@/features/admin/types/report.types';
|
||||
import { useReportsAdmin } from './composables/useReportsAdmin';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 格式化使用分析「按用户统计」展示名:优先真实姓名,并附带用户名便于对照工号。
|
||||
* 核心逻辑:有 real_name 时显示「姓名(username)」,否则仅显示 username。
|
||||
* @param user - 报表 by_user 项
|
||||
* @returns 列表左侧展示文案
|
||||
*/
|
||||
function formatUsageUserLabel(user: { username: string; real_name?: string }): string {
|
||||
const realName = (user.real_name || '').trim();
|
||||
if (realName) {
|
||||
return `${realName}(${user.username})`;
|
||||
}
|
||||
return user.username;
|
||||
}
|
||||
|
||||
const {
|
||||
usageReport,
|
||||
usageRange,
|
||||
usageRangeOptions,
|
||||
usageUserTotal,
|
||||
usageUserTopLimit,
|
||||
usageActiveAgentCount,
|
||||
usageTrendMax,
|
||||
usageLowAgentItems,
|
||||
usageSpikeDayItems,
|
||||
usageTopUserItems,
|
||||
usageTopAgentItems,
|
||||
usageUserPage,
|
||||
usageUserPageSize,
|
||||
usageUserPageSizeOptions,
|
||||
usageUserTotal,
|
||||
usageUserTotalPages,
|
||||
usageUserTopLimit,
|
||||
usageUserPageButtons,
|
||||
goToUsageUserPage,
|
||||
prevUsageUserPage,
|
||||
nextUsageUserPage,
|
||||
usageAgentPage,
|
||||
usageAgentPageSize,
|
||||
usageAgentPageSizeOptions,
|
||||
usageAgentTotal,
|
||||
usageAgentTotalPages,
|
||||
goToUsageAgentPage,
|
||||
usageLowAgentMaxChats,
|
||||
usageLowAgentListLimit,
|
||||
usageSpikeDayMinChats,
|
||||
usageSpikeDayAvgMultiplier,
|
||||
usageSpikeDayListLimit,
|
||||
applicationRange,
|
||||
applicationStatus,
|
||||
applicationUsage,
|
||||
applicationQuery,
|
||||
applicationPage,
|
||||
applicationPageSize,
|
||||
applicationPageSizeOptions,
|
||||
applicationSummary,
|
||||
applicationItems,
|
||||
applicationTotal,
|
||||
applicationTotalPages,
|
||||
goToApplicationPage,
|
||||
onApplicationSortClick,
|
||||
getApplicationSortMark,
|
||||
handleApplicationSearchChange,
|
||||
openApplicationChatLogs,
|
||||
openApplicationPermissionRequests,
|
||||
isLoading,
|
||||
currentTable,
|
||||
tableData,
|
||||
@@ -44,6 +92,8 @@ const {
|
||||
reportPageSizeOptions,
|
||||
chatLogsColumns,
|
||||
chatLogsSortRules,
|
||||
isUsageAnalysisTable,
|
||||
isApplicationOpsTable,
|
||||
isChatLogsTable,
|
||||
showReportTable,
|
||||
visibleReportKeys,
|
||||
@@ -53,7 +103,6 @@ const {
|
||||
reportTotalPages,
|
||||
reportRangeStart,
|
||||
reportRangeEnd,
|
||||
reportPageButtons,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
loadAll,
|
||||
@@ -80,14 +129,93 @@ const {
|
||||
toggleAllReportRows,
|
||||
batchDeleteChatLogs,
|
||||
goToReportPage,
|
||||
prevReportPage,
|
||||
nextReportPage,
|
||||
confirmDelete,
|
||||
} = useReportsAdmin();
|
||||
|
||||
/** 应用运营可点击排序的列 */
|
||||
const applicationSortableKeys: ApplicationSortKey[] = [
|
||||
'name',
|
||||
'chat_count',
|
||||
'unique_users',
|
||||
'last_active_at',
|
||||
'authorized_users',
|
||||
'pending_requests',
|
||||
'avg_score',
|
||||
];
|
||||
|
||||
/**
|
||||
* 点击摘要卡快速切换「有使用 / 零使用」筛选。
|
||||
* @param usage - used | unused | all
|
||||
*/
|
||||
function setApplicationUsageFilter(usage: 'all' | 'used' | 'unused'): void {
|
||||
applicationUsage.value = usage;
|
||||
}
|
||||
|
||||
/** 低使用应用 / 异常高峰规则提示(点击 ? 以 tooltip 形式展示) */
|
||||
const showLowAgentHint = ref(false);
|
||||
const showSpikeDayHint = ref(false);
|
||||
|
||||
/**
|
||||
* 切换低使用应用选取规则 tooltip 显隐;打开时关闭另一侧提示。
|
||||
*/
|
||||
function toggleLowAgentHint(): void {
|
||||
showSpikeDayHint.value = false;
|
||||
showLowAgentHint.value = !showLowAgentHint.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换异常高峰日期选取规则 tooltip 显隐;打开时关闭另一侧提示。
|
||||
*/
|
||||
function toggleSpikeDayHint(): void {
|
||||
showLowAgentHint.value = false;
|
||||
showSpikeDayHint.value = !showSpikeDayHint.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 点击页面其他区域时关闭运营提醒规则 tooltip。
|
||||
*/
|
||||
function onDocumentClickCloseInsightHints(): void {
|
||||
showLowAgentHint.value = false;
|
||||
showSpikeDayHint.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算使用趋势柱状条高度(像素)。
|
||||
* 核心逻辑:按当前范围最大日对话量归一化;不用百分比——flex 子项无明确高度时 % 会塌成 0,导致「有日期无柱子」。
|
||||
* @param count - 单日对话量
|
||||
* @returns CSS height(px)
|
||||
*/
|
||||
function getUsageTrendBarHeight(count: number): string {
|
||||
/** 图表区 h-44(176px) 减去日期标签与间距后的可绘高度 */
|
||||
const plotMaxPx = 140;
|
||||
const minPx = 8;
|
||||
const max = Math.max(1, usageTrendMax.value);
|
||||
const px = Math.max(minPx, Math.round((count / max) * plotMaxPx));
|
||||
return `${px}px`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化趋势日期标签,供紧凑柱状图展示。
|
||||
* 核心逻辑:保留月日,避免长日期挤压图表横向空间。
|
||||
* @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(() => {
|
||||
document.addEventListener('click', onDocumentClickCloseInsightHints);
|
||||
void loadAll();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('click', onDocumentClickCloseInsightHints);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -116,13 +244,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">
|
||||
<div v-if="!isUsageAnalysisTable" 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')"
|
||||
@@ -166,8 +298,346 @@ 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-1.5 self-stretch"
|
||||
:title="`${day.date}: ${day.count}`"
|
||||
>
|
||||
<div
|
||||
class="mt-auto w-full max-w-8 rounded-t bg-brand-500/80"
|
||||
:style="{ height: getUsageTrendBarHeight(day.count) }"
|
||||
/>
|
||||
<span class="text-[10px] leading-none 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="flex items-center gap-1.5">
|
||||
<span class="text-xs font-semibold text-secondary">{{ t('admin.report.usageLowAgents') }}</span>
|
||||
<div class="relative inline-flex">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex rounded p-0.5 text-muted transition-colors hover:text-brand-600"
|
||||
:aria-expanded="showLowAgentHint"
|
||||
:aria-label="t('admin.report.usageLowAgentsHintAria')"
|
||||
@click.stop="toggleLowAgentHint"
|
||||
>
|
||||
<CircleHelp class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<div
|
||||
v-if="showLowAgentHint"
|
||||
role="tooltip"
|
||||
class="absolute left-1/2 top-full z-20 mt-1.5 w-56 -translate-x-1/2 rounded-lg border border-default bg-surface px-3 py-2 text-xs leading-relaxed text-secondary shadow-elevated"
|
||||
@click.stop
|
||||
>
|
||||
{{ t('admin.report.usageLowAgentsHint', { max: usageLowAgentMaxChats, limit: usageLowAgentListLimit }) }}
|
||||
</div>
|
||||
</div>
|
||||
</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="flex items-center gap-1.5">
|
||||
<span class="text-xs font-semibold text-secondary">{{ t('admin.report.usageSpikeDays') }}</span>
|
||||
<div class="relative inline-flex">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex rounded p-0.5 text-muted transition-colors hover:text-brand-600"
|
||||
:aria-expanded="showSpikeDayHint"
|
||||
:aria-label="t('admin.report.usageSpikeDaysHintAria')"
|
||||
@click.stop="toggleSpikeDayHint"
|
||||
>
|
||||
<CircleHelp class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<div
|
||||
v-if="showSpikeDayHint"
|
||||
role="tooltip"
|
||||
class="absolute left-1/2 top-full z-20 mt-1.5 w-60 -translate-x-1/2 rounded-lg border border-default bg-surface px-3 py-2 text-xs leading-relaxed text-secondary shadow-elevated"
|
||||
@click.stop
|
||||
>
|
||||
{{ t('admin.report.usageSpikeDaysHint', {
|
||||
min: usageSpikeDayMinChats,
|
||||
multiplier: usageSpikeDayAvgMultiplier,
|
||||
limit: usageSpikeDayListLimit,
|
||||
}) }}
|
||||
</div>
|
||||
</div>
|
||||
</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 flex flex-col">
|
||||
<div class="mb-4">
|
||||
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.byAgent') }}</h4>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.report.usageByAgentHint') }}</p>
|
||||
</div>
|
||||
<div class="space-y-3 flex-1 min-h-0 max-h-80 overflow-y-auto">
|
||||
<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 shrink-0">{{ 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>
|
||||
<PaginationBar
|
||||
class="mt-4"
|
||||
:page="usageAgentPage"
|
||||
v-model:page-size="usageAgentPageSize"
|
||||
:total="usageAgentTotal"
|
||||
:pages="usageAgentTotalPages"
|
||||
:page-size-options="[...usageAgentPageSizeOptions]"
|
||||
@update:page="goToUsageAgentPage"
|
||||
/>
|
||||
</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.usageByUserTopHint', { limit: usageUserTopLimit }) }}</p>
|
||||
</div>
|
||||
<div class="space-y-3 flex-1 min-h-0 max-h-80 overflow-y-auto">
|
||||
<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>
|
||||
<PaginationBar
|
||||
class="mt-4"
|
||||
:page="usageUserPage"
|
||||
v-model:page-size="usageUserPageSize"
|
||||
:total="usageUserTotal"
|
||||
:pages="usageUserTotalPages"
|
||||
:page-size-options="[...usageUserPageSizeOptions]"
|
||||
@update:page="goToUsageUserPage"
|
||||
/>
|
||||
</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 table-fixed border-collapse">
|
||||
<colgroup>
|
||||
<col class="w-[14%]" />
|
||||
<col class="w-[7%]" />
|
||||
<col class="w-[7%]" />
|
||||
<col class="w-[16%]" />
|
||||
<col class="w-[7%]" />
|
||||
<col class="w-[7%]" />
|
||||
<col class="w-[8%]" />
|
||||
<col class="w-[8%]" />
|
||||
<col class="w-[8%]" />
|
||||
<col class="w-[18%]" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
v-for="key in applicationSortableKeys"
|
||||
:key="`app-h-${key}`"
|
||||
class="px-3 py-3 text-left align-middle"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="admin-report-app-ops-sort-btn"
|
||||
@click="onApplicationSortClick(key)"
|
||||
>
|
||||
<span class="truncate">{{ 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 text-left align-middle">{{ t('admin.report.appOps.columns.category') }}</th>
|
||||
<th class="px-3 py-3 text-left align-middle">{{ t('admin.report.appOps.columns.is_active') }}</th>
|
||||
<th class="px-3 py-3 text-left align-middle">{{ 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 text-left align-middle font-medium text-secondary truncate" :title="row.name">{{ row.name }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums">{{ row.chat_count }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums">{{ row.unique_users }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono text-xs whitespace-nowrap">
|
||||
{{ row.last_active_at ? formatLocalDateTime(row.last_active_at) : '-' }}
|
||||
</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums">{{ row.authorized_users }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums">{{ row.pending_requests }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono 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-left align-middle text-secondary truncate">{{ row.category || '-' }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle">
|
||||
<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 text-left align-middle">
|
||||
<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>
|
||||
|
||||
<PaginationBar
|
||||
:page="applicationPage"
|
||||
v-model:page-size="applicationPageSize"
|
||||
:total="applicationTotal"
|
||||
:pages="applicationTotalPages"
|
||||
:page-size-options="[...applicationPageSizeOptions]"
|
||||
@update:page="goToApplicationPage"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showChatLogsColumnPanel"
|
||||
v-if="showChatLogsColumnPanel && !isApplicationOpsTable"
|
||||
class="admin-report-panel"
|
||||
>
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
@@ -245,7 +715,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>
|
||||
|
||||
@@ -327,147 +797,15 @@ onMounted(() => {
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div v-if="showReportTable" 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: reportTotalRows, page: reportCurrentPage, pages: reportTotalPages }) }}
|
||||
</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="reportPageSize"
|
||||
class="admin-table-filter-input appearance-none pl-2 pr-7 py-1 text-xs leading-5"
|
||||
>
|
||||
<option v-for="size in reportPageSizeOptions" :key="`page-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="prevReportPage"
|
||||
:disabled="reportCurrentPage <= 1"
|
||||
class="admin-report-page-btn"
|
||||
>
|
||||
{{ t('admin.report.prevPage') }}
|
||||
</button>
|
||||
<button
|
||||
v-for="btn in reportPageButtons"
|
||||
:key="`report-page-btn-${btn}`"
|
||||
:disabled="btn === -1"
|
||||
@click="btn !== -1 && goToReportPage(btn)"
|
||||
class="admin-report-page-btn"
|
||||
:class="btn === -1
|
||||
? 'border-transparent text-muted cursor-default opacity-100'
|
||||
: btn === reportCurrentPage
|
||||
? 'admin-report-page-btn--active'
|
||||
: ''"
|
||||
>
|
||||
{{ btn === -1 ? '...' : btn }}
|
||||
</button>
|
||||
<button
|
||||
@click="nextReportPage"
|
||||
:disabled="reportCurrentPage >= reportTotalPages"
|
||||
class="admin-report-page-btn"
|
||||
>
|
||||
{{ t('admin.report.nextPage') }}
|
||||
</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 p-3 bg-surface-soft rounded-xl">
|
||||
<span class="font-medium text-secondary">{{ u.username }}</span>
|
||||
<span class="admin-report-badge admin-report-badge--info font-bold">{{ 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>
|
||||
<PaginationBar
|
||||
v-if="showReportTable"
|
||||
v-model:page="reportCurrentPage"
|
||||
v-model:page-size="reportPageSize"
|
||||
:total="reportTotalRows"
|
||||
:pages="reportTotalPages"
|
||||
:page-size-options="[...reportPageSizeOptions]"
|
||||
@update:page="goToReportPage"
|
||||
/>
|
||||
</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;使用分析按用户服务端分页、按应用前端分页,均复用 PaginationBar。
|
||||
*/
|
||||
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,24 @@ export function useReportsAdmin() {
|
||||
const usageRange = ref<UsageRangeKey>('30d');
|
||||
const usageRangeOptions: UsageRangeKey[] = ['7d', '30d', '90d', '180d', '365d'];
|
||||
|
||||
/** 按应用统计:前端分页(后端已返回范围内全部应用) */
|
||||
const usageAgentPage = ref(1);
|
||||
const usageAgentPageSize = ref(10);
|
||||
const usageAgentPageSizeOptions = [5, 10, 20, 50];
|
||||
|
||||
/** 应用运营看板状态(替换原 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 +122,179 @@ 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 USAGE_LOW_AGENT_MAX_CHATS = 2;
|
||||
/** 低使用应用提醒最多展示条数 */
|
||||
const USAGE_LOW_AGENT_LIST_LIMIT = 5;
|
||||
/** 异常高峰:单日对话量下限(与日均倍数取较大者) */
|
||||
const USAGE_SPIKE_DAY_MIN_CHATS = 5;
|
||||
/** 异常高峰:相对日均的倍数阈值 */
|
||||
const USAGE_SPIKE_DAY_AVG_MULTIPLIER = 2;
|
||||
/** 异常高峰日期最多展示条数 */
|
||||
const USAGE_SPIKE_DAY_LIST_LIMIT = 3;
|
||||
const usageLowAgentItems = computed(() =>
|
||||
[...(usageReport.value?.by_agent || [])]
|
||||
.filter((item) => item.count <= USAGE_LOW_AGENT_MAX_CHATS)
|
||||
.sort((a, b) => a.count - b.count || a.agent.localeCompare(b.agent))
|
||||
.slice(0, USAGE_LOW_AGENT_LIST_LIMIT),
|
||||
);
|
||||
const 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;
|
||||
// 高峰阈值:不低于下限,且不低于日均 × 倍数
|
||||
const threshold = Math.max(USAGE_SPIKE_DAY_MIN_CHATS, average * USAGE_SPIKE_DAY_AVG_MULTIPLIER);
|
||||
return days
|
||||
.filter((item) => item.count >= threshold)
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, USAGE_SPIKE_DAY_LIST_LIMIT);
|
||||
});
|
||||
const usageTopUserItems = computed(() => usageReport.value?.by_user ?? []);
|
||||
const usageAgentTotal = computed(() => usageReport.value?.by_agent.length ?? 0);
|
||||
const usageAgentTotalPages = computed(() => {
|
||||
const size = Math.max(1, Number(usageAgentPageSize.value) || 10);
|
||||
return Math.max(1, Math.ceil(usageAgentTotal.value / size));
|
||||
});
|
||||
/**
|
||||
* 按应用统计当前页数据(对话量降序全集上的偏移分页)。
|
||||
*/
|
||||
const usageTopAgentItems = computed(() => {
|
||||
const list = usageReport.value?.by_agent ?? [];
|
||||
const size = Math.max(1, Number(usageAgentPageSize.value) || 10);
|
||||
const page = Math.min(Math.max(1, usageAgentPage.value), usageAgentTotalPages.value);
|
||||
const start = (page - 1) * size;
|
||||
return list.slice(start, start + size);
|
||||
});
|
||||
const usageUserPageButtons = computed(() =>
|
||||
buildOffsetPageButtons(usageUserPage.value, usageUserTotalPages.value),
|
||||
);
|
||||
@@ -111,6 +306,14 @@ export function useReportsAdmin() {
|
||||
const prevUsageUserPage = () => goToUsageUserPage(usageUserPage.value - 1);
|
||||
const nextUsageUserPage = () => goToUsageUserPage(usageUserPage.value + 1);
|
||||
|
||||
/**
|
||||
* 跳转按应用统计分页(纯前端切片,无需重新请求)。
|
||||
* @param page - 目标页码
|
||||
*/
|
||||
const goToUsageAgentPage = (page: number): void => {
|
||||
usageAgentPage.value = Math.min(Math.max(1, page), usageAgentTotalPages.value);
|
||||
};
|
||||
|
||||
const loadReports = async (): Promise<void> => {
|
||||
await loadUsageReport();
|
||||
};
|
||||
@@ -145,7 +348,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 +383,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 +461,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 +478,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 +504,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 +585,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 +613,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 +646,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 +1059,7 @@ const batchDeleteChatLogs = async () => {
|
||||
};
|
||||
|
||||
watch(currentTable, async () => {
|
||||
columnFilters.value = {}; // Reset filters on table change
|
||||
applyRouteQueryFilters();
|
||||
chatLogsColumns.value = [];
|
||||
selectedReportRowIds.value = [];
|
||||
showChatLogsColumnPanel.value = false;
|
||||
@@ -827,7 +1067,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');
|
||||
}
|
||||
});
|
||||
@@ -862,9 +1102,27 @@ watch(usageUserPageSize, () => {
|
||||
|
||||
watch(usageRange, () => {
|
||||
usageUserPage.value = 1;
|
||||
usageAgentPage.value = 1;
|
||||
void loadUsageReport();
|
||||
});
|
||||
|
||||
watch(usageAgentPageSize, () => {
|
||||
usageAgentPage.value = 1;
|
||||
});
|
||||
|
||||
watch(usageAgentTotalPages, (pages) => {
|
||||
if (usageAgentPage.value > pages) {
|
||||
usageAgentPage.value = pages;
|
||||
}
|
||||
});
|
||||
|
||||
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 +1135,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 +1160,50 @@ watch([reportPageSize, sortedTableData], () => {
|
||||
usageUserTotal,
|
||||
usageUserTotalPages,
|
||||
usageUserTopLimit,
|
||||
usageActiveAgentCount,
|
||||
usageTrendMax,
|
||||
usageLowAgentMaxChats: USAGE_LOW_AGENT_MAX_CHATS,
|
||||
usageLowAgentListLimit: USAGE_LOW_AGENT_LIST_LIMIT,
|
||||
usageSpikeDayMinChats: USAGE_SPIKE_DAY_MIN_CHATS,
|
||||
usageSpikeDayAvgMultiplier: USAGE_SPIKE_DAY_AVG_MULTIPLIER,
|
||||
usageSpikeDayListLimit: USAGE_SPIKE_DAY_LIST_LIMIT,
|
||||
usageLowAgentItems,
|
||||
usageSpikeDayItems,
|
||||
usageTopUserItems,
|
||||
usageTopAgentItems,
|
||||
usageAgentPage,
|
||||
usageAgentPageSize,
|
||||
usageAgentPageSizeOptions,
|
||||
usageAgentTotal,
|
||||
usageAgentTotalPages,
|
||||
goToUsageAgentPage,
|
||||
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 +1223,8 @@ watch([reportPageSize, sortedTableData], () => {
|
||||
chatLogsSortRules,
|
||||
reportHeaderSort,
|
||||
draggingColumnKey,
|
||||
isUsageAnalysisTable,
|
||||
isApplicationOpsTable,
|
||||
isChatLogsTable,
|
||||
showReportTable,
|
||||
visibleReportKeys,
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* features/admin/stores/admin-nav.store.ts
|
||||
* 管理后台导航 UI 状态(侧栏折叠、报表展开、角标)。
|
||||
* 管理后台导航 UI 状态(侧栏折叠、报表/企微子菜单展开、角标)。
|
||||
*
|
||||
* 角标数据来自 GET /api/admin/dashboard/badges,在 store 内做 TTL 缓存与 in-flight 去重,
|
||||
* 避免切换 admin 子路由时重复请求(AdminLayout 挂载一次即可)。
|
||||
* 报表与企业微信子菜单默认折叠,进入对应模块时由 AdminNav 展开。
|
||||
*/
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
@@ -15,8 +16,10 @@ const BADGE_CACHE_TTL_MS = 60_000;
|
||||
|
||||
export const useAdminNavStore = defineStore('adminNav', () => {
|
||||
const sidebarCollapsed = ref(false);
|
||||
const reportsExpanded = ref(true);
|
||||
const wecomExpanded = ref(true);
|
||||
/** 数据报表子菜单:默认折叠 */
|
||||
const reportsExpanded = ref(false);
|
||||
/** 企业微信子菜单:默认折叠 */
|
||||
const wecomExpanded = ref(false);
|
||||
/** 「用户审批」导航角标:pending 注册用户数 */
|
||||
const pendingApprovalsCount = ref(0);
|
||||
/** 「权限申请」导航角标:pending 权限申请数 */
|
||||
|
||||
@@ -20,6 +20,7 @@ export type AdminModuleId =
|
||||
| 'reports';
|
||||
|
||||
export type AdminReportTableId =
|
||||
| 'usage_analysis'
|
||||
| 'users'
|
||||
| 'agents'
|
||||
| 'chat_logs'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/types/report.types.ts
|
||||
* 用途:报表模块类型(使用分析、列配置、排序规则)。
|
||||
* 用途:报表模块类型(使用分析、应用运营、列配置、排序规则)。
|
||||
* 依赖:无。
|
||||
* 逻辑:useReportsAdmin / admin.api 共用。
|
||||
*/
|
||||
@@ -12,8 +12,9 @@ export interface UsageReport {
|
||||
total: number;
|
||||
/** 当前统计时间范围 */
|
||||
range?: UsageRangeKey;
|
||||
by_user: { username: string; count: number }[];
|
||||
by_user: { username: string; real_name?: string; count: number }[];
|
||||
by_agent: { agent: string; count: number }[];
|
||||
/** 当前范围内按自然日聚合的对话趋势,用于使用分析柱状图。 */
|
||||
by_day?: { date: string; count: number }[];
|
||||
user_total: number;
|
||||
user_page: number;
|
||||
@@ -22,6 +23,62 @@ export interface UsageReport {
|
||||
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 {
|
||||
key: string;
|
||||
visible: boolean;
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/auth/components/LoginPage.vue
|
||||
* 登录页主内容:营销文案、公告列表与用户名/密码/企微登录表单。
|
||||
*
|
||||
* 用途:渲染登录页主内容,包括营销文案、公告列表、用户名/密码表单以及“记住我”入口。
|
||||
* 依赖:LOGIN_KEY provide、AnnouncementCardCarousel、共享登录背景与按钮样式。
|
||||
* 逻辑:登录表单仍以密码登录和企微登录为主;“记住我”按当前业务口径负责账号密码回填与登录态持久化。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { Bot, Megaphone } from 'lucide-vue-next';
|
||||
@@ -68,11 +71,42 @@ const lk = inject(LOGIN_KEY)! as any;
|
||||
<div class="space-y-5">
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs font-semibold text-primary uppercase ml-1">{{ $t('login.username') }}</label>
|
||||
<input v-model="lk.loginUsername" type="text" class="input-field" :placeholder="$t('login.placeholder.username')" @keyup.enter="lk.handleLogin" />
|
||||
<input
|
||||
v-model="lk.loginUsername"
|
||||
type="text"
|
||||
name="username"
|
||||
autocomplete="username"
|
||||
class="input-field"
|
||||
:placeholder="$t('login.placeholder.username')"
|
||||
@keyup.enter="lk.handleLogin"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs font-semibold text-primary uppercase ml-1">{{ $t('login.password') }}</label>
|
||||
<input v-model="lk.loginPassword" type="password" class="input-field" :placeholder="$t('login.placeholder.password')" @keyup.enter="lk.handleLogin" />
|
||||
<input
|
||||
v-model="lk.loginPassword"
|
||||
type="password"
|
||||
name="current-password"
|
||||
autocomplete="current-password"
|
||||
class="input-field"
|
||||
:placeholder="$t('login.placeholder.password')"
|
||||
@keyup.enter="lk.handleLogin"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between gap-4 text-sm">
|
||||
<label class="inline-flex items-center gap-2 text-secondary cursor-pointer select-none">
|
||||
<input
|
||||
v-model="lk.rememberMe"
|
||||
type="checkbox"
|
||||
class="h-4 w-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500"
|
||||
@change="lk.handleRememberMeChange"
|
||||
/>
|
||||
<span>{{ $t('login.rememberMe') }}</span>
|
||||
</label>
|
||||
<button type="button" @click="lk.openForgotPasswordModal" class="text-sm text-secondary hover:text-brand-700 transition-colors">
|
||||
{{ $t('login.forgotPassword') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button type="button" @click="lk.handleLogin" class="btn-primary w-full py-3 text-base shadow-brand-500/40 hover:shadow-brand-500/50 transform hover:-translate-y-0.5 transition-all mt-4">
|
||||
@@ -89,11 +123,7 @@ const lk = inject(LOGIN_KEY)! as any;
|
||||
{{ lk.isWecomLoggingIn ? $t('login.wecomConnecting') : $t('login.wecomLogin') }}
|
||||
</button>
|
||||
|
||||
<div class="flex justify-between items-center pt-4 mt-2 border-t border-subtle/50">
|
||||
<button type="button" @click="lk.openForgotPasswordModal" class="text-sm text-secondary hover:text-brand-700 transition-colors">
|
||||
{{ $t('login.forgotPassword') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="pt-4 mt-2 border-t border-subtle/50"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/auth/composables/useLogin.ts
|
||||
* 登录页编排层:组合认证、公告展示与 OAuth 回调,provide 给 LoginView 子组件。
|
||||
*/
|
||||
@@ -62,6 +62,7 @@ export function useLogin() {
|
||||
return;
|
||||
}
|
||||
|
||||
loginAuth.hydrateRememberedLoginState();
|
||||
await landing.fetchPublicAgents();
|
||||
landing.isLoading.value = false;
|
||||
});
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
/**
|
||||
/**
|
||||
* features/auth/composables/useLoginAuth.ts
|
||||
* 登录表单、企微/Casdoor OAuth 回调、注册与找回密码逻辑。
|
||||
*
|
||||
* 用途:封装登录表单、记住我偏好、企微/Casdoor OAuth 回调、注册与找回密码逻辑。
|
||||
* 依赖:shared/utils/auth、requestJson、WeCom/Casdoor 工具函数。
|
||||
* 逻辑:密码登录成功后根据“记住我”同步本地登录态与 remembered username/password;
|
||||
* OAuth 登录仅负责认证,不自动写入 remember 偏好,避免用户未明确选择时持久化登录页账号。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { config } from '@/config';
|
||||
@@ -10,7 +14,14 @@ import {
|
||||
normalizeWecomMatchRules,
|
||||
type WecomMatchField,
|
||||
} from '@/shared/utils/wecom';
|
||||
import { saveAuthUser } from '@/shared/utils/auth';
|
||||
import {
|
||||
clearRememberedLoginProfile,
|
||||
getRememberedLoginPreference,
|
||||
getRememberedLoginProfile,
|
||||
saveAuthUser,
|
||||
saveRememberedLoginPreference,
|
||||
saveRememberedLoginProfile,
|
||||
} from '@/shared/utils/auth';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
|
||||
import type { WecomBindPromptState, WecomLoginDialogContent } from '@/features/workspace/types/workspace.types';
|
||||
@@ -55,10 +66,47 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
window.history.replaceState({}, '', nextUrl);
|
||||
};
|
||||
|
||||
/**
|
||||
* 初始化登录页 remember 状态。
|
||||
* AI 触发时机:登录页首次渲染且用户尚未登录时使用;若用户上次勾选“记住我”,则回填 remembered username/password。
|
||||
*/
|
||||
const hydrateRememberedLoginState = () => {
|
||||
rememberMe.value = getRememberedLoginPreference();
|
||||
if (!rememberMe.value) return;
|
||||
const profile = getRememberedLoginProfile();
|
||||
if (profile?.username) {
|
||||
loginUsername.value = profile.username;
|
||||
loginPassword.value = profile.password;
|
||||
}
|
||||
};
|
||||
|
||||
const persistLoginUser = (user: Record<string, unknown>) => {
|
||||
saveAuthUser({ ...(user || {}) }, rememberMe.value);
|
||||
};
|
||||
|
||||
/**
|
||||
* 持久化登录页 remember 偏好。
|
||||
* AI 触发时机:仅当密码登录成功后执行;勾选时保存 remembered username/password,未勾选时清理本地自动回填数据。
|
||||
*/
|
||||
const persistRememberedLoginState = () => {
|
||||
if (!rememberMe.value) {
|
||||
clearRememberedLoginProfile();
|
||||
return;
|
||||
}
|
||||
saveRememberedLoginPreference(true);
|
||||
saveRememberedLoginProfile(loginUsername.value.trim(), loginPassword.value);
|
||||
};
|
||||
|
||||
/**
|
||||
* 处理“记住我”勾选变化。
|
||||
* AI 触发时机:用户在登录页手动取消勾选时,必须立即清理 remembered username/password,确保下次进入不再自动回填。
|
||||
*/
|
||||
const handleRememberMeChange = () => {
|
||||
if (!rememberMe.value) {
|
||||
clearRememberedLoginProfile();
|
||||
}
|
||||
};
|
||||
|
||||
const openForgotPasswordModal = () => {
|
||||
forgotPasswordForm.value = {
|
||||
employee_id: '',
|
||||
@@ -135,6 +183,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
});
|
||||
|
||||
persistLoginUser(user);
|
||||
persistRememberedLoginState();
|
||||
await completePasswordLogin();
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
@@ -398,6 +447,8 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
loginUsername,
|
||||
loginPassword,
|
||||
rememberMe,
|
||||
hydrateRememberedLoginState,
|
||||
handleRememberMeChange,
|
||||
showRegisterModal,
|
||||
showForgotPasswordModal,
|
||||
openForgotPasswordModal,
|
||||
|
||||
@@ -28,6 +28,12 @@ function normalizeAssetHistoryErrorMessage(message: string): string {
|
||||
if (lowerCaseMessage.includes('asset history share is not configured')) {
|
||||
return '当前系统暂未配置资产履历文件目录,暂时无法查看履历,请联系管理员处理。';
|
||||
}
|
||||
if (lowerCaseMessage.includes('asset history share is unreachable')) {
|
||||
return '当前环境暂时无法访问资产履历共享盘,请联系管理员检查测试环境共享盘挂载或访问权限。';
|
||||
}
|
||||
if (lowerCaseMessage.includes('asset history share is invalid')) {
|
||||
return '当前环境的资产履历目录配置无效,请联系管理员检查共享盘目录配置。';
|
||||
}
|
||||
return normalizedMessage || '检索资产履历失败';
|
||||
}
|
||||
|
||||
|
||||
@@ -386,26 +386,6 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
const target = event.target as HTMLElement | null;
|
||||
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
|
||||
const rawHref = anchor?.getAttribute('href') || '';
|
||||
// #region debug-point A:asset-history-anchor-click
|
||||
if (rawHref.startsWith('#asset-history?')) {
|
||||
fetch('http://127.0.0.1:7777/event', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
sessionId: 'asset-history-click',
|
||||
runId: 'pre-fix',
|
||||
hypothesisId: 'A',
|
||||
location: 'frontend/useChatPageMarkdown.ts',
|
||||
msg: '[DEBUG] asset history anchor clicked',
|
||||
data: {
|
||||
href: rawHref,
|
||||
tagName: target?.tagName || '',
|
||||
anchorText: String(anchor?.textContent || '').trim(),
|
||||
},
|
||||
ts: Date.now(),
|
||||
}),
|
||||
}).catch(() => {});
|
||||
}
|
||||
// #endregion
|
||||
if (rawHref.startsWith('#asset-history?')) {
|
||||
event.preventDefault();
|
||||
const params = new URLSearchParams(rawHref.slice('#asset-history?'.length));
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
/**
|
||||
* features/kb/utils/kb-display.utils.ts
|
||||
* 文档标题、时间、文件大小与状态徽标等纯展示工具。
|
||||
* 用途:文档标题、时间、文件大小与状态徽标等纯展示工具。
|
||||
* 依赖:kb.api 类型、kb-i18n.types、shared/utils/dateTime(UTC 时间戳本地化)。
|
||||
* 逻辑:KbWorkspace / KbAdminPanel 等调用;时间统一走 formatLocalDateTime,避免无时区后缀被当成本地时间导致差 8 小时。
|
||||
*/
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import type { KbDocumentItem } from '../api/kb.api';
|
||||
import type { KbTranslateFn } from './kb-i18n.types';
|
||||
|
||||
/**
|
||||
* 格式化知识库时间戳为本地时区 `YYYY-MM-DD HH:mm:ss`。
|
||||
* 核心逻辑:委托 formatLocalDateTime;后端 isoformat() 常无 Z,按 UTC 解析后再转浏览器本地时区。
|
||||
* @param value - API 返回的时间字符串
|
||||
* @returns 本地展示文案;空值返回 `--`
|
||||
*/
|
||||
export const formatDateTime = (value?: string | null) => {
|
||||
if (!value) return '--';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
const formatted = formatLocalDateTime(value);
|
||||
return formatted === '-' ? '--' : formatted;
|
||||
};
|
||||
|
||||
export const formatFileSize = (value?: number | null) => {
|
||||
|
||||
@@ -761,7 +761,7 @@
|
||||
},
|
||||
"report": {
|
||||
"title": "Data Reports: {table}",
|
||||
"subtitle": "Raw data view and statistics",
|
||||
"subtitle": "Operational analytics and detail tracing",
|
||||
"export": "Export Excel",
|
||||
"columnSettings": "Column Settings",
|
||||
"showSelection": "Show Selection",
|
||||
@@ -878,8 +878,9 @@
|
||||
"general_feedbacks": "Feedback",
|
||||
"feedbacks": "Answer Rating",
|
||||
"departments": "Departments",
|
||||
"agents": "Agents",
|
||||
"permission_requests": "Permission Requests"
|
||||
"agents": "App Ops",
|
||||
"permission_requests": "Permission Requests",
|
||||
"usage_analysis": "Usage Analytics"
|
||||
},
|
||||
"feedbackValues": {
|
||||
"types": {
|
||||
@@ -898,6 +899,59 @@
|
||||
"chat": "Chat",
|
||||
"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",
|
||||
"usageLowAgentsHint": "Apps with ≤ {max} chats in the selected range, sorted ascending, showing up to {limit}.",
|
||||
"usageLowAgentsHintAria": "Show low-usage app selection rule",
|
||||
"usageLowAgentsEmpty": "No low-usage apps in this range",
|
||||
"usageSpikeDays": "Spike days",
|
||||
"usageSpikeDaysHint": "A day is a spike when chats ≥ max({min}, daily average × {multiplier}); sorted descending, showing up to {limit} days.",
|
||||
"usageSpikeDaysHintAria": "Show spike day selection rule",
|
||||
"usageSpikeDaysEmpty": "No clear spikes in this range",
|
||||
"usageByAgentEmpty": "No app chat activity yet",
|
||||
"usageByAgentHint": "All apps with chats in range, with pagination",
|
||||
"usageActiveUserHint": "Top 50 users by chat volume, with pagination",
|
||||
"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": {
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
"accountDisabled": "Account is disabled",
|
||||
"dbConnectionFailed": "Database connection failed. Please check if the database service is running.",
|
||||
"internalError": "Internal server error. Please try again later.",
|
||||
"rememberMe": "Remember me for 30 days",
|
||||
"rememberMe": "Remember me",
|
||||
"forgotPasswordDesc": "Enter your employee ID and username; a reset link will be sent to your WeCom",
|
||||
"findPassword": "Find Password",
|
||||
"employeeIdRequired": "Please enter employee ID",
|
||||
|
||||
@@ -766,7 +766,7 @@
|
||||
},
|
||||
"report": {
|
||||
"title": "รายงานข้อมูล: {table}",
|
||||
"subtitle": "มุมมองข้อมูลดิบและสถิติ",
|
||||
"subtitle": "การวิเคราะห์การใช้งานและรายละเอียดย้อนหลัง",
|
||||
"export": "ส่งออก Excel",
|
||||
"columnSettings": "ตั้งค่าคอลัมน์",
|
||||
"showSelection": "แสดงการเลือก",
|
||||
@@ -797,7 +797,7 @@
|
||||
"exitFullscreen": "ออกจากเต็มหน้าจอ",
|
||||
"noData": "ไม่มีข้อมูลสำหรับ {table}",
|
||||
"noFilterResults": "ไม่พบข้อมูลที่ตรงกับเงื่อนไข โปรดปรับตัวกรอง",
|
||||
"usage": "การวิเคราะห์การใช้งาน",
|
||||
"usage": "วิเคราะห์การใช้งาน",
|
||||
"usageRangeLabel": "ช่วงเวลา",
|
||||
"usageRanges": {
|
||||
"7d": "7 วันล่าสุด",
|
||||
@@ -880,8 +880,62 @@
|
||||
"general_feedbacks": "ข้อเสนอแนะทั่วไป",
|
||||
"feedbacks": "การประเมินคำตอบ",
|
||||
"departments": "แผนก",
|
||||
"agents": "ตัวแทน",
|
||||
"permission_requests": "คำขอสิทธิ์"
|
||||
"agents": "แอปปฏิบัติการ",
|
||||
"permission_requests": "คำขอสิทธิ์",
|
||||
"usage_analysis": "วิเคราะห์การใช้งาน"
|
||||
},
|
||||
"usageIntro": "ดูแนวโน้มการเรียกใช้แอป AI ผู้ใช้ที่ใช้งาน แอปที่ใช้น้อย และช่วงพีคผิดปกติ",
|
||||
"usageTotalSessions": "จำนวนแชทรวม",
|
||||
"usageActiveUsers": "ผู้ใช้ที่ใช้งาน",
|
||||
"usageActiveAgents": "แอปที่ใช้งาน",
|
||||
"usageTrend": "แนวโน้มล่าสุด",
|
||||
"usageTrendEmpty": "ยังไม่มีข้อมูลแนวโน้ม",
|
||||
"usageInsights": "การแจ้งเตือนการดำเนินงาน",
|
||||
"usageLowAgents": "แอปที่ใช้น้อย",
|
||||
"usageLowAgentsHint": "แอปที่มีแชท ≤ {max} ครั้งในช่วงที่เลือก เรียงจากน้อยไปมาก แสดงสูงสุด {limit} รายการ",
|
||||
"usageLowAgentsHintAria": "ดูเกณฑ์การคัดเลือกแอปที่ใช้น้อย",
|
||||
"usageLowAgentsEmpty": "ไม่มีแอปที่ใช้น้อยในช่วงนี้",
|
||||
"usageSpikeDays": "วันที่มีการใช้งานพุ่งสูง",
|
||||
"usageSpikeDaysHint": "ถือว่าเป็นพีคเมื่อแชทต่อวัน ≥ max({min}, ค่าเฉลี่ยรายวัน × {multiplier}) เรียงจากมากไปน้อย แสดงสูงสุด {limit} วัน",
|
||||
"usageSpikeDaysHintAria": "ดูเกณฑ์การคัดเลือกวันพีค",
|
||||
"usageSpikeDaysEmpty": "ไม่พบช่วงพีคที่ชัดเจนในช่วงนี้",
|
||||
"usageByAgentEmpty": "ยังไม่มีประวัติแชทของแอป",
|
||||
"usageByAgentHint": "แสดงแอปทั้งหมดที่มีแชทในช่วงนี้ พร้อมแบ่งหน้า",
|
||||
"usageActiveUserHint": "ผู้ใช้ 50 อันดับแรกตามปริมาณแชท พร้อมแบ่งหน้า",
|
||||
"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": {
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"loginRequired": "กรุณาเข้าสู่ระบบก่อนเริ่มการสนทนา",
|
||||
"requestFailed": "คำขอเข้าสู่ระบบล้มเหลว",
|
||||
"forgotPassword": "ลืมรหัสผ่าน?",
|
||||
"rememberMe": "จดจำการเข้าสู่ระบบ 30 วัน",
|
||||
"rememberMe": "จดจำฉัน",
|
||||
"announcements": "ประกาศ",
|
||||
"forgotPasswordDesc": "กรอกรหัสพนักงานและชื่อผู้ใช้ ลิงก์รีเซ็ตจะถูกส่งไปยัง WeCom ของคุณ",
|
||||
"findPassword": "ค้นหารหัสผ่าน",
|
||||
|
||||
@@ -762,7 +762,7 @@
|
||||
},
|
||||
"report": {
|
||||
"title": "数据报表: {table}",
|
||||
"subtitle": "原始数据与统计视图",
|
||||
"subtitle": "运营分析与明细追溯",
|
||||
"export": "导出 Excel",
|
||||
"columnSettings": "列设置",
|
||||
"showSelection": "显示选择",
|
||||
@@ -876,8 +876,62 @@
|
||||
"general_feedbacks": "意见反馈",
|
||||
"feedbacks": "回答评价",
|
||||
"departments": "部门",
|
||||
"agents": "应用",
|
||||
"permission_requests": "权限申请"
|
||||
"agents": "应用运营",
|
||||
"permission_requests": "权限申请",
|
||||
"usage_analysis": "使用分析"
|
||||
},
|
||||
"usageIntro": "查看 AI 应用调用趋势、活跃用户、低使用应用与异常高峰。",
|
||||
"usageTotalSessions": "对话总量",
|
||||
"usageActiveUsers": "活跃用户",
|
||||
"usageActiveAgents": "活跃应用",
|
||||
"usageTrend": "近段趋势",
|
||||
"usageTrendEmpty": "暂无趋势数据",
|
||||
"usageInsights": "运营提醒",
|
||||
"usageLowAgents": "低使用应用",
|
||||
"usageLowAgentsHint": "统计范围内对话次数 ≤ {max} 的应用,按对话量升序最多展示 {limit} 个。",
|
||||
"usageLowAgentsHintAria": "查看低使用应用选取规则",
|
||||
"usageLowAgentsEmpty": "当前范围内暂无低使用应用",
|
||||
"usageSpikeDays": "异常高峰日期",
|
||||
"usageSpikeDaysHint": "单日对话量 ≥ max({min}, 日均 × {multiplier}) 视为高峰,按对话量降序最多展示 {limit} 天。",
|
||||
"usageSpikeDaysHintAria": "查看异常高峰日期选取规则",
|
||||
"usageSpikeDaysEmpty": "当前范围内未发现明显高峰",
|
||||
"usageByAgentEmpty": "暂无应用对话记录",
|
||||
"usageByAgentHint": "展示范围内全部有对话的应用,支持翻页",
|
||||
"usageActiveUserHint": "对话量前 50 名用户,支持翻页",
|
||||
"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": {
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
"accountDisabled": "账号已禁用",
|
||||
"dbConnectionFailed": "数据库连接失败,请检查数据库服务是否运行。",
|
||||
"internalError": "服务器内部错误,请稍后重试。",
|
||||
"rememberMe": "30天内免登录",
|
||||
"rememberMe": "记住我",
|
||||
"forgotPasswordDesc": "输入工号和用户名,重置链接将发送到您的企业微信",
|
||||
"findPassword": "找回密码",
|
||||
"employeeIdRequired": "请输入工号",
|
||||
|
||||
@@ -765,8 +765,8 @@
|
||||
"reject": "拒絕"
|
||||
},
|
||||
"report": {
|
||||
"title": "數據報表: {table}",
|
||||
"subtitle": "原始數據與統計視圖",
|
||||
"title": "資料報表: {table}",
|
||||
"subtitle": "營運分析與明細追溯",
|
||||
"export": "導出 Excel",
|
||||
"columnSettings": "列設置",
|
||||
"showSelection": "顯示選擇",
|
||||
@@ -880,8 +880,62 @@
|
||||
"general_feedbacks": "意見反饋",
|
||||
"feedbacks": "回答評價",
|
||||
"departments": "部門",
|
||||
"agents": "應用",
|
||||
"permission_requests": "權限申請"
|
||||
"agents": "應用運營",
|
||||
"permission_requests": "權限申請",
|
||||
"usage_analysis": "使用分析"
|
||||
},
|
||||
"usageIntro": "查看 AI 應用呼叫趨勢、活躍使用者、低使用應用與異常高峰。",
|
||||
"usageTotalSessions": "對話總量",
|
||||
"usageActiveUsers": "活躍使用者",
|
||||
"usageActiveAgents": "活躍應用",
|
||||
"usageTrend": "近段趨勢",
|
||||
"usageTrendEmpty": "暫無趨勢資料",
|
||||
"usageInsights": "營運提醒",
|
||||
"usageLowAgents": "低使用應用",
|
||||
"usageLowAgentsHint": "統計範圍內對話次數 ≤ {max} 的應用,按對話量升序最多展示 {limit} 個。",
|
||||
"usageLowAgentsHintAria": "查看低使用應用選取規則",
|
||||
"usageLowAgentsEmpty": "目前範圍內暫無低使用應用",
|
||||
"usageSpikeDays": "異常高峰日期",
|
||||
"usageSpikeDaysHint": "單日對話量 ≥ max({min}, 日均 × {multiplier}) 視為高峰,按對話量降序最多展示 {limit} 天。",
|
||||
"usageSpikeDaysHintAria": "查看異常高峰日期選取規則",
|
||||
"usageSpikeDaysEmpty": "目前範圍內未發現明顯高峰",
|
||||
"usageByAgentEmpty": "暫無應用對話記錄",
|
||||
"usageByAgentHint": "展示範圍內全部有對話的應用,支援翻頁",
|
||||
"usageActiveUserHint": "對話量前 50 名使用者,支援翻頁",
|
||||
"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": {
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"loginRequired": "請先登錄後再進入對話",
|
||||
"requestFailed": "登錄請求失敗",
|
||||
"forgotPassword": "忘記密碼?",
|
||||
"rememberMe": "30天內免登入",
|
||||
"rememberMe": "記住我",
|
||||
"announcements": "公告",
|
||||
"forgotPasswordDesc": "輸入工號與用戶名,重設連結將發送到您的企業微信",
|
||||
"findPassword": "找回密碼",
|
||||
|
||||
@@ -24,7 +24,7 @@ const props = withDefaults(defineProps<{
|
||||
activeAgentId: null,
|
||||
compact: false,
|
||||
showSearch: true,
|
||||
defaultExpanded: true,
|
||||
defaultExpanded: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -64,7 +64,7 @@ const matchesQuery = (agent: AgentWithCategory, query: string) => {
|
||||
const filteredAgents = computed(() => {
|
||||
const q = searchQuery.value.trim();
|
||||
return props.agents.filter((agent) => {
|
||||
if (directoryMemberIds.value.has(agent.id)) return false;
|
||||
if (directoryMemberIds.value.has(agent.id) && !isAggregateAgent(agent)) return false;
|
||||
return matchesQuery(agent, q);
|
||||
});
|
||||
});
|
||||
@@ -134,18 +134,29 @@ const onSelect = (agent: AgentWithCategory) => {
|
||||
|
||||
/**
|
||||
* 统一 Agent 行的激活/默认样式类。
|
||||
* 核心逻辑:选中态用浅蓝底 + 品牌色文字,比实心 brand-600 更轻,与侧栏历史选中风格一致。
|
||||
* @param active - 是否为当前选中项
|
||||
* @param dense - 是否为目录成员等更紧凑的行
|
||||
*/
|
||||
const agentRowClass = (active: boolean, dense = false) => {
|
||||
const base = dense
|
||||
? 'group relative flex w-full min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[11px] font-medium transition-all duration-150'
|
||||
: 'group relative flex w-full min-w-0 items-center gap-2 rounded-xl px-2.5 py-2 text-left text-xs font-medium transition-all duration-150';
|
||||
? 'group relative flex w-full min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[11px] font-medium transition-colors duration-150'
|
||||
: 'group relative flex w-full min-w-0 items-center gap-2 rounded-xl px-2.5 py-2 text-left text-xs font-medium transition-colors duration-150';
|
||||
if (active) {
|
||||
return `${base} cursor-default bg-brand-50 text-brand-700 shadow-sm ring-1 ring-brand-100/80 dark:bg-brand-900/25 dark:text-brand-300 dark:ring-brand-800/40`;
|
||||
return `${base} cursor-default bg-brand-50 text-brand-700`;
|
||||
}
|
||||
return `${base} text-secondary hover:bg-surface hover:text-primary hover:shadow-sm`;
|
||||
return `${base} text-secondary hover:bg-surface hover:text-primary`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 聚合应用作为一级入口时选中态需要更强,避免与浅色未选中卡片混在一起。
|
||||
* 核心逻辑:浅蓝底 + 浅品牌描边表达选中,不用实心深蓝。
|
||||
*/
|
||||
const aggregateCardClass = (active: boolean) => (
|
||||
active
|
||||
? 'border-brand-200 bg-brand-50 text-brand-700'
|
||||
: 'border-subtle bg-surface'
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -170,12 +181,16 @@ const agentRowClass = (active: boolean, dense = false) => {
|
||||
<div
|
||||
v-for="agent in aggregateAgents"
|
||||
:key="agent.id"
|
||||
class="overflow-hidden rounded-2xl border border-subtle bg-surface shadow-sm"
|
||||
class="overflow-hidden rounded-2xl border transition-all duration-150"
|
||||
:class="aggregateCardClass(isActiveAgent(agent))"
|
||||
>
|
||||
<div class="flex min-w-0 items-stretch">
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-7 shrink-0 items-center justify-center text-muted transition-colors hover:bg-surface-soft hover:text-brand-600"
|
||||
class="flex w-7 shrink-0 items-center justify-center transition-colors"
|
||||
:class="isActiveAgent(agent)
|
||||
? 'text-brand-600 hover:bg-brand-100/60'
|
||||
: 'text-muted hover:bg-surface-soft hover:text-brand-600'"
|
||||
:title="isDirectoryCollapsed(agent.id) ? t('chat.expandAgents') : t('chat.collapseAgents')"
|
||||
@click.stop="toggleDirectory(agent.id)"
|
||||
>
|
||||
@@ -189,7 +204,7 @@ const agentRowClass = (active: boolean, dense = false) => {
|
||||
type="button"
|
||||
class="flex min-w-0 flex-1 items-center gap-1.5 py-1.5 pr-2.5 text-left transition-colors"
|
||||
:class="isActiveAgent(agent)
|
||||
? 'cursor-default bg-brand-50/80'
|
||||
? 'cursor-default bg-brand-50 text-brand-700'
|
||||
: 'hover:bg-surface-soft/80'"
|
||||
:aria-current="isActiveAgent(agent) ? 'page' : undefined"
|
||||
@click="onSelect(agent)"
|
||||
@@ -197,57 +212,55 @@ const agentRowClass = (active: boolean, dense = false) => {
|
||||
<span
|
||||
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md"
|
||||
:class="isActiveAgent(agent)
|
||||
? 'bg-brand-100 text-brand-600 dark:bg-brand-900/40 dark:text-brand-300'
|
||||
? 'bg-brand-100 text-brand-600'
|
||||
: 'bg-surface-strong text-brand-500'"
|
||||
>
|
||||
<FolderTree class="h-3 w-3" />
|
||||
</span>
|
||||
<span
|
||||
class="min-w-0 truncate text-xs font-semibold tracking-tight"
|
||||
:class="isActiveAgent(agent) ? 'text-brand-700 dark:text-brand-300' : 'text-primary'"
|
||||
:class="isActiveAgent(agent) ? 'text-brand-700' : 'text-primary'"
|
||||
>
|
||||
{{ agent.name }}
|
||||
</span>
|
||||
<span
|
||||
v-if="visibleDirectoryMembers(agent).length"
|
||||
class="ml-auto shrink-0 rounded px-1 py-px text-[10px] font-medium tabular-nums text-muted"
|
||||
class="ml-auto shrink-0 rounded px-1 py-px text-[10px] font-medium tabular-nums"
|
||||
:class="isActiveAgent(agent) ? 'text-brand-500' : 'text-muted'"
|
||||
>
|
||||
{{ visibleDirectoryMembers(agent).length }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-show="!isDirectoryCollapsed(agent.id)"
|
||||
class="border-t border-subtle bg-surface-soft/40 px-2 py-2"
|
||||
>
|
||||
<div v-show="!isDirectoryCollapsed(agent.id)" class="border-t border-subtle bg-surface-soft/40 px-2 py-2">
|
||||
<div class="grid grid-cols-2 gap-1">
|
||||
<button
|
||||
<template
|
||||
v-for="member in visibleDirectoryMembers(agent)"
|
||||
:key="`${agent.id}-${member.id}`"
|
||||
type="button"
|
||||
:class="agentRowClass(isActiveAgent(member), true)"
|
||||
:title="member.name"
|
||||
:aria-current="isActiveAgent(member) ? 'page' : undefined"
|
||||
@click="onSelect(member)"
|
||||
>
|
||||
<span
|
||||
v-if="isActiveAgent(member)"
|
||||
class="absolute inset-y-1 left-0 w-0.5 rounded-full bg-brand-500"
|
||||
/>
|
||||
<div
|
||||
v-if="member.icon_url"
|
||||
class="h-5 w-5 shrink-0 rounded-md bg-contain bg-center bg-no-repeat ring-1 ring-black/5"
|
||||
:style="{ backgroundImage: `url(${member.icon_url})` }"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md bg-brand-50 text-[10px] font-bold text-brand-600 ring-1 ring-brand-100/60 dark:bg-brand-900/30 dark:text-brand-300 dark:ring-brand-800/40"
|
||||
<button
|
||||
type="button"
|
||||
:class="agentRowClass(isActiveAgent(member), true)"
|
||||
:title="member.name"
|
||||
:aria-current="isActiveAgent(member) ? 'page' : undefined"
|
||||
@click="onSelect(member)"
|
||||
>
|
||||
{{ member.name.charAt(0) }}
|
||||
</div>
|
||||
<span class="min-w-0 truncate leading-tight">{{ member.name }}</span>
|
||||
</button>
|
||||
<span v-if="isActiveAgent(member)" class="absolute inset-y-1 left-0 w-0.5 rounded-full bg-brand-500" />
|
||||
<div
|
||||
v-if="member.icon_url"
|
||||
class="h-5 w-5 shrink-0 rounded-md bg-contain bg-center bg-no-repeat ring-1 ring-black/5"
|
||||
:style="{ backgroundImage: `url(${member.icon_url})` }"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md bg-brand-50 text-[10px] font-bold text-brand-600 ring-1 ring-brand-100/60 dark:bg-brand-900/30 dark:text-brand-300 dark:ring-brand-800/40"
|
||||
>
|
||||
{{ member.name.charAt(0) }}
|
||||
</div>
|
||||
<span class="min-w-0 truncate leading-tight">{{ member.name }}</span>
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -467,6 +467,24 @@
|
||||
@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 text-left;
|
||||
}
|
||||
|
||||
.admin-report-app-ops-sort-btn {
|
||||
@apply inline-flex max-w-full items-center justify-start gap-0.5 text-left 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-left text-[10px] leading-none text-brand-500;
|
||||
}
|
||||
|
||||
.admin-report-page-btn {
|
||||
@apply rounded-lg border border-default px-2.5 py-1.5 text-xs text-secondary transition-colors;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ export interface AgentDirectoryMemberRef extends AgentCategoryFields {
|
||||
description?: string | null;
|
||||
agent_code?: string | null;
|
||||
dify_app_id?: string | null;
|
||||
is_aggregate?: boolean;
|
||||
directory_members?: AgentDirectoryMemberRef[];
|
||||
}
|
||||
|
||||
export interface AgentCategorySubGroup<T extends AgentWithCategory = AgentWithCategory> {
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* shared/utils/auth.test.ts
|
||||
*
|
||||
* 用途:覆盖认证本地存储的关键约束,避免“记住我”回归时把过期登录态或 remembered username/password 逻辑改坏。
|
||||
* 依赖:vitest、shared/utils/auth。
|
||||
* 逻辑:重点验证 remember payload 过期清理、remembered username/password 的存取,以及不勾选时不会生成本地持久登录态。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
clearRememberedLoginProfile,
|
||||
getRememberedLoginPreference,
|
||||
getRememberedLoginProfile,
|
||||
getStoredAuthUser,
|
||||
saveAuthUser,
|
||||
saveRememberedLoginPreference,
|
||||
saveRememberedLoginProfile,
|
||||
} from './auth';
|
||||
|
||||
class MemoryStorage implements Storage {
|
||||
private store = new Map<string, string>();
|
||||
|
||||
get length(): number {
|
||||
return this.store.size;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.store.clear();
|
||||
}
|
||||
|
||||
getItem(key: string): string | null {
|
||||
return this.store.has(key) ? this.store.get(key) ?? null : null;
|
||||
}
|
||||
|
||||
key(index: number): string | null {
|
||||
return Array.from(this.store.keys())[index] ?? null;
|
||||
}
|
||||
|
||||
removeItem(key: string): void {
|
||||
this.store.delete(key);
|
||||
}
|
||||
|
||||
setItem(key: string, value: string): void {
|
||||
this.store.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: new MemoryStorage(),
|
||||
writable: true,
|
||||
});
|
||||
|
||||
Object.defineProperty(globalThis, 'sessionStorage', {
|
||||
value: new MemoryStorage(),
|
||||
writable: true,
|
||||
});
|
||||
|
||||
describe('shared/utils/auth remember me helpers', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
it('stores remembered username and password for auto-fill', () => {
|
||||
saveRememberedLoginPreference(true);
|
||||
saveRememberedLoginProfile('26040006', 'Hxit@54321');
|
||||
|
||||
expect(getRememberedLoginPreference()).toBe(true);
|
||||
expect(getRememberedLoginProfile()).toMatchObject({
|
||||
username: '26040006',
|
||||
password: 'Hxit@54321',
|
||||
});
|
||||
expect(localStorage.getItem('hxops_login_profile')).not.toContain('Hxit@54321');
|
||||
});
|
||||
|
||||
it('clears expired remember login payload automatically', () => {
|
||||
localStorage.setItem('hxops_user', JSON.stringify({
|
||||
user: {
|
||||
username: 'remembered_user',
|
||||
role: 'admin',
|
||||
access_token: 'expired-token',
|
||||
},
|
||||
expiry: Date.now() - 1000,
|
||||
}));
|
||||
|
||||
expect(getStoredAuthUser()).toBeNull();
|
||||
expect(localStorage.getItem('hxops_user')).toBeNull();
|
||||
});
|
||||
|
||||
it('stores non-remembered login state in session storage only', () => {
|
||||
saveAuthUser({
|
||||
username: 'session_only_user',
|
||||
role: 'user',
|
||||
access_token: 'session-token',
|
||||
}, false);
|
||||
|
||||
expect(getStoredAuthUser()).toMatchObject({
|
||||
username: 'session_only_user',
|
||||
role: 'user',
|
||||
});
|
||||
expect(sessionStorage.getItem('hxops_user')).toContain('session_only_user');
|
||||
expect(localStorage.getItem('hxops_user')).toBeNull();
|
||||
});
|
||||
|
||||
it('removes remembered login preference when user cancels remember me', () => {
|
||||
saveRememberedLoginPreference(true);
|
||||
saveRememberedLoginProfile('26040006', 'Hxit@54321');
|
||||
|
||||
clearRememberedLoginProfile();
|
||||
|
||||
expect(getRememberedLoginPreference()).toBe(false);
|
||||
expect(getRememberedLoginProfile()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* shared/utils/auth.ts
|
||||
* 认证 token / 用户读写、logout、跨标签同步。
|
||||
* 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步等认证相关本地存储能力。
|
||||
* 依赖:浏览器 localStorage/sessionStorage、Casdoor refresh 接口。
|
||||
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理,既支持 30 天免登录,也支持按业务确认方案回填账号密码。
|
||||
*/
|
||||
export interface AuthUser {
|
||||
id?: number;
|
||||
@@ -19,18 +21,87 @@ export interface AuthUser {
|
||||
token_expires_at?: number;
|
||||
}
|
||||
|
||||
interface StoredAuthPayload {
|
||||
user?: AuthUser;
|
||||
expiry?: number;
|
||||
}
|
||||
|
||||
export interface RememberedLoginProfile {
|
||||
username: string;
|
||||
password: string;
|
||||
updated_at: number;
|
||||
}
|
||||
|
||||
interface StoredRememberedLoginProfile {
|
||||
username?: string;
|
||||
password_ciphertext?: string;
|
||||
updated_at?: number;
|
||||
}
|
||||
|
||||
const AUTH_USER_KEY = 'hxops_user';
|
||||
const LOGIN_REMEMBER_KEY = 'hxops_login_remember';
|
||||
const LOGIN_PROFILE_KEY = 'hxops_login_profile';
|
||||
|
||||
/**
|
||||
* 对登录页 remember password 做轻量编码,避免在本地存储中直接裸露原始密码文本。
|
||||
* AI 触发时机:当业务明确要求自动回填密码时使用;这里只做本地编码,不改变“浏览器端可恢复”的事实。
|
||||
*/
|
||||
const encodeRememberedSecret = (value: string): string => {
|
||||
const text = String(value || '');
|
||||
if (!text) return '';
|
||||
const bytes = new TextEncoder().encode(text);
|
||||
let binary = '';
|
||||
for (const byte of bytes) {
|
||||
binary += String.fromCharCode(byte);
|
||||
}
|
||||
return globalThis.btoa(binary);
|
||||
};
|
||||
|
||||
/**
|
||||
* 解码本地 remember password。
|
||||
* AI 触发时机:登录页初始化需要回填密码时使用;解码失败时返回空串并清理坏数据。
|
||||
*/
|
||||
const decodeRememberedSecret = (value: string): string => {
|
||||
const text = String(value || '');
|
||||
if (!text) return '';
|
||||
const binary = globalThis.atob(text);
|
||||
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
||||
return new TextDecoder().decode(bytes);
|
||||
};
|
||||
|
||||
/**
|
||||
* 解析认证存储载荷,并在 remember payload 过期时自动清理。
|
||||
* AI 触发时机:当登录页或请求拦截器需要读取当前登录态时,必须先经过这里判断 30 天免登录是否仍有效,
|
||||
* 避免 localStorage 中残留的旧 token 被误认为是有效登录态。
|
||||
*/
|
||||
const readStoredAuthPayload = (storage: Storage, key: string): StoredAuthPayload | null => {
|
||||
const stored = storage.getItem(key);
|
||||
if (!stored) return null;
|
||||
try {
|
||||
const data = JSON.parse(stored) as StoredAuthPayload | AuthUser;
|
||||
const payload = (data && typeof data === 'object' && ('user' in data || 'expiry' in data))
|
||||
? data as StoredAuthPayload
|
||||
: { user: data as AuthUser };
|
||||
if (payload.expiry && payload.expiry <= Date.now()) {
|
||||
storage.removeItem(key);
|
||||
return null;
|
||||
}
|
||||
return payload;
|
||||
} catch {
|
||||
storage.removeItem(key);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const getStoredAuthUser = (): AuthUser | null => {
|
||||
const candidates = [
|
||||
sessionStorage.getItem('hxops_user'),
|
||||
localStorage.getItem('hxops_user'),
|
||||
const candidates: Array<[Storage, string]> = [
|
||||
[sessionStorage, AUTH_USER_KEY],
|
||||
[localStorage, AUTH_USER_KEY],
|
||||
];
|
||||
for (const stored of candidates) {
|
||||
if (!stored) continue;
|
||||
try {
|
||||
const data = JSON.parse(stored);
|
||||
return (data.user || data) as AuthUser;
|
||||
} catch {
|
||||
continue;
|
||||
for (const [storage, key] of candidates) {
|
||||
const payload = readStoredAuthPayload(storage, key);
|
||||
if (payload?.user) {
|
||||
return payload.user;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -58,11 +129,11 @@ export const saveAuthUser = (user: AuthUser, remember = false): void => {
|
||||
? { user: next, expiry: Date.now() + 30 * 24 * 60 * 60 * 1000 }
|
||||
: { user: next };
|
||||
if (remember) {
|
||||
localStorage.setItem('hxops_user', JSON.stringify(payload));
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(payload));
|
||||
sessionStorage.removeItem(AUTH_USER_KEY);
|
||||
} else {
|
||||
sessionStorage.setItem('hxops_user', JSON.stringify(payload));
|
||||
localStorage.removeItem('hxops_user');
|
||||
sessionStorage.setItem(AUTH_USER_KEY, JSON.stringify(payload));
|
||||
localStorage.removeItem(AUTH_USER_KEY);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -73,12 +144,100 @@ let _authBroadcast: BroadcastChannel | null = null;
|
||||
let _authSyncInitialized = false;
|
||||
|
||||
const clearAuthStorage = (): void => {
|
||||
localStorage.removeItem('hxops_user');
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
localStorage.removeItem(AUTH_USER_KEY);
|
||||
sessionStorage.removeItem(AUTH_USER_KEY);
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
sessionStorage.removeItem('hxops_casdoor_state');
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取登录页“记住我”偏好。
|
||||
* AI 触发时机:进入登录页时,需要先判断用户是否曾选择记住我,再决定是否回填 remembered username/password。
|
||||
*/
|
||||
export const getRememberedLoginPreference = (): boolean => {
|
||||
try {
|
||||
const stored = localStorage.getItem(LOGIN_REMEMBER_KEY);
|
||||
if (!stored) return false;
|
||||
const data = JSON.parse(stored) as { remember?: boolean };
|
||||
return Boolean(data?.remember);
|
||||
} catch {
|
||||
localStorage.removeItem(LOGIN_REMEMBER_KEY);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存登录页“记住我”偏好。
|
||||
* AI 触发时机:用户勾选或取消“记住我”时,应只调整登录偏好,不要误写密码或覆盖业务 token。
|
||||
*/
|
||||
export const saveRememberedLoginPreference = (remember: boolean): void => {
|
||||
if (!remember) {
|
||||
localStorage.removeItem(LOGIN_REMEMBER_KEY);
|
||||
return;
|
||||
}
|
||||
localStorage.setItem(LOGIN_REMEMBER_KEY, JSON.stringify({ remember: true }));
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取 remembered username/password。
|
||||
* AI 触发时机:登录页初始化且 remember=true 时,用于回填上次成功登录的账号和密码,减少重复输入。
|
||||
*/
|
||||
export const getRememberedLoginProfile = (): RememberedLoginProfile | null => {
|
||||
try {
|
||||
const stored = localStorage.getItem(LOGIN_PROFILE_KEY);
|
||||
if (!stored) return null;
|
||||
const data = JSON.parse(stored) as StoredRememberedLoginProfile;
|
||||
const username = String(data?.username || '').trim();
|
||||
const password = decodeRememberedSecret(String(data?.password_ciphertext || ''));
|
||||
if (!username) {
|
||||
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
||||
return null;
|
||||
}
|
||||
if (!password) {
|
||||
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
username,
|
||||
password,
|
||||
updated_at: Number(data?.updated_at || Date.now()),
|
||||
};
|
||||
} catch {
|
||||
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存 remembered username/password。
|
||||
* AI 触发时机:仅当密码登录成功且用户明确勾选“记住我”后保存,用于下次回到登录页时直接回填并允许用户直接点登录。
|
||||
*/
|
||||
export const saveRememberedLoginProfile = (username: string, password: string): void => {
|
||||
const normalizedUsername = String(username || '').trim();
|
||||
const normalizedPassword = String(password || '');
|
||||
if (!normalizedUsername || !normalizedPassword) {
|
||||
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
||||
return;
|
||||
}
|
||||
localStorage.setItem(
|
||||
LOGIN_PROFILE_KEY,
|
||||
JSON.stringify({
|
||||
username: normalizedUsername,
|
||||
password_ciphertext: encodeRememberedSecret(normalizedPassword),
|
||||
updated_at: Date.now(),
|
||||
} satisfies StoredRememberedLoginProfile),
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 清理登录页 remember 偏好和 remembered username/password。
|
||||
* AI 触发时机:用户取消“记住我”时,必须同步清理自动回填账号密码所需的数据,避免下次进入登录页仍残留旧凭据。
|
||||
*/
|
||||
export const clearRememberedLoginProfile = (): void => {
|
||||
localStorage.removeItem(LOGIN_REMEMBER_KEY);
|
||||
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
||||
};
|
||||
|
||||
const broadcastLogout = (): void => {
|
||||
try {
|
||||
localStorage.setItem(AUTH_LOGOUT_KEY, String(Date.now()));
|
||||
@@ -123,7 +282,7 @@ export const initAuthSync = (): void => {
|
||||
_authSyncInitialized = true;
|
||||
|
||||
window.addEventListener('storage', (event: StorageEvent) => {
|
||||
if (event.key === 'hxops_user' && event.newValue === null && event.oldValue != null) {
|
||||
if (event.key === AUTH_USER_KEY && event.newValue === null && event.oldValue != null) {
|
||||
handleRemoteLogout();
|
||||
return;
|
||||
}
|
||||
@@ -166,7 +325,7 @@ export const refreshAccessToken = async (): Promise<string | null> => {
|
||||
const data = await res.json();
|
||||
if (!data?.access_token) return null;
|
||||
// Preserve existing profile fields while replacing rotated token material.
|
||||
saveAuthUser({ ...(current || {}), ...data }, Boolean(localStorage.getItem('hxops_user')));
|
||||
saveAuthUser({ ...(current || {}), ...data }, Boolean(localStorage.getItem(AUTH_USER_KEY)));
|
||||
return String(data.access_token);
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
Reference in new issue
Block a user