refactor: 重构前端骨架,及admin模块子路由和懒加载

refactor: 优化多次请求,并使用pinia状态管理
This commit is contained in:
sophie committed 2026-06-03 10:30:16 +08:00
1 parent f877f61efd
commit 61693d014d
74 files changed
+9493 -6418

No files matched your search

@@ -0,0 +1,253 @@
/**
* features/admin/modules/agents/AgentsPage.vue
*
* Agent 管理独立页面(Phase 1 首个拆分模块)。
* 路由:/admin/agents
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Bot, Plus, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import AgentPermissionModal from './components/AgentPermissionModal.vue';
import AgentTestModal from './components/AgentTestModal.vue';
import { useAgentsAdmin } from './composables/useAgentsAdmin';
const { t } = useI18n();
const {
agents,
activeUsers,
isLoading,
isSaving,
isEditing,
selectedAgentId,
form,
showTestModal,
isTesting,
testingAgent,
testResult,
showPermissionModal,
permissionAgent,
permissionUserIds,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
selectAgent,
submitAgent,
deleteAgent,
openTestModal,
runAgentTest,
openPermissionModal,
togglePermissionUser,
savePermissions,
closeDeleteConfirm,
confirmDelete,
} = useAgentsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.agent.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.agent.subtitle') }}</p>
</div>
<button type="button" class="btn-primary" @click="resetForm">
<Plus class="w-5 h-5" />
<span class="font-medium">{{ t('admin.agent.new') }}</span>
</button>
</div>
<div class="admin-form-panel">
<h3 class="section-title mb-6">{{ isEditing ? t('admin.agent.edit') : t('admin.agent.create') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.name') }}</label>
<input
v-model="form.name"
type="text"
class="w-full border-default rounded-xl px-4 py-3 text-base focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm"
:placeholder="t('admin.agent.fields.namePlaceholder')"
/>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.type') }}</label>
<select v-model="form.type" class="w-full input-field">
<option value="api">{{ t('admin.agent.fields.types.api') }}</option>
<option value="iframe">{{ t('admin.agent.fields.types.iframe') }}</option>
</select>
</div>
<template v-if="form.type === 'api'">
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">Dify应用类型</label>
<select v-model="form.dify_app_type" class="w-full input-field text-sm focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm">
<option value="chatflow">Chatflow</option>
<option value="workflow">Workflow</option>
</select>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.appId') }}</label>
<input v-model="form.dify_app_id" type="text" class="w-full input-field text-sm font-mono focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm" />
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">API 基础 URL</label>
<input
v-model="form.api_base_url"
type="text"
class="w-full input-field text-sm font-mono focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm"
:placeholder="t('admin.agent.fields.baseUrlPlaceholder')"
/>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.apiKey') }}</label>
<input v-model="form.dify_api_key" type="password" class="w-full input-field text-sm font-mono focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm" />
</div>
</template>
<template v-if="form.type === 'iframe'">
<div class="col-span-1 md:col-span-2 space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.iframeUrl') }}</label>
<input v-model="form.iframe_url" type="text" class="w-full input-field text-sm font-mono focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm" placeholder="https://..." />
</div>
</template>
<div class="col-span-1 md:col-span-2 space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.description') }}</label>
<input
v-model="form.description"
type="text"
class="w-full input-field focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm"
:placeholder="t('admin.agent.fields.descPlaceholder')"
/>
</div>
</div>
<div class="flex justify-end">
<button type="button" class="btn-primary btn-lg" @click="submitAgent">
<Plus v-if="!isEditing" class="w-5 h-5" />
{{ isEditing ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
<div class="admin-table-wrap">
<div v-if="agents.length === 0" class="admin-table-empty">
<Bot class="w-12 h-12 mx-auto text-muted mb-3" />
<p class="text-lg text-secondary">{{ t('admin.agent.noAgents') }}</p>
</div>
<table v-else class="admin-table">
<thead>
<tr>
<th class="px-8 py-4 text-sm">{{ t('admin.agent.headers.name') }}</th>
<th class="px-8 py-4 text-sm">{{ t('admin.agent.headers.type') }}</th>
<th class="px-8 py-4 text-sm">{{ t('admin.agent.headers.config') }}</th>
<th class="px-8 py-4 text-sm">{{ t('admin.agent.headers.status') }}</th>
<th class="px-8 py-4 text-sm text-right">{{ t('admin.agent.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="agent in agents"
:key="agent.id"
class="group cursor-pointer"
:class="{ 'bg-blue-50/50': selectedAgentId === agent.id }"
@click="selectAgent(agent)"
>
<td class="px-8 py-5">
<div class="font-bold text-primary text-base">{{ agent.name }}</div>
<div class="section-desc mt-1">{{ agent.description }}</div>
</td>
<td class="px-8 py-5">
<span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-surface-soft text-primary uppercase tracking-wide">
{{ agent.type }}
</span>
</td>
<td class="px-8 py-5 font-mono text-xs text-muted max-w-xs truncate">
<span v-if="agent.type === 'api'" class="flex items-center gap-1">
<span class="text-muted">{{ t('admin.agent.idLabel') }}:</span> {{ agent.dify_app_id }}
</span>
<span v-else class="flex items-center gap-1" :title="String(agent.extra_config?.iframe_url || '')">
<span class="text-muted">{{ t('admin.agent.urlLabel') }}:</span> {{ agent.extra_config?.iframe_url }}
</span>
</td>
<td class="px-8 py-5">
<span
class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium border"
:class="agent.is_active ? 'bg-green-50 text-green-700 border-green-100' : 'bg-surface-soft text-secondary border-default'"
>
<span class="w-2 h-2 rounded-full" :class="agent.is_active ? 'bg-green-500' : 'bg-surface-strong'" />
{{ agent.is_active ? t('admin.status.active') : t('admin.status.disabled') }}
</span>
</td>
<td class="px-8 py-5 text-right flex justify-end gap-2">
<button
type="button"
class="p-2 text-emerald-600 bg-emerald-50 hover:bg-emerald-100 rounded-lg transition-all"
:title="t('admin.agent.test')"
@click.stop="openTestModal(agent)"
>
{{ t('admin.agent.test') }}
</button>
<button
type="button"
class="p-2 text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-all"
:title="t('admin.agent.manageAccess')"
@click.stop="openPermissionModal(agent)"
>
<Users class="w-5 h-5" />
</button>
<button
type="button"
class="p-2 text-muted hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
:title="t('admin.agent.delete')"
@click.stop="deleteAgent(agent.id)"
>
<Trash2 class="w-5 h-5" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<AgentTestModal
:visible="showTestModal"
:agent="testingAgent"
:result="testResult"
:is-testing="isTesting"
@close="showTestModal = false"
@retest="runAgentTest()"
/>
<AgentPermissionModal
:visible="showPermissionModal"
:agent="permissionAgent"
:users="activeUsers()"
:selected-user-ids="permissionUserIds"
:is-saving="isSaving"
@close="showPermissionModal = false"
@save="savePermissions"
@toggle-user="togglePermissionUser"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="confirmDelete"
@cancel="closeDeleteConfirm"
/>
</section>
</template>
@@ -0,0 +1,94 @@
/**
* features/admin/modules/agents/components/AgentPermissionModal.vue
*
* 为指定 Agent 批量勾选可访问用户的权限弹窗。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type { AgentRow } from '@/features/admin/types/agent.types';
defineProps<{
visible: boolean;
agent: AgentRow | null;
users: AdminUserRow[];
selectedUserIds: number[];
isSaving: boolean;
}>();
const emit = defineEmits<{
close: [];
save: [];
toggleUser: [userId: number];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible && agent" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-2xl max-h-[90vh] animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle flex justify-between items-center">
<div>
<h3 class="text-lg font-bold text-primary">{{ t('admin.perm.agentModal.title') }}</h3>
<p class="text-sm text-muted">
{{ t('admin.perm.agentModal.agent') }}
<span class="font-medium text-blue-600">{{ agent.name }}</span>
</p>
</div>
<button type="button" class="btn-icon-ds rounded-full" @click="emit('close')">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div class="flex-1 overflow-y-auto p-8">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div
v-for="user in users"
:key="user.id"
class="flex items-center gap-3 p-3 rounded-xl border transition-all cursor-pointer"
:class="selectedUserIds.includes(user.id) ? 'border-blue-200 bg-blue-50/50' : 'border-default hover-surface-soft'"
@click="emit('toggleUser', user.id)"
>
<div
class="w-5 h-5 rounded border flex items-center justify-center transition-colors"
:class="selectedUserIds.includes(user.id) ? 'bg-blue-600 border-blue-600' : 'bg-surface border-default'"
>
<svg
v-if="selectedUserIds.includes(user.id)"
xmlns="http://www.w3.org/2000/svg"
class="h-3.5 w-3.5 text-white"
viewBox="0 0 20 20"
fill="currentColor"
>
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
</svg>
</div>
<div>
<div class="font-medium text-primary text-sm">{{ user.username }}</div>
<div class="text-xs text-muted">{{ user.real_name || user.email }}</div>
</div>
</div>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
<button type="button" class="btn-ghost" @click="emit('close')">
{{ t('admin.cancel') }}
</button>
<button
type="button"
:disabled="isSaving"
class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
@click="emit('save')"
>
<div v-if="isSaving" class="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent" />
{{ t('admin.perm.agentModal.save') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,82 @@
/**
* features/admin/modules/agents/components/AgentTestModal.vue
*
* Agent 连通性测试弹窗:展示请求 URL、输出信息与分析结果。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { AgentRow, AgentTestResult } from '@/features/admin/types/agent.types';
defineProps<{
visible: boolean;
agent: AgentRow | null;
result: AgentTestResult | null;
isTesting: boolean;
}>();
const emit = defineEmits<{
close: [];
retest: [];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible && agent" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-3xl max-h-[90vh] animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle flex justify-between items-start">
<div>
<h3 class="text-lg font-bold text-primary">{{ t('admin.agent.testModalTitle') }}</h3>
<p class="section-desc mt-1">
{{ t('admin.agent.testModalAgent') }}:
<span class="font-medium text-blue-600">{{ agent.name }}</span>
</p>
</div>
<button type="button" class="btn-icon-ds rounded-full" @click="emit('close')">✕</button>
</div>
<div class="flex-1 overflow-y-auto p-8 space-y-5">
<div class="flex items-center justify-between">
<div class="text-sm text-secondary">
<span v-if="result?.tested_at">{{ t('admin.agent.testedAt') }}:{{ result.tested_at }}</span>
</div>
<button
type="button"
:disabled="isTesting"
class="btn-primary btn-sm disabled:opacity-50"
@click="emit('retest')"
>
{{ isTesting ? t('admin.agent.testing') : t('admin.agent.retest') }}
</button>
</div>
<div v-if="isTesting" class="text-sm text-muted">{{ t('admin.agent.testingInProgress') }}</div>
<template v-if="result">
<div>
<div class="text-xs font-semibold text-muted uppercase tracking-wider mb-2">{{ t('admin.agent.requestUrl') }}</div>
<div class="admin-code-block">{{ result.request_url || '-' }}</div>
</div>
<div>
<div class="text-xs font-semibold text-muted uppercase tracking-wider mb-2">{{ t('admin.agent.outputInfo') }}</div>
<pre class="admin-code-block max-h-64 overflow-y-auto whitespace-pre-wrap">{{ result.output_info || '-' }}</pre>
</div>
<div>
<div class="text-xs font-semibold text-muted uppercase tracking-wider mb-2">{{ t('admin.agent.analysis') }}</div>
<div
class="p-3 rounded-lg border text-sm"
:class="result.success ? 'bg-green-50 border-green-200 text-green-800' : 'bg-red-50 border-red-200 text-red-800'"
>
{{ result.analysis }}
<span v-if="result.http_status">(HTTP {{ result.http_status }})</span>
</div>
</div>
</template>
</div>
</div>
</div>
</template>
@@ -0,0 +1,305 @@
/**
* features/admin/modules/agents/composables/useAgentsAdmin.ts
*
* Agent 管理模块的业务逻辑:列表 CRUD、连通性测试、权限分配。
* 从原 AdminView.vue 的 agents 相关 script 抽取,供 AgentsPage 使用。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
createAdminAgent,
deleteAdminAgent,
listAdminAgents,
listAdminUsers,
saveAdminAgentPermissions,
testAdminAgent,
updateAdminAgent,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type { AgentFormState, AgentRow, AgentTestResult } from '@/features/admin/types/agent.types';
import { createEmptyAgentForm } from '@/features/admin/types/agent.types';
export function useAgentsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const agents = ref<AgentRow[]>([]);
const users = ref<AdminUserRow[]>([]);
const isLoading = ref(true);
const isSaving = ref(false);
const isEditing = ref(false);
const selectedAgentId = ref<number | null>(null);
const form = ref<AgentFormState>(createEmptyAgentForm());
const showTestModal = ref(false);
const isTesting = ref(false);
const testingAgent = ref<AgentRow | null>(null);
const testResult = ref<AgentTestResult | null>(null);
const showPermissionModal = ref(false);
const permissionAgent = ref<AgentRow | null>(null);
const permissionUserIds = ref<number[]>([]);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const activeUsers = () => users.value.filter((u) => u.status !== 'pending');
const loadAgents = async (): Promise<void> => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Error loading agents:', e);
agents.value = [];
}
};
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([loadAgents(), loadUsers()]);
isLoading.value = false;
};
const resetForm = (): void => {
selectedAgentId.value = null;
form.value = createEmptyAgentForm();
isEditing.value = false;
};
const selectAgent = (agent: AgentRow): void => {
selectedAgentId.value = agent.id;
form.value = {
id: agent.id,
name: agent.name,
dify_app_id: agent.dify_app_id,
dify_api_key: agent.dify_api_key || '',
description: agent.description || '',
type: agent.type,
dify_app_type: agent.extra_config?.dify_app_type === 'workflow' ? 'workflow' : 'chatflow',
api_base_url: agent.api_base_url || '',
iframe_url: String(agent.extra_config?.iframe_url || ''),
is_active: agent.is_active,
};
isEditing.value = true;
};
const openDeleteConfirm = (
message: string,
action: () => Promise<void> | void,
): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const submitAgent = async (): Promise<void> => {
if (!form.value.name) {
msg.warning(t('admin.dept.msg.nameRequired'));
return;
}
isSaving.value = true;
const extra_config: Record<string, unknown> = {};
if (form.value.type === 'iframe' && form.value.iframe_url) {
extra_config.iframe_url = form.value.iframe_url;
}
if (form.value.type === 'api') {
extra_config.dify_app_type = form.value.dify_app_type === 'workflow' ? 'workflow' : 'chatflow';
}
try {
const editingId = isEditing.value ? Number(form.value.id) : null;
if (isEditing.value && form.value.id != null) {
const payload: Record<string, unknown> = {
name: form.value.name,
dify_app_id: form.value.dify_app_id,
description: form.value.description,
type: form.value.type,
api_base_url: form.value.api_base_url,
extra_config,
is_active: form.value.is_active,
};
if (form.value.dify_api_key) {
payload.dify_api_key = form.value.dify_api_key;
}
await updateAdminAgent(form.value.id, payload);
} else {
await createAdminAgent({
name: form.value.name,
dify_app_id: form.value.dify_app_id,
dify_api_key: form.value.dify_api_key,
description: form.value.description,
type: form.value.type,
api_base_url: form.value.api_base_url,
extra_config,
});
}
await loadAgents();
if (editingId) {
const updated = agents.value.find((a) => a.id === editingId);
if (updated) selectAgent(updated);
} else {
resetForm();
}
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const deleteAgent = async (id: number): Promise<void> => {
openDeleteConfirm(t('admin.agent.confirmDelete'), async () => {
try {
await deleteAdminAgent(id);
await loadAgents();
if (selectedAgentId.value === id) {
resetForm();
}
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
const openTestModal = (agent: AgentRow): void => {
testingAgent.value = agent;
testResult.value = null;
showTestModal.value = true;
void runAgentTest(agent);
};
const runAgentTest = async (agent?: AgentRow): Promise<void> => {
const target = agent || testingAgent.value;
if (!target) return;
isTesting.value = true;
try {
const data = await testAdminAgent(target.id);
testResult.value = {
success: !!data.success,
request_url: data.request_url || '',
output_info: data.output_info || '',
analysis: data.analysis || (data.success ? t('admin.agent.testDone') : t('admin.agent.testFailed')),
http_status: data.http_status,
tested_at: data.tested_at,
};
if (data.success) {
const idx = agents.value.findIndex((a) => a.id === target.id);
const row = idx >= 0 ? agents.value[idx] : undefined;
if (row) {
row.is_active = true;
}
if (selectedAgentId.value === target.id) {
form.value.is_active = true;
}
}
} catch (e) {
testResult.value = {
success: false,
request_url: '',
output_info: (e as Error).message || t('admin.agent.networkError'),
analysis: t('admin.agent.testFailedRequestException'),
http_status: 0,
};
} finally {
isTesting.value = false;
}
};
const openPermissionModal = (agent: AgentRow): void => {
permissionAgent.value = agent;
permissionUserIds.value = users.value
.filter((u) => u.agent_ids.includes(agent.id))
.map((u) => u.id);
showPermissionModal.value = true;
};
const togglePermissionUser = (userId: number): void => {
const index = permissionUserIds.value.indexOf(userId);
if (index === -1) {
permissionUserIds.value.push(userId);
} else {
permissionUserIds.value.splice(index, 1);
}
};
const savePermissions = async (): Promise<void> => {
if (!permissionAgent.value) return;
isSaving.value = true;
try {
await saveAdminAgentPermissions(
permissionAgent.value.id,
permissionUserIds.value,
);
await loadUsers();
showPermissionModal.value = false;
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
} finally {
isSaving.value = false;
}
};
return {
agents,
users,
activeUsers,
isLoading,
isSaving,
isEditing,
selectedAgentId,
form,
showTestModal,
isTesting,
testingAgent,
testResult,
showPermissionModal,
permissionAgent,
permissionUserIds,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
selectAgent,
submitAgent,
deleteAgent,
openTestModal,
runAgentTest,
openPermissionModal,
togglePermissionUser,
savePermissions,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -0,0 +1,107 @@
/**
* features/admin/modules/announcements/AnnouncementsPage.vue
* 公告管理独立页面。路由:/admin/announcements
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useAnnouncementsAdmin } from './composables/useAnnouncementsAdmin';
const { t } = useI18n();
const {
announcements,
newAnnouncement,
isLoading,
isSaving,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
publishAnnouncement,
deleteAnnouncementItem,
closeDeleteConfirm,
confirmDelete,
} = useAnnouncementsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div>
<h2 class="section-title">{{ t('admin.announcement.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.announcement.subtitle') }}</p>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="lg:col-span-1 card p-6 shadow-sm h-fit">
<h3 class="font-bold text-primary mb-4">{{ t('admin.announcement.add') }}</h3>
<div class="space-y-4">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.announcement.fields.title') }}</label>
<input v-model="newAnnouncement.title" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.announcement.fields.content') }}</label>
<textarea v-model="newAnnouncement.content" rows="6" class="input-field text-sm" />
</div>
<div class="flex justify-end pt-2">
<button
type="button"
class="btn-primary btn-sm disabled:opacity-50"
:disabled="isSaving"
@click="publishAnnouncement"
>
{{ isSaving ? t('admin.save') + '...' : t('admin.announcement.publish') }}
</button>
</div>
</div>
</div>
<div class="lg:col-span-2 card shadow-sm overflow-hidden">
<div v-if="announcements.length === 0" class="p-8 text-center text-muted">
{{ t('admin.announcement.noData') }}
</div>
<div v-else class="divide-y divide-subtle">
<div
v-for="ann in announcements"
:key="ann.id"
class="p-5 hover-surface-soft transition-colors"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<h4 class="font-semibold text-primary truncate">{{ ann.title }}</h4>
<p class="text-xs text-muted mt-1">{{ new Date(ann.created_at).toLocaleString() }}</p>
</div>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
@click="deleteAnnouncementItem(ann.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
<p class="text-sm text-secondary mt-2 whitespace-pre-wrap">{{ ann.content }}</p>
</div>
</div>
</div>
</div>
</template>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</section>
</template>
@@ -0,0 +1,109 @@
/**
* features/admin/modules/announcements/composables/useAnnouncementsAdmin.ts
* 公告管理:列表、发布、删除。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { createAnnouncement, deleteAnnouncement, listAnnouncements } from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminAnnouncementRow } from '@/features/admin/types/admin.types';
import {
createEmptyAnnouncementForm,
type AnnouncementFormState,
} from '@/features/admin/types/announcement.types';
export function useAnnouncementsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const announcements = ref<AdminAnnouncementRow[]>([]);
const newAnnouncement = ref<AnnouncementFormState>(createEmptyAnnouncementForm());
const isLoading = ref(true);
const isSaving = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const loadAnnouncements = async (): Promise<void> => {
try {
announcements.value = await listAnnouncements();
} catch (e) {
console.error('Failed to load announcements', e);
announcements.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadAnnouncements();
isLoading.value = false;
};
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const publishAnnouncement = async (): Promise<void> => {
if (!newAnnouncement.value.title.trim() || !newAnnouncement.value.content.trim()) {
msg.warning(t('admin.announcement.msg.fillAll'));
return;
}
isSaving.value = true;
try {
await createAnnouncement({
title: newAnnouncement.value.title.trim(),
content: newAnnouncement.value.content.trim(),
});
newAnnouncement.value = createEmptyAnnouncementForm();
await loadAnnouncements();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const deleteAnnouncementItem = (id: number): void => {
openDeleteConfirm(t('admin.announcement.confirmDelete'), async () => {
try {
await deleteAnnouncement(id);
await loadAnnouncements();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
return {
announcements,
newAnnouncement,
isLoading,
isSaving,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
publishAnnouncement,
deleteAnnouncementItem,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -0,0 +1,108 @@
/**
* features/admin/modules/approvals/ApprovalsPage.vue
* 用户注册审批独立页面。路由:/admin/approvals
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ShieldCheck, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useApprovalsAdmin } from './composables/useApprovalsAdmin';
const { t } = useI18n();
const {
pendingUsers,
isLoading,
showConfirmDialog,
confirmMessage,
loadAll,
approveUser,
rejectUser,
closeConfirm,
confirmActionHandler,
} = useApprovalsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="admin-table-header">
<div>
<h2 class="section-title">{{ t('admin.approval.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.approval.subtitle') }}</p>
</div>
</div>
<div class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.username') }}</th>
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.nameId') }}</th>
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.contact') }}</th>
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.role') }}</th>
<th class="px-8 py-4 text-right text-xs">{{ t('admin.approval.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="pendingUsers.length === 0">
<td colspan="5" class="px-8 admin-table-empty">{{ t('admin.approval.noPending') }}</td>
</tr>
<tr v-for="user in pendingUsers" :key="user.id">
<td class="px-8 py-5 text-sm font-medium text-primary">
<div>{{ user.username }}</div>
<div class="text-xs text-muted font-normal">{{ user.email }}</div>
</td>
<td class="px-8 py-5 text-sm text-muted">
<div>{{ user.real_name || '-' }}</div>
<div class="text-xs text-muted font-mono">{{ user.employee_id || '-' }}</div>
</td>
<td class="px-8 py-5 text-sm text-muted">{{ user.phone_number || '-' }}</td>
<td class="px-8 py-5">
<span
class="px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 border border-yellow-200"
>
{{ t('admin.role.' + user.role) }}
</span>
</td>
<td class="px-8 py-5 text-right flex items-center justify-end gap-2">
<button
type="button"
class="p-2 text-green-600 bg-green-50 rounded-lg hover:bg-green-100 transition-colors"
:title="t('admin.approval.confirmApprove')"
@click="approveUser(user.id)"
>
<ShieldCheck class="w-4 h-4" />
</button>
<button
type="button"
class="p-2 text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
:title="t('admin.approval.confirmReject')"
@click="rejectUser(user.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<DeleteConfirmDialog
v-model="showConfirmDialog"
:message="confirmMessage"
@cancel="closeConfirm"
@confirm="confirmActionHandler"
/>
</section>
</template>
@@ -0,0 +1,98 @@
/**
* features/admin/modules/approvals/composables/useApprovalsAdmin.ts
* 用户注册审批:待审列表、通过、拒绝。
*/
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { approveAdminUser, listAdminUsers, rejectAdminUser } from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import { useAdminNavBadges } from '@/features/admin/composables/useAdminNavBadges';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
export function useApprovalsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const { refreshBadges } = useAdminNavBadges();
const users = ref<AdminUserRow[]>([]);
const isLoading = ref(true);
const showConfirmDialog = ref(false);
const confirmMessage = ref('');
let confirmAction: (() => Promise<void> | void) | null = null;
const pendingUsers = computed(() => users.value.filter((u) => u.status === 'pending'));
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadUsers();
isLoading.value = false;
};
const openConfirm = (message: string, action: () => Promise<void> | void): void => {
confirmMessage.value = message;
confirmAction = action;
showConfirmDialog.value = true;
};
const closeConfirm = (): void => {
showConfirmDialog.value = false;
confirmAction = null;
};
const confirmActionHandler = async (): Promise<void> => {
if (!confirmAction) return;
try {
await confirmAction();
} finally {
closeConfirm();
}
};
const approveUser = (userId: number): void => {
openConfirm(t('admin.approval.confirmApprove'), async () => {
try {
await approveAdminUser(userId);
await loadUsers();
await refreshBadges();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
}
});
};
const rejectUser = (userId: number): void => {
openConfirm(t('admin.approval.confirmReject'), async () => {
try {
await rejectAdminUser(userId);
await loadUsers();
await refreshBadges();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
return {
pendingUsers,
isLoading,
showConfirmDialog,
confirmMessage,
loadAll,
approveUser,
rejectUser,
closeConfirm,
confirmActionHandler,
};
}
@@ -0,0 +1,94 @@
/**
* features/admin/modules/dashboard/DashboardPage.vue
* 管理后台仪表盘。路由:/admin/dashboard
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { BarChart2, Bot, MessageSquare, Users } from 'lucide-vue-next';
import { useDashboardAdmin } from './composables/useDashboardAdmin';
const { t } = useI18n();
const router = useRouter();
const {
agentCount,
userCount,
totalConversations,
avgScore,
isLoading,
loadAll,
} = useDashboardAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-6 animate-fade-in">
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminAgents' })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-brand-50 rounded-xl group-hover:bg-brand-100 transition-colors">
<Bot class="w-6 h-6 text-brand-600" />
</div>
<span class="text-xs font-medium text-green-600 bg-green-50 px-2 py-1 rounded-full">
+2 {{ t('admin.dash.new') }}
</span>
</div>
<div class="text-3xl font-bold text-primary mb-1">{{ agentCount }}</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.activeAgents') }}</div>
</div>
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminPermissions' })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-purple-50 rounded-xl group-hover:bg-purple-100 transition-colors">
<Users class="w-6 h-6 text-purple-600" />
</div>
</div>
<div class="text-3xl font-bold text-primary mb-1">{{ userCount }}</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.totalUsers') }}</div>
</div>
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminReports', params: { table: 'chat_logs' } })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-indigo-50 rounded-xl group-hover:bg-indigo-100 transition-colors">
<MessageSquare class="w-6 h-6 text-indigo-600" />
</div>
</div>
<div class="text-3xl font-bold text-primary mb-1">{{ totalConversations }}</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.totalConversations') }}</div>
</div>
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminReports', params: { table: 'feedbacks' } })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-orange-50 rounded-xl group-hover:bg-orange-100 transition-colors">
<BarChart2 class="w-6 h-6 text-orange-600" />
</div>
</div>
<div class="text-3xl font-bold text-primary mb-1">
{{ avgScore.toFixed(1) }}
</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.avgRating') }}</div>
</div>
</div>
</section>
</template>
@@ -0,0 +1,42 @@
/**
* features/admin/modules/dashboard/composables/useDashboardAdmin.ts
* 仪表盘概览:单次 summary 接口获取四个指标。
*/
import { ref } from 'vue';
import { getAdminDashboardSummary } from '@/api/admin';
export function useDashboardAdmin() {
const agentCount = ref(0);
const userCount = ref(0);
const totalConversations = ref(0);
const avgScore = ref(0);
const isLoading = ref(true);
const loadAll = async (): Promise<void> => {
isLoading.value = true;
try {
const summary = await getAdminDashboardSummary();
agentCount.value = summary.agent_count;
userCount.value = summary.user_count;
totalConversations.value = summary.total_conversations;
avgScore.value = summary.avg_score;
} catch (e) {
console.error('Error loading dashboard:', e);
agentCount.value = 0;
userCount.value = 0;
totalConversations.value = 0;
avgScore.value = 0;
} finally {
isLoading.value = false;
}
};
return {
agentCount,
userCount,
totalConversations,
avgScore,
isLoading,
loadAll,
};
}
@@ -0,0 +1,163 @@
/**
* features/admin/modules/departments/DepartmentsPage.vue
* 部门管理独立页面。路由:/admin/departments
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
const { t } = useI18n();
const {
departments,
editingDept,
isLoading,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
editDepartment,
saveDepartment,
deleteDepartment,
closeDeleteConfirm,
confirmDelete,
} = useDepartmentsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="flex items-center justify-between">
<div>
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="lg:col-span-1 card p-6 shadow-sm h-fit">
<h3 class="font-bold text-primary mb-4">
{{ editingDept.id ? t('admin.dept.edit') : t('admin.dept.add') }}
</h3>
<div class="form-stack">
<div class="space-y-1.5">
<label class="label-field block">{{ t('admin.dept.fields.name') }}</label>
<input
v-model="editingDept.name"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.namePlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.code') }}</label>
<input
v-model="editingDept.code"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.codePlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.company') }}</label>
<input
v-model="editingDept.company"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.companyPlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.description') }}</label>
<textarea
v-model="editingDept.description"
rows="3"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.descriptionPlaceholder')"
/>
</div>
<div class="flex justify-end gap-2 pt-2">
<button
v-if="editingDept.id"
type="button"
class="btn-ghost btn-sm"
@click="resetForm"
>
{{ t('admin.cancel') }}
</button>
<button type="button" class="btn-primary btn-sm" @click="saveDepartment">
{{ editingDept.id ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
</div>
<div class="lg:col-span-2 admin-table-section">
<div v-if="departments.length === 0" class="p-8 text-center text-muted">
{{ t('admin.dept.noDepts') }}
</div>
<table v-else class="admin-table">
<thead>
<tr>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.dept.headers.name') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.dept.headers.code') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.dept.headers.company') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase text-right">
{{ t('admin.dept.headers.actions') }}
</th>
</tr>
</thead>
<tbody class="divide-y divide-subtle">
<tr v-for="d in departments" :key="d.id">
<td class="px-6 py-4">
<div class="font-medium text-primary text-sm">{{ d.name }}</div>
<div class="text-xs text-muted truncate max-w-xs mt-0.5">{{ d.description }}</div>
</td>
<td class="px-6 py-4 text-sm text-muted font-mono">{{ d.code || '-' }}</td>
<td class="px-6 py-4 text-sm text-muted">{{ d.company || '-' }}</td>
<td class="px-6 py-4 text-right flex justify-end gap-2">
<button
type="button"
class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
@click="editDepartment(d)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
@click="deleteDepartment(d.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</section>
</template>
@@ -0,0 +1,131 @@
/**
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts
* 部门管理:列表、创建、编辑、删除。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
createAdminDepartment,
deleteAdminDepartment,
listAdminDepartments,
updateAdminDepartment,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
import {
createEmptyDepartmentForm,
type DepartmentFormState,
} from '@/features/admin/types/department.types';
export function useDepartmentsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const departments = ref<AdminDepartmentRow[]>([]);
const editingDept = ref<DepartmentFormState>(createEmptyDepartmentForm());
const isLoading = ref(true);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const loadDepartments = async (): Promise<void> => {
try {
departments.value = await listAdminDepartments();
} catch (e) {
console.error('Failed to load departments', e);
departments.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadDepartments();
isLoading.value = false;
};
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const resetForm = (): void => {
editingDept.value = createEmptyDepartmentForm();
};
const editDepartment = (dept: AdminDepartmentRow): void => {
editingDept.value = {
id: dept.id,
name: dept.name,
code: dept.code || '',
company: dept.company || '',
description: dept.description || '',
};
};
const saveDepartment = async (): Promise<void> => {
if (!editingDept.value.name?.trim()) {
msg.warning(t('admin.dept.msg.nameRequired'));
return;
}
try {
const payload = {
name: editingDept.value.name,
code: editingDept.value.code,
company: editingDept.value.company,
description: editingDept.value.description,
};
if (editingDept.value.id) {
await updateAdminDepartment(editingDept.value.id, payload);
} else {
await createAdminDepartment(payload);
}
await loadDepartments();
resetForm();
} catch (e) {
msg.error((e as Error).message || t('admin.msg.failed'));
}
};
const deleteDepartment = (id: number): void => {
openDeleteConfirm(t('admin.dept.confirmDelete'), async () => {
try {
await deleteAdminDepartment(id);
await loadDepartments();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
return {
departments,
editingDept,
isLoading,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
editDepartment,
saveDepartment,
deleteDepartment,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -0,0 +1,13 @@
/**
* features/admin/modules/knowledge-base/KnowledgeBasePage.vue
* 知识库管理独立页面。路由:/admin/knowledge-base
*/
<script setup lang="ts">
import KbAdminPanel from '@/components/kb/KbAdminPanel.vue';
</script>
<template>
<section class="admin-table-section overflow-hidden animate-fade-in-up">
<KbAdminPanel />
</section>
</template>
@@ -0,0 +1,195 @@
/**
* features/admin/modules/permissions/PermissionsPage.vue
* 用户权限矩阵独立页面。路由:/admin/permissions
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Download, FileText, Users } from 'lucide-vue-next';
import BatchPermissionModal from '@/features/admin/modules/users/components/BatchPermissionModal.vue';
import { usePermissionsAdmin } from './composables/usePermissionsAdmin';
const { t } = useI18n();
const {
agents,
permissionFilters,
selectedUserIds,
filteredUsers,
isLoading,
isSaving,
showBatchPermissionModal,
batchPermissionForm,
loadAll,
toggleUserSelection,
toggleAllUsers,
openBatchPermissionModal,
closeBatchPermissionModal,
submitBatchPermission,
toggleUserAgentPermission,
exportPermissions,
importPermissions,
} = usePermissionsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
<div>
<h2 class="section-title">{{ t('admin.perm.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.perm.subtitle') }}</p>
</div>
<div class="flex gap-3">
<button
v-if="selectedUserIds.length > 0"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-200 active:scale-95"
@click="openBatchPermissionModal"
>
<Users class="w-4 h-4" />
<span class="font-medium">{{ t('admin.perm.batchAssign') }}</span>
</button>
<label
class="flex items-center gap-2 px-4 py-2 btn-secondary cursor-pointer text-sm font-medium transition-all shadow-sm"
>
<input type="file" accept=".csv" class="hidden" @change="importPermissions" />
<FileText class="w-4 h-4" />
{{ t('admin.perm.importCsv') }}
</label>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 btn-secondary text-sm font-medium transition-all shadow-sm"
@click="exportPermissions"
>
<Download class="w-4 h-4" />
{{ t('admin.perm.exportCsv') }}
</button>
</div>
</div>
<div class="admin-table-filters--inline">
<input
v-model="permissionFilters.username"
:placeholder="t('admin.perm.filterName')"
class="admin-table-filter-input w-48"
/>
<input
v-model="permissionFilters.department"
:placeholder="t('admin.perm.filterDept')"
class="admin-table-filter-input w-48"
/>
<select v-model="permissionFilters.role" class="admin-table-filter-input w-32">
<option value="">{{ t('admin.perm.allRoles') }}</option>
<option value="user">{{ t('admin.role.user') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
<div class="admin-table-section admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-4 py-4 w-12 text-center sticky left-0 admin-table-sticky-head z-20">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500"
:checked="selectedUserIds.length > 0 && selectedUserIds.length === filteredUsers.length"
@change="toggleAllUsers"
/>
</th>
<th
class="px-6 py-4 text-left text-sm sticky left-12 admin-table-sticky-head z-20 w-64 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]"
>
{{ t('admin.perm.headers.user') }}
</th>
<th
class="px-6 py-4 text-left text-sm sticky left-[19rem] admin-table-sticky-head z-20 w-40 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]"
>
{{ t('admin.perm.headers.dept') }}
</th>
<th
v-for="agent in agents"
:key="agent.id"
class="px-4 py-4 text-center text-sm min-w-[100px]"
>
<div class="flex flex-col items-center gap-1">
<span>{{ agent.name }}</span>
<span class="text-[10px] text-muted font-normal border border-default px-1 rounded">
{{ agent.type }}
</span>
</div>
</th>
</tr>
</thead>
<tbody>
<tr v-for="user in filteredUsers" :key="user.id">
<td class="px-4 py-4 text-center sticky left-0 admin-table-sticky-cell z-20">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500"
:checked="selectedUserIds.includes(user.id)"
@change="toggleUserSelection(user.id)"
/>
</td>
<td class="px-6 py-4 sticky left-12 admin-table-sticky-cell z-20 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]">
<div class="flex items-center gap-3">
<div
class="w-8 h-8 rounded-full bg-gradient-to-br from-brand-100 to-indigo-100 text-brand-600 flex items-center justify-center font-bold text-sm"
>
{{ user.username.charAt(0).toUpperCase() }}
</div>
<div class="truncate max-w-[150px]">
<div class="font-medium text-primary truncate" :title="user.username">
{{ user.username }}
</div>
<div class="text-xs text-muted truncate" :title="user.email">
{{ user.email }}
</div>
</div>
</div>
</td>
<td
class="px-6 py-4 sticky left-[19rem] admin-table-sticky-cell z-20 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]"
>
<div class="text-sm text-muted truncate" :title="user.department">
{{ user.department || '-' }}
</div>
</td>
<td
v-for="agent in agents"
:key="agent.id"
class="px-4 py-4 text-center border-l border-dashed border-subtle"
>
<input
type="checkbox"
class="admin-checkbox-lg"
:checked="user.agent_ids.includes(agent.id)"
@change="toggleUserAgentPermission(user, agent.id)"
/>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<BatchPermissionModal
:visible="showBatchPermissionModal"
:form="batchPermissionForm"
:agents="agents"
:selected-count="selectedUserIds.length"
:is-saving="isSaving"
@close="closeBatchPermissionModal"
@save="submitBatchPermission"
/>
</section>
</template>
@@ -0,0 +1,205 @@
/**
* features/admin/modules/permissions/composables/usePermissionsAdmin.ts
* 用户权限矩阵:筛选、单格切换、批量分配、CSV 导入导出。
*/
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import * as XLSX from 'xlsx';
import {
batchUpdateAdminPermissions,
importAdminPermissions,
listAdminAgents,
listAdminUsers,
updateAdminUserPermissions,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
import {
createEmptyPermissionFilters,
type PermissionFilters,
} from '@/features/admin/types/permission.types';
import type { BatchPermissionForm } from '@/features/admin/types/user.types';
export function usePermissionsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const users = ref<AdminUserRow[]>([]);
const agents = ref<AdminAgentOption[]>([]);
const permissionFilters = ref<PermissionFilters>(createEmptyPermissionFilters());
const selectedUserIds = ref<number[]>([]);
const isLoading = ref(true);
const isSaving = ref(false);
const showBatchPermissionModal = ref(false);
const batchPermissionForm = ref<BatchPermissionForm>({ agent_ids: [], action: 'add' });
const activeUsers = computed(() => users.value.filter((u) => u.status !== 'pending'));
const filteredUsers = computed(() =>
activeUsers.value.filter((u) => {
const matchName =
!permissionFilters.value.username ||
u.username.toLowerCase().includes(permissionFilters.value.username.toLowerCase()) ||
(u.real_name &&
u.real_name.toLowerCase().includes(permissionFilters.value.username.toLowerCase()));
const matchDept =
!permissionFilters.value.department ||
(u.department &&
u.department.toLowerCase().includes(permissionFilters.value.department.toLowerCase()));
const matchRole = !permissionFilters.value.role || u.role === permissionFilters.value.role;
return matchName && matchDept && matchRole;
}),
);
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const loadAgents = async (): Promise<void> => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Failed to load agents', e);
agents.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([loadUsers(), loadAgents()]);
isLoading.value = false;
};
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 = (): void => {
if (selectedUserIds.value.length === filteredUsers.value.length) {
selectedUserIds.value = [];
} else {
selectedUserIds.value = filteredUsers.value.map((u) => u.id);
}
};
const openBatchPermissionModal = (): void => {
if (selectedUserIds.value.length === 0) return;
batchPermissionForm.value = { agent_ids: [], action: 'add' };
showBatchPermissionModal.value = true;
};
const closeBatchPermissionModal = (): void => {
showBatchPermissionModal.value = false;
};
const submitBatchPermission = async (): Promise<void> => {
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;
}
};
const toggleUserAgentPermission = async (user: AdminUserRow, agentId: number): Promise<void> => {
const hasPermission = user.agent_ids.includes(agentId);
const newAgentIds = hasPermission
? user.agent_ids.filter((id) => id !== agentId)
: [...user.agent_ids, agentId];
const originalIds = [...user.agent_ids];
user.agent_ids = newAgentIds;
try {
await updateAdminUserPermissions(user.id, newAgentIds);
} catch (e) {
console.error(e);
user.agent_ids = originalIds;
msg.error((e as Error).message || t('admin.msg.failed'));
}
};
const exportPermissions = (): void => {
const data = users.value.map((u) => ({
Username: u.username,
Email: u.email,
Role: u.role,
Allowed_Agents: u.agent_ids.join('|'),
}));
const ws = XLSX.utils.json_to_sheet(data);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Permissions');
XLSX.writeFile(wb, 'user_permissions.csv');
};
const importPermissions = async (event: Event): Promise<void> => {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
const formData = new FormData();
formData.append('file', file);
isSaving.value = true;
try {
await importAdminPermissions(formData);
await loadUsers();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
input.value = '';
}
};
return {
users,
agents,
permissionFilters,
selectedUserIds,
filteredUsers,
isLoading,
isSaving,
showBatchPermissionModal,
batchPermissionForm,
loadAll,
toggleUserSelection,
toggleAllUsers,
openBatchPermissionModal,
closeBatchPermissionModal,
submitBatchPermission,
toggleUserAgentPermission,
exportPermissions,
importPermissions,
};
}
@@ -0,0 +1,174 @@
/**
* features/admin/modules/questions/QuestionsPage.vue
* 常用问题管理独立页面。路由:/admin/questions
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useQuestionsAdmin } from './composables/useQuestionsAdmin';
const { t } = useI18n();
const {
questions,
agents,
form,
isEditing,
isLoading,
isSaving,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
editQuestion,
saveQuestion,
deleteQuestion,
closeDeleteConfirm,
confirmDelete,
} = useQuestionsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="flex items-center justify-between">
<div>
<h2 class="section-title">{{ t('admin.question.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.question.subtitle') }}</p>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="lg:col-span-1 card p-6 shadow-sm h-fit">
<h3 class="font-bold text-primary mb-4">
{{ isEditing ? t('admin.question.edit') : t('admin.question.add') }}
</h3>
<div class="space-y-4">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.question.fields.title') }}</label>
<input
v-model="form.title"
class="input-field text-sm"
:placeholder="t('admin.question.fields.titlePlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.question.fields.targetAgent') }}</label>
<select v-model="form.agent_id" class="input-field text-sm">
<option :value="undefined" disabled>{{ t('admin.perm.batchModal.selectAgents') }}</option>
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
{{ agent.name }}
</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.question.fields.sortOrder') }}</label>
<input v-model.number="form.sort_order" type="number" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.question.fields.content') }}</label>
<textarea
v-model="form.question"
rows="4"
class="input-field text-sm"
:placeholder="t('admin.question.fields.contentPlaceholder')"
/>
</div>
<div class="flex justify-end gap-2 pt-2">
<button
v-if="isEditing"
type="button"
class="btn-ghost btn-sm"
@click="resetForm"
>
{{ t('admin.cancel') }}
</button>
<button
type="button"
class="btn-primary btn-sm disabled:opacity-50"
:disabled="isSaving"
@click="saveQuestion"
>
{{ isSaving ? t('admin.save') + '...' : (isEditing ? t('admin.update') : t('admin.add')) }}
</button>
</div>
</div>
</div>
<div class="lg:col-span-2 admin-table-section">
<div v-if="questions.length === 0" class="p-8 text-center text-muted">
{{ t('admin.question.noData') }}
</div>
<table v-else class="admin-table">
<thead>
<tr>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.question.headers.title') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.question.headers.agent') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.question.headers.order') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase text-right">
{{ t('admin.question.headers.actions') }}
</th>
</tr>
</thead>
<tbody class="divide-y divide-subtle">
<tr v-for="q in questions" :key="q.id">
<td class="px-6 py-4">
<div class="font-medium text-primary text-sm">{{ q.title }}</div>
<div class="text-xs text-muted truncate max-w-xs mt-0.5">{{ q.question }}</div>
</td>
<td class="px-6 py-4">
<span
class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 border border-blue-100"
>
{{ q.agent_name || 'Unknown' }}
</span>
</td>
<td class="px-6 py-4 text-sm text-muted">{{ q.sort_order }}</td>
<td class="px-6 py-4 text-right flex justify-end gap-2">
<button
type="button"
class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
@click="editQuestion(q)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
@click="deleteQuestion(q.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</section>
</template>
@@ -0,0 +1,149 @@
/**
* features/admin/modules/questions/composables/useQuestionsAdmin.ts
* 常用问题管理:列表、创建、编辑、删除。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
deleteAdminQuickQuestion,
listAdminAgents,
listAdminQuickQuestions,
saveAdminQuickQuestion,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminAgentOption } from '@/features/admin/types/admin.types';
import {
createEmptyQuestionForm,
type AdminQuickQuestionRow,
type QuestionFormState,
} from '@/features/admin/types/question.types';
export function useQuestionsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const questions = ref<AdminQuickQuestionRow[]>([]);
const agents = ref<AdminAgentOption[]>([]);
const form = ref<QuestionFormState>(createEmptyQuestionForm());
const isEditing = ref(false);
const isLoading = ref(true);
const isSaving = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const loadQuestions = async (): Promise<void> => {
try {
questions.value = await listAdminQuickQuestions();
} catch (e) {
console.error('Failed to load quick questions', e);
questions.value = [];
}
};
const loadAgents = async (): Promise<void> => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Failed to load agents', e);
agents.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([loadQuestions(), loadAgents()]);
isLoading.value = false;
};
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const resetForm = (): void => {
form.value = createEmptyQuestionForm();
isEditing.value = false;
};
const editQuestion = (q: AdminQuickQuestionRow): void => {
form.value = {
id: q.id,
title: q.title,
question: q.question,
agent_id: q.agent_id,
sort_order: q.sort_order,
};
isEditing.value = true;
};
const saveQuestion = async (): Promise<void> => {
if (!form.value.title || !form.value.question || !form.value.agent_id) {
msg.warning(t('admin.question.msg.fillAll'));
return;
}
isSaving.value = true;
try {
const url = isEditing.value
? `/api/admin/quick-questions/${form.value.id}`
: '/api/admin/quick-questions';
const method = isEditing.value ? 'PUT' : 'POST';
await saveAdminQuickQuestion(url, method, form.value as Record<string, unknown>);
await loadQuestions();
resetForm();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const deleteQuestion = (id: number): void => {
openDeleteConfirm(t('admin.question.confirmDelete'), async () => {
try {
await deleteAdminQuickQuestion(id);
await loadQuestions();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
return {
questions,
agents,
form,
isEditing,
isLoading,
isSaving,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
editQuestion,
saveQuestion,
deleteQuestion,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -0,0 +1,390 @@
/**
* features/admin/modules/reports/ReportsPage.vue
* 管理后台报表独立页面。路由:/admin/reports/:table?
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { BarChart2, Download, Settings2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useReportsAdmin } from './composables/useReportsAdmin';
const { t } = useI18n();
const {
usageReport,
isLoading,
currentTable,
tableData,
isFullScreen,
columnFilters,
selectedReportRowIds,
isDeletingChatLogs,
chatLogsTotal,
showChatLogsColumnPanel,
chatLogsWrapEnabled,
chatLogsWrapMaxHeight,
showChatLogsSelection,
reportCurrentPage,
reportPageSize,
reportPageSizeOptions,
chatLogsColumns,
chatLogsSortRules,
isChatLogsTable,
visibleReportKeys,
allReportRowsSelected,
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,
} = useReportsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<!-- Reports -->
<section
v-else
class="admin-report-section transition-all duration-300"
:class="isFullScreen ? 'fixed inset-0 z-50 m-0 rounded-none h-screen w-screen overflow-auto p-8' : ''"
>
<div class="admin-report-toolbar">
<div class="space-y-2">
<h2 class="section-title text-lg flex items-center gap-3">
<span class="inline-flex h-8 w-8 items-center justify-center rounded-xl bg-gradient-to-br from-brand-600 to-brand-400 shadow-md shadow-brand-500/25">
<BarChart2 class="w-4 h-4 text-white" />
</span>
{{ t('admin.report.title', { table: getReportTableLabel(currentTable) }) }}
</h2>
<div class="flex flex-wrap items-center gap-2 text-xs">
<span class="admin-report-badge">
{{ t('admin.report.subtitle') }}
</span>
<span v-if="isChatLogsTable" class="admin-report-badge admin-report-badge--info font-semibold">
{{ t('admin.report.totalRows', { total: chatLogsTotal }) }}
</span>
<span class="admin-report-badge admin-report-badge--indigo font-semibold">
{{ t('admin.report.showingRange', { start: reportRangeStart, end: reportRangeEnd, total: reportTotalRows }) }}
</span>
</div>
</div>
<div class="flex flex-wrap items-center gap-2 md:gap-3">
<button
@click="showChatLogsColumnPanel = !showChatLogsColumnPanel"
class="btn-secondary text-sm font-semibold"
:title="t('admin.report.columnSettings')"
>
<Settings2 class="w-4 h-4" />
<span>{{ t('admin.report.columnSettings') }}</span>
</button>
<button
v-if="isChatLogsTable"
@click="showChatLogsSelection = !showChatLogsSelection"
class="btn-secondary text-xs font-medium"
>
{{ showChatLogsSelection ? t('admin.report.hideSelection') : t('admin.report.showSelection') }}
</button>
<button
v-if="isChatLogsTable && showChatLogsSelection"
@click="batchDeleteChatLogs"
:disabled="selectedReportRowIds.length === 0 || isDeletingChatLogs"
class="flex items-center gap-2 px-4 py-2 bg-rose-600 text-white text-sm font-medium rounded-xl hover:bg-rose-700 transition-all shadow-md shadow-rose-200 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ isDeletingChatLogs ? t('admin.report.deleting') : t('admin.report.deleteSelected', { count: selectedReportRowIds.length }) }}
</button>
<button
@click="exportToExcel"
class="flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white text-sm font-medium rounded-xl hover:bg-emerald-700 transition-all shadow-md shadow-emerald-200 active:scale-95"
>
<Download class="w-4 h-4" />
{{ t('admin.report.export') }}
</button>
<button
@click="isFullScreen = !isFullScreen"
class="btn-icon-ds"
:title="isFullScreen ? t('admin.report.exitFullscreen') : t('admin.report.enterFullscreen')"
>
<svg v-if="!isFullScreen" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M16 3h3a2 2 0 0 1 2 2v3"/><path d="M8 21H5a2 2 0 0 1-2-2v-3"/><path d="M16 21h3a2 2 0 0 1 2 2v-3"/></svg>
<svg v-else xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3v3a2 2 0 0 1-2 2H3"/><path d="M21 8h-3a2 2 0 0 1-2-2V3"/><path d="M3 16h3a2 2 0 0 1 2 2v3"/><path d="M16 21v-3a2 2 0 0 1 2-2h3"/></svg>
</button>
</div>
</div>
<div class="p-5 md:p-8 space-y-5">
<div
v-if="showChatLogsColumnPanel"
class="admin-report-panel"
>
<div class="flex items-center justify-between mb-3">
<div class="text-sm font-semibold text-primary">{{ t('admin.report.tableSettings') }}</div>
<button
@click="resetChatLogsColumns"
class="btn-secondary text-xs px-3 py-1.5"
>
{{ t('admin.report.resetLayout') }}
</button>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
<label class="admin-report-setting-chip">
<input type="checkbox" v-model="chatLogsWrapEnabled" class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500" />
<span>{{ t('admin.report.wrapText') }}</span>
</label>
<label class="admin-report-setting-chip">
<span>{{ t('admin.report.wrapMaxHeightPx') }}</span>
<input
v-model.number="chatLogsWrapMaxHeight"
type="number"
step="1"
class="admin-table-filter-input w-24 py-1"
/>
</label>
</div>
<div class="mb-3 p-3 rounded-xl border border-default bg-surface-soft">
<div class="flex items-center justify-between mb-2">
<span class="text-xs font-semibold text-secondary">{{ t('admin.report.advancedSortRules') }}</span>
<button
@click="addChatLogsSortRule"
class="btn-secondary text-xs px-2 py-1"
>
+ {{ t('admin.report.addRule') }}
</button>
</div>
<div v-if="chatLogsSortRules.length === 0" class="text-xs text-muted">{{ t('admin.report.noAdvancedSort') }}</div>
<div v-else class="space-y-2">
<div
v-for="(rule, ridx) in chatLogsSortRules"
:key="`sort-rule-${ridx}`"
class="admin-report-sort-row"
>
<span class="col-span-1 text-muted">{{ ridx + 1 }}.</span>
<select v-model="rule.key" class="col-span-4 admin-table-filter-input py-1">
<option v-for="k in Object.keys(tableData[0] || {})" :key="`rule-key-${k}`" :value="k">{{ getReportColumnLabel(k) }}</option>
</select>
<select v-model="rule.direction" class="col-span-3 admin-table-filter-input py-1">
<option value="asc">{{ t('admin.report.sortAsc') }}</option>
<option value="desc">{{ t('admin.report.sortDesc') }}</option>
</select>
<div class="col-span-4 flex items-center justify-end gap-1">
<button @click="moveChatLogsSortRule(ridx, -1)" class="btn-secondary text-xs px-2 py-1">{{ t('admin.report.moveUp') }}</button>
<button @click="moveChatLogsSortRule(ridx, 1)" class="btn-secondary text-xs px-2 py-1">{{ t('admin.report.moveDown') }}</button>
<button @click="removeChatLogsSortRule(ridx)" class="btn-danger text-xs px-2 py-1">{{ t('admin.report.remove') }}</button>
</div>
</div>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
<div
v-for="col in chatLogsColumns"
:key="`cfg-${col.key}`"
class="admin-report-col-chip"
>
<label class="flex items-center gap-2 min-w-0">
<input type="checkbox" v-model="col.visible" class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500" />
<span class="text-xs text-secondary truncate">{{ getReportColumnLabel(col.key) }}</span>
</label>
<div class="flex items-center gap-1">
<button @click="moveChatLogsColumn(col.key, -1)" class="btn-secondary text-xs px-1.5 py-0.5">&lt;</button>
<button @click="moveChatLogsColumn(col.key, 1)" class="btn-secondary text-xs px-1.5 py-0.5">&gt;</button>
</div>
</div>
</div>
</div>
<div v-if="tableData.length === 0" class="text-center text-muted py-20 bg-surface-soft rounded-2xl border border-dashed border-default">
<p>{{ t('admin.report.noData', { table: getReportTableLabel(currentTable) }) }}</p>
</div>
<div v-else class="admin-report-table-wrap">
<table class="admin-report-table w-full border-collapse">
<thead>
<tr>
<th v-if="isChatLogsTable && showChatLogsSelection" class="px-4 py-4 w-10">
<input
type="checkbox"
:checked="allReportRowsSelected"
@change="toggleAllReportRows"
class="w-4 h-4 rounded text-blue-600 focus:ring-blue-500"
/>
</th>
<th
v-for="key in visibleReportKeys"
:key="key"
class="px-6 py-4 whitespace-nowrap align-top relative"
:style="getColumnWidthStyle(key)"
:draggable="true"
@dragstart="onColumnDragStart(String(key))"
@dragover.prevent
@drop="onColumnDrop(String(key))"
>
<div class="flex flex-col gap-2 min-w-0">
<button
@click="onReportHeaderClick(String(key))"
class="admin-report-header-btn"
>
{{ getReportColumnLabel(String(key)) }} <span class="text-[10px] text-brand-500">{{ getHeaderSortMark(String(key)) }}</span>
</button>
<input
v-model="columnFilters[key]"
@input="handleFilterChange"
type="text"
class="admin-report-filter-input"
:placeholder="t('admin.report.filterPlaceholder')"
/>
</div>
<span
class="absolute right-0 top-0 h-full w-1.5 cursor-col-resize select-none"
@mousedown="startResizeColumn(String(key), $event)"
></span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, idx) in paginatedSortedTableData" :key="idx">
<td v-if="isChatLogsTable && showChatLogsSelection" class="px-4 py-3">
<input
type="checkbox"
:checked="selectedReportRowIds.includes(getReportRowId(row))"
@change="toggleReportRowSelection(getReportRowId(row))"
class="w-4 h-4 rounded text-blue-600 focus:ring-blue-500"
/>
</td>
<td
v-for="key in visibleReportKeys"
:key="`cell-${idx}-${key}`"
class="px-6 py-3 font-mono"
:title="String(getReportCellValue(row, String(key)))"
:style="getReportCellDisplayStyle(String(key))"
>
<div :style="getReportCellInnerStyle()">
{{ getReportCellValue(row, String(key)) }}
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="tableData.length > 0" class="flex flex-col gap-3 rounded-2xl border border-default bg-surface px-4 py-3 md:flex-row md:items-center md:justify-between">
<div class="text-sm text-secondary">
{{ t('admin.report.paginationSummary', { total: reportTotalRows, page: reportCurrentPage, pages: reportTotalPages }) }}
</div>
<div class="flex flex-wrap items-center gap-2">
<label class="flex items-center gap-2 text-xs text-secondary">
<span>{{ t('admin.report.perPage') }}</span>
<span class="relative inline-flex items-center">
<select
v-model.number="reportPageSize"
class="admin-table-filter-input appearance-none pl-2 pr-7 py-1 text-xs leading-5"
>
<option v-for="size in reportPageSizeOptions" :key="`page-size-${size}`" :value="size">{{ size }}</option>
</select>
<svg class="pointer-events-none absolute right-2 h-3.5 w-3.5 text-muted" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z" clip-rule="evenodd" />
</svg>
</span>
<span>{{ t('admin.report.itemsUnit') }}</span>
</label>
<button
@click="prevReportPage"
:disabled="reportCurrentPage <= 1"
class="admin-report-page-btn"
>
{{ t('admin.report.prevPage') }}
</button>
<button
v-for="btn in reportPageButtons"
:key="`report-page-btn-${btn}`"
:disabled="btn === -1"
@click="btn !== -1 && goToReportPage(btn)"
class="admin-report-page-btn"
:class="btn === -1
? 'border-transparent text-muted cursor-default opacity-100'
: btn === reportCurrentPage
? 'admin-report-page-btn--active'
: ''"
>
{{ btn === -1 ? '...' : btn }}
</button>
<button
@click="nextReportPage"
:disabled="reportCurrentPage >= reportTotalPages"
class="admin-report-page-btn"
>
{{ t('admin.report.nextPage') }}
</button>
</div>
</div>
<!-- Statistics Charts -->
<div v-if="currentTable === 'chat_logs' && usageReport" class="mt-10 border-t border-default pt-10">
<h3 class="section-title text-lg mb-6">{{ t('admin.report.usage') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-8">
<div class="card p-6">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byUser') }}</h4>
<div class="space-y-3">
<div v-for="u in usageReport.by_user" :key="u.username" class="flex items-center justify-between p-3 bg-surface-soft rounded-xl">
<span class="font-medium text-secondary">{{ u.username }}</span>
<span class="admin-report-badge admin-report-badge--info font-bold">{{ u.count }}</span>
</div>
</div>
</div>
<div class="card p-6">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byAgent') }}</h4>
<div class="space-y-3">
<div v-for="a in usageReport.by_agent" :key="a.agent" class="flex items-center justify-between p-3 bg-surface-soft rounded-xl">
<span class="font-medium text-secondary">{{ a.agent }}</span>
<span class="admin-report-badge admin-report-badge--info font-bold">{{ a.count }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="confirmDelete"
/>
</template>
@@ -0,0 +1,865 @@
/**
* features/admin/modules/reports/composables/useReportsAdmin.ts
* 管理后台报表:多表浏览、筛选、排序、chat_logs 批量删除与用量图表。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import * as XLSX from 'xlsx';
import {
batchDeleteAdminChatLogs,
getAdminReportTable,
getAdminReportTableCount,
getAdminUsageReport,
} from '@/api/admin';
import { loadReportLayoutPref, saveReportLayoutPref } from '@/composables/useReportLayoutStorage';
import { useMessage } from '@/composables/useMessage';
import { ADMIN_REPORT_TABLES } from '@/features/admin/constants/modules';
import type {
ChatLogsLayoutPref,
ReportColumnConfig,
SortRule,
UsageReport,
} from '@/features/admin/types/report.types';
import type { AdminReportTableId } from '@/features/admin/types/admin.types';
export function useReportsAdmin() {
const { t, locale } = useI18n();
const msg = useMessage();
const route = useRoute();
const usageReport = ref<UsageReport | null>(null);
const isLoading = ref(true);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const resolveTableFromRoute = (): AdminReportTableId => {
const table = route.params.table;
if (typeof table === 'string' && (ADMIN_REPORT_TABLES as readonly string[]).includes(table)) {
return table as AdminReportTableId;
}
return 'users';
};
const currentTable = ref<AdminReportTableId>(resolveTableFromRoute());
watch(
() => route.params.table,
() => {
currentTable.value = resolveTableFromRoute();
},
);
const loadReports = async (): Promise<void> => {
try {
usageReport.value = await getAdminUsageReport();
} catch (e) {
console.error('Error loading reports:', e);
}
};
// 报表相关状态
const tableData = ref<any[]>([]);
const isFullScreen = ref(false);
const columnFilters = ref<Record<string, string>>({});
const selectedReportRowIds = ref<number[]>([]);
const isDeletingChatLogs = ref(false);
const chatLogsTotal = ref(0);
const showChatLogsColumnPanel = ref(false);
const chatLogsWrapEnabled = ref(false);
const chatLogsWrapMaxHeight = ref(120);
const showChatLogsSelection = ref(false);
const reportCurrentPage = ref(1);
const reportPageSize = ref(20);
const reportPageSizeOptions = [10, 20, 50, 100];
const chatLogsColumns = ref<ReportColumnConfig[]>([]);
const chatLogsSortRules = ref<SortRule[]>([]);
const reportHeaderSort = ref<SortRule | null>(null);
const draggingColumnKey = ref<string | null>(null);
const resizingColumnKey = ref<string | null>(null);
let resizeStartX = 0;
let resizeStartWidth = 0;
const loadTableData = async () => {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(columnFilters.value)) {
if (value) params.append(key, value);
}
const url = currentTable.value === 'general_feedbacks'
? `/api/admin/reports/general-feedbacks?${params.toString()}`
: `/api/admin/database/${currentTable.value}?${params.toString()}`;
try {
tableData.value = await getAdminReportTable(url);
if (tableData.value.length > 0) {
initChatLogsColumns(Object.keys(tableData.value[0] || {}));
}
if (currentTable.value === 'chat_logs') {
const validIds = new Set(
tableData.value
.map((row: any) => Number(row?.id))
.filter((id: number) => Number.isFinite(id))
);
selectedReportRowIds.value = selectedReportRowIds.value.filter(id => validIds.has(id));
} else {
selectedReportRowIds.value = [];
}
} catch {
tableData.value = [];
selectedReportRowIds.value = [];
}
};
const saveChatLogsColumns = () => {
if (chatLogsColumns.value.length === 0) return;
const payload: ChatLogsLayoutPref = {
columns: chatLogsColumns.value,
wrapEnabled: chatLogsWrapEnabled.value,
wrapMaxHeight: chatLogsWrapMaxHeight.value,
sortRules: chatLogsSortRules.value,
};
saveReportLayoutPref(currentTable.value, payload);
};
const initChatLogsColumns = (keys: string[]) => {
chatLogsWrapEnabled.value = false;
chatLogsWrapMaxHeight.value = 120;
const defaults: ReportColumnConfig[] = keys.map((k) => ({
key: k,
visible: true,
width: k === 'id' ? 90 : 180
}));
let merged = defaults;
try {
const parsed = loadReportLayoutPref<ReportColumnConfig[] | ChatLogsLayoutPref>(currentTable.value);
if (parsed) {
const saved = Array.isArray(parsed) ? parsed : (parsed.columns || []);
const savedMap = new Map(saved.map((c) => [c.key, c]));
const order = saved.map((c) => c.key).filter((k) => keys.includes(k));
const missing = keys.filter((k) => !order.includes(k));
merged = [...order, ...missing].map((k) => ({
key: k,
visible: savedMap.get(k)?.visible ?? true,
width: savedMap.get(k)?.width ?? (k === 'id' ? 90 : 180),
}));
if (!Array.isArray(parsed)) {
chatLogsWrapEnabled.value = !!parsed.wrapEnabled;
chatLogsWrapMaxHeight.value = Number(parsed.wrapMaxHeight || 120);
chatLogsSortRules.value = Array.isArray(parsed.sortRules)
? parsed.sortRules
.filter((r: any) => r && typeof r.key === 'string' && (r.direction === 'asc' || r.direction === 'desc'))
: [];
}
}
} catch {
merged = defaults;
}
if (!Number.isFinite(chatLogsWrapMaxHeight.value)) chatLogsWrapMaxHeight.value = 120;
chatLogsColumns.value = merged;
};
const resetChatLogsColumns = () => {
if (tableData.value.length === 0) return;
chatLogsWrapEnabled.value = false;
chatLogsWrapMaxHeight.value = 120;
chatLogsSortRules.value = [];
reportHeaderSort.value = null;
initChatLogsColumns(Object.keys(tableData.value[0] || {}));
saveChatLogsColumns();
};
const moveChatLogsColumn = (key: string, direction: -1 | 1) => {
const idx = chatLogsColumns.value.findIndex((c) => c.key === key);
if (idx < 0) return;
const target = idx + direction;
if (target < 0 || target >= chatLogsColumns.value.length) return;
const copy = [...chatLogsColumns.value];
const [item] = copy.splice(idx, 1);
if (!item) return;
copy.splice(target, 0, item);
chatLogsColumns.value = copy;
saveChatLogsColumns();
};
const onColumnDragStart = (key: string) => {
draggingColumnKey.value = key;
};
const onColumnDrop = (targetKey: string) => {
const sourceKey = draggingColumnKey.value;
draggingColumnKey.value = null;
if (!sourceKey || sourceKey === targetKey) return;
const sourceIdx = chatLogsColumns.value.findIndex((c) => c.key === sourceKey);
const targetIdx = chatLogsColumns.value.findIndex((c) => c.key === targetKey);
if (sourceIdx < 0 || targetIdx < 0) return;
const copy = [...chatLogsColumns.value];
const [item] = copy.splice(sourceIdx, 1);
if (!item) return;
copy.splice(targetIdx, 0, item);
chatLogsColumns.value = copy;
saveChatLogsColumns();
};
const onResizeMouseMove = (e: MouseEvent) => {
if (!resizingColumnKey.value) return;
const diff = e.clientX - resizeStartX;
const col = chatLogsColumns.value.find((c) => c.key === resizingColumnKey.value);
if (!col) return;
col.width = Math.max(80, resizeStartWidth + diff);
};
const onResizeMouseUp = () => {
if (!resizingColumnKey.value) return;
resizingColumnKey.value = null;
document.removeEventListener('mousemove', onResizeMouseMove);
document.removeEventListener('mouseup', onResizeMouseUp);
saveChatLogsColumns();
};
const startResizeColumn = (key: string, e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
const col = chatLogsColumns.value.find((c) => c.key === key);
if (!col) return;
resizingColumnKey.value = key;
resizeStartX = e.clientX;
resizeStartWidth = col.width;
document.addEventListener('mousemove', onResizeMouseMove);
document.addEventListener('mouseup', onResizeMouseUp);
};
const loadTableCount = async (table: string) => {
try {
const countUrl = table === 'general_feedbacks'
? '/api/admin/reports/general-feedbacks/count'
: `/api/admin/database/${table}/count`;
const data = await getAdminReportTableCount(countUrl);
return Number(data.total || 0);
} catch {
return 0;
}
};
const exportToExcel = () => {
if (tableData.value.length === 0) return;
const ws = XLSX.utils.json_to_sheet(tableData.value);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, currentTable.value);
XLSX.writeFile(wb, `${currentTable.value}_report_${new Date().toISOString().split('T')[0]}.xlsx`);
};
// Debounce filter input
let debounceTimer: any = null;
const handleFilterChange = () => {
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
loadTableData();
}, 500);
};
const isChatLogsTable = computed(() => currentTable.value === 'chat_logs');
const visibleReportKeys = computed(() => {
let keys: string[];
if (chatLogsColumns.value.length === 0) {
keys = Object.keys(tableData.value[0] || {});
} else {
keys = chatLogsColumns.value.filter((c) => c.visible).map((c) => c.key);
}
if (currentTable.value === 'general_feedbacks') {
const feedbackFixedOrder = [
'created_at',
'source_page',
'feedback_module',
'feedback_type',
'content',
'username',
'real_name',
'department',
'chat_log_id',
];
const available = new Set(keys);
return feedbackFixedOrder.filter((k) => available.has(k));
}
return keys;
});
const resolveReportLang = () => {
const l = String(locale.value || 'en').toLowerCase();
if (l.startsWith('zh-cn')) return 'zh-CN';
if (l.startsWith('zh-tw')) return 'zh-TW';
if (l.startsWith('th')) return 'th';
return 'en';
};
const feedbackReportI18nMap: Record<string, {
columns: Record<string, string>;
types: Record<string, string>;
modules: Record<string, string>;
pages: Record<string, string>;
}> = {
en: {
columns: {
feedback_module: 'Feedback Module',
feedback_type: 'Feedback Type',
source_page: 'Source Page',
real_name: 'Real Name',
department: 'Department',
},
types: {
feature_suggestion: 'Feature Suggestion',
issue_feedback: 'Issue Feedback',
experience_optimization: 'Experience Optimization',
},
modules: {
knowledge_base: 'Knowledge Base',
general: 'General',
workflow: 'Workflow',
account_permission: 'Account & Permissions',
},
pages: {
workspace: 'Workspace',
chat: 'Chat',
unknown: 'Unknown',
},
},
'zh-CN': {
columns: {
feedback_module: '\u53cd\u9988\u6a21\u5757',
feedback_type: '\u53cd\u9988\u7c7b\u578b',
source_page: '\u6765\u6e90\u9875\u9762',
real_name: '\u771f\u5b9e\u59d3\u540d',
department: '\u90e8\u95e8',
},
types: {
feature_suggestion: '\u529f\u80fd\u5efa\u8bae',
issue_feedback: '\u95ee\u9898\u53cd\u9988',
experience_optimization: '\u4f53\u9a8c\u4f18\u5316',
},
modules: {
knowledge_base: '\u77e5\u8bc6\u5e93',
general: '\u901a\u7528',
workflow: '\u5de5\u4f5c\u6d41',
account_permission: '\u8d26\u53f7\u6743\u9650',
},
pages: {
workspace: '\u5de5\u4f5c\u53f0',
chat: '\u5bf9\u8bdd',
unknown: '\u672a\u77e5',
},
},
'zh-TW': {
columns: {
feedback_module: '\u53cd\u994b\u6a21\u7d44',
feedback_type: '\u53cd\u994b\u985e\u578b',
source_page: '\u4f86\u6e90\u9801\u9762',
real_name: '\u771f\u5be6\u59d3\u540d',
department: '\u90e8\u9580',
},
types: {
feature_suggestion: '\u529f\u80fd\u5efa\u8b70',
issue_feedback: '\u554f\u984c\u56de\u994b',
experience_optimization: '\u9ad4\u9a57\u512a\u5316',
},
modules: {
knowledge_base: '\u77e5\u8b58\u5eab',
general: '\u901a\u7528',
workflow: '\u5de5\u4f5c\u6d41',
account_permission: '\u5e33\u865f\u6b0a\u9650',
},
pages: {
workspace: '\u5de5\u4f5c\u53f0',
chat: '\u5c0d\u8a71',
unknown: '\u672a\u77e5',
},
},
th: {
columns: {
feedback_module: '\u0e42\u0e21\u0e14\u0e39\u0e25\u0e02\u0e49\u0e2d\u0e40\u0e2a\u0e19\u0e2d\u0e41\u0e19\u0e30',
feedback_type: '\u0e1b\u0e23\u0e30\u0e40\u0e20\u0e17\u0e02\u0e49\u0e2d\u0e40\u0e2a\u0e19\u0e2d\u0e41\u0e19\u0e30',
source_page: '\u0e2b\u0e19\u0e49\u0e32\u0e15\u0e49\u0e19\u0e17\u0e32\u0e07',
real_name: '\u0e0a\u0e37\u0e48\u0e2d\u0e08\u0e23\u0e34\u0e07',
department: '\u0e41\u0e1c\u0e19\u0e01',
},
types: {
feature_suggestion: '\u0e02\u0e49\u0e2d\u0e40\u0e2a\u0e19\u0e2d\u0e41\u0e19\u0e30\u0e1f\u0e35\u0e40\u0e08\u0e2d\u0e23\u0e4c',
issue_feedback: '\u0e41\u0e08\u0e49\u0e07\u0e1b\u0e31\u0e0d\u0e2b\u0e32',
experience_optimization: '\u0e1b\u0e23\u0e31\u0e1a\u0e1b\u0e23\u0e38\u0e07\u0e1b\u0e23\u0e30\u0e2a\u0e1a\u0e01\u0e32\u0e23\u0e13\u0e4c',
},
modules: {
knowledge_base: '\u0e04\u0e25\u0e31\u0e07\u0e04\u0e27\u0e32\u0e21\u0e23\u0e39\u0e49',
general: '\u0e17\u0e31\u0e48\u0e27\u0e44\u0e1b',
workflow: '\u0e40\u0e27\u0e34\u0e23\u0e4c\u0e01\u0e42\u0e1f\u0e25\u0e27\u0e4c',
account_permission: '\u0e1a\u0e31\u0e0d\u0e0a\u0e35\u0e41\u0e25\u0e30\u0e2a\u0e34\u0e17\u0e18\u0e34\u0e4c',
},
pages: {
workspace: '\u0e40\u0e27\u0e34\u0e23\u0e4c\u0e01\u0e2a\u0e40\u0e1b\u0e0b',
chat: '\u0e41\u0e0a\u0e17',
unknown: '\u0e44\u0e21\u0e48\u0e17\u0e23\u0e32\u0e1a',
},
},
};
const getReportColumnLabel = (key: string) => {
const lang = resolveReportLang();
const enPack = feedbackReportI18nMap['en'] || { columns: {}, types: {}, modules: {}, pages: {} };
const direct = feedbackReportI18nMap[lang]?.columns?.[key] || enPack.columns[key];
if (direct) return direct;
const i18nKey = `admin.report.columns.${key}`;
const translated = t(i18nKey);
if (translated && translated !== i18nKey) return translated;
return key.replace(/_/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase());
};
const getReportTableLabel = (table: string) => {
const i18nKey = `admin.report.tables.${table}`;
const translated = t(i18nKey);
if (translated && translated !== i18nKey) return translated;
return table.replace(/_/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase());
};
const getReportRowId = (row: any) => Number(row?.id);
const allReportRowsSelected = computed(() => {
if (!isChatLogsTable.value || paginatedSortedTableData.value.length === 0) return false;
return paginatedSortedTableData.value.every((row: any) => selectedReportRowIds.value.includes(getReportRowId(row)));
});
const getColumnWidthStyle = (key: string) => {
const col = chatLogsColumns.value.find((c) => c.key === key);
if (!col) return {};
return {
width: `${col.width}px`,
minWidth: `${col.width}px`,
maxWidth: `${col.width}px`,
};
};
// 报表值翻译辅助:优先返回 i18n 文案;若没有配置对应翻译则回退原始值
const getTranslatedValue = (i18nKey: string, fallbackValue: any) => {
const translated = t(i18nKey);
return translated && translated !== i18nKey ? translated : fallbackValue;
};
const normalizeFeedbackKey = (value: any) => {
if (value === null || value === undefined) return '';
const raw = String(value).trim();
if (!raw) return '';
const map: Record<string, string> = {
'\u529f\u80fd\u5efa\u8bae': 'feature_suggestion',
'\u95ee\u9898\u53cd\u9988': 'issue_feedback',
'\u4f53\u9a8c\u4f18\u5316': 'experience_optimization',
'\u77e5\u8bc6\u5e93': 'knowledge_base',
'\u901a\u7528': 'general',
'\u5de5\u4f5c\u6d41': 'workflow',
'\u8d26\u53f7\u6743\u9650': 'account_permission',
workspace: 'workspace',
chat: 'chat',
unknown: 'unknown',
};
const normalized = raw.toLowerCase().replace(/[\s\-]+/g, '_');
return map[raw] || map[normalized] || normalized;
};
const getTranslatedFeedbackValue = (group: 'types' | 'modules' | 'pages', value: any) => {
const normalized = normalizeFeedbackKey(value);
if (!normalized) return value;
const lang = resolveReportLang();
const enPack = feedbackReportI18nMap['en'] || { columns: {}, types: {}, modules: {}, pages: {} };
const dict = feedbackReportI18nMap[lang]?.[group] || enPack[group];
return dict?.[normalized] || value;
};
const formatReportDateTime = (value: any) => {
if (value === null || value === undefined || value === '') return value;
const d = new Date(value);
if (Number.isNaN(d.getTime())) return value;
const localeMap: Record<string, string> = {
'zh-CN': 'zh-CN',
'zh-TW': 'zh-TW',
en: 'en-US',
th: 'th-TH',
};
const lang = resolveReportLang();
const localeName = localeMap[lang] || 'en-US';
return new Intl.DateTimeFormat(localeName, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
}).format(d);
};
const getReportCellValue = (row: any, key: string) => {
const value = row?.[key];
if (key === 'is_active') {
const truthy = value === true || value === 1 || value === '1' || value === 'true' || value === 'True';
return truthy ? t('admin.status.active') : t('admin.status.disabled');
}
if (key === 'role' && typeof value === 'string') {
return getTranslatedValue(`admin.role.${value}`, value);
}
if (key === 'status' && typeof value === 'string') {
return getTranslatedValue(`admin.status.${value}`, value);
}
if (key === 'theme_preference' && typeof value === 'string') {
return getTranslatedValue(`theme.${value}`, value);
}
if (key === 'feedback_type') {
return getTranslatedFeedbackValue('types', value);
}
if (key === 'feedback_module') {
return getTranslatedFeedbackValue('modules', value);
}
if (key === 'source_page') {
return getTranslatedFeedbackValue('pages', value);
}
// format datetime fields in report table
if (typeof value === 'string' && (key.endsWith('_at') || key === 'created_at' || key === 'updated_at')) {
return formatReportDateTime(value);
}
if (key === 'language' && typeof value === 'string') {
const languageLabelMap: Record<string, string> = {
'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 <td>; height clamp is applied to inner block container.
return { ...getColumnWidthStyle(key) } as any;
};
const getReportCellInnerStyle = () => {
const style: Record<string, string> = { 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<void> => {
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,
};
}
@@ -0,0 +1,100 @@
/**
* features/admin/modules/requests/RequestsPage.vue
* 权限申请管理独立页面。路由:/admin/requests
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ShieldCheck } from 'lucide-vue-next';
import { useRequestsAdmin } from './composables/useRequestsAdmin';
const { t } = useI18n();
const {
requests,
isLoading,
loadAll,
approveRequest,
rejectRequest,
} = useRequestsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="admin-table-header">
<div>
<h2 class="section-title">{{ t('admin.request.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.request.subtitle') }}</p>
</div>
</div>
<div
v-if="requests.length === 0"
class="flex flex-col items-center justify-center py-16 text-muted"
>
<div class="w-16 h-16 bg-surface-soft rounded-full flex items-center justify-center mb-4">
<ShieldCheck class="w-8 h-8 text-muted" />
</div>
<p>{{ t('admin.request.noPending') }}</p>
</div>
<table v-else class="admin-table">
<thead>
<tr>
<th class="px-8 py-4 text-xs">{{ t('admin.request.headers.userId') }}</th>
<th class="px-8 py-4 text-xs">{{ t('admin.request.headers.targetAgent') }}</th>
<th class="px-8 py-4 text-xs">{{ t('admin.request.headers.reason') }}</th>
<th class="px-8 py-4 text-xs">{{ t('admin.request.headers.status') }}</th>
<th class="px-8 py-4 text-xs text-right">{{ t('admin.request.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="req in requests" :key="req.id">
<td class="px-8 py-4 text-sm font-medium text-primary">{{ req.user_id }}</td>
<td class="px-8 py-4 text-sm text-secondary">{{ req.agent_id }}</td>
<td
class="px-8 py-4 text-sm text-muted max-w-xs truncate"
:title="req.reason"
>
{{ req.reason || '-' }}
</td>
<td class="px-8 py-4">
<span
class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-50 text-yellow-700 border border-yellow-100"
>
{{ t('admin.status.' + req.status) }}
</span>
</td>
<td class="px-8 py-4 text-right">
<div class="flex justify-end gap-3">
<button
type="button"
class="text-green-600 hover:text-green-800 text-sm font-medium hover:underline"
@click="approveRequest(req.id)"
>
{{ t('admin.request.approve') }}
</button>
<button
type="button"
class="text-red-500 hover:text-red-700 text-sm font-medium hover:underline"
@click="rejectRequest(req.id)"
>
{{ t('admin.request.reject') }}
</button>
</div>
</td>
</tr>
</tbody>
</table>
</template>
</section>
</template>
@@ -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<AdminPermissionRequestRow[]>([]);
const isLoading = ref(true);
const loadRequests = async (): Promise<void> => {
try {
requests.value = await listAdminPermissionRequests();
} catch (e) {
console.error('Error loading permission requests:', e);
requests.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadRequests();
isLoading.value = false;
};
const approveRequest = async (id: number): Promise<void> => {
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<void> => {
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,
};
}
File diff suppressed because it is too large. Load diff
@@ -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<AdminAgentOption[]>([]);
const users = ref<AdminUserRow[]>([]);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmTitle = ref('');
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const openDeleteConfirm = (
message: string,
onConfirm: () => Promise<void> | 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<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const loadAgents = async (): Promise<void> => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Failed to load agents', e);
agents.value = [];
}
};
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const schedules = ref<ScheduleTask[]>([]);
const schedulesLoaded = ref(false); void schedulesLoaded;
const selectedScheduleRuns = ref<ScheduleRun[]>([]);
const scheduleLoading = ref(false);
const scheduleRunsLoading = ref(false);
const selectedScheduleId = ref<number | null>(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<string, string> = {
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<number | null>(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<string, { cls: string; label: string }> = {
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<number | null>(null);
const expandedScheduleRun = computed(() => {
if (!expandedScheduleRunId.value) return null;
return filteredScheduleRuns.value.find((x) => x.id === expandedScheduleRunId.value) || null;
});
const stepLabelMap: Record<string, string> = {
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<string, { cls: string; label: string }> = {
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<ScheduleTask | null>(null);
const testRunWhere = ref('');
const testRunOrderBy = ref('');
const testRunBaseFetchSql = ref('');
const testRunLimit = ref(3);
const testRunLoading = ref(false);
const testRunResult = ref<TestScheduleRunResult | null>(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<string, string> = {};
try {
headerLabels = JSON.parse(scheduleSqlEditForm.value.header_labels_str || '{}');
} catch {
msg.error(t('admin.schedule.msg.headerLabelsJsonInvalid'));
return;
}
let apiHeaders: Record<string, string> = {};
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<string, any> = {
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<void> => {
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,
};
}
@@ -0,0 +1,244 @@
/**
* features/admin/modules/users/UsersPage.vue
* 用户管理独立页面。路由:/admin/users
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Plus, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import BatchEditUserModal from './components/BatchEditUserModal.vue';
import BatchPermissionModal from './components/BatchPermissionModal.vue';
import UserFormModal from './components/UserFormModal.vue';
import { useUsersAdmin } from './composables/useUsersAdmin';
const { t } = useI18n();
const {
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,
} = useUsersAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.user.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.user.subtitle') }}</p>
</div>
<div class="flex flex-wrap gap-3">
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-red-50 text-red-600 rounded-xl hover:bg-red-100 transition-all border border-red-200 text-sm font-medium"
@click="cleanRejectedUsers"
>
<Trash2 class="w-4 h-4" />
<span>{{ t('admin.user.cleanRejected') }}</span>
</button>
<button
v-if="selectedUserIds.length > 0"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-xl hover:bg-red-700 transition-all shadow-lg shadow-red-200 active:scale-95 text-sm font-medium"
@click="batchDeleteUsers"
>
<Trash2 class="w-4 h-4" />
<span>{{ t('admin.user.batchDelete') }} ({{ selectedUserIds.length }})</span>
</button>
<button
v-if="selectedUserIds.length > 0"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-200 active:scale-95 text-sm font-medium"
@click="openBatchEditModal"
>
<Edit class="w-4 h-4" />
<span>{{ t('admin.user.batchEdit') }} ({{ selectedUserIds.length }})</span>
</button>
<button
v-if="selectedUserIds.length > 0"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-xl hover:bg-purple-700 transition-all shadow-lg shadow-purple-200 active:scale-95 text-sm font-medium"
@click="openBatchPermissionModal"
>
<Users class="w-4 h-4" />
<span>{{ t('admin.user.batchPermission') }} ({{ selectedUserIds.length }})</span>
</button>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateUserModal"
>
<Plus class="w-4 h-4" />
<span class="font-medium">{{ t('admin.user.addUser') }}</span>
</button>
</div>
</div>
<div class="admin-table-filters grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5">
<input v-model="userFilters.username" :placeholder="t('admin.user.filterUsername')" class="admin-table-filter-input" />
<input v-model="userFilters.email" :placeholder="t('admin.user.filterEmail')" class="admin-table-filter-input" />
<select v-model="userFilters.department" class="admin-table-filter-input">
<option value="">{{ t('admin.user.allDepts') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
<input v-model="userFilters.role" :placeholder="t('admin.user.filterRole')" class="admin-table-filter-input" />
<div class="flex items-center gap-2">
<input id="hideRejectedUsers" v-model="hideRejected" type="checkbox" class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 border-default" />
<label for="hideRejectedUsers" class="text-sm text-secondary select-none">{{ t('admin.user.hideRejected') }}</label>
</div>
</div>
<div class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 w-12 text-center">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 cursor-pointer border-default"
:checked="selectedUserIds.length === filteredUsers.length && filteredUsers.length > 0"
@change="toggleAllUsers(filteredUsers)"
/>
</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.user') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.role') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.dept') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs">{{ t('admin.user.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="filteredUsers.length === 0">
<td colspan="6" class="px-6 admin-table-empty">{{ t('admin.user.noUsers') }}</td>
</tr>
<tr v-for="user in filteredUsers" :key="user.id" class="group">
<td class="px-6 py-4 text-center">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 cursor-pointer border-default"
:checked="selectedUserIds.includes(user.id)"
@change="toggleUserSelection(user.id)"
/>
</td>
<td class="px-6 py-4">
<div class="flex items-center">
<div class="h-9 w-9 rounded-full bg-gradient-to-br from-brand-500 to-indigo-600 text-white flex items-center justify-center text-xs font-bold shadow-sm">
{{ user.username.charAt(0).toUpperCase() }}
</div>
<div class="ml-3">
<div class="text-sm font-medium text-primary">{{ user.username }}</div>
<div class="text-xs text-muted">{{ user.email }}</div>
</div>
</div>
</td>
<td class="px-6 py-4">
<span
class="px-2.5 py-0.5 rounded-full text-xs font-medium border"
:class="user.role === 'admin' ? 'bg-purple-50 text-purple-700 border-purple-100' : 'bg-blue-50 text-blue-700 border-blue-100'"
>
{{ t('admin.role.' + user.role) }}
</span>
</td>
<td class="px-6 py-4 text-sm text-muted">{{ user.department || '-' }}</td>
<td class="px-6 py-4">
<span
class="px-2.5 py-0.5 rounded-full text-xs font-medium border"
:class="{
'bg-green-50 text-green-700 border-green-100': user.status === 'active',
'bg-yellow-50 text-yellow-700 border-yellow-100': user.status === 'pending',
'bg-red-50 text-red-700 border-red-100': user.status === 'disabled' || user.status === 'rejected',
}"
>
{{ t('admin.status.' + user.status) }}
</span>
</td>
<td class="px-6 py-4 text-right">
<button
type="button"
class="text-brand-600 hover:text-brand-900 font-medium text-xs px-3 py-1.5 rounded-lg hover:bg-brand-50 transition-colors"
@click="openEditUserModal(user)"
>
{{ t('admin.edit') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<UserFormModal
:visible="showUserModal"
:form="editingUser"
:agents="agents"
:departments="departments"
:is-saving="isSaving"
@close="showUserModal = false"
@save="saveUser"
/>
<BatchEditUserModal
:visible="showBatchEditModal"
:form="batchEditForm"
:departments="departments"
:selected-count="selectedUserIds.length"
:is-saving="isSaving"
@close="showBatchEditModal = false"
@save="submitBatchEdit"
/>
<BatchPermissionModal
:visible="showBatchPermissionModal"
:form="batchPermissionForm"
:agents="agents"
:selected-count="selectedUserIds.length"
:is-saving="isSaving"
@close="showBatchPermissionModal = false"
@save="submitBatchPermission"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="confirmDelete"
@cancel="closeDeleteConfirm"
/>
</section>
</template>
@@ -0,0 +1,62 @@
/**
* features/admin/modules/users/components/BatchEditUserModal.vue
* 批量编辑用户部门/角色/状态弹窗。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
import type { BatchEditForm } from '@/features/admin/types/user.types';
defineProps<{
visible: boolean;
form: BatchEditForm;
departments: AdminDepartmentRow[];
selectedCount: number;
isSaving: boolean;
}>();
const emit = defineEmits<{ close: []; save: [] }>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-md animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle">
<h3 class="text-lg font-bold text-primary">{{ t('admin.batchEdit.title') }}</h3>
<p class="text-sm text-muted">{{ t('admin.batchEdit.selected', { count: selectedCount }) }}</p>
</div>
<div class="p-8 space-y-4">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.batchEdit.fields.dept') }}</label>
<select v-model="form.department" class="input-field text-sm">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.batchEdit.fields.role') }}</label>
<select v-model="form.role" class="input-field text-sm">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option value="user">{{ t('admin.role.user') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.batchEdit.fields.status') }}</label>
<select v-model="form.status" class="input-field text-sm">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option value="active">{{ t('admin.status.active') }}</option>
<option value="disabled">{{ t('admin.status.disabled') }}</option>
</select>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-50" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.batchEdit.update') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,70 @@
/**
* features/admin/modules/users/components/BatchPermissionModal.vue
* 批量分配/移除用户 Agent 权限弹窗。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { AdminAgentOption } from '@/features/admin/types/admin.types';
import type { BatchPermissionForm } from '@/features/admin/types/user.types';
defineProps<{
visible: boolean;
form: BatchPermissionForm;
agents: AdminAgentOption[];
selectedCount: number;
isSaving: boolean;
}>();
const emit = defineEmits<{ close: []; save: [] }>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-lg animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle">
<h3 class="text-lg font-bold text-primary">{{ t('admin.perm.batchModal.title') }}</h3>
<p class="text-sm text-muted">{{ t('admin.perm.batchModal.selected', { count: selectedCount }) }}</p>
</div>
<div class="p-8 space-y-6">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.perm.batchModal.action') }}</label>
<div class="flex gap-4">
<label class="flex items-center gap-2 cursor-pointer">
<input v-model="form.action" type="radio" value="add" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.add') }}</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input v-model="form.action" type="radio" value="remove" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.remove') }}</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input v-model="form.action" type="radio" value="set" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.set') }}</span>
</label>
</div>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.perm.batchModal.selectAgents') }}</label>
<div class="grid grid-cols-2 gap-3 max-h-60 overflow-y-auto p-1">
<label
v-for="agent in agents"
:key="agent.id"
class="flex items-center gap-2 p-3 border border-default rounded-lg cursor-pointer hover-surface-soft transition-colors"
:class="form.agent_ids.includes(agent.id) ? 'border-blue-500 bg-blue-50' : ''"
>
<input v-model="form.agent_ids" type="checkbox" :value="agent.id" class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500" />
<span class="text-sm font-medium text-secondary">{{ agent.name }}</span>
</label>
</div>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-50" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.perm.batchModal.apply') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,109 @@
/**
* features/admin/modules/users/components/UserFormModal.vue
* 创建/编辑用户弹窗。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { AdminAgentOption, AdminDepartmentRow } from '@/features/admin/types/admin.types';
import type { UserFormState } from '@/features/admin/types/user.types';
defineProps<{
visible: boolean;
form: UserFormState;
agents: AdminAgentOption[];
departments: AdminDepartmentRow[];
isSaving: boolean;
}>();
const emit = defineEmits<{
close: [];
save: [];
'update:form': [UserFormState];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in">
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">{{ form.id ? t('admin.user.editUser') : t('admin.user.createUser') }}</h3>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.realName') }}
</label>
<input v-model="form.real_name" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.employeeId') }}
</label>
<input v-model="form.employee_id" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.phone') }}
</label>
<input v-model="form.phone_number" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div class="space-y-1.5 col-span-1 md:col-span-2">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.allowedAgents') }}</label>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-2">
<label
v-for="agent in agents"
:key="agent.id"
class="flex items-center gap-2 p-3 border border-default rounded-lg cursor-pointer hover-surface-soft transition-colors"
:class="form.agent_ids.includes(agent.id) ? 'border-blue-500 bg-blue-50' : ''"
>
<input v-model="form.agent_ids" type="checkbox" :value="agent.id" class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500" />
<span class="text-sm font-medium text-secondary">{{ agent.name }}</span>
</label>
</div>
<p v-if="agents.length === 0" class="text-sm text-muted italic">{{ t('admin.user.fields.noAgents') }}</p>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.username') }}
</label>
<input v-model="form.username" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" :disabled="!!form.id" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.email') }}
</label>
<input v-model="form.email" type="email" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.department') }}</label>
<select v-model="form.department" class="w-full border-default rounded-xl px-4 py-3 text-sm">
<option value="">{{ t('admin.user.allDepts') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.role') }}</label>
<select v-model="form.role" class="w-full border-default rounded-xl px-4 py-3 text-sm">
<option value="user">{{ t('admin.role.user') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.password') }}
<span v-if="form.id" class="text-muted font-normal lowercase">{{ t('admin.user.fields.passwordHint') }}</span>
</label>
<input v-model="form.password" type="password" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.save') }}
</button>
</div>
</div>
</div>
</template>
@@ -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<AdminUserRow[]>([]);
const agents = ref<AdminAgentOption[]>([]);
const departments = ref<AdminDepartmentRow[]>([]);
const isLoading = ref(true);
const isSaving = ref(false);
const userFilters = ref<UserFilters>(createEmptyUserFilters());
const hideRejected = ref(true);
const selectedUserIds = ref<number[]>([]);
const showUserModal = ref(false);
const editingUser = ref<UserFormState>(createEmptyUserForm());
const showBatchEditModal = ref(false);
const batchEditForm = ref<BatchEditForm>({ department: '', role: '', status: '' });
const showBatchPermissionModal = ref(false);
const batchPermissionForm = ref<BatchPermissionForm>({ agent_ids: [], action: 'add' });
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | 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<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const loadAgents = async (): Promise<void> => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Error loading agents:', e);
agents.value = [];
}
};
const loadDepartments = async (): Promise<void> => {
try {
departments.value = await listAdminDepartments();
} catch (e) {
console.error('Error loading departments:', e);
departments.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([loadUsers(), loadAgents(), loadDepartments()]);
isLoading.value = false;
};
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
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<void> => {
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<void> => {
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<void> => {
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<void> => {
isSaving.value = true;
try {
const data: Record<string, string> = {};
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<void> => {
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,
};
}
@@ -0,0 +1,456 @@
/**
* features/admin/modules/wecom/WecomPage.vue
* 企业微信管理独立页面。路由:/admin/wecom
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { CircleHelp, Download, Link2, RefreshCw, Unlink2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useWecomAdmin } from './composables/useWecomAdmin';
const { t } = useI18n();
const {
isLoading,
isSaving,
wecomBindings,
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,
} = useWecomAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<section v-else class="section-gap animate-fade-in-up">
<div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
<div>
<h2 class="section-title">{{ t('admin.wecom.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.wecom.subtitle') }}</p>
</div>
<button
@click="refreshWecomData"
class="btn-secondary inline-flex items-center gap-2 px-4 py-2 text-secondary rounded-xl hover-surface-soft transition-all shadow-sm"
>
<RefreshCw class="w-4 h-4" />
{{ t('admin.wecom.refresh') }}
</button>
</div>
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.quickBind') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-4 gap-3">
<div class="relative md:col-span-1">
<input
v-model="wecomBindUserQuery"
type="text"
class="input-field"
:placeholder="t('admin.wecom.fields.userSelect')"
@focus="wecomBindUserDropdownOpen = true"
@input="wecomBindUserDropdownOpen = true"
@blur="scheduleCloseWecomBindUserDropdown"
/>
<div
v-if="wecomBindUserDropdownOpen"
class="admin-dropdown w-72"
>
<button
v-for="u in wecomBindUserOptions"
:key="u.id"
type="button"
class="flex w-full items-center justify-between gap-3 px-3 py-2 text-left hover:bg-blue-50"
@mousedown.prevent="selectWecomBindUser(u.id, u.label)"
>
<span class="text-sm text-primary">{{ u.label }}</span>
<span class="text-xs text-muted">{{ u.employeeId || '' }}</span>
</button>
<div v-if="wecomBindUserOptions.length === 0" class="px-3 py-2 text-sm text-muted">
{{ t('admin.wecom.noData') }}
</div>
</div>
</div>
<input v-model="wecomBindForm.wecom_userid" :placeholder="t('admin.wecom.fields.wecomUserId')" class="input-field md:col-span-2" />
<input v-model="wecomBindForm.wecom_unionid" :placeholder="t('admin.wecom.fields.wecomUnionId')" class="input-field" />
</div>
<div class="flex justify-end">
<button @click="bindWecomUser" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60">
<Link2 class="w-4 h-4" /> {{ t('admin.wecom.bind') }}
</button>
</div>
</div>
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.systemSettings') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<label class="inline-flex items-center gap-2 text-sm text-secondary">
<input v-model="wecomSystemSettings.enabled" type="checkbox" class="admin-checkbox" />
{{ t('admin.wecom.fields.enabled') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.enabled')" />
</label>
<label class="inline-flex items-center gap-2 text-sm text-secondary">
<input v-model="wecomSystemSettings.auto_create_user" type="checkbox" class="admin-checkbox" />
{{ t('admin.wecom.fields.autoCreateUser') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.autoCreateUser')" />
</label>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.corpId') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.corpId')" />
</label>
<input v-model="wecomSystemSettings.corp_id" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.agentId') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.agentId')" />
</label>
<input v-model="wecomSystemSettings.agent_id" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.secret') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.secret')" />
</label>
<input v-model="wecomSystemSettings.secret" type="password" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.redirectUri') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.redirectUri')" />
</label>
<input v-model="wecomSystemSettings.redirect_uri" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.publicBaseUrl') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.publicBaseUrl')" />
</label>
<div class="flex flex-wrap gap-2">
<input
v-model="wecomSystemSettings.public_base_url"
:placeholder="t('admin.wecom.publicBasePlaceholder')"
class="input-field flex-1 min-w-[200px]"
/>
<button type="button" class="btn-secondary px-4 shrink-0" @click="generateWecomAddressesFromPublicBase">
{{ t('admin.wecom.generateAddresses') }}
</button>
</div>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.callbackToken') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.callbackToken')" />
</label>
<div class="flex gap-2">
<input v-model="wecomSystemSettings.callback_token" class="input-field flex-1 min-w-0" />
<button type="button" class="btn-secondary px-3 shrink-0 text-xs" @click="generateWecomCallbackToken">
{{ t('admin.wecom.generateToken') }}
</button>
</div>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.encodingAesKey') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.encodingAesKey')" />
</label>
<div class="flex gap-2">
<input v-model="wecomSystemSettings.encoding_aes_key" class="input-field flex-1 min-w-0 font-mono text-xs" />
<button type="button" class="btn-secondary px-3 shrink-0 text-xs" @click="generateWecomEncodingAesKey">
{{ t('admin.wecom.generateEncodingKey') }}
</button>
</div>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.callbackUrl') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.callbackUrl')" />
</label>
<input v-model="wecomSystemSettings.callback_url" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.homepageUrl') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.homepageUrl')" />
</label>
<input v-model="wecomSystemSettings.homepage_url" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.trustedDomain') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.trustedDomain')" />
</label>
<input v-model="wecomSystemSettings.trusted_domain" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.matchRules') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.matchRules')" />
</label>
<input v-model="wecomSystemSettings.match_rules" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.matchOperator') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.matchOperator')" />
</label>
<select v-model="wecomSystemSettings.match_operator" class="input-field">
<option value="AND">AND</option>
<option value="OR">OR</option>
</select>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.firstLoginBindMode') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.firstLoginBindMode')" />
</label>
<select v-model="wecomSystemSettings.first_login_bind_mode" class="input-field">
<option value="match_rules">{{ t('admin.wecom.bindModes.match_rules') }}</option>
<option value="input_verify">{{ t('admin.wecom.bindModes.input_verify') }}</option>
</select>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.firstLoginInputFields') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.firstLoginInputFields')" />
</label>
<input v-model="wecomSystemSettings.first_login_input_fields" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.employeeIdSource') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.employeeIdSource')" />
</label>
<input v-model="wecomSystemSettings.employee_id_source" class="input-field" />
</div>
<label class="inline-flex items-center gap-2 text-sm text-secondary pt-7">
<input v-model="wecomSystemSettings.mobile_normalize" type="checkbox" class="admin-checkbox" />
{{ t('admin.wecom.fields.mobileNormalize') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.mobileNormalize')" />
</label>
</div>
<div class="flex justify-end">
<button @click="saveWecomSystemSettings" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60">
{{ t('admin.save') }}
</button>
</div>
</div>
<div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.notifySettings') }}</h3>
<label class="inline-flex items-center gap-2 text-sm text-secondary">
<input v-model="wecomNotifySettings.enabled" type="checkbox" class="admin-checkbox" />
{{ t('admin.wecom.notifyEnabled') }}
</label>
<input v-model="wecomNotifySettings.base_url" :placeholder="t('admin.wecom.notifyBaseUrl')" class="input-field" />
<input v-model="wecomNotifyEventsText" :placeholder="t('admin.wecom.notifyEvents')" class="input-field" />
<div class="flex justify-end">
<button @click="saveWecomNotifySettings" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60">
{{ t('admin.save') }}
</button>
</div>
</div>
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.notifyMetrics') }}</h3>
<div v-if="wecomNotifyMetrics" class="grid grid-cols-2 gap-3 text-sm">
<div class="rounded-lg bg-surface-soft px-3 py-2">
<div class="text-muted">{{ t('admin.wecom.metricTotal') }}</div>
<div class="text-lg font-semibold text-primary">{{ wecomNotifyMetrics.total }}</div>
</div>
<div class="rounded-lg bg-surface-soft px-3 py-2">
<div class="text-muted">{{ t('admin.wecom.metricSuccessRate') }}</div>
<div class="text-lg font-semibold text-emerald-700">{{ wecomNotifyMetrics.send_success_rate }}%</div>
</div>
<div class="rounded-lg bg-surface-soft px-3 py-2">
<div class="text-muted">{{ t('admin.wecom.metricOpenedRate') }}</div>
<div class="text-lg font-semibold text-blue-700">{{ wecomNotifyMetrics.opened_24h_rate }}%</div>
</div>
<div class="rounded-lg bg-surface-soft px-3 py-2">
<div class="text-muted">{{ t('admin.wecom.metricWindowDays') }}</div>
<div class="text-lg font-semibold text-primary">{{ wecomNotifyMetrics.window_days }}</div>
</div>
</div>
</div>
</div>
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.integrationCopyTitle') }}</h3>
<p class="text-xs text-muted">{{ t('admin.wecom.integrationCopyDesc') }}</p>
<p class="text-xs text-amber-800 bg-amber-50 border border-amber-100 rounded-lg px-3 py-2">{{ t('admin.wecom.integrationCopySecretsNote') }}</p>
<div v-if="wecomIntegrationManifest" class="grid grid-cols-1 gap-3">
<div v-for="item in [
{ key: 'public_base_url', label: t('admin.wecom.copyFields.publicBaseUrl') },
{ key: 'callback_url', label: t('admin.wecom.copyFields.callbackUrl') },
{ key: 'callback_token', label: t('admin.wecom.copyFields.callbackToken') },
{ key: 'encoding_aes_key', label: t('admin.wecom.copyFields.encodingAesKey') },
{ key: 'oauth_redirect_uri', label: t('admin.wecom.copyFields.oauthRedirectUri') },
{ key: 'homepage_url', label: t('admin.wecom.copyFields.homepageUrl') },
{ key: 'trusted_domain', label: t('admin.wecom.copyFields.trustedDomain') },
{ key: 'authorize_api', label: t('admin.wecom.copyFields.authorizeApi') },
{ key: 'login_api', label: t('admin.wecom.copyFields.loginApi') },
]" :key="item.key">
<label class="mb-1.5 block text-xs text-muted">{{ item.label }}</label>
<div class="flex gap-2">
<input :value="(wecomIntegrationManifest as any)[item.key] || ''" readonly class="input-field flex-1 bg-surface-soft font-mono text-xs" />
<button class="btn-secondary px-3" @click="copyText(String((wecomIntegrationManifest as any)[item.key] || ''))">{{ t('admin.wecom.copy') }}</button>
</div>
</div>
</div>
</div>
<div class="admin-table-section">
<div class="admin-table-header px-5 py-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.bindingList') }}</h3>
<label class="inline-flex items-center gap-2 text-sm text-secondary">
<input type="checkbox" v-model="wecomBoundOnly" class="w-4 h-4 rounded text-brand-600 border-default" />
{{ t('admin.wecom.boundOnly') }}
</label>
</div>
<div class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.user') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.roleStatus') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.wecomUserId') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.unionId') }}</th>
<th class="px-4 py-3 text-xs text-right">{{ t('admin.wecom.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="wecomBindings.length === 0">
<td colspan="5" class="px-4 admin-table-empty">{{ t('admin.wecom.noData') }}</td>
</tr>
<tr v-for="u in wecomBindings" :key="u.id">
<td class="px-4 py-3">
<div class="text-sm font-medium text-primary">{{ u.username }} <span class="text-muted">(#{{ u.id }})</span></div>
<div class="text-xs text-muted">{{ u.real_name || '-' }} · {{ u.email }}</div>
</td>
<td class="px-4 py-3 text-sm text-secondary">{{ t('admin.role.' + u.role) }} / {{ t('admin.status.' + u.status) }}</td>
<td class="px-4 py-3 text-sm text-secondary font-mono">{{ u.wecom_userid || '-' }}</td>
<td class="px-4 py-3 text-sm text-secondary font-mono">{{ u.wecom_unionid || '-' }}</td>
<td class="px-4 py-3 text-right">
<button
v-if="u.wecom_userid"
@click="unbindWecomUserByAdmin(u.id)"
class="inline-flex items-center gap-1 px-3 py-1.5 text-xs text-red-600 bg-red-50 rounded-lg hover:bg-red-100"
>
<Unlink2 class="w-3.5 h-3.5" />
{{ t('admin.wecom.unbind') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="admin-table-section">
<div class="admin-table-header admin-table-header--stacked px-5 py-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.auditTitle') }}</h3>
<div class="flex w-full md:w-auto flex-wrap md:flex-nowrap items-center justify-start md:justify-end gap-2">
<select v-model="wecomAuditSourceFilter" class="admin-table-filter-input h-11 min-w-[112px] shrink-0">
<option value="all">{{ t('admin.wecom.filters.allSources') }}</option>
<option value="wecom">{{ t('admin.wecom.sources.wecom') }}</option>
<option value="password">{{ t('admin.wecom.sources.password') }}</option>
</select>
<select v-model="wecomAuditStatusFilter" class="admin-table-filter-input h-11 min-w-[112px] shrink-0">
<option value="all">{{ t('admin.wecom.filters.allStatus') }}</option>
<option value="success">{{ t('admin.wecom.auditStatus.success') }}</option>
<option value="failed">{{ t('admin.wecom.auditStatus.failed') }}</option>
</select>
<button
@click="exportWecomAudits"
class="btn-secondary h-11 shrink-0 text-sm"
>
<Download class="w-4 h-4" />
{{ t('admin.wecom.exportAudit') }}
</button>
</div>
</div>
<div class="admin-table-wrap max-h-[420px]">
<table class="admin-table">
<thead class="sticky top-0 z-10 admin-table-sticky-head">
<tr>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.time') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.source') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.user') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.status') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.reason') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.ip') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="filteredWecomLoginAudits.length === 0">
<td colspan="6" class="px-4 admin-table-empty">{{ t('admin.wecom.noAuditData') }}</td>
</tr>
<tr v-for="row in filteredWecomLoginAudits" :key="row.id">
<td class="px-4 py-3 text-xs text-muted whitespace-nowrap">{{ row.created_at || '-' }}</td>
<td class="px-4 py-3 text-xs text-secondary">{{ t('admin.wecom.sources.' + row.source) }}</td>
<td class="px-4 py-3 text-xs text-secondary">{{ row.username || '-' }}</td>
<td class="px-4 py-3">
<span class="inline-flex px-2 py-0.5 rounded-full text-[11px] font-medium" :class="row.status === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'">
{{ t('admin.wecom.auditStatus.' + row.status) }}
</span>
</td>
<td class="px-4 py-3 text-xs text-muted max-w-[360px] align-top">
<div class="max-w-[360px] whitespace-normal break-words">
<div class="text-xs text-secondary leading-5">{{ getWecomAuditReasonText(row) }}</div>
<div v-if="getWecomAuditMetaText(row)" class="mt-1 text-[11px] text-muted leading-5" :title="getWecomAuditMetaText(row)">
{{ getWecomAuditMetaText(row) }}
</div>
</div>
</td>
<td class="px-4 py-3 text-xs text-muted font-mono">{{ row.ip || '-' }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="confirmDelete"
/>
</template>
@@ -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<AdminUserRow[]>([]);
const isLoading = ref(true);
const isSaving = ref(false);
const wecomBindings = ref<WecomBindingRow[]>([]);
const wecomLoginAudits = ref<WecomLoginAuditRow[]>([]);
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<typeof setTimeout> | null = null;
const wecomAuditSourceFilter = ref<'all' | 'wecom' | 'password'>('all');
const wecomAuditStatusFilter = ref<'all' | 'success' | 'failed'>('all');
const filteredWecomLoginAudits = computed(() => wecomLoginAudits.value);
const wecomNotifySettings = ref<WecomNotifySettings>({
enabled: true,
base_url: '',
events: [],
});
const wecomNotifyEventsText = ref('');
const wecomNotifyMetrics = ref<WecomNotifyMetrics | null>(null);
const wecomSystemSettings = ref<WecomSystemSettings>(createDefaultWecomSystemSettings());
const wecomIntegrationManifest = ref<WecomIntegrationManifest | null>(null);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | 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): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const loadWecomBindings = async (): Promise<void> => {
try {
wecomBindings.value = await listAdminWecomBindings(wecomBoundOnly.value);
} catch (e) {
console.error('Error loading WeCom bindings:', e);
}
};
const loadWecomAudits = async (): Promise<void> => {
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<void> => {
try {
wecomSystemSettings.value = await getAdminWecomSystemSettings();
} catch (e) {
console.error('Error loading WeCom system settings:', e);
}
};
const loadWecomIntegrationManifest = async (): Promise<void> => {
try {
wecomIntegrationManifest.value = await getAdminWecomIntegrationManifest();
} catch (e) {
console.error('Error loading WeCom integration manifest:', e);
}
};
const loadWecomNotifySettings = async (): Promise<void> => {
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<void> => {
try {
wecomNotifyMetrics.value = await getAdminWecomNotifyMetrics();
} catch (e) {
console.error('Error loading WeCom notify metrics:', e);
}
};
const refreshWecomData = async (): Promise<void> => {
await Promise.all([
loadWecomBindings(),
loadWecomAudits(),
loadWecomSystemSettings(),
loadWecomIntegrationManifest(),
loadWecomNotifySettings(),
loadWecomNotifyMetrics(),
]);
};
const loadAll = async (): Promise<void> => {
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<void> => {
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<void> => {
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<void> => {
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<void> => {
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<void> => {
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,
};
}