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

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

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,972 @@
/**
* features/admin/modules/schedules/composables/useSchedulesAdmin.ts
* 定时任务管理:概览、工作台、创建/编辑、试运行。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { listAdminAgents, listAdminUsers } from '@/api/admin';
import {
createAdminSchedule,
deleteAdminSchedule,
getAdminScheduleTaskConfig,
listAdminScheduleRuns,
listAdminSchedules,
runAdminSchedule,
testAdminScheduleRun,
testAdminScheduleSql,
toggleAdminSchedule,
updateAdminSchedule,
type ScheduleRun,
type ScheduleTask,
type TestScheduleRunResult,
} from '@/api/schedule';
import { useMessage } from '@/composables/useMessage';
import { getAuthHeaders } from '@/utils/auth';
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
export function useSchedulesAdmin() {
const { t, locale } = useI18n();
const msg = useMessage();
const agents = ref<AdminAgentOption[]>([]);
const users = ref<AdminUserRow[]>([]);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmTitle = ref('');
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const openDeleteConfirm = (
message: string,
onConfirm: () => Promise<void> | void,
title = '',
): void => {
deleteConfirmTitle.value = title;
deleteConfirmMessage.value = message;
deleteConfirmAction = onConfirm;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmTitle.value = '';
deleteConfirmMessage.value = '';
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const loadAgents = async (): Promise<void> => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Failed to load agents', e);
agents.value = [];
}
};
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const schedules = ref<ScheduleTask[]>([]);
const schedulesLoaded = ref(false); void schedulesLoaded;
const selectedScheduleRuns = ref<ScheduleRun[]>([]);
const scheduleLoading = ref(false);
const scheduleRunsLoading = ref(false);
const selectedScheduleId = ref<number | null>(null);
const scheduleRunStatusFilter = ref<'all' | string>('all');
const scheduleRunStartedAfter = ref('');
const scheduleRunStartedBefore = ref('');
const scheduleRunColumnDefs = ref([
{ key: 'run_no', label: '', width: 280, min: 60 },
{ key: 'started_at', label: '', width: 190, min: 60 },
{ key: 'finished_at', label: '', width: 190, min: 60 },
{ key: 'status', label: '', width: 130, min: 50 },
{ key: 'total_count', label: '', width: 70, min: 40 },
{ key: 'success_count', label: '', width: 70, min: 40 },
{ key: 'failed_count', label: '', width: 70, min: 40 },
{ key: 'wecom_notified', label: '', width: 100, min: 80 },
{ key: 'detail', label: '', width: 100, min: 80 },
{ key: 'log', label: '', width: 100, min: 80 },
]);
const syncScheduleRunColumnLabels = () => {
const keyToI18n: Record<string, string> = {
run_no: 'runNo',
started_at: 'startedAt',
finished_at: 'finishedAt',
status: 'status',
total_count: 'totalCount',
success_count: 'successCount',
failed_count: 'failedCount',
wecom_notified: 'wecomNotified',
detail: 'detail',
log: 'log',
};
scheduleRunColumnDefs.value.forEach((col) => {
const i18nKey = keyToI18n[col.key];
if (i18nKey) col.label = t(`admin.schedule.columns.${i18nKey}`);
});
};
watch(locale, syncScheduleRunColumnLabels, { immediate: true });
const resizingScheduleCol = ref<{ index: number; startX: number; startWidth: number } | null>(null);
const onScheduleColResizeMove = (event: MouseEvent) => {
const state = resizingScheduleCol.value;
if (!state) return;
const def = scheduleRunColumnDefs.value[state.index];
if (!def) return;
const delta = event.clientX - state.startX;
def.width = Math.max(def.min, state.startWidth + delta);
};
const stopScheduleColResize = () => {
if (!resizingScheduleCol.value) return;
resizingScheduleCol.value = null;
window.removeEventListener('mousemove', onScheduleColResizeMove);
window.removeEventListener('mouseup', stopScheduleColResize);
};
const startScheduleColResize = (index: number, event: MouseEvent) => {
const def = scheduleRunColumnDefs.value[index];
if (!def) return;
resizingScheduleCol.value = {
index,
startX: event.clientX,
startWidth: def.width,
};
window.addEventListener('mousemove', onScheduleColResizeMove);
window.addEventListener('mouseup', stopScheduleColResize);
};
const scheduleViewMode = ref<'overview' | 'workbench'>('overview');
const showScheduleCreateModal = ref(false);
const scheduleCreateSaving = ref(false);
const scheduleEditingId = ref<number | null>(null);
const scheduleCreateForm = ref({
name: '',
platform_api_path: '',
data_source_type: 'database' as 'database' | 'external_api',
dify_agent_id: null as number | null,
owner_user_id: null as number | null,
wait_seconds: 300,
notify_enabled: true,
notify_user_ids_json: [] as number[],
enabled: true,
});
const scheduleConfigCollapsed = ref(true);
const scheduleCronDesigner = ref({
mode: 'every_minutes' as 'every_minutes' | 'hourly' | 'daily' | 'weekly',
every_minutes: 30,
hourly_minute: 0,
daily_hour: 9,
daily_minute: 0,
weekly_day: 1,
weekly_hour: 9,
weekly_minute: 0,
});
const weeklyDayOptions = computed(() => [
{ value: 1, label: t('admin.schedule.weekday.mon') },
{ value: 2, label: t('admin.schedule.weekday.tue') },
{ value: 3, label: t('admin.schedule.weekday.wed') },
{ value: 4, label: t('admin.schedule.weekday.thu') },
{ value: 5, label: t('admin.schedule.weekday.fri') },
{ value: 6, label: t('admin.schedule.weekday.sat') },
{ value: 0, label: t('admin.schedule.weekday.sun') },
]);
const buildCronExprFromDesigner = () => {
const cfg = scheduleCronDesigner.value;
if (cfg.mode === 'every_minutes') {
const every = Math.max(1, Math.min(59, Number(cfg.every_minutes || 30)));
return `*/${every} * * * *`;
}
if (cfg.mode === 'hourly') {
const minute = Math.max(0, Math.min(59, Number(cfg.hourly_minute || 0)));
return `${minute} * * * *`;
}
if (cfg.mode === 'daily') {
const minute = Math.max(0, Math.min(59, Number(cfg.daily_minute || 0)));
const hour = Math.max(0, Math.min(23, Number(cfg.daily_hour || 0)));
return `${minute} ${hour} * * *`;
}
const minute = Math.max(0, Math.min(59, Number(cfg.weekly_minute || 0)));
const hour = Math.max(0, Math.min(23, Number(cfg.weekly_hour || 0)));
const day = Number(cfg.weekly_day);
return `${minute} ${hour} * * ${Number.isNaN(day) ? 1 : day}`;
};
const scheduleCronPreview = computed(() => buildCronExprFromDesigner());
const scheduleNextRunPreview = computed(() => {
const expr = scheduleCronPreview.value;
if (!expr) return null;
try {
const parts = expr.trim().split(/\s+/);
if (parts.length !== 5) return null;
const now = new Date();
const minuteRaw = parts[0]!;
const hourRaw = parts[1]!;
const dayOfMonth = parts[2]!;
const month = parts[3]!;
const dayOfWeek = parts[4]!;
if (month !== '*') return null;
if (dayOfMonth !== '*' && dayOfWeek !== '*') return null;
const minute = minuteRaw.startsWith('*/') ? undefined : parseInt(minuteRaw, 10);
const hour = hourRaw === '*' ? undefined : parseInt(hourRaw, 10);
if (minuteRaw.startsWith('*/')) {
const every = parseInt(minuteRaw.replace('*/', ''), 10);
const next = new Date(now);
next.setSeconds(0, 0);
const mod = next.getMinutes() % every;
next.setMinutes(next.getMinutes() + (every - mod));
if (next <= now) next.setMinutes(next.getMinutes() + every);
return next;
}
if (minute !== undefined && hour === undefined) {
const next = new Date(now);
next.setMinutes(minute, 0, 0);
if (next <= now) next.setHours(next.getHours() + 1);
return next;
}
if (minute !== undefined && hour !== undefined) {
const next = new Date(now);
next.setHours(hour, minute, 0, 0);
if (next <= now) {
if (dayOfWeek !== '*') {
const dow = parseInt(dayOfWeek, 10);
const currentDow = next.getDay();
let diff = dow - currentDow;
if (diff <= 0) diff += 7;
next.setDate(next.getDate() + diff);
} else {
next.setDate(next.getDate() + 1);
}
} else if (dayOfWeek !== '*') {
const dow = parseInt(dayOfWeek, 10);
const target = new Date(next);
const currentDow = target.getDay();
let diff = dow - currentDow;
if (diff < 0) diff += 7;
if (diff > 0) target.setDate(target.getDate() + diff);
if (target <= now) {
target.setDate(target.getDate() + 7);
}
return target;
}
return next;
}
return null;
} catch {
return null;
}
});
const parseCronExprToDesigner = (expr: string | null | undefined) => {
const text = String(expr || '').trim();
const parts = text.split(/\s+/);
if (parts.length !== 5) {
scheduleCronDesigner.value = {
mode: 'every_minutes',
every_minutes: 30,
hourly_minute: 0,
daily_hour: 9,
daily_minute: 0,
weekly_day: 1,
weekly_hour: 9,
weekly_minute: 0,
};
return;
}
const m = parts[0] ?? '';
const h = parts[1] ?? '';
const dow = parts[4] ?? '';
if (/^\*\/\d+$/.test(m) && h === '*' && dow === '*') {
scheduleCronDesigner.value.mode = 'every_minutes';
scheduleCronDesigner.value.every_minutes = Number(m.replace('*/', '')) || 30;
return;
}
if (/^\d+$/.test(m) && h === '*' && dow === '*') {
scheduleCronDesigner.value.mode = 'hourly';
scheduleCronDesigner.value.hourly_minute = Number(m) || 0;
return;
}
if (/^\d+$/.test(m) && /^\d+$/.test(h) && dow === '*') {
scheduleCronDesigner.value.mode = 'daily';
scheduleCronDesigner.value.daily_hour = Number(h) || 0;
scheduleCronDesigner.value.daily_minute = Number(m) || 0;
return;
}
if (/^\d+$/.test(m) && /^\d+$/.test(h) && /^\d+$/.test(dow)) {
scheduleCronDesigner.value.mode = 'weekly';
scheduleCronDesigner.value.weekly_hour = Number(h) || 0;
scheduleCronDesigner.value.weekly_minute = Number(m) || 0;
scheduleCronDesigner.value.weekly_day = Number(dow);
return;
}
scheduleCronDesigner.value.mode = 'every_minutes';
scheduleCronDesigner.value.every_minutes = 30;
};
const resetScheduleCreateForm = () => {
scheduleEditingId.value = null;
scheduleCreateForm.value = {
name: '',
platform_api_path: '',
data_source_type: 'database',
dify_agent_id: null,
owner_user_id: null,
wait_seconds: 300,
notify_enabled: true,
notify_user_ids_json: [],
enabled: true,
};
scheduleSqlEditForm.value = {
base_fetch_sql: '',
fetch_where_conditions: '',
fetch_order_by: '',
detail_sql: '',
writeback_sql: '',
row_id_key: 'id',
log_prefix: '',
alias_order_str: '',
detail_alias_order_str: '',
header_labels_str: '{}',
ds_db_type: 'sqlserver',
ds_host: '',
ds_port: '',
ds_database: '',
ds_username: '',
ds_password: '',
ds_driver: '',
ds_encrypt: '',
ds_trust_cert: '',
api_url: '',
api_method: 'POST',
api_headers_str: '{}',
api_body_template: '',
dify_system_prompt: '',
};
scheduleTestResult.value = null;
scheduleCronDesigner.value = {
mode: 'every_minutes',
every_minutes: 30,
hourly_minute: 0,
daily_hour: 9,
daily_minute: 0,
weekly_day: 1,
weekly_hour: 9,
weekly_minute: 0,
};
};
const openScheduleCreateModal = async () => {
resetScheduleCreateForm();
scheduleConfigCollapsed.value = true;
await Promise.all([loadAgents(), loadUsers()]);
showScheduleCreateModal.value = true;
};
const openScheduleEditModal = async (task: ScheduleTask) => {
await Promise.all([loadAgents(), loadUsers()]);
scheduleConfigCollapsed.value = true;
scheduleEditingId.value = task.id;
scheduleCreateForm.value = {
name: task.name || '',
platform_api_path: task.platform_api_path || '',
dify_agent_id: task.dify_agent_id || null,
owner_user_id: task.owner_user_id || null,
wait_seconds: task.wait_seconds || 0,
notify_enabled: !!task.notify_enabled,
notify_user_ids_json: task.notify_user_ids_json || [],
enabled: !!task.enabled,
data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api',
};
try {
const result = await getAdminScheduleTaskConfig(task.id);
const cfg = result.config;
scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as 'database' | 'external_api';
if (cfg) {
scheduleSqlEditForm.value = {
base_fetch_sql: cfg.base_fetch_sql || '',
fetch_where_conditions: cfg.fetch_where_conditions || '',
fetch_order_by: cfg.fetch_order_by || '',
detail_sql: cfg.detail_sql || '',
writeback_sql: cfg.writeback_sql || '',
row_id_key: cfg.row_id_key || 'id',
log_prefix: cfg.log_prefix || '',
alias_order_str: (cfg.alias_order || []).join(','),
detail_alias_order_str: (cfg.detail_alias_order || []).join(','),
header_labels_str: cfg.header_labels ? JSON.stringify(cfg.header_labels, null, 2) : '{}',
ds_db_type: cfg.data_source?.db_type || 'sqlserver',
ds_host: cfg.data_source?.host || '',
ds_port: cfg.data_source?.port || '',
ds_database: cfg.data_source?.database || '',
ds_username: cfg.data_source?.username || '',
ds_password: cfg.data_source?.password || '',
ds_driver: cfg.data_source?.driver || '',
ds_encrypt: cfg.data_source?.encrypt || '',
ds_trust_cert: cfg.data_source?.trust_cert || '',
api_url: cfg.external_api?.url || '',
api_method: cfg.external_api?.method || 'POST',
api_headers_str: cfg.external_api?.headers ? JSON.stringify(cfg.external_api.headers, null, 2) : '{}',
api_body_template: cfg.external_api?.body_template || '',
dify_system_prompt: cfg.dify_system_prompt || '',
};
}
} catch {
scheduleSqlEditForm.value = {
base_fetch_sql: '',
fetch_where_conditions: '',
fetch_order_by: '',
detail_sql: '',
writeback_sql: '',
row_id_key: 'id',
log_prefix: '',
alias_order_str: '',
detail_alias_order_str: '',
header_labels_str: '{}',
ds_db_type: 'sqlserver',
ds_host: '',
ds_port: '',
ds_database: '',
ds_username: '',
ds_password: '',
ds_driver: '',
ds_encrypt: '',
ds_trust_cert: '',
api_url: '',
api_method: 'POST',
api_headers_str: '{}',
api_body_template: '',
dify_system_prompt: '',
};
}
scheduleTestResult.value = null;
parseCronExprToDesigner(task.cron_expr);
showScheduleCreateModal.value = true;
};
const selectedSchedule = computed(() =>
schedules.value.find((item) => item.id === selectedScheduleId.value) || null
);
const scheduleRunStatusOptions = computed(() => [
{ value: 'all', label: t('admin.schedule.status.all') },
{ value: 'success', label: t('admin.schedule.status.success') },
{ value: 'partial_failed', label: t('admin.schedule.status.partialFailed') },
{ value: 'failed', label: t('admin.schedule.status.failed') },
{ value: 'running', label: t('admin.schedule.status.running') },
]);
const getScheduleRunStatusBadge = (status: string) => {
const map: Record<string, { cls: string; label: string }> = {
success: { cls: 'bg-emerald-100 text-emerald-700', label: t('admin.schedule.status.success') },
partial_failed: { cls: 'bg-blue-100 text-blue-700', label: t('admin.schedule.status.partialFailed') },
failed: { cls: 'bg-rose-100 text-rose-700', label: t('admin.schedule.status.failed') },
running: { cls: 'bg-amber-100 text-amber-700', label: t('admin.schedule.status.running') },
queued: { cls: 'bg-surface-soft text-secondary', label: t('admin.schedule.status.queued') },
};
return map[status] || { cls: 'bg-surface-soft text-secondary', label: status };
};
const formatDateTime = (iso?: string | null) => {
if (!iso) return '-';
const d = new Date(iso);
if (isNaN(d.getTime())) return iso;
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};
const expandedScheduleRunId = ref<number | null>(null);
const expandedScheduleRun = computed(() => {
if (!expandedScheduleRunId.value) return null;
return filteredScheduleRuns.value.find((x) => x.id === expandedScheduleRunId.value) || null;
});
const stepLabelMap: Record<string, string> = {
fetch_srm: t('admin.schedule.step.fetchSrm'),
call_dify: t('admin.schedule.step.callDify'),
writeback_srm: t('admin.schedule.step.writebackSrm'),
call_internal_api: t('admin.schedule.step.callInternalApi'),
pre_dify: t('admin.schedule.step.preDify'),
};
const stepStatusMap: Record<string, { cls: string; label: string }> = {
success: { cls: 'bg-emerald-100 text-emerald-700', label: t('admin.schedule.status.success') },
failed: { cls: 'bg-rose-100 text-rose-700', label: t('admin.schedule.status.failed') },
};
const showTestRunDialog = ref(false);
const testRunSchedule = ref<ScheduleTask | null>(null);
const testRunWhere = ref('');
const testRunOrderBy = ref('');
const testRunBaseFetchSql = ref('');
const testRunLimit = ref(3);
const testRunLoading = ref(false);
const testRunResult = ref<TestScheduleRunResult | null>(null);
const openTestRunDialog = async (s: ScheduleTask) => {
testRunSchedule.value = s;
try {
const result = await getAdminScheduleTaskConfig(s.id);
const cfg = result.config;
testRunWhere.value = cfg?.fetch_where_conditions || '';
testRunOrderBy.value = cfg?.fetch_order_by || '';
testRunBaseFetchSql.value = cfg?.base_fetch_sql || '';
} catch {
testRunWhere.value = '';
testRunOrderBy.value = '';
testRunBaseFetchSql.value = '';
}
testRunLimit.value = 3;
testRunResult.value = null;
testRunLoading.value = false;
showTestRunDialog.value = true;
};
const handleTestRun = async () => {
const s = testRunSchedule.value;
if (!s?.id) return;
testRunLoading.value = true;
testRunResult.value = null;
try {
const result = await testAdminScheduleRun(s.id, {
fetch_where_conditions: testRunWhere.value,
fetch_order_by: testRunOrderBy.value,
limit: testRunLimit.value,
});
testRunResult.value = result;
await loadSchedules();
if (s.id) {
await viewScheduleRuns(s.id);
}
} catch (e: any) {
msg.error(`${t('admin.schedule.msg.testRunFailed')}: ${e?.message || e}`);
} finally {
testRunLoading.value = false;
}
};
const filteredScheduleRuns = computed(() => {
if (scheduleRunStatusFilter.value === 'all') return selectedScheduleRuns.value;
return selectedScheduleRuns.value.filter((item) => item.status === scheduleRunStatusFilter.value);
});
const selectedScheduleRunMetrics = computed(() => {
const runs = selectedScheduleRuns.value;
return runs.reduce(
(acc, item) => {
acc.total += item.total_count || 0;
acc.success += item.success_count || 0;
acc.failed += item.failed_count || 0;
return acc;
},
{ total: 0, success: 0, failed: 0 }
);
});
const selectedScheduleLatestRunAt = computed(
() => selectedScheduleRuns.value[0]?.started_at || selectedSchedule.value?.last_run_at || '-'
);
const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length);
const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length);
const scheduleRunningCount = computed(() => schedules.value.filter((item) => item.last_status === 'running').length);
const loadSchedules = async () => {
scheduleLoading.value = true;
try {
schedules.value = await listAdminSchedules();
if (schedules.value.length === 0) {
selectedScheduleId.value = null;
selectedScheduleRuns.value = [];
scheduleViewMode.value = 'overview';
return;
}
const exists = selectedScheduleId.value && schedules.value.some((item) => item.id === selectedScheduleId.value);
const nextScheduleId = exists && selectedScheduleId.value ? selectedScheduleId.value : schedules.value[0]?.id ?? null;
if (!exists && nextScheduleId) {
selectedScheduleId.value = nextScheduleId;
}
if (scheduleViewMode.value === 'workbench' && nextScheduleId) {
await viewScheduleRuns(nextScheduleId);
}
} finally {
scheduleLoading.value = false;
}
};
const scheduleSqlEditForm = ref({
base_fetch_sql: '',
fetch_where_conditions: '',
fetch_order_by: '',
detail_sql: '',
writeback_sql: '',
row_id_key: 'id',
log_prefix: '',
alias_order_str: '',
detail_alias_order_str: '',
header_labels_str: '{}',
ds_db_type: 'sqlserver',
ds_host: '',
ds_port: '',
ds_database: '',
ds_username: '',
ds_password: '',
ds_driver: '',
ds_encrypt: '',
ds_trust_cert: '',
api_url: '',
api_method: 'POST',
api_headers_str: '{}',
api_body_template: '',
dify_system_prompt: '',
});
const scheduleSqlSaving = ref(false); void scheduleSqlSaving;
const scheduleTestLoading = ref(false);
const scheduleTestResult = ref<{ total: number; showing: number; columns: string[]; rows: any[]; sql: string } | null>(null);
const handleTestScheduleSql = async () => {
const taskId = scheduleEditingId.value;
if (!taskId) return;
scheduleTestLoading.value = true;
scheduleTestResult.value = null;
try {
const result = await testAdminScheduleSql(taskId, {
fetch_where_conditions: scheduleSqlEditForm.value.fetch_where_conditions,
fetch_order_by: scheduleSqlEditForm.value.fetch_order_by,
limit: 10,
});
scheduleTestResult.value = result;
} catch (e: any) {
msg.error(`${t('admin.schedule.msg.testQueryFailed')}: ${e?.message || e}`);
} finally {
scheduleTestLoading.value = false;
}
};
const scheduleNotifyDropdownOpen = ref(false);
watch(() => scheduleCreateForm.value.dify_agent_id, (agentId) => {
if (!agentId) {
scheduleSqlEditForm.value.dify_system_prompt = '';
}
});
const getUserName = (uid: number) => {
const u = users.value.find(x => x.id === uid);
return u ? (u.real_name || u.username) : String(uid);
};
const toggleNotifyUser = (uid: number) => {
const list = scheduleCreateForm.value.notify_user_ids_json;
if (list.includes(uid)) {
scheduleCreateForm.value.notify_user_ids_json = list.filter((id: number) => id !== uid);
} else {
scheduleCreateForm.value.notify_user_ids_json = [...list, uid];
}
};
const removeNotifyUser = (uid: number) => {
scheduleCreateForm.value.notify_user_ids_json = scheduleCreateForm.value.notify_user_ids_json.filter((id: number) => id !== uid);
};
const createSchedule = async () => {
if (!scheduleCreateForm.value.name || !scheduleCreateForm.value.owner_user_id) return;
const dst = scheduleCreateForm.value.data_source_type;
const hasAgent = !!scheduleCreateForm.value.dify_agent_id;
const hasSql = dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.trim();
const hasApi = dst === 'external_api' && !!scheduleSqlEditForm.value.api_url.trim();
if (!hasAgent && !hasSql && !hasApi) {
msg.error(t('admin.schedule.msg.configRequired'));
return;
}
let headerLabels: Record<string, string> = {};
try {
headerLabels = JSON.parse(scheduleSqlEditForm.value.header_labels_str || '{}');
} catch {
msg.error(t('admin.schedule.msg.headerLabelsJsonInvalid'));
return;
}
let apiHeaders: Record<string, string> = {};
if (dst === 'external_api') {
try {
apiHeaders = JSON.parse(scheduleSqlEditForm.value.api_headers_str || '{}');
} catch {
msg.error(t('admin.schedule.msg.apiHeadersJsonInvalid'));
return;
}
}
const aliasOrder = scheduleSqlEditForm.value.alias_order_str.split(',').map(s => s.trim()).filter(Boolean);
const detailAliasOrder = scheduleSqlEditForm.value.detail_alias_order_str.split(',').map(s => s.trim()).filter(Boolean);
const configPayload: Record<string, any> = {
base_fetch_sql: scheduleSqlEditForm.value.base_fetch_sql,
fetch_where_conditions: scheduleSqlEditForm.value.fetch_where_conditions,
fetch_order_by: scheduleSqlEditForm.value.fetch_order_by,
detail_sql: scheduleSqlEditForm.value.detail_sql,
writeback_sql: scheduleSqlEditForm.value.writeback_sql,
row_id_key: scheduleSqlEditForm.value.row_id_key || 'id',
log_prefix: scheduleSqlEditForm.value.log_prefix,
alias_order: aliasOrder,
detail_alias_order: detailAliasOrder,
header_labels: headerLabels,
data_source: scheduleSqlEditForm.value.ds_host.trim() ? {
db_type: scheduleSqlEditForm.value.ds_db_type,
host: scheduleSqlEditForm.value.ds_host,
port: scheduleSqlEditForm.value.ds_port,
database: scheduleSqlEditForm.value.ds_database,
username: scheduleSqlEditForm.value.ds_username,
password: scheduleSqlEditForm.value.ds_password,
driver: scheduleSqlEditForm.value.ds_driver,
encrypt: scheduleSqlEditForm.value.ds_encrypt,
trust_cert: scheduleSqlEditForm.value.ds_trust_cert,
} : undefined,
external_api: scheduleSqlEditForm.value.api_url.trim() ? {
url: scheduleSqlEditForm.value.api_url,
method: scheduleSqlEditForm.value.api_method,
headers: apiHeaders,
body_template: scheduleSqlEditForm.value.api_body_template,
} : undefined,
dify_system_prompt: hasAgent ? scheduleSqlEditForm.value.dify_system_prompt : '',
};
scheduleCreateSaving.value = true;
try {
const payload: any = {
name: scheduleCreateForm.value.name,
schedule_type: 'platform_app',
owner_user_id: scheduleCreateForm.value.owner_user_id,
cron_expr: scheduleCronPreview.value,
wait_seconds: Math.max(0, Number(scheduleCreateForm.value.wait_seconds || 0)),
dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined,
notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [],
notify_enabled: scheduleCreateForm.value.notify_enabled,
enabled: scheduleCreateForm.value.enabled,
data_source_type: dst,
config: configPayload,
};
let resultData: any = null;
if (scheduleEditingId.value) {
resultData = await updateAdminSchedule(scheduleEditingId.value, payload);
} else {
resultData = await createAdminSchedule(payload);
}
const createdId = resultData?.id ?? resultData?.schedule?.id ?? null;
const targetId = scheduleEditingId.value || createdId;
showScheduleCreateModal.value = false;
await loadSchedules();
if (targetId) {
await viewScheduleRuns(targetId);
}
} catch (err: any) {
msg.error(err?.message || t('common.errorOccurred'));
} finally {
scheduleCreateSaving.value = false;
}
};
const todayStart = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T00:00:00`;
};
const todayEnd = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T23:59:59`;
};
const resetScheduleRunFilters = () => {
scheduleRunStatusFilter.value = 'all';
scheduleRunStartedAfter.value = todayStart();
scheduleRunStartedBefore.value = todayEnd();
};
const viewScheduleRuns = async (taskId: number) => {
selectedScheduleId.value = taskId;
scheduleRunsLoading.value = true;
if (!scheduleRunStartedAfter.value && !scheduleRunStartedBefore.value) {
resetScheduleRunFilters();
}
try {
const params: { status?: string; started_after?: string; started_before?: string } = {};
if (scheduleRunStatusFilter.value !== 'all') params.status = scheduleRunStatusFilter.value;
if (scheduleRunStartedAfter.value) params.started_after = scheduleRunStartedAfter.value;
if (scheduleRunStartedBefore.value) params.started_before = scheduleRunStartedBefore.value;
selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params);
} finally {
scheduleRunsLoading.value = false;
}
};
const openScheduleRunSubmenu = async (taskId: number) => {
scheduleViewMode.value = 'workbench';
await viewScheduleRuns(taskId);
};
const backToScheduleOverview = () => {
scheduleViewMode.value = 'overview';
};
const runScheduleNow = async (taskId: number) => {
try {
await runAdminSchedule(taskId);
} catch (err: any) {
msg.error(err?.message || t('admin.schedule.msg.runNowFailed'));
return;
}
await viewScheduleRuns(taskId);
await loadSchedules();
const pollInterval = setInterval(async () => {
await viewScheduleRuns(taskId);
await loadSchedules();
const target = schedules.value.find((s: ScheduleTask) => s.id === taskId);
if (target && target.last_status && target.last_status !== 'running') {
clearInterval(pollInterval);
}
}, 5000);
};
const setScheduleEnabled = async (taskId: number, enabled: boolean) => {
try {
await toggleAdminSchedule(taskId, enabled);
await loadSchedules();
} catch (err: any) {
msg.error(err?.message || t('common.errorOccurred'));
}
};
const downloadScheduleExcel = async (runId: number) => {
const res = await fetch(`/api/admin/schedule-runs/${runId}/excel`, { headers: getAuthHeaders() });
if (!res.ok) {
msg.error(t('admin.schedule.msg.downloadExcelFailed'));
return;
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
const disposition = res.headers.get('content-disposition');
a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'result.xlsx';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
const deleteSchedule = (task: ScheduleTask) => {
openDeleteConfirm(
t('admin.schedule.deleteConfirmMessage', { name: task.name }),
async () => {
try {
await deleteAdminSchedule(task.id);
} catch (err: any) {
msg.error(err?.message || t('admin.schedule.msg.deleteFailed'));
return;
}
if (selectedScheduleId.value === task.id) {
selectedScheduleId.value = null;
selectedScheduleRuns.value = [];
}
await loadSchedules();
},
t('admin.schedule.deleteDialogTitle')
);
};
const loadAll = async (): Promise<void> => {
await loadSchedules();
};
return {
agents,
users,
schedules,
selectedScheduleRuns,
scheduleLoading,
scheduleRunsLoading,
selectedScheduleId,
scheduleRunStatusFilter,
scheduleRunStartedAfter,
scheduleRunStartedBefore,
scheduleRunColumnDefs,
scheduleViewMode,
showScheduleCreateModal,
scheduleCreateSaving,
scheduleEditingId,
scheduleCreateForm,
scheduleConfigCollapsed,
scheduleCronDesigner,
weeklyDayOptions,
scheduleCronPreview,
scheduleNextRunPreview,
selectedSchedule,
scheduleRunStatusOptions,
getScheduleRunStatusBadge,
formatDateTime,
expandedScheduleRunId,
expandedScheduleRun,
stepLabelMap,
stepStatusMap,
showTestRunDialog,
testRunSchedule,
testRunWhere,
testRunOrderBy,
testRunBaseFetchSql,
testRunLimit,
testRunLoading,
testRunResult,
filteredScheduleRuns,
selectedScheduleRunMetrics,
selectedScheduleLatestRunAt,
scheduleEnabledCount,
scheduleDisabledCount,
scheduleRunningCount,
scheduleSqlEditForm,
scheduleTestLoading,
scheduleTestResult,
scheduleNotifyDropdownOpen,
showDeleteConfirmDialog,
deleteConfirmTitle,
deleteConfirmMessage,
loadAll,
loadSchedules,
startScheduleColResize,
openScheduleCreateModal,
openScheduleEditModal,
openScheduleRunSubmenu,
backToScheduleOverview,
viewScheduleRuns,
resetScheduleRunFilters,
runScheduleNow,
setScheduleEnabled,
deleteSchedule,
downloadScheduleExcel,
openTestRunDialog,
handleTestRun,
handleTestScheduleSql,
getUserName,
toggleNotifyUser,
removeNotifyUser,
createSchedule,
closeDeleteConfirm,
confirmDelete,
};
}