niucloud/admin/src/app/views/tools/schedule.vue
2026-10-17 19:26:55 +08:00

421 lines
16 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<div ref="pageRef" class="main-container table-fill-page" :style="pageStyle">
<div class="table-fill-page__card">
<!-- 计划任务说明:原 el-alert 自带关闭功能,保留关闭按钮 -->
<tip-notice closable>
<p>{{ t('cronTipsOne') }}</p>
<p>{{ t('cronTipsTwo') }}</p>
</tip-notice>
<el-card class="box-card !border-none table-search-wrap table-search-wrap--panel table-fill-page__search" shadow="never">
<div class="flex justify-between">
<el-form :inline="true" :model="cronTableData.searchParam" ref="searchFormRef">
<el-form-item :label="t('title')" prop="key">
<el-select v-model="cronTableData.searchParam.key" placeholder="全部" filterable clearable popper-class="schedule-name-select">
<el-option-group v-for="group in templateGroupList" :key="group.addon" :label="group.label">
<el-option v-for="item in group.list" :key="item.key" :label="item.name" :value="item.key" />
</el-option-group>
</el-select>
</el-form-item>
<el-form-item :label="t('status')" prop="status">
<el-select v-model="cronTableData.searchParam.status" placeholder="全部" clearable>
<el-option label="全部" value="all" />
<el-option label="启用" value="1" />
<el-option label="关闭" value="0" />
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="loadCronList()">{{ t('search') }}</el-button>
<el-button @click="resetForm(searchFormRef)">{{ t('reset') }}</el-button>
</el-form-item>
</el-form>
</div>
</el-card>
<div class="table-panel table-fill-page__panel">
<table-toolbar :title="pageName" :selectable="false">
<template #actions>
<el-button type="primary" @click="showEvent">{{ t('addCron') }}</el-button>
<el-button type="primary" @click="resetCronFn">{{ t('重置计划任务') }}</el-button>
</template>
</table-toolbar>
<div class="table-fill-page__table">
<el-table height="100%" :data="cronTableData.data" size="large" v-loading="cronTableData.loading">
<template #empty>
<span>{{ !cronTableData.loading ? t('emptyData') : '' }}</span>
</template>
<el-table-column prop="name" :label="t('title')" min-width="150" />
<el-table-column prop="key" :label="t('key')" min-width="150" />
<el-table-column :label="t('crondType')" min-width="150">
<template #default="{ row }">
{{ row.crontab_content }}
</template>
</el-table-column>
<el-table-column prop="status_name" :label="t('openStatus')" min-width="100" />
<el-table-column :label="t('operation')" align="right" fixed="right" width="200">
<template #default="{ row }">
<table-actions :actions="rowActions(row)" />
</template>
</el-table-column>
</el-table>
</div>
<table-pagination
v-model:current-page="cronTableData.page"
v-model:page-size="cronTableData.limit"
:total="cronTableData.total"
@size-change="loadCronList()"
@current-change="loadCronList"
/>
</div>
</div>
<cron-info ref="cronDialog" @complete="loadCronList" />
<schedule-log ref="scheduleLogRef" />
<el-dialog v-model="showDialog" :title="t('editCron')" width="750px" :destroy-on-close="true">
<el-form :model="formData" label-width="110px" ref="formRef" :rules="formRules" class="page-form" v-loading="loading">
<el-form-item :label="t('cronTemplate')" class="items-center" prop="key">
<el-select v-model="formData.key">
<el-option v-for="item in templateList" :key="item.key" :label="item.name" :value="item.key" />
</el-select>
</el-form-item>
<el-form-item :label="t('cronTime')" prop="timeDate" class="schedule-cron-time">
<el-select v-model="formData.time.type" class="!w-[150px]">
<el-option v-for="(item, index) in date_type" :key="index" :label="item" :value="index" />
</el-select>
<el-select v-model="formData.time.week" class="!w-[120px]" v-if="formData.time.type == 'week'">
<el-option v-for="(item, index) in week_list" :key="index" :label="item" :value="index" />
</el-select>
<el-input v-model.trim="formData.time.day" class="!w-[120px]" v-if="['month', 'day'].indexOf(formData.time.type) != -1">
<template #append>{{ t('day') }}</template>
</el-input>
<el-input v-model.trim="formData.time.hour" class="!w-[120px]" v-if="['month', 'day', 'hour', 'week'].indexOf(formData.time.type) != -1">
<template #append>{{ t('hour') }}</template>
</el-input>
<el-input v-model.trim="formData.time.min" class="!w-[120px]" v-if="['month', 'day', 'hour', 'week', 'min'].indexOf(formData.time.type) != -1">
<template #append>{{ t('min') }}</template>
</el-input>
<div v-if="cronTimeDesc" class="w-full text-xs text-[var(--el-text-color-secondary)]">
{{ t('cronTimePreview') }}{{ cronTimeDesc }}
</div>
</el-form-item>
<el-form-item :label="t('isopen')">
<div class="input-width flex items-center text-sm">
<el-radio-group v-model="formData.status">
<el-radio :label="1">{{ t('yes') }}</el-radio>
<el-radio :label="2">{{ t('no') }}</el-radio>
</el-radio-group>
</div>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button type="primary" @click="addEvent(formRef)">{{ t('confirm') }}</el-button>
</span>
</template>
</el-dialog>
</div>
</template>
<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { t } from '@/lang'
import {
getCronList,
getCronTemplate,
getCronDateType,
getWeek,
addCron,
editCron,
deleteCron,
doCron,
resetCron
} from '@/app/api/sys'
import { ElMessageBox, FormInstance } from 'element-plus'
import TableActions from '@/components/table-actions/index.vue'
import TablePagination from '@/components/table-pagination/index.vue'
import TableToolbar from '@/components/table-toolbar/index.vue'
import TipNotice from '@/components/tip-notice/index.vue'
import { useRoute } from 'vue-router'
import ScheduleLog from '@/app/views/tools/schedule_log.vue'
import { useTablePageHeight } from '@/hooks/useTablePageHeight'
import CronInfo from '@/app/views/setting/components/cron-info.vue'
const route = useRoute()
const pageName = route.meta.title
// 表格占满页面剩余高度,超出部分在表格内部滚动
const { pageRef, pageStyle } = useTablePageHeight()
/**
* 表格行内操作:超过 2 个自动收进「更多」
*/
const rowActions = (row: any) => [
{ label: t('edit'), onClick: () => editEvent(row) },
{ label: t('cronLog'), onClick: () => toLogList(row.id) },
{ label: t('doOne'), onClick: () => doEvent(row) },
{ label: t('delete'), type: 'danger', onClick: () => deleteEvent(row.id) }
]
const cronTableData = reactive({
page: 1,
limit: 10,
total: 0,
loading: true,
data: [],
searchParam: {
type: '',
status: 'all'
}
})
const templateList = ref<any[]>([])
const templateGroupList = computed(() => {
const groups: { addon: string, label: string, list: any[] }[] = []
const indexMap: Record<string, number> = {}
templateList.value.forEach((item) => {
const addon = item.addon || ''
if (indexMap[addon] === undefined) {
indexMap[addon] = groups.length
groups.push({
addon,
label: item.addon_name || addon,
list: []
})
}
groups[indexMap[addon]].list.push(item)
})
return groups
})
const date_type = ref([])
const week_list = ref<Record<string, string>>({})
const searchFormRef = ref<FormInstance>()
const resetForm = (formEl: FormInstance | undefined) => {
if (!formEl) return
formEl.resetFields()
loadCronList()
}
const setTypeList = async () => {
templateList.value = await (await getCronTemplate()).data
date_type.value = await (await getCronDateType()).data
week_list.value = await (await getWeek()).data
}
setTypeList()
/**
* 获取任务列表
*/
const loadCronList = (page: number = 1) => {
cronTableData.loading = true
cronTableData.page = page
getCronList({
page: cronTableData.page,
limit: cronTableData.limit,
...cronTableData.searchParam
}).then(res => {
cronTableData.loading = false
cronTableData.data = res.data.data
cronTableData.total = res.data.total
}).catch(() => {
cronTableData.loading = false
})
}
loadCronList()
const showDialog = ref(false)
const initialFormData = {
id: 0,
key: '',
status: 2,
time: {
type: 'min',
week: '',
day: '',
hour: '',
min: ''
}
}
const formData: Record<string, any> = reactive({ ...initialFormData })
const formRef = ref<FormInstance>()
const showEvent = () => {
formData.id = 0
formData.key = ''
formData.status = 2
formData.time.type = 'min'
formData.time.week = ''
formData.time.day = ''
formData.time.hour = ''
formData.time.min = ''
showDialog.value = true
}
// 表单验证规则
const formRules = computed(() => {
return {
key: [
{ required: true, message: t('titlePlaceholder'), trigger: 'blur' }
],
timeDate: [
{ required: true, validator: validatePass, trigger: 'blur' }
],
}
})
const validatePass = (rule: any, value: any, callback: any) => {
const time = formData.time;
const isPositiveInt = (v: any) => /^[1-9]\d*$/.test(v);
const error = () => callback(new Error(t('cronTimeTips')));
switch (time.type) {
case 'min':
return isPositiveInt(time.min) ? callback() : error();
case 'hour':
return isPositiveInt(time.hour) && isPositiveInt(time.min) ? callback() : error();
case 'day':
return isPositiveInt(time.day) && isPositiveInt(time.hour) && isPositiveInt(time.min) ? callback() : error();
case 'week':
return time.week !== '' && isPositiveInt(time.hour) && isPositiveInt(time.min) ? callback() : error();
case 'month':
return isPositiveInt(time.day) && isPositiveInt(time.hour) && isPositiveInt(time.min) ? callback() : error();
default:
return error();
}
}
/**
* 根据当前任务周期设置实时换算实际执行周期描述(口径与列表 crontab_content 一致),设置不完整时返回空串
*/
const cronTimeDesc = computed(() => {
const time = formData.time
const isPositiveInt = (v: any) => /^[1-9]\d*$/.test(String(v ?? ''))
switch (time.type) {
case 'min':
return isPositiveInt(time.min) ? `每隔${time.min}分钟执行一次` : ''
case 'hour':
return isPositiveInt(time.hour) && isPositiveInt(time.min) ? `每隔${time.hour}小时的${time.min}分执行一次` : ''
case 'day':
return isPositiveInt(time.day) && isPositiveInt(time.hour) && isPositiveInt(time.min) ? `每隔${time.day}天的${time.hour}时${time.min}分执行一次` : ''
case 'week': {
const weekName = week_list.value[time.week] ?? ''
return weekName && isPositiveInt(time.hour) && isPositiveInt(time.min) ? `每周的${weekName}的${time.hour}时${time.min}分执行一次` : ''
}
case 'month':
return isPositiveInt(time.day) && isPositiveInt(time.hour) && isPositiveInt(time.min) ? `每月的${time.day}号的${time.hour}时${time.min}分执行一次` : ''
default:
return ''
}
})
const save_type = ref(false)
const addEvent = async (formEl: FormInstance | undefined) => {
if (save_type.value || !formEl) return
await formEl.validate(async (valid) => {
if (valid) {
save_type.value = true
const data = formData
const save = formData.id > 0 ? editCron : addCron
save(data).then(res => {
save_type.value = false
showDialog.value = false
loadCronList()
}).catch(() => {
save_type.value = false
})
}
})
}
const editEvent = (item:any) => {
formData.id = item.id
formData.key = item.key
formData.status = item.status
formData.time = item.time
showDialog.value = true
}
const deleteEvent = (id: number) => {
ElMessageBox.confirm(t('cronDeleteTips'), t('warning'),
{
confirmButtonText: t('confirm'),
cancelButtonText: t('cancel'),
type: 'warning'
}
).then(() => {
deleteCron(id).then(() => {
loadCronList()
}).catch(() => {
})
})
}
const doEvent = (row: any) => {
ElMessageBox.confirm(t(`确认要立即执行一次"${row.name}"任务吗?`), t('warning'),
{
confirmButtonText: t('confirm'),
cancelButtonText: t('cancel'),
type: 'warning'
}
).then(() => {
doCron({id: row.id}).then((res) => {
}).catch(() => {
})
})
}
// 重置任务
const resetCronFn = (row: any) => {
ElMessageBox.confirm(t('确认要重置计划任务吗?'), t('warning'),
{
confirmButtonText: t('confirm'),
cancelButtonText: t('cancel'),
type: 'warning'
}
).then(() => {
resetCron().then((res) => {
ElMessage.success(res.msg)
}).catch(() => {
})
})
}
const cronDialog: Record<string, any> | null = ref(null)
/**
* 查看任务
* @param data
*/
const infoEvent = (data: any) => {
cronDialog.value.setFormData(data)
cronDialog.value.showDialog = true
}
const scheduleLogRef = ref<any>(null)
const toLogList = (id: number) => {
scheduleLogRef.value?.open(id)
}
</script>
<style lang="scss">
.schedule-name-select .el-select-group .el-select-dropdown__item {
padding-left: 25px;
}
/** 任务周期:下拉框与输入框同行排列,一行放不下时自动换行并保留间距 */
.schedule-cron-time {
.el-form-item__content {
flex-wrap: wrap;
gap: var(--sys-space-2);
}
}
</style>