Files
syops/frontend/src/views/AdminView.vue
T
2026-05-30 17:06:32 +08:00

6292 lines
279 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
/**
* AdminView.vue
* 文件用途:管理员控制台,用于配置 Dify Agent 与用户权限
* 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/admin 接口
* 逻辑关系:
* - 通过 /api/admin/agents 管理 Agent 配置
* - 通过 /api/admin/users 与 /permissions 管理用户可访问的 Agent
* - 该页面后续可继续优化按模块懒加载数据
*/
import { ref, onMounted, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import KbAdminPanel from '../components/kb/KbAdminPanel.vue';
import { useI18n } from 'vue-i18n';
import { config } from '../config';
import AppHeaderTools from '../layouts/AppHeaderTools.vue';
import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
import { loadReportLayoutPref, saveReportLayoutPref } from '../composables/useReportLayoutStorage';
import { useMessage } from '../composables/useMessage';
import { buildWecomAuditMeta, formatWecomAuditReason } from '../utils/wecom';
import { getAuthHeaders } from '../utils/auth';
import { listAdminSchedules, createAdminSchedule, updateAdminSchedule, deleteAdminSchedule, toggleAdminSchedule, runAdminSchedule, listAdminScheduleRuns, getAdminScheduleTaskConfig, testAdminScheduleSql, testAdminScheduleRun, type ScheduleTask, type ScheduleRun, type TestScheduleRunResult } from '../api/schedule';
import {
listAdminUsers,
createAdminUser,
updateAdminUser,
approveAdminUser,
rejectAdminUser,
cleanupRejectedAdminUsers,
batchDeleteAdminUsers,
batchUpdateAdminUsers,
updateAdminUserPermissions,
listAdminDepartments,
createAdminDepartment,
updateAdminDepartment,
deleteAdminDepartment,
listAdminAgents,
createAdminAgent,
updateAdminAgent,
deleteAdminAgent,
testAdminAgent,
saveAdminAgentPermissions,
listAdminPermissionRequests,
approveAdminPermissionRequest,
rejectAdminPermissionRequest,
batchUpdateAdminPermissions,
importAdminPermissions,
getAdminUsageReport,
getAdminFeedbackReport,
getAdminReportTable,
getAdminReportTableCount,
batchDeleteAdminChatLogs,
listAdminWecomBindings,
listAdminWecomLoginAudits,
getAdminWecomSystemSettings,
getAdminWecomIntegrationManifest,
saveAdminWecomSystemSettings,
getAdminWecomNotifySettings,
saveAdminWecomNotifySettings,
getAdminWecomNotifyMetrics,
bindAdminWecomUser,
unbindAdminWecomUser,
listAnnouncements,
createAnnouncement,
deleteAnnouncement,
listAdminQuickQuestions,
saveAdminQuickQuestion,
deleteAdminQuickQuestion,
} from '../api/admin';
import {
ArrowLeft,
// Save,
Plus,
Trash2,
UserPlus,
Edit,
ShieldCheck,
LayoutDashboard,
Bot,
Users,
FileText,
BarChart2,
MessageSquare,
Download,
UserCog,
Building,
MessageCircleQuestion,
Settings2,
Megaphone,
Link2,
Unlink2,
RefreshCw,
CircleHelp,
Eye,
ChevronDown,
ChevronUp,
Edit3,
Power,
PowerOff,
Rocket,
FlaskConical
} from 'lucide-vue-next';
import * as XLSX from 'xlsx';
const { t, locale } = useI18n();
const msg = useMessage();
const EMAIL_PATTERN = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/;
const sidebarItems = computed(() => {
const items = [
{ id: 'dashboard', icon: LayoutDashboard, label: t('admin.nav.dashboard') },
{ id: 'approvals', icon: UserPlus, label: t('admin.nav.approvals'), badge: pendingUsers.value.length },
{ id: 'users', icon: UserCog, label: t('admin.nav.users') },
{ id: 'departments', icon: Building, label: t('admin.nav.departments') },
{ id: 'agents', icon: Bot, label: t('admin.nav.agents') },
{ id: 'knowledge_base', icon: FileText, label: t('admin.nav.knowledgeBase') },
{ id: 'schedules', icon: Settings2, label: t('admin.nav.schedules') },
{ id: 'announcements', icon: Megaphone, label: t('admin.nav.announcements') },
{ id: 'questions', icon: MessageCircleQuestion, label: t('admin.nav.questions') },
{ id: 'wecom', icon: Link2, label: t('admin.nav.wecom') },
{ id: 'permissions', icon: Users, label: t('admin.nav.permissions') },
{ id: 'requests', icon: ShieldCheck, label: t('admin.nav.requests'), badge: permissionRequests.value.filter(r => r.status === 'pending').length },
];
return items.filter(item => {
if (config.admin.modules[item.id as keyof typeof config.admin.modules] === false) {
return false;
}
return true;
});
});
onMounted(() => {
const allowed = sidebarItems.value.map(i => i.id);
if (!allowed.includes(activeModule.value)) {
activeModule.value = (allowed[0] ?? 'agents') as any;
}
});
// 获取路由实例,用于页面跳转
interface AgentRow {
id: number;
name: string;
dify_app_id: string;
dify_api_key: string;
is_active: boolean;
description?: string;
type: 'api' | 'iframe';
dify_app_type?: 'chatflow' | 'workflow';
api_base_url?: string;
extra_config?: Record<string, any>;
iframe_url?: string; // Frontend helper property
}
interface AgentTestResult {
success: boolean;
request_url: string;
output_info: string;
analysis: string;
http_status?: number;
tested_at?: string;
}
// 定义 User 行的数据结构
interface UserRow {
id: number;
username: string;
email: string;
department?: string;
role: string;
status: string;
real_name?: string;
employee_id?: string;
phone_number?: string;
agent_ids: number[];
}
interface PermissionRequestRow {
id: number;
user_id: number;
agent_id: number;
reason: string;
status: string;
created_at: string;
reviewed_at?: string | null;
}
interface UsageReport {
total: number;
by_user: { username: string; count: number }[];
by_agent: { agent: string; count: number }[];
by_day: { date: string; count: number }[];
}
interface FeedbackReportSummary {
total: number;
avg_score: number;
distribution: { score: number; count: number }[];
}
interface WecomBindingRow {
id: number;
username: string;
real_name?: string;
email: string;
role: string;
status: string;
wecom_userid?: string | null;
wecom_unionid?: string | null;
bound: boolean;
}
interface LoginAuditRow {
id: number;
user_id?: number | null;
username?: string | null;
source: string;
status: string;
reason?: string | null;
wecom_userid?: string | null;
ip?: string | null;
user_agent?: string | null;
created_at?: string | null;
error_code?: string | null;
match_rules?: string | null;
match_operator?: string | null;
match_result?: string | null;
}
interface WecomNotifySettings {
enabled: boolean;
base_url: string;
events: string[];
}
interface WecomNotifyMetrics {
window_days: number;
total: number;
sent: number;
failed: number;
send_success_rate: number;
opened_24h: number;
opened_24h_rate: number;
by_event: Record<string, { sent: number; failed: number }>;
}
interface WecomSystemSettings {
enabled: boolean;
corp_id: string;
agent_id: string;
secret: string;
redirect_uri: string;
auto_create_user: boolean;
match_rules: string;
match_operator: 'AND' | 'OR';
first_login_bind_mode: 'match_rules' | 'input_verify';
first_login_input_fields: string;
employee_id_source: string;
mobile_normalize: boolean;
callback_token: string;
encoding_aes_key: string;
callback_url: string;
homepage_url: string;
trusted_domain: string;
/** HTTPS origin shown to WeCom (e.g. https://ai.company.com) */
public_base_url: string;
}
interface WecomIntegrationManifest {
public_base_url: string;
callback_url: string;
callback_token: string;
encoding_aes_key: string;
oauth_redirect_uri: string;
homepage_url: string;
trusted_domain: string;
authorize_api: string;
login_api: string;
}
// 获取路由实例,用于页面跳转
const router = useRouter();
const route = useRoute();
// 当前左侧菜单激活的模块:dashboard / agents / permissions
const activeModule = ref<'dashboard' | 'agents' | 'announcements' | 'permissions' | 'requests' | 'reports' | 'approvals' | 'users' | 'departments' | 'questions' | 'wecom' | 'schedules' | 'knowledge_base'>('dashboard');
const expandedReports = ref(true);
// agents:管理员视角下的所有 Agent 列表
const agents = ref<AgentRow[]>([]);
// users:系统中的用户列表及其权限
const users = ref<UserRow[]>([]);
// isSaving:标记保存操作是否进行中
const isSaving = ref(false);
const isLoading = ref(true);
const showUserModal = ref(false);
const newAgent = ref<Partial<AgentRow>>({
name: '',
dify_app_id: '',
dify_api_key: '',
description: '',
type: 'api',
dify_app_type: 'chatflow',
api_base_url: '',
iframe_url: '',
is_active: true
});
const editingUser = ref<{
id: number | null;
username: string;
email: string;
department?: string;
role: string;
password?: string;
real_name?: string;
employee_id?: string;
phone_number?: string;
agent_ids: number[];
}>({
id: null,
username: '',
email: '',
department: '',
role: 'user',
password: '',
real_name: '',
employee_id: '',
phone_number: '',
agent_ids: []
});
const openCreateUserModal = () => {
editingUser.value = {
id: null,
username: '',
email: '',
department: '',
role: 'user',
password: '',
real_name: '',
employee_id: '',
phone_number: '',
agent_ids: []
};
showUserModal.value = true;
};
const openEditUserModal = (user: UserRow) => {
editingUser.value = {
id: user.id,
username: user.username,
email: user.email,
department: user.department || '',
role: user.role,
password: '', // Keep empty unless user updates 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 () => {
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;
}
if (!editingUser.value.id && !editingUser.value.password) {
msg.warning(t('admin.user.msgs.passwordRequired'));
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 permissionRequests = ref<PermissionRequestRow[]>([]);
const usageReport = ref<UsageReport | null>(null);
const feedbackReportSummary = ref<FeedbackReportSummary | null>(null);
const wecomBindings = ref<WecomBindingRow[]>([]);
const wecomLoginAudits = ref<LoginAuditRow[]>([]);
const wecomBindForm = ref({
user_id: '' as string | number,
wecom_userid: '',
wecom_unionid: '',
});
const wecomBindUserQuery = ref('');
const wecomBindUserDropdownOpen = ref(false);
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 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>({
enabled: true,
corp_id: '',
agent_id: '',
secret: '',
redirect_uri: '',
auto_create_user: true,
match_rules: 'employee_id,mobile',
match_operator: 'AND',
first_login_bind_mode: 'match_rules',
first_login_input_fields: 'employee_id,mobile,email',
employee_id_source: 'userid',
mobile_normalize: true,
callback_token: '',
encoding_aes_key: '',
callback_url: '',
homepage_url: '',
trusted_domain: '',
public_base_url: '',
});
const wecomIntegrationManifest = ref<WecomIntegrationManifest | null>(null);
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) => {
openDeleteConfirmDialog(
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')
);
};
// Batch Operation Refs
const selectedUserIds = ref<number[]>([]);
const showBatchEditModal = ref(false);
const showBatchPermissionModal = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmTitle = ref('');
const deleteConfirmMessage = ref('');
const deleteConfirmLoading = ref(false);
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
const batchEditForm = ref({
department: '',
role: '',
status: '',
});
const batchPermissionForm = ref({
agent_ids: [] as number[],
action: 'add' as 'add' | 'remove' | 'set'
});
const openDeleteConfirmDialog = (
message: string,
onConfirm: () => Promise<void> | void,
title = ''
) => {
deleteConfirmTitle.value = title;
deleteConfirmMessage.value = message;
pendingDeleteAction = onConfirm;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirmDialog = () => {
showDeleteConfirmDialog.value = false;
deleteConfirmTitle.value = '';
deleteConfirmMessage.value = '';
pendingDeleteAction = null;
deleteConfirmLoading.value = false;
};
const handleDeleteConfirm = async () => {
if (!pendingDeleteAction) return;
deleteConfirmLoading.value = true;
try {
await pendingDeleteAction();
closeDeleteConfirmDialog();
} finally {
deleteConfirmLoading.value = false;
}
};
// Department Management
interface Department {
id: number;
name: string;
code?: string;
company?: string;
description?: string;
}
const departments = ref<Department[]>([]);
const editingDept = ref<Partial<Department>>({});
const isManagingDepts = ref(false);
const loadDepartments = async () => {
try {
departments.value = await listAdminDepartments();
} catch (e) {
console.error('Failed to load departments', e);
}
};
const saveDepartment = async () => {
if (!editingDept.value.name) return msg.warning(t('admin.dept.msg.nameRequired'));
try {
if (editingDept.value.id) {
await updateAdminDepartment(editingDept.value.id, editingDept.value as Record<string, unknown>);
} else {
await createAdminDepartment(editingDept.value as Record<string, unknown>);
}
await loadDepartments();
editingDept.value = {};
} catch (e) {
msg.error((e as Error).message);
}
};
const editDepartment = (dept: Department) => {
editingDept.value = { ...dept };
};
// Sidebar Toggle
const isSidebarCollapsed = ref(false);
const toggleSidebar = () => {
isSidebarCollapsed.value = !isSidebarCollapsed.value;
};
// Report Tabs
interface ReportTab {
id: string;
label: string;
type: string; // 'table' or 'chart'
table?: string;
filter?: Record<string, string>;
}
const reportTabs = ref<ReportTab[]>([]);
const activeReportTabId = ref<string | null>(null);
const openReportTab = (table: string) => {
const existingTab = reportTabs.value.find(t => t.table === table);
if (existingTab) {
activeReportTabId.value = existingTab.id;
} else {
const newTab: ReportTab = {
id: Date.now().toString(),
label: getReportTableLabel(table),
type: 'table',
table: table,
filter: {}
};
reportTabs.value.push(newTab);
activeReportTabId.value = newTab.id;
}
activeModule.value = 'reports';
currentTable.value = table;
};
watch(activeReportTabId, (newId) => {
if (newId) {
const tab = reportTabs.value.find(t => t.id === newId);
if (tab && tab.table) {
currentTable.value = tab.table;
columnFilters.value = tab.filter || {};
}
}
});
const deleteDepartment = async (id: number) => {
openDeleteConfirmDialog(t('admin.dept.confirmDelete'), async () => {
try {
await deleteAdminDepartment(id);
await loadDepartments();
} catch (e) {
console.error(e);
}
});
};
// User Filters & Actions
const userFilters = ref({
username: '',
email: '',
department: '',
role: '',
status: '',
real_name: '',
employee_id: '',
phone_number: ''
});
const hideRejected = ref(true);
const filteredUsers = computed(() => {
return users.value.filter(u => {
if (hideRejected.value && u.status === 'rejected') return false;
for (const key of Object.keys(userFilters.value)) {
const k = key as keyof typeof userFilters.value;
const filterVal = userFilters.value[k].toLowerCase();
if (!filterVal) continue;
const userVal = u[k]?.toString().toLowerCase() || '';
if (!userVal.includes(filterVal)) return false;
}
return true;
});
});
const cleanRejectedUsers = async () => {
openDeleteConfirmDialog(t('admin.user.confirmClean'), async () => {
try {
const data = await cleanupRejectedAdminUsers();
msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
loadUsers();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
const batchDeleteUsers = async () => {
if (selectedUserIds.value.length === 0) return;
const targetUserIds = [...selectedUserIds.value];
openDeleteConfirmDialog(
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 = [];
loadUsers();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
}
);
};
const toggleUserSelection = (userId: number) => {
const index = selectedUserIds.value.indexOf(userId);
if (index === -1) {
selectedUserIds.value.push(userId);
} else {
selectedUserIds.value.splice(index, 1);
}
};
const toggleAllUsers = (filteredUsers: UserRow[]) => {
if (selectedUserIds.value.length === filteredUsers.length) {
selectedUserIds.value = [];
} else {
selectedUserIds.value = filteredUsers.map(u => u.id);
}
};
const openBatchEditModal = () => {
if (selectedUserIds.value.length === 0) return;
batchEditForm.value = { department: '', role: '', status: '' };
showBatchEditModal.value = true;
};
const openBatchPermissionModal = () => {
if (selectedUserIds.value.length === 0) return;
batchPermissionForm.value = { agent_ids: [], action: 'add' };
showBatchPermissionModal.value = true;
};
const submitBatchEdit = async () => {
isSaving.value = true;
try {
const data: any = {};
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 () => {
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;
}
};
/**
* 加载 Agent 列表
* 核心逻辑:调用 GET /api/admin/agents
*/
const loadAgents = async () => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Error loading agents:', e);
agents.value = [];
}
};
/**
* 加载用户与权限列表
* 核心逻辑:调用 GET /api/admin/users
*/
const loadUsers = async () => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
}
};
const loadPermissionRequests = async () => {
try {
permissionRequests.value = await listAdminPermissionRequests();
} catch (e) {
console.error('Error loading permission requests:', e);
}
};
const approvePermissionRequest = async (id: number) => {
try {
await approveAdminPermissionRequest(id);
await loadPermissionRequests();
await loadUsers();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
}
};
const rejectPermissionRequest = async (id: number) => {
try {
await rejectAdminPermissionRequest(id);
await loadPermissionRequests();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
}
};
const loadReports = async () => {
try {
const [usage, feedback] = await Promise.all([
getAdminUsageReport(),
getAdminFeedbackReport(),
]);
usageReport.value = usage;
feedbackReportSummary.value = feedback;
} catch (e) {
console.error('Error loading reports:', e);
}
};
const loadWecomBindings = async () => {
try {
wecomBindings.value = await listAdminWecomBindings(wecomBoundOnly.value);
} catch (e) {
console.error('Error loading WeCom bindings:', e);
}
};
const selectWecomBindUser = (id: number, label: string) => {
wecomBindForm.value.user_id = id;
wecomBindUserQuery.value = label;
wecomBindUserDropdownOpen.value = false;
};
const scheduleCloseWecomBindUserDropdown = () => {
if (wecomBindUserCloseTimer) clearTimeout(wecomBindUserCloseTimer);
wecomBindUserCloseTimer = setTimeout(() => {
wecomBindUserDropdownOpen.value = false;
}, 150);
};
const loadWecomAudits = async () => {
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 () => {
try {
wecomSystemSettings.value = await getAdminWecomSystemSettings();
} catch (e) {
console.error('Error loading WeCom system settings:', e);
}
};
const loadWecomIntegrationManifest = async () => {
try {
wecomIntegrationManifest.value = await getAdminWecomIntegrationManifest();
} catch (e) {
console.error('Error loading WeCom integration manifest:', e);
}
};
const copyText = async (text: string) => {
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: LoginAuditRow) => formatWecomAuditReason(row, t);
const getWecomAuditMetaText = (row: LoginAuditRow) => 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() {
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() {
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() {
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() {
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() {
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 () => {
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 loadWecomNotifySettings = async () => {
try {
wecomNotifySettings.value = await getAdminWecomNotifySettings();
wecomNotifyEventsText.value = (wecomNotifySettings.value.events || []).join(',');
} catch (e) {
console.error('Error loading WeCom notify settings:', e);
}
};
const saveWecomNotifySettings = async () => {
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 loadWecomNotifyMetrics = async () => {
try {
wecomNotifyMetrics.value = await getAdminWecomNotifyMetrics();
} catch (e) {
console.error('Error loading WeCom notify metrics:', e);
}
};
const refreshWecomData = async () => {
await Promise.all([
loadWecomBindings(),
loadWecomAudits(),
loadWecomSystemSettings(),
loadWecomIntegrationManifest(),
loadWecomNotifySettings(),
loadWecomNotifyMetrics(),
]);
};
const bindWecomUser = async () => {
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) => {
openDeleteConfirmDialog(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 = () => {
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`);
};
// Quick Questions Logic
interface QuickQuestion {
id: number;
title: string;
question: string;
agent_id: number;
agent_name?: string;
sort_order: number;
}
const quickQuestions = ref<QuickQuestion[]>([]);
const newQuestion = ref<Partial<QuickQuestion>>({
title: '',
question: '',
agent_id: undefined,
sort_order: 0
});
const isEditingQuestion = ref(false);
interface AnnouncementItem {
id: number;
title: string;
content: string;
created_at: string;
}
const adminAnnouncements = ref<AnnouncementItem[]>([]);
const newAnnouncement = ref({ title: '', content: '' });
const loadAnnouncementsAdmin = async () => {
try {
adminAnnouncements.value = await listAnnouncements();
} catch (e) {
console.error('Failed to load announcements', e);
adminAnnouncements.value = [];
}
};
const createAnnouncementAdmin = async () => {
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 = { title: '', content: '' };
await loadAnnouncementsAdmin();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const deleteAnnouncementAdmin = async (id: number) => {
openDeleteConfirmDialog(t('admin.announcement.confirmDelete'), async () => {
try {
await deleteAnnouncement(id);
await loadAnnouncementsAdmin();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
const loadQuickQuestions = async () => {
try {
quickQuestions.value = await listAdminQuickQuestions();
} catch (e) {
console.error('Failed to load quick questions', e);
}
};
const saveQuestion = async () => {
if (!newQuestion.value.title || !newQuestion.value.question || !newQuestion.value.agent_id) {
msg.warning(t('admin.question.msg.fillAll'));
return;
}
isSaving.value = true;
try {
const url = isEditingQuestion.value
? `/api/admin/quick-questions/${newQuestion.value.id}`
: '/api/admin/quick-questions';
const method = isEditingQuestion.value ? 'PUT' : 'POST';
await saveAdminQuickQuestion(url, method, newQuestion.value as Record<string, unknown>);
await loadQuickQuestions();
resetQuestionForm();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const editQuestion = (q: QuickQuestion) => {
newQuestion.value = { ...q };
isEditingQuestion.value = true;
};
const deleteQuestion = async (id: number) => {
openDeleteConfirmDialog(t('admin.question.confirmDelete'), async () => {
try {
await deleteAdminQuickQuestion(id);
await loadQuickQuestions();
} catch (e) {
console.error(e);
}
});
};
const resetQuestionForm = () => {
newQuestion.value = { title: '', question: '', agent_id: undefined, sort_order: 0 };
isEditingQuestion.value = false;
};
// 组件挂载时加载初始数据
onMounted(async () => {
const headers = getAuthHeaders();
if (!headers['Authorization']) {
console.warn('No auth headers found, redirecting to login');
router.push('/');
return;
}
const moduleQuery = typeof route.query.module === 'string' ? route.query.module : '';
const allowedModules = sidebarItems.value.map((item) => item.id);
if (moduleQuery && allowedModules.includes(moduleQuery)) {
activeModule.value = moduleQuery as typeof activeModule.value;
if (route.query.module) {
router.replace({ path: '/admin' });
}
}
isLoading.value = true;
await Promise.all([
loadAgents(),
loadUsers(),
loadReports(),
loadPermissionRequests(),
loadDepartments(),
loadAnnouncementsAdmin(),
loadQuickQuestions(),
loadWecomBindings(),
loadWecomAudits()
]);
isLoading.value = false;
});
watch(activeModule, async (value) => {
if (value === 'requests') {
await loadPermissionRequests();
}
if (value === 'questions') {
await loadQuickQuestions();
}
if (value === 'announcements') {
await loadAnnouncementsAdmin();
}
if (value === 'reports' || value === 'dashboard') {
await loadReports();
}
if (value === 'departments') {
await loadDepartments();
}
if (value === 'wecom') {
await refreshWecomData();
}
if (value === 'schedules') {
await loadSchedules();
}
});
/**
* saveConfig
* 用途:目前仅作为“保存成功”提示,核心配置变更在具体操作时已写入后台
*/
// const saveConfig = () => {
// msg.success(t('admin.msg.allSaved'));
// };
const pendingUsers = computed(() => users.value.filter(u => u.status === 'pending'));
const activeUsers = computed(() => users.value.filter(u => u.status !== 'pending'));
const permissionFilters = ref({
username: '',
department: '',
role: ''
});
const filteredPermissionUsers = computed(() => {
return 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 isEditingAgent = ref(false);
const selectedAgentId = ref<number | null>(null);
const showAgentTestModal = ref(false);
const isTestingAgent = ref(false);
const testingAgent = ref<AgentRow | null>(null);
const agentTestResult = ref<AgentTestResult | null>(null);
const selectAgent = (agent: AgentRow) => {
selectedAgentId.value = agent.id;
// Deep clone and ensure all fields are present
newAgent.value = {
...agent,
dify_app_type: (agent.extra_config?.dify_app_type === 'workflow' ? 'workflow' : 'chatflow') as 'chatflow' | 'workflow',
// Show existing API key while editing selected row.
dify_api_key: agent.dify_api_key || '',
iframe_url: agent.extra_config?.iframe_url || ''
};
isEditingAgent.value = true;
};
const resetAgentForm = () => {
selectedAgentId.value = null;
newAgent.value = {
name: '',
dify_app_id: '',
dify_api_key: '',
description: '',
type: 'api',
dify_app_type: 'chatflow',
api_base_url: '',
iframe_url: '',
is_active: true
} as any;
isEditingAgent.value = false;
};
const openAgentTestModal = (agent: AgentRow) => {
testingAgent.value = agent;
agentTestResult.value = null;
showAgentTestModal.value = true;
runAgentTest(agent);
};
const runAgentTest = async (agent?: AgentRow) => {
const target = agent || testingAgent.value;
if (!target) return;
isTestingAgent.value = true;
try {
const data = await testAdminAgent(target.id);
agentTestResult.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);
if (idx >= 0) {
const updatedAgent = agents.value[idx];
if (updatedAgent) {
updatedAgent.is_active = true;
}
}
if (selectedAgentId.value === target.id) {
newAgent.value.is_active = true;
}
}
} catch (e) {
agentTestResult.value = {
success: false,
request_url: '',
output_info: (e as Error).message || t('admin.agent.networkError'),
analysis: t('admin.agent.testFailedRequestException'),
http_status: 0
};
} finally {
isTestingAgent.value = false;
}
};
/**
* createAgent
* 用途:使用表单一次性填写所有字段并创建 Agent
* 实现方式:调 POST /api/admin/agents
*/
const createAgent = async () => {
if (!newAgent.value.name) {
msg.warning(t('admin.dept.msg.nameRequired'));
return;
}
isSaving.value = true;
const extra_config: Record<string, any> = {};
if (newAgent.value.type === 'iframe' && newAgent.value.iframe_url) {
extra_config.iframe_url = newAgent.value.iframe_url;
}
if (newAgent.value.type === 'api') {
extra_config.dify_app_type = newAgent.value.dify_app_type === 'workflow' ? 'workflow' : 'chatflow';
}
try {
const editingId = isEditingAgent.value ? Number(newAgent.value.id) : null;
if (isEditingAgent.value) {
const payload: Record<string, unknown> = {
name: newAgent.value.name,
dify_app_id: newAgent.value.dify_app_id,
description: newAgent.value.description,
type: newAgent.value.type,
api_base_url: newAgent.value.api_base_url,
extra_config: extra_config,
is_active: newAgent.value.is_active
};
if (newAgent.value.dify_api_key) {
payload.dify_api_key = newAgent.value.dify_api_key;
}
await updateAdminAgent(newAgent.value.id!, payload);
} else {
await createAdminAgent({
name: newAgent.value.name,
dify_app_id: newAgent.value.dify_app_id,
dify_api_key: newAgent.value.dify_api_key,
description: newAgent.value.description,
type: newAgent.value.type,
api_base_url: newAgent.value.api_base_url,
extra_config: extra_config
});
}
await loadAgents();
if (editingId) {
const updated = agents.value.find(a => a.id === editingId);
if (updated) {
selectAgent(updated);
}
} else {
resetAgentForm();
}
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const approveUser = async (userId: number) => {
openDeleteConfirmDialog(t('admin.approval.confirmApprove'), async () => {
try {
await approveAdminUser(userId);
await loadUsers();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
}
});
};
const rejectUser = async (userId: number) => {
openDeleteConfirmDialog(t('admin.approval.confirmReject'), async () => {
try {
await rejectAdminUser(userId);
await loadUsers();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
// 报表相关状态
const currentTable = ref('users');
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];
interface ReportColumnConfig {
key: string;
visible: boolean;
width: number;
}
interface ChatLogsLayoutPref {
columns: ReportColumnConfig[];
wrapEnabled: boolean;
wrapMaxHeight: number;
sortRules?: SortRule[];
}
type SortDirection = 'asc' | 'desc';
interface SortRule {
key: string;
direction: SortDirection;
}
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];
openDeleteConfirmDialog(`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 () => {
if (activeModule.value === 'reports') {
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(activeModule, async (value) => {
if (value === 'requests') {
await loadPermissionRequests();
}
if (value === 'reports') {
reportCurrentPage.value = 1;
await loadTableData();
if (currentTable.value === 'chat_logs') {
chatLogsTotal.value = await loadTableCount('chat_logs');
} else {
showChatLogsSelection.value = false;
}
}
});
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(wecomBoundOnly, async () => {
if (activeModule.value === 'wecom') {
await loadWecomBindings();
}
});
watch([wecomAuditSourceFilter, wecomAuditStatusFilter], async () => {
if (activeModule.value === 'wecom') {
await loadWecomAudits();
}
});
watch([reportPageSize, sortedTableData], () => {
if (reportCurrentPage.value > reportTotalPages.value) {
reportCurrentPage.value = reportTotalPages.value;
}
if (reportCurrentPage.value < 1) {
reportCurrentPage.value = 1;
}
});
/**
* deleteAgent
* 用途:删除指定 Agent
* 实现方式:调 DELETE /api/admin/agents/:id
*/
const deleteAgent = async (id: number) => {
openDeleteConfirmDialog(t('admin.agent.confirmDelete'), async () => {
try {
await deleteAdminAgent(id);
await loadAgents();
if (selectedAgentId.value === id) {
resetAgentForm();
}
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
const showAgentPermissionModal = ref(false);
const selectedAgentForPermissions = ref<AgentRow | null>(null);
const agentPermissionUserIds = ref<number[]>([]);
const openAgentPermissionModal = (agent: AgentRow) => {
selectedAgentForPermissions.value = agent;
// Find users who have this agent in their agent_ids
agentPermissionUserIds.value = users.value
.filter(u => u.agent_ids.includes(agent.id))
.map(u => u.id);
showAgentPermissionModal.value = true;
};
const saveAgentPermissions = async () => {
if (!selectedAgentForPermissions.value) return;
isSaving.value = true;
try {
await saveAdminAgentPermissions(
selectedAgentForPermissions.value.id,
agentPermissionUserIds.value
);
await loadUsers();
showAgentPermissionModal.value = false;
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
} finally {
isSaving.value = false;
}
};
const toggleAgentPermission = (userId: number) => {
const index = agentPermissionUserIds.value.indexOf(userId);
if (index === -1) {
agentPermissionUserIds.value.push(userId);
} else {
agentPermissionUserIds.value.splice(index, 1);
}
};
// Toggle permission from Matrix View
const toggleUserAgentPermission = async (user: UserRow, agentId: number) => {
const hasPermission = user.agent_ids.includes(agentId);
const newAgentIds = hasPermission
? user.agent_ids.filter(id => id !== agentId)
: [...user.agent_ids, agentId];
// Optimistic update
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'));
}
};
/**
* editUserPermissions
* 用途:通过输入框编辑用户可访问的 Agent ID 列表
* 实现方式:调 POST /api/admin/users/:id/permissions
*/
/* const editUserPermissions = (user: UserRow) => {
openEditUserModal(user);
}; */
const exportPermissions = () => {
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');
};
/**
* handlePermissionImport
* 用途:从 Excel 导出的 CSV 文件中批量导入用户权限
* 实现方式:将文件作为 multipart/form-data 上传到 /api/admin/permissions/import
*/
const handlePermissionImport = async (event: Event) => {
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 = '';
}
};
</script>
<template>
<div class="page-shell min-h-screen font-sans flex flex-col">
<!-- Header -->
<header class="app-header px-6">
<div class="flex items-center gap-4">
<button
@click="toggleSidebar"
class="btn-icon-ds md:block hidden"
title="Toggle Sidebar"
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><path d="M9 3v18"/></svg>
</button>
<button
@click="router.push('/workspace')"
class="btn-icon-ds"
title="Back to Workspace"
>
<ArrowLeft class="w-6 h-6" />
</button>
<div class="flex flex-col">
<h1 class="text-xl md:text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-brand-600 to-indigo-600 tracking-tight">
{{ t('admin.title') }}
</h1>
<span class="text-xs text-muted font-medium tracking-wide">{{ t('admin.subtitle') }}</span>
</div>
</div>
<AppHeaderTools />
<!-- <button
@click="saveConfig"
class="btn-primary hidden md:flex items-center gap-2 px-5 py-2.5 shadow-lg active:scale-95"
>
<Save class="w-4 h-4" />
<span class="font-medium text-sm">{{ t('admin.save') }}</span>
</button> -->
</header>
<main class="flex-1 w-full mx-auto px-4 md:px-8 py-6 md:py-8 flex flex-col md:flex-row gap-8 items-start">
<!-- Sidebar Navigation -->
<aside
class="surface-panel rounded-2xl shadow-sm h-fit md:sticky md:top-24 overflow-hidden shrink-0 z-10 transition-all duration-300"
:class="isSidebarCollapsed ? 'w-0 md:w-20' : 'w-full md:w-64'"
>
<nav class="flex md:flex-col p-3 gap-1 overflow-x-auto md:overflow-visible no-scrollbar">
<button
v-for="item in sidebarItems"
:key="item.id"
class="admin-nav-btn group"
:class="{ 'admin-nav-btn--active': activeModule === item.id }"
@click="activeModule = item.id as any; activeReportTabId = null"
:title="isSidebarCollapsed ? item.label : ''"
>
<component :is="item.icon" class="w-5 h-5 transition-transform group-hover:scale-110 flex-shrink-0" :class="activeModule === item.id ? 'text-brand-600' : 'text-muted group-hover:text-secondary'" />
<span :class="isSidebarCollapsed ? 'md:hidden' : ''">{{ item.label }}</span>
<span v-if="item.badge && !isSidebarCollapsed" class="ml-auto bg-red-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-sm">
{{ item.badge }}
</span>
<span v-if="item.badge && isSidebarCollapsed" class="absolute top-2 right-2 w-2 h-2 bg-red-500 rounded-full"></span>
<div v-if="activeModule === item.id" class="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 bg-brand-600 rounded-r-full"></div>
</button>
<!-- Reports Submenu -->
<div v-if="config.admin.modules.reports !== false" class="flex flex-col flex-shrink-0">
<button
@click="expandedReports = !expandedReports"
class="admin-nav-btn group justify-between"
:class="{ 'admin-nav-btn--active': activeModule === 'reports' }"
:title="isSidebarCollapsed ? t('admin.nav.reports') : ''"
>
<div class="flex items-center gap-3">
<BarChart2 class="w-5 h-5 flex-shrink-0 transition-colors" :class="activeModule === 'reports' ? 'text-brand-600' : 'text-muted group-hover:text-secondary'" />
<span :class="isSidebarCollapsed ? 'md:hidden' : ''">{{ t('admin.nav.reports') }}</span>
</div>
<svg v-if="!isSidebarCollapsed" :class="expandedReports ? 'rotate-180' : ''" class="w-4 h-4 transition-transform text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
</button>
<div v-if="expandedReports && !isSidebarCollapsed" class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6">
<button
v-for="table in ['users', 'agents', 'chat_logs', 'permission_requests', 'general_feedbacks', 'feedbacks']"
:key="table"
@click="openReportTab(table)"
class="admin-nav-subitem"
:class="{ 'admin-nav-subitem--active': activeModule === 'reports' && currentTable === table }"
>
<div class="w-1.5 h-1.5 rounded-full" :class="(activeModule === 'reports' && currentTable === table) ? 'bg-brand-600' : 'bg-surface-strong'"></div>
{{ getReportTableLabel(table) }}
</button>
</div>
</div>
</nav>
</aside>
<!-- Main Content Area -->
<section class="flex-1 min-w-0 space-y-8 w-full">
<!-- Loading State -->
<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>
<!-- Dashboard Overview -->
<section v-else-if="activeModule === 'dashboard'" 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="activeModule = 'agents'"
>
<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">{{ agents.length }}</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="activeModule = 'permissions'"
>
<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">{{ users.length }}</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="activeModule = 'reports'; currentTable = '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">{{ usageReport?.total ?? 0 }}</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="activeModule = 'reports'; currentTable = '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">{{ Number(feedbackReportSummary?.avg_score ?? 0).toFixed(1) }}</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.avgRating') }}</div>
</div>
</section>
<!-- User Approvals -->
<section v-else-if="activeModule === 'approvals'" class="admin-table-section">
<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
@click="approveUser(user.id)"
class="p-2 text-green-600 bg-green-50 rounded-lg hover:bg-green-100 transition-colors"
title="Approve"
>
<ShieldCheck class="w-4 h-4" />
</button>
<button
@click="rejectUser(user.id)"
class="p-2 text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
title="Reject"
>
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- User Maintenance -->
<section v-else-if="activeModule === 'users'" class="admin-table-section">
<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
@click="isManagingDepts = true"
class="btn-secondary text-sm"
>
<span>{{ t('admin.user.manageDepts') }}</span>
</button>
<button
@click="cleanRejectedUsers"
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"
>
<Trash2 class="w-4 h-4" />
<span>{{ t('admin.user.cleanRejected') }}</span>
</button>
<button
v-if="selectedUserIds.length > 0"
@click="batchDeleteUsers"
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"
>
<Trash2 class="w-4 h-4" />
<span>{{ t('admin.user.batchDelete') }} ({{ selectedUserIds.length }})</span>
</button>
<button
v-if="selectedUserIds.length > 0"
@click="openBatchEditModal"
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"
>
<Edit class="w-4 h-4" />
<span>{{ t('admin.user.batchEdit') }} ({{ selectedUserIds.length }})</span>
</button>
<button
v-if="selectedUserIds.length > 0"
@click="openBatchPermissionModal"
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"
>
<Users class="w-4 h-4" />
<span>{{ t('admin.user.batchPermission') }} ({{ selectedUserIds.length }})</span>
</button>
<button
@click="openCreateUserModal"
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"
>
<Plus class="w-4 h-4" />
<span class="font-medium">{{ t('admin.user.addUser') }}</span>
</button>
</div>
</div>
<!-- Filters -->
<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 type="checkbox" id="hideRejected" v-model="hideRejected" class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 border-default" />
<label for="hideRejected" 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"
:checked="selectedUserIds.length === filteredUsers.length && filteredUsers.length > 0"
@change="toggleAllUsers(filteredUsers)"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 cursor-pointer border-default"
/>
</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"
:checked="selectedUserIds.includes(user.id)"
@change="toggleUserSelection(user.id)"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 cursor-pointer border-default"
/>
</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
@click="openEditUserModal(user)"
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"
>
{{ t('admin.edit') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- Department Management -->
<section v-else-if="activeModule === 'departments'" class="section-gap animate-fade-in-up">
<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">
<!-- Form Section -->
<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')"></textarea>
</div>
<div class="flex justify-end gap-2 pt-2">
<button v-if="editingDept.id" @click="editingDept = {}" class="btn-ghost btn-sm">{{ t('admin.cancel') }}</button>
<button @click="saveDepartment" class="btn-primary btn-sm">
{{ editingDept.id ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
</div>
<!-- List Section -->
<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 @click="editDepartment(d)" class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors">
<Edit class="w-4 h-4" />
</button>
<button @click="deleteDepartment(d.id)" class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- Knowledge Base Management -->
<section v-else-if="activeModule === 'knowledge_base'" class="admin-table-section overflow-hidden animate-fade-in-up">
<KbAdminPanel />
</section>
<!-- Agent Management -->
<section v-else-if="activeModule === 'agents'" class="admin-table-section">
<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
@click="resetAgentForm"
class="btn-primary"
>
<Plus class="w-5 h-5" />
<span class="font-medium">{{ t('admin.agent.new') }}</span>
</button>
</div>
<!-- Add Agent Form -->
<div class="admin-form-panel">
<h3 class="section-title mb-6">{{ isEditingAgent ? 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="newAgent.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="newAgent.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="newAgent.type === 'api'">
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">Dify应用类型</label>
<select
v-model="newAgent.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="newAgent.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="newAgent.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="newAgent.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="newAgent.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="newAgent.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="newAgent.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
class="btn-primary btn-lg"
@click="createAgent"
>
<Plus v-if="!isEditingAgent" class="w-5 h-5" />
{{ isEditingAgent ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
<!-- Agent List -->
<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="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'"></span>
{{ 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
@click.stop="openAgentTestModal(agent)"
class="p-2 text-emerald-600 bg-emerald-50 hover:bg-emerald-100 rounded-lg transition-all"
:title="t('admin.agent.test')"
>
{{ t('admin.agent.test') }}
</button>
<button
@click.stop="openAgentPermissionModal(agent)"
class="p-2 text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-all"
:title="t('admin.agent.manageAccess')"
>
<Users class="w-5 h-5" />
</button>
<button
@click.stop="deleteAgent(agent.id)"
class="p-2 text-muted hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
:title="t('admin.agent.delete')"
>
<Trash2 class="w-5 h-5" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- Announcement Management -->
<section v-else-if="activeModule === 'announcements'" class="section-gap animate-fade-in-up">
<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"></textarea>
</div>
<div class="flex justify-end pt-2">
<button @click="createAnnouncementAdmin" :disabled="isSaving" class="btn-primary btn-sm disabled:opacity-50">
{{ 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="adminAnnouncements.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 adminAnnouncements" :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 @click="deleteAnnouncementAdmin(ann.id)" class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
<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>
</section>
<!-- Common Questions Management -->
<section v-else-if="activeModule === 'questions'" class="section-gap animate-fade-in-up">
<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">
<!-- Form Section -->
<div class="lg:col-span-1 card p-6 shadow-sm h-fit">
<h3 class="font-bold text-primary mb-4">{{ isEditingQuestion ? 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="newQuestion.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="newQuestion.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 type="number" v-model="newQuestion.sort_order" 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="newQuestion.question" rows="4" class="input-field text-sm" :placeholder="t('admin.question.fields.contentPlaceholder')"></textarea>
</div>
<div class="flex justify-end gap-2 pt-2">
<button v-if="isEditingQuestion" @click="resetQuestionForm" class="btn-ghost btn-sm">{{ t('admin.cancel') }}</button>
<button @click="saveQuestion" :disabled="isSaving" class="btn-primary btn-sm disabled:opacity-50">
{{ isSaving ? t('admin.save') + '...' : (isEditingQuestion ? t('admin.update') : t('admin.add')) }}
</button>
</div>
</div>
</div>
<!-- List Section -->
<div class="lg:col-span-2 admin-table-section">
<div v-if="quickQuestions.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 quickQuestions" :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 @click="editQuestion(q)" class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors">
<Edit class="w-4 h-4" />
</button>
<button @click="deleteQuestion(q.id)" class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- User Permission Management (Matrix View) -->
<section v-else-if="activeModule === 'permissions'" 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.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"
@click="openBatchPermissionModal"
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"
>
<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="handlePermissionImport" />
<FileText class="w-4 h-4" />
{{ t('admin.perm.importCsv') }}
</label>
<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>
<!-- Filters -->
<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" :checked="selectedUserIds.length > 0 && selectedUserIds.length === filteredPermissionUsers.length" @change="toggleAllUsers(filteredPermissionUsers)" class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500" />
</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 filteredPermissionUsers" :key="user.id">
<td class="px-4 py-4 text-center sticky left-0 admin-table-sticky-cell z-20">
<input type="checkbox" :checked="selectedUserIds.includes(user.id)" @change="toggleUserSelection(user.id)" class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500" />
</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"
:checked="user.agent_ids.includes(agent.id)"
@change="toggleUserAgentPermission(user, agent.id)"
class="admin-checkbox-lg"
/>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<section v-else-if="activeModule === 'schedules'" class="section-gap animate-fade-in-up">
<div class="admin-panel-lg px-7 py-6 shadow-sm">
<div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div class="flex items-start gap-4">
<button
v-if="scheduleViewMode === 'workbench'"
class="inline-flex h-14 w-14 items-center justify-center admin-panel text-muted transition hover:bg-surface-soft hover:text-secondary"
@click="backToScheduleOverview"
>
<ArrowLeft class="h-7 w-7" />
</button>
<div class="flex h-14 w-14 items-center justify-center rounded-2xl bg-blue-50 text-blue-600">
<Settings2 class="h-7 w-7" />
</div>
<div>
<h2 class="text-2xl font-bold tracking-tight text-primary">
{{ scheduleViewMode === 'overview' ? $t('admin.schedule.overviewTitle') : $t('admin.schedule.workbenchTitle') }}
</h2>
<p class="mt-1.5 text-sm text-muted">
{{ scheduleViewMode === 'overview' ? $t('admin.schedule.overviewSubtitle') : $t('admin.schedule.workbenchSubtitle') }}
</p>
</div>
</div>
<button
class="inline-flex items-center gap-2 admin-panel px-5 py-2.5 text-sm font-semibold text-secondary transition hover:bg-surface-soft"
@click="loadSchedules"
>
<RefreshCw class="h-5 w-5" />
{{ $t('admin.schedule.refresh') }}
</button>
</div>
</div>
<template v-if="scheduleViewMode === 'overview'">
<div class="admin-panel-lg p-6 shadow-sm">
<div class="mb-5 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
<div class="admin-stat-tile px-4 py-3">
<div class="text-xl font-bold text-primary">{{ schedules.length }}</div>
<div class="text-sm text-muted">{{ $t('admin.schedule.stats.total') }}</div>
</div>
<div class="admin-stat-tile px-4 py-3">
<div class="text-xl font-bold text-primary">{{ scheduleEnabledCount }}</div>
<div class="text-sm text-muted">{{ $t('admin.schedule.stats.enabled') }}</div>
</div>
<div class="admin-stat-tile px-4 py-3">
<div class="text-xl font-bold text-primary">{{ scheduleDisabledCount }}</div>
<div class="text-sm text-muted">{{ $t('admin.schedule.stats.disabled') }}</div>
</div>
<div class="admin-stat-tile px-4 py-3">
<div class="text-xl font-bold text-primary">{{ scheduleRunningCount }}</div>
<div class="text-sm text-muted">{{ $t('admin.schedule.stats.running') }}</div>
</div>
</div>
<div class="admin-panel p-4">
<div class="mb-3 flex items-center justify-between">
<h4 class="text-lg font-bold text-primary">{{ $t('admin.schedule.sectionOverview') }}</h4>
<span class="text-xs text-muted">{{ $t('admin.schedule.switchByCard') }}</span>
</div>
<div v-if="scheduleLoading" class="py-8 text-center text-sm text-muted">{{ $t('admin.schedule.loading') }}</div>
<div v-else class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3 auto-rows-fr">
<div class="admin-panel p-4 transition-colors hover:border-brand-300 h-full min-h-[260px] flex flex-col">
<div class="mb-3 flex items-center gap-2">
<div class="flex h-8 w-8 items-center justify-center rounded-xl bg-brand-50 text-brand-600">
<Settings2 class="h-4 w-4" />
</div>
<div class="font-semibold text-primary">{{ $t('admin.schedule.addTitle') }}</div>
</div>
<div class="text-sm text-muted">
{{ $t('admin.schedule.addHint') }}
</div>
<div class="mt-auto pt-3">
<button
@click="openScheduleCreateModal"
class="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-brand-600 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
>
<Plus class="h-4 w-4" />
{{ $t('admin.schedule.addButton') }}
</button>
</div>
</div>
<div
v-for="s in schedules"
:key="s.id"
class="flex h-full min-h-[260px] flex-col admin-panel p-4 transition hover:border-blue-200 hover:bg-surface-soft"
>
<button class="w-full text-left" @click="openScheduleRunSubmenu(s.id)">
<div class="min-h-[96px]">
<div class="flex items-center justify-between gap-3">
<div class="truncate text-base font-semibold text-primary">{{ s.name }}</div>
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold"
:class="s.enabled ? 'bg-emerald-100 text-emerald-700' : 'bg-surface-strong text-secondary'">
{{ s.enabled ? $t('admin.schedule.enabled') : $t('admin.schedule.disabled') }}
</span>
</div>
<div class="mt-2 text-sm text-muted">{{ $t('admin.schedule.scheduleNo') }}:{{ s.schedule_no }}</div>
<div class="mt-1 text-sm text-muted">Cron:{{ s.cron_expr }}</div>
<div
v-if="s.schedule_type === 'platform_app' && s.platform_api_path"
class="mt-1 text-sm text-muted"
>
{{ $t('admin.schedule.config') }}:{{ s.platform_api_path }}
</div>
<div class="mt-1 text-sm text-muted">{{ $t('admin.schedule.owner') }}:{{ s.owner_username || s.owner_user_id }}</div>
</div>
</button>
<div class="mt-auto pt-3">
<div class="mb-1 text-sm text-muted">
{{ $t('admin.schedule.lastRun') }}:{{ formatDateTime(s.last_run_at) }}
</div>
<div class="mb-3 text-sm text-muted">
{{ $t('admin.schedule.nextRun') }}:{{ formatDateTime(s.next_run_at) }}
</div>
<div class="flex flex-wrap items-center gap-2">
<button
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-2 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
@click.stop="openScheduleEditModal(s)"
>
<Edit3 class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.edit') }}
</button>
<button
v-if="!s.enabled"
class="inline-flex items-center gap-1 rounded-xl border border-emerald-200 px-3 py-2 text-xs font-medium text-emerald-700 transition-colors hover:bg-emerald-50"
@click.stop="setScheduleEnabled(s.id, true)"
>
<Power class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.start') }}
</button>
<button
v-else
class="inline-flex items-center gap-1 rounded-xl border border-amber-200 px-3 py-2 text-xs font-medium text-amber-700 transition-colors hover:bg-amber-50"
@click.stop="setScheduleEnabled(s.id, false)"
>
<PowerOff class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.pause') }}
</button>
<button
class="inline-flex items-center gap-1 rounded-xl border border-blue-200 px-3 py-2 text-xs font-medium text-blue-700 transition-colors hover:bg-blue-50"
@click.stop="runScheduleNow(s.id)"
>
<Rocket class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.run') }}
</button>
<button
v-if="s.platform_api_path && s.data_source_type !== 'external_api'"
class="inline-flex items-center gap-1 rounded-xl border border-violet-200 px-3 py-2 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
@click.stop="openTestRunDialog(s)"
>
<FlaskConical class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.test') }}
</button>
<button
class="inline-flex items-center gap-1 rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50"
@click.stop="deleteSchedule(s)"
>
<Trash2 class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.delete') }}
</button>
</div>
</div>
</div>
<div v-if="schedules.length === 0" class="rounded-xl border border-dashed border-default px-4 py-6 text-center text-sm text-muted">
{{ $t('admin.schedule.emptyList') }}
</div>
</div>
</div>
</div>
</template>
<template v-else>
<div class="space-y-6">
<div class="grid grid-cols-2 gap-3 admin-panel-lg p-4 shadow-sm md:grid-cols-4 xl:grid-cols-7">
<div class="col-span-2 admin-stat-tile px-4 py-3 xl:col-span-3">
<div class="truncate text-base font-semibold text-primary">{{ selectedSchedule?.name || $t('admin.schedule.noSelection') }}</div>
<div class="mt-1 text-xs text-muted">{{ $t('admin.schedule.selectedHint', { time: selectedScheduleLatestRunAt }) }}</div>
</div>
<div class="admin-stat-tile px-4 py-3 text-center">
<div class="text-base font-semibold text-primary">{{ selectedScheduleRuns.length }}</div>
<div class="mt-1 text-xs text-muted">{{ $t('admin.schedule.runBatches') }}</div>
</div>
<div class="admin-stat-tile px-4 py-3 text-center">
<div class="text-base font-semibold text-primary">{{ selectedScheduleRunMetrics.total }}</div>
<div class="mt-1 text-xs text-muted">{{ $t('admin.schedule.totalProcessed') }}</div>
</div>
<div class="admin-stat-tile px-4 py-3 text-center">
<div class="text-base font-semibold text-emerald-700">{{ selectedScheduleRunMetrics.success }}</div>
<div class="mt-1 text-xs text-muted">{{ $t('admin.schedule.totalSuccess') }}</div>
</div>
<div class="admin-stat-tile px-4 py-3 text-center">
<div class="text-base font-semibold text-rose-600">{{ selectedScheduleRunMetrics.failed }}</div>
<div class="mt-1 text-xs text-muted">{{ $t('admin.schedule.totalFailed') }}</div>
</div>
</div>
<div class="admin-panel-lg p-6 shadow-sm">
<div class="grid grid-cols-1 gap-6 lg:grid-cols-[320px_minmax(0,1fr)]">
<div class="admin-panel-lg p-6 shadow-sm">
<div class="mb-4 flex items-center justify-between">
<h4 class="text-lg font-semibold text-primary">{{ $t('admin.schedule.listTitle') }}</h4>
<span class="text-xs text-muted">{{ $t('admin.schedule.switchByCard') }}</span>
</div>
<div class="space-y-3">
<button
v-for="s in schedules"
:key="`workbench-${s.id}`"
class="w-full rounded-2xl border px-4 py-4 text-left transition-all"
:class="selectedScheduleId === s.id ? 'border-blue-300 bg-blue-50/60' : 'border-default bg-surface hover:border-blue-200 hover:bg-surface-soft'"
@click="viewScheduleRuns(s.id)"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="truncate font-semibold text-primary">{{ s.name }}</div>
<div class="mt-0.5 text-xs text-muted">{{ s.schedule_no }}</div>
<div class="mt-2 flex flex-wrap items-center gap-2">
<button
class="inline-flex items-center justify-center rounded-xl border border-default p-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
:title="$t('admin.schedule.actions.edit')"
@click.stop="openScheduleEditModal(s)"
>
<Edit3 class="h-3 w-3" />
</button>
<button
v-if="!s.enabled"
class="inline-flex items-center justify-center rounded-xl border border-emerald-200 p-1.5 text-xs font-medium text-emerald-700 transition-colors hover:bg-emerald-50"
:title="$t('admin.schedule.actions.start')"
@click.stop="setScheduleEnabled(s.id, true)"
>
<Power class="h-3 w-3" />
</button>
<button
v-else
class="inline-flex items-center justify-center rounded-xl border border-amber-200 p-1.5 text-xs font-medium text-amber-700 transition-colors hover:bg-amber-50"
:title="$t('admin.schedule.actions.pause')"
@click.stop="setScheduleEnabled(s.id, false)"
>
<PowerOff class="h-3 w-3" />
</button>
<button
class="inline-flex items-center justify-center rounded-xl border border-blue-200 p-1.5 text-xs font-medium text-blue-700 transition-colors hover:bg-blue-50"
:title="$t('admin.schedule.actions.run')"
@click.stop="runScheduleNow(s.id)"
>
<Rocket class="h-3 w-3" />
</button>
<button
v-if="s.platform_api_path && s.data_source_type !== 'external_api'"
class="inline-flex items-center justify-center rounded-xl border border-violet-200 p-1.5 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
:title="$t('admin.schedule.actions.test')"
@click.stop="openTestRunDialog(s)"
>
<FlaskConical class="h-3 w-3" />
</button>
<button
class="inline-flex items-center justify-center rounded-xl border border-rose-200 p-1.5 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50"
:title="$t('admin.schedule.actions.delete')"
@click.stop="deleteSchedule(s)"
>
<Trash2 class="h-3 w-3" />
</button>
</div>
</div>
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold"
:class="s.enabled ? 'bg-emerald-100 text-emerald-700' : 'bg-surface-strong text-secondary'">
{{ s.enabled ? $t('admin.schedule.enabled') : $t('admin.schedule.disabled') }}
</span>
</div>
</button>
</div>
</div>
<div>
<div v-if="selectedSchedule" class="admin-panel p-4">
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<div>
<h3 class="text-lg font-semibold text-primary">{{ $t('admin.schedule.recordsTitle', { name: selectedSchedule.name }) }}</h3>
<p class="mt-1 text-sm text-muted">{{ $t('admin.schedule.recordsSubtitle') }}</p>
</div>
</div>
<div>
<div class="mb-3 flex flex-wrap items-center gap-2 text-xs">
<label class="text-muted">{{ $t('admin.schedule.filterStart') }}</label>
<input type="datetime-local" step="1" v-model="scheduleRunStartedAfter" class="!min-w-0 !w-[170px] !py-1 !px-2 !text-xs rounded-lg border border-default" />
<label class="text-muted">{{ $t('admin.schedule.filterEnd') }}</label>
<input type="datetime-local" step="1" v-model="scheduleRunStartedBefore" class="!min-w-0 !w-[170px] !py-1 !px-2 !text-xs rounded-lg border border-default" />
<select v-model="scheduleRunStatusFilter" class="!min-w-0 !w-[90px] !py-1 !px-2 !text-xs rounded-lg border border-default">
<option v-for="opt in scheduleRunStatusOptions" :key="opt.value" :value="opt.value">
{{ opt.label }}
</option>
</select>
<button
class="inline-flex items-center rounded-lg bg-brand-600 px-2.5 py-1 text-xs font-medium text-white hover:bg-brand-700"
@click="viewScheduleRuns(selectedSchedule.id)"
>
{{ $t('admin.schedule.query') }}
</button>
<button
class="inline-flex items-center rounded-lg border border-default px-2.5 py-1 text-xs font-medium text-secondary hover:bg-surface-soft"
@click="resetScheduleRunFilters(); viewScheduleRuns(selectedSchedule.id)"
>
{{ $t('admin.schedule.reset') }}
</button>
</div>
<div class="admin-table-wrap max-h-[calc(100vh-20rem)] rounded-xl border border-subtle scrollbar-thin">
<table class="admin-table min-w-[1270px] table-fixed text-xs">
<colgroup>
<col
v-for="col in scheduleRunColumnDefs"
:key="col.key"
:style="{ width: `${col.width}px` }"
/>
</colgroup>
<thead class="sticky top-0 z-10 admin-table-sticky-head">
<tr class="text-muted">
<th
v-for="(col, colIndex) in scheduleRunColumnDefs"
:key="col.key"
class="group relative whitespace-nowrap admin-table-sticky-head px-4 py-3 text-xs font-semibold uppercase select-none"
>
<span class="whitespace-nowrap">{{ col.label }}</span>
<span
class="absolute inset-y-0 -right-1 z-10 w-2 cursor-col-resize"
@mousedown.prevent="startScheduleColResize(colIndex, $event)"
:title="$t('admin.schedule.resizeColumn', { label: col.label })"
></span>
</th>
</tr>
</thead>
<tbody>
<tr v-if="scheduleRunsLoading">
<td colspan="10" class="px-4 py-8 text-center text-sm text-muted">{{ $t('admin.schedule.queryingRuns') }}</td>
</tr>
<tr v-else-if="filteredScheduleRuns.length === 0">
<td colspan="10" class="px-4 py-8 text-center text-sm text-muted">{{ $t('admin.schedule.noRunRecords') }}</td>
</tr>
<tr
v-else
v-for="r in filteredScheduleRuns"
:key="r.id"
class="text-secondary transition"
>
<td class="whitespace-nowrap px-4 py-2.5" :title="r.run_no">{{ r.run_no }}</td>
<td class="whitespace-nowrap px-4 py-2.5" :title="formatDateTime(r.started_at)">{{ formatDateTime(r.started_at) }}</td>
<td class="whitespace-nowrap px-4 py-2.5" :title="formatDateTime(r.finished_at)">{{ formatDateTime(r.finished_at) }}</td>
<td class="whitespace-nowrap px-4 py-2.5">
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold"
:class="getScheduleRunStatusBadge(r.status).cls">
{{ getScheduleRunStatusBadge(r.status).label }}
</span>
<span v-if="r.error_message" class="ml-1 text-xs text-muted" :title="r.error_message">...</span>
</td>
<td class="whitespace-nowrap px-4 py-2.5">{{ r.total_count }}</td>
<td class="whitespace-nowrap px-4 py-2.5">{{ r.success_count }}</td>
<td class="whitespace-nowrap px-4 py-2.5">{{ r.failed_count }}</td>
<td class="whitespace-nowrap px-4 py-2.5">
<span v-if="r.wecom_notified" class="inline-flex shrink-0 items-center gap-1 whitespace-nowrap text-xs text-emerald-600">
<svg class="h-3.5 w-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg>
{{ $t('admin.schedule.notified') }}
</span>
<span v-else-if="r.wecom_notify_error" class="whitespace-nowrap text-xs text-amber-500" :title="r.wecom_notify_error">{{ $t('admin.schedule.notifyError') }}</span>
<span v-else class="text-xs text-muted">-</span>
</td>
<td class="whitespace-nowrap px-4 py-2.5">
<div class="flex items-center">
<a
v-if="r.total_count > 0"
href="#"
@click.prevent="downloadScheduleExcel(r.id)"
class="inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded-lg border border-default px-2 py-1 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
>
<Download class="h-3 w-3 shrink-0" />
{{ $t('admin.schedule.download') }}
</a>
<span v-if="r.total_count === 0" class="text-muted">-</span>
</div>
</td>
<td class="whitespace-nowrap px-4 py-2.5">
<div class="flex items-center">
<button
v-if="(r.step_logs && r.step_logs.length > 0) || r.dify_execution_snapshot"
@click="expandedScheduleRunId = expandedScheduleRunId === r.id ? null : r.id"
class="inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded-lg border border-blue-200 px-2 py-1 text-xs font-medium text-blue-600 transition-colors hover:bg-blue-50"
>
<Eye class="h-3 w-3 shrink-0" />
{{ $t('admin.schedule.log') }}
<ChevronDown v-if="expandedScheduleRunId !== r.id" class="h-3 w-3 shrink-0" />
<ChevronUp v-else class="h-3 w-3 shrink-0" />
</button>
<span v-else class="text-muted">-</span>
</div>
</td>
</tr>
<tr
v-if="expandedScheduleRun"
:key="'expanded-' + expandedScheduleRunId"
>
<td colspan="10" class="px-4 py-3 bg-surface-soft/60">
<div class="space-y-3">
<div
v-if="expandedScheduleRun.dify_execution_snapshot"
class="rounded-xl border border-indigo-200 bg-indigo-50/50 p-3"
>
<div class="mb-2 flex items-center justify-between">
<h5 class="text-xs font-bold uppercase text-indigo-800">Dify 执行快照(审计)</h5>
<span class="text-[10px] text-indigo-600/80">
{{ expandedScheduleRun.dify_execution_snapshot.captured_at || '-' }}
</span>
</div>
<div v-if="expandedScheduleRun.dify_execution_snapshot.dify_enabled" class="space-y-2 text-xs text-secondary">
<div>
<span class="font-semibold text-muted">Agent:</span>
{{ expandedScheduleRun.dify_execution_snapshot.dify_agent_name || '-' }}
<span class="text-muted">(ID: {{ expandedScheduleRun.dify_execution_snapshot.dify_agent_id ?? '-' }})</span>
</div>
<div v-if="expandedScheduleRun.dify_execution_snapshot.dify_app_id">
<span class="font-semibold text-muted">Dify App ID:</span>
{{ expandedScheduleRun.dify_execution_snapshot.dify_app_id }}
</div>
<div>
<span class="mb-1 block font-semibold text-muted">System Prompt:</span>
<pre
v-if="expandedScheduleRun.dify_execution_snapshot.dify_system_prompt"
class="max-h-[240px] overflow-auto whitespace-pre-wrap rounded-lg border border-indigo-100 bg-surface p-3 font-mono text-[11px] leading-relaxed text-primary"
>{{ expandedScheduleRun.dify_execution_snapshot.dify_system_prompt }}</pre>
<span v-else class="text-muted">(未配置,使用 Dify 编排内默认提示词)</span>
</div>
</div>
<div v-else class="text-xs text-muted">本次执行未启用 Dify Agent</div>
</div>
<div class="space-y-2">
<div class="flex items-center justify-between mb-2">
<h5 class="text-xs font-bold text-secondary uppercase">{{ $t('admin.schedule.runLogs') }}</h5>
<span class="text-xs text-muted">{{ $t('admin.schedule.stepsCount', { count: expandedScheduleRun.step_logs?.length || 0 }) }}</span>
</div>
<div
v-for="(log, li) in expandedScheduleRun.step_logs || []"
:key="li"
class="rounded-xl border p-3"
:class="log.status === 'failed' ? 'border-rose-200 bg-rose-50/40' : 'border-default bg-surface'"
>
<div class="flex items-center gap-2 mb-1">
<span class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold"
:class="(stepStatusMap[log.status] || stepStatusMap.success || { cls: 'bg-surface-soft text-secondary' }).cls">
{{ (stepStatusMap[log.status] || { label: log.status }).label }}
</span>
<span class="text-xs font-semibold text-secondary">{{ stepLabelMap[log.step] || log.step }}</span>
<span v-if="log.row_id" class="text-[10px] text-muted">row_id={{ log.row_id }}</span>
<span v-if="log.duration_ms != null" class="text-[10px] text-muted">{{ log.duration_ms }}ms</span>
</div>
<details v-if="log.detail" class="mt-1">
<summary class="cursor-pointer text-[10px] font-semibold text-muted hover:text-secondary">{{ $t('admin.schedule.viewDetail') }}</summary>
<pre class="admin-pre-block">{{ JSON.stringify(log.detail, null, 2) }}</pre>
</details>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div v-else class="rounded-2xl border border-dashed border-default bg-surface px-4 py-10 text-center text-sm text-muted">
{{ $t('admin.schedule.noSelectionHint') }}
</div>
</div>
</div>
</div>
</div>
</template>
</section>
<!-- WeCom Management -->
<section v-else-if="activeModule === 'wecom'" 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>
<!-- Requests -->
<section
v-if="activeModule === 'requests'"
class="admin-table-section"
>
<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="permissionRequests.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 permissionRequests" :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
class="text-green-600 hover:text-green-800 text-sm font-medium hover:underline"
@click="approvePermissionRequest(req.id)"
>
{{ t('admin.request.approve') }}
</button>
<button
class="text-red-500 hover:text-red-700 text-sm font-medium hover:underline"
@click="rejectPermissionRequest(req.id)"
>
{{ t('admin.request.reject') }}
</button>
</div>
</td>
</tr>
</tbody>
</table>
</section>
<!-- Reports -->
<section
v-if="activeModule === 'reports'"
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>
</section>
</main>
<!-- User Modal -->
<!-- 用户弹窗:外层允许滚动,避免小屏/高缩放下被裁切 -->
<div v-if="showUserModal" 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">{{ editingUser.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">{{ t('admin.user.fields.realName') }}</label>
<input
v-model="editingUser.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">{{ t('admin.user.fields.employeeId') }}</label>
<input
v-model="editingUser.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">{{ t('admin.user.fields.phone') }}</label>
<input
v-model="editingUser.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="editingUser.agent_ids.includes(agent.id) ? 'border-blue-500 bg-blue-50' : ''"
>
<input
type="checkbox"
:value="agent.id"
v-model="editingUser.agent_ids"
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">{{ t('admin.user.fields.username') }}</label>
<input
v-model="editingUser.username"
type="text"
class="w-full border-default rounded-xl px-4 py-3 text-sm "
:disabled="!!editingUser.id"
/>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.email') }}</label>
<input
v-model="editingUser.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="editingUser.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="editingUser.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">
{{ t('admin.user.fields.password') }} <span v-if="editingUser.id" class="text-muted font-normal lowercase">{{ t('admin.user.fields.passwordHint') }}</span>
</label>
<input
v-model="editingUser.password"
type="password"
class="w-full border-default rounded-xl px-4 py-3 text-sm "
/>
</div>
</div>
<!-- 底部固定操作区:始终可见,避免页面过长时按钮被滚动到视口外 -->
<div class="admin-modal-footer">
<button
class="btn-ghost"
@click="showUserModal = false"
>
{{ t('admin.cancel') }}
</button>
<button
class="btn-primary disabled:opacity-70 disabled:cursor-not-allowed"
@click="saveUser"
:disabled="isSaving"
>
{{ isSaving ? t('admin.save') + '...' : t('admin.save') }}
</button>
</div>
</div>
</div>
<!-- Agent Test Modal -->
<div v-if="showAgentTestModal && testingAgent" 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">{{ testingAgent.name }}</span></p>
</div>
<button @click="showAgentTestModal = false" class="btn-icon-ds rounded-full">✕</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="agentTestResult?.tested_at">{{ t('admin.agent.testedAt') }}:{{ agentTestResult.tested_at }}</span>
</div>
<button
@click="runAgentTest()"
:disabled="isTestingAgent"
class="btn-primary btn-sm disabled:opacity-50"
>
{{ isTestingAgent ? t('admin.agent.testing') : t('admin.agent.retest') }}
</button>
</div>
<div v-if="isTestingAgent" class="text-sm text-muted">{{ t('admin.agent.testingInProgress') }}</div>
<template v-if="agentTestResult">
<div>
<div class="text-xs font-semibold text-muted uppercase tracking-wider mb-2">{{ t('admin.agent.requestUrl') }}</div>
<div class="admin-code-block">{{ agentTestResult.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">{{ agentTestResult.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="agentTestResult.success ? 'bg-green-50 border-green-200 text-green-800' : 'bg-red-50 border-red-200 text-red-800'"
>
{{ agentTestResult.analysis }}
<span v-if="agentTestResult.http_status">(HTTP {{ agentTestResult.http_status }})</span>
</div>
</div>
</template>
</div>
</div>
</div>
<!-- Test Run Dialog -->
<div v-if="showTestRunDialog" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-4xl max-h-[90vh] overflow-y-auto">
<div class="admin-modal-header sticky top-0 z-10 px-6 py-4 rounded-t-3xl">
<div>
<h3 class="text-lg font-bold text-primary">{{ $t('admin.schedule.testRun.title', { name: testRunSchedule?.name }) }}</h3>
<p class="text-xs text-muted mt-0.5">{{ $t('admin.schedule.testRun.subtitle') }}</p>
</div>
<button @click="showTestRunDialog = false" class="rounded-xl border border-default px-3 py-1.5 text-sm text-muted hover:bg-surface-soft">{{ $t('admin.schedule.testRun.close') }}</button>
</div>
<div class="p-6 space-y-4">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">基础查询 SQL (base_fetch_sql) — 只读</label>
<textarea
:value="testRunBaseFetchSql"
readonly
class="w-full min-h-[120px] rounded-xl border border-default bg-surface-soft p-3 text-xs leading-relaxed text-muted font-mono resize-y cursor-default"
></textarea>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">WHERE 条件 (fetch_where_conditions) — 可修改以测试不同筛选条件</label>
<textarea v-model="testRunWhere"
class="w-full min-h-[80px] rounded-xl border border-amber-200 bg-amber-50/30 p-3 text-xs leading-relaxed text-secondary font-mono focus:border-amber-300 focus:outline-none focus:ring-1 focus:ring-amber-200 resize-y"
></textarea>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">排序 (fetch_order_by)</label>
<input v-model="testRunOrderBy" class="w-full input-field px-3 py-2 text-xs font-mono text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">限制行数 (limit)</label>
<input type="number" v-model.number="testRunLimit" min="1" max="10" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
</div>
<div class="flex items-center gap-3">
<button
class="inline-flex items-center gap-1.5 rounded-xl bg-violet-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-violet-700 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="testRunLoading"
@click="handleTestRun"
>
{{ testRunLoading ? $t('admin.schedule.testRun.running') : $t('admin.schedule.testRun.start') }}
</button>
<span v-if="testRunLoading" class="text-xs text-muted">{{ $t('admin.schedule.testRun.waitingHint') }}</span>
</div>
<div v-if="testRunResult" class="space-y-4 mt-2">
<div class="flex items-center gap-4 rounded-xl border border-default bg-surface-soft/50 px-4 py-3">
<div class="text-center">
<div class="text-lg font-bold text-primary">{{ testRunResult.total_count }}</div>
<div class="text-[10px] text-muted">{{ $t('admin.schedule.testRun.total') }}</div>
</div>
<div class="text-center">
<div class="text-lg font-bold text-emerald-600">{{ testRunResult.success_count }}</div>
<div class="text-[10px] text-muted">{{ $t('admin.schedule.testRun.success') }}</div>
</div>
<div class="text-center">
<div class="text-lg font-bold text-rose-600">{{ testRunResult.failed_count }}</div>
<div class="text-[10px] text-muted">{{ $t('admin.schedule.testRun.failed') }}</div>
</div>
<div class="text-center">
<div class="text-lg font-bold text-amber-600">{{ testRunResult.skipped_count }}</div>
<div class="text-[10px] text-muted">{{ $t('admin.schedule.testRun.skipped') }}</div>
</div>
<div class="ml-auto text-xs text-muted">
{{ $t('admin.schedule.testRun.limitSummary', { limit: testRunResult.limit, agentId: testRunResult.dify_agent_id || $t('admin.schedule.testRun.noAgent') }) }}
</div>
</div>
<div
v-if="testRunResult.dify_execution_snapshot"
class="rounded-xl border border-indigo-200 bg-indigo-50/50 p-3"
>
<h4 class="mb-2 text-sm font-bold text-indigo-900">Dify 执行快照(审计)</h4>
<div v-if="testRunResult.dify_execution_snapshot.dify_enabled" class="space-y-2 text-xs text-secondary">
<div>
<span class="font-semibold text-muted">Agent:</span>
{{ testRunResult.dify_execution_snapshot.dify_agent_name || '-' }}
(ID: {{ testRunResult.dify_execution_snapshot.dify_agent_id ?? '-' }})
</div>
<div>
<span class="mb-1 block font-semibold text-muted">System Prompt:</span>
<pre
v-if="testRunResult.dify_execution_snapshot.dify_system_prompt"
class="max-h-[200px] overflow-auto whitespace-pre-wrap rounded-lg border border-indigo-100 bg-surface p-3 font-mono text-[11px] text-primary"
>{{ testRunResult.dify_execution_snapshot.dify_system_prompt }}</pre>
<span v-else class="text-muted">(未配置)</span>
</div>
</div>
<div v-else class="text-xs text-muted">本次测试未启用 Dify</div>
</div>
<div>
<h4 class="text-sm font-bold text-secondary mb-2">{{ $t('admin.schedule.testRun.stepLogs') }}</h4>
<div class="space-y-2">
<div
v-for="(log, li) in testRunResult.step_logs"
:key="li"
class="rounded-xl border p-3"
:class="log.status === 'failed' ? 'border-rose-200 bg-rose-50/40' : 'border-default bg-surface'"
>
<div class="flex items-center gap-2 mb-1">
<span class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold"
:class="(stepStatusMap[log.status] || stepStatusMap.success || { cls: 'bg-surface-soft text-secondary' }).cls">
{{ (stepStatusMap[log.status] || { label: log.status }).label }}
</span>
<span class="text-xs font-semibold text-secondary">{{ stepLabelMap[log.step] || log.step }}</span>
<span v-if="log.row_id" class="text-[10px] text-muted">row_id={{ log.row_id }}</span>
<span v-if="log.duration_ms != null" class="text-[10px] text-muted">{{ log.duration_ms }}ms</span>
</div>
<details v-if="log.detail" class="mt-1">
<summary class="cursor-pointer text-[10px] font-semibold text-muted hover:text-secondary">{{ $t('admin.schedule.viewDetail') }}</summary>
<pre class="admin-pre-block">{{ JSON.stringify(log.detail, null, 2) }}</pre>
</details>
</div>
</div>
</div>
<details>
<summary class="cursor-pointer text-xs font-semibold text-muted hover:text-secondary">{{ $t('admin.schedule.testRun.viewSql') }}</summary>
<pre class="admin-pre-block admin-pre-block--sql">{{ testRunResult.sql }}</pre>
</details>
<details v-if="testRunResult.errors && testRunResult.errors.length > 0">
<summary class="cursor-pointer text-xs font-semibold text-rose-600 hover:text-rose-800">{{ $t('admin.schedule.testRun.errors', { count: testRunResult.errors.length }) }}</summary>
<pre class="mt-1 whitespace-pre-wrap rounded-lg bg-rose-50 p-3 text-xs text-rose-700 font-mono">{{ testRunResult.errors.join('\n') }}</pre>
</details>
</div>
</div>
</div>
</div>
<!-- Schedule Create Modal -->
<div v-if="showScheduleCreateModal" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-3xl">
<div class="flex items-center justify-between border-b border-subtle px-8 py-6">
<h3 class="text-2xl font-bold tracking-tight text-primary">{{ scheduleEditingId ? $t('admin.schedule.form.editTitle') : $t('admin.schedule.form.createTitle') }}</h3>
<button
class="rounded-full p-2 text-muted transition hover-surface-soft hover:text-secondary"
@click="showScheduleCreateModal = false"
>
✕
</button>
</div>
<div class="max-h-[72vh] space-y-5 overflow-y-auto px-8 py-6">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.name') }}</label>
<input v-model="scheduleCreateForm.name" class="input-field !text-sm !leading-5" :placeholder="$t('admin.schedule.form.namePlaceholder')" />
</div>
<div>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.owner') }}</label>
<div class="relative">
<select v-model="scheduleCreateForm.owner_user_id" class="input-field appearance-none pr-10 !text-sm !leading-5" :disabled="users.length === 0">
<option :value="null">{{ users.length === 0 ? $t('admin.schedule.form.noUsers') : $t('admin.schedule.form.selectOwner') }}</option>
<option v-for="u in users" :key="u.id" :value="u.id">{{ u.real_name || u.username }}{{ u.employee_id ? '(' + u.employee_id + ')' : '' }}</option>
</select>
<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
<svg class="h-4 w-4 text-muted" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" clip-rule="evenodd"/></svg>
</div>
</div>
</div>
</div>
<!-- SQL Config Panel -->
<div class="rounded-2xl border border-default bg-surface-soft/40 p-4">
<div class="mb-3 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<h4 class="text-base font-bold text-primary shrink-0">{{ $t('admin.schedule.form.dataSourceConfig') }}</h4>
<div class="flex flex-wrap items-center gap-2">
<div
class="segment-control segment-control--fit segment-control--sm shrink-0"
role="radiogroup"
:aria-label="$t('admin.schedule.form.dataSourceConfig')"
>
<button
type="button"
role="radio"
:aria-checked="scheduleCreateForm.data_source_type === 'database'"
class="segment-item"
:class="scheduleCreateForm.data_source_type === 'database' ? 'segment-item--active' : ''"
@click="scheduleCreateForm.data_source_type = 'database'"
>{{ $t('admin.schedule.form.databaseDirect') }}</button>
<button
type="button"
role="radio"
:aria-checked="scheduleCreateForm.data_source_type === 'external_api'"
class="segment-item"
:class="scheduleCreateForm.data_source_type === 'external_api' ? 'segment-item--active' : ''"
@click="scheduleCreateForm.data_source_type = 'external_api'"
>{{ $t('admin.schedule.form.externalApi') }}</button>
</div>
<button
type="button"
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap disabled:cursor-not-allowed disabled:opacity-60"
:disabled="scheduleTestLoading || !scheduleEditingId"
@click="handleTestScheduleSql"
>
{{ scheduleTestLoading ? $t('admin.schedule.form.querying') : $t('admin.schedule.form.testQuery') }}
</button>
<button
type="button"
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap"
@click="scheduleConfigCollapsed = !scheduleConfigCollapsed"
>
<ChevronDown v-if="scheduleConfigCollapsed" class="h-3.5 w-3.5 shrink-0" />
<ChevronUp v-else class="h-3.5 w-3.5 shrink-0" />
{{ scheduleConfigCollapsed ? $t('admin.schedule.form.expandConfig') : $t('admin.schedule.form.collapseConfig') }}
</button>
</div>
</div>
<div v-show="!scheduleConfigCollapsed" class="space-y-3">
<!-- 数据库直联模式 -->
<template v-if="scheduleCreateForm.data_source_type === 'database'">
<!-- 数据源配置 -->
<details class="rounded-xl border border-default bg-surface" open>
<summary class="cursor-pointer px-4 py-2.5 text-sm font-semibold text-secondary hover:bg-surface-soft rounded-xl">{{ $t('admin.schedule.form.dataSourceSection') }}</summary>
<div class="space-y-3 px-4 pb-4 pt-2">
<div class="grid grid-cols-2 gap-3">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">数据库类型</label>
<select v-model="scheduleSqlEditForm.ds_db_type" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200">
<option value="sqlserver">SQL Server</option>
<option value="postgresql">PostgreSQL</option>
<option value="mysql">MySQL</option>
</select>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">主机地址</label>
<input v-model="scheduleSqlEditForm.ds_host" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" placeholder="如 192.168.1.100 或 ${SRM_SQLSERVER_HOST}" />
</div>
</div>
<div class="grid grid-cols-4 gap-3">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">端口</label>
<input v-model="scheduleSqlEditForm.ds_port" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" placeholder="1433" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">数据库</label>
<input v-model="scheduleSqlEditForm.ds_database" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" placeholder="数据库名" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">用户名</label>
<input v-model="scheduleSqlEditForm.ds_username" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" placeholder="sa" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">密码</label>
<input v-model="scheduleSqlEditForm.ds_password" type="password" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" placeholder="或 ${ENV_VAR}" />
</div>
</div>
<div v-if="scheduleSqlEditForm.ds_db_type === 'sqlserver'" class="grid grid-cols-3 gap-3">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">ODBC 驱动</label>
<input v-model="scheduleSqlEditForm.ds_driver" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" placeholder="SQL Server" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">Encrypt</label>
<select v-model="scheduleSqlEditForm.ds_encrypt" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200">
<option value="">默认 (no)</option>
<option value="yes">yes</option>
<option value="no">no</option>
</select>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">TrustServerCertificate</label>
<select v-model="scheduleSqlEditForm.ds_trust_cert" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200">
<option value="">默认 (yes)</option>
<option value="yes">yes</option>
<option value="no">no</option>
</select>
</div>
</div>
<p class="text-xs text-muted">值支持 <code class="rounded bg-surface-soft px-1 py-0.5 text-xs">${环境变量名}</code> 格式,运行时自动从环境变量解析(推荐密码使用此方式)</p>
</div>
</details>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">基础查询 SQL (base_fetch_sql) — SELECT + FROM + JOIN 部分,不含 WHERE</label>
<textarea
v-model="scheduleSqlEditForm.base_fetch_sql"
class="w-full min-h-[160px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">WHERE 条件 (fetch_where_conditions) — 可修改以测试不同筛选条件</label>
<textarea
v-model="scheduleSqlEditForm.fetch_where_conditions"
class="w-full min-h-[80px] rounded-xl border border-amber-200 bg-amber-50/30 p-3 text-xs leading-relaxed text-secondary font-mono focus:border-amber-300 focus:outline-none focus:ring-1 focus:ring-amber-200 resize-y"
></textarea>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">排序 (fetch_order_by)</label>
<input v-model="scheduleSqlEditForm.fetch_order_by" class="w-full input-field px-3 py-2 text-xs font-mono text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">明细 SQL (detail_sql)</label>
<textarea
v-model="scheduleSqlEditForm.detail_sql"
class="w-full min-h-[120px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">回写 SQL (writeback_sql)</label>
<textarea
v-model="scheduleSqlEditForm.writeback_sql"
class="w-full min-h-[48px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">主键字段 (row_id_key)</label>
<input v-model="scheduleSqlEditForm.row_id_key" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">日志前缀 (log_prefix)</label>
<input v-model="scheduleSqlEditForm.log_prefix" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
</div>
<div class="hidden">
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">字段顺序 (alias_order) — 逗号分隔</label>
<input v-model="scheduleSqlEditForm.alias_order_str" class="w-full input-field px-3 py-2 text-xs font-mono text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">明细字段顺序 (detail_alias_order) — 逗号分隔</label>
<input v-model="scheduleSqlEditForm.detail_alias_order_str" class="w-full input-field px-3 py-2 text-xs font-mono text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">表头标签 (header_labels) — JSON 格式</label>
<textarea
v-model="scheduleSqlEditForm.header_labels_str"
class="w-full min-h-[100px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
</template>
<!-- 外部API模式 -->
<template v-if="scheduleCreateForm.data_source_type === 'external_api'">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">API 地址</label>
<input v-model="scheduleSqlEditForm.api_url" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" placeholder="https://api.example.com/endpoint" />
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">请求方法</label>
<select v-model="scheduleSqlEditForm.api_method" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200">
<option value="POST">POST</option>
<option value="GET">GET</option>
<option value="PUT">PUT</option>
</select>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">超时(秒)</label>
<input type="number" :value="120" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" disabled />
</div>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">请求头 (Headers) — JSON 格式</label>
<textarea
v-model="scheduleSqlEditForm.api_headers_str"
class="w-full min-h-[60px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">请求体模板 (Body)</label>
<textarea
v-model="scheduleSqlEditForm.api_body_template"
class="w-full min-h-[80px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
</template>
</div>
<div v-if="scheduleTestResult" class="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
<div class="mb-3 flex items-center justify-between">
<h4 class="text-sm font-bold text-emerald-900">{{ $t('admin.schedule.testRun.queryResult') }}</h4>
<div class="flex items-center gap-3">
<span class="text-xs text-emerald-600">{{ $t('admin.schedule.testRun.resultSummary', { total: scheduleTestResult.total, showing: scheduleTestResult.showing }) }}</span>
<button class="rounded-full p-1 text-emerald-400 transition hover:bg-emerald-100 hover:text-emerald-600" @click="scheduleTestResult = null">✕</button>
</div>
</div>
<div class="mb-2 overflow-x-auto rounded-xl border border-emerald-200 bg-surface">
<table class="w-full text-xs">
<thead class="bg-emerald-50">
<tr>
<th v-for="col in scheduleTestResult.columns" :key="col" class="whitespace-nowrap px-3 py-2 text-left font-semibold text-emerald-800">{{ col }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in scheduleTestResult.rows" :key="ri" class="border-t border-emerald-100">
<td v-for="col in scheduleTestResult.columns" :key="col" class="whitespace-nowrap px-3 py-1.5 text-secondary">{{ row[col] }}</td>
</tr>
</tbody>
</table>
</div>
<details class="mt-2">
<summary class="cursor-pointer text-xs font-semibold text-emerald-700 hover:text-emerald-900">{{ $t('admin.schedule.testRun.viewGeneratedSql') }}</summary>
<pre class="admin-pre-block admin-pre-block--sql">{{ scheduleTestResult.sql }}</pre>
</details>
</div>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label class="mb-2 block text-sm font-medium text-secondary">Agent</label>
<div class="relative">
<select v-model="scheduleCreateForm.dify_agent_id" class="input-field appearance-none pr-10 !text-sm !leading-5" :disabled="agents.length === 0">
<option :value="null">{{ agents.length === 0 ? $t('admin.schedule.form.noAgents') : $t('admin.schedule.form.agentDisabled') }}</option>
<option v-for="a in agents" :key="a.id" :value="a.id">{{ a.name }}(ID: {{ a.dify_app_id?.slice(0, 8) || a.id }})</option>
</select>
<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
<svg class="h-4 w-4 text-muted" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" clip-rule="evenodd"/></svg>
</div>
</div>
</div>
<div>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.waitSeconds') }}</label>
<input v-model.number="scheduleCreateForm.wait_seconds" type="number" min="0" class="input-field !text-sm !leading-5" placeholder="300" />
</div>
</div>
<div v-if="scheduleCreateForm.dify_agent_id" class="rounded-2xl border border-indigo-200 bg-indigo-50/40 p-4">
<div class="mb-2">
<label class="block text-sm font-medium text-secondary">Dify System Prompt</label>
<p class="mt-1 text-xs text-muted">仅在启用 Dify Agent 时可配置。保存后将作为 <code class="rounded bg-surface-soft px-1 py-0.5 text-indigo-700">system_prompt</code> 传入 Workflow;编排中 LLM 节点需引用该变量。</p>
</div>
<textarea
v-model="scheduleSqlEditForm.dify_system_prompt"
class="input-field min-h-[140px] p-3 text-sm font-mono resize-y border-indigo-200"
placeholder="例如:你是物料合规判定助手。根据 record 中的检测数据判定是否合格,仅返回 JSON:dify_result(合格/不合格/人工判定)与 dify_message。"
></textarea>
</div>
<div class="rounded-2xl border border-default bg-surface-soft/40 p-4">
<div class="mb-3">
<h4 class="text-base font-bold text-primary">{{ $t('admin.schedule.form.cronTitle') }}</h4>
<p class="text-sm text-muted">{{ $t('admin.schedule.form.cronHint') }}</p>
</div>
<div
class="segment-control segment-control--cols-4 segment-control--sm"
role="radiogroup"
:aria-label="$t('admin.schedule.form.cronTitle')"
>
<button
type="button"
role="radio"
:aria-checked="scheduleCronDesigner.mode === 'every_minutes'"
class="segment-item"
:class="scheduleCronDesigner.mode === 'every_minutes' ? 'segment-item--active' : ''"
@click="scheduleCronDesigner.mode = 'every_minutes'"
>
{{ $t('admin.schedule.form.everyMinutes') }}
</button>
<button
type="button"
role="radio"
:aria-checked="scheduleCronDesigner.mode === 'hourly'"
class="segment-item"
:class="scheduleCronDesigner.mode === 'hourly' ? 'segment-item--active' : ''"
@click="scheduleCronDesigner.mode = 'hourly'"
>
{{ $t('admin.schedule.form.hourly') }}
</button>
<button
type="button"
role="radio"
:aria-checked="scheduleCronDesigner.mode === 'daily'"
class="segment-item"
:class="scheduleCronDesigner.mode === 'daily' ? 'segment-item--active' : ''"
@click="scheduleCronDesigner.mode = 'daily'"
>
{{ $t('admin.schedule.form.daily') }}
</button>
<button
type="button"
role="radio"
:aria-checked="scheduleCronDesigner.mode === 'weekly'"
class="segment-item"
:class="scheduleCronDesigner.mode === 'weekly' ? 'segment-item--active' : ''"
@click="scheduleCronDesigner.mode = 'weekly'"
>
{{ $t('admin.schedule.form.weekly') }}
</button>
</div>
<div class="mt-4 grid grid-cols-1 gap-3 md:grid-cols-3">
<template v-if="scheduleCronDesigner.mode === 'every_minutes'">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.minuteInterval') }}</label>
<input v-model.number="scheduleCronDesigner.every_minutes" type="number" min="1" max="59" class="input-field !text-sm !leading-5" />
</div>
</template>
<template v-else-if="scheduleCronDesigner.mode === 'hourly'">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.minuteOfHour') }}</label>
<input v-model.number="scheduleCronDesigner.hourly_minute" type="number" min="0" max="59" class="input-field !text-sm !leading-5" />
</div>
</template>
<template v-else-if="scheduleCronDesigner.mode === 'daily'">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.hour') }}</label>
<input v-model.number="scheduleCronDesigner.daily_hour" type="number" min="0" max="23" class="input-field !text-sm !leading-5" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.minute') }}</label>
<input v-model.number="scheduleCronDesigner.daily_minute" type="number" min="0" max="59" class="input-field !text-sm !leading-5" />
</div>
</template>
<template v-else>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.weekday') }}</label>
<select v-model.number="scheduleCronDesigner.weekly_day" class="input-field !text-sm !leading-5">
<option v-for="d in weeklyDayOptions" :key="d.value" :value="d.value">{{ d.label }}</option>
</select>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.hour') }}</label>
<input v-model.number="scheduleCronDesigner.weekly_hour" type="number" min="0" max="23" class="input-field !text-sm !leading-5" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.minute') }}</label>
<input v-model.number="scheduleCronDesigner.weekly_minute" type="number" min="0" max="59" class="input-field !text-sm !leading-5" />
</div>
</template>
</div>
<div class="mt-4 rounded-xl border border-dashed border-default bg-surface-soft px-4 py-3 text-xs text-secondary">
{{ $t('admin.schedule.form.cronPreview') }}:<span class="font-mono text-primary">{{ scheduleCronPreview }}</span>
<span v-if="scheduleNextRunPreview" class="ml-4">{{ $t('admin.schedule.form.nextRun') }}:<span class="font-medium text-primary">{{ formatDateTime(scheduleNextRunPreview.toISOString()) }}</span></span>
</div>
</div>
<div class="input-field px-3 py-2.5">
<div class="flex flex-col gap-2 md:flex-row md:items-center">
<label class="inline-flex shrink-0 items-center gap-2 text-sm text-secondary">
<input v-model="scheduleCreateForm.notify_enabled" type="checkbox" class="h-4 w-4 rounded text-blue-600" />
{{ $t('admin.schedule.form.notifyEnabled') }}
</label>
<div v-if="scheduleCreateForm.notify_enabled" class="relative flex-1">
<div
class="min-h-[38px] cursor-pointer input-field px-3 py-2 text-sm flex flex-wrap gap-1.5 items-center focus-within:border-blue-300 focus-within:ring-1 focus-within:ring-blue-200"
@click="scheduleNotifyDropdownOpen = !scheduleNotifyDropdownOpen"
>
<template v-if="scheduleCreateForm.notify_user_ids_json.length > 0">
<span
v-for="uid in scheduleCreateForm.notify_user_ids_json"
:key="uid"
class="inline-flex items-center gap-1 rounded-lg bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700"
>
{{ getUserName(uid) }}
<button
class="ml-0.5 text-blue-400 hover:text-blue-600"
@click.stop="removeNotifyUser(uid)"
>✕</button>
</span>
</template>
<span v-else class="text-muted">{{ $t('admin.schedule.form.selectNotifyUsers') }}</span>
</div>
<div
v-if="scheduleNotifyDropdownOpen"
class="admin-dropdown w-full"
>
<div
v-for="u in users"
:key="u.id"
class="flex cursor-pointer items-center gap-2 px-3 py-2 text-sm transition hover:bg-surface-soft"
:class="scheduleCreateForm.notify_user_ids_json.includes(u.id) ? 'bg-blue-50/50' : ''"
@click="toggleNotifyUser(u.id)"
>
<input
type="checkbox"
class="h-3.5 w-3.5 rounded text-blue-600"
:checked="scheduleCreateForm.notify_user_ids_json.includes(u.id)"
@click.stop
@change.stop="toggleNotifyUser(u.id)"
readonly
/>
<span class="text-secondary">{{ u.real_name || u.username }}{{ u.employee_id ? '(' + u.employee_id + ')' : '' }}</span>
</div>
</div>
</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-surface-soft/40 px-4 py-3">
<label class="inline-flex cursor-pointer items-center gap-2 text-sm text-secondary">
<input v-model="scheduleCreateForm.enabled" type="checkbox" class="admin-checkbox" />
{{ $t('admin.schedule.form.enableOnCreate') }}
</label>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted justify-end gap-3 px-8 py-5">
<button
type="button"
class="btn-secondary"
@click="showScheduleCreateModal = false"
>
{{ $t('admin.schedule.form.cancel') }}
</button>
<button
type="button"
class="btn-primary inline-flex items-center gap-2 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="scheduleCreateSaving || !scheduleCreateForm.name || !scheduleCreateForm.owner_user_id"
@click="createSchedule"
>
<Plus class="h-4 w-4 shrink-0" />
{{ scheduleCreateSaving ? $t('admin.schedule.form.saving') : (scheduleEditingId ? $t('admin.schedule.form.saveChanges') : $t('admin.schedule.form.createSchedule')) }}
</button>
</div>
</div>
</div>
<!-- Agent Permission Modal -->
<div v-if="showAgentPermissionModal && selectedAgentForPermissions" 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">{{ selectedAgentForPermissions.name }}</span></p>
</div>
<button @click="showAgentPermissionModal = false" class="btn-icon-ds rounded-full">
<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 activeUsers"
:key="user.id"
class="flex items-center gap-3 p-3 rounded-xl border transition-all cursor-pointer"
:class="agentPermissionUserIds.includes(user.id) ? 'border-blue-200 bg-blue-50/50' : 'border-default hover-surface-soft'"
@click="toggleAgentPermission(user.id)"
>
<div
class="w-5 h-5 rounded border flex items-center justify-center transition-colors"
:class="agentPermissionUserIds.includes(user.id) ? 'bg-blue-600 border-blue-600' : 'bg-surface border-default'"
>
<svg v-if="agentPermissionUserIds.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
@click="showAgentPermissionModal = false"
class="btn-ghost"
>
{{ t('admin.cancel') }}
</button>
<button
@click="saveAgentPermissions"
:disabled="isSaving"
class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
>
<div v-if="isSaving" class="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"></div>
{{ t('admin.perm.agentModal.save') }}
</button>
</div>
</div>
</div>
<!-- Batch Edit User Modal -->
<div v-if="showBatchEditModal" 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: selectedUserIds.length }) }}</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="batchEditForm.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="batchEditForm.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="batchEditForm.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 @click="showBatchEditModal = false" class="btn-ghost">{{ t('admin.cancel') }}</button>
<button @click="submitBatchEdit" :disabled="isSaving" class="btn-primary disabled:opacity-50">
{{ isSaving ? t('admin.save') + '...' : t('admin.batchEdit.update') }}
</button>
</div>
</div>
</div>
<!-- Batch Permission Modal -->
<div v-if="showBatchPermissionModal" 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: selectedUserIds.length }) }}</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 type="radio" v-model="batchPermissionForm.action" 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 type="radio" v-model="batchPermissionForm.action" 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 type="radio" v-model="batchPermissionForm.action" 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="batchPermissionForm.agent_ids.includes(agent.id) ? 'border-blue-500 bg-blue-50' : ''"
>
<input
type="checkbox"
:value="agent.id"
v-model="batchPermissionForm.agent_ids"
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 @click="showBatchPermissionModal = false" class="btn-ghost">{{ t('admin.cancel') }}</button>
<button @click="submitBatchPermission" :disabled="isSaving" class="btn-primary disabled:opacity-50">
{{ isSaving ? t('admin.save') + '...' : t('admin.perm.batchModal.apply') }}
</button>
</div>
</div>
</div>
<!-- Department Management Modal -->
<div v-if="isManagingDepts" class="admin-modal-overlay items-center animate-fade-in">
<div class="admin-modal-panel max-w-lg p-6 animate-fade-in-up">
<h3 class="section-title mb-6">{{ t('admin.user.manageDepts') }}</h3>
<div class="flex gap-2 mb-6">
<input
v-model="editingDept.name"
:placeholder="t('admin.dept.fields.name')"
class="input-field flex-1 text-sm"
@keyup.enter="saveDepartment"
/>
<button
@click="saveDepartment"
class="btn-primary btn-sm"
>
{{ t('admin.add') }}
</button>
</div>
<div class="max-h-[50vh] overflow-y-auto border border-subtle rounded-xl divide-y divide-subtle bg-surface-soft/50">
<div v-if="departments.length === 0" class="p-8 text-center text-muted text-sm">{{ t('admin.dept.noDepts') }}</div>
<div v-for="d in departments" :key="d.id" class="p-3 flex justify-between items-center hover-surface-soft transition-colors group">
<span class="text-sm font-medium text-secondary ml-2">{{ d.name }}</span>
<button
@click="deleteDepartment(d.id)"
class="text-muted hover:text-red-500 hover:bg-red-50 p-1.5 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
:title="t('admin.delete')"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</div>
<div class="mt-6 flex justify-end">
<button
@click="isManagingDepts = false"
class="btn-ghost"
>
{{ t('admin.close') }}
</button>
</div>
</div>
</div>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:title="deleteConfirmTitle"
:message="deleteConfirmMessage"
:confirm-loading="deleteConfirmLoading"
@confirm="handleDeleteConfirm"
@cancel="closeDeleteConfirmDialog"
/>
</div>
</template>