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>
<DndContext>
<div
style={{ display: 'flex', alignItems: 'center', gap: 8, ...style, marginTop: 0 }}
style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 0, ...style }}
{...others}
className={cx(others.className, 'nb-action-bar')}
>

View File

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

View File

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

View File

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

View File

@ -16,13 +16,14 @@ import * as jobActions from './actions';
import ManualInstruction from './ManualInstruction';
import { MANUAL_TASK_TYPE } from '../common/constants';
import { Model } from '@nocobase/database';
interface WorkflowManualTaskModel {
id: number;
userId: number;
workflowId: number;
executionId: number;
status: number;
class WorkflowManualTaskModel extends Model {
declare id: number;
declare userId: number;
declare workflowId: number;
declare executionId: number;
declare status: number;
}
export default class extends Plugin {
@ -55,7 +56,13 @@ export default class extends Plugin {
const workflowPlugin = this.app.pm.get(WorkflowPlugin) as WorkflowPlugin;
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(
{
type: MANUAL_TASK_TYPE,
@ -63,8 +70,9 @@ export default class extends Plugin {
userId: task.userId,
workflowId: task.workflowId,
},
Boolean(task.status),
options,
task.status === JOB_STATUS.PENDING,
// allCount,
{ transaction },
);
});
}

View File

@ -7,7 +7,7 @@
* 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 ManualInstruction from './ManualInstruction';
@ -111,3 +111,24 @@ export async function submit(context: Context, next) {
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 classnames from 'classnames';
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 {
ActionContextProvider,
CollectionRecordProvider,
css,
PinnedPluginListProvider,
SchemaComponent,
SchemaComponentContext,
SchemaComponentOptions,
useAPIClient,
useApp,
useCompile,
useDocumentTitle,
@ -44,9 +47,11 @@ const contentClass = css`
export interface TaskTypeOptions {
title: string;
collection: string;
action: string;
useActionParams: Function;
component: React.ComponentType;
extraActions?: React.ComponentType;
Actions?: React.ComponentType;
Item: React.ComponentType;
Detail: React.ComponentType;
// children?: TaskTypeOptions[];
}
@ -65,7 +70,7 @@ function MenuLink({ type }: any) {
return (
<Link
to={`/admin/workflow/tasks/${type}`}
to={`/admin/workflow/tasks/${type}/${TASK_STATUS.PENDING}`}
className={css`
display: flex;
align-items: center;
@ -85,7 +90,7 @@ function MenuLink({ type }: any) {
);
}
const TASK_STATUS = {
export const TASK_STATUS = {
ALL: 'all',
PENDING: 'pending',
COMPLETED: 'completed',
@ -95,7 +100,7 @@ function StatusTabs() {
const navigate = useNavigate();
const { taskType, status = TASK_STATUS.PENDING } = useParams();
const type = useCurrentTaskType();
const { extraActions: ExtraActions } = type;
const { Actions } = type;
return (
<Tabs
activeKey={status}
@ -122,9 +127,9 @@ function StatusTabs() {
},
]}
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() {
const compile = useCompile();
const { setTitle } = useDocumentTitle();
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 [currentRecord, setCurrentRecord] = useState<any>(null);
const items = useTaskTypeItems();
const { title, collection, useActionParams, component: Component } = useCurrentTaskType();
const { title, collection, action = 'list', useActionParams, Item, Detail } = useCurrentTaskType();
const params = useActionParams(status);
@ -180,6 +214,24 @@ export function WorkflowTasks() {
}
}, [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;
return (
@ -205,84 +257,95 @@ export function WorkflowTasks() {
}
`}
>
<SchemaComponentContext.Provider value={{ designable: false }}>
<SchemaComponent
components={{
Layout,
PageHeader,
StatusTabs,
}}
schema={{
name: `${taskType}-${status}`,
type: 'void',
'x-decorator': 'List.Decorator',
'x-decorator-props': {
collection,
action: 'list',
params: {
pageSize: 20,
sort: ['-createdAt'],
...params,
},
},
properties: {
header: {
type: 'void',
'x-component': 'PageHeader',
'x-component-props': {
className: classnames('pageHeaderCss'),
style: {
background: token.colorBgContainer,
padding: '12px 24px 0 24px',
},
title,
},
properties: {
tabs: {
type: 'void',
'x-component': 'StatusTabs',
},
<PopupRecordContext.Provider
value={{
record: currentRecord,
setRecord: setCurrentRecord,
}}
>
<SchemaComponentContext.Provider value={{ designable: false }}>
<SchemaComponent
components={{
Layout,
PageHeader,
StatusTabs,
}}
schema={{
name: `${taskType}-${status}`,
type: 'void',
'x-decorator': 'List.Decorator',
'x-decorator-props': {
collection,
action,
params: {
pageSize: 20,
sort: ['-createdAt'],
...params,
},
},
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: {
header: {
type: 'void',
'x-component': 'PageHeader',
'x-component-props': {
className: classnames('pageHeaderCss'),
style: {
background: token.colorBgContainer,
padding: '12px 24px 0 24px',
},
properties: {
item: {
type: 'object',
'x-decorator': 'List.Item',
'x-component': Component,
'x-read-pretty': true,
title,
},
properties: {
tabs: {
type: 'void',
'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,
},
},
},
}}
/>
<Outlet />
</SchemaComponentContext.Provider>
}}
/>
</SchemaComponentContext.Provider>
</PopupRecordContext.Provider>
</Layout>
</Layout>
);
@ -296,7 +359,7 @@ function WorkflowTasksLink() {
return types.length ? (
<Tooltip title={lang('Workflow todos')}>
<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">
<CheckCircleOutlined />
</Badge>
@ -357,7 +420,7 @@ function TasksCountsProvider(props: any) {
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 content = (
@ -377,4 +440,4 @@ export const TasksProvider = (props: any) => {
);
return isLoggedIn ? <TasksCountsProvider>{content}</TasksCountsProvider> : content;
};
}

View File

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

View File

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

View File

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