feat(schedule): 新增调度时区转换功能

This commit is contained in:
hugo committed 2026-06-10 11:29:41 +08:00
1 parent 6d40d504c5
commit a88b60e505
2 files changed
+157 -9

No files matched your search

+9
View File
@@ -19,6 +19,15 @@ def utc_iso_now() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z") return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def utc_iso(dt: datetime | None) -> str | None:
"""将 naive UTC datetime 序列化为带 Z 后缀的 ISO 字符串,便于前端正确转本地时区。"""
if dt is None:
return None
if dt.tzinfo is not None:
return dt.astimezone(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
return dt.isoformat() + "Z"
def ok(data: Any, *, request_id: str | None = None, status: int = 200): def ok(data: Any, *, request_id: str | None = None, status: int = 200):
payload: dict[str, Any] = { payload: dict[str, Any] = {
"success": True, "success": True,
@@ -5,9 +5,11 @@
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { listAdminAgents, listAdminUsers } from '@/api/admin'; import { listAdminAgents, listAdminUsers } from '@/api/admin';
import { getKbGroups, type KbGroup } from '@/api/kb';
import { import {
createAdminSchedule, createAdminSchedule,
deleteAdminSchedule, deleteAdminSchedule,
getAdminSchedule,
getAdminScheduleTaskConfig, getAdminScheduleTaskConfig,
listAdminScheduleRuns, listAdminScheduleRuns,
listAdminSchedules, listAdminSchedules,
@@ -30,6 +32,7 @@ export function useSchedulesAdmin() {
const agents = ref<AdminAgentOption[]>([]); const agents = ref<AdminAgentOption[]>([]);
const users = ref<AdminUserRow[]>([]); const users = ref<AdminUserRow[]>([]);
const kbGroups = ref<KbGroup[]>([]);
const showDeleteConfirmDialog = ref(false); const showDeleteConfirmDialog = ref(false);
const deleteConfirmTitle = ref(''); const deleteConfirmTitle = ref('');
@@ -81,6 +84,15 @@ export function useSchedulesAdmin() {
} }
}; };
const loadKbGroups = async (): Promise<void> => {
try {
kbGroups.value = await getKbGroups();
} catch (e) {
console.error('Failed to load kb groups', e);
kbGroups.value = [];
}
};
const schedules = ref<ScheduleTask[]>([]); const schedules = ref<ScheduleTask[]>([]);
const schedulesLoaded = ref(false); void schedulesLoaded; const schedulesLoaded = ref(false); void schedulesLoaded;
const selectedScheduleRuns = ref<ScheduleRun[]>([]); const selectedScheduleRuns = ref<ScheduleRun[]>([]);
@@ -164,6 +176,8 @@ const scheduleCreateForm = ref({
wait_seconds: 300, wait_seconds: 300,
notify_enabled: true, notify_enabled: true,
notify_user_ids_json: [] as number[], notify_user_ids_json: [] as number[],
kb_sync_enabled: false,
kb_group_id: null as number | null,
enabled: true, enabled: true,
}); });
const scheduleConfigCollapsed = ref(true); const scheduleConfigCollapsed = ref(true);
@@ -331,6 +345,8 @@ const resetScheduleCreateForm = () => {
wait_seconds: 300, wait_seconds: 300,
notify_enabled: true, notify_enabled: true,
notify_user_ids_json: [], notify_user_ids_json: [],
kb_sync_enabled: false,
kb_group_id: null,
enabled: true, enabled: true,
}; };
scheduleSqlEditForm.value = { scheduleSqlEditForm.value = {
@@ -360,6 +376,10 @@ const resetScheduleCreateForm = () => {
dify_system_prompt: '', dify_system_prompt: '',
}; };
scheduleTestResult.value = null; scheduleTestResult.value = null;
scheduleNotifyUserQuery.value = '';
scheduleNotifyDropdownOpen.value = false;
scheduleOwnerQuery.value = '';
scheduleOwnerDropdownOpen.value = false;
scheduleCronDesigner.value = { scheduleCronDesigner.value = {
mode: 'every_minutes', mode: 'every_minutes',
every_minutes: 30, every_minutes: 30,
@@ -375,13 +395,16 @@ const resetScheduleCreateForm = () => {
const openScheduleCreateModal = async () => { const openScheduleCreateModal = async () => {
resetScheduleCreateForm(); resetScheduleCreateForm();
scheduleConfigCollapsed.value = true; scheduleConfigCollapsed.value = true;
await Promise.all([loadAgents(), loadUsers()]); await Promise.all([loadAgents(), loadUsers(), loadKbGroups()]);
showScheduleCreateModal.value = true; showScheduleCreateModal.value = true;
}; };
const openScheduleEditModal = async (task: ScheduleTask) => { const openScheduleEditModal = async (task: ScheduleTask) => {
await Promise.all([loadAgents(), loadUsers()]); await Promise.all([loadAgents(), loadUsers(), loadKbGroups()]);
scheduleConfigCollapsed.value = true; scheduleConfigCollapsed.value = true;
scheduleNotifyUserQuery.value = '';
scheduleNotifyDropdownOpen.value = false;
scheduleOwnerDropdownOpen.value = false;
scheduleEditingId.value = task.id; scheduleEditingId.value = task.id;
scheduleCreateForm.value = { scheduleCreateForm.value = {
name: task.name || '', name: task.name || '',
@@ -391,6 +414,8 @@ const openScheduleEditModal = async (task: ScheduleTask) => {
wait_seconds: task.wait_seconds || 0, wait_seconds: task.wait_seconds || 0,
notify_enabled: !!task.notify_enabled, notify_enabled: !!task.notify_enabled,
notify_user_ids_json: task.notify_user_ids_json || [], notify_user_ids_json: task.notify_user_ids_json || [],
kb_sync_enabled: !!task.kb_sync_enabled,
kb_group_id: task.kb_group_id || null,
enabled: !!task.enabled, enabled: !!task.enabled,
data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api', data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api',
}; };
@@ -458,6 +483,7 @@ const openScheduleEditModal = async (task: ScheduleTask) => {
scheduleTestResult.value = null; scheduleTestResult.value = null;
parseCronExprToDesigner(task.cron_expr); parseCronExprToDesigner(task.cron_expr);
syncScheduleOwnerQuery();
showScheduleCreateModal.value = true; showScheduleCreateModal.value = true;
}; };
@@ -484,9 +510,14 @@ const getScheduleRunStatusBadge = (status: string) => {
return map[status] || { cls: 'bg-surface-soft text-secondary', label: status }; return map[status] || { cls: 'bg-surface-soft text-secondary', label: status };
}; };
const parseApiUtcDate = (iso: string) => {
const normalized = /(?:Z|[+-]\d{2}:\d{2})$/i.test(iso) ? iso : `${iso}Z`;
return new Date(normalized);
};
const formatDateTime = (iso?: string | null) => { const formatDateTime = (iso?: string | null) => {
if (!iso) return '-'; if (!iso) return '-';
const d = new Date(iso); const d = parseApiUtcDate(iso);
if (isNaN(d.getTime())) return iso; if (isNaN(d.getTime())) return iso;
const pad = (n: number) => String(n).padStart(2, '0'); 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())}`; return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
@@ -517,11 +548,23 @@ const testRunWhere = ref('');
const testRunOrderBy = ref(''); const testRunOrderBy = ref('');
const testRunBaseFetchSql = ref(''); const testRunBaseFetchSql = ref('');
const testRunLimit = ref(3); const testRunLimit = ref(3);
const testRunKbSync = ref(false);
const testRunKbSyncAttempted = ref(false);
const testRunLoading = ref(false); const testRunLoading = ref(false);
const testRunResult = ref<TestScheduleRunResult | null>(null); const testRunResult = ref<TestScheduleRunResult | null>(null);
const testRunKbSyncAvailable = computed(
() => !!(testRunSchedule.value?.kb_group_id),
);
const openTestRunDialog = async (s: ScheduleTask) => { const openTestRunDialog = async (s: ScheduleTask) => {
testRunSchedule.value = s; let freshTask = s;
try {
freshTask = await getAdminSchedule(s.id);
} catch {
// 列表数据兜底
}
testRunSchedule.value = freshTask;
try { try {
const result = await getAdminScheduleTaskConfig(s.id); const result = await getAdminScheduleTaskConfig(s.id);
const cfg = result.config; const cfg = result.config;
@@ -534,6 +577,8 @@ const openTestRunDialog = async (s: ScheduleTask) => {
testRunBaseFetchSql.value = ''; testRunBaseFetchSql.value = '';
} }
testRunLimit.value = 3; testRunLimit.value = 3;
testRunKbSync.value = !!(freshTask.kb_group_id && freshTask.kb_sync_enabled);
testRunKbSyncAttempted.value = false;
testRunResult.value = null; testRunResult.value = null;
testRunLoading.value = false; testRunLoading.value = false;
showTestRunDialog.value = true; showTestRunDialog.value = true;
@@ -544,11 +589,13 @@ const handleTestRun = async () => {
if (!s?.id) return; if (!s?.id) return;
testRunLoading.value = true; testRunLoading.value = true;
testRunResult.value = null; testRunResult.value = null;
testRunKbSyncAttempted.value = testRunKbSync.value;
try { try {
const result = await testAdminScheduleRun(s.id, { const result = await testAdminScheduleRun(s.id, {
fetch_where_conditions: testRunWhere.value, fetch_where_conditions: testRunWhere.value,
fetch_order_by: testRunOrderBy.value, fetch_order_by: testRunOrderBy.value,
limit: testRunLimit.value, limit: testRunLimit.value,
kb_sync_enabled: testRunKbSync.value,
}); });
testRunResult.value = result; testRunResult.value = result;
await loadSchedules(); await loadSchedules();
@@ -580,9 +627,10 @@ const selectedScheduleRunMetrics = computed(() => {
); );
}); });
const selectedScheduleLatestRunAt = computed( const selectedScheduleLatestRunAt = computed(() => {
() => selectedScheduleRuns.value[0]?.started_at || selectedSchedule.value?.last_run_at || '-' const raw = selectedScheduleRuns.value[0]?.started_at || selectedSchedule.value?.last_run_at;
); return raw ? formatDateTime(raw) : '-';
});
const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length); const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length);
const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length); const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length);
@@ -662,6 +710,78 @@ const handleTestScheduleSql = async () => {
}; };
const scheduleNotifyDropdownOpen = ref(false); const scheduleNotifyDropdownOpen = ref(false);
const scheduleNotifyUserQuery = ref('');
let scheduleNotifyCloseTimer: ReturnType<typeof setTimeout> | null = null;
const filteredNotifyUsers = computed(() => {
const keyword = scheduleNotifyUserQuery.value.trim().toLowerCase();
return users.value.filter((u) => {
if (!keyword) return true;
return [u.real_name, u.username, u.employee_id, String(u.id)]
.filter(Boolean)
.some((val) => String(val).toLowerCase().includes(keyword));
});
});
const scheduleCloseNotifyDropdown = (): void => {
if (scheduleNotifyCloseTimer) clearTimeout(scheduleNotifyCloseTimer);
scheduleNotifyCloseTimer = setTimeout(() => {
scheduleNotifyDropdownOpen.value = false;
}, 150);
};
const scheduleOwnerDropdownOpen = ref(false);
const scheduleOwnerQuery = ref('');
let scheduleOwnerCloseTimer: ReturnType<typeof setTimeout> | null = null;
const formatUserOptionLabel = (u: AdminUserRow) =>
`${u.real_name || u.username}${u.employee_id ? `(${u.employee_id})` : ''}`;
const filteredOwnerUsers = computed(() => {
const keyword = scheduleOwnerQuery.value.trim().toLowerCase();
return users.value.filter((u) => {
if (!keyword) return true;
return [u.real_name, u.username, u.employee_id, String(u.id)]
.filter(Boolean)
.some((val) => String(val).toLowerCase().includes(keyword));
});
});
const syncScheduleOwnerQuery = (): void => {
const ownerId = scheduleCreateForm.value.owner_user_id;
if (!ownerId) {
scheduleOwnerQuery.value = '';
return;
}
const u = users.value.find((x) => x.id === ownerId);
scheduleOwnerQuery.value = u ? formatUserOptionLabel(u) : String(ownerId);
};
const selectScheduleOwner = (id: number): void => {
const u = users.value.find((x) => x.id === id);
if (!u) return;
scheduleCreateForm.value.owner_user_id = id;
scheduleOwnerQuery.value = formatUserOptionLabel(u);
scheduleOwnerDropdownOpen.value = false;
};
const handleScheduleOwnerInput = (): void => {
scheduleOwnerDropdownOpen.value = true;
const ownerId = scheduleCreateForm.value.owner_user_id;
if (!ownerId) return;
const u = users.value.find((x) => x.id === ownerId);
const currentLabel = u ? formatUserOptionLabel(u) : '';
if (scheduleOwnerQuery.value.trim() !== currentLabel) {
scheduleCreateForm.value.owner_user_id = null;
}
};
const scheduleCloseOwnerDropdown = (): void => {
if (scheduleOwnerCloseTimer) clearTimeout(scheduleOwnerCloseTimer);
scheduleOwnerCloseTimer = setTimeout(() => {
scheduleOwnerDropdownOpen.value = false;
}, 150);
};
watch(() => scheduleCreateForm.value.dify_agent_id, (agentId) => { watch(() => scheduleCreateForm.value.dify_agent_id, (agentId) => {
if (!agentId) { if (!agentId) {
@@ -760,6 +880,8 @@ const createSchedule = async () => {
dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined, dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined,
notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [], notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [],
notify_enabled: scheduleCreateForm.value.notify_enabled, notify_enabled: scheduleCreateForm.value.notify_enabled,
kb_sync_enabled: scheduleCreateForm.value.kb_sync_enabled,
kb_group_id: scheduleCreateForm.value.kb_sync_enabled ? scheduleCreateForm.value.kb_group_id : null,
enabled: scheduleCreateForm.value.enabled, enabled: scheduleCreateForm.value.enabled,
data_source_type: dst, data_source_type: dst,
config: configPayload, config: configPayload,
@@ -808,8 +930,12 @@ const viewScheduleRuns = async (taskId: number) => {
try { try {
const params: { status?: string; started_after?: string; started_before?: string } = {}; const params: { status?: string; started_after?: string; started_before?: string } = {};
if (scheduleRunStatusFilter.value !== 'all') params.status = scheduleRunStatusFilter.value; if (scheduleRunStatusFilter.value !== 'all') params.status = scheduleRunStatusFilter.value;
if (scheduleRunStartedAfter.value) params.started_after = scheduleRunStartedAfter.value; if (scheduleRunStartedAfter.value) {
if (scheduleRunStartedBefore.value) params.started_before = scheduleRunStartedBefore.value; params.started_after = new Date(scheduleRunStartedAfter.value).toISOString();
}
if (scheduleRunStartedBefore.value) {
params.started_before = new Date(scheduleRunStartedBefore.value).toISOString();
}
selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params); selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params);
} finally { } finally {
scheduleRunsLoading.value = false; scheduleRunsLoading.value = false;
@@ -898,6 +1024,7 @@ const deleteSchedule = (task: ScheduleTask) => {
return { return {
agents, agents,
users, users,
kbGroups,
schedules, schedules,
selectedScheduleRuns, selectedScheduleRuns,
scheduleLoading, scheduleLoading,
@@ -931,6 +1058,9 @@ const deleteSchedule = (task: ScheduleTask) => {
testRunOrderBy, testRunOrderBy,
testRunBaseFetchSql, testRunBaseFetchSql,
testRunLimit, testRunLimit,
testRunKbSync,
testRunKbSyncAvailable,
testRunKbSyncAttempted,
testRunLoading, testRunLoading,
testRunResult, testRunResult,
filteredScheduleRuns, filteredScheduleRuns,
@@ -943,6 +1073,15 @@ const deleteSchedule = (task: ScheduleTask) => {
scheduleTestLoading, scheduleTestLoading,
scheduleTestResult, scheduleTestResult,
scheduleNotifyDropdownOpen, scheduleNotifyDropdownOpen,
scheduleNotifyUserQuery,
filteredNotifyUsers,
scheduleCloseNotifyDropdown,
scheduleOwnerDropdownOpen,
scheduleOwnerQuery,
filteredOwnerUsers,
selectScheduleOwner,
handleScheduleOwnerInput,
scheduleCloseOwnerDropdown,
showDeleteConfirmDialog, showDeleteConfirmDialog,
deleteConfirmTitle, deleteConfirmTitle,
deleteConfirmMessage, deleteConfirmMessage,