This commit is contained in:
那些花儿
2025-07-28 10:48:38 +08:00
parent 030cf7cc4c
commit 3b51ed7a51
450 changed files with 82310 additions and 1213 deletions
@@ -0,0 +1,13 @@
package com.budwk.app.flow.engine;
import com.budwk.app.flow.engine.core.Execution;
/**
*
* 模型行为
* @author mldong
* @date 2023/4/25
*/
public interface Action {
public void execute(Execution execution);
}
@@ -0,0 +1,29 @@
package com.budwk.app.flow.engine;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.model.TaskModel;
import java.util.List;
/**
*
* 分配参与者的处理接口
* @author mldong
* @date 2023/6/15
*/
public interface AssignmentHandler {
/**
* 分配参与者方法,可获取到当前的执行对象
* @param model 模型对象
* @param execution 执行对象
* @return Object 参与者对象
*/
List<String> assign(TaskModel model, Execution execution);
default String getMessage() {
return this.getClass().getSimpleName();
}
default int getOrder() {
return Integer.MIN_VALUE;
}
}
@@ -0,0 +1,22 @@
package com.budwk.app.flow.engine;
import com.budwk.app.flow.engine.model.TaskModel;
import com.budwk.app.flow.entity.Candidate;
import java.util.List;
/**
*
* 候选人处理接口
* @author mldong
* @date 2023/6/26
*/
public interface CandidateHandler {
/**
* 根据任务模型参数获取候选人信息
* @param model
* @return
*/
List<Candidate> handle(TaskModel model);
}
@@ -0,0 +1,54 @@
package com.budwk.app.flow.engine;
import java.util.List;
/**
*
* 服务上下文接口,类似spring的ioc
* @author mldong
* @date 2023/4/26
*/
public interface Context {
/**
* 根据服务名称、实例向服务工厂注册
* @param name 服务名称
* @param object 服务实例
*/
void put(String name, Object object);
/**
* 根据服务名称、类型向服务工厂注册
* @param name 服务名称
* @param clazz 类型
*/
void put(String name, Class<?> clazz);
/**
* 判断是否存在给定的服务名称
* @param name 服务名称
* @return
*/
boolean exist(String name);
/**
* 根据给定的类型查找服务实例
* @param clazz 类型
* @return
*/
<T> T find(Class<T> clazz);
/**
* 根据给定的类型查找所有此类型的服务实例
* @param clazz 类型
* @return
*/
<T> List<T> findList(Class<T> clazz);
/**
* 根据给定的服务名称、类型查找服务实例
* @param name 服务名称
* @param clazz 类型
* @return
*/
<T> T findByName(String name, Class<T> clazz);
}
@@ -0,0 +1,19 @@
package com.budwk.app.flow.engine;
import com.budwk.app.flow.engine.core.Execution;
/**
*
* 决策处理器接口
* @author mldong
* @date 2023/5/1
*/
public interface DecisionHandler {
/**
* 定义决策方法,实现类需要根据执行对象做处理,并返回后置流转的name
* @param execution
* @return String 后置流转的name
*/
String decide(Execution execution);
}
@@ -0,0 +1,125 @@
package com.budwk.app.flow.engine;
import cn.hutool.core.lang.Dict;
import com.budwk.app.flow.engine.cfg.Configuration;
import com.budwk.app.flow.entity.ProcessInstance;
import com.budwk.app.flow.entity.ProcessTask;
import com.budwk.app.flow.service.ProcessDefineService;
import com.budwk.app.flow.service.ProcessInstanceService;
import com.budwk.app.flow.service.ProcessTaskService;
import java.util.List;
/**
* 流程引擎接口
*
* @author mldong
* @date 2023/5/29
*/
public interface FlowEngine {
/**
* 根据Configuration对象配置实现类
*
* @param config 全局配置对象
* @return FlowEngine 流程引擎
*/
FlowEngine configure(Configuration config);
/**
* 获取流程定义服务
*
* @return ProcessDefineService
*/
ProcessDefineService processDefineService();
/**
* 获取流程实例服务
*
* @return ProcessInstanceService
*/
ProcessInstanceService processInstanceService();
/**
* 获取流程任务服务
*
* @return ProcessTaskService
*/
ProcessTaskService processTaskService();
/**
* 根据流程定义KEY、操作人ID、启动流程参数启动流程实例 (会自动选择KEY相同的流程定义中最新版本的那个)
*
* @param key 流程定义KEY
* @param businessKey 业务标识
* @param operator 操作人ID
* @param args 启动参数
* @return
*/
ProcessInstance startProcessInstanceByKey(String key, String businessKey, String operator, Dict args);
/**
* 根据流程定义ID、操作人ID、启动流程参数启动流程实例
*
* @param id 流程定义ID
* @param businessKey 业务标识
* @param operator 操作人ID
* @param args 启动流程参数
* @return ProcessInstance 流程实例
*/
ProcessInstance startProcessInstanceById(Long id, String businessKey, String operator, Dict args);
/**
* 根据流程定义ID、操作人ID、启动流程参数启动流程实例
*
* @param id 流程定义ID
* @param businessKey 业务标识
* @param operator 操作人ID
* @param args 启动流程参数
* @param parentId
* @param parentNodeName
* @return ProcessInstance 流程实例
*/
ProcessInstance startProcessInstanceById(Long id, String businessKey, String operator, Dict args, Long parentId, String parentNodeName);
/**
* 执行流程任务
*
* @param processTaskId
* @param operator
* @param args
* @return
*/
List<ProcessTask> executeProcessTask(Long processTaskId, String operator, Dict args);
/**
* 执行流程任务并跳转
*
* @param processTaskId
* @param operator
* @param args
* @param nodeName
* @return
*/
List<ProcessTask> executeAndJumpTask(Long processTaskId, String operator, Dict args, String nodeName);
/**
* 执行流程任务并跳转到结束节点
*
* @param processTaskId
* @param operator
* @param args
* @return
*/
List<ProcessTask> executeAndJumpToEnd(Long processTaskId, String operator, Dict args);
/**
* 执行流程任务并跳转到第一个任务节点
*
* @param processTaskId
* @param operator
* @param args
* @return
*/
List<ProcessTask> executeAndJumpToFirstTaskNode(Long processTaskId, String operator, Dict args);
}
@@ -0,0 +1,18 @@
package com.budwk.app.flow.engine;
import com.budwk.app.flow.engine.core.Execution;
/**
*
* 流程节点拦截器
* @author mldong
* @date 2023/9/3
*/
public interface FlowInterceptor{
/**
* 拦截方法,参数为执行对象
* @param execution 执行对象。可从中获取执行的数据
*/
void intercept(Execution execution);
}
@@ -0,0 +1,31 @@
package com.budwk.app.flow.engine.cfg;
import com.budwk.app.flow.engine.Context;
import com.budwk.app.flow.engine.core.ServiceContext;
import com.budwk.app.flow.engine.impl.SimpleContext;
import com.budwk.app.flow.engine.parser.impl.*;
/**
*
* 流程引擎配置类
* @author mldong
* @date 2022/6/12
*/
public class Configuration {
public Configuration() {
this(new SimpleContext());
}
public Configuration(Context context) {
ServiceContext.setContext(context);
ServiceContext.put("decision", DecisionParser.class);
ServiceContext.put("end", EndParser.class);
ServiceContext.put("fork", ForkParser.class);
ServiceContext.put("join", JoinParser.class);
ServiceContext.put("start", StartParser.class);
ServiceContext.put("task", TaskParser.class);
ServiceContext.put("custom",CustomParser.class);
ServiceContext.put("wfSubProcess", WfSubProcessParser.class);
}
}
@@ -0,0 +1,70 @@
package com.budwk.app.flow.engine.core;
import cn.hutool.core.lang.Dict;
import com.budwk.app.flow.engine.FlowEngine;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.ProcessModel;
import com.budwk.app.flow.entity.ProcessInstance;
import com.budwk.app.flow.entity.ProcessTask;
import com.budwk.app.flow.enums.ProcessTaskStateEnum;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* 执行对象参数
* @author mldong
* @date 2023/4/25
*/
@Data
public class Execution {
// 流程实例ID
private Long processInstanceId;
// 当前流程任务ID
private Long processTaskId;
// 执行对象扩展参数
private Dict args;
// 当前流程模型
private ProcessModel processModel;
// 当前任务
private ProcessTask processTask;
// 当前流程实例
private ProcessInstance processInstance;
// 所有任务集合
private List<ProcessTask> processTaskList = new ArrayList<>();
// 是否可合并
private boolean isMerged;
// 流程引擎对象
private FlowEngine engine;
// 操作人
private String operator;
// 当前节点模型
private NodeModel nodeModel;
/**
* 添加任务到任务集合
* @param processTask
*/
public void addTask(ProcessTask processTask) {
this.processTaskList.add(processTask);
}
/**
* 添加任务集合
* @param processTasks
*/
public void addTasks(List<ProcessTask> processTasks) {
this.processTaskList.addAll(processTasks);
}
/**
* 获取正在进行中的任务列表
* @return
*/
public List<ProcessTask> getDoingTaskList() {
return this.processTaskList.stream().filter(item->{
return ProcessTaskStateEnum.DOING.getCode().equals(item.getTaskState());
}).collect(Collectors.toList());
}
}
@@ -0,0 +1,241 @@
package com.budwk.app.flow.engine.core;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.budwk.app.base.exception.BaseException;
import com.budwk.app.flow.constant.FlowConst;
import com.budwk.app.flow.engine.FlowEngine;
import com.budwk.app.flow.engine.cfg.Configuration;
import com.budwk.app.flow.engine.model.*;
import com.budwk.app.flow.engine.parser.ModelParser;
import com.budwk.app.flow.engine.util.FlowUtil;
import com.budwk.app.flow.entity.ProcessDefine;
import com.budwk.app.flow.entity.ProcessInstance;
import com.budwk.app.flow.entity.ProcessTask;
import com.budwk.app.flow.enums.ProcessTaskStateEnum;
import com.budwk.app.flow.service.ProcessDefineService;
import com.budwk.app.flow.service.ProcessInstanceService;
import com.budwk.app.flow.service.ProcessTaskService;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.ioc.aop.Aop;
import java.util.Collections;
import java.util.List;
/**
* 工作流引擎实现
*
* @author mldong
* @date 2023/5/29
*/
public class FlowEngineImpl implements FlowEngine {
protected Configuration configuration;
private ProcessDefineService processDefineService;
private ProcessInstanceService processInstanceService;
private ProcessTaskService processTaskService;
@Override
public FlowEngine configure(Configuration config) {
this.configuration = config;
processDefineService = ServiceContext.find(ProcessDefineService.class);
processInstanceService = ServiceContext.find(ProcessInstanceService.class);
processTaskService = ServiceContext.find(ProcessTaskService.class);
return this;
}
@Override
public ProcessDefineService processDefineService() {
return processDefineService;
}
@Override
public ProcessInstanceService processInstanceService() {
return processInstanceService;
}
@Override
public ProcessTaskService processTaskService() {
return processTaskService;
}
@Override
public ProcessInstance startProcessInstanceByKey(String key, String businessKey, String operator, Dict args) {
ProcessDefine define = processDefineService.getLastByName(key);
return startProcessInstanceById(define.getId(), businessKey, operator, args);
}
@Override
@Aop(TransAop.READ_COMMITTED)
public ProcessInstance startProcessInstanceById(Long id, String businessKey, String operator, Dict args) {
return startProcessInstanceById(id, businessKey, operator, args, null, null);
}
@Override
@Aop(TransAop.READ_COMMITTED)
public ProcessInstance startProcessInstanceById(Long id, String businessKey, String operator, Dict args, Long parentId, String parentNodeName) {
if (StrUtil.isBlank(businessKey)) {
// throw new RuntimeException("业务主键不能为空");
}
if (args == null) args = Dict.create();
// 1. 根据流程定义ID查询流程定义文件
ProcessDefine processDefine = processDefineService.getById(id);
if (processDefine == null) {
throw new BaseException("没有流程定义");
}
// 2. 将流程定义文件转成流程模型
ProcessModel processModel = processDefineService.processDefineToModel(processDefine);
// 3. 根据流程定义对象创建流程实例
ProcessInstance processInstance = processInstanceService.createProcessInstance(processDefine, businessKey, operator, args, parentId, parentNodeName);
args.set(FlowConst.PROCESS_INSTANCE_ID_KEY, processInstance.getId());
// 4. 构建执行参数对象
Execution execution = new Execution();
execution.setProcessModel(processModel);
execution.setProcessInstance(processInstance);
execution.setProcessInstanceId(processInstance.getId());
execution.setEngine(this);
execution.setArgs(args);
// 5. 拿到开始节点模型,调用其execute方法
processModel.getStart().execute(execution);
return processInstance;
}
@Override
@Aop(TransAop.READ_COMMITTED)
public List<ProcessTask> executeProcessTask(Long processTaskId, String operator, Dict args) {
Execution execution = execute(processTaskId, operator, args);
if (execution == null) return Collections.emptyList();
ProcessModel processModel = execution.getProcessModel();
// 7. 根据流程任务名称获取对应的任务节点模型
NodeModel nodeModel = processModel.getNode(execution.getProcessTask().getTaskName());
// 8. 调用节点模型执行方法
nodeModel.execute(execution);
return execution.getProcessTaskList();
}
@Override
@Aop(TransAop.READ_COMMITTED)
public List<ProcessTask> executeAndJumpTask(Long processTaskId, String operator, Dict args, String nodeName) {
Execution execution = execute(processTaskId, operator, args);
if (execution == null) return Collections.emptyList();
ProcessModel model = execution.getProcessModel();
if (StrUtil.isEmpty(nodeName)) {
ProcessTask newTask = processTaskService.rejectTask(model, execution.getProcessTask());
execution.addTask(newTask);
} else {
NodeModel nodeModel = model.getNode(nodeName);
if (nodeModel == null) {
throw new BaseException("根据节点名称[" + nodeName + "]无法找到节点模型");
}
// 判断是否为第一个任务节点
if (nodeModel instanceof TaskModel) {
TaskModel taskModel = (TaskModel) nodeModel;
if (FlowUtil.isFistTaskName(model, taskModel.getName())) {
// 第一个任务节点为申请节点,处理人等于流程发起人
taskModel.setAssignee(execution.getProcessInstance().getOperator());
}
}
//动态创建转移对象,由转移对象执行execution实例
TransitionModel tm = new TransitionModel();
tm.setTarget(nodeModel);
tm.setEnabled(true);
tm.execute(execution);
}
return execution.getProcessTaskList();
}
@Override
@Aop(TransAop.READ_COMMITTED)
public List<ProcessTask> executeAndJumpToEnd(Long processTaskId, String operator, Dict args) {
Execution execution = execute(processTaskId, operator, args);
if (execution == null) return Collections.emptyList();
ProcessModel model = execution.getProcessModel();
List<EndModel> endModelList = model.getModels(EndModel.class);
endModelList.forEach(endModel -> {
TransitionModel tm = new TransitionModel();
tm.setTarget(endModel);
tm.setEnabled(true);
tm.execute(execution);
});
return execution.getProcessTaskList();
}
@Override
public List<ProcessTask> executeAndJumpToFirstTaskNode(Long processTaskId, String operator, Dict args) {
Execution execution = execute(processTaskId, operator, args);
if (execution == null) return Collections.emptyList();
ProcessModel model = execution.getProcessModel();
StartModel startModel = model.getStart();
startModel.getOutputs().forEach(transitionModel -> {
transitionModel.setEnabled(true);
// 调整参与者为流程发起人
if (transitionModel.getTarget() instanceof TaskModel) {
TaskModel taskModel = (TaskModel) transitionModel.getTarget();
taskModel.setAssignee(execution.getProcessInstance().getOperator());
}
transitionModel.execute(execution);
});
return execution.getProcessTaskList();
}
/**
* 生成执行对象
*
* @param processTaskId
* @param operator
* @param args
* @return
*/
private Execution execute(Long processTaskId, String operator, Dict args) {
// 1.1 根据id查询正在进行中的流程任务
ProcessTask processTask = processTaskService.getById(processTaskId);
if (processTask == null || !ProcessTaskStateEnum.DOING.getCode().equals(processTask.getTaskState())) {
throw new BaseException("没有进行中的流程任务");
}
// 1.2 判断是否可以执行任务
if (!processTaskService.isAllowed(processTask, operator)) {
// 当前参与者不能执行该流程任务
throw new BaseException("当前参与者不能执行该流程任务");
}
// 2. 根据流程任务查询流程实例
ProcessInstance processInstance = processInstanceService.getById(processTask.getProcessInstanceId());
// 3. 根据流程实例查询流程定义
ProcessDefine processDefine = processDefineService.getById(processInstance.getProcessDefineId());
// 4. 将流程定义文件转成流程模型
ProcessModel processModel = ModelParser.parse(JSONUtil.toJsonStr(processDefine.getContent()));
// 5. 将流程任务状态修改为已完成
processTaskService.finishProcessTask(processTaskId, operator, args);
processTask.setTaskState(ProcessTaskStateEnum.FINISHED.getCode());
// 6. 根据流程定义、实例、任务构建执行参数对象
Execution execution = new Execution();
execution.setProcessModel(processModel);
execution.setProcessInstance(processInstance);
execution.setProcessInstanceId(processInstance.getId());
execution.setProcessTask(processTask);
execution.setProcessTaskId(processTaskId);
execution.setOperator(operator);
execution.setEngine(this);
Dict processInstanceVariable = JSONUtil.toBean(processInstance.getVariable(), Dict.class);
Dict newArgs = Dict.create();
newArgs.putAll(processInstanceVariable);
newArgs.putAll(args);
execution.setArgs(newArgs);
// 如果提交参数中存在f_前辍参数,则更新到流程实例变量中
Dict addArgs = Dict.create();
args.forEach((key, value) -> {
if (key.startsWith(FlowConst.FORM_DATA_PREFIX)) {
addArgs.put(key, value);
}
});
if (ObjectUtil.isNotEmpty(addArgs)) {
processInstanceService.addVariable(processInstance.getId(), addArgs);
}
return execution;
}
}
@@ -0,0 +1,51 @@
package com.budwk.app.flow.engine.core;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReflectUtil;
import com.budwk.app.flow.engine.Context;
import java.util.List;
/**
*
* 单例服务上下文
* @author mldong
* @date 2022/6/12
*/
public class ServiceContext {
private static Context context;
public static void setContext(Context context) {
ServiceContext.context = context;
}
public static void put(String name, Object object) {
Assert.notNull(context,"未注册服务上下文");
context.put(name, object);
}
public static void put(String name, Class<?> clazz) {
Assert.notNull(context,"未注册服务上下文");
context.put(name, ReflectUtil.newInstance(clazz));
}
public static boolean exist(String name) {
Assert.notNull(context,"未注册服务上下文");
return context.exist(name);
}
public static <T> T find(Class<T> clazz) {
Assert.notNull(context,"未注册服务上下文");
return context.find(clazz);
}
public static <T> List<T> findList(Class<T> clazz) {
Assert.notNull(context,"未注册服务上下文");
return context.findList(clazz);
}
public static <T> T findByName(String name, Class<T> clazz) {
Assert.notNull(context,"未注册服务上下文");
return context.findByName(name, clazz);
}
}
@@ -0,0 +1,19 @@
package com.budwk.app.flow.engine.event;
import com.budwk.app.flow.enums.ProcessEventTypeEnum;
import lombok.Builder;
import lombok.Data;
/**
* 流程开始事件
* @author mldong
* @date 2023/12/5
*/
@Data
@Builder
public class ProcessEvent {
// 流程事件类型
private ProcessEventTypeEnum eventType;
// 执行源id(流程实例id,流程任务id)
private Long sourceId;
}
@@ -0,0 +1,10 @@
package com.budwk.app.flow.engine.event;
/**
* 流程事件监听接口
* @author mldong
* @date 2023/12/5
*/
public interface ProcessEventListener {
void onEvent(ProcessEvent event);
}
@@ -0,0 +1,21 @@
package com.budwk.app.flow.engine.event;
import com.budwk.app.flow.engine.core.ServiceContext;
import java.util.List;
/**
* 流程事件发布者类
* @author mldong
* @date 2023/12/5
*/
public class ProcessPublisher {
// 事件通知方法
public static void notify(ProcessEvent event) {
// 这里直接从上下文中获取所有的监听器,并调用监听器的onEvent方法==>通知
List<ProcessEventListener> processEventListenerList = ServiceContext.findList(ProcessEventListener.class);
processEventListenerList.forEach(processEventListener -> {
processEventListener.onEvent(event);
});
}
}
@@ -0,0 +1,17 @@
package com.budwk.app.flow.engine.handlers;
import com.budwk.app.flow.engine.core.Execution;
/**
* 流程各模型操作处理接口
* @author mldong
* @date 2023/5/17
*/
public interface IHandler {
/**
* 子类需要实现的方法,来处理具体的操作
* @param execution 执行对象
*/
void handle(Execution execution);
}
@@ -0,0 +1,98 @@
package com.budwk.app.flow.engine.handlers.impl;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.expression.ExpressionUtil;
import com.budwk.app.flow.constant.FlowConst;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.handlers.IHandler;
import com.budwk.app.flow.engine.model.TaskModel;
import com.budwk.app.flow.enums.CountersignTypeEnum;
import java.util.List;
import java.util.stream.Collectors;
/**
* 会签任务处理,用于判断会签任务是否可通过
* @author mldong
* @date 2023/11/24
*/
public class CountersignHandler implements IHandler {
private TaskModel taskModel;
public CountersignHandler(TaskModel taskModel) {
this.taskModel = taskModel;
}
@Override
public void handle(Execution execution) {
boolean isMerged = false;
String countersignType = taskModel.getExt().get("countersignType","PARALLEL");
String countersignCompletionCondition = taskModel.getExt().get("countersignCompletionCondition","");
String prefix = FlowConst.COUNTERSIGN_VARIABLE_PREFIX +taskModel.getName()+"_";
// 会签办理人列表
List<String> operatorList = Convert.toList(String.class,execution.getArgs().get(prefix+FlowConst.COUNTERSIGN_OPERATOR_LIST));
// 循环计数器,办理人在列表中的索引
int loopCounter = operatorList.indexOf(execution.getOperator());
// 追加计数器
execution.getArgs().put(prefix+FlowConst.LOOP_COUNTER,loopCounter);
// 追加已完成数量
execution.getArgs().put(prefix + FlowConst.NR_OF_COMPLETED_INSTANCES,
execution.getArgs().get(prefix + FlowConst.NR_OF_COMPLETED_INSTANCES,0)+1);
/**
* ● 全部通过:为空
* ● 按数量通过:#nrOfCompletedInstances==n,这里表示n人完成任务,会签结束。
* ● 按比例通过:#nrOfCompletedInstances/nrOfInstances==n,这里表示已完成会签数与总实例数达到一定比例时,会签结束
* ● 一票通过:#nrOfCompletedInstances==1,这里表示1人完成任务,会签结束。
* ● 一票否决:ONE_VOTE_VETO
*/
if("ONE_VOTE_VETO".equalsIgnoreCase(countersignCompletionCondition)) {
// 一票否决
if(execution.getArgs().containsKey(FlowConst.COUNTERSIGN_DISAGREE_FLAG)) {
// 存在拒绝标识,则直接通过
isMerged = true;
}
} else if(!StrUtil.isBlank(countersignCompletionCondition)) {
// 根据条件判断是否通过
Dict dict = Dict.create();
execution.getArgs().forEach((k,v)->{
dict.set(k.replace(prefix,""),v);
});
isMerged = Convert.toBool(ExpressionUtil.eval(countersignCompletionCondition, dict));
}
if(!isMerged && CountersignTypeEnum.SEQUENTIAL.toString().equalsIgnoreCase(countersignType)) {
// 串行未通过,则判断是否为最后一个
if (loopCounter == operatorList.size() - 1) {
isMerged = true;
} else {
// 非最后一个,则继续创建会签任务
execution.getEngine().processTaskService().createCountersignTask(taskModel, execution);
}
}
if(!isMerged && CountersignTypeEnum.PARALLEL.toString().equalsIgnoreCase(countersignType)) {
// 是否所有会签任务已完成
isMerged = execution.getEngine().processTaskService().getDoingTaskList(execution.getProcessInstanceId(), new String[]{taskModel.getName()}).size()==0;
if(!isMerged) {
// 未通过,更新已完成实例数量
Dict addVariable = Dict.create();
addVariable.put(prefix + FlowConst.NR_OF_COMPLETED_INSTANCES, execution.getArgs().get(prefix+FlowConst.NR_OF_COMPLETED_INSTANCES));
execution.getEngine().processInstanceService().addVariable(execution.getProcessInstanceId(), addVariable);
}
}
if(isMerged) {
// 获取所有会签参数键值
List<String> keys = execution.getArgs().keySet().stream().filter(k->k.startsWith(prefix)).collect(Collectors.toList());
keys.add(FlowConst.COUNTERSIGN_DISAGREE_FLAG);
// 如果可以合并,则把流程实例中的会签参数清空
execution.getEngine().processInstanceService().removeVariable(
execution.getProcessInstanceId(),
keys.toArray(new String[]{}));
// 如果为并行会签,需将其他会签任务设置为废弃
if(CountersignTypeEnum.PARALLEL.toString().equalsIgnoreCase(countersignType)) {
execution.getEngine().processTaskService().getDoingTaskList(execution.getProcessInstanceId(), new String[]{taskModel.getName()}).stream().forEach(t->{
execution.getEngine().processTaskService().abandonProcessTask(t.getId(), FlowConst.AUTO_ID, execution.getArgs());
});
}
}
execution.setMerged(isMerged);
}
}
@@ -0,0 +1,48 @@
package com.budwk.app.flow.engine.handlers.impl;
import com.budwk.app.flow.engine.FlowInterceptor;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.core.ServiceContext;
import com.budwk.app.flow.engine.event.ProcessEvent;
import com.budwk.app.flow.engine.event.ProcessPublisher;
import com.budwk.app.flow.engine.handlers.IHandler;
import com.budwk.app.flow.engine.model.TaskModel;
import com.budwk.app.flow.entity.ProcessTask;
import com.budwk.app.flow.enums.ProcessEventTypeEnum;
import com.budwk.app.flow.enums.ProcessTaskPerformTypeEnum;
import java.util.List;
/**
* 创建任务处理器
* @author mldong
* @date 2023/5/16
*/
public class CreateTaskHandler implements IHandler {
private TaskModel taskModel;
public CreateTaskHandler(TaskModel taskModel) {
this.taskModel = taskModel;
}
@Override
public void handle(Execution execution) {
List<ProcessTask> processTaskList;
if(ProcessTaskPerformTypeEnum.COUNTERSIGN.equals(taskModel.getPerformType())) {
// 会签类型,创建会签任务
processTaskList = execution.getEngine().processTaskService().createCountersignTask(taskModel, execution);
} else {
// 创建普通任务
processTaskList = execution.getEngine().processTaskService().createTask(taskModel, execution);
}
// 将任务添加到执行对象中
execution.addTasks(processTaskList);
// 从服务上下文中获取拦截器执行
ServiceContext.findList(FlowInterceptor.class).forEach(flowInterceptor -> {
flowInterceptor.intercept(execution);
});
// 发布流程任务开始事件
processTaskList.forEach(processTask -> {
ProcessPublisher.notify(ProcessEvent.builder().eventType(ProcessEventTypeEnum.PROCESS_TASK_START).sourceId(processTask.getId()).build());
});
}
}
@@ -0,0 +1,55 @@
package com.budwk.app.flow.engine.handlers.impl;
import cn.hutool.core.util.ObjectUtil;
import com.budwk.app.flow.constant.FlowConst;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.event.ProcessEvent;
import com.budwk.app.flow.engine.event.ProcessPublisher;
import com.budwk.app.flow.engine.handlers.IHandler;
import com.budwk.app.flow.engine.model.EndModel;
import com.budwk.app.flow.engine.model.ProcessModel;
import com.budwk.app.flow.engine.model.SubProcessModel;
import com.budwk.app.flow.entity.ProcessInstance;
import com.budwk.app.flow.enums.ProcessEventTypeEnum;
import com.budwk.app.flow.enums.ProcessSubmitTypeEnum;
/**
*
* 结束流程实例的处理器
* @author mldong
* @date 2023/5/29
*/
public class EndProcessHandler implements IHandler {
private EndModel endModel;
public EndProcessHandler(EndModel endModel) {
this.endModel = endModel;
}
@Override
public void handle(Execution execution) {
Integer submitType = execution.getArgs().get(FlowConst.SUBMIT_TYPE, ProcessSubmitTypeEnum.AGREE.getCode());
if(ObjectUtil.equals(submitType, ProcessSubmitTypeEnum.REJECT.getCode())) {
execution.getEngine().processInstanceService().rejectProcessInstance(execution.getProcessInstanceId());
} else {
execution.getEngine().processInstanceService().finishProcessInstance(execution.getProcessInstanceId());
}
// 发布流程实例结束事件
ProcessPublisher.notify(ProcessEvent.builder().eventType(ProcessEventTypeEnum.PROCESS_INSTANCE_END).sourceId(execution.getProcessInstanceId()).build());
ProcessInstance processInstance = execution.getProcessInstance();
if(ObjectUtil.isNotNull(processInstance.getParentId())) {
// 如果子流程存在父流程实例,则执行父流程的子流程节点模型方法
ProcessInstance parentInstance = execution.getEngine().processInstanceService().getById(processInstance.getParentId());
if(parentInstance == null) return;
ProcessModel pm = execution.getEngine().processDefineService().getProcessModel(parentInstance.getProcessDefineId());
if(pm == null) return;
SubProcessModel spm = (SubProcessModel)pm.getNode(processInstance.getParentNodeName());
Execution newExecution = new Execution();
newExecution.setEngine(execution.getEngine());
newExecution.setProcessModel(pm);
newExecution.setProcessInstance(parentInstance);
newExecution.setProcessInstanceId(parentInstance.getId());
newExecution.setArgs(execution.getArgs());
spm.execute(newExecution);
execution.addTasks(newExecution.getProcessTaskList());
}
}
}
@@ -0,0 +1,72 @@
package com.budwk.app.flow.engine.handlers.impl;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.core.ServiceContext;
import com.budwk.app.flow.engine.handlers.IHandler;
import com.budwk.app.flow.engine.model.*;
import com.budwk.app.flow.service.ProcessTaskService;
import java.util.List;
/**
* 合并分支操作的处理器
* @author mldong
* @date 2023/5/21
*/
public class MergeBranchHandler implements IHandler {
private JoinModel joinModel;
public MergeBranchHandler(JoinModel joinModel) {
this.joinModel = joinModel;
}
@Override
public void handle(Execution execution) {
// 判断是否存在正在执行的任务,存在则不允许合并
execution.setMerged(
execution.getEngine()
.processTaskService()
.getDoingTaskList(execution.getProcessInstanceId(),findActiveNodes()).isEmpty());
}
/**
* 对join节点的所有输入变迁进行递归,查找join至fork节点的所有中间task元素
* @param node
* @param buffer
*/
public static void findForkTaskNames(NodeModel node, StringBuilder buffer) {
if(node instanceof ForkModel) return;
List<TransitionModel> inputs = node.getInputs();
for(TransitionModel tm : inputs) {
if(tm.getSource() instanceof TaskModel) {
buffer.append(tm.getSource().getName()).append(",");
}
findForkTaskNames(tm.getSource(), buffer);
}
}
/**
* 对join节点的所有输入变迁进行递归,查找join至fork节点的所有中间task元素
* @see MergeBranchHandler#findActiveNodes()
*/
public String[] findActiveNodes() {
StringBuilder buffer = new StringBuilder(20);
findForkTaskNames(joinModel, buffer);
String[] taskNames = buffer.toString().split(",");
return taskNames;
}
/**
* 判断流程是否可合并
* @param processInstanceId
* @param nodeModel
* @return
*/
public static boolean isMerged(Long processInstanceId, NodeModel nodeModel) {
// 合并节点
StringBuilder buffer = new StringBuilder(20);
MergeBranchHandler.findForkTaskNames(nodeModel, buffer);
String[] taskNames = buffer.toString().split(",");
ProcessTaskService processTaskService = ServiceContext.find(ProcessTaskService.class);
boolean isMerged = processTaskService.getDoingTaskList(processInstanceId,taskNames).isEmpty();
return isMerged;
}
}
@@ -0,0 +1,38 @@
package com.budwk.app.flow.engine.handlers.impl;
import com.budwk.app.base.exception.BaseException;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.handlers.IHandler;
import com.budwk.app.flow.engine.model.SubProcessModel;
import com.budwk.app.flow.entity.ProcessDefine;
/**
* 启动子流程处理类
*
* @author mldong
* @date 2023/12/7
*/
public class StartSubProcessHandler implements IHandler {
private SubProcessModel model;
public StartSubProcessHandler(SubProcessModel model) {
this.model = model;
}
@Override
public void handle(Execution execution) {
ProcessDefine processDefine = execution.getEngine().processDefineService().getProcessDefineByVersion(model.getName(), model.getVersion());
if (processDefine == null) {
throw new BaseException("子流程" + model.getName() + "定义不存在");
}
Long parentId = execution.getProcessInstanceId();
String parentNodeName = model.getName();
execution.getEngine().startProcessInstanceById(
processDefine.getId(),
null,
execution.getOperator(),
execution.getArgs(),
parentId, parentNodeName);
}
}
@@ -0,0 +1,66 @@
package com.budwk.app.flow.engine.impl;
import com.budwk.app.flow.engine.Context;
import lombok.extern.slf4j.Slf4j;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
@IocBean
@Slf4j
public class NutzContext implements Context {
@Inject("refer:$ioc")
private Ioc ioc;
@Override
public void put(String name, Object object) {
ioc.addBean(name, object);
}
@Override
public void put(String name, Class<?> clazz) {
try {
Object o = clazz.getDeclaredConstructor().newInstance();
ioc.addBean(name, o);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException |
NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean exist(String name) {
return ioc.has(name);
}
@Override
public <T> T find(Class<T> clazz) {
try {
T bean = ioc.getByType(clazz);
return bean;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
@Override
public <T> List<T> findList(Class<T> clazz) {
List<T> res = new ArrayList<>();
String[] names = ioc.getNamesByType(clazz);
for (String name : names) {
res.add(ioc.get(clazz, name));
}
return res;
}
@Override
public <T> T findByName(String name, Class<T> clazz) {
return ioc.get(clazz, name);
}
}
@@ -0,0 +1,65 @@
package com.budwk.app.flow.engine.impl;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.budwk.app.flow.engine.Context;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
* 简单的上下文发现实现类
* @author mldong
* @date 2023/4/26
*/
public class SimpleContext implements Context {
private Dict dict = Dict.create();
@Override
public void put(String name, Object object) {
dict.put(name, object);
}
@Override
public void put(String name, Class<?> clazz) {
dict.put(name, ReflectUtil.newInstance(clazz));
}
@Override
public boolean exist(String name) {
return ObjectUtil.isNotNull(dict.getObj(name));
}
@Override
public <T> T find(Class<T> clazz) {
for (Map.Entry<String, Object> entry : dict.entrySet()) {
if (clazz.isInstance(entry.getValue())) {
return clazz.cast(entry.getValue());
}
}
return null;
}
@Override
public <T> List<T> findList(Class<T> clazz) {
List<T> res = new ArrayList<>();
for (Map.Entry<String, Object> entry : dict.entrySet()) {
if (clazz.isInstance(entry.getValue())) {
res.add(clazz.cast(entry.getValue()));
}
}
return res;
}
@Override
public <T> T findByName(String name, Class<T> clazz) {
for (Map.Entry<String, Object> entry : dict.entrySet()) {
if (entry.getKey().equals(name) && clazz.isInstance(entry.getValue())) {
return clazz.cast(entry.getValue());
}
}
return null;
}
}
@@ -0,0 +1,71 @@
//package com.budwk.app.flow.engine.impl;
//
//import cn.hutool.core.util.ObjectUtil;
//import com.budwk.app.flow.engine.Context;
//import org.springframework.beans.factory.config.BeanDefinition;
//import org.springframework.beans.factory.support.DefaultListableBeanFactory;
//import org.springframework.beans.factory.support.RootBeanDefinition;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.ApplicationContextAware;
//import org.springframework.context.ConfigurableApplicationContext;
//import org.springframework.stereotype.Component;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//
///**
// *
// * spring的服务查找实现
// * @author mldong
// * @date 2023/5/31
// */
//@Component
//public class SpringContext implements Context {
//// private ApplicationContext applicationContext;
//// DefaultListableBeanFactory beanFactory;
//
// @Override
// public void put(String name, Object object) {
// ConfigurableApplicationContext context = (ConfigurableApplicationContext)applicationContext;
// context.getBeanFactory().registerSingleton(name, object);
// }
//
// @Override
// public void put(String name, Class<?> clazz) {
// BeanDefinition definition = new RootBeanDefinition(clazz);
// if(beanFactory==null) {
// beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
// }
// beanFactory.registerBeanDefinition(name, definition);
// }
//
// @Override
// public boolean exist(String name) {
// try{
// return ObjectUtil.isNotNull(SpringUtil.getBean(name));
// } catch (Exception e) {
// return false;
// }
// }
//
// @Override
// public <T> T find(Class<T> clazz) {
// return SpringUtil.getBean(clazz);
// }
//
// @Override
// public <T> List<T> findList(Class<T> clazz) {
// List<T> res = new ArrayList<>();
// Map<String,T> map = SpringUtil.getBeansOfType(clazz);
// map.forEach((k,v)->{
// res.add(v);
// });
// return res;
// }
//
// @Override
// public <T> T findByName(String name, Class<T> clazz) {
// return SpringUtil.getBean(name, clazz);
// }
//}
@@ -0,0 +1,41 @@
package com.budwk.app.flow.engine.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.budwk.app.flow.engine.FlowInterceptor;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.service.ProcessSurrogateService;
import com.budwk.app.flow.service.ProcessTaskService;
import lombok.RequiredArgsConstructor;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 任务拦截器,处理代理人
*
* @author mldong
* @date 2023/12/6
*/
@IocBean
public class SurrogateInterceptor implements FlowInterceptor {
@Inject
private ProcessSurrogateService processSurrogateService;
@Inject
private ProcessTaskService processTaskService;
@Override
public void intercept(Execution execution) {
execution.getProcessTaskList().forEach(processTask -> {
List<String> actorList = processTaskService.getTaskActors(processTask.getId());
actorList.forEach(actor -> {
String agent = processSurrogateService.getSurrogate(actor, execution.getProcessModel().getName());
if (StrUtil.isNotEmpty(agent)) {
processTaskService.addTaskActor(processTask.getId(), CollectionUtil.newArrayList(agent));
}
});
});
}
}
@@ -0,0 +1,24 @@
package com.budwk.app.flow.engine.model;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.handlers.IHandler;
import lombok.Data;
/**
*
* 模型基类
* @author mldong
* @date 2023/4/25
*/
@Data
public class BaseModel {
private String name; // 唯一编码
private String displayName; // 显示名称
/**
* 将执行对象execution交给具体的处理器处理
* @param handler
* @param execution
*/
protected void fire(IHandler handler, Execution execution) {
handler.handle(execution);
}
}
@@ -0,0 +1,76 @@
package com.budwk.app.flow.engine.model;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.budwk.app.base.exception.BaseException;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.handlers.IHandler;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
/**
* 自定义节点模型
* @author mldong
* @date 2023/12/7
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class CustomModel extends NodeModel{
private String clazz; // 类路径
private String methodName; // 方法名
private String args; // 入参
private String var; // 执行返回值的变量
/**
* 加载模型时初始化的对象实例
*/
private Object invokeObject;
public void exec(Execution execution) {
if(invokeObject == null) {
invokeObject = ReflectUtil.newInstance(clazz);
}
if(invokeObject == null) {
throw new BaseException("自定义模型[class=" + clazz + "]实例化对象失败");
}
if(invokeObject instanceof IHandler) {
IHandler handler = (IHandler)invokeObject;
handler.handle(execution);
} else {
Object[] objects = getArgs(execution.getArgs(), args);
Class<?> paramTypes[] = Arrays.stream(objects).map(Object::getClass).toArray(Class[]::new);
Method method = ReflectUtil.getMethod(invokeObject.getClass(),methodName, paramTypes);
if(method == null) {
throw new BaseException("自定义模型[class=" + clazz + "]无法找到方法名称:" + methodName);
}
Object returnValue = ReflectUtil.invoke(invokeObject, method, objects);
if(StrUtil.isNotEmpty(var)) {
execution.getArgs().put(var, returnValue);
}
}
execution.getEngine().processTaskService().history(execution, this);
runOutTransition(execution);
}
/**
* 根据传递的执行参数、模型的参数列表返回实际的参数对象数组
* @param execArgs 运行时传递的参数数据
* @param args 自定义节点需要的参数
* @return 调用自定义节点类方法的参数数组
*/
private Object[] getArgs(Map<String, Object> execArgs, String args) {
Object[] objects = null;
if(StrUtil.isNotEmpty(args)) {
String[] argArray = args.split(",");
objects = new Object[argArray.length];
for(int i = 0; i < argArray.length; i++) {
objects[i] = execArgs.get(argArray[i]);
}
}
return objects;
}
}
@@ -0,0 +1,55 @@
package com.budwk.app.flow.engine.model;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.expression.ExpressionUtil;
import com.budwk.app.base.exception.BaseException;
import com.budwk.app.flow.engine.DecisionHandler;
import com.budwk.app.flow.engine.core.Execution;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 决策模型
*
* @author mldong
* @date 2023/4/25
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class DecisionModel extends NodeModel {
private String expr; // 决策表达式
private String handleClass; // 决策处理类
@Override
public void exec(Execution execution) {
// 执行决策节点自定义执行逻辑
boolean isFound = false;
String nextNodeName = null;
if (StrUtil.isNotEmpty(expr)) {
Object obj = ExpressionUtil.eval(expr, execution.getArgs());
nextNodeName = Convert.toStr(obj, "");
} else if (StrUtil.isNotEmpty(handleClass)) {
DecisionHandler decisionHandler = ReflectUtil.newInstance(handleClass);
nextNodeName = decisionHandler.decide(execution);
}
for (TransitionModel transitionModel : getOutputs()) {
if (StrUtil.isNotEmpty(transitionModel.getExpr()) && Convert.toBool(ExpressionUtil.eval(transitionModel.getExpr(), execution.getArgs()), false)) {
// 决策节点输出边存在表达式,则使用输出边的表达式,true则执行
isFound = true;
transitionModel.setEnabled(true);
transitionModel.execute(execution);
} else if (transitionModel.getTo().equalsIgnoreCase(nextNodeName)) {
// 找到对应的下一个节点
isFound = true;
transitionModel.setEnabled(true);
transitionModel.execute(execution);
}
}
if (!isFound) {
// 找不到下一个可执行路线
throw new BaseException("decision节点无法确定下一步执行路线");
}
}
}
@@ -0,0 +1,23 @@
package com.budwk.app.flow.engine.model;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.handlers.impl.EndProcessHandler;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
* 结束模型
* @author mldong
* @date 2023/4/25
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class EndModel extends NodeModel {
@Override
public void exec(Execution execution) {
// 执行结束节点自定义执行逻辑
System.out.println(super.toString());
fire(new EndProcessHandler(this), execution);
}
}
@@ -0,0 +1,18 @@
package com.budwk.app.flow.engine.model;
import com.budwk.app.flow.engine.core.Execution;
/**
*
* 分支模型
* @author mldong
* @date 2023/4/25
*/
public class ForkModel extends NodeModel {
@Override
public void exec(Execution execution) {
// 执行分支节点自定义执行逻辑
runOutTransition(execution);
}
}
@@ -0,0 +1,25 @@
package com.budwk.app.flow.engine.model;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.handlers.impl.MergeBranchHandler;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
* 合并模型
* @author mldong
* @date 2023/4/25
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class JoinModel extends NodeModel {
@Override
public void exec(Execution execution) {
// 执行合并节点自定义执行逻辑
fire(new MergeBranchHandler(this),execution);
if(execution.isMerged()) {
runOutTransition(execution);
}
}
}
@@ -0,0 +1,152 @@
package com.budwk.app.flow.engine.model;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.budwk.app.flow.engine.Action;
import com.budwk.app.flow.engine.*;
import com.budwk.app.flow.engine.core.Execution;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* 节点模型
* @author mldong
* @date 2023/4/25
*/
@EqualsAndHashCode(callSuper = true, exclude = {"inputs", "outputs"})
@Data
public abstract class NodeModel extends BaseModel implements Action {
private String layout;// 布局属性(x,y,w,h)
// 输入边集合
@JsonIgnore
private List<TransitionModel> inputs = new ArrayList<TransitionModel>();
// 输出边集合
@JsonIgnore
private List<TransitionModel> outputs = new ArrayList<TransitionModel>();
private String preInterceptors; // 节点前置拦截器
private String postInterceptors; // 节点后置拦截器
/**
* 由子类自定义执行方法
* @param execution
*/
abstract void exec(Execution execution);
@Override
public void execute(Execution execution) {
// 0.设置当前节点模型
execution.setNodeModel(this);
// 1. 调用前置拦截器
execPreInterceptors(execution);
// 2. 调用子类的exec方法
exec(execution);
// 3. 调用后置拦截器
execPostInterceptors(execution);
}
/**
* 执行输出边
*/
protected void runOutTransition(Execution execution) {
outputs.forEach(tr->{
tr.setEnabled(true);
tr.execute(execution);
});
}
/**
* 执行节点前置拦截器
* @param execution
*/
private void execPreInterceptors(Execution execution) {
if(StrUtil.isEmpty(preInterceptors)) {
preInterceptors = execution.getProcessModel().getPreInterceptors();
}
execInterceptors(preInterceptors,execution);
}
/**
* 执行节点后置拦截器
* @param execution
*/
private void execPostInterceptors(Execution execution) {
if(StrUtil.isEmpty(postInterceptors)) {
postInterceptors = execution.getProcessModel().getPostInterceptors();
}
execInterceptors(postInterceptors,execution);
}
/**
* 执行节点拦截器
* @param execution
*/
private void execInterceptors(String interceptors,Execution execution) {
if(StrUtil.isEmpty(interceptors)) return;
// 存在多个,英文逗号分割
String [] interceptorArr = interceptors.split(",");
for (int i = 0; i < interceptorArr.length; i++) {
String interceptor = interceptorArr[i];
// 反射实例化
FlowInterceptor flowInterceptor = ReflectUtil.newInstance(interceptor);
if(flowInterceptor!=null){
// 调用拦截器方法
flowInterceptor.intercept(execution);
}
}
}
public <T> List<T> getNextModels(Class<T> clazz) {
List<T> models = new ArrayList<T>();
// 记录已递归项,防止死循环
Map<String,Object> temp = new HashMap();
for(TransitionModel tm : this.getOutputs()) {
addNextModels(models, tm, clazz, temp);
}
return models;
}
protected <T> void addNextModels(List<T> models, TransitionModel tm, Class<T> clazz,Map<String,Object> temp) {
if(temp.get(tm.getTo())!=null) {
return;
}
if(clazz.isInstance(tm.getTarget())) {
models.add((T)tm.getTarget());
} else {
for(TransitionModel tm2 : tm.getTarget().getOutputs()) {
temp.put(tm.getTo(), tm.getTarget());
addNextModels(models, tm2, clazz,temp);
}
}
}
/**
* 根据父节点模型、当前节点模型判断是否可退回。可退回条件:
* 1、满足中间无fork、join、subprocess模型
* 2、满足父节点模型如果为任务模型时,参与类型为any
* @param parent 父节点模型
* @return 是否可以退回
*/
public static boolean canRejected(NodeModel current, NodeModel parent) {
boolean result = false;
for(TransitionModel tm : current.getInputs()) {
NodeModel source = tm.getSource();
if(source == parent) {
return true;
}
if(source instanceof ForkModel
|| source instanceof JoinModel
//|| source instanceof SubProcessModel
|| source instanceof StartModel) {
continue;
}
result = result || canRejected(source, parent);
}
return result;
}
@Override
public String toString() {
return StrUtil.format("调用模型节点执行方法:model:{},name:{},displayName:{}", this.getClass().getSimpleName(), getName(),getDisplayName());
}
}
@@ -0,0 +1,156 @@
package com.budwk.app.flow.engine.model;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.budwk.app.flow.engine.CandidateHandler;
import com.budwk.app.flow.engine.core.ServiceContext;
import com.budwk.app.flow.entity.Candidate;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* 流程模型
* @author mldong
* @date 2023/4/25
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class ProcessModel extends BaseModel {
private String type; // 流程定义分类
private String category; // 流程定义分类
private String instanceUrl; // 启动实例要填写的表单key
private String h5InstanceUrl; // 启动实例要填写的手机端表单key
private String expireTime; // 期待完成时间变量key
private String instanceNoClass; // 实例编号生成器实现类
private String preInterceptors; // 节点前置拦截器
private String postInterceptors; // 节点后置拦截器
// 流程定义的所有节点
private List<NodeModel> nodes = new ArrayList<NodeModel>();
// 流程定义的所有任务节点
private List<TaskModel> tasks = new ArrayList<TaskModel>();
/**
* 获取开始节点
* @return
*/
public StartModel getStart() {
StartModel startModel = null;
for (int i = 0; i < nodes.size(); i++) {
NodeModel nodeModel = nodes.get(i);
if(nodeModel instanceof StartModel) {
startModel = (StartModel) nodeModel;
break;
}
}
return startModel;
}
/**
* 获取process定义的指定节点名称的节点模型
* @param nodeName 节点名称
* @return
*/
public NodeModel getNode(String nodeName) {
for(NodeModel node : nodes) {
if(node.getName().equals(nodeName)) {
return node;
}
}
return null;
}
/**
* 获取下一个任务节点模型集合
* @param nodeName
* @return
*/
public List<TaskModel> getNextTaskModels(String nodeName) {
List<TaskModel> res = new ArrayList<>();
NodeModel nodeModel = getNode(nodeName);
if(nodeModel == null) return res;
// 获取所有输出边的目标节点
List<NodeModel> nextNodeModelList = nodeModel.getOutputs().stream().map(item->{
return item.getTarget();
}).collect(Collectors.toList());
nextNodeModelList.forEach(item->{
if(item instanceof TaskModel) {
res.add((TaskModel) item);
}
});
if(res.isEmpty()) {
// 如果下一个节点不存在任务节点,递归往下找
nextNodeModelList.forEach(item->{
List<TaskModel> taskModelList = getNextTaskModels(item.getName());
res.addAll(taskModelList);
});
}
return res;
}
/**
* 获取下一个任务节点的候选人
* @param nodeName
* @return
*/
public List<Candidate> getNextTaskModelCandidates(String nodeName) {
List<Candidate> res = new ArrayList<>();
List<TaskModel> nextTaskModels = getNextTaskModels(nodeName);
nextTaskModels.forEach(item->{
res.addAll(getCandidates(item));
});
return res;
}
/**
* 根据任务模型获取候选人
* @param taskModel
* @return
*/
public List<Candidate> getCandidates(TaskModel taskModel) {
List<Candidate> res = new ArrayList<>();
// 从上下文中查找候选人处理人
List<CandidateHandler> handlerList = ServiceContext.findList(CandidateHandler.class);
handlerList.forEach(handler->{
// 通过候选从处理类获取候选人集合
List<Candidate> candidateList = handler.handle(taskModel);
if(candidateList!=null) {
res.addAll(candidateList);
}
});
// 通过候选人处理类获取修选人
String candidateHandler = taskModel.getCandidateHandler();
if(StrUtil.isNotEmpty(candidateHandler)) {
CandidateHandler candidateHandlerClass = ReflectUtil.newInstance(candidateHandler);
List<Candidate> candidateList = candidateHandlerClass.handle(taskModel);
if(candidateList!=null) {
res.addAll(candidateList);
}
}
// 去重
return res.stream().distinct().collect(Collectors.toList());
}
/**
* 根据指定的节点类型返回流程定义中所有模型对象
* @param clazz 节点类型
* @param <T> 泛型
* @return 节点列表
*/
public <T> List<T> getModels(Class<T> clazz) {
List<T> models = new ArrayList<T>();
buildModels(models, getStart().getNextModels(clazz), clazz);
return models;
}
private <T> void buildModels(List<T> models, List<T> nextModels, Class<T> clazz) {
for(T nextModel : nextModels) {
if(!models.contains(nextModel)) {
models.add(nextModel);
buildModels(models, ((NodeModel)nextModel).getNextModels(clazz), clazz);
}
}
}
}
@@ -0,0 +1,27 @@
package com.budwk.app.flow.engine.model;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.event.ProcessEvent;
import com.budwk.app.flow.engine.event.ProcessPublisher;
import com.budwk.app.flow.enums.ProcessEventTypeEnum;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
* 开始模型
* @author mldong
* @date 2023/4/25
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class StartModel extends NodeModel {
@Override
public void exec(Execution execution) {
// 执行开始节点自定义执行逻辑
System.out.println(super.toString());
// 发布流程实例开始事件
ProcessPublisher.notify(ProcessEvent.builder().eventType(ProcessEventTypeEnum.PROCESS_INSTANCE_START).sourceId(execution.getProcessInstanceId()).build());
runOutTransition(execution);
}
}
@@ -0,0 +1,21 @@
package com.budwk.app.flow.engine.model;
import com.budwk.app.flow.engine.core.Execution;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 子流程模型
* @author mldong
* @date 2023/12/7
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class SubProcessModel extends NodeModel{
private String form;
private Integer version;
@Override
void exec(Execution execution) {
runOutTransition(execution);
}
}
@@ -0,0 +1,58 @@
package com.budwk.app.flow.engine.model;
import cn.hutool.core.lang.Dict;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.handlers.impl.CountersignHandler;
import com.budwk.app.flow.enums.CountersignTypeEnum;
import com.budwk.app.flow.enums.ProcessTaskPerformTypeEnum;
import com.budwk.app.flow.enums.ProcessTaskTypeEnum;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class TaskModel extends NodeModel {
private String form; // 表单标识
private String assignee; // 参与人
private String assignmentHandler; // 参与人处理类
private ProcessTaskTypeEnum taskType; // 任务类型(主办/协办)
private ProcessTaskPerformTypeEnum performType; // 参与类型(普通参与/会签参与)
private String reminderTime; // 提醒时间
private String reminderRepeat; // 重复提醒间隔
private String expireTime; // 期待任务完成时间变量key
private String autoExecute; // 到期是否自动执行Y/N
private String callback; // 自动执行回调类
private Dict ext = Dict.create(); // 自定义扩展属性
// 候选用户标识
private String candidateUsers; // ext.getStr("candidateUsers");
// 候选用户组标识
private String candidateGroups; // ext.getStr("candidateGroups");
// 候选用户处理类字符串
private String candidateHandler; // ext.getStr("candidateHandler");
// 会签类型 PARALLEL表示并行会签,SEQUENTIAL表示串行会签
private CountersignTypeEnum countersignType;
// 会签完成条件
/**
* ● 全部完成:为空
* ● 按数量通过:#nrOfCompletedInstances==n,这里表示n人完成任务,会签结束。
* ● 按比例通过:#nrOfCompletedInstances/nrOfInstances==n,这里表示已完成会签数与总实例数达到一定比例时,会签结束
* ● 一票通过:#nrOfCompletedInstances==1,这里表示1人完成任务,会签结束。
* ● 一票否决:ONE_VOTE_VETO
*/
private String countersignCompletionCondition;
@Override
public void exec(Execution execution) {
// 执行任务节点自定义执行逻辑
System.out.println(super.toString());
if (ProcessTaskPerformTypeEnum.COUNTERSIGN.equals(performType)) {
// 会签任务处理
fire(new CountersignHandler(this), execution);
if (execution.isMerged()) {
runOutTransition(execution);
}
} else {
runOutTransition(execution);
}
}
}
@@ -0,0 +1,38 @@
package com.budwk.app.flow.engine.model;
import com.budwk.app.flow.engine.Action;
import com.budwk.app.flow.engine.core.Execution;
import com.budwk.app.flow.engine.handlers.impl.CreateTaskHandler;
import com.budwk.app.flow.engine.handlers.impl.StartSubProcessHandler;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
* 边模型
* @author mldong
* @date 2023/4/25
*/
@EqualsAndHashCode(callSuper = true, exclude = {"source", "target"})
@Data
public class TransitionModel extends BaseModel implements Action {
private NodeModel source; // 边源节点引用
private NodeModel target; // 边目标节点引用
private String to; // 目标节点名称
private String expr; // 边表达式
private String g; // 边点坐标集合(x1,y1;x2,y2,x3,y3……)开始、拐角、结束
private boolean enabled; // 是否可执行
@Override
public void execute(Execution execution) {
if(!enabled) return;
if(target instanceof TaskModel) {
// 创建阻塞任务
fire(new CreateTaskHandler((TaskModel) target),execution);
} else if(target instanceof SubProcessModel){
// 如果为子流程,则启动子流程
fire(new StartSubProcessHandler((SubProcessModel) target), execution);
} else {
target.execute(execution);
}
}
}
@@ -0,0 +1,25 @@
package com.budwk.app.flow.engine.model.logicflow;
import cn.hutool.core.lang.Dict;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
*
* logicFlow边
* @author mldong
* @date 2023/4/26
*/
@Data
public class LfEdge implements Serializable {
private String id; // 边唯一id
private String type; // 边类型
private String sourceNodeId; // 源节点id
private String targetNodeId; // 目标节点id
private Dict properties; // 边属性
private Dict text; // 边文本
private LfPoint startPoint; // 边开始点坐标
private LfPoint endPoint; // 边结束点坐标
private List<LfPoint> pointsList; // 边所有点集合
}
@@ -0,0 +1,23 @@
package com.budwk.app.flow.engine.model.logicflow;
import com.budwk.app.flow.engine.model.BaseModel;
import lombok.Data;
import java.util.List;
/**
*
* logicFlow模型
* @author mldong
* @date 2023/4/26
*/
@Data
public class LfModel extends BaseModel {
private String type; // 流程定义分类
private String expireTime;// 过期时间(常量或变量)
private String instanceUrl; // 启动实例的url,前后端分离后,定义为路由名或或路由地址
private String instanceNoClass; // 启动流程时,流程实例的流水号生成类
private String preInterceptors; // 节点前置拦截器
private String postInterceptors; // 节点后置拦截器
private List<LfNode> nodes; // 节点集合
private List<LfEdge> edges; // 边集合
}
@@ -0,0 +1,21 @@
package com.budwk.app.flow.engine.model.logicflow;
import cn.hutool.core.lang.Dict;
import lombok.Data;
import java.io.Serializable;
/**
*
* logicFlow节点
* @author mldong
* @date 2023/4/26
*/
@Data
public class LfNode implements Serializable {
private String id; // 节点唯一id
private String type; // 节点类型
private int x; // 节点中心点x轴坐标
private int y; // 节点中心点y轴坐标
Dict properties; // 节点属性
Dict text; // 节点文本
}
@@ -0,0 +1,16 @@
package com.budwk.app.flow.engine.model.logicflow;
import lombok.Data;
import java.io.Serializable;
/**
*
* logicFlow坐标
* @author mldong
* @date 2023/4/26
*/
@Data
public class LfPoint implements Serializable {
private int x; // x轴坐标
private int y; // y轴坐标
}
@@ -0,0 +1,106 @@
package com.budwk.app.flow.engine.parser;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.TransitionModel;
import com.budwk.app.flow.engine.model.logicflow.*;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* 通用属性解析(基本属性和边)
* @author mldong
* @date 2023/4/26
*/
public abstract class AbstractNodeParser implements NodeParser {
// 节点模型对象
protected NodeModel nodeModel;
@Override
public void parse(LfNode lfNode, List<LfEdge> edges) {
nodeModel = newModel();
// 解析基本信息
nodeModel.setName(lfNode.getId());
if(ObjectUtil.isNotNull(lfNode.getText())) {
nodeModel.setDisplayName(lfNode.getText().getStr(TEXT_VALUE_KEY));
}
Dict properties = lfNode.getProperties();
// 解析布局属性
int x = lfNode.getX();
int y = lfNode.getY();
int w = Convert.toInt(properties.get(WIDTH_KEY),0);
int h = Convert.toInt(properties.get(HEIGHT_KEY),0);
nodeModel.setLayout(StrUtil.format("{},{},{},{}",x,y,w,h));
// 解析拦截器
nodeModel.setPreInterceptors(properties.getStr(PRE_INTERCEPTORS_KEY));
nodeModel.setPostInterceptors(properties.getStr(POST_INTERCEPTORS_KEY));
// 解析输出边
List<LfEdge> nodeEdges = getEdgeBySourceNodeId(lfNode.getId(), edges);
nodeEdges.forEach(edge->{
TransitionModel transitionModel = new TransitionModel();
transitionModel.setName(edge.getId());
transitionModel.setTo(edge.getTargetNodeId());
transitionModel.setSource(nodeModel);
transitionModel.setExpr(edge.getProperties().getStr(EXPR_KEY));
if(CollectionUtil.isNotEmpty(edge.getPointsList())) {
// x1,y1;x2,y2;x3,y3……
transitionModel.setG(edge.getPointsList().stream().map(point->{
return point.getX()+","+point.getY();
}).collect(Collectors.joining(";")));
} else {
if(ObjectUtil.isNotNull(edge.getStartPoint()) && ObjectUtil.isNotNull(edge.getEndPoint())) {
int startPointX = edge.getStartPoint().getX();
int startPointY = edge.getStartPoint().getY();
int endPointX = edge.getEndPoint().getX();
int endPointY = edge.getEndPoint().getY();
transitionModel.setG(StrUtil.format("{},{};{},{}", startPointX, startPointY, endPointX, endPointY));
}
}
nodeModel.getOutputs().add(transitionModel);
});
// 调用子类特定解析方法
parseNode(lfNode);
}
/**
* 子类实现此类完成特定解析
* @param lfNode
*/
public abstract void parseNode(LfNode lfNode);
/**
* 由子类各自创建节点模型对象
* @return
*/
public abstract NodeModel newModel();
@Override
public NodeModel getModel() {
return nodeModel;
}
/**
* 获取节点输入
* @param targetNodeId 目标节点id
* @param edges
* @return
*/
private List<LfEdge> getEdgeByTargetNodeId(String targetNodeId,List<LfEdge> edges) {
return edges.stream().filter(edge->{
return edge.getTargetNodeId().equals(targetNodeId);
}).collect(Collectors.toList());
}
/**
* 获取节点输出
* @param sourceNodeId 源节点id
* @param edges
* @return
*/
private List<LfEdge> getEdgeBySourceNodeId(String sourceNodeId,List<LfEdge> edges) {
return edges.stream().filter(edge->{
return edge.getSourceNodeId().equals(sourceNodeId);
}).collect(Collectors.toList());
}
}
@@ -0,0 +1,112 @@
package com.budwk.app.flow.engine.parser;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.budwk.app.flow.engine.core.ServiceContext;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.ProcessModel;
import com.budwk.app.flow.engine.model.TaskModel;
import com.budwk.app.flow.engine.model.TransitionModel;
import com.budwk.app.flow.engine.model.logicflow.*;
import java.io.ByteArrayInputStream;
import java.util.List;
public class ModelParser {
private ModelParser(){}
// /**
// * 将json定义文件解析成流程模型对象
// * @param bytes
// * @return
// */
// public static ProcessModel parse(byte [] bytes) {
// String json = IoUtil.readUtf8(new ByteArrayInputStream(bytes));
// LfModel lfModel = JSONUtil.parse(json).toBean(LfModel.class);
// ProcessModel processModel = new ProcessModel();
// List<LfNode> nodes = lfModel.getNodes();
// List<LfEdge> edges = lfModel.getEdges();
// if(CollectionUtil.isEmpty(nodes) || CollectionUtil.isEmpty(edges) ) {
// return processModel;
// }
// // 流程定义基本信息
// processModel.setName(lfModel.getName());
// processModel.setDisplayName(lfModel.getDisplayName());
// processModel.setType(lfModel.getType());
// processModel.setInstanceUrl(lfModel.getInstanceUrl());
// processModel.setInstanceNoClass(lfModel.getInstanceNoClass());
// processModel.setPostInterceptors(lfModel.getPostInterceptors());
// processModel.setPreInterceptors(lfModel.getPreInterceptors());
// // 流程节点信息
// nodes.forEach(node->{
// String type = node.getType().replace(NodeParser.NODE_NAME_PREFIX,"");
// NodeParser nodeParser = ServiceContext.findByName(type,NodeParser.class);
// if(nodeParser!=null) {
// nodeParser.parse(node, edges);
// NodeModel nodeModel = nodeParser.getModel();
// processModel.getNodes().add(nodeParser.getModel());
// if (nodeModel instanceof TaskModel) {
// processModel.getTasks().add((TaskModel) nodeModel);
// }
// }
// });
// // 循环节点模型,构造输入边、输出边的source、target
// for(NodeModel node : processModel.getNodes()) {
// for(TransitionModel transition : node.getOutputs()) {
// String to = transition.getTo();
// for(NodeModel node2 : processModel.getNodes()) {
// if(to.equalsIgnoreCase(node2.getName())) {
// node2.getInputs().add(transition);
// transition.setTarget(node2);
// }
// }
// }
// }
// return processModel;
// }
public static ProcessModel parse(String json) {
LfModel lfModel = JSONUtil.parse(json).toBean(LfModel.class);
ProcessModel processModel = new ProcessModel();
List<LfNode> nodes = lfModel.getNodes();
List<LfEdge> edges = lfModel.getEdges();
if(CollectionUtil.isEmpty(nodes) || CollectionUtil.isEmpty(edges) ) {
return processModel;
}
// 流程定义基本信息
processModel.setName(lfModel.getName());
processModel.setDisplayName(lfModel.getDisplayName());
processModel.setType(lfModel.getType());
processModel.setInstanceUrl(lfModel.getInstanceUrl());
processModel.setInstanceNoClass(lfModel.getInstanceNoClass());
processModel.setPostInterceptors(lfModel.getPostInterceptors());
processModel.setPreInterceptors(lfModel.getPreInterceptors());
// 流程节点信息
nodes.forEach(node->{
String type = node.getType().replace(NodeParser.NODE_NAME_PREFIX,"");
NodeParser nodeParser = ServiceContext.findByName(type,NodeParser.class);
if(nodeParser!=null) {
nodeParser.parse(node, edges);
NodeModel nodeModel = nodeParser.getModel();
processModel.getNodes().add(nodeParser.getModel());
if (nodeModel instanceof TaskModel) {
processModel.getTasks().add((TaskModel) nodeModel);
}
}
});
// 循环节点模型,构造输入边、输出边的source、target
for(NodeModel node : processModel.getNodes()) {
for(TransitionModel transition : node.getOutputs()) {
String to = transition.getTo();
for(NodeModel node2 : processModel.getNodes()) {
if(to.equalsIgnoreCase(node2.getName())) {
node2.getInputs().add(transition);
transition.setTarget(node2);
}
}
}
}
return processModel;
}
}
@@ -0,0 +1,56 @@
package com.budwk.app.flow.engine.parser;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.logicflow.LfEdge;
import com.budwk.app.flow.engine.model.logicflow.LfNode;
import java.util.List;
/**
*
* 节点解析接口
* @author mldong
* @date 2023/4/26
*/
public interface NodeParser {
String NODE_NAME_PREFIX="snaker:"; // 节点名称前辍
String TEXT_VALUE_KEY = "value"; // 文本值
String WIDTH_KEY = "width"; // 节点宽度
String HEIGHT_KEY = "height"; // 节点高度
String PRE_INTERCEPTORS_KEY = "preInterceptors"; // 前置拦截器
String POST_INTERCEPTORS_KEY = "postInterceptors"; // 后置拦截器
String EXPR_KEY = "expr"; // 表达式key
String HANDLE_CLASS_KEY = "handleClass"; // 表达式处理类
String FORM_KEY = "form"; // 表单标识
String ASSIGNEE_KEY = "assignee"; // 参与人
String ASSIGNMENT_HANDLE_KEY = "assignmentHandler"; // 参与人处理类
String TASK_TYPE_KEY = "taskType"; // 任务类型(主办/协办)
String PERFORM_TYPE_KEY = "performType"; // 参与类型(普通参与/会签参与)
String REMINDER_TIME_KEY = "reminderTime"; // 提醒时间
String REMINDER_REPEAT_KEY = "reminderRepeat"; // 重复提醒间隔
String EXPIRE_TIME_KEY = "expireTime"; // 期待任务完成时间变量key
String AUTH_EXECUTE_KEY = "autoExecute"; // 到期是否自动执行Y/N
String CALLBACK_KEY = "callback"; // 自动执行回调类
String EXT_FIELD_KEY = "field"; // 自定义扩展属性
String EXT_FIELD_CANDIDATE_USERS_KET = "candidateUsers";
String EXT_FIELD_CANDIDATE_GROUPS_KEY = "candidateGroups";
String EXT_FIELD_CANDIDATE_HANDLER_KEY = "candidateHandler";
String EXT_FIELD_COUNTERSIGN_TYPE_KEY = "countersignType"; // 会签类型
String EXT_FIELD_COUNTERSIGN_COMPLETION_CONDITION_KEY = "countersignCompletionCondition"; // 会签完成条件
String CLASS_KEY = "clazz"; // 类路径
String METHOD_NAME_KEY = "methodName"; // 方法名
String ARGS_KEY = "args"; // 方法入参
String RETURN_VAL_KEY = "val"; // 返回变量名
String VERSION_KEY = "version"; // 版本号
/**
* 节点属性解析方法,由解析类完成解析
* @param lfNode LogicFlow节点对象
* @param edges 所有边对象
*/
void parse(LfNode lfNode, List<LfEdge> edges);
/**
* 解析完成后,提供返回NodeModel对象
* @return 节点模型
*/
NodeModel getModel();
}
@@ -0,0 +1,29 @@
package com.budwk.app.flow.engine.parser.impl;
import cn.hutool.core.lang.Dict;
import com.budwk.app.flow.constant.FlowConst;
import com.budwk.app.flow.engine.model.CustomModel;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.logicflow.LfNode;
import com.budwk.app.flow.engine.parser.AbstractNodeParser;
/**
* 自定义节点解析类
* @author mldong
* @date 2023/12/7
*/
public class CustomParser extends AbstractNodeParser {
@Override
public void parseNode(LfNode lfNode) {
CustomModel customModel = (CustomModel) nodeModel;
Dict properties = lfNode.getProperties();
customModel.setClazz(properties.getStr(CLASS_KEY));
customModel.setMethodName(properties.getStr(METHOD_NAME_KEY));
customModel.setArgs(properties.getStr(ARGS_KEY));
customModel.setVar(properties.get(RETURN_VAL_KEY, FlowConst.CUSTOM_RETURN_VAL));
}
@Override
public NodeModel newModel() {
return new CustomModel();
}
}
@@ -0,0 +1,33 @@
package com.budwk.app.flow.engine.parser.impl;
import cn.hutool.core.lang.Dict;
import com.budwk.app.flow.engine.model.DecisionModel;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.logicflow.LfNode;
import com.budwk.app.flow.engine.parser.AbstractNodeParser;
/**
*
* 决策节点解析类
* @author mldong
* @date 2023/4/26
*/
public class DecisionParser extends AbstractNodeParser {
/**
* 解析decision节点特有属性
* @param lfNode
*/
@Override
public void parseNode(LfNode lfNode) {
DecisionModel decisionModel = (DecisionModel) nodeModel;
Dict properties = lfNode.getProperties();
decisionModel.setExpr(properties.getStr(EXPR_KEY));
decisionModel.setHandleClass(properties.getStr(HANDLE_CLASS_KEY));
}
@Override
public NodeModel newModel() {
return new DecisionModel();
}
}
@@ -0,0 +1,25 @@
package com.budwk.app.flow.engine.parser.impl;
import com.budwk.app.flow.engine.model.EndModel;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.logicflow.LfNode;
import com.budwk.app.flow.engine.parser.AbstractNodeParser;
/**
*
* 结束节点解析类
* @author mldong
* @date 2023/4/26
*/
public class EndParser extends AbstractNodeParser {
@Override
public void parseNode(LfNode lfNode) {
}
@Override
public NodeModel newModel() {
return new EndModel();
}
}
@@ -0,0 +1,26 @@
package com.budwk.app.flow.engine.parser.impl;
import com.budwk.app.flow.engine.model.ForkModel;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.logicflow.LfNode;
import com.budwk.app.flow.engine.parser.AbstractNodeParser;
/**
*
* 分支节点解析类
* @author mldong
* @date 2023/4/26
*/
public class ForkParser extends AbstractNodeParser {
@Override
public void parseNode(LfNode lfNode) {
}
@Override
public NodeModel newModel() {
return new ForkModel();
}
}
@@ -0,0 +1,26 @@
package com.budwk.app.flow.engine.parser.impl;
import com.budwk.app.flow.engine.model.JoinModel;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.logicflow.LfNode;
import com.budwk.app.flow.engine.parser.AbstractNodeParser;
/**
*
* 合并节点解析器
* @author mldong
* @date 2023/4/26
*/
public class JoinParser extends AbstractNodeParser {
@Override
public void parseNode(LfNode lfNode) {
}
@Override
public NodeModel newModel() {
return new JoinModel();
}
}
@@ -0,0 +1,24 @@
package com.budwk.app.flow.engine.parser.impl;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.StartModel;
import com.budwk.app.flow.engine.model.logicflow.LfNode;
import com.budwk.app.flow.engine.parser.AbstractNodeParser;
/**
*
* 开始节点解析类
* @author mldong
* @date 2023/4/26
*/
public class StartParser extends AbstractNodeParser {
@Override
public void parseNode(LfNode lfNode) {
}
@Override
public NodeModel newModel() {
return new StartModel();
}
}
@@ -0,0 +1,75 @@
package com.budwk.app.flow.engine.parser.impl;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ReflectUtil;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.TaskModel;
import com.budwk.app.flow.engine.model.logicflow.*;
import com.budwk.app.flow.engine.parser.AbstractNodeParser;
import com.budwk.app.flow.enums.CountersignTypeEnum;
import com.budwk.app.flow.enums.ProcessTaskPerformTypeEnum;
import com.budwk.app.flow.enums.ProcessTaskTypeEnum;
/**
*
* 任务节点解析类
* @author mldong
* @date 2023/4/26
*/
public class TaskParser extends AbstractNodeParser {
/**
* 解析task节点特有属性
* @param lfNode
*/
@Override
public void parseNode(LfNode lfNode) {
TaskModel taskModel = (TaskModel)nodeModel;
Dict properties = lfNode.getProperties();
taskModel.setForm(properties.getStr(FORM_KEY));
taskModel.setAssignee(properties.getStr(ASSIGNEE_KEY));
taskModel.setAssignmentHandler(properties.getStr(ASSIGNMENT_HANDLE_KEY));
taskModel.setTaskType(ProcessTaskTypeEnum.codeOf(properties.get(TASK_TYPE_KEY)));
taskModel.setPerformType(ProcessTaskPerformTypeEnum.codeOf(properties.get(PERFORM_TYPE_KEY)));
taskModel.setReminderTime(properties.getStr(REMINDER_TIME_KEY));
taskModel.setReminderRepeat(properties.getStr(REMINDER_REPEAT_KEY));
taskModel.setExpireTime(properties.getStr(EXPIRE_TIME_KEY));
taskModel.setAutoExecute(properties.getStr(AUTH_EXECUTE_KEY));
taskModel.setCallback(properties.getStr(CALLBACK_KEY));
// 解析候选人属性
taskModel.setCandidateUsers(properties.getStr(EXT_FIELD_CANDIDATE_USERS_KET));
taskModel.setCandidateGroups(properties.getStr(EXT_FIELD_CANDIDATE_GROUPS_KEY));
taskModel.setCandidateHandler(properties.getStr(EXT_FIELD_CANDIDATE_HANDLER_KEY));
// 解析会签属性
taskModel.setCountersignType(CountersignTypeEnum.codeOf(properties.getStr(EXT_FIELD_COUNTERSIGN_TYPE_KEY)));
taskModel.setCountersignCompletionCondition(properties.getStr(EXT_FIELD_COUNTERSIGN_COMPLETION_CONDITION_KEY));
// 自定义扩展属性
Object field = properties.get(EXT_FIELD_KEY);
if(field!=null) {
Dict ext = Convert.convert(Dict.class, field);
taskModel.setExt(ext);
// 解析候选人属性
taskModel.setCandidateUsers(properties.get(EXT_FIELD_CANDIDATE_USERS_KET,ext.getStr(EXT_FIELD_CANDIDATE_USERS_KET)));
taskModel.setCandidateGroups(properties.get(EXT_FIELD_CANDIDATE_GROUPS_KEY,ext.getStr(EXT_FIELD_CANDIDATE_GROUPS_KEY)));
taskModel.setCandidateHandler(properties.get(EXT_FIELD_CANDIDATE_HANDLER_KEY,ext.getStr(EXT_FIELD_CANDIDATE_HANDLER_KEY)));
// 解析会签属性
taskModel.setCountersignType(CountersignTypeEnum.codeOf(properties.get(EXT_FIELD_COUNTERSIGN_TYPE_KEY,ext.getStr(EXT_FIELD_COUNTERSIGN_TYPE_KEY))));
taskModel.setCountersignCompletionCondition(properties.get(EXT_FIELD_COUNTERSIGN_COMPLETION_CONDITION_KEY,ext.getStr(EXT_FIELD_COUNTERSIGN_COMPLETION_CONDITION_KEY)));
} else {
taskModel.setExt(Dict.create());
}
// 将其他properties添加到ext中
properties.forEach((k,v)->{
if(!ReflectUtil.hasField(TaskModel.class,k)){
taskModel.getExt().set(k,v);
}
});
}
@Override
public NodeModel newModel() {
return new TaskModel();
}
}
@@ -0,0 +1,28 @@
package com.budwk.app.flow.engine.parser.impl;
import cn.hutool.core.lang.Dict;
import com.budwk.app.flow.engine.model.NodeModel;
import com.budwk.app.flow.engine.model.SubProcessModel;
import com.budwk.app.flow.engine.model.logicflow.LfNode;
import com.budwk.app.flow.engine.parser.AbstractNodeParser;
/**
* 子流程解析类
* @author mldong
* @date 2023/12/7
*/
public class WfSubProcessParser extends AbstractNodeParser {
@Override
public void parseNode(LfNode lfNode) {
SubProcessModel subProcessModel = (SubProcessModel) nodeModel;
Dict properties = lfNode.getProperties();
subProcessModel.setForm(properties.getStr(FORM_KEY));
subProcessModel.setVersion(properties.getInt(VERSION_KEY));
}
@Override
public NodeModel newModel() {
return new SubProcessModel();
}
}
@@ -0,0 +1,24 @@
package com.budwk.app.flow.engine.scheduling;
import cn.hutool.core.lang.Dict;
/**
* 任务调度接口,增加、删除任务
* @author mldong
* @date 2023/12/4
*/
public interface IScheduler {
String SOURCE_ID_KEY = "sourceId";
String SOURCE_TYPE_KEY = "sourceType";
/**
* 添加作业到调度器
* @param args
*/
void addJob(String jobId,Dict args);
/**
* 从调度器中删除作业
* @param jobId
*/
void removeJob(String jobId);
}
@@ -0,0 +1,44 @@
package com.budwk.app.flow.engine.scheduling;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import com.budwk.app.flow.engine.core.ServiceContext;
import com.budwk.app.flow.engine.event.ProcessEvent;
import com.budwk.app.flow.engine.event.ProcessEventListener;
import com.budwk.app.flow.enums.ProcessEventTypeEnum;
import org.nutz.ioc.loader.annotation.IocBean;
import java.util.List;
/**
* @author mldong
* @date 2023/12/5
*/
@IocBean
public class SchedulerProcessEventListener implements ProcessEventListener {
@Override
public void onEvent(ProcessEvent event) {
List<IScheduler> schedulerList = ServiceContext.findList(IScheduler.class);
if(CollectionUtil.newArrayList(
ProcessEventTypeEnum.PROCESS_INSTANCE_START,
ProcessEventTypeEnum.PROCESS_TASK_START
).contains(event.getEventType())) {
// 流程实例开始事件、流程任务开始事件,添加作业到调度器
schedulerList.forEach(scheduler->{
scheduler.addJob(event.getEventType().name()+"_"+event.getSourceId(),
Dict.of(
IScheduler.SOURCE_ID_KEY,event.getSourceId(),
IScheduler.SOURCE_TYPE_KEY,event.getEventType().getCode()
));
});
} else if(CollectionUtil.newArrayList(
ProcessEventTypeEnum.PROCESS_INSTANCE_END,
ProcessEventTypeEnum.PROCESS_TASK_END
).contains(event.getEventType())) {
// 流程实例结束事件、流程任务结束事件,从调度器移除作业
schedulerList.forEach(scheduler->{
scheduler.removeJob(event.getEventType().name()+"_"+event.getSourceId());
});
}
}
}
@@ -0,0 +1,137 @@
package com.budwk.app.flow.engine.util;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.expression.ExpressionUtil;
import cn.hutool.json.JSONUtil;
import com.budwk.app.flow.constant.FlowConst;
import com.budwk.app.flow.engine.core.ServiceContext;
import com.budwk.app.flow.engine.model.ProcessModel;
import com.budwk.app.flow.engine.model.TaskModel;
import com.budwk.app.sys.views.View_user;
import org.dromara.warm.flow.core.exception.FlowException;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* 流程工具
*
* @author mldong
* @date 2023/10/7
*/
public class FlowUtil {
private FlowUtil() {
}
/**
* 追加用户信息到变量中
*
* @param operator
* @param args
*/
public static void addUserInfoToArgs(String operator, Dict args) {
Dao dao = ServiceContext.find(Dao.class);
View_user user = dao.fetch(View_user.class, Cnd.where(View_user::getId, "=", operator));
if (user == null) {
throw new FlowException("用户不存在:" + operator);
}
args.put(FlowConst.USER_USER_ID, operator);
args.put(FlowConst.INITIATOR, operator);
args.put(FlowConst.INITIATOR_NAME, user.getUsername());
args.put(FlowConst.INITIATOR_ACCOUNT, user.getLoginname());
args.put(FlowConst.INITIATOR_UNIT_ID, user.getUnitId());
args.put(FlowConst.INITIATOR_UNIT_NAME, user.getUnitName());
args.put(FlowConst.INITIATOR_UNIT_UNION_ID, user.getUnionId());
args.put(FlowConst.INITIATOR_UNIT_UNION_NAME, user.getUnionName());
}
/**
* 增加自动构造标题
*
* @param args
*/
public static void addAutoGenTitle(String processDefineDisplayName, Dict args) {
// 申请人的xx流程-日期
// String format = "{}的{}-{}";
// args.put(FlowConst.AUTO_GEN_TITLE, StrUtil.format(format, args.getStr(FlowConst.USER_REAL_NAME), processDefineDisplayName,
// DateUtil.format(new Date(), "yyyy-MM-dd HH:mm")));
args.put(FlowConst.PROCESS_INSTANCE_NAME, args.getStr(FlowConst.INITIATOR_NAME) + "" + processDefineDisplayName + "申请");
}
/**
* 参数转字典
*
* @param variable
* @return
*/
public static Dict variableToDict(String variable) {
if (JSONUtil.isTypeJSON(variable)) {
return Dict.parse(JSONUtil.parseObj(variable));
}
return Dict.create();
}
/**
* 判断是否为第一个任务节点
*
* @param processModel
* @param taskName
* @return
*/
public static boolean isFistTaskName(ProcessModel processModel, String taskName) {
AtomicBoolean atomicBoolean = new AtomicBoolean(false);
processModel.getStart().getOutputs().forEach(nodeModel -> {
if (nodeModel.getTo().equalsIgnoreCase(taskName)) {
atomicBoolean.set(true);
}
});
return atomicBoolean.get();
}
/**
* 解析日期
*
* @param expireTime
* @param args
* @return
*/
public static Date processTime(String expireTime, Dict args) {
// 如果变量中存在,则使用变量中的时间
if (args.containsKey(expireTime)) {
Object obj = args.get(expireTime);
if (obj instanceof Date) {
return Convert.toDate(obj);
} else if (obj instanceof Long) {
return new Date(Convert.toLong(obj));
} else if (obj instanceof String) {
return DateUtil.parseDateTime(Convert.toStr(obj));
}
}
if (StrUtil.isNotBlank(expireTime)) {
if (expireTime.contains("s")) {
return DateUtil.offsetSecond(new Date(), Convert.toInt(expireTime.substring(0, expireTime.length() - 1)));
} else if (expireTime.contains("m")) {
return DateUtil.offsetMinute(new Date(), Convert.toInt(expireTime.substring(0, expireTime.length() - 1)));
} else if (expireTime.contains("h")) {
return DateUtil.offsetHour(new Date(), Convert.toInt(expireTime.substring(0, expireTime.length() - 1)));
} else if (expireTime.contains("d")) {
return DateUtil.offsetDay(new Date(), Convert.toInt(expireTime.substring(0, expireTime.length() - 1)));
}
return DateUtil.parseDateTime(expireTime);
}
return null;
}
}