= {
+ 'zh-CN': '\u7b80\u4f53\u4e2d\u6587',
+ 'zh-TW': '\u7e41\u9ad4\u4e2d\u6587',
+ en: 'English',
+ th: '\u0e44\u0e17\u0e22',
+ };
+ return languageLabelMap[value] || value;
+ }
+
+ return value;
+};
+const normalizeSortValue = (v: any) => {
+ if (v === null || v === undefined) return null;
+ if (typeof v === 'number') return v;
+ if (typeof v === 'boolean') return v ? 1 : 0;
+ if (typeof v === 'string') {
+ const n = Number(v);
+ if (!Number.isNaN(n) && v.trim() !== '') return n;
+ const d = Date.parse(v);
+ if (!Number.isNaN(d)) return d;
+ return v.toLowerCase();
+ }
+ return String(v).toLowerCase();
+};
+const compareByRule = (a: any, b: any, rule: SortRule) => {
+ const av = normalizeSortValue(getReportCellValue(a, rule.key));
+ const bv = normalizeSortValue(getReportCellValue(b, rule.key));
+ if (av === bv) return 0;
+ if (av === null) return 1;
+ if (bv === null) return -1;
+ const dir = rule.direction === 'asc' ? 1 : -1;
+ return av > bv ? dir : -dir;
+};
+const sortedTableData = computed(() => {
+ const list = [...tableData.value];
+ const advanced = chatLogsSortRules.value.length > 0 ? chatLogsSortRules.value : [];
+ const rules = advanced.length > 0 ? advanced : (reportHeaderSort.value ? [reportHeaderSort.value] : []);
+ if (rules.length === 0) return list;
+ return list.sort((a, b) => {
+ for (const r of rules) {
+ const c = compareByRule(a, b, r);
+ if (c !== 0) return c;
+ }
+ return 0;
+ });
+});
+// Front-end pagination over the already filtered/sorted dataset.
+const reportTotalRows = computed(() => sortedTableData.value.length);
+const reportTotalPages = computed(() => {
+ const size = Math.max(1, Number(reportPageSize.value) || 20);
+ return Math.max(1, Math.ceil(reportTotalRows.value / size));
+});
+const paginatedSortedTableData = computed(() => {
+ const size = Math.max(1, Number(reportPageSize.value) || 20);
+ // Clamp page number to avoid empty pages after filtering/deletion.
+ const safePage = Math.min(Math.max(1, reportCurrentPage.value), reportTotalPages.value);
+ const start = (safePage - 1) * size;
+ return sortedTableData.value.slice(start, start + size);
+});
+const reportRangeStart = computed(() => {
+ if (reportTotalRows.value === 0) return 0;
+ const safePage = Math.min(Math.max(1, reportCurrentPage.value), reportTotalPages.value);
+ const size = Math.max(1, Number(reportPageSize.value) || 20);
+ return (safePage - 1) * size + 1;
+});
+const reportRangeEnd = computed(() => {
+ if (reportTotalRows.value === 0) return 0;
+ const size = Math.max(1, Number(reportPageSize.value) || 20);
+ return Math.min(reportRangeStart.value + size - 1, reportTotalRows.value);
+});
+const goToReportPage = (page: number) => {
+ reportCurrentPage.value = Math.min(Math.max(1, page), reportTotalPages.value);
+};
+const prevReportPage = () => goToReportPage(reportCurrentPage.value - 1);
+const nextReportPage = () => goToReportPage(reportCurrentPage.value + 1);
+const reportPageButtons = computed(() => {
+ const total = reportTotalPages.value;
+ const current = Math.min(Math.max(1, reportCurrentPage.value), total);
+ if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);
+ if (current <= 4) return [1, 2, 3, 4, 5, -1, total];
+ if (current >= total - 3) return [1, -1, total - 4, total - 3, total - 2, total - 1, total];
+ return [1, -1, current - 1, current, current + 1, -1, total];
+});
+
+const onReportHeaderClick = (key: string) => {
+ // Column-header sorting is the quick mode; clear advanced rules to avoid precedence conflict.
+ if (chatLogsSortRules.value.length > 0) {
+ chatLogsSortRules.value = [];
+ }
+ if (reportHeaderSort.value?.key === key) {
+ reportHeaderSort.value = { key, direction: reportHeaderSort.value.direction === 'asc' ? 'desc' : 'asc' };
+ } else {
+ reportHeaderSort.value = { key, direction: 'asc' };
+ }
+ reportCurrentPage.value = 1;
+};
+const getHeaderSortMark = (key: string) => {
+ if (reportHeaderSort.value?.key !== key) return '';
+ return reportHeaderSort.value.direction === 'asc' ? '^' : 'v';
+};
+const addChatLogsSortRule = () => {
+ const keys = visibleReportKeys.value;
+ const fallback = Object.keys(tableData.value[0] || {});
+ const key = keys[0] || fallback[0];
+ if (!key) return;
+ chatLogsSortRules.value.push({ key, direction: 'asc' });
+};
+const removeChatLogsSortRule = (idx: number) => {
+ chatLogsSortRules.value.splice(idx, 1);
+};
+const moveChatLogsSortRule = (idx: number, direction: -1 | 1) => {
+ const target = idx + direction;
+ if (target < 0 || target >= chatLogsSortRules.value.length) return;
+ const copy = [...chatLogsSortRules.value];
+ const [item] = copy.splice(idx, 1);
+ if (!item) return;
+ copy.splice(target, 0, item);
+ chatLogsSortRules.value = copy;
+};
+const getReportCellDisplayStyle = (key: string) => {
+ // Width is applied on ; height clamp is applied to inner block container.
+ return { ...getColumnWidthStyle(key) } as any;
+};
+
+const getReportCellInnerStyle = () => {
+ const style: Record = { display: 'block' };
+ if (!chatLogsWrapEnabled.value) {
+ style.whiteSpace = 'nowrap';
+ style.overflow = 'hidden';
+ style.textOverflow = 'ellipsis';
+ return style;
+ }
+ const maxH = Number.isFinite(chatLogsWrapMaxHeight.value) ? chatLogsWrapMaxHeight.value : 120;
+ style.whiteSpace = 'normal';
+ style.wordBreak = 'break-word';
+ style.maxHeight = `${maxH}px`;
+ style.overflow = 'hidden';
+ return style;
+};
+
+const toggleReportRowSelection = (rowId: number) => {
+ const idx = selectedReportRowIds.value.indexOf(rowId);
+ if (idx === -1) selectedReportRowIds.value.push(rowId);
+ else selectedReportRowIds.value.splice(idx, 1);
+};
+
+const toggleAllReportRows = () => {
+ if (!isChatLogsTable.value) return;
+ const ids = paginatedSortedTableData.value
+ .map((row: any) => getReportRowId(row))
+ .filter((id: number) => Number.isFinite(id));
+ const allSelected = ids.length > 0 && ids.every((id: number) => selectedReportRowIds.value.includes(id));
+ if (allSelected) {
+ selectedReportRowIds.value = selectedReportRowIds.value.filter((id) => !ids.includes(id));
+ return;
+ }
+ const merged = new Set([...selectedReportRowIds.value, ...ids]);
+ selectedReportRowIds.value = Array.from(merged);
+};
+
+const batchDeleteChatLogs = async () => {
+ if (!isChatLogsTable.value) return;
+ if (selectedReportRowIds.value.length === 0) return;
+ const targetRowIds = [...selectedReportRowIds.value];
+ openDeleteConfirm(`Delete ${targetRowIds.length} selected chat logs?`, async () => {
+ isDeletingChatLogs.value = true;
+ try {
+ const data = await batchDeleteAdminChatLogs(targetRowIds);
+ msg.success(`Deleted ${data.deleted_count ?? 0} chat logs.`);
+ selectedReportRowIds.value = [];
+ await loadTableData();
+ chatLogsTotal.value = await loadTableCount('chat_logs');
+ } catch (e) {
+ console.error(e);
+ msg.error((e as Error).message || t('admin.msg.failed'));
+ } finally {
+ isDeletingChatLogs.value = false;
+ }
+ });
+};
+
+watch(currentTable, async () => {
+ columnFilters.value = {}; // Reset filters on table change
+ selectedReportRowIds.value = [];
+ showChatLogsColumnPanel.value = false;
+ showChatLogsSelection.value = false;
+ reportCurrentPage.value = 1;
+ await loadTableData();
+ reportHeaderSort.value = null;
+ if (currentTable.value === 'chat_logs') {
+ chatLogsTotal.value = await loadTableCount('chat_logs');
+ }
+});
+
+watch(chatLogsColumns, () => {
+ saveChatLogsColumns();
+}, { deep: true });
+
+watch([chatLogsWrapEnabled, chatLogsWrapMaxHeight], () => {
+ saveChatLogsColumns();
+});
+
+watch(chatLogsSortRules, () => {
+ // Force row re-evaluation immediately when rule fields/order change.
+ tableData.value = [...tableData.value];
+ reportCurrentPage.value = 1;
+ saveChatLogsColumns();
+}, { deep: true });
+
+watch(showChatLogsSelection, (v) => {
+ if (!v) selectedReportRowIds.value = [];
+});
+
+watch(columnFilters, () => {
+ reportCurrentPage.value = 1;
+}, { deep: true });
+
+watch([reportPageSize, sortedTableData], () => {
+ if (reportCurrentPage.value > reportTotalPages.value) {
+ reportCurrentPage.value = reportTotalPages.value;
+ }
+ if (reportCurrentPage.value < 1) {
+ reportCurrentPage.value = 1;
+ }
+});
+
+ const loadAll = async (): Promise => {
+ isLoading.value = true;
+ await loadReports();
+ columnFilters.value = {};
+ selectedReportRowIds.value = [];
+ showChatLogsColumnPanel.value = false;
+ showChatLogsSelection.value = false;
+ reportCurrentPage.value = 1;
+ reportHeaderSort.value = null;
+ await loadTableData();
+ if (currentTable.value === 'chat_logs') {
+ chatLogsTotal.value = await loadTableCount('chat_logs');
+ } else {
+ showChatLogsSelection.value = false;
+ }
+ isLoading.value = false;
+ };
+
+ return {
+ usageReport,
+ isLoading,
+ currentTable,
+ tableData,
+ isFullScreen,
+ columnFilters,
+ selectedReportRowIds,
+ isDeletingChatLogs,
+ chatLogsTotal,
+ showChatLogsColumnPanel,
+ chatLogsWrapEnabled,
+ chatLogsWrapMaxHeight,
+ showChatLogsSelection,
+ reportCurrentPage,
+ reportPageSize,
+ reportPageSizeOptions,
+ chatLogsColumns,
+ chatLogsSortRules,
+ reportHeaderSort,
+ draggingColumnKey,
+ isChatLogsTable,
+ visibleReportKeys,
+ allReportRowsSelected,
+ sortedTableData,
+ paginatedSortedTableData,
+ reportTotalRows,
+ reportTotalPages,
+ reportRangeStart,
+ reportRangeEnd,
+ reportPageButtons,
+ showDeleteConfirmDialog,
+ deleteConfirmMessage,
+ loadAll,
+ handleFilterChange,
+ resetChatLogsColumns,
+ moveChatLogsColumn,
+ onColumnDragStart,
+ onColumnDrop,
+ startResizeColumn,
+ exportToExcel,
+ getReportColumnLabel,
+ getReportTableLabel,
+ getReportCellValue,
+ getColumnWidthStyle,
+ getReportRowId,
+ getReportCellDisplayStyle,
+ getReportCellInnerStyle,
+ getHeaderSortMark,
+ onReportHeaderClick,
+ addChatLogsSortRule,
+ removeChatLogsSortRule,
+ moveChatLogsSortRule,
+ toggleReportRowSelection,
+ toggleAllReportRows,
+ batchDeleteChatLogs,
+ goToReportPage,
+ prevReportPage,
+ nextReportPage,
+ confirmDelete,
+ };
+}
diff --git a/frontend/src/features/admin/modules/requests/RequestsPage.vue b/frontend/src/features/admin/modules/requests/RequestsPage.vue
new file mode 100644
index 00000000..9f58e189
--- /dev/null
+++ b/frontend/src/features/admin/modules/requests/RequestsPage.vue
@@ -0,0 +1,100 @@
+/**
+ * features/admin/modules/requests/RequestsPage.vue
+ * 权限申请管理独立页面。路由:/admin/requests
+ */
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ t('admin.request.noPending') }}
+
+
+
+
+
+ | {{ t('admin.request.headers.userId') }} |
+ {{ t('admin.request.headers.targetAgent') }} |
+ {{ t('admin.request.headers.reason') }} |
+ {{ t('admin.request.headers.status') }} |
+ {{ t('admin.request.headers.actions') }} |
+
+
+
+
+ | {{ req.user_id }} |
+ {{ req.agent_id }} |
+
+ {{ req.reason || '-' }}
+ |
+
+
+ {{ t('admin.status.' + req.status) }}
+
+ |
+
+
+
+
+
+ |
+
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/requests/composables/useRequestsAdmin.ts b/frontend/src/features/admin/modules/requests/composables/useRequestsAdmin.ts
new file mode 100644
index 00000000..1d813a08
--- /dev/null
+++ b/frontend/src/features/admin/modules/requests/composables/useRequestsAdmin.ts
@@ -0,0 +1,68 @@
+/**
+ * features/admin/modules/requests/composables/useRequestsAdmin.ts
+ * 权限申请管理:列表、通过、拒绝。
+ */
+import { ref } from 'vue';
+import { useI18n } from 'vue-i18n';
+import {
+ approveAdminPermissionRequest,
+ listAdminPermissionRequests,
+ rejectAdminPermissionRequest,
+} from '@/api/admin';
+import { useMessage } from '@/composables/useMessage';
+import { useAdminNavBadges } from '@/features/admin/composables/useAdminNavBadges';
+import type { AdminPermissionRequestRow } from '@/features/admin/types/request.types';
+
+export function useRequestsAdmin() {
+ const { t } = useI18n();
+ const msg = useMessage();
+ const { refreshBadges } = useAdminNavBadges();
+
+ const requests = ref([]);
+ const isLoading = ref(true);
+
+ const loadRequests = async (): Promise => {
+ try {
+ requests.value = await listAdminPermissionRequests();
+ } catch (e) {
+ console.error('Error loading permission requests:', e);
+ requests.value = [];
+ }
+ };
+
+ const loadAll = async (): Promise => {
+ isLoading.value = true;
+ await loadRequests();
+ isLoading.value = false;
+ };
+
+ const approveRequest = async (id: number): Promise => {
+ try {
+ await approveAdminPermissionRequest(id);
+ await loadRequests();
+ await refreshBadges();
+ } catch (e) {
+ console.error(e);
+ msg.error((e as Error).message || t('admin.msg.failed'));
+ }
+ };
+
+ const rejectRequest = async (id: number): Promise => {
+ try {
+ await rejectAdminPermissionRequest(id);
+ await loadRequests();
+ await refreshBadges();
+ } catch (e) {
+ console.error(e);
+ msg.error((e as Error).message || t('admin.msg.failed'));
+ }
+ };
+
+ return {
+ requests,
+ isLoading,
+ loadAll,
+ approveRequest,
+ rejectRequest,
+ };
+}
diff --git a/frontend/src/features/admin/modules/schedules/SchedulesPage.vue b/frontend/src/features/admin/modules/schedules/SchedulesPage.vue
new file mode 100644
index 00000000..a8ecc467
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/SchedulesPage.vue
@@ -0,0 +1,1127 @@
+/**
+ * features/admin/modules/schedules/SchedulesPage.vue
+ * 定时任务管理独立页面。路由:/admin/schedules
+ */
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ scheduleViewMode === 'overview' ? $t('admin.schedule.overviewTitle') : $t('admin.schedule.workbenchTitle') }}
+
+
+ {{ scheduleViewMode === 'overview' ? $t('admin.schedule.overviewSubtitle') : $t('admin.schedule.workbenchSubtitle') }}
+
+
+
+
+
+
+
+
+
+
+
+ {{ schedules.length }}
+ {{ $t('admin.schedule.stats.total') }}
+
+
+ {{ scheduleEnabledCount }}
+ {{ $t('admin.schedule.stats.enabled') }}
+
+
+ {{ scheduleDisabledCount }}
+ {{ $t('admin.schedule.stats.disabled') }}
+
+
+ {{ scheduleRunningCount }}
+ {{ $t('admin.schedule.stats.running') }}
+
+
+
+
+ {{ $t('admin.schedule.sectionOverview') }}
+ {{ $t('admin.schedule.switchByCard') }}
+
+ {{ $t('admin.schedule.loading') }}
+
+
+
+
+
+
+ {{ $t('admin.schedule.addTitle') }}
+
+
+ {{ $t('admin.schedule.addHint') }}
+
+
+
+
+
+
+
+
+
+
+ {{ $t('admin.schedule.lastRun') }}:{{ formatDateTime(s.last_run_at) }}
+
+
+ {{ $t('admin.schedule.nextRun') }}:{{ formatDateTime(s.next_run_at) }}
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ $t('admin.schedule.emptyList') }}
+
+
+
+
+
+
+
+
+
+
+ {{ selectedSchedule?.name || $t('admin.schedule.noSelection') }}
+ {{ $t('admin.schedule.selectedHint', { time: selectedScheduleLatestRunAt }) }}
+
+
+ {{ selectedScheduleRuns.length }}
+ {{ $t('admin.schedule.runBatches') }}
+
+
+ {{ selectedScheduleRunMetrics.total }}
+ {{ $t('admin.schedule.totalProcessed') }}
+
+
+ {{ selectedScheduleRunMetrics.success }}
+ {{ $t('admin.schedule.totalSuccess') }}
+
+
+ {{ selectedScheduleRunMetrics.failed }}
+ {{ $t('admin.schedule.totalFailed') }}
+
+
+
+
+
+
+
+ {{ $t('admin.schedule.listTitle') }}
+ {{ $t('admin.schedule.switchByCard') }}
+
+
+
+
+
+
+
+
+
+
+ {{ $t('admin.schedule.recordsTitle', { name: selectedSchedule.name }) }}
+ {{ $t('admin.schedule.recordsSubtitle') }}
+
+
+
+
+
+
+ {{ $t('admin.schedule.noSelectionHint') }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ testRunLoading ? $t('admin.schedule.testRun.running') : $t('admin.schedule.testRun.start') }}
+
+ {{ $t('admin.schedule.testRun.waitingHint') }}
+
+
+
+
+
+ {{ testRunResult.total_count }}
+ {{ $t('admin.schedule.testRun.total') }}
+
+
+ {{ testRunResult.success_count }}
+ {{ $t('admin.schedule.testRun.success') }}
+
+
+ {{ testRunResult.failed_count }}
+ {{ $t('admin.schedule.testRun.failed') }}
+
+
+ {{ testRunResult.skipped_count }}
+ {{ $t('admin.schedule.testRun.skipped') }}
+
+
+ {{ $t('admin.schedule.testRun.limitSummary', { limit: testRunResult.limit, agentId: testRunResult.dify_agent_id || $t('admin.schedule.testRun.noAgent') }) }}
+
+
+
+
+ Dify 执行快照(审计)
+
+
+ Agent:
+ {{ testRunResult.dify_execution_snapshot.dify_agent_name || '-' }}
+ (ID: {{ testRunResult.dify_execution_snapshot.dify_agent_id ?? '-' }})
+
+
+ System Prompt:
+ {{ testRunResult.dify_execution_snapshot.dify_system_prompt }}
+ (未配置)
+
+
+ 本次测试未启用 Dify
+
+
+
+ {{ $t('admin.schedule.testRun.stepLogs') }}
+
+
+
+
+ {{ (stepStatusMap[log.status] || { label: log.status }).label }}
+
+ {{ stepLabelMap[log.step] || log.step }}
+ row_id={{ log.row_id }}
+ {{ log.duration_ms }}ms
+
+
+ {{ $t('admin.schedule.viewDetail') }}
+ {{ JSON.stringify(log.detail, null, 2) }}
+
+
+
+
+
+
+ {{ $t('admin.schedule.testRun.viewSql') }}
+ {{ testRunResult.sql }}
+
+
+
+ {{ $t('admin.schedule.testRun.errors', { count: testRunResult.errors.length }) }}
+ {{ testRunResult.errors.join('\n') }}
+
+
+
+
+
+
+
+
+
+ {{ scheduleEditingId ? $t('admin.schedule.form.editTitle') : $t('admin.schedule.form.createTitle') }}
+
+ ✕
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ $t('admin.schedule.form.dataSourceConfig') }}
+
+
+ {{ $t('admin.schedule.form.databaseDirect') }}
+ {{ $t('admin.schedule.form.externalApi') }}
+
+
+ {{ scheduleTestLoading ? $t('admin.schedule.form.querying') : $t('admin.schedule.form.testQuery') }}
+
+
+
+
+ {{ scheduleConfigCollapsed ? $t('admin.schedule.form.expandConfig') : $t('admin.schedule.form.collapseConfig') }}
+
+
+
+
+
+
+
+
+ {{ $t('admin.schedule.form.dataSourceSection') }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 值支持 ${环境变量名} 格式,运行时自动从环境变量解析(推荐密码使用此方式)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ $t('admin.schedule.testRun.queryResult') }}
+
+ {{ $t('admin.schedule.testRun.resultSummary', { total: scheduleTestResult.total, showing: scheduleTestResult.showing }) }}
+ ✕
+
+
+
+
+
+
+ | {{ col }} |
+
+
+
+
+ | {{ row[col] }} |
+
+
+
+
+
+ {{ $t('admin.schedule.testRun.viewGeneratedSql') }}
+ {{ scheduleTestResult.sql }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 仅在启用 Dify Agent 时可配置。保存后将作为 system_prompt 传入 Workflow;编排中 LLM 节点需引用该变量。
+
+
+
+
+
+
+ {{ $t('admin.schedule.form.cronTitle') }}
+ {{ $t('admin.schedule.form.cronHint') }}
+
+
+
+ {{ $t('admin.schedule.form.everyMinutes') }}
+
+
+ {{ $t('admin.schedule.form.hourly') }}
+
+
+ {{ $t('admin.schedule.form.daily') }}
+
+
+ {{ $t('admin.schedule.form.weekly') }}
+
+
+
+
+
+ {{ $t('admin.schedule.form.cronPreview') }}:{{ scheduleCronPreview }}
+ {{ $t('admin.schedule.form.nextRun') }}:{{ formatDateTime(scheduleNextRunPreview.toISOString()) }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts b/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts
new file mode 100644
index 00000000..bca7059a
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts
@@ -0,0 +1,972 @@
+/**
+ * features/admin/modules/schedules/composables/useSchedulesAdmin.ts
+ * 定时任务管理:概览、工作台、创建/编辑、试运行。
+ */
+import { computed, ref, watch } from 'vue';
+import { useI18n } from 'vue-i18n';
+import { listAdminAgents, listAdminUsers } from '@/api/admin';
+import {
+ createAdminSchedule,
+ deleteAdminSchedule,
+ getAdminScheduleTaskConfig,
+ listAdminScheduleRuns,
+ listAdminSchedules,
+ runAdminSchedule,
+ testAdminScheduleRun,
+ testAdminScheduleSql,
+ toggleAdminSchedule,
+ updateAdminSchedule,
+ type ScheduleRun,
+ type ScheduleTask,
+ type TestScheduleRunResult,
+} from '@/api/schedule';
+import { useMessage } from '@/composables/useMessage';
+import { getAuthHeaders } from '@/utils/auth';
+import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
+
+export function useSchedulesAdmin() {
+ const { t, locale } = useI18n();
+ const msg = useMessage();
+
+ const agents = ref([]);
+ const users = ref([]);
+
+ const showDeleteConfirmDialog = ref(false);
+ const deleteConfirmTitle = ref('');
+ const deleteConfirmMessage = ref('');
+ let deleteConfirmAction: (() => Promise | void) | null = null;
+
+ const openDeleteConfirm = (
+ message: string,
+ onConfirm: () => Promise | void,
+ title = '',
+ ): void => {
+ deleteConfirmTitle.value = title;
+ deleteConfirmMessage.value = message;
+ deleteConfirmAction = onConfirm;
+ showDeleteConfirmDialog.value = true;
+ };
+
+ const closeDeleteConfirm = (): void => {
+ showDeleteConfirmDialog.value = false;
+ deleteConfirmTitle.value = '';
+ deleteConfirmMessage.value = '';
+ deleteConfirmAction = null;
+ };
+
+ const confirmDelete = async (): Promise => {
+ if (!deleteConfirmAction) return;
+ try {
+ await deleteConfirmAction();
+ } finally {
+ closeDeleteConfirm();
+ }
+ };
+
+ const loadAgents = async (): Promise => {
+ try {
+ agents.value = await listAdminAgents();
+ } catch (e) {
+ console.error('Failed to load agents', e);
+ agents.value = [];
+ }
+ };
+
+ const loadUsers = async (): Promise => {
+ try {
+ users.value = await listAdminUsers();
+ } catch (e) {
+ console.error('Error loading users:', e);
+ users.value = [];
+ }
+ };
+
+const schedules = ref([]);
+const schedulesLoaded = ref(false); void schedulesLoaded;
+const selectedScheduleRuns = ref([]);
+const scheduleLoading = ref(false);
+const scheduleRunsLoading = ref(false);
+const selectedScheduleId = ref(null);
+const scheduleRunStatusFilter = ref<'all' | string>('all');
+const scheduleRunStartedAfter = ref('');
+const scheduleRunStartedBefore = ref('');
+const scheduleRunColumnDefs = ref([
+ { key: 'run_no', label: '', width: 280, min: 60 },
+ { key: 'started_at', label: '', width: 190, min: 60 },
+ { key: 'finished_at', label: '', width: 190, min: 60 },
+ { key: 'status', label: '', width: 130, min: 50 },
+ { key: 'total_count', label: '', width: 70, min: 40 },
+ { key: 'success_count', label: '', width: 70, min: 40 },
+ { key: 'failed_count', label: '', width: 70, min: 40 },
+ { key: 'wecom_notified', label: '', width: 100, min: 80 },
+ { key: 'detail', label: '', width: 100, min: 80 },
+ { key: 'log', label: '', width: 100, min: 80 },
+]);
+
+const syncScheduleRunColumnLabels = () => {
+ const keyToI18n: Record = {
+ run_no: 'runNo',
+ started_at: 'startedAt',
+ finished_at: 'finishedAt',
+ status: 'status',
+ total_count: 'totalCount',
+ success_count: 'successCount',
+ failed_count: 'failedCount',
+ wecom_notified: 'wecomNotified',
+ detail: 'detail',
+ log: 'log',
+ };
+ scheduleRunColumnDefs.value.forEach((col) => {
+ const i18nKey = keyToI18n[col.key];
+ if (i18nKey) col.label = t(`admin.schedule.columns.${i18nKey}`);
+ });
+};
+watch(locale, syncScheduleRunColumnLabels, { immediate: true });
+const resizingScheduleCol = ref<{ index: number; startX: number; startWidth: number } | null>(null);
+
+const onScheduleColResizeMove = (event: MouseEvent) => {
+ const state = resizingScheduleCol.value;
+ if (!state) return;
+ const def = scheduleRunColumnDefs.value[state.index];
+ if (!def) return;
+ const delta = event.clientX - state.startX;
+ def.width = Math.max(def.min, state.startWidth + delta);
+};
+
+const stopScheduleColResize = () => {
+ if (!resizingScheduleCol.value) return;
+ resizingScheduleCol.value = null;
+ window.removeEventListener('mousemove', onScheduleColResizeMove);
+ window.removeEventListener('mouseup', stopScheduleColResize);
+};
+
+const startScheduleColResize = (index: number, event: MouseEvent) => {
+ const def = scheduleRunColumnDefs.value[index];
+ if (!def) return;
+ resizingScheduleCol.value = {
+ index,
+ startX: event.clientX,
+ startWidth: def.width,
+ };
+ window.addEventListener('mousemove', onScheduleColResizeMove);
+ window.addEventListener('mouseup', stopScheduleColResize);
+};
+const scheduleViewMode = ref<'overview' | 'workbench'>('overview');
+const showScheduleCreateModal = ref(false);
+const scheduleCreateSaving = ref(false);
+const scheduleEditingId = ref(null);
+const scheduleCreateForm = ref({
+ name: '',
+ platform_api_path: '',
+ data_source_type: 'database' as 'database' | 'external_api',
+ dify_agent_id: null as number | null,
+ owner_user_id: null as number | null,
+ wait_seconds: 300,
+ notify_enabled: true,
+ notify_user_ids_json: [] as number[],
+ enabled: true,
+});
+const scheduleConfigCollapsed = ref(true);
+const scheduleCronDesigner = ref({
+ mode: 'every_minutes' as 'every_minutes' | 'hourly' | 'daily' | 'weekly',
+ every_minutes: 30,
+ hourly_minute: 0,
+ daily_hour: 9,
+ daily_minute: 0,
+ weekly_day: 1,
+ weekly_hour: 9,
+ weekly_minute: 0,
+});
+const weeklyDayOptions = computed(() => [
+ { value: 1, label: t('admin.schedule.weekday.mon') },
+ { value: 2, label: t('admin.schedule.weekday.tue') },
+ { value: 3, label: t('admin.schedule.weekday.wed') },
+ { value: 4, label: t('admin.schedule.weekday.thu') },
+ { value: 5, label: t('admin.schedule.weekday.fri') },
+ { value: 6, label: t('admin.schedule.weekday.sat') },
+ { value: 0, label: t('admin.schedule.weekday.sun') },
+]);
+
+const buildCronExprFromDesigner = () => {
+ const cfg = scheduleCronDesigner.value;
+ if (cfg.mode === 'every_minutes') {
+ const every = Math.max(1, Math.min(59, Number(cfg.every_minutes || 30)));
+ return `*/${every} * * * *`;
+ }
+ if (cfg.mode === 'hourly') {
+ const minute = Math.max(0, Math.min(59, Number(cfg.hourly_minute || 0)));
+ return `${minute} * * * *`;
+ }
+ if (cfg.mode === 'daily') {
+ const minute = Math.max(0, Math.min(59, Number(cfg.daily_minute || 0)));
+ const hour = Math.max(0, Math.min(23, Number(cfg.daily_hour || 0)));
+ return `${minute} ${hour} * * *`;
+ }
+ const minute = Math.max(0, Math.min(59, Number(cfg.weekly_minute || 0)));
+ const hour = Math.max(0, Math.min(23, Number(cfg.weekly_hour || 0)));
+ const day = Number(cfg.weekly_day);
+ return `${minute} ${hour} * * ${Number.isNaN(day) ? 1 : day}`;
+};
+
+const scheduleCronPreview = computed(() => buildCronExprFromDesigner());
+
+const scheduleNextRunPreview = computed(() => {
+ const expr = scheduleCronPreview.value;
+ if (!expr) return null;
+ try {
+ const parts = expr.trim().split(/\s+/);
+ if (parts.length !== 5) return null;
+ const now = new Date();
+ const minuteRaw = parts[0]!;
+ const hourRaw = parts[1]!;
+ const dayOfMonth = parts[2]!;
+ const month = parts[3]!;
+ const dayOfWeek = parts[4]!;
+ if (month !== '*') return null;
+ if (dayOfMonth !== '*' && dayOfWeek !== '*') return null;
+ const minute = minuteRaw.startsWith('*/') ? undefined : parseInt(minuteRaw, 10);
+ const hour = hourRaw === '*' ? undefined : parseInt(hourRaw, 10);
+ if (minuteRaw.startsWith('*/')) {
+ const every = parseInt(minuteRaw.replace('*/', ''), 10);
+ const next = new Date(now);
+ next.setSeconds(0, 0);
+ const mod = next.getMinutes() % every;
+ next.setMinutes(next.getMinutes() + (every - mod));
+ if (next <= now) next.setMinutes(next.getMinutes() + every);
+ return next;
+ }
+ if (minute !== undefined && hour === undefined) {
+ const next = new Date(now);
+ next.setMinutes(minute, 0, 0);
+ if (next <= now) next.setHours(next.getHours() + 1);
+ return next;
+ }
+ if (minute !== undefined && hour !== undefined) {
+ const next = new Date(now);
+ next.setHours(hour, minute, 0, 0);
+ if (next <= now) {
+ if (dayOfWeek !== '*') {
+ const dow = parseInt(dayOfWeek, 10);
+ const currentDow = next.getDay();
+ let diff = dow - currentDow;
+ if (diff <= 0) diff += 7;
+ next.setDate(next.getDate() + diff);
+ } else {
+ next.setDate(next.getDate() + 1);
+ }
+ } else if (dayOfWeek !== '*') {
+ const dow = parseInt(dayOfWeek, 10);
+ const target = new Date(next);
+ const currentDow = target.getDay();
+ let diff = dow - currentDow;
+ if (diff < 0) diff += 7;
+ if (diff > 0) target.setDate(target.getDate() + diff);
+ if (target <= now) {
+ target.setDate(target.getDate() + 7);
+ }
+ return target;
+ }
+ return next;
+ }
+ return null;
+ } catch {
+ return null;
+ }
+});
+
+const parseCronExprToDesigner = (expr: string | null | undefined) => {
+ const text = String(expr || '').trim();
+ const parts = text.split(/\s+/);
+ if (parts.length !== 5) {
+ scheduleCronDesigner.value = {
+ mode: 'every_minutes',
+ every_minutes: 30,
+ hourly_minute: 0,
+ daily_hour: 9,
+ daily_minute: 0,
+ weekly_day: 1,
+ weekly_hour: 9,
+ weekly_minute: 0,
+ };
+ return;
+ }
+ const m = parts[0] ?? '';
+ const h = parts[1] ?? '';
+ const dow = parts[4] ?? '';
+ if (/^\*\/\d+$/.test(m) && h === '*' && dow === '*') {
+ scheduleCronDesigner.value.mode = 'every_minutes';
+ scheduleCronDesigner.value.every_minutes = Number(m.replace('*/', '')) || 30;
+ return;
+ }
+ if (/^\d+$/.test(m) && h === '*' && dow === '*') {
+ scheduleCronDesigner.value.mode = 'hourly';
+ scheduleCronDesigner.value.hourly_minute = Number(m) || 0;
+ return;
+ }
+ if (/^\d+$/.test(m) && /^\d+$/.test(h) && dow === '*') {
+ scheduleCronDesigner.value.mode = 'daily';
+ scheduleCronDesigner.value.daily_hour = Number(h) || 0;
+ scheduleCronDesigner.value.daily_minute = Number(m) || 0;
+ return;
+ }
+ if (/^\d+$/.test(m) && /^\d+$/.test(h) && /^\d+$/.test(dow)) {
+ scheduleCronDesigner.value.mode = 'weekly';
+ scheduleCronDesigner.value.weekly_hour = Number(h) || 0;
+ scheduleCronDesigner.value.weekly_minute = Number(m) || 0;
+ scheduleCronDesigner.value.weekly_day = Number(dow);
+ return;
+ }
+ scheduleCronDesigner.value.mode = 'every_minutes';
+ scheduleCronDesigner.value.every_minutes = 30;
+};
+
+const resetScheduleCreateForm = () => {
+ scheduleEditingId.value = null;
+ scheduleCreateForm.value = {
+ name: '',
+ platform_api_path: '',
+ data_source_type: 'database',
+ dify_agent_id: null,
+ owner_user_id: null,
+ wait_seconds: 300,
+ notify_enabled: true,
+ notify_user_ids_json: [],
+ enabled: true,
+ };
+ scheduleSqlEditForm.value = {
+ base_fetch_sql: '',
+ fetch_where_conditions: '',
+ fetch_order_by: '',
+ detail_sql: '',
+ writeback_sql: '',
+ row_id_key: 'id',
+ log_prefix: '',
+ alias_order_str: '',
+ detail_alias_order_str: '',
+ header_labels_str: '{}',
+ ds_db_type: 'sqlserver',
+ ds_host: '',
+ ds_port: '',
+ ds_database: '',
+ ds_username: '',
+ ds_password: '',
+ ds_driver: '',
+ ds_encrypt: '',
+ ds_trust_cert: '',
+ api_url: '',
+ api_method: 'POST',
+ api_headers_str: '{}',
+ api_body_template: '',
+ dify_system_prompt: '',
+ };
+ scheduleTestResult.value = null;
+ scheduleCronDesigner.value = {
+ mode: 'every_minutes',
+ every_minutes: 30,
+ hourly_minute: 0,
+ daily_hour: 9,
+ daily_minute: 0,
+ weekly_day: 1,
+ weekly_hour: 9,
+ weekly_minute: 0,
+ };
+};
+
+const openScheduleCreateModal = async () => {
+ resetScheduleCreateForm();
+ scheduleConfigCollapsed.value = true;
+ await Promise.all([loadAgents(), loadUsers()]);
+ showScheduleCreateModal.value = true;
+};
+
+const openScheduleEditModal = async (task: ScheduleTask) => {
+ await Promise.all([loadAgents(), loadUsers()]);
+ scheduleConfigCollapsed.value = true;
+ scheduleEditingId.value = task.id;
+ scheduleCreateForm.value = {
+ name: task.name || '',
+ platform_api_path: task.platform_api_path || '',
+ dify_agent_id: task.dify_agent_id || null,
+ owner_user_id: task.owner_user_id || null,
+ wait_seconds: task.wait_seconds || 0,
+ notify_enabled: !!task.notify_enabled,
+ notify_user_ids_json: task.notify_user_ids_json || [],
+ enabled: !!task.enabled,
+ data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api',
+ };
+
+ try {
+ const result = await getAdminScheduleTaskConfig(task.id);
+ const cfg = result.config;
+ scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as 'database' | 'external_api';
+ if (cfg) {
+ scheduleSqlEditForm.value = {
+ base_fetch_sql: cfg.base_fetch_sql || '',
+ fetch_where_conditions: cfg.fetch_where_conditions || '',
+ fetch_order_by: cfg.fetch_order_by || '',
+ detail_sql: cfg.detail_sql || '',
+ writeback_sql: cfg.writeback_sql || '',
+ row_id_key: cfg.row_id_key || 'id',
+ log_prefix: cfg.log_prefix || '',
+ alias_order_str: (cfg.alias_order || []).join(','),
+ detail_alias_order_str: (cfg.detail_alias_order || []).join(','),
+ header_labels_str: cfg.header_labels ? JSON.stringify(cfg.header_labels, null, 2) : '{}',
+ ds_db_type: cfg.data_source?.db_type || 'sqlserver',
+ ds_host: cfg.data_source?.host || '',
+ ds_port: cfg.data_source?.port || '',
+ ds_database: cfg.data_source?.database || '',
+ ds_username: cfg.data_source?.username || '',
+ ds_password: cfg.data_source?.password || '',
+ ds_driver: cfg.data_source?.driver || '',
+ ds_encrypt: cfg.data_source?.encrypt || '',
+ ds_trust_cert: cfg.data_source?.trust_cert || '',
+ api_url: cfg.external_api?.url || '',
+ api_method: cfg.external_api?.method || 'POST',
+ api_headers_str: cfg.external_api?.headers ? JSON.stringify(cfg.external_api.headers, null, 2) : '{}',
+ api_body_template: cfg.external_api?.body_template || '',
+ dify_system_prompt: cfg.dify_system_prompt || '',
+ };
+ }
+ } catch {
+ scheduleSqlEditForm.value = {
+ base_fetch_sql: '',
+ fetch_where_conditions: '',
+ fetch_order_by: '',
+ detail_sql: '',
+ writeback_sql: '',
+ row_id_key: 'id',
+ log_prefix: '',
+ alias_order_str: '',
+ detail_alias_order_str: '',
+ header_labels_str: '{}',
+ ds_db_type: 'sqlserver',
+ ds_host: '',
+ ds_port: '',
+ ds_database: '',
+ ds_username: '',
+ ds_password: '',
+ ds_driver: '',
+ ds_encrypt: '',
+ ds_trust_cert: '',
+ api_url: '',
+ api_method: 'POST',
+ api_headers_str: '{}',
+ api_body_template: '',
+ dify_system_prompt: '',
+ };
+ }
+
+ scheduleTestResult.value = null;
+ parseCronExprToDesigner(task.cron_expr);
+ showScheduleCreateModal.value = true;
+};
+
+const selectedSchedule = computed(() =>
+ schedules.value.find((item) => item.id === selectedScheduleId.value) || null
+);
+
+const scheduleRunStatusOptions = computed(() => [
+ { value: 'all', label: t('admin.schedule.status.all') },
+ { value: 'success', label: t('admin.schedule.status.success') },
+ { value: 'partial_failed', label: t('admin.schedule.status.partialFailed') },
+ { value: 'failed', label: t('admin.schedule.status.failed') },
+ { value: 'running', label: t('admin.schedule.status.running') },
+]);
+
+const getScheduleRunStatusBadge = (status: string) => {
+ const map: Record = {
+ success: { cls: 'bg-emerald-100 text-emerald-700', label: t('admin.schedule.status.success') },
+ partial_failed: { cls: 'bg-blue-100 text-blue-700', label: t('admin.schedule.status.partialFailed') },
+ failed: { cls: 'bg-rose-100 text-rose-700', label: t('admin.schedule.status.failed') },
+ running: { cls: 'bg-amber-100 text-amber-700', label: t('admin.schedule.status.running') },
+ queued: { cls: 'bg-surface-soft text-secondary', label: t('admin.schedule.status.queued') },
+ };
+ return map[status] || { cls: 'bg-surface-soft text-secondary', label: status };
+};
+
+const formatDateTime = (iso?: string | null) => {
+ if (!iso) return '-';
+ const d = new Date(iso);
+ if (isNaN(d.getTime())) return iso;
+ const pad = (n: number) => String(n).padStart(2, '0');
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
+};
+
+const expandedScheduleRunId = ref(null);
+
+const expandedScheduleRun = computed(() => {
+ if (!expandedScheduleRunId.value) return null;
+ return filteredScheduleRuns.value.find((x) => x.id === expandedScheduleRunId.value) || null;
+});
+
+const stepLabelMap: Record = {
+ fetch_srm: t('admin.schedule.step.fetchSrm'),
+ call_dify: t('admin.schedule.step.callDify'),
+ writeback_srm: t('admin.schedule.step.writebackSrm'),
+ call_internal_api: t('admin.schedule.step.callInternalApi'),
+ pre_dify: t('admin.schedule.step.preDify'),
+};
+const stepStatusMap: Record = {
+ success: { cls: 'bg-emerald-100 text-emerald-700', label: t('admin.schedule.status.success') },
+ failed: { cls: 'bg-rose-100 text-rose-700', label: t('admin.schedule.status.failed') },
+};
+
+const showTestRunDialog = ref(false);
+const testRunSchedule = ref(null);
+const testRunWhere = ref('');
+const testRunOrderBy = ref('');
+const testRunBaseFetchSql = ref('');
+const testRunLimit = ref(3);
+const testRunLoading = ref(false);
+const testRunResult = ref(null);
+
+const openTestRunDialog = async (s: ScheduleTask) => {
+ testRunSchedule.value = s;
+ try {
+ const result = await getAdminScheduleTaskConfig(s.id);
+ const cfg = result.config;
+ testRunWhere.value = cfg?.fetch_where_conditions || '';
+ testRunOrderBy.value = cfg?.fetch_order_by || '';
+ testRunBaseFetchSql.value = cfg?.base_fetch_sql || '';
+ } catch {
+ testRunWhere.value = '';
+ testRunOrderBy.value = '';
+ testRunBaseFetchSql.value = '';
+ }
+ testRunLimit.value = 3;
+ testRunResult.value = null;
+ testRunLoading.value = false;
+ showTestRunDialog.value = true;
+};
+
+const handleTestRun = async () => {
+ const s = testRunSchedule.value;
+ if (!s?.id) return;
+ testRunLoading.value = true;
+ testRunResult.value = null;
+ try {
+ const result = await testAdminScheduleRun(s.id, {
+ fetch_where_conditions: testRunWhere.value,
+ fetch_order_by: testRunOrderBy.value,
+ limit: testRunLimit.value,
+ });
+ testRunResult.value = result;
+ await loadSchedules();
+ if (s.id) {
+ await viewScheduleRuns(s.id);
+ }
+ } catch (e: any) {
+ msg.error(`${t('admin.schedule.msg.testRunFailed')}: ${e?.message || e}`);
+ } finally {
+ testRunLoading.value = false;
+ }
+};
+
+const filteredScheduleRuns = computed(() => {
+ if (scheduleRunStatusFilter.value === 'all') return selectedScheduleRuns.value;
+ return selectedScheduleRuns.value.filter((item) => item.status === scheduleRunStatusFilter.value);
+});
+
+const selectedScheduleRunMetrics = computed(() => {
+ const runs = selectedScheduleRuns.value;
+ return runs.reduce(
+ (acc, item) => {
+ acc.total += item.total_count || 0;
+ acc.success += item.success_count || 0;
+ acc.failed += item.failed_count || 0;
+ return acc;
+ },
+ { total: 0, success: 0, failed: 0 }
+ );
+});
+
+const selectedScheduleLatestRunAt = computed(
+ () => selectedScheduleRuns.value[0]?.started_at || selectedSchedule.value?.last_run_at || '-'
+);
+
+const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length);
+const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length);
+const scheduleRunningCount = computed(() => schedules.value.filter((item) => item.last_status === 'running').length);
+
+const loadSchedules = async () => {
+ scheduleLoading.value = true;
+ try {
+ schedules.value = await listAdminSchedules();
+ if (schedules.value.length === 0) {
+ selectedScheduleId.value = null;
+ selectedScheduleRuns.value = [];
+ scheduleViewMode.value = 'overview';
+ return;
+ }
+ const exists = selectedScheduleId.value && schedules.value.some((item) => item.id === selectedScheduleId.value);
+ const nextScheduleId = exists && selectedScheduleId.value ? selectedScheduleId.value : schedules.value[0]?.id ?? null;
+ if (!exists && nextScheduleId) {
+ selectedScheduleId.value = nextScheduleId;
+ }
+ if (scheduleViewMode.value === 'workbench' && nextScheduleId) {
+ await viewScheduleRuns(nextScheduleId);
+ }
+ } finally {
+ scheduleLoading.value = false;
+ }
+};
+
+const scheduleSqlEditForm = ref({
+ base_fetch_sql: '',
+ fetch_where_conditions: '',
+ fetch_order_by: '',
+ detail_sql: '',
+ writeback_sql: '',
+ row_id_key: 'id',
+ log_prefix: '',
+ alias_order_str: '',
+ detail_alias_order_str: '',
+ header_labels_str: '{}',
+ ds_db_type: 'sqlserver',
+ ds_host: '',
+ ds_port: '',
+ ds_database: '',
+ ds_username: '',
+ ds_password: '',
+ ds_driver: '',
+ ds_encrypt: '',
+ ds_trust_cert: '',
+ api_url: '',
+ api_method: 'POST',
+ api_headers_str: '{}',
+ api_body_template: '',
+ dify_system_prompt: '',
+});
+const scheduleSqlSaving = ref(false); void scheduleSqlSaving;
+const scheduleTestLoading = ref(false);
+const scheduleTestResult = ref<{ total: number; showing: number; columns: string[]; rows: any[]; sql: string } | null>(null);
+
+const handleTestScheduleSql = async () => {
+ const taskId = scheduleEditingId.value;
+ if (!taskId) return;
+
+ scheduleTestLoading.value = true;
+ scheduleTestResult.value = null;
+ try {
+ const result = await testAdminScheduleSql(taskId, {
+ fetch_where_conditions: scheduleSqlEditForm.value.fetch_where_conditions,
+ fetch_order_by: scheduleSqlEditForm.value.fetch_order_by,
+ limit: 10,
+ });
+ scheduleTestResult.value = result;
+ } catch (e: any) {
+ msg.error(`${t('admin.schedule.msg.testQueryFailed')}: ${e?.message || e}`);
+ } finally {
+ scheduleTestLoading.value = false;
+ }
+};
+
+const scheduleNotifyDropdownOpen = ref(false);
+
+watch(() => scheduleCreateForm.value.dify_agent_id, (agentId) => {
+ if (!agentId) {
+ scheduleSqlEditForm.value.dify_system_prompt = '';
+ }
+});
+
+const getUserName = (uid: number) => {
+ const u = users.value.find(x => x.id === uid);
+ return u ? (u.real_name || u.username) : String(uid);
+};
+
+const toggleNotifyUser = (uid: number) => {
+ const list = scheduleCreateForm.value.notify_user_ids_json;
+ if (list.includes(uid)) {
+ scheduleCreateForm.value.notify_user_ids_json = list.filter((id: number) => id !== uid);
+ } else {
+ scheduleCreateForm.value.notify_user_ids_json = [...list, uid];
+ }
+};
+
+const removeNotifyUser = (uid: number) => {
+ scheduleCreateForm.value.notify_user_ids_json = scheduleCreateForm.value.notify_user_ids_json.filter((id: number) => id !== uid);
+};
+
+const createSchedule = async () => {
+ if (!scheduleCreateForm.value.name || !scheduleCreateForm.value.owner_user_id) return;
+
+ const dst = scheduleCreateForm.value.data_source_type;
+ const hasAgent = !!scheduleCreateForm.value.dify_agent_id;
+ const hasSql = dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.trim();
+ const hasApi = dst === 'external_api' && !!scheduleSqlEditForm.value.api_url.trim();
+ if (!hasAgent && !hasSql && !hasApi) {
+ msg.error(t('admin.schedule.msg.configRequired'));
+ return;
+ }
+
+ let headerLabels: Record = {};
+ try {
+ headerLabels = JSON.parse(scheduleSqlEditForm.value.header_labels_str || '{}');
+ } catch {
+ msg.error(t('admin.schedule.msg.headerLabelsJsonInvalid'));
+ return;
+ }
+ let apiHeaders: Record = {};
+ if (dst === 'external_api') {
+ try {
+ apiHeaders = JSON.parse(scheduleSqlEditForm.value.api_headers_str || '{}');
+ } catch {
+ msg.error(t('admin.schedule.msg.apiHeadersJsonInvalid'));
+ return;
+ }
+ }
+ const aliasOrder = scheduleSqlEditForm.value.alias_order_str.split(',').map(s => s.trim()).filter(Boolean);
+ const detailAliasOrder = scheduleSqlEditForm.value.detail_alias_order_str.split(',').map(s => s.trim()).filter(Boolean);
+
+ const configPayload: Record = {
+ base_fetch_sql: scheduleSqlEditForm.value.base_fetch_sql,
+ fetch_where_conditions: scheduleSqlEditForm.value.fetch_where_conditions,
+ fetch_order_by: scheduleSqlEditForm.value.fetch_order_by,
+ detail_sql: scheduleSqlEditForm.value.detail_sql,
+ writeback_sql: scheduleSqlEditForm.value.writeback_sql,
+ row_id_key: scheduleSqlEditForm.value.row_id_key || 'id',
+ log_prefix: scheduleSqlEditForm.value.log_prefix,
+ alias_order: aliasOrder,
+ detail_alias_order: detailAliasOrder,
+ header_labels: headerLabels,
+ data_source: scheduleSqlEditForm.value.ds_host.trim() ? {
+ db_type: scheduleSqlEditForm.value.ds_db_type,
+ host: scheduleSqlEditForm.value.ds_host,
+ port: scheduleSqlEditForm.value.ds_port,
+ database: scheduleSqlEditForm.value.ds_database,
+ username: scheduleSqlEditForm.value.ds_username,
+ password: scheduleSqlEditForm.value.ds_password,
+ driver: scheduleSqlEditForm.value.ds_driver,
+ encrypt: scheduleSqlEditForm.value.ds_encrypt,
+ trust_cert: scheduleSqlEditForm.value.ds_trust_cert,
+ } : undefined,
+ external_api: scheduleSqlEditForm.value.api_url.trim() ? {
+ url: scheduleSqlEditForm.value.api_url,
+ method: scheduleSqlEditForm.value.api_method,
+ headers: apiHeaders,
+ body_template: scheduleSqlEditForm.value.api_body_template,
+ } : undefined,
+ dify_system_prompt: hasAgent ? scheduleSqlEditForm.value.dify_system_prompt : '',
+ };
+
+ scheduleCreateSaving.value = true;
+ try {
+ const payload: any = {
+ name: scheduleCreateForm.value.name,
+ schedule_type: 'platform_app',
+ owner_user_id: scheduleCreateForm.value.owner_user_id,
+ cron_expr: scheduleCronPreview.value,
+ wait_seconds: Math.max(0, Number(scheduleCreateForm.value.wait_seconds || 0)),
+ dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined,
+ notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [],
+ notify_enabled: scheduleCreateForm.value.notify_enabled,
+ enabled: scheduleCreateForm.value.enabled,
+ data_source_type: dst,
+ config: configPayload,
+ };
+ let resultData: any = null;
+ if (scheduleEditingId.value) {
+ resultData = await updateAdminSchedule(scheduleEditingId.value, payload);
+ } else {
+ resultData = await createAdminSchedule(payload);
+ }
+ const createdId = resultData?.id ?? resultData?.schedule?.id ?? null;
+ const targetId = scheduleEditingId.value || createdId;
+ showScheduleCreateModal.value = false;
+ await loadSchedules();
+ if (targetId) {
+ await viewScheduleRuns(targetId);
+ }
+ } catch (err: any) {
+ msg.error(err?.message || t('common.errorOccurred'));
+ } finally {
+ scheduleCreateSaving.value = false;
+ }
+};
+
+const todayStart = () => {
+ const d = new Date();
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T00:00:00`;
+};
+const todayEnd = () => {
+ const d = new Date();
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T23:59:59`;
+};
+
+const resetScheduleRunFilters = () => {
+ scheduleRunStatusFilter.value = 'all';
+ scheduleRunStartedAfter.value = todayStart();
+ scheduleRunStartedBefore.value = todayEnd();
+};
+
+const viewScheduleRuns = async (taskId: number) => {
+ selectedScheduleId.value = taskId;
+ scheduleRunsLoading.value = true;
+ if (!scheduleRunStartedAfter.value && !scheduleRunStartedBefore.value) {
+ resetScheduleRunFilters();
+ }
+ try {
+ const params: { status?: string; started_after?: string; started_before?: string } = {};
+ if (scheduleRunStatusFilter.value !== 'all') params.status = scheduleRunStatusFilter.value;
+ if (scheduleRunStartedAfter.value) params.started_after = scheduleRunStartedAfter.value;
+ if (scheduleRunStartedBefore.value) params.started_before = scheduleRunStartedBefore.value;
+ selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params);
+ } finally {
+ scheduleRunsLoading.value = false;
+ }
+};
+
+const openScheduleRunSubmenu = async (taskId: number) => {
+ scheduleViewMode.value = 'workbench';
+ await viewScheduleRuns(taskId);
+};
+
+const backToScheduleOverview = () => {
+ scheduleViewMode.value = 'overview';
+};
+
+const runScheduleNow = async (taskId: number) => {
+ try {
+ await runAdminSchedule(taskId);
+ } catch (err: any) {
+ msg.error(err?.message || t('admin.schedule.msg.runNowFailed'));
+ return;
+ }
+ await viewScheduleRuns(taskId);
+ await loadSchedules();
+
+ const pollInterval = setInterval(async () => {
+ await viewScheduleRuns(taskId);
+ await loadSchedules();
+ const target = schedules.value.find((s: ScheduleTask) => s.id === taskId);
+ if (target && target.last_status && target.last_status !== 'running') {
+ clearInterval(pollInterval);
+ }
+ }, 5000);
+};
+
+const setScheduleEnabled = async (taskId: number, enabled: boolean) => {
+ try {
+ await toggleAdminSchedule(taskId, enabled);
+ await loadSchedules();
+ } catch (err: any) {
+ msg.error(err?.message || t('common.errorOccurred'));
+ }
+};
+
+const downloadScheduleExcel = async (runId: number) => {
+ const res = await fetch(`/api/admin/schedule-runs/${runId}/excel`, { headers: getAuthHeaders() });
+ if (!res.ok) {
+ msg.error(t('admin.schedule.msg.downloadExcelFailed'));
+ return;
+ }
+ const blob = await res.blob();
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ const disposition = res.headers.get('content-disposition');
+ a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'result.xlsx';
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+};
+
+const deleteSchedule = (task: ScheduleTask) => {
+ openDeleteConfirm(
+ t('admin.schedule.deleteConfirmMessage', { name: task.name }),
+ async () => {
+ try {
+ await deleteAdminSchedule(task.id);
+ } catch (err: any) {
+ msg.error(err?.message || t('admin.schedule.msg.deleteFailed'));
+ return;
+ }
+ if (selectedScheduleId.value === task.id) {
+ selectedScheduleId.value = null;
+ selectedScheduleRuns.value = [];
+ }
+ await loadSchedules();
+ },
+ t('admin.schedule.deleteDialogTitle')
+ );
+};
+ const loadAll = async (): Promise => {
+ await loadSchedules();
+ };
+
+ return {
+ agents,
+ users,
+ schedules,
+ selectedScheduleRuns,
+ scheduleLoading,
+ scheduleRunsLoading,
+ selectedScheduleId,
+ scheduleRunStatusFilter,
+ scheduleRunStartedAfter,
+ scheduleRunStartedBefore,
+ scheduleRunColumnDefs,
+ scheduleViewMode,
+ showScheduleCreateModal,
+ scheduleCreateSaving,
+ scheduleEditingId,
+ scheduleCreateForm,
+ scheduleConfigCollapsed,
+ scheduleCronDesigner,
+ weeklyDayOptions,
+ scheduleCronPreview,
+ scheduleNextRunPreview,
+ selectedSchedule,
+ scheduleRunStatusOptions,
+ getScheduleRunStatusBadge,
+ formatDateTime,
+ expandedScheduleRunId,
+ expandedScheduleRun,
+ stepLabelMap,
+ stepStatusMap,
+ showTestRunDialog,
+ testRunSchedule,
+ testRunWhere,
+ testRunOrderBy,
+ testRunBaseFetchSql,
+ testRunLimit,
+ testRunLoading,
+ testRunResult,
+ filteredScheduleRuns,
+ selectedScheduleRunMetrics,
+ selectedScheduleLatestRunAt,
+ scheduleEnabledCount,
+ scheduleDisabledCount,
+ scheduleRunningCount,
+ scheduleSqlEditForm,
+ scheduleTestLoading,
+ scheduleTestResult,
+ scheduleNotifyDropdownOpen,
+ showDeleteConfirmDialog,
+ deleteConfirmTitle,
+ deleteConfirmMessage,
+ loadAll,
+ loadSchedules,
+ startScheduleColResize,
+ openScheduleCreateModal,
+ openScheduleEditModal,
+ openScheduleRunSubmenu,
+ backToScheduleOverview,
+ viewScheduleRuns,
+ resetScheduleRunFilters,
+ runScheduleNow,
+ setScheduleEnabled,
+ deleteSchedule,
+ downloadScheduleExcel,
+ openTestRunDialog,
+ handleTestRun,
+ handleTestScheduleSql,
+ getUserName,
+ toggleNotifyUser,
+ removeNotifyUser,
+ createSchedule,
+ closeDeleteConfirm,
+ confirmDelete,
+ };
+}
diff --git a/frontend/src/features/admin/modules/users/UsersPage.vue b/frontend/src/features/admin/modules/users/UsersPage.vue
new file mode 100644
index 00000000..cb00b741
--- /dev/null
+++ b/frontend/src/features/admin/modules/users/UsersPage.vue
@@ -0,0 +1,244 @@
+/**
+ * features/admin/modules/users/UsersPage.vue
+ * 用户管理独立页面。路由:/admin/users
+ */
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+ |
+ {{ t('admin.user.headers.user') }} |
+ {{ t('admin.user.headers.role') }} |
+ {{ t('admin.user.headers.dept') }} |
+ {{ t('admin.user.headers.status') }} |
+ {{ t('admin.user.headers.actions') }} |
+
+
+
+
+ | {{ t('admin.user.noUsers') }} |
+
+
+ |
+
+ |
+
+
+
+ {{ user.username.charAt(0).toUpperCase() }}
+
+
+ {{ user.username }}
+ {{ user.email }}
+
+
+ |
+
+
+ {{ t('admin.role.' + user.role) }}
+
+ |
+ {{ user.department || '-' }} |
+
+
+ {{ t('admin.status.' + user.status) }}
+
+ |
+
+
+ {{ t('admin.edit') }}
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue b/frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue
new file mode 100644
index 00000000..95396c18
--- /dev/null
+++ b/frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue
@@ -0,0 +1,62 @@
+/**
+ * features/admin/modules/users/components/BatchEditUserModal.vue
+ * 批量编辑用户部门/角色/状态弹窗。
+ */
+
+
+
+
+
+
+ {{ t('admin.batchEdit.title') }}
+ {{ t('admin.batchEdit.selected', { count: selectedCount }) }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue b/frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue
new file mode 100644
index 00000000..79901833
--- /dev/null
+++ b/frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue
@@ -0,0 +1,70 @@
+/**
+ * features/admin/modules/users/components/BatchPermissionModal.vue
+ * 批量分配/移除用户 Agent 权限弹窗。
+ */
+
+
+
+
+
+
+ {{ t('admin.perm.batchModal.title') }}
+ {{ t('admin.perm.batchModal.selected', { count: selectedCount }) }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/users/components/UserFormModal.vue b/frontend/src/features/admin/modules/users/components/UserFormModal.vue
new file mode 100644
index 00000000..0169081d
--- /dev/null
+++ b/frontend/src/features/admin/modules/users/components/UserFormModal.vue
@@ -0,0 +1,109 @@
+/**
+ * features/admin/modules/users/components/UserFormModal.vue
+ * 创建/编辑用户弹窗。
+ */
+
+
+
+
+
+
+ {{ form.id ? t('admin.user.editUser') : t('admin.user.createUser') }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ t('admin.user.fields.noAgents') }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts b/frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts
new file mode 100644
index 00000000..e5afb66a
--- /dev/null
+++ b/frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts
@@ -0,0 +1,360 @@
+/**
+ * features/admin/modules/users/composables/useUsersAdmin.ts
+ * 用户管理模块业务逻辑:CRUD、筛选、批量操作。
+ */
+import { computed, ref } from 'vue';
+import { useI18n } from 'vue-i18n';
+import {
+ batchDeleteAdminUsers,
+ batchUpdateAdminPermissions,
+ batchUpdateAdminUsers,
+ cleanupRejectedAdminUsers,
+ createAdminUser,
+ listAdminAgents,
+ listAdminDepartments,
+ listAdminUsers,
+ updateAdminUser,
+} from '@/api/admin';
+import { useMessage } from '@/composables/useMessage';
+import type { AdminAgentOption, AdminDepartmentRow, AdminUserRow } from '@/features/admin/types/admin.types';
+import {
+ createEmptyUserFilters,
+ createEmptyUserForm,
+ type BatchEditForm,
+ type BatchPermissionForm,
+ type UserFilters,
+ type UserFormState,
+} from '@/features/admin/types/user.types';
+
+const EMAIL_PATTERN = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/;
+
+export function useUsersAdmin() {
+ const { t } = useI18n();
+ const msg = useMessage();
+
+ const users = ref([]);
+ const agents = ref([]);
+ const departments = ref([]);
+ const isLoading = ref(true);
+ const isSaving = ref(false);
+
+ const userFilters = ref(createEmptyUserFilters());
+ const hideRejected = ref(true);
+ const selectedUserIds = ref([]);
+
+ const showUserModal = ref(false);
+ const editingUser = ref(createEmptyUserForm());
+
+ const showBatchEditModal = ref(false);
+ const batchEditForm = ref({ department: '', role: '', status: '' });
+
+ const showBatchPermissionModal = ref(false);
+ const batchPermissionForm = ref({ agent_ids: [], action: 'add' });
+
+ const showDeleteConfirmDialog = ref(false);
+ const deleteConfirmMessage = ref('');
+ let deleteConfirmAction: (() => Promise | void) | null = null;
+
+ const filteredUsers = computed(() =>
+ users.value.filter((u) => {
+ if (hideRejected.value && u.status === 'rejected') return false;
+ for (const key of Object.keys(userFilters.value) as (keyof UserFilters)[]) {
+ const filterVal = userFilters.value[key].toLowerCase();
+ if (!filterVal) continue;
+ const userVal = u[key]?.toString().toLowerCase() || '';
+ if (!userVal.includes(filterVal)) return false;
+ }
+ return true;
+ }),
+ );
+
+ const loadUsers = async (): Promise => {
+ try {
+ users.value = await listAdminUsers();
+ } catch (e) {
+ console.error('Error loading users:', e);
+ users.value = [];
+ }
+ };
+
+ const loadAgents = async (): Promise => {
+ try {
+ agents.value = await listAdminAgents();
+ } catch (e) {
+ console.error('Error loading agents:', e);
+ agents.value = [];
+ }
+ };
+
+ const loadDepartments = async (): Promise => {
+ try {
+ departments.value = await listAdminDepartments();
+ } catch (e) {
+ console.error('Error loading departments:', e);
+ departments.value = [];
+ }
+ };
+
+ const loadAll = async (): Promise => {
+ isLoading.value = true;
+ await Promise.all([loadUsers(), loadAgents(), loadDepartments()]);
+ isLoading.value = false;
+ };
+
+ const openDeleteConfirm = (message: string, action: () => Promise | void): void => {
+ deleteConfirmMessage.value = message;
+ deleteConfirmAction = action;
+ showDeleteConfirmDialog.value = true;
+ };
+
+ const closeDeleteConfirm = (): void => {
+ showDeleteConfirmDialog.value = false;
+ deleteConfirmAction = null;
+ };
+
+ const confirmDelete = async (): Promise => {
+ if (!deleteConfirmAction) return;
+ try {
+ await deleteConfirmAction();
+ } finally {
+ closeDeleteConfirm();
+ }
+ };
+
+ const openCreateUserModal = (): void => {
+ editingUser.value = createEmptyUserForm();
+ showUserModal.value = true;
+ };
+
+ const openEditUserModal = (user: AdminUserRow): void => {
+ editingUser.value = {
+ id: user.id,
+ username: user.username,
+ email: user.email,
+ department: user.department || '',
+ role: user.role,
+ password: '',
+ real_name: user.real_name || '',
+ employee_id: user.employee_id || '',
+ phone_number: user.phone_number || '',
+ agent_ids: user.agent_ids || [],
+ };
+ showUserModal.value = true;
+ };
+
+ const saveUser = async (): Promise => {
+ const isCreate = !editingUser.value.id;
+
+ if (isCreate) {
+ if (!(editingUser.value.real_name || '').trim()) {
+ msg.warning(t('admin.user.msgs.realNameRequired'));
+ return;
+ }
+ if (!(editingUser.value.employee_id || '').trim()) {
+ msg.warning(t('admin.user.msgs.employeeIdRequired'));
+ return;
+ }
+ if (!(editingUser.value.phone_number || '').trim()) {
+ msg.warning(t('admin.user.msgs.phoneRequired'));
+ return;
+ }
+ if (!(editingUser.value.username || '').trim()) {
+ msg.warning(t('admin.user.msgs.usernameRequired'));
+ return;
+ }
+ const email = (editingUser.value.email || '').trim();
+ if (!email) {
+ msg.warning(t('admin.user.msgs.emailRequired'));
+ return;
+ }
+ if (!EMAIL_PATTERN.test(email)) {
+ msg.warning(t('admin.user.msgs.invalidEmail'));
+ return;
+ }
+ if (!(editingUser.value.password || '').trim()) {
+ msg.warning(t('admin.user.msgs.passwordRequired'));
+ return;
+ }
+ } else {
+ if (!editingUser.value.username) {
+ msg.warning(t('admin.user.msgs.usernameRequired'));
+ return;
+ }
+ const email = (editingUser.value.email || '').trim();
+ if (email && !EMAIL_PATTERN.test(email)) {
+ msg.warning(t('admin.user.msgs.invalidEmail'));
+ return;
+ }
+ }
+
+ isSaving.value = true;
+ try {
+ if (editingUser.value.id) {
+ await updateAdminUser(editingUser.value.id, {
+ email: editingUser.value.email,
+ department: editingUser.value.department,
+ role: editingUser.value.role,
+ password: editingUser.value.password || undefined,
+ real_name: editingUser.value.real_name,
+ employee_id: editingUser.value.employee_id,
+ phone_number: editingUser.value.phone_number,
+ agent_ids: editingUser.value.agent_ids,
+ });
+ } else {
+ await createAdminUser({
+ username: editingUser.value.username,
+ email: editingUser.value.email,
+ department: editingUser.value.department,
+ role: editingUser.value.role,
+ password: editingUser.value.password,
+ real_name: editingUser.value.real_name,
+ employee_id: editingUser.value.employee_id,
+ phone_number: editingUser.value.phone_number,
+ agent_ids: editingUser.value.agent_ids,
+ });
+ }
+ await loadUsers();
+ showUserModal.value = false;
+ } catch (e) {
+ console.error(e);
+ msg.error((e as Error).message || t('admin.msg.failed'));
+ } finally {
+ isSaving.value = false;
+ }
+ };
+
+ const cleanRejectedUsers = async (): Promise => {
+ openDeleteConfirm(t('admin.user.confirmClean'), async () => {
+ try {
+ const data = await cleanupRejectedAdminUsers();
+ msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
+ await loadUsers();
+ } catch (e) {
+ console.error(e);
+ msg.error((e as Error).message || t('admin.msg.requestFailed'));
+ }
+ });
+ };
+
+ const batchDeleteUsers = async (): Promise => {
+ if (selectedUserIds.value.length === 0) return;
+ const targetUserIds = [...selectedUserIds.value];
+ openDeleteConfirm(t('admin.user.confirmBatchDelete', { count: targetUserIds.length }), async () => {
+ try {
+ const data = await batchDeleteAdminUsers(targetUserIds);
+ msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
+ selectedUserIds.value = [];
+ await loadUsers();
+ } catch (e) {
+ console.error(e);
+ msg.error((e as Error).message || t('admin.msg.requestFailed'));
+ }
+ });
+ };
+
+ const toggleUserSelection = (userId: number): void => {
+ const index = selectedUserIds.value.indexOf(userId);
+ if (index === -1) selectedUserIds.value.push(userId);
+ else selectedUserIds.value.splice(index, 1);
+ };
+
+ const toggleAllUsers = (rows: AdminUserRow[]): void => {
+ if (selectedUserIds.value.length === rows.length) {
+ selectedUserIds.value = [];
+ } else {
+ selectedUserIds.value = rows.map((u) => u.id);
+ }
+ };
+
+ const openBatchEditModal = (): void => {
+ if (selectedUserIds.value.length === 0) return;
+ batchEditForm.value = { department: '', role: '', status: '' };
+ showBatchEditModal.value = true;
+ };
+
+ const openBatchPermissionModal = (): void => {
+ if (selectedUserIds.value.length === 0) return;
+ batchPermissionForm.value = { agent_ids: [], action: 'add' };
+ showBatchPermissionModal.value = true;
+ };
+
+ const submitBatchEdit = async (): Promise => {
+ isSaving.value = true;
+ try {
+ const data: Record = {};
+ if (batchEditForm.value.department) data.department = batchEditForm.value.department;
+ if (batchEditForm.value.role) data.role = batchEditForm.value.role;
+ if (batchEditForm.value.status) data.status = batchEditForm.value.status;
+ if (Object.keys(data).length === 0) {
+ msg.warning(t('admin.msg.enterOneField'));
+ return;
+ }
+ await batchUpdateAdminUsers(selectedUserIds.value, data);
+ await loadUsers();
+ showBatchEditModal.value = false;
+ selectedUserIds.value = [];
+ } catch (e) {
+ console.error(e);
+ msg.error((e as Error).message || t('admin.msg.batchUpdateFailed'));
+ } finally {
+ isSaving.value = false;
+ }
+ };
+
+ const submitBatchPermission = async (): Promise => {
+ if (batchPermissionForm.value.agent_ids.length === 0) {
+ msg.warning(t('admin.perm.msg.selectAgent'));
+ return;
+ }
+ isSaving.value = true;
+ try {
+ await batchUpdateAdminPermissions({
+ user_ids: selectedUserIds.value,
+ agent_ids: batchPermissionForm.value.agent_ids,
+ action: batchPermissionForm.value.action,
+ });
+ await loadUsers();
+ showBatchPermissionModal.value = false;
+ selectedUserIds.value = [];
+ } catch (e) {
+ console.error(e);
+ msg.error((e as Error).message || t('admin.msg.batchPermissionUpdateFailed'));
+ } finally {
+ isSaving.value = false;
+ }
+ };
+
+ return {
+ users,
+ agents,
+ departments,
+ isLoading,
+ isSaving,
+ userFilters,
+ hideRejected,
+ selectedUserIds,
+ filteredUsers,
+ showUserModal,
+ editingUser,
+ showBatchEditModal,
+ batchEditForm,
+ showBatchPermissionModal,
+ batchPermissionForm,
+ showDeleteConfirmDialog,
+ deleteConfirmMessage,
+ loadAll,
+ openCreateUserModal,
+ openEditUserModal,
+ saveUser,
+ cleanRejectedUsers,
+ batchDeleteUsers,
+ toggleUserSelection,
+ toggleAllUsers,
+ openBatchEditModal,
+ openBatchPermissionModal,
+ submitBatchEdit,
+ submitBatchPermission,
+ closeDeleteConfirm,
+ confirmDelete,
+ };
+}
diff --git a/frontend/src/features/admin/modules/wecom/WecomPage.vue b/frontend/src/features/admin/modules/wecom/WecomPage.vue
new file mode 100644
index 00000000..37fb2be9
--- /dev/null
+++ b/frontend/src/features/admin/modules/wecom/WecomPage.vue
@@ -0,0 +1,456 @@
+/**
+ * features/admin/modules/wecom/WecomPage.vue
+ * 企业微信管理独立页面。路由:/admin/wecom
+ */
+
+
+
+
+
+
+
+
+ {{ t('admin.wecom.title') }}
+ {{ t('admin.wecom.subtitle') }}
+
+
+
+ {{ t('admin.wecom.refresh') }}
+
+
+
+
+ {{ t('admin.wecom.quickBind') }}
+
+
+
+
+
+ {{ u.label }}
+ {{ u.employeeId || '' }}
+
+
+ {{ t('admin.wecom.noData') }}
+
+
+
+
+
+
+
+
+ {{ t('admin.wecom.bind') }}
+
+
+
+
+
+ {{ t('admin.wecom.systemSettings') }}
+
+
+
+
+
+
+
+ {{ t('admin.save') }}
+
+
+
+
+
+
+
+ {{ t('admin.wecom.notifyMetrics') }}
+
+
+ {{ t('admin.wecom.metricTotal') }}
+ {{ wecomNotifyMetrics.total }}
+
+
+ {{ t('admin.wecom.metricSuccessRate') }}
+ {{ wecomNotifyMetrics.send_success_rate }}%
+
+
+ {{ t('admin.wecom.metricOpenedRate') }}
+ {{ wecomNotifyMetrics.opened_24h_rate }}%
+
+
+ {{ t('admin.wecom.metricWindowDays') }}
+ {{ wecomNotifyMetrics.window_days }}
+
+
+
+
+
+
+ {{ t('admin.wecom.integrationCopyTitle') }}
+ {{ t('admin.wecom.integrationCopyDesc') }}
+ {{ t('admin.wecom.integrationCopySecretsNote') }}
+
+
+
+
+
+ {{ t('admin.wecom.copy') }}
+
+
+
+
+
+
+
+
+
+
+
+ | {{ t('admin.wecom.headers.user') }} |
+ {{ t('admin.wecom.headers.roleStatus') }} |
+ {{ t('admin.wecom.headers.wecomUserId') }} |
+ {{ t('admin.wecom.headers.unionId') }} |
+ {{ t('admin.wecom.headers.actions') }} |
+
+
+
+
+ | {{ t('admin.wecom.noData') }} |
+
+
+ |
+ {{ u.username }} (#{{ u.id }})
+ {{ u.real_name || '-' }} · {{ u.email }}
+ |
+ {{ t('admin.role.' + u.role) }} / {{ t('admin.status.' + u.status) }} |
+ {{ u.wecom_userid || '-' }} |
+ {{ u.wecom_unionid || '-' }} |
+
+
+
+ {{ t('admin.wecom.unbind') }}
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+ | {{ t('admin.wecom.auditHeaders.time') }} |
+ {{ t('admin.wecom.auditHeaders.source') }} |
+ {{ t('admin.wecom.auditHeaders.user') }} |
+ {{ t('admin.wecom.auditHeaders.status') }} |
+ {{ t('admin.wecom.auditHeaders.reason') }} |
+ {{ t('admin.wecom.auditHeaders.ip') }} |
+
+
+
+
+ | {{ t('admin.wecom.noAuditData') }} |
+
+
+ | {{ row.created_at || '-' }} |
+ {{ t('admin.wecom.sources.' + row.source) }} |
+ {{ row.username || '-' }} |
+
+
+ {{ t('admin.wecom.auditStatus.' + row.status) }}
+
+ |
+
+
+ {{ getWecomAuditReasonText(row) }}
+
+ {{ getWecomAuditMetaText(row) }}
+
+
+ |
+ {{ row.ip || '-' }} |
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/wecom/composables/useWecomAdmin.ts b/frontend/src/features/admin/modules/wecom/composables/useWecomAdmin.ts
new file mode 100644
index 00000000..acfb2b8b
--- /dev/null
+++ b/frontend/src/features/admin/modules/wecom/composables/useWecomAdmin.ts
@@ -0,0 +1,456 @@
+/**
+ * features/admin/modules/wecom/composables/useWecomAdmin.ts
+ * 企业微信:绑定、系统配置、通知、登录审计。
+ */
+import { computed, ref, watch } from 'vue';
+import { useI18n } from 'vue-i18n';
+import * as XLSX from 'xlsx';
+import {
+ bindAdminWecomUser,
+ getAdminWecomIntegrationManifest,
+ getAdminWecomNotifyMetrics,
+ getAdminWecomNotifySettings,
+ getAdminWecomSystemSettings,
+ listAdminUsers,
+ listAdminWecomBindings,
+ listAdminWecomLoginAudits,
+ saveAdminWecomNotifySettings,
+ saveAdminWecomSystemSettings,
+ unbindAdminWecomUser,
+} from '@/api/admin';
+import { useMessage } from '@/composables/useMessage';
+import type { AdminUserRow } from '@/features/admin/types/admin.types';
+import {
+ createDefaultWecomSystemSettings,
+ type WecomBindingRow,
+ type WecomIntegrationManifest,
+ type WecomLoginAuditRow,
+ type WecomNotifyMetrics,
+ type WecomNotifySettings,
+ type WecomSystemSettings,
+} from '@/features/admin/types/wecom.types';
+import { buildWecomAuditMeta, formatWecomAuditReason } from '@/utils/wecom';
+
+export function useWecomAdmin() {
+ const { t } = useI18n();
+ const msg = useMessage();
+
+ const users = ref([]);
+ const isLoading = ref(true);
+ const isSaving = ref(false);
+
+ const wecomBindings = ref([]);
+ const wecomLoginAudits = ref([]);
+ const wecomBindForm = ref({
+ user_id: '' as string | number,
+ wecom_userid: '',
+ wecom_unionid: '',
+ });
+ const wecomBindUserQuery = ref('');
+ const wecomBindUserDropdownOpen = ref(false);
+ const wecomBoundOnly = ref(false);
+ let wecomBindUserCloseTimer: ReturnType | null = null;
+ const wecomAuditSourceFilter = ref<'all' | 'wecom' | 'password'>('all');
+ const wecomAuditStatusFilter = ref<'all' | 'success' | 'failed'>('all');
+ const filteredWecomLoginAudits = computed(() => wecomLoginAudits.value);
+ const wecomNotifySettings = ref({
+ enabled: true,
+ base_url: '',
+ events: [],
+ });
+ const wecomNotifyEventsText = ref('');
+ const wecomNotifyMetrics = ref(null);
+ const wecomSystemSettings = ref(createDefaultWecomSystemSettings());
+ const wecomIntegrationManifest = ref(null);
+
+ const showDeleteConfirmDialog = ref(false);
+ const deleteConfirmMessage = ref('');
+ let deleteConfirmAction: (() => Promise | void) | null = null;
+
+ const wecomBindUserOptions = computed(() => {
+ const keyword = wecomBindUserQuery.value.trim().toLowerCase();
+ return users.value
+ .filter((u) => {
+ if (!keyword) return true;
+ return [u.real_name, u.employee_id, String(u.id)]
+ .filter(Boolean)
+ .some((val) => String(val).toLowerCase().includes(keyword));
+ })
+ .map((u) => ({
+ id: u.id,
+ label: `${u.real_name || u.username} ${u.employee_id ? `(${u.employee_id})` : ''}`.trim(),
+ employeeId: u.employee_id || '',
+ }));
+ });
+
+ const openDeleteConfirm = (message: string, action: () => Promise | void): void => {
+ deleteConfirmMessage.value = message;
+ deleteConfirmAction = action;
+ showDeleteConfirmDialog.value = true;
+ };
+
+ const closeDeleteConfirm = (): void => {
+ showDeleteConfirmDialog.value = false;
+ deleteConfirmAction = null;
+ };
+
+ const confirmDelete = async (): Promise => {
+ if (!deleteConfirmAction) return;
+ try {
+ await deleteConfirmAction();
+ } finally {
+ closeDeleteConfirm();
+ }
+ };
+
+ const loadUsers = async (): Promise => {
+ try {
+ users.value = await listAdminUsers();
+ } catch (e) {
+ console.error('Error loading users:', e);
+ users.value = [];
+ }
+ };
+
+ const loadWecomBindings = async (): Promise => {
+ try {
+ wecomBindings.value = await listAdminWecomBindings(wecomBoundOnly.value);
+ } catch (e) {
+ console.error('Error loading WeCom bindings:', e);
+ }
+ };
+
+ const loadWecomAudits = async (): Promise => {
+ try {
+ const params = new URLSearchParams({ limit: '200' });
+ if (wecomAuditSourceFilter.value !== 'all') {
+ params.set('source', wecomAuditSourceFilter.value);
+ }
+ if (wecomAuditStatusFilter.value !== 'all') {
+ params.set('status', wecomAuditStatusFilter.value);
+ }
+ wecomLoginAudits.value = await listAdminWecomLoginAudits(params.toString());
+ } catch (e) {
+ console.error('Error loading WeCom login audits:', e);
+ }
+ };
+
+ const loadWecomSystemSettings = async (): Promise => {
+ try {
+ wecomSystemSettings.value = await getAdminWecomSystemSettings();
+ } catch (e) {
+ console.error('Error loading WeCom system settings:', e);
+ }
+ };
+
+ const loadWecomIntegrationManifest = async (): Promise => {
+ try {
+ wecomIntegrationManifest.value = await getAdminWecomIntegrationManifest();
+ } catch (e) {
+ console.error('Error loading WeCom integration manifest:', e);
+ }
+ };
+
+ const loadWecomNotifySettings = async (): Promise => {
+ try {
+ wecomNotifySettings.value = await getAdminWecomNotifySettings();
+ wecomNotifyEventsText.value = (wecomNotifySettings.value.events || []).join(',');
+ } catch (e) {
+ console.error('Error loading WeCom notify settings:', e);
+ }
+ };
+
+ const loadWecomNotifyMetrics = async (): Promise => {
+ try {
+ wecomNotifyMetrics.value = await getAdminWecomNotifyMetrics();
+ } catch (e) {
+ console.error('Error loading WeCom notify metrics:', e);
+ }
+ };
+
+ const refreshWecomData = async (): Promise => {
+ await Promise.all([
+ loadWecomBindings(),
+ loadWecomAudits(),
+ loadWecomSystemSettings(),
+ loadWecomIntegrationManifest(),
+ loadWecomNotifySettings(),
+ loadWecomNotifyMetrics(),
+ ]);
+ };
+
+ const loadAll = async (): Promise => {
+ isLoading.value = true;
+ await Promise.all([loadUsers(), refreshWecomData()]);
+ isLoading.value = false;
+ };
+
+ const selectWecomBindUser = (id: number, label: string): void => {
+ wecomBindForm.value.user_id = id;
+ wecomBindUserQuery.value = label;
+ wecomBindUserDropdownOpen.value = false;
+ };
+
+ const scheduleCloseWecomBindUserDropdown = (): void => {
+ if (wecomBindUserCloseTimer) clearTimeout(wecomBindUserCloseTimer);
+ wecomBindUserCloseTimer = setTimeout(() => {
+ wecomBindUserDropdownOpen.value = false;
+ }, 150);
+ };
+
+ const copyText = async (text: string): Promise => {
+ if (!text) return;
+ try {
+ await navigator.clipboard.writeText(text);
+ msg.success(t('admin.wecom.msg.copySuccess'));
+ } catch (e) {
+ console.error(e);
+ msg.error(t('admin.wecom.msg.copyFailed'));
+ }
+ };
+
+ const getWecomAuditReasonText = (row: WecomLoginAuditRow) => formatWecomAuditReason(row, t);
+
+ const getWecomAuditMetaText = (row: WecomLoginAuditRow) => buildWecomAuditMeta(row, t).join(' | ');
+
+ function normalizeWecomPublicBase(input: string): string | null {
+ const raw = (input || '').trim();
+ if (!raw) return null;
+ let url = raw;
+ if (!/^https?:\/\//i.test(url)) url = `https://${url}`;
+ url = url.replace(/\/+$/, '');
+ try {
+ const u = new URL(url);
+ if (!u.hostname) return null;
+ return `${u.protocol}//${u.host}`;
+ } catch {
+ return null;
+ }
+ }
+
+ function ensureWecomIntegrationManifest(): void {
+ if (!wecomIntegrationManifest.value) {
+ wecomIntegrationManifest.value = {
+ public_base_url: '',
+ callback_url: '',
+ callback_token: '',
+ encoding_aes_key: '',
+ oauth_redirect_uri: '',
+ homepage_url: '',
+ trusted_domain: '',
+ authorize_api: '',
+ login_api: '',
+ };
+ }
+ }
+
+ function patchWecomIntegrationManifestFromSettings(): void {
+ ensureWecomIntegrationManifest();
+ const s = wecomSystemSettings.value;
+ const base = normalizeWecomPublicBase(s.public_base_url);
+ const prev = wecomIntegrationManifest.value!;
+ wecomIntegrationManifest.value = {
+ ...prev,
+ callback_token: s.callback_token || '',
+ encoding_aes_key: s.encoding_aes_key || '',
+ };
+ if (!base) return;
+ wecomIntegrationManifest.value = {
+ ...wecomIntegrationManifest.value!,
+ public_base_url: base,
+ callback_url: s.callback_url || `${base}/api/user/wecom/callback`,
+ oauth_redirect_uri: s.redirect_uri || `${base}/workspace`,
+ homepage_url: s.homepage_url || `${base}/workspace`,
+ trusted_domain: s.trusted_domain || new URL(base).hostname,
+ authorize_api: `${base}/api/user/wecom/authorize-url`,
+ login_api: `${base}/api/user/wecom/login`,
+ };
+ }
+
+ function generateWecomAddressesFromPublicBase(): void {
+ const base = normalizeWecomPublicBase(wecomSystemSettings.value.public_base_url);
+ if (!base) {
+ msg.warning(t('admin.wecom.msg.publicBaseRequired'));
+ return;
+ }
+ const host = new URL(base).hostname;
+ wecomSystemSettings.value.callback_url = `${base}/api/user/wecom/callback`;
+ wecomSystemSettings.value.homepage_url = `${base}/workspace`;
+ wecomSystemSettings.value.trusted_domain = host;
+ wecomSystemSettings.value.redirect_uri = `${base}/workspace`;
+ patchWecomIntegrationManifestFromSettings();
+ }
+
+ function generateWecomCallbackToken(): void {
+ const bytes = new Uint8Array(24);
+ crypto.getRandomValues(bytes);
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
+ wecomSystemSettings.value.callback_token = hex;
+ patchWecomIntegrationManifestFromSettings();
+ }
+
+ function generateWecomEncodingAesKey(): void {
+ const bytes = new Uint8Array(32);
+ crypto.getRandomValues(bytes);
+ let bin = '';
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);
+ const b64 = btoa(bin);
+ const key43 = b64.replace(/=+$/, '');
+ wecomSystemSettings.value.encoding_aes_key = key43;
+ patchWecomIntegrationManifestFromSettings();
+ }
+
+ const saveWecomSystemSettings = async (): Promise => {
+ isSaving.value = true;
+ try {
+ const payload = {
+ ...wecomSystemSettings.value,
+ match_operator: (wecomSystemSettings.value.match_operator || 'AND').toUpperCase(),
+ };
+ const data = await saveAdminWecomSystemSettings(payload);
+ wecomSystemSettings.value = data.settings || wecomSystemSettings.value;
+ await loadWecomIntegrationManifest();
+ } catch (e) {
+ console.error(e);
+ msg.error((e as Error).message || t('admin.msg.requestFailed'));
+ } finally {
+ isSaving.value = false;
+ }
+ };
+
+ const saveWecomNotifySettings = async (): Promise => {
+ isSaving.value = true;
+ try {
+ wecomNotifySettings.value.events = wecomNotifyEventsText.value
+ .split(',')
+ .map((x) => x.trim())
+ .filter(Boolean);
+ const data = await saveAdminWecomNotifySettings(wecomNotifySettings.value);
+ wecomNotifySettings.value = data.settings || wecomNotifySettings.value;
+ await loadWecomNotifyMetrics();
+ } catch (e) {
+ console.error(e);
+ msg.error((e as Error).message || t('admin.msg.requestFailed'));
+ } finally {
+ isSaving.value = false;
+ }
+ };
+
+ const bindWecomUser = async (): Promise => {
+ if (!wecomBindForm.value.user_id || !wecomBindForm.value.wecom_userid.trim()) {
+ msg.warning(t('admin.wecom.msg.bindInputRequired'));
+ return;
+ }
+ isSaving.value = true;
+ try {
+ await bindAdminWecomUser({
+ user_id: Number(wecomBindForm.value.user_id),
+ wecom_userid: wecomBindForm.value.wecom_userid.trim(),
+ wecom_unionid: wecomBindForm.value.wecom_unionid.trim() || undefined,
+ });
+ wecomBindUserQuery.value = '';
+ wecomBindUserDropdownOpen.value = false;
+ wecomBindForm.value.wecom_userid = '';
+ wecomBindForm.value.wecom_unionid = '';
+ await refreshWecomData();
+ msg.success(t('admin.wecom.msg.bindSuccess'));
+ } catch (e) {
+ console.error(e);
+ const errorMessage = (e as Error).message || t('admin.wecom.msg.bindFailed');
+ if (String(errorMessage).includes('already bound to user')) {
+ msg.error(t('admin.wecom.msg.boundConflict', { detail: errorMessage }));
+ } else {
+ msg.error(errorMessage);
+ }
+ } finally {
+ isSaving.value = false;
+ }
+ };
+
+ const unbindWecomUserByAdmin = async (userId: number): Promise => {
+ openDeleteConfirm(t('admin.wecom.confirmUnbind'), async () => {
+ isSaving.value = true;
+ try {
+ await unbindAdminWecomUser(userId);
+ await refreshWecomData();
+ } catch (e) {
+ console.error(e);
+ msg.error((e as Error).message || t('admin.wecom.msg.unbindFailed'));
+ } finally {
+ isSaving.value = false;
+ }
+ });
+ };
+
+ const exportWecomAudits = (): void => {
+ if (filteredWecomLoginAudits.value.length === 0) {
+ msg.warning(t('admin.wecom.noAuditData'));
+ return;
+ }
+ const rows = filteredWecomLoginAudits.value.map((row) => ({
+ Time: row.created_at || '',
+ Source: row.source || '',
+ Username: row.username || '',
+ Status: row.status || '',
+ Reason: getWecomAuditReasonText(row),
+ Meta: getWecomAuditMetaText(row),
+ ErrorCode: row.error_code || '',
+ MatchRules: row.match_rules || '',
+ MatchOperator: row.match_operator || '',
+ MatchResult: row.match_result || '',
+ IP: row.ip || '',
+ WecomUserId: row.wecom_userid || '',
+ UserAgent: row.user_agent || '',
+ }));
+ const ws = XLSX.utils.json_to_sheet(rows);
+ const wb = XLSX.utils.book_new();
+ XLSX.utils.book_append_sheet(wb, ws, 'wecom_login_audits');
+ XLSX.writeFile(wb, `wecom_login_audits_${new Date().toISOString().split('T')[0]}.xlsx`);
+ };
+
+ watch(wecomBoundOnly, () => {
+ void loadWecomBindings();
+ });
+
+ watch([wecomAuditSourceFilter, wecomAuditStatusFilter], () => {
+ void loadWecomAudits();
+ });
+
+ return {
+ isLoading,
+ isSaving,
+ wecomBindings,
+ wecomLoginAudits,
+ wecomBindForm,
+ wecomBindUserQuery,
+ wecomBindUserDropdownOpen,
+ wecomBindUserOptions,
+ wecomBoundOnly,
+ wecomAuditSourceFilter,
+ wecomAuditStatusFilter,
+ filteredWecomLoginAudits,
+ wecomNotifySettings,
+ wecomNotifyEventsText,
+ wecomNotifyMetrics,
+ wecomSystemSettings,
+ wecomIntegrationManifest,
+ showDeleteConfirmDialog,
+ deleteConfirmMessage,
+ loadAll,
+ refreshWecomData,
+ selectWecomBindUser,
+ scheduleCloseWecomBindUserDropdown,
+ copyText,
+ getWecomAuditReasonText,
+ getWecomAuditMetaText,
+ generateWecomAddressesFromPublicBase,
+ generateWecomCallbackToken,
+ generateWecomEncodingAesKey,
+ saveWecomSystemSettings,
+ saveWecomNotifySettings,
+ bindWecomUser,
+ unbindWecomUserByAdmin,
+ exportWecomAudits,
+ confirmDelete,
+ };
+}
diff --git a/frontend/src/features/admin/stores/admin-nav.store.ts b/frontend/src/features/admin/stores/admin-nav.store.ts
new file mode 100644
index 00000000..cf4722dd
--- /dev/null
+++ b/frontend/src/features/admin/stores/admin-nav.store.ts
@@ -0,0 +1,94 @@
+/**
+ * features/admin/stores/admin-nav.store.ts
+ * 管理后台导航 UI 状态(侧栏折叠、报表展开、角标)。
+ *
+ * 角标数据来自 GET /api/admin/dashboard/badges,在 store 内做 TTL 缓存与 in-flight 去重,
+ * 避免切换 admin 子路由时重复请求(AdminLayout 挂载一次即可)。
+ */
+import { defineStore } from 'pinia';
+import { ref } from 'vue';
+import { getAdminDashboardBadges } from '@/api/admin';
+import type { AdminModuleId } from '../types/admin.types';
+
+/** 角标缓存有效期(毫秒):此时间内 ensureBadges 直接复用内存中的计数 */
+const BADGE_CACHE_TTL_MS = 60_000;
+
+export const useAdminNavStore = defineStore('adminNav', () => {
+ const sidebarCollapsed = ref(false);
+ const reportsExpanded = ref(true);
+ /** 「用户审批」导航角标:pending 注册用户数 */
+ const pendingApprovalsCount = ref(0);
+ /** 「权限申请」导航角标:pending 权限申请数 */
+ const pendingRequestsCount = ref(0);
+
+ /** 上次成功拉取 badges 的时间戳;0 表示尚未拉取 */
+ let badgesFetchedAt = 0;
+ /** 进行中的 badges 请求 Promise,用于并发调用合并为单次 HTTP */
+ let badgesInFlight: Promise | null = null;
+
+ const toggleSidebar = (): void => {
+ sidebarCollapsed.value = !sidebarCollapsed.value;
+ };
+
+ const setBadgeCounts = (approvals: number, requests: number): void => {
+ pendingApprovalsCount.value = approvals;
+ pendingRequestsCount.value = requests;
+ };
+
+ const badgeForModule = (moduleId: AdminModuleId): number | undefined => {
+ if (moduleId === 'approvals' && pendingApprovalsCount.value > 0) return pendingApprovalsCount.value;
+ if (moduleId === 'requests' && pendingRequestsCount.value > 0) return pendingRequestsCount.value;
+ return undefined;
+ };
+
+ /**
+ * 拉取侧栏角标。force=false 时命中 TTL 缓存则跳过网络请求;
+ * 多个组件同时调用时会共享同一 inFlight,避免重复打 /dashboard/badges。
+ */
+ const fetchBadges = async (options?: { force?: boolean }): Promise => {
+ const force = options?.force ?? false;
+ const now = Date.now();
+
+ // 非强制刷新且缓存未过期:直接返回 store 中已有计数
+ if (!force && badgesFetchedAt > 0 && now - badgesFetchedAt < BADGE_CACHE_TTL_MS) {
+ return;
+ }
+
+ // 已有请求在飞:等待同一 Promise,不再发起第二次请求
+ if (badgesInFlight) {
+ return badgesInFlight;
+ }
+
+ badgesInFlight = (async () => {
+ try {
+ const data = await getAdminDashboardBadges();
+ setBadgeCounts(data.pending_approvals, data.pending_requests);
+ badgesFetchedAt = Date.now();
+ } catch {
+ setBadgeCounts(0, 0);
+ } finally {
+ badgesInFlight = null;
+ }
+ })();
+
+ return badgesInFlight;
+ };
+
+ /** AdminLayout onMounted:有有效缓存则跳过请求 */
+ const ensureBadges = (): Promise => fetchBadges({ force: false });
+
+ /** 审批/驳回操作后:忽略缓存,立即重新拉取角标 */
+ const refreshBadges = (): Promise => fetchBadges({ force: true });
+
+ return {
+ sidebarCollapsed,
+ reportsExpanded,
+ pendingApprovalsCount,
+ pendingRequestsCount,
+ toggleSidebar,
+ setBadgeCounts,
+ badgeForModule,
+ ensureBadges,
+ refreshBadges,
+ };
+});
diff --git a/frontend/src/features/admin/types/admin.types.ts b/frontend/src/features/admin/types/admin.types.ts
new file mode 100644
index 00000000..839115d8
--- /dev/null
+++ b/frontend/src/features/admin/types/admin.types.ts
@@ -0,0 +1,62 @@
+/**
+ * features/admin/types/admin.types.ts
+ * 管理后台域公共类型。
+ */
+
+export type AdminModuleId =
+ | 'dashboard'
+ | 'approvals'
+ | 'users'
+ | 'departments'
+ | 'agents'
+ | 'knowledge_base'
+ | 'schedules'
+ | 'announcements'
+ | 'questions'
+ | 'wecom'
+ | 'permissions'
+ | 'requests'
+ | 'reports';
+
+export type AdminReportTableId =
+ | 'users'
+ | 'agents'
+ | 'chat_logs'
+ | 'permission_requests'
+ | 'general_feedbacks'
+ | 'feedbacks';
+
+export interface AdminUserRow {
+ id: number;
+ username: string;
+ email: string;
+ department?: string;
+ role: string;
+ status: string;
+ real_name?: string;
+ employee_id?: string;
+ phone_number?: string;
+ agent_ids: number[];
+}
+
+export interface AdminDepartmentRow {
+ id: number;
+ name: string;
+ code?: string;
+ company?: string;
+ description?: string;
+}
+
+export interface AdminAgentOption {
+ id: number;
+ name: string;
+ type?: string;
+ dify_app_id?: string;
+}
+
+export interface AdminAnnouncementRow {
+ id: number;
+ title: string;
+ content: string;
+ created_at: string;
+}
diff --git a/frontend/src/features/admin/types/agent.types.ts b/frontend/src/features/admin/types/agent.types.ts
new file mode 100644
index 00000000..21759b22
--- /dev/null
+++ b/frontend/src/features/admin/types/agent.types.ts
@@ -0,0 +1,54 @@
+/**
+ * features/admin/types/agent.types.ts
+ *
+ * Agent 管理模块专用类型,供 AgentsPage 与相关 composable / 组件使用。
+ */
+
+export interface AgentRow {
+ id: number;
+ name: string;
+ dify_app_id: string;
+ dify_api_key: string;
+ is_active: boolean;
+ description?: string;
+ type: 'api' | 'iframe';
+ dify_app_type?: 'chatflow' | 'workflow';
+ api_base_url?: string;
+ extra_config?: Record;
+ /** 表单编辑时的 iframe 地址辅助字段 */
+ iframe_url?: string;
+}
+
+export interface AgentTestResult {
+ success: boolean;
+ request_url: string;
+ output_info: string;
+ analysis: string;
+ http_status?: number;
+ tested_at?: string;
+}
+
+export interface AgentFormState {
+ id?: number;
+ name: string;
+ dify_app_id: string;
+ dify_api_key: string;
+ description: string;
+ type: 'api' | 'iframe';
+ dify_app_type: 'chatflow' | 'workflow';
+ api_base_url: string;
+ iframe_url: string;
+ is_active: boolean;
+}
+
+export const createEmptyAgentForm = (): AgentFormState => ({
+ name: '',
+ dify_app_id: '',
+ dify_api_key: '',
+ description: '',
+ type: 'api',
+ dify_app_type: 'chatflow',
+ api_base_url: '',
+ iframe_url: '',
+ is_active: true,
+});
diff --git a/frontend/src/features/admin/types/announcement.types.ts b/frontend/src/features/admin/types/announcement.types.ts
new file mode 100644
index 00000000..e2a895a9
--- /dev/null
+++ b/frontend/src/features/admin/types/announcement.types.ts
@@ -0,0 +1,14 @@
+/**
+ * features/admin/types/announcement.types.ts
+ * 公告管理表单类型。
+ */
+
+export interface AnnouncementFormState {
+ title: string;
+ content: string;
+}
+
+export const createEmptyAnnouncementForm = (): AnnouncementFormState => ({
+ title: '',
+ content: '',
+});
diff --git a/frontend/src/features/admin/types/dashboard.types.ts b/frontend/src/features/admin/types/dashboard.types.ts
new file mode 100644
index 00000000..c4a279b0
--- /dev/null
+++ b/frontend/src/features/admin/types/dashboard.types.ts
@@ -0,0 +1,31 @@
+/**
+ * features/admin/types/dashboard.types.ts
+ * 管理后台仪表盘统计类型。
+ */
+
+/** GET /api/admin/dashboard/summary — 仪表盘四张卡片 */
+export interface AdminDashboardSummary {
+ agent_count: number;
+ user_count: number;
+ total_conversations: number;
+ avg_score: number;
+}
+
+/** GET /api/admin/dashboard/badges — 侧栏「用户审批」「权限申请」角标 */
+export interface AdminDashboardBadges {
+ pending_approvals: number;
+ pending_requests: number;
+}
+
+export interface AdminUsageReport {
+ total: number;
+ by_user: { username: string; count: number }[];
+ by_agent: { agent: string; count: number }[];
+ by_day: { date: string; count: number }[];
+}
+
+export interface AdminFeedbackReportSummary {
+ total: number;
+ avg_score: number;
+ distribution: { score: number; count: number }[];
+}
diff --git a/frontend/src/features/admin/types/department.types.ts b/frontend/src/features/admin/types/department.types.ts
new file mode 100644
index 00000000..623ed2a5
--- /dev/null
+++ b/frontend/src/features/admin/types/department.types.ts
@@ -0,0 +1,19 @@
+/**
+ * features/admin/types/department.types.ts
+ * 部门管理表单类型。
+ */
+
+export interface DepartmentFormState {
+ id?: number;
+ name: string;
+ code?: string;
+ company?: string;
+ description?: string;
+}
+
+export const createEmptyDepartmentForm = (): DepartmentFormState => ({
+ name: '',
+ code: '',
+ company: '',
+ description: '',
+});
diff --git a/frontend/src/features/admin/types/permission.types.ts b/frontend/src/features/admin/types/permission.types.ts
new file mode 100644
index 00000000..761b39c6
--- /dev/null
+++ b/frontend/src/features/admin/types/permission.types.ts
@@ -0,0 +1,16 @@
+/**
+ * features/admin/types/permission.types.ts
+ * 权限矩阵模块筛选类型。
+ */
+
+export interface PermissionFilters {
+ username: string;
+ department: string;
+ role: string;
+}
+
+export const createEmptyPermissionFilters = (): PermissionFilters => ({
+ username: '',
+ department: '',
+ role: '',
+});
diff --git a/frontend/src/features/admin/types/question.types.ts b/frontend/src/features/admin/types/question.types.ts
new file mode 100644
index 00000000..1d9f5749
--- /dev/null
+++ b/frontend/src/features/admin/types/question.types.ts
@@ -0,0 +1,28 @@
+/**
+ * features/admin/types/question.types.ts
+ * 常用问题管理类型。
+ */
+
+export interface AdminQuickQuestionRow {
+ id: number;
+ title: string;
+ question: string;
+ agent_id: number;
+ agent_name?: string;
+ sort_order: number;
+}
+
+export interface QuestionFormState {
+ id?: number;
+ title: string;
+ question: string;
+ agent_id?: number;
+ sort_order: number;
+}
+
+export const createEmptyQuestionForm = (): QuestionFormState => ({
+ title: '',
+ question: '',
+ agent_id: undefined,
+ sort_order: 0,
+});
diff --git a/frontend/src/features/admin/types/report.types.ts b/frontend/src/features/admin/types/report.types.ts
new file mode 100644
index 00000000..813bb7c7
--- /dev/null
+++ b/frontend/src/features/admin/types/report.types.ts
@@ -0,0 +1,31 @@
+/**
+ * features/admin/types/report.types.ts
+ * 报表模块类型。
+ */
+
+export interface UsageReport {
+ total: number;
+ by_user: { username: string; count: number }[];
+ by_agent: { agent: string; count: number }[];
+ by_day: { date: string; count: number }[];
+}
+
+export interface ReportColumnConfig {
+ key: string;
+ visible: boolean;
+ width: number;
+}
+
+export interface ChatLogsLayoutPref {
+ columns: ReportColumnConfig[];
+ wrapEnabled: boolean;
+ wrapMaxHeight: number;
+ sortRules?: SortRule[];
+}
+
+export type SortDirection = 'asc' | 'desc';
+
+export interface SortRule {
+ key: string;
+ direction: SortDirection;
+}
diff --git a/frontend/src/features/admin/types/request.types.ts b/frontend/src/features/admin/types/request.types.ts
new file mode 100644
index 00000000..dc78be66
--- /dev/null
+++ b/frontend/src/features/admin/types/request.types.ts
@@ -0,0 +1,14 @@
+/**
+ * features/admin/types/request.types.ts
+ * 权限申请管理类型。
+ */
+
+export interface AdminPermissionRequestRow {
+ id: number;
+ user_id: number;
+ agent_id: number;
+ reason: string;
+ status: string;
+ created_at: string;
+ reviewed_at?: string | null;
+}
diff --git a/frontend/src/features/admin/types/user.types.ts b/frontend/src/features/admin/types/user.types.ts
new file mode 100644
index 00000000..6f665dd7
--- /dev/null
+++ b/frontend/src/features/admin/types/user.types.ts
@@ -0,0 +1,63 @@
+/**
+ * features/admin/types/user.types.ts
+ * 用户管理模块表单与筛选类型。
+ */
+
+export interface UserFormState {
+ id: number | null;
+ username: string;
+ email: string;
+ department: string;
+ role: string;
+ password: string;
+ real_name: string;
+ employee_id: string;
+ phone_number: string;
+ agent_ids: number[];
+}
+
+export interface UserFilters {
+ username: string;
+ email: string;
+ department: string;
+ role: string;
+ status: string;
+ real_name: string;
+ employee_id: string;
+ phone_number: string;
+}
+
+export interface BatchEditForm {
+ department: string;
+ role: string;
+ status: string;
+}
+
+export interface BatchPermissionForm {
+ agent_ids: number[];
+ action: 'add' | 'remove' | 'set';
+}
+
+export const createEmptyUserForm = (): UserFormState => ({
+ id: null,
+ username: '',
+ email: '',
+ department: '',
+ role: 'user',
+ password: '',
+ real_name: '',
+ employee_id: '',
+ phone_number: '',
+ agent_ids: [],
+});
+
+export const createEmptyUserFilters = (): UserFilters => ({
+ username: '',
+ email: '',
+ department: '',
+ role: '',
+ status: '',
+ real_name: '',
+ employee_id: '',
+ phone_number: '',
+});
diff --git a/frontend/src/features/admin/types/wecom.types.ts b/frontend/src/features/admin/types/wecom.types.ts
new file mode 100644
index 00000000..b1e9e0f3
--- /dev/null
+++ b/frontend/src/features/admin/types/wecom.types.ts
@@ -0,0 +1,104 @@
+/**
+ * features/admin/types/wecom.types.ts
+ * 企业微信管理模块类型。
+ */
+
+export interface WecomBindingRow {
+ id: number;
+ username: string;
+ real_name?: string;
+ email: string;
+ role: string;
+ status: string;
+ wecom_userid?: string | null;
+ wecom_unionid?: string | null;
+ bound: boolean;
+}
+
+export interface WecomLoginAuditRow {
+ id: number;
+ user_id?: number | null;
+ username?: string | null;
+ source: string;
+ status: string;
+ reason?: string | null;
+ wecom_userid?: string | null;
+ ip?: string | null;
+ user_agent?: string | null;
+ created_at?: string | null;
+ error_code?: string | null;
+ match_rules?: string | null;
+ match_operator?: string | null;
+ match_result?: string | null;
+}
+
+export interface WecomNotifySettings {
+ enabled: boolean;
+ base_url: string;
+ events: string[];
+}
+
+export interface WecomNotifyMetrics {
+ window_days: number;
+ total: number;
+ sent: number;
+ failed: number;
+ send_success_rate: number;
+ opened_24h: number;
+ opened_24h_rate: number;
+ by_event: Record;
+}
+
+export interface WecomSystemSettings {
+ enabled: boolean;
+ corp_id: string;
+ agent_id: string;
+ secret: string;
+ redirect_uri: string;
+ auto_create_user: boolean;
+ match_rules: string;
+ match_operator: 'AND' | 'OR';
+ first_login_bind_mode: 'match_rules' | 'input_verify';
+ first_login_input_fields: string;
+ employee_id_source: string;
+ mobile_normalize: boolean;
+ callback_token: string;
+ encoding_aes_key: string;
+ callback_url: string;
+ homepage_url: string;
+ trusted_domain: string;
+ public_base_url: string;
+}
+
+export interface WecomIntegrationManifest {
+ public_base_url: string;
+ callback_url: string;
+ callback_token: string;
+ encoding_aes_key: string;
+ oauth_redirect_uri: string;
+ homepage_url: string;
+ trusted_domain: string;
+ authorize_api: string;
+ login_api: string;
+}
+
+export const createDefaultWecomSystemSettings = (): WecomSystemSettings => ({
+ enabled: true,
+ corp_id: '',
+ agent_id: '',
+ secret: '',
+ redirect_uri: '',
+ auto_create_user: true,
+ match_rules: 'employee_id,mobile',
+ match_operator: 'AND',
+ first_login_bind_mode: 'match_rules',
+ first_login_input_fields: 'employee_id,mobile,email',
+ employee_id_source: 'userid',
+ mobile_normalize: true,
+ callback_token: '',
+ encoding_aes_key: '',
+ callback_url: '',
+ homepage_url: '',
+ trusted_domain: '',
+ public_base_url: '',
+});
diff --git a/frontend/src/features/admin/views/AdminLayout.vue b/frontend/src/features/admin/views/AdminLayout.vue
new file mode 100644
index 00000000..bb518aed
--- /dev/null
+++ b/frontend/src/features/admin/views/AdminLayout.vue
@@ -0,0 +1,52 @@
+/**
+ * features/admin/views/AdminLayout.vue
+ * 管理后台壳层:顶栏 + AdminNav + 子路由出口。
+ * 角标仅在 Layout 首次挂载时 ensureBadges(store 内 60s TTL 缓存)。
+ */
+
+
+
+
+
diff --git a/frontend/src/features/auth/composables/useAuth.ts b/frontend/src/features/auth/composables/useAuth.ts
new file mode 100644
index 00000000..15ea24bc
--- /dev/null
+++ b/frontend/src/features/auth/composables/useAuth.ts
@@ -0,0 +1,23 @@
+import { storeToRefs } from 'pinia';
+import { useAuthStore } from '../stores/auth.store';
+
+/**
+ * 认证 composable:新代码的统一入口。
+ */
+export function useAuth() {
+ const store = useAuthStore();
+ const { user, isLoggedIn, isAdmin, isGuest, token } = storeToRefs(store);
+
+ return {
+ user,
+ isLoggedIn,
+ isAdmin,
+ isGuest,
+ token,
+ login: store.login,
+ logout: store.logout,
+ refreshAccessToken: store.refreshAccessToken,
+ getHeaders: store.getHeaders,
+ syncFromStorage: store.syncFromStorage,
+ };
+}
diff --git a/frontend/src/features/auth/index.ts b/frontend/src/features/auth/index.ts
new file mode 100644
index 00000000..8d9f8b53
--- /dev/null
+++ b/frontend/src/features/auth/index.ts
@@ -0,0 +1,2 @@
+export { useAuthStore, bindAuthStoreSync } from './stores/auth.store';
+export { useAuth } from './composables/useAuth';
diff --git a/frontend/src/features/auth/stores/auth.store.ts b/frontend/src/features/auth/stores/auth.store.ts
new file mode 100644
index 00000000..eb1e9680
--- /dev/null
+++ b/frontend/src/features/auth/stores/auth.store.ts
@@ -0,0 +1,85 @@
+/**
+ * features/auth/stores/auth.store.ts
+ * 认证全局状态;Phase 0 仍委托 utils/auth 读写 storage。
+ */
+import { defineStore } from 'pinia';
+import { computed, ref } from 'vue';
+import {
+ getStoredAuthUser,
+ getAuthToken,
+ getAuthHeaders,
+ saveAuthUser,
+ logoutAuth as logoutAuthStorage,
+ refreshAccessToken as refreshAccessTokenStorage,
+} from '@/utils/auth';
+
+export interface AuthUser {
+ id?: number;
+ username?: string;
+ real_name?: string;
+ employee_id?: string;
+ role?: string;
+ token?: string;
+ access_token?: string;
+ refresh_token?: string;
+ expires_in?: number;
+ token_expires_at?: number;
+}
+
+let _syncBound = false;
+
+export const useAuthStore = defineStore('auth', () => {
+ const user = ref(getStoredAuthUser());
+
+ const syncFromStorage = (): void => {
+ user.value = getStoredAuthUser();
+ };
+
+ const isLoggedIn = computed(() => !!user.value && user.value.role !== 'guest');
+ const isAdmin = computed(() => user.value?.role === 'admin');
+ const isGuest = computed(() => user.value?.role === 'guest');
+ const token = computed(() => getAuthToken());
+
+ const login = (nextUser: AuthUser, remember = false): void => {
+ saveAuthUser(nextUser, remember);
+ syncFromStorage();
+ };
+
+ const logout = (): void => {
+ logoutAuthStorage();
+ user.value = null;
+ };
+
+ const refreshAccessToken = (): Promise =>
+ refreshAccessTokenStorage().then((accessToken) => {
+ if (accessToken) syncFromStorage();
+ return accessToken;
+ });
+
+ const getHeaders = (): Record => getAuthHeaders();
+
+ return {
+ user,
+ isLoggedIn,
+ isAdmin,
+ isGuest,
+ token,
+ syncFromStorage,
+ login,
+ logout,
+ refreshAccessToken,
+ getHeaders,
+ };
+});
+
+export function bindAuthStoreSync(): void {
+ if (_syncBound) return;
+ _syncBound = true;
+ const store = useAuthStore();
+ window.addEventListener('hxops:logout', () => {
+ store.user = null;
+ });
+ window.addEventListener('storage', (event: StorageEvent) => {
+ if (event.key === 'hxops_user') store.syncFromStorage();
+ });
+}
diff --git a/frontend/src/features/chat/stores/chat.store.ts b/frontend/src/features/chat/stores/chat.store.ts
new file mode 100644
index 00000000..b55fa106
--- /dev/null
+++ b/frontend/src/features/chat/stores/chat.store.ts
@@ -0,0 +1,20 @@
+import { defineStore } from 'pinia';
+import { ref } from 'vue';
+
+/**
+ * 聊天域共享状态骨架。Phase 2 迁移 ChatView 时会话列表、当前 agent 等迁入此处。
+ */
+export const useChatStore = defineStore('chat', () => {
+ const currentAgentId = ref(null);
+ const sidebarCollapsed = ref(false);
+
+ const setCurrentAgentId = (agentId: number | null): void => {
+ currentAgentId.value = agentId;
+ };
+
+ return {
+ currentAgentId,
+ sidebarCollapsed,
+ setCurrentAgentId,
+ };
+});
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index 191d957e..38e96ebc 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -1,29 +1,25 @@
-import { createApp } from 'vue'
-import './style.css'
-import App from './App.vue'
-import router from './router'
-import i18n from './i18n'
-import { config } from './config'
-import { refreshAccessToken, getAuthToken, initAuthSync } from './utils/auth'
-import { initAgentTabSync } from './utils/agentTabs'
+import { createApp } from 'vue';
+import './style.css';
+import App from './App.vue';
+import router from './app/router';
+import i18n from './i18n';
+import { config } from './config';
+import { pinia } from './app/plugins/pinia';
+import { bindAuthStoreSync } from './features/auth/stores/auth.store';
+import { refreshAccessToken, getAuthToken, initAuthSync } from './utils/auth';
+import { initAgentTabSync } from './utils/agentTabs';
initAuthSync();
initAgentTabSync();
-
-// Set document title from config
document.title = config.appTitle || 'AI工作台';
-// Global 401 interceptor for API calls.
const _rawFetch = window.fetch.bind(window);
window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise => {
- // Keep original request closure so we can retry with a refreshed token.
const runFetch = (nextInit?: RequestInit) => _rawFetch(input, nextInit);
let reqInit = init;
let res = await runFetch(reqInit);
try {
- const url = typeof input === 'string'
- ? input
- : (input instanceof URL ? input.toString() : input.url);
+ const url = typeof input === 'string' ? input : (input instanceof URL ? input.toString() : input.url);
const isApi = url.includes('/api/');
const isRefreshApi = url.includes('/api/user/casdoor/refresh');
const isLoginApi =
@@ -31,18 +27,15 @@ window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise {
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 2e7ca496..01551184 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -1,103 +1,2 @@
-
-
-import { createRouter, createWebHistory } from 'vue-router';
-import WorkspaceView from '../views/WorkspaceView.vue';
-import ChatView from '../views/ChatView.vue';
-import AdminView from '../views/AdminView.vue';
-import ResetPasswordView from '../views/ResetPasswordView.vue';
-import KbWorkspaceView from '../views/KbWorkspaceView.vue';
-import { config } from '../config';
-import { getStoredAuthUser } from '../utils/auth';
-
-const routes = [
- {
- path: '/',
- name: 'Home',
- component: WorkspaceView
- },
- {
- path: '/workspace',
- name: 'Workspace',
- component: WorkspaceView
- },
- {
- path: '/casdoor-callback',
- name: 'CasdoorCallback',
- component: WorkspaceView
- },
- {
- path: '/reset-password',
- name: 'ResetPassword',
- component: ResetPasswordView
- },
- {
- path: '/chat/:agentId',
- name: 'Chat',
- component: ChatView,
- props: true
- },
- {
- path: '/admin',
- name: 'Admin',
- component: AdminView
- },
- {
- path: '/kb/workspace',
- name: 'KbWorkspace',
- component: KbWorkspaceView,
- meta: { title: '知识库工作台' }
- },
- {
- path: '/kb/admin',
- redirect: { path: '/admin', query: { module: 'knowledge_base' } }
- },
-
-];
-
-const router = createRouter({
- history: createWebHistory(),
- routes
-});
-
-const DEFAULT_CHAT_AGENT_ID = 16;
-
-const publicPaths = ['/', '/workspace', '/casdoor-callback', '/reset-password'];
-
-router.beforeEach((to, _from, next) => {
- const user = getStoredAuthUser();
- const isLoggedIn = !!user && user.role !== 'guest';
-
- if (to.path === '/admin') {
- if (!user || user.role !== 'admin') {
- next('/workspace');
- return;
- }
- }
-
- if (to.path === '/') {
- if (isLoggedIn) {
- next(`/chat/${DEFAULT_CHAT_AGENT_ID}`);
- return;
- }
- next('/workspace');
- return;
- }
-
- if (!isLoggedIn && !publicPaths.includes(to.path)) {
- next('/workspace');
- return;
- }
-
- next();
-});
-
-router.afterEach((to) => {
- const baseTitle = config.appTitle || 'AI工作台';
- if (to.meta.title) {
- document.title = `${to.meta.title} - ${baseTitle}`;
- } else {
- document.title = baseTitle;
- }
-});
-
-export default router;
+/** @deprecated 请改用 `@/app/router`;保留此文件以兼容现有 import。 */
+export { default } from '@/app/router';
diff --git a/frontend/src/shared/api/client.ts b/frontend/src/shared/api/client.ts
new file mode 100644
index 00000000..4cff376e
--- /dev/null
+++ b/frontend/src/shared/api/client.ts
@@ -0,0 +1,12 @@
+/**
+ * shared/api/client.ts
+ * 转发至现有 api/client,后续迁移实现到此文件。
+ */
+export {
+ BusinessError,
+ isEnvelope,
+ requestJson,
+ type ApiSuccessEnvelope,
+ type ApiErrorBody,
+ type ApiErrorEnvelope,
+} from '@/api/client';
diff --git a/frontend/src/shared/constants/routes.ts b/frontend/src/shared/constants/routes.ts
new file mode 100644
index 00000000..3d9f5421
--- /dev/null
+++ b/frontend/src/shared/constants/routes.ts
@@ -0,0 +1,10 @@
+/** 无需登录即可访问的路由 path */
+export const PUBLIC_PATHS = ['/', '/workspace', '/casdoor-callback', '/reset-password'] as const;
+
+/** 登录后首页默认跳转的 Agent ID */
+export const DEFAULT_CHAT_AGENT_ID = 16;
+
+export type PublicPath = (typeof PUBLIC_PATHS)[number];
+
+export const isPublicPath = (path: string): path is PublicPath =>
+ (PUBLIC_PATHS as readonly string[]).includes(path);
diff --git a/frontend/src/shared/types/auth.types.ts b/frontend/src/shared/types/auth.types.ts
new file mode 100644
index 00000000..94433c4b
--- /dev/null
+++ b/frontend/src/shared/types/auth.types.ts
@@ -0,0 +1 @@
+export type { AuthUser } from '@/utils/auth';
diff --git a/frontend/src/views/AdminView.vue b/frontend/src/views/AdminView.vue
deleted file mode 100644
index a164d9b5..00000000
--- a/frontend/src/views/AdminView.vue
+++ /dev/null
@@ -1,6284 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- +2 {{ t('admin.dash.new') }}
-
- {{ agents.length }}
- {{ t('admin.dash.activeAgents') }}
-
-
-
-
- {{ users.length }}
- {{ t('admin.dash.totalUsers') }}
-
-
-
-
- {{ usageReport?.total ?? 0 }}
- {{ t('admin.dash.totalConversations') }}
-
-
-
-
- {{ Number(feedbackReportSummary?.avg_score ?? 0).toFixed(1) }}
- {{ t('admin.dash.avgRating') }}
-
-
-
-
-
-
-
-
-
-
- | {{ t('admin.approval.headers.username') }} |
- {{ t('admin.approval.headers.nameId') }} |
- {{ t('admin.approval.headers.contact') }} |
- {{ t('admin.approval.headers.role') }} |
- {{ t('admin.approval.headers.actions') }} |
-
-
-
-
- | {{ t('admin.approval.noPending') }} |
-
-
- |
- {{ user.username }}
- {{ user.email }}
- |
-
- {{ user.real_name || '-' }}
- {{ user.employee_id || '-' }}
- |
- {{ user.phone_number || '-' }} |
-
-
- {{ t('admin.role.' + user.role) }}
-
- |
-
-
-
-
-
-
-
- |
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- |
-
- |
- {{ t('admin.user.headers.user') }} |
- {{ t('admin.user.headers.role') }} |
- {{ t('admin.user.headers.dept') }} |
- {{ t('admin.user.headers.status') }} |
- {{ t('admin.user.headers.actions') }} |
-
-
-
-
- | {{ t('admin.user.noUsers') }} |
-
-
- |
-
- |
-
-
-
- {{ user.username.charAt(0).toUpperCase() }}
-
-
- {{ user.username }}
- {{ user.email }}
-
-
- |
-
-
- {{ t('admin.role.' + user.role) }}
-
- |
-
- {{ user.department || '-' }}
- |
-
-
- {{ t('admin.status.' + user.status) }}
-
- |
-
-
- {{ t('admin.edit') }}
-
- |
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.dept.title') }}
- {{ t('admin.dept.subtitle') }}
-
-
-
-
-
-
- {{ editingDept.id ? t('admin.dept.edit') : t('admin.dept.add') }}
-
-
-
-
-
-
- {{ t('admin.dept.noDepts') }}
-
-
-
-
- | {{ t('admin.dept.headers.name') }} |
- {{ t('admin.dept.headers.code') }} |
- {{ t('admin.dept.headers.company') }} |
- {{ t('admin.dept.headers.actions') }} |
-
-
-
-
- |
- {{ d.name }}
- {{ d.description }}
- |
- {{ d.code || '-' }} |
- {{ d.company || '-' }} |
-
-
-
-
-
-
-
- |
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.agent.noAgents') }}
-
-
-
-
- | {{ t('admin.agent.headers.name') }} |
- {{ t('admin.agent.headers.type') }} |
- {{ t('admin.agent.headers.config') }} |
- {{ t('admin.agent.headers.status') }} |
- {{ t('admin.agent.headers.actions') }} |
-
-
-
-
- |
- {{ agent.name }}
- {{ agent.description }}
- |
-
-
- {{ agent.type }}
-
- |
-
-
- {{ t('admin.agent.idLabel') }}: {{ agent.dify_app_id }}
-
-
- {{ t('admin.agent.urlLabel') }}: {{ agent.extra_config?.iframe_url }}
-
- |
-
-
-
- {{ agent.is_active ? t('admin.status.active') : t('admin.status.disabled') }}
-
- |
-
-
- {{ t('admin.agent.test') }}
-
-
-
-
-
-
-
- |
-
-
-
-
-
-
-
-
-
- {{ t('admin.announcement.title') }}
- {{ t('admin.announcement.subtitle') }}
-
-
-
-
- {{ t('admin.announcement.add') }}
-
-
-
-
-
-
-
-
-
-
-
- {{ isSaving ? t('admin.save') + '...' : t('admin.announcement.publish') }}
-
-
-
-
-
-
-
- {{ t('admin.announcement.noData') }}
-
-
-
-
-
- {{ ann.title }}
- {{ new Date(ann.created_at).toLocaleString() }}
-
-
-
-
-
- {{ ann.content }}
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.question.title') }}
- {{ t('admin.question.subtitle') }}
-
-
-
-
-
-
- {{ isEditingQuestion ? t('admin.question.edit') : t('admin.question.add') }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.cancel') }}
-
- {{ isSaving ? t('admin.save') + '...' : (isEditingQuestion ? t('admin.update') : t('admin.add')) }}
-
-
-
-
-
-
-
-
- {{ t('admin.question.noData') }}
-
-
-
-
- | {{ t('admin.question.headers.title') }} |
- {{ t('admin.question.headers.agent') }} |
- {{ t('admin.question.headers.order') }} |
- {{ t('admin.question.headers.actions') }} |
-
-
-
-
- |
- {{ q.title }}
- {{ q.question }}
- |
-
-
- {{ q.agent_name || 'Unknown' }}
-
- |
- {{ q.sort_order }} |
-
-
-
-
-
-
-
- |
-
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.perm.title') }}
- {{ t('admin.perm.subtitle') }}
-
-
-
-
- {{ t('admin.perm.batchAssign') }}
-
-
-
-
- {{ t('admin.perm.exportCsv') }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- |
-
- |
- {{ t('admin.perm.headers.user') }} |
- {{ t('admin.perm.headers.dept') }} |
-
-
- {{ agent.name }}
- {{ agent.type }}
-
- |
-
-
-
-
- |
-
- |
-
-
-
- {{ user.username.charAt(0).toUpperCase() }}
-
-
- {{ user.username }}
- {{ user.email }}
-
-
- |
-
- {{ user.department || '-' }}
- |
-
-
- |
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ scheduleViewMode === 'overview' ? $t('admin.schedule.overviewTitle') : $t('admin.schedule.workbenchTitle') }}
-
-
- {{ scheduleViewMode === 'overview' ? $t('admin.schedule.overviewSubtitle') : $t('admin.schedule.workbenchSubtitle') }}
-
-
-
-
-
- {{ $t('admin.schedule.refresh') }}
-
-
-
-
-
-
-
-
- {{ schedules.length }}
- {{ $t('admin.schedule.stats.total') }}
-
-
- {{ scheduleEnabledCount }}
- {{ $t('admin.schedule.stats.enabled') }}
-
-
- {{ scheduleDisabledCount }}
- {{ $t('admin.schedule.stats.disabled') }}
-
-
- {{ scheduleRunningCount }}
- {{ $t('admin.schedule.stats.running') }}
-
-
-
-
- {{ $t('admin.schedule.sectionOverview') }}
- {{ $t('admin.schedule.switchByCard') }}
-
- {{ $t('admin.schedule.loading') }}
-
-
-
-
-
-
- {{ $t('admin.schedule.addTitle') }}
-
-
- {{ $t('admin.schedule.addHint') }}
-
-
-
-
- {{ $t('admin.schedule.addButton') }}
-
-
-
-
-
-
-
-
- {{ s.name }}
-
- {{ s.enabled ? $t('admin.schedule.enabled') : $t('admin.schedule.disabled') }}
-
-
- {{ $t('admin.schedule.scheduleNo') }}:{{ s.schedule_no }}
- Cron:{{ s.cron_expr }}
-
- {{ $t('admin.schedule.config') }}:{{ s.platform_api_path }}
-
- {{ $t('admin.schedule.owner') }}:{{ s.owner_username || s.owner_user_id }}
-
-
-
-
- {{ $t('admin.schedule.lastRun') }}:{{ formatDateTime(s.last_run_at) }}
-
-
- {{ $t('admin.schedule.nextRun') }}:{{ formatDateTime(s.next_run_at) }}
-
-
-
-
- {{ $t('admin.schedule.actions.edit') }}
-
-
-
- {{ $t('admin.schedule.actions.start') }}
-
-
-
- {{ $t('admin.schedule.actions.pause') }}
-
-
-
- {{ $t('admin.schedule.actions.run') }}
-
-
-
- {{ $t('admin.schedule.actions.test') }}
-
-
-
- {{ $t('admin.schedule.actions.delete') }}
-
-
-
-
-
- {{ $t('admin.schedule.emptyList') }}
-
-
-
-
-
-
-
-
-
-
- {{ selectedSchedule?.name || $t('admin.schedule.noSelection') }}
- {{ $t('admin.schedule.selectedHint', { time: selectedScheduleLatestRunAt }) }}
-
-
- {{ selectedScheduleRuns.length }}
- {{ $t('admin.schedule.runBatches') }}
-
-
- {{ selectedScheduleRunMetrics.total }}
- {{ $t('admin.schedule.totalProcessed') }}
-
-
- {{ selectedScheduleRunMetrics.success }}
- {{ $t('admin.schedule.totalSuccess') }}
-
-
- {{ selectedScheduleRunMetrics.failed }}
- {{ $t('admin.schedule.totalFailed') }}
-
-
-
-
-
-
-
- {{ $t('admin.schedule.listTitle') }}
- {{ $t('admin.schedule.switchByCard') }}
-
-
-
-
-
- {{ s.name }}
- {{ s.schedule_no }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ s.enabled ? $t('admin.schedule.enabled') : $t('admin.schedule.disabled') }}
-
-
-
-
-
-
-
-
-
-
- {{ $t('admin.schedule.recordsTitle', { name: selectedSchedule.name }) }}
- {{ $t('admin.schedule.recordsSubtitle') }}
-
-
-
-
-
-
- {{ $t('admin.schedule.noSelectionHint') }}
-
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.wecom.title') }}
- {{ t('admin.wecom.subtitle') }}
-
-
-
- {{ t('admin.wecom.refresh') }}
-
-
-
-
- {{ t('admin.wecom.quickBind') }}
-
-
-
-
-
- {{ u.label }}
- {{ u.employeeId || '' }}
-
-
- {{ t('admin.wecom.noData') }}
-
-
-
-
-
-
-
-
- {{ t('admin.wecom.bind') }}
-
-
-
-
-
- {{ t('admin.wecom.systemSettings') }}
-
-
-
-
-
-
-
- {{ t('admin.save') }}
-
-
-
-
-
-
-
- {{ t('admin.wecom.notifyMetrics') }}
-
-
- {{ t('admin.wecom.metricTotal') }}
- {{ wecomNotifyMetrics.total }}
-
-
- {{ t('admin.wecom.metricSuccessRate') }}
- {{ wecomNotifyMetrics.send_success_rate }}%
-
-
- {{ t('admin.wecom.metricOpenedRate') }}
- {{ wecomNotifyMetrics.opened_24h_rate }}%
-
-
- {{ t('admin.wecom.metricWindowDays') }}
- {{ wecomNotifyMetrics.window_days }}
-
-
-
-
-
-
- {{ t('admin.wecom.integrationCopyTitle') }}
- {{ t('admin.wecom.integrationCopyDesc') }}
- {{ t('admin.wecom.integrationCopySecretsNote') }}
-
-
-
-
-
- {{ t('admin.wecom.copy') }}
-
-
-
-
-
-
-
-
-
-
-
- | {{ t('admin.wecom.headers.user') }} |
- {{ t('admin.wecom.headers.roleStatus') }} |
- {{ t('admin.wecom.headers.wecomUserId') }} |
- {{ t('admin.wecom.headers.unionId') }} |
- {{ t('admin.wecom.headers.actions') }} |
-
-
-
-
- | {{ t('admin.wecom.noData') }} |
-
-
- |
- {{ u.username }} (#{{ u.id }})
- {{ u.real_name || '-' }} · {{ u.email }}
- |
- {{ t('admin.role.' + u.role) }} / {{ t('admin.status.' + u.status) }} |
- {{ u.wecom_userid || '-' }} |
- {{ u.wecom_unionid || '-' }} |
-
-
-
- {{ t('admin.wecom.unbind') }}
-
- |
-
-
-
-
-
-
-
-
-
-
-
-
- | {{ t('admin.wecom.auditHeaders.time') }} |
- {{ t('admin.wecom.auditHeaders.source') }} |
- {{ t('admin.wecom.auditHeaders.user') }} |
- {{ t('admin.wecom.auditHeaders.status') }} |
- {{ t('admin.wecom.auditHeaders.reason') }} |
- {{ t('admin.wecom.auditHeaders.ip') }} |
-
-
-
-
- | {{ t('admin.wecom.noAuditData') }} |
-
-
- | {{ row.created_at || '-' }} |
- {{ t('admin.wecom.sources.' + row.source) }} |
- {{ row.username || '-' }} |
-
-
- {{ t('admin.wecom.auditStatus.' + row.status) }}
-
- |
-
-
- {{ getWecomAuditReasonText(row) }}
-
- {{ getWecomAuditMetaText(row) }}
-
-
- |
- {{ row.ip || '-' }} |
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.request.noPending') }}
-
-
-
-
-
- | {{ t('admin.request.headers.userId') }} |
- {{ t('admin.request.headers.targetAgent') }} |
- {{ t('admin.request.headers.reason') }} |
- {{ t('admin.request.headers.status') }} |
- {{ t('admin.request.headers.actions') }} |
-
-
-
-
- | {{ req.user_id }} |
- {{ req.agent_id }} |
- {{ req.reason || '-' }} |
-
-
- {{ t('admin.status.' + req.status) }}
-
- |
-
-
-
- {{ t('admin.request.approve') }}
-
-
- {{ t('admin.request.reject') }}
-
-
- |
-
-
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.report.tableSettings') }}
-
- {{ t('admin.report.resetLayout') }}
-
-
-
-
-
-
-
-
- {{ t('admin.report.advancedSortRules') }}
-
- + {{ t('admin.report.addRule') }}
-
-
- {{ t('admin.report.noAdvancedSort') }}
-
-
- {{ ridx + 1 }}.
-
-
-
- {{ t('admin.report.moveUp') }}
- {{ t('admin.report.moveDown') }}
- {{ t('admin.report.remove') }}
-
-
-
-
-
-
-
-
- <
- >
-
-
-
-
-
-
- {{ t('admin.report.noData', { table: getReportTableLabel(currentTable) }) }}
-
-
-
-
-
-
- {{ t('admin.report.paginationSummary', { total: reportTotalRows, page: reportCurrentPage, pages: reportTotalPages }) }}
-
-
-
-
- {{ t('admin.report.prevPage') }}
-
-
- {{ btn === -1 ? '...' : btn }}
-
-
- {{ t('admin.report.nextPage') }}
-
-
-
-
-
-
- {{ t('admin.report.usage') }}
-
-
- {{ t('admin.report.byUser') }}
-
-
- {{ u.username }}
- {{ u.count }}
-
-
-
-
- {{ t('admin.report.byAgent') }}
-
-
- {{ a.agent }}
- {{ a.count }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ editingUser.id ? t('admin.user.editUser') : t('admin.user.createUser') }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.user.fields.noAgents') }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.agent.testModalTitle') }}
- {{ t('admin.agent.testModalAgent') }}:{{ testingAgent.name }}
-
- ✕
-
-
-
-
-
- {{ t('admin.agent.testedAt') }}:{{ agentTestResult.tested_at }}
-
-
- {{ isTestingAgent ? t('admin.agent.testing') : t('admin.agent.retest') }}
-
-
-
- {{ t('admin.agent.testingInProgress') }}
-
-
-
- {{ t('admin.agent.requestUrl') }}
- {{ agentTestResult.request_url || '-' }}
-
-
-
- {{ t('admin.agent.outputInfo') }}
- {{ agentTestResult.output_info || '-' }}
-
-
-
- {{ t('admin.agent.analysis') }}
-
- {{ agentTestResult.analysis }}
- (HTTP {{ agentTestResult.http_status }})
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ testRunLoading ? $t('admin.schedule.testRun.running') : $t('admin.schedule.testRun.start') }}
-
- {{ $t('admin.schedule.testRun.waitingHint') }}
-
-
-
-
-
- {{ testRunResult.total_count }}
- {{ $t('admin.schedule.testRun.total') }}
-
-
- {{ testRunResult.success_count }}
- {{ $t('admin.schedule.testRun.success') }}
-
-
- {{ testRunResult.failed_count }}
- {{ $t('admin.schedule.testRun.failed') }}
-
-
- {{ testRunResult.skipped_count }}
- {{ $t('admin.schedule.testRun.skipped') }}
-
-
- {{ $t('admin.schedule.testRun.limitSummary', { limit: testRunResult.limit, agentId: testRunResult.dify_agent_id || $t('admin.schedule.testRun.noAgent') }) }}
-
-
-
-
- Dify 执行快照(审计)
-
-
- Agent:
- {{ testRunResult.dify_execution_snapshot.dify_agent_name || '-' }}
- (ID: {{ testRunResult.dify_execution_snapshot.dify_agent_id ?? '-' }})
-
-
- System Prompt:
- {{ testRunResult.dify_execution_snapshot.dify_system_prompt }}
- (未配置)
-
-
- 本次测试未启用 Dify
-
-
-
- {{ $t('admin.schedule.testRun.stepLogs') }}
-
-
-
-
- {{ (stepStatusMap[log.status] || { label: log.status }).label }}
-
- {{ stepLabelMap[log.step] || log.step }}
- row_id={{ log.row_id }}
- {{ log.duration_ms }}ms
-
-
- {{ $t('admin.schedule.viewDetail') }}
- {{ JSON.stringify(log.detail, null, 2) }}
-
-
-
-
-
-
- {{ $t('admin.schedule.testRun.viewSql') }}
- {{ testRunResult.sql }}
-
-
-
- {{ $t('admin.schedule.testRun.errors', { count: testRunResult.errors.length }) }}
- {{ testRunResult.errors.join('\n') }}
-
-
-
-
-
-
-
-
-
-
- {{ scheduleEditingId ? $t('admin.schedule.form.editTitle') : $t('admin.schedule.form.createTitle') }}
-
- ✕
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ $t('admin.schedule.form.dataSourceConfig') }}
-
-
- {{ $t('admin.schedule.form.databaseDirect') }}
- {{ $t('admin.schedule.form.externalApi') }}
-
-
- {{ scheduleTestLoading ? $t('admin.schedule.form.querying') : $t('admin.schedule.form.testQuery') }}
-
-
-
-
- {{ scheduleConfigCollapsed ? $t('admin.schedule.form.expandConfig') : $t('admin.schedule.form.collapseConfig') }}
-
-
-
-
-
-
-
-
- {{ $t('admin.schedule.form.dataSourceSection') }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 值支持 ${环境变量名} 格式,运行时自动从环境变量解析(推荐密码使用此方式)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ $t('admin.schedule.testRun.queryResult') }}
-
- {{ $t('admin.schedule.testRun.resultSummary', { total: scheduleTestResult.total, showing: scheduleTestResult.showing }) }}
- ✕
-
-
-
-
-
-
- | {{ col }} |
-
-
-
-
- | {{ row[col] }} |
-
-
-
-
-
- {{ $t('admin.schedule.testRun.viewGeneratedSql') }}
- {{ scheduleTestResult.sql }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 仅在启用 Dify Agent 时可配置。保存后将作为 system_prompt 传入 Workflow;编排中 LLM 节点需引用该变量。
-
-
-
-
-
-
- {{ $t('admin.schedule.form.cronTitle') }}
- {{ $t('admin.schedule.form.cronHint') }}
-
-
-
- {{ $t('admin.schedule.form.everyMinutes') }}
-
-
- {{ $t('admin.schedule.form.hourly') }}
-
-
- {{ $t('admin.schedule.form.daily') }}
-
-
- {{ $t('admin.schedule.form.weekly') }}
-
-
-
-
-
- {{ $t('admin.schedule.form.cronPreview') }}:{{ scheduleCronPreview }}
- {{ $t('admin.schedule.form.nextRun') }}:{{ formatDateTime(scheduleNextRunPreview.toISOString()) }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.perm.agentModal.title') }}
- {{ t('admin.perm.agentModal.agent') }} {{ selectedAgentForPermissions.name }}
-
-
-
-
-
-
-
-
-
-
-
- {{ user.username }}
- {{ user.real_name || user.email }}
-
-
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.batchEdit.title') }}
- {{ t('admin.batchEdit.selected', { count: selectedUserIds.length }) }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ t('admin.perm.batchModal.title') }}
- {{ t('admin.perm.batchModal.selected', { count: selectedUserIds.length }) }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json
index 8d16e425..d4932065 100644
--- a/frontend/tsconfig.app.json
+++ b/frontend/tsconfig.app.json
@@ -3,6 +3,10 @@
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"types": ["vite/client"],
+ "baseUrl": ".",
+ "paths": {
+ "@/*": ["src/*"]
+ },
/* Linting */
"strict": true,
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index def2cc81..f0dbc83c 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -1,10 +1,18 @@
-
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
+const rootDir = path.dirname(fileURLToPath(import.meta.url))
+
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
+ resolve: {
+ alias: {
+ '@': path.resolve(rootDir, 'src'),
+ },
+ },
server: {
port: 8881, // 前端开发端口,实际上我们会用 Nginx 反代,但本地开发先改这个方便
allowedHosts: ['hx.benl.cn'],
|