feat(schedule): 新增平台任务参数契约与动态选项支持

This commit is contained in:
hugo committed 2026-07-09 13:19:36 +08:00
1 parent 2ce1aca023
commit 8b5b0b49bf
76 files changed
+7103 -1203

No files matched your search

@@ -0,0 +1,377 @@
<script setup lang="ts">
/**
* features/admin/modules/schedules/components/DynamicTaskParamsForm.vue
* 用途:平台任务参数通用表单——按注册表 params_schema 渲染控件并输出统一 job_params。
* 依赖:schedule.api(PlatformTaskDefinition/listAdminPlatformTaskOptions)、vue-i18n。
* 逻辑:ScheduleCreateEditModal 传入选中任务的 definition;本组件只认识控件 type 与
* options_source,不认识具体任务(红框参数区完全由 schema 决定);
* 高级配置折叠 JSON 与 schema type=json 字段均本地校验,非法时 emit valid=false 阻止保存;
* modelValue 异步回填时同步 _advanced / json 文本(用户已编辑时不覆盖)。
*/
import { computed, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import {
listAdminPlatformTaskOptions,
type PlatformTaskDefinition,
type PlatformTaskOption,
type PlatformTaskParamField,
} from '@/features/admin/api/schedule.api';
const props = defineProps<{
definition: PlatformTaskDefinition;
modelValue: Record<string, any> | null;
valid?: boolean;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: Record<string, any> | null): void;
(e: 'update:valid', value: boolean): void;
}>();
const { t, te } = useI18n();
/** options_source → 选项列表缓存(组件生命周期内共享,避免重复请求) */
const optionsCache = reactive<Record<string, PlatformTaskOption[]>>({});
const optionsLoading = reactive<Record<string, boolean>>({});
const advancedJsonText = ref('');
const advancedJsonError = ref(false);
/** schema type=json 字段的本地文本与非法标记(key → text/error) */
const jsonFieldTexts = reactive<Record<string, string>>({});
const jsonFieldErrors = reactive<Record<string, boolean>>({});
/** 向父级同步表单合法性(高级 JSON 或 schema json 字段非法时为 false,阻止保存)。 */
const syncValid = (): void => {
const jsonFieldsInvalid = Object.values(jsonFieldErrors).some(Boolean);
emit('update:valid', !advancedJsonError.value && !jsonFieldsInvalid);
};
/**
* 将当前值格式化为 json 字段 textarea 文本。
* @param value - job_params 中该字段的现值
*/
const formatJsonFieldText = (value: unknown): string => {
if (value === null || value === undefined || value === '') return '';
if (typeof value === 'string') return value;
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
};
/**
* 校验 schema type=json 字段:空允许;非空须为可 JSON.parse 的文本(与后端一致)。
* 合法时解析后写入 job_params,非法时只标记错误不 emit 坏值。
*/
const handleJsonFieldInput = (key: string, rawText: string): void => {
jsonFieldTexts[key] = rawText;
const text = rawText.trim();
if (!text) {
jsonFieldErrors[key] = false;
setField(key, null);
syncValid();
return;
}
try {
const parsed = JSON.parse(text);
jsonFieldErrors[key] = false;
setField(key, parsed);
} catch {
jsonFieldErrors[key] = true;
}
syncValid();
};
/**
* i18n key 优先解析文案:te(key) 命中用 $t(key),否则回退注册表内置中文。
* @param key - schema 下发的 i18n key(可空)
* @param fallback - 注册表中文 fallback
*/
const resolveText = (key: string | null | undefined, fallback: string | undefined): string => {
if (key && te(key)) return t(key);
return fallback || '';
};
const schemaFields = computed<PlatformTaskParamField[]>(
() => props.definition.params_schema || [],
);
const descriptionText = computed(() =>
resolveText(props.definition.description_key, props.definition.description),
);
/**
* 当前 job_params 值(保证非空对象,方便字段读写)。
*/
const params = computed<Record<string, any>>(() => props.modelValue || {});
/**
* 更新单个字段值并向外发出完整 job_params。
* 核心逻辑:以 defaults 为底、合并现值与新值,保证输出结构稳定。
*/
const setField = (key: string, value: any): void => {
emit('update:modelValue', {
...(props.definition.defaults || {}),
...params.value,
[key]: value,
});
};
/** 拉取并缓存某个 options_source 的动态选项。 */
const loadOptions = async (source: string): Promise<void> => {
if (optionsCache[source] || optionsLoading[source]) return;
optionsLoading[source] = true;
try {
optionsCache[source] = await listAdminPlatformTaskOptions(source);
} catch (e) {
console.error(`Failed to load options for ${source}`, e);
optionsCache[source] = [];
} finally {
optionsLoading[source] = false;
}
};
/** multi_select 勾选切换。 */
const toggleMultiValue = (key: string, value: string | number): void => {
const current: Array<string | number> = Array.isArray(params.value[key]) ? [...params.value[key]] : [];
const idx = current.indexOf(value);
if (idx >= 0) current.splice(idx, 1);
else current.push(value);
setField(key, current);
};
/**
* 高级 JSON 文本变更:合法时写入 _advanced,空文本移除该键。
*/
const handleAdvancedInput = (): void => {
const text = advancedJsonText.value.trim();
if (!text) {
advancedJsonError.value = false;
const next = { ...(props.modelValue || {}) };
delete next._advanced;
emit('update:modelValue', Object.keys(next).length ? next : null);
syncValid();
return;
}
try {
const parsed = JSON.parse(text);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not object');
advancedJsonError.value = false;
setField('_advanced', parsed);
} catch {
advancedJsonError.value = true;
}
syncValid();
};
// 任务切换时:预加载动态选项、回填 _advanced / json 字段文本
watch(
() => props.definition.task_type,
() => {
Object.keys(jsonFieldTexts).forEach((k) => delete jsonFieldTexts[k]);
Object.keys(jsonFieldErrors).forEach((k) => delete jsonFieldErrors[k]);
schemaFields.value.forEach((field) => {
if (field.options_source && (field.type === 'select' || field.type === 'multi_select')) {
void loadOptions(field.options_source);
}
if (field.type === 'json') {
jsonFieldTexts[field.key] = formatJsonFieldText(params.value[field.key]);
jsonFieldErrors[field.key] = false;
}
});
const advanced = (props.modelValue || {})._advanced;
advancedJsonText.value = advanced ? JSON.stringify(advanced, null, 2) : '';
advancedJsonError.value = false;
syncValid();
},
{ immediate: true },
);
// 编辑回填异步到达时同步 _advanced 文本(用户正在编辑且已有文本时不覆盖)
watch(
() => props.modelValue?._advanced,
(advanced) => {
if (advancedJsonText.value.trim() || !advanced) return;
advancedJsonText.value = JSON.stringify(advanced, null, 2);
},
);
// 编辑回填异步到达时同步 schema type=json 字段文本(task_type 未变时也要跟上)
watch(
() => props.modelValue,
(value) => {
schemaFields.value.forEach((field) => {
if (field.type !== 'json') return;
// 用户已输入或校验中:不覆盖本地 textarea
if ((jsonFieldTexts[field.key] || '').trim() || jsonFieldErrors[field.key]) return;
const incoming = value?.[field.key];
if (incoming === undefined || incoming === null || incoming === '') return;
jsonFieldTexts[field.key] = formatJsonFieldText(incoming);
jsonFieldErrors[field.key] = false;
});
},
{ deep: true },
);
</script>
<template>
<div class="rounded-xl border border-blue-200 bg-blue-50/40 p-4 space-y-3">
<!-- 任务说明块(schema 之外的任务级描述) -->
<p v-if="descriptionText" class="text-sm text-blue-900">{{ descriptionText }}</p>
<div v-for="field in schemaFields" :key="field.key">
<!-- info:纯说明块 -->
<p v-if="field.type === 'info'" class="text-xs text-muted">
{{ resolveText(field.help_key, field.help) || resolveText(field.label_key, field.label) }}
</p>
<template v-else>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">
{{ resolveText(field.label_key, field.label) }}
<span v-if="field.required" class="text-rose-500">*</span>
</label>
<!-- text / cron / date / datetime -->
<input
v-if="field.type === 'text' || field.type === 'cron'"
:value="params[field.key] ?? ''"
class="input-field w-full !text-sm !leading-5"
:class="field.type === 'cron' ? 'font-mono' : ''"
:placeholder="resolveText(field.placeholder_key, field.placeholder)"
@input="setField(field.key, ($event.target as HTMLInputElement).value)"
/>
<input
v-else-if="field.type === 'date'"
type="date"
:value="params[field.key] ?? ''"
class="input-field w-full !text-sm !leading-5"
@input="setField(field.key, ($event.target as HTMLInputElement).value)"
/>
<input
v-else-if="field.type === 'datetime'"
type="datetime-local"
:value="params[field.key] ?? ''"
class="input-field w-full !text-sm !leading-5"
@input="setField(field.key, ($event.target as HTMLInputElement).value)"
/>
<!-- number -->
<input
v-else-if="field.type === 'number'"
type="number"
:value="params[field.key] ?? ''"
class="input-field w-full !text-sm !leading-5"
:placeholder="resolveText(field.placeholder_key, field.placeholder)"
@input="setField(field.key, ($event.target as HTMLInputElement).value === '' ? null : Number(($event.target as HTMLInputElement).value))"
/>
<!-- boolean -->
<label v-else-if="field.type === 'boolean'" class="inline-flex items-center gap-2 text-sm text-secondary">
<input
type="checkbox"
class="h-4 w-4 rounded text-blue-600"
:checked="!!params[field.key]"
@change="setField(field.key, ($event.target as HTMLInputElement).checked)"
/>
{{ resolveText(field.placeholder_key, field.placeholder) }}
</label>
<!-- textarea -->
<textarea
v-else-if="field.type === 'textarea'"
:value="typeof params[field.key] === 'string' ? params[field.key] : (params[field.key] ? String(params[field.key]) : '')"
class="w-full min-h-[80px] input-field p-3 text-xs leading-relaxed text-secondary font-mono resize-y"
:placeholder="resolveText(field.placeholder_key, field.placeholder)"
@input="setField(field.key, ($event.target as HTMLTextAreaElement).value)"
></textarea>
<!-- json:本地解析,非法时阻止保存 -->
<div v-else-if="field.type === 'json'" class="space-y-1">
<textarea
:value="jsonFieldTexts[field.key] ?? ''"
class="w-full min-h-[80px] input-field p-3 text-xs leading-relaxed text-secondary font-mono resize-y"
:class="jsonFieldErrors[field.key] ? 'border-red-400 focus:border-red-500' : ''"
:placeholder="resolveText(field.placeholder_key, field.placeholder) || $t('admin.schedule.form.dynamicParamsAdvancedPlaceholder')"
@input="handleJsonFieldInput(field.key, ($event.target as HTMLTextAreaElement).value)"
></textarea>
<p v-if="jsonFieldErrors[field.key]" class="text-xs text-red-600">
{{ $t('admin.schedule.form.dynamicParamsJsonInvalid') }}
</p>
</div>
<!-- select(单选,动态选项) -->
<select
v-else-if="field.type === 'select'"
:value="params[field.key] ?? ''"
class="input-field w-full !text-sm !leading-5"
@change="setField(field.key, ($event.target as HTMLSelectElement).value === '' ? null : (optionsCache[field.options_source || '']?.find((o) => String(o.value) === ($event.target as HTMLSelectElement).value)?.value ?? ($event.target as HTMLSelectElement).value))"
>
<option value="">{{ resolveText(field.placeholder_key, field.placeholder) || $t('admin.schedule.form.dynamicParamsSelectPlaceholder') }}</option>
<option
v-for="option in optionsCache[field.options_source || ''] || []"
:key="String(option.value)"
:value="String(option.value)"
>
{{ option.label }}
</option>
</select>
<!-- multi_select(多选,动态选项,复选框列表) -->
<div
v-else-if="field.type === 'multi_select'"
class="max-h-52 space-y-1 overflow-y-auto rounded-xl border border-default bg-surface p-2"
>
<p v-if="optionsLoading[field.options_source || '']" class="px-2 py-1 text-xs text-muted">
{{ $t('admin.schedule.form.dynamicParamsOptionsLoading') }}
</p>
<p
v-else-if="!(optionsCache[field.options_source || ''] || []).length"
class="px-2 py-1 text-xs text-muted"
>
{{ $t('admin.schedule.form.dynamicParamsNoOptions') }}
</p>
<label
v-for="option in optionsCache[field.options_source || ''] || []"
:key="String(option.value)"
class="flex cursor-pointer items-start gap-2 rounded-lg px-2 py-1.5 text-sm transition hover:bg-surface-soft"
>
<input
type="checkbox"
class="mt-0.5 h-3.5 w-3.5 rounded text-blue-600"
:checked="Array.isArray(params[field.key]) && params[field.key].includes(option.value)"
@change="toggleMultiValue(field.key, option.value)"
/>
<span class="min-w-0">
<span class="block text-secondary">{{ option.label }}</span>
<span v-if="option.description" class="block text-xs text-muted">{{ option.description }}</span>
</span>
</label>
</div>
<p v-if="resolveText(field.help_key, field.help)" class="mt-1 text-xs text-muted">
{{ resolveText(field.help_key, field.help) }}
</p>
</template>
</div>
<!-- 高级配置折叠 JSON(写入 job_params._advanced,兜底历史/特殊任务) -->
<details class="rounded-xl border border-default bg-surface">
<summary class="cursor-pointer rounded-xl px-3 py-2 text-xs font-semibold text-secondary hover:bg-surface-soft">
{{ $t('admin.schedule.form.dynamicParamsAdvanced') }}
</summary>
<div class="px-3 pb-3 pt-1">
<textarea
v-model="advancedJsonText"
class="w-full min-h-[72px] input-field p-3 text-xs leading-relaxed text-secondary font-mono resize-y"
:class="advancedJsonError ? '!border-rose-300' : ''"
:placeholder="$t('admin.schedule.form.dynamicParamsAdvancedPlaceholder')"
@input="handleAdvancedInput"
></textarea>
<p v-if="advancedJsonError" class="mt-1 text-xs text-rose-600">
{{ $t('admin.schedule.form.dynamicParamsAdvancedInvalid') }}
</p>
</div>
</details>
</div>
</template>
@@ -2,11 +2,13 @@
/**
* features/admin/modules/schedules/components/ScheduleCreateEditModal.vue
* 用途:定时任务创建/编辑弹窗。
* 依赖:schedules.context、ScheduleCronDesigner。
* 逻辑:平台 Job 下拉展示由 registry 返回的 label_key 经 $t() 渲染,前端不维护 key→i18n 映射。
* 依赖:schedules.context、ScheduleCronDesigner、DynamicTaskParamsForm。
* 逻辑:平台 Job 下拉展示由 registry 返回的 label_key 经 $t() 渲染;平台任务参数区由
* DynamicTaskParamsForm 按 params_schema 通用渲染,本组件不再按任务硬编码 v-if。
*/
import { ChevronDown, ChevronUp, Plus } from 'lucide-vue-next';
import { useScheduleCreateModalOpen, useSchedulesAdminContext } from '../composables/schedules.context';
import DynamicTaskParamsForm from './DynamicTaskParamsForm.vue';
import ScheduleCronDesigner from './ScheduleCronDesigner.vue';
const admin = useSchedulesAdminContext();
@@ -102,6 +104,7 @@ const showCreateModal = useScheduleCreateModalOpen();
<select
v-model="admin.scheduleCreateForm.platform_api_path"
class="input-field w-full !text-sm !leading-5"
@change="admin.handlePlatformJobChange"
>
<option :value="null">{{ $t('admin.schedule.form.selectPlatformJob') }}</option>
<option v-for="job in admin.platformJobs" :key="job.key" :value="job.key">
@@ -297,38 +300,18 @@ const showCreateModal = useScheduleCreateModalOpen();
</template>
</div>
<!-- 平台任务参数区:完全由注册表 params_schema 决定,无任务级 v-if -->
<div
v-if="admin.scheduleCreateForm.schedule_type === 'platform_job'"
class="mt-3 space-y-3"
v-if="admin.scheduleCreateForm.schedule_type === 'platform_job' && admin.selectedPlatformTaskDefinition"
class="mt-3"
>
<div
v-if="admin.scheduleCreateForm.platform_api_path === 'faq-aggregate-hot'"
class="rounded-xl border border-amber-200 bg-amber-50/60 p-4 space-y-3"
>
<p class="text-sm text-amber-900">{{ $t('admin.schedule.form.faqHotAggregateHint') }}</p>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.faqHotAgentFilter') }}</label>
<select v-model="admin.scheduleCreateForm.dify_agent_id" class="input-field !text-sm !leading-5" :disabled="admin.agents.length === 0">
<option :value="null">{{ $t('admin.schedule.form.faqHotAllAgents') }}</option>
<option v-for="agent in admin.agents" :key="agent.id" :value="agent.id">{{ agent.name }}</option>
</select>
<p class="mt-1 text-xs text-muted">{{ $t('admin.schedule.form.faqHotAgentFilterHelp') }}</p>
</div>
</div>
<div
v-if="admin.scheduleCreateForm.platform_api_path === 'shipping-inventory-rpa'"
class="rounded-xl border border-blue-200 bg-blue-50/40 p-4 space-y-2"
>
<p class="text-sm text-blue-900">{{ $t('admin.schedule.form.shippingInventoryJobHint') }}</p>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.shippingInventoryJobParams') }}</label>
<textarea
v-model="admin.scheduleSqlEditForm.api_body_template"
class="w-full min-h-[80px] input-field p-3 text-xs leading-relaxed text-secondary font-mono resize-y"
:placeholder="$t('admin.schedule.form.shippingInventoryJobParamsPlaceholder')"
></textarea>
</div>
</div>
<DynamicTaskParamsForm
:definition="admin.selectedPlatformTaskDefinition"
:model-value="admin.scheduleCreateForm.job_params"
:valid="admin.platformJobParamsValid"
@update:model-value="admin.scheduleCreateForm.job_params = $event"
@update:valid="admin.platformJobParamsValid = $event"
/>
</div>
<div v-if="admin.scheduleTestResult" class="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
@@ -211,7 +211,13 @@ const admin = useSchedulesAdminContext();
</td>
<td class="max-w-0 truncate px-4 py-2.5">{{ r.total_count }}</td>
<td class="max-w-0 truncate px-4 py-2.5">{{ r.success_count }}</td>
<td class="max-w-0 truncate px-4 py-2.5">{{ r.failed_count }}</td>
<td class="max-w-0 truncate px-4 py-2.5" :title="admin.getScheduleRunFailedCountTitle(r)">
<span>{{ r.failed_count }}</span>
<span
v-if="admin.isScheduleRunExcelExportFailed(r)"
class="ml-1 text-xs font-medium text-amber-600"
>+Excel</span>
</td>
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<span v-if="r.wecom_notified" class="inline-flex max-w-full shrink-0 items-center gap-1 truncate text-xs text-emerald-600" :title="$t('admin.schedule.notified')">
<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>
@@ -3,7 +3,7 @@
* 定时任务管理页共享 ref 与删除确认弹窗状态。
*/
import { ref } from 'vue';
import type { PlatformJobOption, ScheduleRun, ScheduleTask, TestScheduleRunResult } from '@/features/admin/api/schedule.api';
import type { PlatformJobOption, PlatformTaskDefinition, ScheduleRun, ScheduleTask, TestScheduleRunResult } from '@/features/admin/api/schedule.api';
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
import type { KbGroup } from '@/features/kb/api/kb.api';
import {
@@ -16,6 +16,8 @@ export function createScheduleAdminState() {
const users = ref<AdminUserRow[]>([]);
const kbGroups = ref<KbGroup[]>([]);
const platformJobs = ref<PlatformJobOption[]>([]);
/** 平台任务完整契约(含 params_schema),供 DynamicTaskParamsForm 渲染 */
const platformTaskDefinitions = ref<PlatformTaskDefinition[]>([]);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmTitle = ref('');
@@ -103,12 +105,14 @@ export function createScheduleAdminState() {
const scheduleNotifyUserQuery = ref('');
const scheduleOwnerDropdownOpen = ref(false);
const scheduleOwnerQuery = ref('');
const platformJobParamsValid = ref(true);
return {
agents,
users,
kbGroups,
platformJobs,
platformTaskDefinitions,
showDeleteConfirmDialog,
deleteConfirmTitle,
deleteConfirmMessage,
@@ -151,6 +155,7 @@ export function createScheduleAdminState() {
scheduleNotifyUserQuery,
scheduleOwnerDropdownOpen,
scheduleOwnerQuery,
platformJobParamsValid,
};
}
@@ -1,6 +1,9 @@
/**
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminForm.ts
* 创建/编辑弹窗:Cron 设计器、负责人/通知人、SQL 配置与提交。
* 用途:创建/编辑弹窗——Cron 设计器、负责人/通知人、SQL 配置、平台任务 job_params 契约与提交。
* 依赖:schedule.api(含 platform-tasks definitions)、schedule-admin.state、schedule-form-payload.utils。
* 逻辑:platform_job 参数由 DynamicTaskParamsForm 按 selectedPlatformTaskDefinition.params_schema
* 渲染并写入 form.job_params;历史任务(dify_agent_id / api_body_template)编辑时自动迁移。
*/
import { computed, markRaw, watch } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
@@ -27,7 +30,7 @@ import type { ScheduleAdminRuns } from './useScheduleAdminRuns';
export function useScheduleAdminForm(
state: ScheduleAdminState,
lookups: Pick<ScheduleAdminLookups, 'loadAgents' | 'loadUsers' | 'loadKbGroups' | 'loadPlatformJobs'>,
lookups: Pick<ScheduleAdminLookups, 'loadAgents' | 'loadUsers' | 'loadKbGroups' | 'loadPlatformJobs' | 'loadPlatformTaskDefinitions'>,
list: Pick<ScheduleAdminList, 'loadSchedules'>,
runs: Pick<ScheduleAdminRuns, 'viewScheduleRuns'>,
t: ComposerTranslation,
@@ -37,6 +40,7 @@ export function useScheduleAdminForm(
const cronDesigner = markRaw(useScheduleCronDesigner());
const {
users,
platformTaskDefinitions,
showScheduleCreateModal,
scheduleCreateSaving,
scheduleEditingId,
@@ -49,11 +53,33 @@ export function useScheduleAdminForm(
scheduleNotifyUserQuery,
scheduleOwnerDropdownOpen,
scheduleOwnerQuery,
platformJobParamsValid,
} = state;
let scheduleNotifyCloseTimer: ReturnType<typeof setTimeout> | null = null;
let scheduleOwnerCloseTimer: ReturnType<typeof setTimeout> | null = null;
/** 当前选中平台任务的完整契约(params_schema/defaults);未选中或非 platform_job 为 null */
const selectedPlatformTaskDefinition = computed(() => {
const form = scheduleCreateForm.value;
if (form.schedule_type !== 'platform_job' || !form.platform_api_path) return null;
return platformTaskDefinitions.value.find((d) => d.task_type === form.platform_api_path) || null;
});
/**
* 用户在下拉切换平台任务时重置参数为注册表默认值(避免脏参数带到别的任务)。
* 核心逻辑:由 modal select @change 触发(不用 watch,防止编辑回填被覆盖)。
*/
const handlePlatformJobChange = (): void => {
const definition = platformTaskDefinitions.value.find(
(d) => d.task_type === scheduleCreateForm.value.platform_api_path,
);
scheduleCreateForm.value.job_params = definition && Object.keys(definition.defaults || {}).length
? { ...definition.defaults }
: null;
platformJobParamsValid.value = true;
};
const formatUserOptionLabel = (u: AdminUserRow) =>
`${u.real_name || u.username}${u.employee_id ? `(${u.employee_id})` : ''}`;
@@ -96,6 +122,7 @@ export function useScheduleAdminForm(
scheduleNotifyDropdownOpen.value = false;
scheduleOwnerQuery.value = '';
scheduleOwnerDropdownOpen.value = false;
platformJobParamsValid.value = true;
cronDesigner.reset();
};
@@ -111,6 +138,26 @@ export function useScheduleAdminForm(
scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as ScheduleCreateForm['data_source_type'];
}
if (!cfg) return;
// 历史货代 RPA 任务兼容:job_params 为空时把旧 api_body_template JSON 迁移进 schema 表单
if (
scheduleCreateForm.value.schedule_type === 'platform_job'
&& scheduleCreateForm.value.platform_api_path === 'shipping-inventory-rpa'
&& !(scheduleCreateForm.value.job_params && Object.values(scheduleCreateForm.value.job_params).some((v) => Array.isArray(v) ? v.length : v))
&& (cfg.external_api?.body_template || '').trim()
) {
try {
const legacy = JSON.parse(cfg.external_api.body_template);
if (legacy && typeof legacy === 'object' && !Array.isArray(legacy)) {
const { source_codes: sourceCodes, ...rest } = legacy;
scheduleCreateForm.value.job_params = {
source_codes: Array.isArray(sourceCodes) ? sourceCodes : [],
...(Object.keys(rest).length ? { _advanced: rest } : {}),
};
}
} catch {
// 非法历史 JSON 不迁移,保留高级区手工处理
}
}
scheduleSqlEditForm.value = {
base_fetch_sql: cfg.base_fetch_sql || '',
fetch_where_conditions: cfg.fetch_where_conditions || '',
@@ -146,6 +193,7 @@ export function useScheduleAdminForm(
lookups.loadUsers(),
lookups.loadKbGroups(),
lookups.loadPlatformJobs(),
lookups.loadPlatformTaskDefinitions(),
]);
syncScheduleOwnerQuery();
try {
@@ -168,6 +216,7 @@ export function useScheduleAdminForm(
lookups.loadUsers(),
lookups.loadKbGroups(),
lookups.loadPlatformJobs(),
lookups.loadPlatformTaskDefinitions(),
]);
};
@@ -189,6 +238,13 @@ export function useScheduleAdminForm(
? ((task.data_source_type || 'database') as ScheduleCreateForm['data_source_type'])
: null,
platform_api_path: task.schedule_type === 'platform_job' ? (task.platform_api_path || null) : null,
// 历史 FAQ 任务兼容:无 job_params 时把旧 dify_agent_id 迁移为 app_id
job_params: task.schedule_type === 'platform_job'
? (task.job_params
|| (task.platform_api_path === 'faq-aggregate-hot' && task.dify_agent_id
? { app_id: task.dify_agent_id }
: null))
: null,
dify_agent_id: task.dify_agent_id || null,
owner_user_id: task.owner_user_id || null,
wait_seconds: task.wait_seconds || 0,
@@ -297,7 +353,6 @@ export function useScheduleAdminForm(
const form = scheduleCreateForm.value;
const isDataPipeline = form.schedule_type === 'data_pipeline';
const isPlatformJob = form.schedule_type === 'platform_job';
const isShippingRpa = isPlatformJob && form.platform_api_path === 'shipping-inventory-rpa';
const dst = form.data_source_type;
const hasAgent = !!form.dify_agent_id;
const hasSql = isDataPipeline && dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.trim();
@@ -307,6 +362,23 @@ export function useScheduleAdminForm(
msg.error(t('admin.schedule.msg.platformJobRequired'));
return;
}
if (isPlatformJob && selectedPlatformTaskDefinition.value && !platformJobParamsValid.value) {
msg.error(t('admin.schedule.form.dynamicParamsInvalid'));
return;
}
// 平台任务参数:按选中任务 params_schema 校验必填字段(后端保存时会再校验一次)
if (isPlatformJob && selectedPlatformTaskDefinition.value) {
const jobParams = form.job_params || {};
const missing = selectedPlatformTaskDefinition.value.params_schema.find((field) => {
if (!field.required || field.type === 'info') return false;
const value = jobParams[field.key];
return value === null || value === undefined || value === '' || (Array.isArray(value) && value.length === 0);
});
if (missing) {
msg.error(t('admin.schedule.msg.jobParamRequired', { field: missing.label_key ? t(missing.label_key) : missing.label }));
return;
}
}
if (isDataPipeline && !hasAgent && !hasSql && !hasApi) {
msg.error(t('admin.schedule.msg.configRequired'));
return;
@@ -339,10 +411,6 @@ export function useScheduleAdminForm(
headerLabels,
apiHeaders,
);
} else if (isShippingRpa && scheduleSqlEditForm.value.api_body_template.trim()) {
configPayload = {
api_body_template: scheduleSqlEditForm.value.api_body_template,
};
}
scheduleCreateSaving.value = true;
@@ -353,7 +421,8 @@ export function useScheduleAdminForm(
owner_user_id: form.owner_user_id,
cron_expr: cronDesigner.cronExpr.value,
wait_seconds: Math.max(0, Number(form.wait_seconds || 0)),
dify_agent_id: form.dify_agent_id || undefined,
// platform_job 参数走 job_params 契约通道;显式清空 dify_agent_id 避免旧参数通道残留
dify_agent_id: isPlatformJob ? null : (form.dify_agent_id || undefined),
notify_user_ids_json: form.notify_enabled ? form.notify_user_ids_json : [],
notify_enabled: form.notify_enabled,
kb_sync_enabled: isDataPipeline ? form.kb_sync_enabled : false,
@@ -361,7 +430,7 @@ export function useScheduleAdminForm(
enabled: form.enabled,
...(isDataPipeline
? { data_source_type: dst, platform_api_path: null }
: { data_source_type: null, platform_api_path: form.platform_api_path }),
: { data_source_type: null, platform_api_path: form.platform_api_path, job_params: form.job_params }),
...(configPayload ? { config: configPayload } : {}),
};
let resultData: { id?: number; schedule?: { id?: number } } | null = null;
@@ -390,6 +459,9 @@ export function useScheduleAdminForm(
return {
cronDesigner,
selectedPlatformTaskDefinition,
handlePlatformJobChange,
platformJobParamsValid,
filteredNotifyUsers,
filteredOwnerUsers,
openScheduleCreateModal,
@@ -1,14 +1,14 @@
/**
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminLookups.ts
* 定时任务表单依赖的下拉数据:Agent、用户、知识库分组。
* 定时任务表单依赖的下拉数据:Agent、用户、知识库分组、平台任务契约。
*/
import { listAdminAgents, listAdminUsers } from '@/features/admin/api/admin.api';
import { listAdminPlatformJobs } from '@/features/admin/api/schedule.api';
import { listAdminPlatformJobs, listAdminPlatformTaskDefinitions } from '@/features/admin/api/schedule.api';
import { getKbGroups } from '@/features/kb/api/kb.api';
import type { ScheduleAdminState } from './schedule-admin.state';
export function useScheduleAdminLookups(state: ScheduleAdminState) {
const { agents, users, kbGroups, platformJobs } = state;
const { agents, users, kbGroups, platformJobs, platformTaskDefinitions } = state;
const loadAgents = async (): Promise<void> => {
try {
@@ -50,11 +50,25 @@ export function useScheduleAdminLookups(state: ScheduleAdminState) {
}
};
/**
* 加载平台任务完整契约(task_type + params_schema + defaults)。
* 核心逻辑:GET /api/admin/platform-tasks/definitions,供 DynamicTaskParamsForm 按 schema 渲染。
*/
const loadPlatformTaskDefinitions = async (): Promise<void> => {
try {
platformTaskDefinitions.value = await listAdminPlatformTaskDefinitions();
} catch (e) {
console.error('Failed to load platform task definitions', e);
platformTaskDefinitions.value = [];
}
};
return {
loadAgents,
loadUsers,
loadKbGroups,
loadPlatformJobs,
loadPlatformTaskDefinitions,
};
}
@@ -8,6 +8,10 @@ import { listAdminScheduleRuns } from '@/features/admin/api/schedule.api';
import { useMessage } from '@/shared/composables/useMessage';
import { getAuthHeaders } from '@/shared/utils/auth';
import { formatDateTime } from '../../utils/schedule-format.utils';
import {
getScheduleRunFailedCountTitle as buildScheduleRunFailedCountTitle,
isScheduleRunExcelExportFailed,
} from '@/shared/utils/schedule-run-display.utils';
import type { ScheduleAdminState } from './schedule-admin.state';
export function useScheduleAdminRuns(
@@ -194,6 +198,9 @@ export function useScheduleAdminRuns(
URL.revokeObjectURL(url);
};
const getScheduleRunFailedCountTitle = (run: (typeof selectedScheduleRuns.value)[number]) =>
buildScheduleRunFailedCountTitle(run, t('admin.schedule.excelExportFailedHint'));
return {
selectedSchedule,
scheduleRunStatusOptions,
@@ -209,6 +216,8 @@ export function useScheduleAdminRuns(
downloadScheduleExcel,
startScheduleColResize,
formatDateTime,
isScheduleRunExcelExportFailed,
getScheduleRunFailedCountTitle,
};
}
@@ -38,6 +38,8 @@ export interface ScheduleCreateForm {
schedule_type: ScheduleExecutionMode;
data_source_type: ScheduleDataSourceType | null;
platform_api_path: PlatformJobKey | string | null;
/** platform_job 结构化参数(DynamicTaskParamsForm 输出,按注册表 params_schema 校验) */
job_params: Record<string, any> | null;
dify_agent_id: number | null;
owner_user_id: number | null;
wait_seconds: number;
@@ -103,6 +105,7 @@ export function createDefaultScheduleCreateForm(): ScheduleCreateForm {
schedule_type: 'data_pipeline',
data_source_type: 'database',
platform_api_path: null,
job_params: null,
dify_agent_id: null,
owner_user_id: null,
wait_seconds: 300,