refactor(plugin-workflow): change tasks api (#6640)

* refactor(plugin-workflow): change tasks api

* refactor(plugin-workflow): change task center popup logic

* refactor(preset): remove some builtin plugins
This commit is contained in:
Junyi 2025-04-14 18:27:28 +08:00 committed by GitHub
parent 75c8265392
commit 23d7e09fa5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 239 additions and 163 deletions

View File

@ -72,7 +72,7 @@ const InternalActionBar: FC = (props: any) => {
<Portal> <Portal>
<DndContext> <DndContext>
<div <div
style={{ display: 'flex', alignItems: 'center', gap: 8, ...style, marginTop: 0 }} style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 0, ...style }}
{...others} {...others}
className={cx(others.className, 'nb-action-bar')} className={cx(others.className, 'nb-action-bar')}
> >

View File

@ -158,7 +158,7 @@ const InternalList = withSkeletonComponent(
> >
<AntdList <AntdList
{...props} {...props}
pagination={!meta || !field.value?.length ? false : paginationProps} pagination={!meta || !field.value?.length || count <= field.value?.length ? false : paginationProps}
loading={service?.loading} loading={service?.loading}
> >
{field.value?.length {field.value?.length

View File

@ -8,3 +8,4 @@
*/ */
export * from './List'; export * from './List';
export { useListBlockContext } from './List.Decorator';

View File

@ -33,9 +33,12 @@ import {
useActionContext, useActionContext,
useCurrentUserContext, useCurrentUserContext,
useFormBlockContext, useFormBlockContext,
useTableBlockContext, useListBlockContext,
List, List,
OpenModeProvider, OpenModeProvider,
ActionContextProvider,
useRequest,
CollectionRecordProvider,
} from '@nocobase/client'; } from '@nocobase/client';
import WorkflowPlugin, { import WorkflowPlugin, {
DetailsBlockProvider, DetailsBlockProvider,
@ -46,12 +49,15 @@ import WorkflowPlugin, {
EXECUTION_STATUS, EXECUTION_STATUS,
JOB_STATUS, JOB_STATUS,
WorkflowTitle, WorkflowTitle,
TASK_STATUS,
usePopupRecordContext,
} from '@nocobase/plugin-workflow/client'; } from '@nocobase/plugin-workflow/client';
import { NAMESPACE, useLang } from '../locale'; import { NAMESPACE, useLang } from '../locale';
import { FormBlockProvider } from './instruction/FormBlockProvider'; import { FormBlockProvider } from './instruction/FormBlockProvider';
import { ManualFormType, manualFormTypes } from './instruction/SchemaConfig'; import { ManualFormType, manualFormTypes } from './instruction/SchemaConfig';
import { TaskStatusOptionsMap } from '../common/constants'; import { TaskStatusOptionsMap } from '../common/constants';
import { useNavigate, useParams } from 'react-router-dom';
function TaskStatusColumn(props) { function TaskStatusColumn(props) {
const recordData = useCollectionRecordData(); const recordData = useCollectionRecordData();
@ -291,11 +297,12 @@ function useSubmit() {
const { values, submit } = useForm(); const { values, submit } = useForm();
const field = useField(); const field = useField();
const buttonSchema = useFieldSchema(); const buttonSchema = useFieldSchema();
const { service } = useTableBlockContext(); const { service } = useListBlockContext();
const { userJob, execution } = useFlowContext(); const { userJob, execution } = useFlowContext();
const { name: actionKey } = buttonSchema; const { name: actionKey } = buttonSchema;
const { name: formKey } = buttonSchema.parent.parent; const { name: formKey } = buttonSchema.parent.parent;
const { assignedValues = {} } = buttonSchema?.['x-action-settings'] ?? {}; const { assignedValues = {} } = buttonSchema?.['x-action-settings'] ?? {};
return { return {
async run() { async run() {
if (execution.status || userJob.status) { if (execution.status || userJob.status) {
@ -611,57 +618,37 @@ function ContentDetailWithTitle(props) {
function TaskItem() { function TaskItem() {
const token = useAntdToken(); const token = useAntdToken();
const [visible, setVisible] = useState(false);
const record = useCollectionRecordData(); const record = useCollectionRecordData();
const { t } = useTranslation(); const navigate = useNavigate();
// const { defaultOpenMode } = useOpenModeContext(); const { setRecord } = usePopupRecordContext();
// const { openPopup } = usePopupUtils(); const onOpen = useCallback(
// const { isPopupVisibleControlledByURL } = usePopupSettings(); (e: React.MouseEvent) => {
const onOpen = useCallback((e: React.MouseEvent) => { const targetElement = e.target as Element; // 将事件目标转换为Element类型
const targetElement = e.target as Element; // 将事件目标转换为Element类型 const currentTargetElement = e.currentTarget as Element;
const currentTargetElement = e.currentTarget as Element; if (currentTargetElement.contains(targetElement)) {
if (currentTargetElement.contains(targetElement)) { setRecord(record);
setVisible(true); navigate(`./${record.id}`);
// if (!isPopupVisibleControlledByURL()) { }
// } else { e.stopPropagation();
// openPopup({ },
// // popupUidUsedInURL: 'job', [navigate, record.id],
// customActionSchema: { );
// type: 'void',
// 'x-uid': 'job-view',
// 'x-action-context': {
// dataSource: 'main',
// collection: 'workflowManualTasks',
// doNotUpdateContext: true,
// },
// properties: {},
// },
// });
// }
}
e.stopPropagation();
}, []);
return ( return (
<> <Card
<Card onClick={onOpen}
onClick={onOpen} hoverable
hoverable size="small"
size="small" title={record.title}
title={record.title} extra={<WorkflowTitle {...record.workflow} />}
extra={<WorkflowTitle {...record.workflow} />} className={css`
className={css` .ant-card-extra {
.ant-card-extra { color: ${token.colorTextDescription};
color: ${token.colorTextDescription}; }
} `}
`} >
> <ContentDetail />
<ContentDetail /> </Card>
</Card>
<PopupContextProvider visible={visible} setVisible={setVisible} openMode="modal">
<Drawer />
</PopupContextProvider>
</>
); );
} }
@ -734,7 +721,9 @@ function TodoExtraActions() {
export const manualTodo = { export const manualTodo = {
title: `{{t("My manual tasks", { ns: "${NAMESPACE}" })}}`, title: `{{t("My manual tasks", { ns: "${NAMESPACE}" })}}`,
collection: 'workflowManualTasks', collection: 'workflowManualTasks',
action: 'listMine',
useActionParams: useTodoActionParams, useActionParams: useTodoActionParams,
component: TaskItem, Actions: TodoExtraActions,
extraActions: TodoExtraActions, Item: TaskItem,
Detail: Drawer,
}; };

View File

@ -16,13 +16,14 @@ import * as jobActions from './actions';
import ManualInstruction from './ManualInstruction'; import ManualInstruction from './ManualInstruction';
import { MANUAL_TASK_TYPE } from '../common/constants'; import { MANUAL_TASK_TYPE } from '../common/constants';
import { Model } from '@nocobase/database';
interface WorkflowManualTaskModel { class WorkflowManualTaskModel extends Model {
id: number; declare id: number;
userId: number; declare userId: number;
workflowId: number; declare workflowId: number;
executionId: number; declare executionId: number;
status: number; declare status: number;
} }
export default class extends Plugin { export default class extends Plugin {
@ -55,7 +56,13 @@ export default class extends Plugin {
const workflowPlugin = this.app.pm.get(WorkflowPlugin) as WorkflowPlugin; const workflowPlugin = this.app.pm.get(WorkflowPlugin) as WorkflowPlugin;
workflowPlugin.registerInstruction('manual', ManualInstruction); workflowPlugin.registerInstruction('manual', ManualInstruction);
this.db.on('workflowManualTasks.afterSave', async (task: WorkflowManualTaskModel, options) => { this.db.on('workflowManualTasks.afterSave', async (task: WorkflowManualTaskModel, { transaction }) => {
// const allCount = await (task.constructor as typeof WorkflowManualTaskModel).count({
// where: {
// userId: task.userId,
// },
// transaction,
// });
await workflowPlugin.toggleTaskStatus( await workflowPlugin.toggleTaskStatus(
{ {
type: MANUAL_TASK_TYPE, type: MANUAL_TASK_TYPE,
@ -63,8 +70,9 @@ export default class extends Plugin {
userId: task.userId, userId: task.userId,
workflowId: task.workflowId, workflowId: task.workflowId,
}, },
Boolean(task.status), task.status === JOB_STATUS.PENDING,
options, // allCount,
{ transaction },
); );
}); });
} }

View File

@ -7,7 +7,7 @@
* For more information, please refer to: https://www.nocobase.com/agreement. * For more information, please refer to: https://www.nocobase.com/agreement.
*/ */
import { Context, utils } from '@nocobase/actions'; import actions, { Context, utils } from '@nocobase/actions';
import WorkflowPlugin, { EXECUTION_STATUS, JOB_STATUS } from '@nocobase/plugin-workflow'; import WorkflowPlugin, { EXECUTION_STATUS, JOB_STATUS } from '@nocobase/plugin-workflow';
import ManualInstruction from './ManualInstruction'; import ManualInstruction from './ManualInstruction';
@ -111,3 +111,24 @@ export async function submit(context: Context, next) {
plugin.resume(task.job); plugin.resume(task.job);
} }
export async function listMine(context, next) {
context.action.mergeParams({
filter: {
userId: context.state.currentUser.id,
$or: [
{
'workflow.enabled': true,
},
{
'workflow.enabled': false,
status: {
$ne: JOB_STATUS.PENDING,
},
},
],
},
});
return actions.list(context, next);
}

View File

@ -11,14 +11,17 @@ import { PageHeader } from '@ant-design/pro-layout';
import { Badge, Button, Layout, Menu, Tabs, Tooltip } from 'antd'; import { Badge, Button, Layout, Menu, Tabs, Tooltip } from 'antd';
import classnames from 'classnames'; import classnames from 'classnames';
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'; import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { Link, Outlet, useNavigate, useParams } from 'react-router-dom'; import { Link, useNavigate, useParams } from 'react-router-dom';
import { import {
ActionContextProvider,
CollectionRecordProvider,
css, css,
PinnedPluginListProvider, PinnedPluginListProvider,
SchemaComponent, SchemaComponent,
SchemaComponentContext, SchemaComponentContext,
SchemaComponentOptions, SchemaComponentOptions,
useAPIClient,
useApp, useApp,
useCompile, useCompile,
useDocumentTitle, useDocumentTitle,
@ -44,9 +47,11 @@ const contentClass = css`
export interface TaskTypeOptions { export interface TaskTypeOptions {
title: string; title: string;
collection: string; collection: string;
action: string;
useActionParams: Function; useActionParams: Function;
component: React.ComponentType; Actions?: React.ComponentType;
extraActions?: React.ComponentType; Item: React.ComponentType;
Detail: React.ComponentType;
// children?: TaskTypeOptions[]; // children?: TaskTypeOptions[];
} }
@ -65,7 +70,7 @@ function MenuLink({ type }: any) {
return ( return (
<Link <Link
to={`/admin/workflow/tasks/${type}`} to={`/admin/workflow/tasks/${type}/${TASK_STATUS.PENDING}`}
className={css` className={css`
display: flex; display: flex;
align-items: center; align-items: center;
@ -85,7 +90,7 @@ function MenuLink({ type }: any) {
); );
} }
const TASK_STATUS = { export const TASK_STATUS = {
ALL: 'all', ALL: 'all',
PENDING: 'pending', PENDING: 'pending',
COMPLETED: 'completed', COMPLETED: 'completed',
@ -95,7 +100,7 @@ function StatusTabs() {
const navigate = useNavigate(); const navigate = useNavigate();
const { taskType, status = TASK_STATUS.PENDING } = useParams(); const { taskType, status = TASK_STATUS.PENDING } = useParams();
const type = useCurrentTaskType(); const type = useCurrentTaskType();
const { extraActions: ExtraActions } = type; const { Actions } = type;
return ( return (
<Tabs <Tabs
activeKey={status} activeKey={status}
@ -122,9 +127,9 @@ function StatusTabs() {
}, },
]} ]}
tabBarExtraContent={ tabBarExtraContent={
ExtraActions Actions
? { ? {
right: <ExtraActions />, right: <Actions />,
} }
: {} : {}
} }
@ -157,16 +162,45 @@ function useCurrentTaskType() {
); );
} }
function PopupContext(props: any) {
const { popupId } = useParams();
const { record } = usePopupRecordContext();
const navigate = useNavigate();
if (!popupId) {
return null;
}
return (
<ActionContextProvider
visible={Boolean(popupId)}
setVisible={(visible) => {
if (!visible) {
navigate(-1);
}
}}
openMode="modal"
>
<CollectionRecordProvider record={record}>{props.children}</CollectionRecordProvider>
</ActionContextProvider>
);
}
const PopupRecordContext = createContext<any>({ record: null, setRecord: (record) => {} });
export function usePopupRecordContext() {
return useContext(PopupRecordContext);
}
export function WorkflowTasks() { export function WorkflowTasks() {
const compile = useCompile(); const compile = useCompile();
const { setTitle } = useDocumentTitle(); const { setTitle } = useDocumentTitle();
const navigate = useNavigate(); const navigate = useNavigate();
const { taskType, status = TASK_STATUS.PENDING } = useParams(); const apiClient = useAPIClient();
const { taskType, status = TASK_STATUS.PENDING, popupId } = useParams();
const { token } = useToken(); const { token } = useToken();
const [currentRecord, setCurrentRecord] = useState<any>(null);
const items = useTaskTypeItems(); const items = useTaskTypeItems();
const { title, collection, useActionParams, component: Component } = useCurrentTaskType(); const { title, collection, action = 'list', useActionParams, Item, Detail } = useCurrentTaskType();
const params = useActionParams(status); const params = useActionParams(status);
@ -180,6 +214,24 @@ export function WorkflowTasks() {
} }
}, [items, navigate, status, taskType]); }, [items, navigate, status, taskType]);
useEffect(() => {
if (popupId && !currentRecord) {
apiClient
.resource(collection)
.get({
filterByTk: popupId,
})
.then((res) => {
if (res.data?.data) {
setCurrentRecord(res.data.data);
}
})
.catch((err) => {
console.error(err);
});
}
}, [popupId, collection, currentRecord, apiClient]);
const typeKey = taskType ?? items[0].key; const typeKey = taskType ?? items[0].key;
return ( return (
@ -205,84 +257,95 @@ export function WorkflowTasks() {
} }
`} `}
> >
<SchemaComponentContext.Provider value={{ designable: false }}> <PopupRecordContext.Provider
<SchemaComponent value={{
components={{ record: currentRecord,
Layout, setRecord: setCurrentRecord,
PageHeader, }}
StatusTabs, >
}} <SchemaComponentContext.Provider value={{ designable: false }}>
schema={{ <SchemaComponent
name: `${taskType}-${status}`, components={{
type: 'void', Layout,
'x-decorator': 'List.Decorator', PageHeader,
'x-decorator-props': { StatusTabs,
collection, }}
action: 'list', schema={{
params: { name: `${taskType}-${status}`,
pageSize: 20, type: 'void',
sort: ['-createdAt'], 'x-decorator': 'List.Decorator',
...params, 'x-decorator-props': {
}, collection,
}, action,
properties: { params: {
header: { pageSize: 20,
type: 'void', sort: ['-createdAt'],
'x-component': 'PageHeader', ...params,
'x-component-props': {
className: classnames('pageHeaderCss'),
style: {
background: token.colorBgContainer,
padding: '12px 24px 0 24px',
},
title,
},
properties: {
tabs: {
type: 'void',
'x-component': 'StatusTabs',
},
}, },
}, },
content: { properties: {
type: 'void', header: {
'x-component': 'Layout.Content', type: 'void',
'x-component-props': { 'x-component': 'PageHeader',
className: contentClass, 'x-component-props': {
style: { className: classnames('pageHeaderCss'),
padding: `${token.paddingPageVertical}px ${token.paddingPageHorizontal}px`, style: {
}, background: token.colorBgContainer,
}, padding: '12px 24px 0 24px',
properties: {
list: {
type: 'array',
'x-component': 'List',
'x-component-props': {
className: css`
> .itemCss:not(:last-child) {
border-bottom: none;
}
`,
locale: {
emptyText: `{{ t("No data yet", { ns: "${NAMESPACE}" }) }}`,
},
}, },
properties: { title,
item: { },
type: 'object', properties: {
'x-decorator': 'List.Item', tabs: {
'x-component': Component, type: 'void',
'x-read-pretty': true, 'x-component': 'StatusTabs',
},
},
},
content: {
type: 'void',
'x-component': 'Layout.Content',
'x-component-props': {
className: contentClass,
style: {
padding: `${token.paddingPageVertical}px ${token.paddingPageHorizontal}px`,
},
},
properties: {
list: {
type: 'array',
'x-component': 'List',
'x-component-props': {
className: css`
> .itemCss:not(:last-child) {
border-bottom: none;
}
`,
locale: {
emptyText: `{{ t("No data yet", { ns: "${NAMESPACE}" }) }}`,
},
},
properties: {
item: {
type: 'object',
'x-decorator': 'List.Item',
'x-component': Item,
'x-read-pretty': true,
},
}, },
}, },
}, },
}, },
popup: {
type: 'void',
'x-decorator': PopupContext,
'x-component': Detail,
},
}, },
}, }}
}} />
/> </SchemaComponentContext.Provider>
<Outlet /> </PopupRecordContext.Provider>
</SchemaComponentContext.Provider>
</Layout> </Layout>
</Layout> </Layout>
); );
@ -296,7 +359,7 @@ function WorkflowTasksLink() {
return types.length ? ( return types.length ? (
<Tooltip title={lang('Workflow todos')}> <Tooltip title={lang('Workflow todos')}>
<Button> <Button>
<Link to={`/admin/workflow/tasks/${types[0]}`} onClick={reload}> <Link to={`/admin/workflow/tasks/${types[0]}/${TASK_STATUS.PENDING}`} onClick={reload}>
<Badge count={total} size="small"> <Badge count={total} size="small">
<CheckCircleOutlined /> <CheckCircleOutlined />
</Badge> </Badge>
@ -357,7 +420,7 @@ function TasksCountsProvider(props: any) {
return <TasksCountsContext.Provider value={{ reload, total, counts }}>{props.children}</TasksCountsContext.Provider>; return <TasksCountsContext.Provider value={{ reload, total, counts }}>{props.children}</TasksCountsContext.Provider>;
} }
export const TasksProvider = (props: any) => { export function TasksProvider(props: any) {
const isLoggedIn = useIsLoggedIn(); const isLoggedIn = useIsLoggedIn();
const content = ( const content = (
@ -377,4 +440,4 @@ export const TasksProvider = (props: any) => {
); );
return isLoggedIn ? <TasksCountsProvider>{content}</TasksCountsProvider> : content; return isLoggedIn ? <TasksCountsProvider>{content}</TasksCountsProvider> : content;
}; }

View File

@ -120,15 +120,10 @@ export default class PluginWorkflowClient extends Plugin {
}); });
this.router.add('admin.workflow.tasks', { this.router.add('admin.workflow.tasks', {
path: '/admin/workflow/tasks/:taskType/:status?', path: '/admin/workflow/tasks/:taskType/:status/:popupId?',
Component: WorkflowTasks, Component: WorkflowTasks,
}); });
this.router.add('admin.workflow.tasks.popup', {
path: '/admin/workflow/tasks/:taskType/:status/popups/*',
Component: PagePopups,
});
this.app.pluginSettingsManager.add(NAMESPACE, { this.app.pluginSettingsManager.add(NAMESPACE, {
icon: 'PartitionOutlined', icon: 'PartitionOutlined',
title: `{{t("Workflow", { ns: "${NAMESPACE}" })}}`, title: `{{t("Workflow", { ns: "${NAMESPACE}" })}}`,
@ -193,3 +188,4 @@ export { default as useStyles } from './style';
export { Trigger, useTrigger } from './triggers'; export { Trigger, useTrigger } from './triggers';
export * from './utils'; export * from './utils';
export * from './variable'; export * from './variable';
export { TASK_STATUS, usePopupRecordContext } from './WorkflowTasks';

View File

@ -793,10 +793,16 @@ export default class PluginWorkflowServer extends Plugin {
/** /**
* @experimental * @experimental
*/ */
public async toggleTaskStatus(task: WorkflowTaskModel, done: boolean, { transaction }: Transactionable) { public async toggleTaskStatus(task: WorkflowTaskModel, on: boolean, { transaction }: Transactionable) {
const { db } = this.app; const { db } = this.app;
const repository = db.getRepository('workflowTasks') as WorkflowTasksRepository; const repository = db.getRepository('workflowTasks') as WorkflowTasksRepository;
if (done) { if (on) {
await repository.updateOrCreate({
filterKeys: ['key', 'type'],
values: task,
transaction,
});
} else {
await repository.destroy({ await repository.destroy({
filter: { filter: {
type: task.type, type: task.type,
@ -804,12 +810,6 @@ export default class PluginWorkflowServer extends Plugin {
}, },
transaction, transaction,
}); });
} else {
await repository.updateOrCreate({
filterKeys: ['key', 'type'],
values: task,
transaction,
});
} }
// NOTE: // NOTE:

View File

@ -128,9 +128,7 @@
"@nocobase/plugin-workflow-action-trigger", "@nocobase/plugin-workflow-action-trigger",
"@nocobase/plugin-workflow-aggregate", "@nocobase/plugin-workflow-aggregate",
"@nocobase/plugin-workflow-delay", "@nocobase/plugin-workflow-delay",
"@nocobase/plugin-workflow-dynamic-calculation",
"@nocobase/plugin-workflow-loop", "@nocobase/plugin-workflow-loop",
"@nocobase/plugin-workflow-manual",
"@nocobase/plugin-workflow-parallel", "@nocobase/plugin-workflow-parallel",
"@nocobase/plugin-workflow-request", "@nocobase/plugin-workflow-request",
"@nocobase/plugin-workflow-sql", "@nocobase/plugin-workflow-sql",