feat: add views

This commit is contained in:
xingyu4j
2025-11-11 15:24:41 +08:00
parent 10f2583e2f
commit 736d91019e
206 changed files with 30261 additions and 0 deletions

View File

@@ -0,0 +1,245 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { DescriptionItemSchema } from '#/components/description';
import { h, markRaw } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { formatDateTime } from '@vben/utils';
import { Timeline } from 'tdesign-vue-next';
import { CronTab } from '#/components/cron-tab';
import { DictTag } from '#/components/dict-tag';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'name',
label: '任务名称',
component: 'Input',
componentProps: {
placeholder: '请输入任务名称',
},
rules: 'required',
},
{
fieldName: 'handlerName',
label: '处理器的名字',
component: 'Input',
componentProps: {
placeholder: '请输入处理器的名字',
},
dependencies: {
triggerFields: ['id'],
disabled: (values) => !!values.id,
},
rules: 'required',
},
{
fieldName: 'handlerParam',
label: '处理器的参数',
component: 'Input',
componentProps: {
placeholder: '请输入处理器的参数',
},
},
{
fieldName: 'cronExpression',
label: 'CRON 表达式',
component: markRaw(CronTab),
componentProps: {
placeholder: '请输入 CRON 表达式',
},
rules: 'required',
},
{
fieldName: 'retryCount',
label: '重试次数',
component: 'InputNumber',
componentProps: {
placeholder: '请输入重试次数。设置为 0 时,不进行重试',
min: 0,
},
rules: 'required',
},
{
fieldName: 'retryInterval',
label: '重试间隔',
component: 'InputNumber',
componentProps: {
placeholder: '请输入重试间隔,单位:毫秒。设置为 0 时,无需间隔',
min: 0,
},
rules: 'required',
},
{
fieldName: 'monitorTimeout',
label: '监控超时时间',
component: 'InputNumber',
componentProps: {
placeholder: '请输入监控超时时间,单位:毫秒',
min: 0,
},
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '任务名称',
component: 'Input',
componentProps: {
allowClear: true,
placeholder: '请输入任务名称',
},
},
{
fieldName: 'status',
label: '任务状态',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.INFRA_JOB_STATUS, 'number'),
allowClear: true,
placeholder: '请选择任务状态',
},
},
{
fieldName: 'handlerName',
label: '处理器的名字',
component: 'Input',
componentProps: {
allowClear: true,
placeholder: '请输入处理器的名字',
},
},
];
}
/** 表格列配置 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{ type: 'checkbox', width: 40 },
{
field: 'id',
title: '任务编号',
minWidth: 80,
},
{
field: 'name',
title: '任务名称',
minWidth: 120,
},
{
field: 'status',
title: '任务状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.INFRA_JOB_STATUS },
},
},
{
field: 'handlerName',
title: '处理器的名字',
minWidth: 180,
},
{
field: 'handlerParam',
title: '处理器的参数',
minWidth: 140,
},
{
field: 'cronExpression',
title: 'CRON 表达式',
minWidth: 120,
},
{
title: '操作',
width: 240,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 详情页的字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
return [
{
field: 'id',
label: '任务编号',
},
{
field: 'name',
label: '任务名称',
},
{
field: 'status',
label: '任务状态',
render: (val) => {
return h(DictTag, {
type: DICT_TYPE.INFRA_JOB_STATUS,
value: val,
});
},
},
{
field: 'handlerName',
label: '处理器的名字',
},
{
field: 'handlerParam',
label: '处理器的参数',
},
{
field: 'cronExpression',
label: 'Cron 表达式',
},
{
field: 'retryCount',
label: '重试次数',
},
{
label: '重试间隔',
field: 'retryInterval',
render: (val) => {
return val ? `${val} 毫秒` : '无间隔';
},
},
{
label: '监控超时时间',
field: 'monitorTimeout',
render: (val) => {
return val && val > 0 ? `${val} 毫秒` : '未开启';
},
},
{
field: 'nextTimes',
label: '后续执行时间',
render: (val) => {
if (!val || val.length === 0) {
return '无后续执行时间';
}
return h(Timeline, {}, () =>
val?.map((time: Date) =>
h(Timeline.Item, {}, () => formatDateTime(time)),
),
);
},
},
];
}

View File

@@ -0,0 +1,291 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { InfraJobApi } from '#/api/infra/job';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { confirm, DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { InfraJobStatusEnum } from '@vben/constants';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';
import { message } from '#/adapter/tdesign';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteJob,
deleteJobList,
exportJob,
getJobPage,
runJob,
updateJobStatus,
} from '#/api/infra/job';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Detail from './modules/detail.vue';
import Form from './modules/form.vue';
const { push } = useRouter();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
const [DetailModal, detailModalApi] = useVbenModal({
connectedComponent: Detail,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 导出表格 */
async function handleExport() {
const data = await exportJob(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '定时任务.xls', source: data });
}
/** 创建任务 */
function handleCreate() {
formModalApi.setData(null).open();
}
/** 编辑任务 */
function handleEdit(row: InfraJobApi.Job) {
formModalApi.setData(row).open();
}
/** 查看任务详情 */
function handleDetail(row: InfraJobApi.Job) {
detailModalApi.setData({ id: row.id }).open();
}
/** 更新任务状态 */
async function handleUpdateStatus(row: InfraJobApi.Job) {
const status =
row.status === InfraJobStatusEnum.STOP
? InfraJobStatusEnum.NORMAL
: InfraJobStatusEnum.STOP;
const statusText = status === InfraJobStatusEnum.NORMAL ? '启用' : '停用';
await confirm(`确定${statusText} ${row.name} 吗?`);
const hideLoading = message.loading({
content: `正在${statusText}中...`,
duration: 0,
});
try {
await updateJobStatus(row.id!, status);
message.success($t('ui.actionMessage.operationSuccess'));
handleRefresh();
} finally {
message.close(hideLoading);
}
}
/** 执行一次任务 */
async function handleTrigger(row: InfraJobApi.Job) {
await confirm(`确定执行一次 ${row.name} 吗?`);
const hideLoading = message.loading({
content: '正在执行中...',
duration: 0,
});
try {
await runJob(row.id!);
message.success($t('ui.actionMessage.operationSuccess'));
} finally {
message.close(hideLoading);
}
}
/** 跳转到任务日志 */
function handleLog(row?: InfraJobApi.Job) {
push({
name: 'InfraJobLog',
query: row?.id ? { id: row.id } : {},
});
}
/** 删除任务 */
async function handleDelete(row: InfraJobApi.Job) {
const hideLoading = message.loading({
content: $t('ui.actionMessage.deleting', [row.name]),
duration: 0,
});
try {
await deleteJob(row.id!);
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
message.close(hideLoading);
}
}
/** 批量删除任务 */
async function handleDeleteBatch() {
await confirm($t('ui.actionMessage.deleteBatchConfirm'));
const hideLoading = message.loading({
content: $t('ui.actionMessage.deletingBatch'),
duration: 0,
});
try {
await deleteJobList(checkedIds.value);
checkedIds.value = [];
message.success($t('ui.actionMessage.deleteSuccess'));
handleRefresh();
} finally {
message.close(hideLoading);
}
}
const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({ records }: { records: InfraJobApi.Job[] }) {
checkedIds.value = records.map((item) => item.id!);
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getJobPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<InfraJobApi.Job>,
gridEvents: {
checkboxAll: handleRowCheckboxChange,
checkboxChange: handleRowCheckboxChange,
},
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert title="定时任务" url="https://doc.iocoder.cn/job/" />
<DocAlert title="异步任务" url="https://doc.iocoder.cn/async-task/" />
<DocAlert title="消息队列" url="https://doc.iocoder.cn/message-queue/" />
</template>
<FormModal @success="handleRefresh" />
<DetailModal />
<Grid table-title="定时任务列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['任务']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['infra:job:create'],
onClick: handleCreate,
},
{
label: $t('ui.actionTitle.export'),
type: 'primary',
icon: ACTION_ICON.DOWNLOAD,
auth: ['infra:job:export'],
onClick: handleExport,
},
{
label: '执行日志',
type: 'primary',
icon: 'lucide:history',
auth: ['infra:job:query'],
onClick: () => handleLog(undefined),
},
{
label: $t('ui.actionTitle.deleteBatch'),
type: 'danger',
icon: ACTION_ICON.DELETE,
disabled: isEmpty(checkedIds),
auth: ['infra:job:delete'],
onClick: handleDeleteBatch,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
variant: 'text',
icon: ACTION_ICON.EDIT,
auth: ['infra:job:update'],
onClick: handleEdit.bind(null, row),
},
{
label: '开启',
variant: 'text',
icon: 'lucide:circle-play',
auth: ['infra:job:update'],
ifShow: () => row.status === InfraJobStatusEnum.STOP,
onClick: handleUpdateStatus.bind(null, row),
},
{
label: '暂停',
variant: 'text',
icon: 'lucide:circle-pause',
auth: ['infra:job:update'],
ifShow: () => row.status === InfraJobStatusEnum.NORMAL,
onClick: handleUpdateStatus.bind(null, row),
},
{
label: '执行',
variant: 'text',
icon: 'lucide:clock-plus',
auth: ['infra:job:trigger'],
onClick: handleTrigger.bind(null, row),
},
]"
:drop-down-actions="[
{
label: $t('common.detail'),
variant: 'text',
auth: ['infra:job:query'],
onClick: handleDetail.bind(null, row),
},
{
label: '日志',
variant: 'text',
auth: ['infra:job:query'],
onClick: handleLog.bind(null, row),
},
{
label: $t('common.delete'),
variant: 'text',
type: 'danger',
auth: ['infra:job:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,185 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { DescriptionItemSchema } from '#/components/description';
import { h } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { formatDateTime } from '@vben/utils';
import dayjs from 'dayjs';
import { DictTag } from '#/components/dict-tag';
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'handlerName',
label: '处理器的名字',
component: 'Input',
componentProps: {
allowClear: true,
placeholder: '请输入处理器的名字',
},
},
{
fieldName: 'beginTime',
label: '开始执行时间',
component: 'DatePicker',
componentProps: {
allowClear: true,
placeholder: '选择开始执行时间',
valueFormat: 'YYYY-MM-DD HH:mm:ss',
showTime: {
format: 'HH:mm:ss',
defaultValue: dayjs('00:00:00', 'HH:mm:ss'),
},
},
},
{
fieldName: 'endTime',
label: '结束执行时间',
component: 'DatePicker',
componentProps: {
allowClear: true,
placeholder: '选择结束执行时间',
valueFormat: 'YYYY-MM-DD HH:mm:ss',
showTime: {
format: 'HH:mm:ss',
defaultValue: dayjs('23:59:59', 'HH:mm:ss'),
},
},
},
{
fieldName: 'status',
label: '任务状态',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.INFRA_JOB_LOG_STATUS, 'number'),
allowClear: true,
placeholder: '请选择任务状态',
},
},
];
}
/** 表格列配置 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '日志编号',
minWidth: 80,
},
{
field: 'jobId',
title: '任务编号',
minWidth: 80,
},
{
field: 'handlerName',
title: '处理器的名字',
minWidth: 180,
},
{
field: 'handlerParam',
title: '处理器的参数',
minWidth: 140,
},
{
field: 'executeIndex',
title: '第几次执行',
minWidth: 100,
},
{
field: 'beginTime',
title: '执行时间',
minWidth: 280,
formatter: ({ row }) => {
return `${formatDateTime(row.beginTime)} ~ ${formatDateTime(row.endTime)}`;
},
},
{
field: 'duration',
title: '执行时长',
minWidth: 120,
formatter: ({ row }) => {
return `${row.duration} 毫秒`;
},
},
{
field: 'status',
title: '任务状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.INFRA_JOB_LOG_STATUS },
},
},
{
title: '操作',
width: 80,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 详情页的字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
return [
{
field: 'id',
label: '日志编号',
},
{
field: 'jobId',
label: '任务编号',
},
{
field: 'handlerName',
label: '处理器的名字',
},
{
field: 'handlerParam',
label: '处理器的参数',
},
{
field: 'executeIndex',
label: '第几次执行',
},
{
field: 'beginTime',
label: '执行时间',
render: (val, data) => {
if (val && data?.endTime) {
return `${formatDateTime(val)} ~ ${formatDateTime(data.endTime)}`;
}
return '';
},
},
{
field: 'duration',
label: '执行时长',
render: (val) => {
return val ? `${val} 毫秒` : '';
},
},
{
field: 'status',
label: '任务状态',
render: (val) => {
return h(DictTag, {
type: DICT_TYPE.INFRA_JOB_LOG_STATUS,
value: val,
});
},
},
{
field: 'result',
label: '执行结果',
},
];
}

View File

@@ -0,0 +1,105 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { InfraJobLogApi } from '#/api/infra/job-log';
import { useRoute } from 'vue-router';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { exportJobLog, getJobLogPage } from '#/api/infra/job-log';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Detail from './modules/detail.vue';
const { query } = useRoute();
const [DetailModal, detailModalApi] = useVbenModal({
connectedComponent: Detail,
destroyOnClose: true,
});
/** 导出表格 */
async function handleExport() {
const data = await exportJobLog(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '任务日志.xls', source: data });
}
/** 查看日志详情 */
function handleDetail(row: InfraJobLogApi.JobLog) {
detailModalApi.setData({ id: row.id }).open();
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getJobLogPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
jobId: query.id,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<InfraJobLogApi.JobLog>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert title="定时任务" url="https://doc.iocoder.cn/job/" />
<DocAlert title="异步任务" url="https://doc.iocoder.cn/async-task/" />
<DocAlert title="消息队列" url="https://doc.iocoder.cn/message-queue/" />
</template>
<DetailModal />
<Grid table-title="任务日志列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.export'),
type: 'primary',
icon: ACTION_ICON.DOWNLOAD,
auth: ['infra:job:export'],
onClick: handleExport,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.detail'),
variant: 'text',
icon: ACTION_ICON.VIEW,
auth: ['infra:job:query'],
onClick: handleDetail.bind(null, row),
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,51 @@
<script lang="ts" setup>
import type { InfraJobLogApi } from '#/api/infra/job-log';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { getJobLog } from '#/api/infra/job-log';
import { useDescription } from '#/components/description';
import { useDetailSchema } from '../data';
const formData = ref<InfraJobLogApi.JobLog>();
const [Descriptions] = useDescription({
bordered: true,
column: 1,
schema: useDetailSchema(),
});
const [Modal, modalApi] = useVbenModal({
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<{ id: number }>();
if (!data?.id) {
return;
}
modalApi.lock();
try {
formData.value = await getJobLog(data.id);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal
title="日志详情"
class="w-1/2"
:show-cancel-button="false"
:show-confirm-button="false"
>
<Descriptions :data="formData" />
</Modal>
</template>

View File

@@ -0,0 +1,56 @@
<script lang="ts" setup>
import type { InfraJobApi } from '#/api/infra/job';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { getJob, getJobNextTimes } from '#/api/infra/job';
import { useDescription } from '#/components/description';
import { useDetailSchema } from '../data';
const formData = ref<InfraJobApi.Job>(); // 任务详情
const nextTimes = ref<Date[]>([]); // 下一次执行时间
const [Descriptions] = useDescription({
bordered: true,
column: 1,
schema: useDetailSchema(),
});
const [Modal, modalApi] = useVbenModal({
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<{ id: number }>();
if (!data?.id) {
return;
}
modalApi.lock();
try {
formData.value = await getJob(data.id);
// 获取下一次执行时间
nextTimes.value = await getJobNextTimes(data.id);
// 将 nextTimes 赋值给 formData以便在 schema 中使用
formData.value.nextTimes = nextTimes.value;
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal
title="任务详情"
class="w-1/2"
:show-cancel-button="false"
:show-confirm-button="false"
>
<Descriptions :data="formData" />
</Modal>
</template>

View File

@@ -0,0 +1,81 @@
<script lang="ts" setup>
import type { InfraJobApi } from '#/api/infra/job';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { message } from '#/adapter/tdesign';
import { createJob, getJob, updateJob } from '#/api/infra/job';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<InfraJobApi.Job>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', ['任务'])
: $t('ui.actionTitle.create', ['任务']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: useFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data = (await formApi.getValues()) as InfraJobApi.Job;
try {
await (formData.value?.id ? updateJob(data) : createJob(data));
// 关闭并提示
await modalApi.close();
emit('success');
message.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<InfraJobApi.Job>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
formData.value = await getJob(data.id);
// 设置到 values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal :title="getTitle" class="w-2/5">
<Form class="mx-4" />
</Modal>
</template>