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")
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):
payload: dict[str, Any] = {
"success": True,
@@ -5,9 +5,11 @@
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { listAdminAgents, listAdminUsers } from '@/api/admin';
import { getKbGroups, type KbGroup } from '@/api/kb';
import {
createAdminSchedule,
deleteAdminSchedule,
getAdminSchedule,
getAdminScheduleTaskConfig,
listAdminScheduleRuns,
listAdminSchedules,
@@ -30,6 +32,7 @@ export function useSchedulesAdmin() {
const agents = ref<AdminAgentOption[]>([]);
const users = ref<AdminUserRow[]>([]);
const kbGroups = ref<KbGroup[]>([]);
const showDeleteConfirmDialog = ref(false);
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 schedulesLoaded = ref(false); void schedulesLoaded;
const selectedScheduleRuns = ref<ScheduleRun[]>([]);
@@ -164,6 +176,8 @@ const scheduleCreateForm = ref({
wait_seconds: 300,
notify_enabled: true,
notify_user_ids_json: [] as number[],
kb_sync_enabled: false,
kb_group_id: null as number | null,
enabled: true,
});
const scheduleConfigCollapsed = ref(true);
@@ -331,6 +345,8 @@ const resetScheduleCreateForm = () => {
wait_seconds: 300,
notify_enabled: true,
notify_user_ids_json: [],
kb_sync_enabled: false,
kb_group_id: null,
enabled: true,
};
scheduleSqlEditForm.value = {
@@ -360,6 +376,10 @@ const resetScheduleCreateForm = () => {
dify_system_prompt: '',
};
scheduleTestResult.value = null;
scheduleNotifyUserQuery.value = '';
scheduleNotifyDropdownOpen.value = false;
scheduleOwnerQuery.value = '';
scheduleOwnerDropdownOpen.value = false;
scheduleCronDesigner.value = {
mode: 'every_minutes',
every_minutes: 30,
@@ -375,13 +395,16 @@ const resetScheduleCreateForm = () => {
const openScheduleCreateModal = async () => {
resetScheduleCreateForm();
scheduleConfigCollapsed.value = true;
await Promise.all([loadAgents(), loadUsers()]);
await Promise.all([loadAgents(), loadUsers(), loadKbGroups()]);
showScheduleCreateModal.value = true;
};
const openScheduleEditModal = async (task: ScheduleTask) => {
await Promise.all([loadAgents(), loadUsers()]);
await Promise.all([loadAgents(), loadUsers(), loadKbGroups()]);
scheduleConfigCollapsed.value = true;
scheduleNotifyUserQuery.value = '';
scheduleNotifyDropdownOpen.value = false;
scheduleOwnerDropdownOpen.value = false;
scheduleEditingId.value = task.id;
scheduleCreateForm.value = {
name: task.name || '',
@@ -391,6 +414,8 @@ const openScheduleEditModal = async (task: ScheduleTask) => {
wait_seconds: task.wait_seconds || 0,
notify_enabled: !!task.notify_enabled,
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,
data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api',
};
@@ -458,6 +483,7 @@ const openScheduleEditModal = async (task: ScheduleTask) => {
scheduleTestResult.value = null;
parseCronExprToDesigner(task.cron_expr);
syncScheduleOwnerQuery();
showScheduleCreateModal.value = true;
};
@@ -484,9 +510,14 @@ const getScheduleRunStatusBadge = (status: string) => {
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) => {
if (!iso) return '-';
const d = new Date(iso);
const d = parseApiUtcDate(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())}`;
@@ -517,11 +548,23 @@ const testRunWhere = ref('');
const testRunOrderBy = ref('');
const testRunBaseFetchSql = ref('');
const testRunLimit = ref(3);
const testRunKbSync = ref(false);
const testRunKbSyncAttempted = ref(false);
const testRunLoading = ref(false);
const testRunResult = ref<TestScheduleRunResult | null>(null);
const testRunKbSyncAvailable = computed(
() => !!(testRunSchedule.value?.kb_group_id),
);
const openTestRunDialog = async (s: ScheduleTask) => {
testRunSchedule.value = s;
let freshTask = s;
try {
freshTask = await getAdminSchedule(s.id);
} catch {
// 列表数据兜底
}
testRunSchedule.value = freshTask;
try {
const result = await getAdminScheduleTaskConfig(s.id);
const cfg = result.config;
@@ -534,6 +577,8 @@ const openTestRunDialog = async (s: ScheduleTask) => {
testRunBaseFetchSql.value = '';
}
testRunLimit.value = 3;
testRunKbSync.value = !!(freshTask.kb_group_id && freshTask.kb_sync_enabled);
testRunKbSyncAttempted.value = false;
testRunResult.value = null;
testRunLoading.value = false;
showTestRunDialog.value = true;
@@ -544,11 +589,13 @@ const handleTestRun = async () => {
if (!s?.id) return;
testRunLoading.value = true;
testRunResult.value = null;
testRunKbSyncAttempted.value = testRunKbSync.value;
try {
const result = await testAdminScheduleRun(s.id, {
fetch_where_conditions: testRunWhere.value,
fetch_order_by: testRunOrderBy.value,
limit: testRunLimit.value,
kb_sync_enabled: testRunKbSync.value,
});
testRunResult.value = result;
await loadSchedules();
@@ -580,9 +627,10 @@ const selectedScheduleRunMetrics = computed(() => {
);
});
const selectedScheduleLatestRunAt = computed(
() => selectedScheduleRuns.value[0]?.started_at || selectedSchedule.value?.last_run_at || '-'
);
const selectedScheduleLatestRunAt = computed(() => {
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 scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length);
@@ -662,6 +710,78 @@ const handleTestScheduleSql = async () => {
};
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) => {
if (!agentId) {
@@ -760,6 +880,8 @@ const createSchedule = async () => {
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,
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,
data_source_type: dst,
config: configPayload,
@@ -808,8 +930,12 @@ const viewScheduleRuns = async (taskId: number) => {
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;
if (scheduleRunStartedAfter.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);
} finally {
scheduleRunsLoading.value = false;
@@ -898,6 +1024,7 @@ const deleteSchedule = (task: ScheduleTask) => {
return {
agents,
users,
kbGroups,
schedules,
selectedScheduleRuns,
scheduleLoading,
@@ -931,6 +1058,9 @@ const deleteSchedule = (task: ScheduleTask) => {
testRunOrderBy,
testRunBaseFetchSql,
testRunLimit,
testRunKbSync,
testRunKbSyncAvailable,
testRunKbSyncAttempted,
testRunLoading,
testRunResult,
filteredScheduleRuns,
@@ -943,6 +1073,15 @@ const deleteSchedule = (task: ScheduleTask) => {
scheduleTestLoading,
scheduleTestResult,
scheduleNotifyDropdownOpen,
scheduleNotifyUserQuery,
filteredNotifyUsers,
scheduleCloseNotifyDropdown,
scheduleOwnerDropdownOpen,
scheduleOwnerQuery,
filteredOwnerUsers,
selectScheduleOwner,
handleScheduleOwnerInput,
scheduleCloseOwnerDropdown,
showDeleteConfirmDialog,
deleteConfirmTitle,
deleteConfirmMessage,