feat(chat): 新增对话流性能监控功能及相关日志输出
This commit is contained in:
1 parent
e827c5dc38
commit
9d7dad6a4b
19 files changed
+1603
-271
No files matched your search
@@ -9,6 +9,7 @@ import {
|
||||
Plus, Power, PowerOff, RefreshCw, Rocket, Settings2, Trash2,
|
||||
} from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import ScheduleCronDesigner from './components/ScheduleCronDesigner.vue';
|
||||
import { useSchedulesAdmin } from './composables/useSchedulesAdmin';
|
||||
|
||||
const admin = useSchedulesAdmin();
|
||||
@@ -19,7 +20,7 @@ const {
|
||||
selectedScheduleId, scheduleRunStatusFilter, scheduleRunStartedAfter, scheduleRunStartedBefore,
|
||||
scheduleRunColumnDefs, scheduleViewMode, showScheduleCreateModal, scheduleCreateSaving,
|
||||
scheduleEditingId, scheduleCreateForm, scheduleConfigCollapsed, scheduleCronDesigner,
|
||||
weeklyDayOptions, scheduleCronPreview, scheduleNextRunPreview, selectedSchedule,
|
||||
scheduleCronValid, selectedSchedule,
|
||||
scheduleRunStatusOptions, getScheduleRunStatusBadge, formatDateTime, expandedScheduleRunId,
|
||||
expandedScheduleRun, stepLabelMap, stepStatusMap, showTestRunDialog, testRunSchedule,
|
||||
testRunWhere, testRunOrderBy, testRunBaseFetchSql, testRunLimit, testRunKbSync, testRunKbSyncAvailable,
|
||||
@@ -135,7 +136,7 @@ const {
|
||||
</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 class="mt-1 text-sm text-muted">{{ $t('admin.schedule.form.cronLabel') }}{{ s.cron_expr }}</div>
|
||||
<div
|
||||
v-if="s.schedule_type === 'platform_app' && s.platform_api_path"
|
||||
class="mt-1 text-sm text-muted"
|
||||
@@ -1033,103 +1034,7 @@ const {
|
||||
></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>
|
||||
<ScheduleCronDesigner :designer="scheduleCronDesigner" :format-date-time="formatDateTime" />
|
||||
|
||||
<div class="input-field px-3 py-2.5">
|
||||
<div class="flex flex-col gap-2 md:flex-row md:items-center">
|
||||
@@ -1211,7 +1116,7 @@ const {
|
||||
<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"
|
||||
:disabled="scheduleCreateSaving || !scheduleCreateForm.name || !scheduleCreateForm.owner_user_id || !scheduleCronValid"
|
||||
@click="createSchedule"
|
||||
>
|
||||
<Plus class="h-4 w-4 shrink-0" />
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
/**
|
||||
* ScheduleCronDesigner.vue
|
||||
* 排程运行时间图形化 / 高级 Cron 设计器。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import type { useScheduleCronDesigner } from '../composables/useScheduleCronDesigner';
|
||||
|
||||
const props = defineProps<{
|
||||
designer: ReturnType<typeof useScheduleCronDesigner>;
|
||||
formatDateTime: (iso: string | null | undefined) => string;
|
||||
}>();
|
||||
|
||||
const d = props.designer;
|
||||
const { state, cronExpr, isValid, nextRunAt, weekdayOptions } = d;
|
||||
|
||||
const handleSwitchVisual = () => {
|
||||
if (state.value.editorMode === 'visual') return;
|
||||
d.switchToVisual();
|
||||
};
|
||||
|
||||
const handleSwitchAdvanced = () => {
|
||||
if (state.value.editorMode === 'advanced') return;
|
||||
d.switchToAdvanced();
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-2xl border border-default bg-surface-soft/40 p-4">
|
||||
<div class="mb-4 space-y-3">
|
||||
<div class="min-w-0">
|
||||
<h4 class="text-base font-bold text-primary">{{ $t('admin.schedule.form.cronTitle') }}</h4>
|
||||
<p class="mt-1 text-sm leading-relaxed text-muted">{{ $t('admin.schedule.form.cronHint') }}</p>
|
||||
</div>
|
||||
<div
|
||||
class="segment-control segment-control--cols-2 segment-control--sm w-full max-w-xs"
|
||||
role="radiogroup"
|
||||
:aria-label="$t('admin.schedule.form.cronTitle')"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
:aria-checked="state.editorMode === 'visual'"
|
||||
class="segment-item"
|
||||
:class="state.editorMode === 'visual' ? 'segment-item--active' : ''"
|
||||
@click="handleSwitchVisual"
|
||||
>
|
||||
{{ $t('admin.schedule.form.editorVisual') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
:aria-checked="state.editorMode === 'advanced'"
|
||||
class="segment-item"
|
||||
:class="state.editorMode === 'advanced' ? 'segment-item--active' : ''"
|
||||
@click="handleSwitchAdvanced"
|
||||
>
|
||||
{{ $t('admin.schedule.form.editorAdvanced') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-if="state.parseFailed && state.editorMode === 'advanced'"
|
||||
class="mb-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800"
|
||||
>
|
||||
{{ $t('admin.schedule.form.parseFailedHint') }}
|
||||
</p>
|
||||
|
||||
<template v-if="state.editorMode === 'visual'">
|
||||
<div class="mb-4">
|
||||
<div class="mb-2">
|
||||
<span class="text-xs font-semibold uppercase text-muted">{{ $t('admin.schedule.form.presetsTitle') }}</span>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="button" class="rounded-lg border border-default bg-surface px-3 py-1.5 text-xs font-medium text-secondary transition hover:border-blue-300 hover:text-primary" @click="d.setPreset('every_minutes')">
|
||||
{{ $t('admin.schedule.form.everyMinutes') }}
|
||||
</button>
|
||||
<button type="button" class="rounded-lg border border-default bg-surface px-3 py-1.5 text-xs font-medium text-secondary transition hover:border-blue-300 hover:text-primary" @click="d.setPreset('hourly')">
|
||||
{{ $t('admin.schedule.form.hourly') }}
|
||||
</button>
|
||||
<button type="button" class="rounded-lg border border-default bg-surface px-3 py-1.5 text-xs font-medium text-secondary transition hover:border-blue-300 hover:text-primary" @click="d.setPreset('daily')">
|
||||
{{ $t('admin.schedule.form.daily') }}
|
||||
</button>
|
||||
<button type="button" class="rounded-lg border border-default bg-surface px-3 py-1.5 text-xs font-medium text-secondary transition hover:border-blue-300 hover:text-primary" @click="d.setPreset('weekly')">
|
||||
{{ $t('admin.schedule.form.weekly') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 月别 -->
|
||||
<div class="mb-4">
|
||||
<div class="mb-2 flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="text-xs font-semibold uppercase text-muted">{{ $t('admin.schedule.form.months') }}</span>
|
||||
<div class="flex gap-2 text-xs">
|
||||
<button type="button" class="text-blue-600 hover:underline" @click="d.selectAllMonths()">{{ $t('admin.schedule.form.selectAll') }}</button>
|
||||
<button type="button" class="text-muted hover:underline" @click="d.clearAllMonths()">{{ $t('admin.schedule.form.clearAll') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<label
|
||||
v-for="m in 12"
|
||||
:key="m"
|
||||
class="inline-flex cursor-pointer items-center gap-1 rounded-md border px-2 py-1 text-xs transition"
|
||||
:class="d.isMonthSelected(m) ? 'border-blue-300 bg-blue-50 text-blue-700' : 'border-default bg-surface text-secondary'"
|
||||
>
|
||||
<input type="checkbox" class="sr-only" :checked="d.isMonthSelected(m)" @change="d.toggleMonth(m)" />
|
||||
{{ String(m).padStart(2, '0') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 周别 -->
|
||||
<div class="mb-4">
|
||||
<div class="mb-2 flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="text-xs font-semibold uppercase text-muted">{{ $t('admin.schedule.form.weekdays') }}</span>
|
||||
<div class="flex gap-2 text-xs">
|
||||
<button type="button" class="text-blue-600 hover:underline" @click="d.selectAllWeekdays()">{{ $t('admin.schedule.form.selectAll') }}</button>
|
||||
<button type="button" class="text-muted hover:underline" @click="d.clearAllWeekdays()">{{ $t('admin.schedule.form.clearAll') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<label
|
||||
v-for="wd in weekdayOptions"
|
||||
:key="wd.value"
|
||||
class="inline-flex cursor-pointer items-center gap-1 rounded-md border px-2.5 py-1 text-xs transition"
|
||||
:class="d.isWeekdaySelected(wd.value) ? 'border-blue-300 bg-blue-50 text-blue-700' : 'border-default bg-surface text-secondary'"
|
||||
>
|
||||
<input type="checkbox" class="sr-only" :checked="d.isWeekdaySelected(wd.value)" @change="d.toggleWeekday(wd.value)" />
|
||||
{{ wd.label }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 日别 -->
|
||||
<div class="mb-4">
|
||||
<div class="mb-2 flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="text-xs font-semibold uppercase text-muted">{{ $t('admin.schedule.form.daysOfMonth') }}</span>
|
||||
<div class="flex gap-2 text-xs">
|
||||
<button type="button" class="text-blue-600 hover:underline" @click="d.selectAllDaysOfMonth()">{{ $t('admin.schedule.form.selectAll') }}</button>
|
||||
<button type="button" class="text-muted hover:underline" @click="d.clearAllDaysOfMonth()">{{ $t('admin.schedule.form.clearAll') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="mb-2 text-xs text-muted">{{ $t('admin.schedule.form.domDowHint') }}</p>
|
||||
<div class="grid grid-cols-7 gap-1.5">
|
||||
<label
|
||||
v-for="day in 31"
|
||||
:key="day"
|
||||
class="inline-flex cursor-pointer items-center justify-center rounded-md border py-1 text-xs transition"
|
||||
:class="d.isDayOfMonthSelected(day) ? 'border-blue-300 bg-blue-50 text-blue-700' : 'border-default bg-surface text-secondary'"
|
||||
>
|
||||
<input type="checkbox" class="sr-only" :checked="d.isDayOfMonthSelected(day)" @change="d.toggleDayOfMonth(day)" />
|
||||
{{ String(day).padStart(2, '0') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 执行时刻 -->
|
||||
<div class="mb-4 rounded-xl border border-default bg-surface p-4">
|
||||
<div class="mb-3 text-xs font-semibold uppercase text-muted">{{ $t('admin.schedule.form.timeModeTitle') }}</div>
|
||||
<div class="mb-4 flex flex-wrap gap-4">
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary">
|
||||
<input v-model="state.timeMode" type="radio" value="fixed" class="h-4 w-4 text-blue-600" />
|
||||
{{ $t('admin.schedule.form.timeModeFixed') }}
|
||||
</label>
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary">
|
||||
<input v-model="state.timeMode" type="radio" value="interval" class="h-4 w-4 text-blue-600" />
|
||||
{{ $t('admin.schedule.form.timeModeInterval') }}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div v-if="state.timeMode === 'fixed'" class="grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.hour') }}</label>
|
||||
<input
|
||||
v-model.number="state.fixedHour"
|
||||
type="number"
|
||||
min="0"
|
||||
max="23"
|
||||
class="input-field !text-sm !leading-5"
|
||||
:disabled="state.wildcardHour"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.minute') }}</label>
|
||||
<input v-model.number="state.fixedMinute" type="number" min="0" max="59" class="input-field !text-sm !leading-5" />
|
||||
</div>
|
||||
<div v-if="state.wildcardHour" class="col-span-2 flex items-end">
|
||||
<span class="text-xs text-muted">{{ $t('admin.schedule.form.hourlyHint') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.timeStart') }}</label>
|
||||
<div class="flex gap-1">
|
||||
<input v-model.number="state.rangeStartHour" type="number" min="0" max="23" class="input-field !text-sm !leading-5 w-full" :placeholder="$t('admin.schedule.form.hour')" />
|
||||
<span class="self-center text-muted">:</span>
|
||||
<input v-model.number="state.rangeStartMinute" type="number" min="0" max="59" class="input-field !text-sm !leading-5 w-full" :placeholder="$t('admin.schedule.form.minute')" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.timeEnd') }}</label>
|
||||
<div class="flex gap-1">
|
||||
<input v-model.number="state.rangeEndHour" type="number" min="0" max="23" class="input-field !text-sm !leading-5 w-full" :placeholder="$t('admin.schedule.form.hour')" />
|
||||
<span class="self-center text-muted">:</span>
|
||||
<input v-model.number="state.rangeEndMinute" type="number" min="0" max="59" class="input-field !text-sm !leading-5 w-full" :placeholder="$t('admin.schedule.form.minute')" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.intervalMinutes') }}</label>
|
||||
<input v-model.number="state.intervalMinutes" type="number" min="1" max="59" class="input-field !text-sm !leading-5" />
|
||||
</div>
|
||||
<div class="col-span-2 flex items-end md:col-span-1">
|
||||
<p class="text-xs text-muted">{{ $t('admin.schedule.form.intervalHourHint') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.advancedCronInput') }}</label>
|
||||
<input
|
||||
v-model="state.advancedCronExpr"
|
||||
type="text"
|
||||
class="input-field font-mono !text-sm"
|
||||
placeholder="0 9 * * 1-5"
|
||||
spellcheck="false"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-muted">{{ $t('admin.schedule.form.advancedCronHint') }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div
|
||||
class="mt-4 flex flex-col gap-1.5 rounded-xl border border-dashed px-4 py-3 text-xs sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-4"
|
||||
:class="isValid ? 'border-default bg-surface-soft text-secondary' : 'border-red-200 bg-red-50 text-red-700'"
|
||||
>
|
||||
<span>
|
||||
{{ $t('admin.schedule.form.cronPreview') }}:<span class="font-mono text-primary">{{ cronExpr }}</span>
|
||||
</span>
|
||||
<span v-if="nextRunAt && isValid">
|
||||
{{ $t('admin.schedule.form.nextRun') }}:
|
||||
<span class="font-medium text-primary">{{ formatDateTime(nextRunAt.toISOString()) }}</span>
|
||||
</span>
|
||||
<span v-if="!isValid">{{ $t('admin.schedule.form.cronInvalid') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* scheduleCronDesigner.utils.spec.ts
|
||||
* 排程 Cron 设计器纯函数单测。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
applyPreset,
|
||||
buildCronExpr,
|
||||
defaultCronDesignerState,
|
||||
parseCronExpr,
|
||||
toCronField,
|
||||
validateCronDesignerState,
|
||||
} from './scheduleCronDesigner.utils';
|
||||
|
||||
describe('scheduleCronDesigner.utils', () => {
|
||||
it('builds every-minutes cron', () => {
|
||||
const state = applyPreset('every_minutes', defaultCronDesignerState(), { everyMinutes: 30 });
|
||||
expect(buildCronExpr(state)).toBe('*/30 * * * *');
|
||||
});
|
||||
|
||||
it('builds hourly cron', () => {
|
||||
const state = applyPreset('hourly', defaultCronDesignerState());
|
||||
state.fixedMinute = 15;
|
||||
expect(buildCronExpr(state)).toBe('15 * * * *');
|
||||
});
|
||||
|
||||
it('builds daily cron', () => {
|
||||
const state = applyPreset('daily', defaultCronDesignerState());
|
||||
expect(buildCronExpr(state)).toBe('0 9 * * *');
|
||||
});
|
||||
|
||||
it('builds weekly cron', () => {
|
||||
const state = applyPreset('weekly', defaultCronDesignerState(), { weeklyDay: 1 });
|
||||
expect(buildCronExpr(state)).toBe('0 9 * * 1');
|
||||
});
|
||||
|
||||
it('builds interval range with weekday filter', () => {
|
||||
const state = defaultCronDesignerState();
|
||||
state.timeMode = 'interval';
|
||||
state.intervalMinutes = 15;
|
||||
state.rangeStartHour = 9;
|
||||
state.rangeEndHour = 17;
|
||||
state.weekdays = [1, 2, 3, 4, 5];
|
||||
expect(buildCronExpr(state)).toBe('*/15 9-17 * * 1-5');
|
||||
});
|
||||
|
||||
it('builds fixed time with month and day filters', () => {
|
||||
const state = defaultCronDesignerState();
|
||||
state.timeMode = 'fixed';
|
||||
state.fixedHour = 8;
|
||||
state.fixedMinute = 30;
|
||||
state.months = [1, 6, 12];
|
||||
state.daysOfMonth = [1, 15];
|
||||
expect(buildCronExpr(state)).toBe('30 8 1,15 1,6,12 *');
|
||||
});
|
||||
|
||||
it('parses legacy every-minutes expression', () => {
|
||||
const result = parseCronExpr('*/30 * * * *');
|
||||
expect(result.ok).toBe(true);
|
||||
expect(result.state?.timeMode).toBe('interval');
|
||||
expect(result.state?.intervalMinutes).toBe(30);
|
||||
});
|
||||
|
||||
it('parses interval range expression', () => {
|
||||
const result = parseCronExpr('*/15 9-17 * * 1-5');
|
||||
expect(result.ok).toBe(true);
|
||||
expect(result.state?.intervalMinutes).toBe(15);
|
||||
expect(result.state?.rangeStartHour).toBe(9);
|
||||
expect(result.state?.rangeEndHour).toBe(17);
|
||||
expect(result.state?.weekdays).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it('round-trips daily expression', () => {
|
||||
const parsed = parseCronExpr('30 8 * * *');
|
||||
expect(parsed.ok).toBe(true);
|
||||
expect(buildCronExpr(parsed.state!)).toBe('30 8 * * *');
|
||||
});
|
||||
|
||||
it('fails parse for unsupported expression', () => {
|
||||
expect(parseCronExpr('0/5 * * * *').ok).toBe(false);
|
||||
expect(parseCronExpr('* * * *').ok).toBe(false);
|
||||
});
|
||||
|
||||
it('compresses consecutive values in cron field', () => {
|
||||
expect(toCronField([1, 2, 3, 4, 5], 1, 12)).toBe('1-5');
|
||||
expect(toCronField(null, 1, 12)).toBe('*');
|
||||
});
|
||||
|
||||
it('invalidates empty calendar selection', () => {
|
||||
const state = defaultCronDesignerState();
|
||||
state.months = [];
|
||||
expect(validateCronDesignerState(state)).toBe(false);
|
||||
});
|
||||
});
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
* scheduleCronDesigner.utils.ts
|
||||
* 排程 Cron 图形化设计器的纯函数:生成、解析、校验与下次执行预览。
|
||||
*/
|
||||
|
||||
export type CronEditorMode = 'visual' | 'advanced';
|
||||
export type CronTimeMode = 'fixed' | 'interval';
|
||||
export type CronPreset = 'every_minutes' | 'hourly' | 'daily' | 'weekly';
|
||||
|
||||
export interface ScheduleCronDesignerState {
|
||||
editorMode: CronEditorMode;
|
||||
advancedCronExpr: string;
|
||||
parseFailed: boolean;
|
||||
/** null 表示全选(*),空数组表示未选(无效) */
|
||||
months: number[] | null;
|
||||
weekdays: number[] | null;
|
||||
daysOfMonth: number[] | null;
|
||||
timeMode: CronTimeMode;
|
||||
fixedHour: number;
|
||||
fixedMinute: number;
|
||||
intervalMinutes: number;
|
||||
rangeStartHour: number;
|
||||
rangeStartMinute: number;
|
||||
rangeEndHour: number;
|
||||
rangeEndMinute: number;
|
||||
/** 每小时模式:小时字段为 * */
|
||||
wildcardHour: boolean;
|
||||
}
|
||||
|
||||
export const ALL_MONTHS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] as const;
|
||||
export const ALL_WEEKDAYS = [0, 1, 2, 3, 4, 5, 6] as const;
|
||||
export const ALL_DAYS_OF_MONTH = Array.from({ length: 31 }, (_, i) => i + 1);
|
||||
|
||||
export function defaultCronDesignerState(): ScheduleCronDesignerState {
|
||||
return {
|
||||
editorMode: 'visual',
|
||||
advancedCronExpr: '*/30 * * * *',
|
||||
parseFailed: false,
|
||||
months: null,
|
||||
weekdays: null,
|
||||
daysOfMonth: null,
|
||||
timeMode: 'interval',
|
||||
fixedHour: 9,
|
||||
fixedMinute: 0,
|
||||
intervalMinutes: 30,
|
||||
rangeStartHour: 0,
|
||||
rangeStartMinute: 0,
|
||||
rangeEndHour: 23,
|
||||
rangeEndMinute: 0,
|
||||
wildcardHour: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** 将数字数组压缩为 cron 字段(连续段用 a-b)。null 或全量视为 *。 */
|
||||
export function toCronField(values: number[] | null, min: number, max: number): string {
|
||||
const fullCount = max - min + 1;
|
||||
if (values === null || values.length >= fullCount) return '*';
|
||||
if (values.length === 0) return '*';
|
||||
const sorted = [...new Set(values.filter((v) => v >= min && v <= max))].sort((a, b) => a - b);
|
||||
if (sorted.length === 0) return '*';
|
||||
if (sorted.length >= fullCount) return '*';
|
||||
|
||||
const parts: string[] = [];
|
||||
let start = sorted[0]!;
|
||||
let prev = start;
|
||||
for (let i = 1; i < sorted.length; i++) {
|
||||
const cur = sorted[i]!;
|
||||
if (cur === prev + 1) {
|
||||
prev = cur;
|
||||
continue;
|
||||
}
|
||||
parts.push(start === prev ? String(start) : `${start}-${prev}`);
|
||||
start = prev = cur;
|
||||
}
|
||||
parts.push(start === prev ? String(start) : `${start}-${prev}`);
|
||||
return parts.join(',');
|
||||
}
|
||||
|
||||
/** 解析 cron 单字段为数组;* 返回 null 表示全选。 */
|
||||
export function parseCronFieldToArray(field: string, min: number, max: number): number[] | null {
|
||||
const text = String(field || '').trim();
|
||||
if (!text || text === '*') return null;
|
||||
const result = new Set<number>();
|
||||
for (const segment of text.split(',')) {
|
||||
const part = segment.trim();
|
||||
if (!part) continue;
|
||||
if (part.includes('/')) return null; // 步进语法不在日历字段中解析
|
||||
if (part.includes('-')) {
|
||||
const [rawStart, rawEnd] = part.split('-');
|
||||
const start = Number(rawStart);
|
||||
const end = Number(rawEnd);
|
||||
if (Number.isNaN(start) || Number.isNaN(end)) continue;
|
||||
for (let i = start; i <= end; i++) {
|
||||
if (i >= min && i <= max) result.add(i);
|
||||
}
|
||||
} else {
|
||||
const n = Number(part);
|
||||
if (!Number.isNaN(n) && n >= min && n <= max) result.add(n);
|
||||
}
|
||||
}
|
||||
return Array.from(result).sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
export function buildCronExpr(state: ScheduleCronDesignerState): string {
|
||||
const dom = toCronField(state.daysOfMonth, 1, 31);
|
||||
const month = toCronField(state.months, 1, 12);
|
||||
const dow = toCronField(state.weekdays, 0, 6);
|
||||
|
||||
if (state.timeMode === 'fixed') {
|
||||
const minute = clamp(state.fixedMinute, 0, 59);
|
||||
const hourPart = state.wildcardHour ? '*' : String(clamp(state.fixedHour, 0, 23));
|
||||
return `${minute} ${hourPart} ${dom} ${month} ${dow}`;
|
||||
}
|
||||
|
||||
const interval = clamp(state.intervalMinutes, 1, 59);
|
||||
const hStart = clamp(state.rangeStartHour, 0, 23);
|
||||
const hEnd = clamp(state.rangeEndHour, 0, 23);
|
||||
const hourPart = hStart === 0 && hEnd === 23 ? '*' : `${Math.min(hStart, hEnd)}-${Math.max(hStart, hEnd)}`;
|
||||
return `*/${interval} ${hourPart} ${dom} ${month} ${dow}`;
|
||||
}
|
||||
|
||||
export interface ParseCronResult {
|
||||
ok: boolean;
|
||||
state?: ScheduleCronDesignerState;
|
||||
}
|
||||
|
||||
export function parseCronExpr(expr: string | null | undefined): ParseCronResult {
|
||||
const text = String(expr || '').trim();
|
||||
const parts = text.split(/\s+/);
|
||||
if (parts.length !== 5) return { ok: false };
|
||||
|
||||
const [minPart, hourPart, domPart, monthPart, dowPart] = parts;
|
||||
if (!minPart || !hourPart || !domPart || !monthPart || !dowPart) return { ok: false };
|
||||
|
||||
const base = defaultCronDesignerState();
|
||||
base.months = parseCronFieldToArray(monthPart, 1, 12);
|
||||
base.daysOfMonth = parseCronFieldToArray(domPart, 1, 31);
|
||||
base.weekdays = parseCronFieldToArray(dowPart, 0, 6);
|
||||
base.advancedCronExpr = text;
|
||||
base.editorMode = 'visual';
|
||||
base.parseFailed = false;
|
||||
|
||||
// */N 分钟间隔
|
||||
if (/^\*\/\d+$/.test(minPart)) {
|
||||
const interval = Number(minPart.slice(2));
|
||||
if (Number.isNaN(interval) || interval < 1 || interval > 59) return { ok: false };
|
||||
base.timeMode = 'interval';
|
||||
base.intervalMinutes = interval;
|
||||
if (hourPart === '*') {
|
||||
base.rangeStartHour = 0;
|
||||
base.rangeEndHour = 23;
|
||||
return { ok: true, state: base };
|
||||
}
|
||||
if (/^\d+$/.test(hourPart)) {
|
||||
const h = Number(hourPart);
|
||||
base.rangeStartHour = h;
|
||||
base.rangeEndHour = h;
|
||||
return { ok: true, state: base };
|
||||
}
|
||||
if (/^\d+-\d+$/.test(hourPart)) {
|
||||
const [h1, h2] = hourPart.split('-').map(Number);
|
||||
if (Number.isNaN(h1!) || Number.isNaN(h2!)) return { ok: false };
|
||||
base.rangeStartHour = h1!;
|
||||
base.rangeEndHour = h2!;
|
||||
return { ok: true, state: base };
|
||||
}
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
// 整点每小时:M * * * *
|
||||
if (/^\d+$/.test(minPart) && hourPart === '*') {
|
||||
base.timeMode = 'fixed';
|
||||
base.fixedMinute = Number(minPart);
|
||||
base.wildcardHour = true;
|
||||
return { ok: true, state: base };
|
||||
}
|
||||
|
||||
// 指定时刻:M H ...
|
||||
if (/^\d+$/.test(minPart) && /^\d+$/.test(hourPart)) {
|
||||
base.timeMode = 'fixed';
|
||||
base.fixedMinute = Number(minPart);
|
||||
base.fixedHour = Number(hourPart);
|
||||
return { ok: true, state: base };
|
||||
}
|
||||
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
export function applyPreset(
|
||||
preset: CronPreset,
|
||||
state: ScheduleCronDesignerState,
|
||||
options?: { everyMinutes?: number; weeklyDay?: number },
|
||||
): ScheduleCronDesignerState {
|
||||
const next = { ...defaultCronDesignerState(), editorMode: state.editorMode, advancedCronExpr: state.advancedCronExpr };
|
||||
next.months = null;
|
||||
next.weekdays = null;
|
||||
next.daysOfMonth = null;
|
||||
|
||||
if (preset === 'every_minutes') {
|
||||
next.timeMode = 'interval';
|
||||
next.intervalMinutes = clamp(options?.everyMinutes ?? 30, 1, 59);
|
||||
next.rangeStartHour = 0;
|
||||
next.rangeEndHour = 23;
|
||||
next.advancedCronExpr = buildCronExpr(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
if (preset === 'hourly') {
|
||||
next.timeMode = 'fixed';
|
||||
next.fixedMinute = 0;
|
||||
next.wildcardHour = true;
|
||||
next.advancedCronExpr = buildCronExpr(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
if (preset === 'daily') {
|
||||
next.timeMode = 'fixed';
|
||||
next.fixedHour = 9;
|
||||
next.fixedMinute = 0;
|
||||
next.advancedCronExpr = buildCronExpr(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
// weekly
|
||||
const dow = options?.weeklyDay ?? 1;
|
||||
next.timeMode = 'fixed';
|
||||
next.fixedHour = 9;
|
||||
next.fixedMinute = 0;
|
||||
next.weekdays = [dow];
|
||||
next.advancedCronExpr = buildCronExpr(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function isCalendarValid(values: number[] | null): boolean {
|
||||
return values === null || values.length > 0;
|
||||
}
|
||||
|
||||
export function validateCronDesignerState(state: ScheduleCronDesignerState): boolean {
|
||||
if (state.editorMode === 'advanced') {
|
||||
const text = state.advancedCronExpr.trim();
|
||||
return text.length > 0 && text.split(/\s+/).length === 5;
|
||||
}
|
||||
|
||||
if (!isCalendarValid(state.months) || !isCalendarValid(state.weekdays) || !isCalendarValid(state.daysOfMonth)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (state.timeMode === 'fixed') {
|
||||
if (state.fixedHour < 0 || state.fixedHour > 23) return false;
|
||||
if (state.fixedMinute < 0 || state.fixedMinute > 59) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (state.intervalMinutes < 1 || state.intervalMinutes > 59) return false;
|
||||
if (state.rangeStartHour < 0 || state.rangeStartHour > 23) return false;
|
||||
if (state.rangeEndHour < 0 || state.rangeEndHour > 23) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function computeNextRunAt(
|
||||
expr: string,
|
||||
parseFn?: (e: string) => { next: () => { toDate: () => Date } },
|
||||
): Date | null {
|
||||
const text = String(expr || '').trim();
|
||||
if (!text || !parseFn) return null;
|
||||
try {
|
||||
return parseFn(text).next().toDate();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
const n = Number(value);
|
||||
if (Number.isNaN(n)) return min;
|
||||
return Math.max(min, Math.min(max, Math.floor(n)));
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* useScheduleCronDesigner.ts
|
||||
* 排程 Cron 图形化设计器 composable。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
import {
|
||||
applyPreset,
|
||||
buildCronExpr,
|
||||
computeNextRunAt,
|
||||
defaultCronDesignerState,
|
||||
parseCronExpr,
|
||||
validateCronDesignerState,
|
||||
type CronPreset,
|
||||
type ScheduleCronDesignerState,
|
||||
} from './scheduleCronDesigner.utils';
|
||||
|
||||
export function useScheduleCronDesigner() {
|
||||
const { t } = useI18n();
|
||||
const state = ref<ScheduleCronDesignerState>(defaultCronDesignerState());
|
||||
|
||||
const cronExpr = computed(() => {
|
||||
if (state.value.editorMode === 'advanced') {
|
||||
return state.value.advancedCronExpr.trim();
|
||||
}
|
||||
return buildCronExpr(state.value);
|
||||
});
|
||||
|
||||
const isValid = computed(() => validateCronDesignerState(state.value));
|
||||
|
||||
const nextRunAt = computed(() =>
|
||||
computeNextRunAt(cronExpr.value, (expr) => {
|
||||
const normalized = normalizeCronForParser(expr);
|
||||
return CronExpressionParser.parse(normalized);
|
||||
}),
|
||||
);
|
||||
|
||||
const loadFromExpr = (expr: string | null | undefined) => {
|
||||
const result = parseCronExpr(expr);
|
||||
if (result.ok && result.state) {
|
||||
state.value = {
|
||||
...result.state,
|
||||
advancedCronExpr: String(expr || '').trim() || buildCronExpr(result.state),
|
||||
parseFailed: false,
|
||||
};
|
||||
return;
|
||||
}
|
||||
const text = String(expr || '').trim();
|
||||
state.value = {
|
||||
...defaultCronDesignerState(),
|
||||
editorMode: 'advanced',
|
||||
advancedCronExpr: text || '*/30 * * * *',
|
||||
parseFailed: !!text,
|
||||
};
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
state.value = defaultCronDesignerState();
|
||||
};
|
||||
|
||||
const switchToAdvanced = () => {
|
||||
if (state.value.editorMode !== 'advanced') {
|
||||
state.value.advancedCronExpr = buildCronExpr(state.value);
|
||||
}
|
||||
state.value.editorMode = 'advanced';
|
||||
state.value.parseFailed = false;
|
||||
};
|
||||
|
||||
const switchToVisual = (): boolean => {
|
||||
const result = parseCronExpr(state.value.advancedCronExpr);
|
||||
if (!result.ok || !result.state) {
|
||||
state.value.parseFailed = true;
|
||||
return false;
|
||||
}
|
||||
state.value = {
|
||||
...result.state,
|
||||
editorMode: 'visual',
|
||||
advancedCronExpr: state.value.advancedCronExpr.trim(),
|
||||
parseFailed: false,
|
||||
};
|
||||
return true;
|
||||
};
|
||||
|
||||
const setPreset = (preset: CronPreset, options?: { everyMinutes?: number; weeklyDay?: number }) => {
|
||||
state.value = applyPreset(preset, state.value, options);
|
||||
state.value.editorMode = 'visual';
|
||||
state.value.parseFailed = false;
|
||||
};
|
||||
|
||||
const toggleMonth = (month: number) => {
|
||||
state.value.months = toggleInList(state.value.months, month, [...ALL_MONTHS_VAL]);
|
||||
};
|
||||
|
||||
const toggleWeekday = (day: number) => {
|
||||
state.value.weekdays = toggleInList(state.value.weekdays, day, [...ALL_WEEKDAYS_VAL]);
|
||||
};
|
||||
|
||||
const toggleDayOfMonth = (day: number) => {
|
||||
state.value.daysOfMonth = toggleInList(state.value.daysOfMonth, day, ALL_DAYS_VAL);
|
||||
};
|
||||
|
||||
const selectAllMonths = () => {
|
||||
state.value.months = null;
|
||||
};
|
||||
|
||||
const clearAllMonths = () => {
|
||||
state.value.months = [];
|
||||
};
|
||||
|
||||
const selectAllWeekdays = () => {
|
||||
state.value.weekdays = null;
|
||||
};
|
||||
|
||||
const clearAllWeekdays = () => {
|
||||
state.value.weekdays = [];
|
||||
};
|
||||
|
||||
const selectAllDaysOfMonth = () => {
|
||||
state.value.daysOfMonth = null;
|
||||
};
|
||||
|
||||
const clearAllDaysOfMonth = () => {
|
||||
state.value.daysOfMonth = [];
|
||||
};
|
||||
|
||||
const isMonthSelected = (month: number) =>
|
||||
state.value.months === null || state.value.months.includes(month);
|
||||
|
||||
const isWeekdaySelected = (day: number) =>
|
||||
state.value.weekdays === null || state.value.weekdays.includes(day);
|
||||
|
||||
const isDayOfMonthSelected = (day: number) =>
|
||||
state.value.daysOfMonth === null || state.value.daysOfMonth.includes(day);
|
||||
|
||||
const weekdayOptions = computed(() => [
|
||||
{ value: 0, label: t('admin.schedule.weekday.sun') },
|
||||
{ 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') },
|
||||
]);
|
||||
|
||||
return {
|
||||
state,
|
||||
cronExpr,
|
||||
isValid,
|
||||
nextRunAt,
|
||||
loadFromExpr,
|
||||
reset,
|
||||
switchToAdvanced,
|
||||
switchToVisual,
|
||||
setPreset,
|
||||
toggleMonth,
|
||||
toggleWeekday,
|
||||
toggleDayOfMonth,
|
||||
selectAllMonths,
|
||||
clearAllMonths,
|
||||
selectAllWeekdays,
|
||||
clearAllWeekdays,
|
||||
selectAllDaysOfMonth,
|
||||
clearAllDaysOfMonth,
|
||||
isMonthSelected,
|
||||
isWeekdaySelected,
|
||||
isDayOfMonthSelected,
|
||||
weekdayOptions,
|
||||
};
|
||||
}
|
||||
|
||||
const ALL_MONTHS_VAL = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] as const;
|
||||
const ALL_WEEKDAYS_VAL = [0, 1, 2, 3, 4, 5, 6] as const;
|
||||
const ALL_DAYS_VAL = Array.from({ length: 31 }, (_, i) => i + 1);
|
||||
|
||||
function normalizeCronForParser(expr: string): string {
|
||||
const parts = expr.trim().split(/\s+/);
|
||||
if (parts.length === 5) return `0 ${parts.join(' ')}`;
|
||||
return expr.trim();
|
||||
}
|
||||
|
||||
function toggleInList(
|
||||
current: number[] | null,
|
||||
value: number,
|
||||
allValues: number[],
|
||||
): number[] | null {
|
||||
const effective = current === null ? [...allValues] : [...current];
|
||||
const idx = effective.indexOf(value);
|
||||
if (idx >= 0) {
|
||||
effective.splice(idx, 1);
|
||||
} else {
|
||||
effective.push(value);
|
||||
effective.sort((a, b) => a - b);
|
||||
}
|
||||
if (effective.length === allValues.length) return null;
|
||||
return effective;
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
|
||||
import { useScheduleCronDesigner } from './useScheduleCronDesigner';
|
||||
|
||||
export function useSchedulesAdmin() {
|
||||
const { t, locale } = useI18n();
|
||||
@@ -181,158 +182,9 @@ const scheduleCreateForm = ref({
|
||||
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 scheduleCronDesigner = useScheduleCronDesigner();
|
||||
const scheduleCronPreview = scheduleCronDesigner.cronExpr;
|
||||
const scheduleCronValid = scheduleCronDesigner.isValid;
|
||||
|
||||
const resetScheduleCreateForm = () => {
|
||||
scheduleEditingId.value = null;
|
||||
@@ -380,16 +232,7 @@ const resetScheduleCreateForm = () => {
|
||||
scheduleNotifyDropdownOpen.value = false;
|
||||
scheduleOwnerQuery.value = '';
|
||||
scheduleOwnerDropdownOpen.value = false;
|
||||
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,
|
||||
};
|
||||
scheduleCronDesigner.reset();
|
||||
};
|
||||
|
||||
const openScheduleCreateModal = async () => {
|
||||
@@ -482,7 +325,7 @@ const openScheduleEditModal = async (task: ScheduleTask) => {
|
||||
}
|
||||
|
||||
scheduleTestResult.value = null;
|
||||
parseCronExprToDesigner(task.cron_expr);
|
||||
scheduleCronDesigner.loadFromExpr(task.cron_expr);
|
||||
syncScheduleOwnerQuery();
|
||||
showScheduleCreateModal.value = true;
|
||||
};
|
||||
@@ -869,6 +712,11 @@ const createSchedule = async () => {
|
||||
dify_system_prompt: hasAgent ? scheduleSqlEditForm.value.dify_system_prompt : '',
|
||||
};
|
||||
|
||||
if (!scheduleCronValid.value) {
|
||||
msg.error(t('admin.schedule.form.cronInvalid'));
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleCreateSaving.value = true;
|
||||
try {
|
||||
const payload: any = {
|
||||
@@ -1041,9 +889,8 @@ const deleteSchedule = (task: ScheduleTask) => {
|
||||
scheduleCreateForm,
|
||||
scheduleConfigCollapsed,
|
||||
scheduleCronDesigner,
|
||||
weeklyDayOptions,
|
||||
scheduleCronPreview,
|
||||
scheduleNextRunPreview,
|
||||
scheduleCronValid,
|
||||
selectedSchedule,
|
||||
scheduleRunStatusOptions,
|
||||
getScheduleRunStatusBadge,
|
||||
|
||||
Reference in new issue
Block a user