Commit 7d497ce09b2d9e42447ceac5c2c020cac4c894e0

Authored by kehaiyou
1 parent f088fdff

feat: 【工作流】--加签

yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/enums/SymbolConstant.java 0 → 100644
  1 +package cn.iocoder.yudao.framework.common.enums;
  2 +
  3 +/**
  4 + * 符号常量
  5 + */
  6 +public interface SymbolConstant {
  7 +
  8 + String D =",";
  9 +
  10 + /**
  11 + * _
  12 + */
  13 + String XH="_";
  14 + /**
  15 + * -
  16 + */
  17 + String HG="-";
  18 +
  19 + /**
  20 + * /
  21 + */
  22 + String XG="/";
  23 +
  24 + /**
  25 + * 箭头
  26 + */
  27 + String ARROWHEAD="->";
  28 +
  29 + /**
  30 + * 数组的开始元素
  31 + */
  32 + String ARRAY_START="[";
  33 +
  34 + /**
  35 + * 数组的结束元素
  36 + */
  37 + String ARRAY_END="]";
  38 +
  39 + /**
  40 + * null 字符串
  41 + */
  42 + String NULL_STRING="null";
  43 +
  44 + /**
  45 + * 点号
  46 + */
  47 + String DIAN="\\.";
  48 +}
... ...
yudao-module-bpm/yudao-module-bpm-api/src/main/java/cn/iocoder/yudao/module/bpm/enums/ErrorCodeConstants.java
... ... @@ -50,7 +50,9 @@ public interface ErrorCodeConstants {
50 50 ErrorCode TASK_RETURN_FAIL_SOURCE_TARGET_ERROR = new ErrorCode(1_009_005_006, "回退任务失败,目标节点是在并行网关上或非同一路线上,不可跳转");
51 51 ErrorCode TASK_DELEGATE_FAIL_USER_REPEAT = new ErrorCode(1_009_005_007, "任务委派失败,委派人和当前审批人为同一人");
52 52 ErrorCode TASK_DELEGATE_FAIL_USER_NOT_EXISTS = new ErrorCode(1_009_005_008, "任务委派失败,被委派人不存在");
53   -
  53 + ErrorCode TASK_ADD_SIGN_USER_NOT_EXIST = new ErrorCode(1_009_005_009, "任务加签:选择的用户不存在");
  54 + ErrorCode TASK_ADD_SIGN_TYPE_ERROR = new ErrorCode(1_009_005_010, "任务加签:当前任务已经{},不能{}");
  55 + ErrorCode TASK_ADD_SIGN_USER_REPEAT = new ErrorCode(1_009_005_011, "任务加签失败,加签人与现有审批人[{}]重复");
54 56 // ========== 流程任务分配规则 1-009-006-000 ==========
55 57 ErrorCode TASK_ASSIGN_RULE_EXISTS = new ErrorCode(1_009_006_000, "流程({}) 的任务({}) 已经存在分配规则");
56 58 ErrorCode TASK_ASSIGN_RULE_NOT_EXISTS = new ErrorCode(1_009_006_001, "流程任务分配规则不存在");
... ...
yudao-module-bpm/yudao-module-bpm-api/src/main/java/cn/iocoder/yudao/module/bpm/enums/task/BpmCommentTypeEnum.java 0 → 100644
  1 +package cn.iocoder.yudao.module.bpm.enums.task;
  2 +
  3 +import lombok.AllArgsConstructor;
  4 +import lombok.Getter;
  5 +
  6 +/**
  7 + * 流程任务 -- comment类型枚举
  8 + */
  9 +@Getter
  10 +@AllArgsConstructor
  11 +public enum BpmCommentTypeEnum {
  12 +
  13 + APPROVE(1, "通过"),
  14 + REJECT(2, "不通过"),
  15 + CANCEL(3, "已取消"),
  16 +
  17 + // ========== 流程任务独有的状态 ==========
  18 +
  19 + BACK(4, "退回"), // 退回
  20 + DELEGATE(5, "委派"),
  21 + ADD_SIGN(6, "加签"),
  22 + SUB_SIGN(7,"减签"),
  23 + ;
  24 +
  25 + /**
  26 + * 结果
  27 + */
  28 + private final Integer result;
  29 + /**
  30 + * 描述
  31 + */
  32 + private final String desc;
  33 +}
... ...
yudao-module-bpm/yudao-module-bpm-api/src/main/java/cn/iocoder/yudao/module/bpm/enums/task/BpmProcessInstanceResultEnum.java
... ... @@ -21,11 +21,26 @@ public enum BpmProcessInstanceResultEnum {
21 21 // ========== 流程任务独有的状态 ==========
22 22  
23 23 BACK(5, "驳回"), // 退回
24   - DELEGATE(6, "委派");
  24 + DELEGATE(6, "委派"),
  25 + /**
  26 + * 源任务已经审批完成,但是它使用了后加签,后加签的任务未完成,源任务就会是这个状态
  27 + * 例如:A审批, A 后加签了 B ,并且审批通过了任务,但是 B 还未审批,则当前任务状态为 待后加签任务完成
  28 + */
  29 + ADD_SIGN_AFTER(7, "待后加签任务完成"),
  30 + /**
  31 + * 源任务未审批,但是向前加签了,所以源任务状态变为 待前加签任务完成
  32 + * 例如:A审批, A 前加签了 B ,B 还未审核
  33 + */
  34 + ADD_SIGN_BEFORE(8, "待前加签任务完成"),
  35 + /**
  36 + * 后加签任务被创建时的初始状态
  37 + * 因为需要源任务先完成,才能到后加签的人来审批,所以加了一个状态区分
  38 + */
  39 + WAIT_BEFORE_TASK(9, "待前置任务完成");
25 40  
26 41 /**
27 42 * 结果
28   - *
  43 + * <p>
29 44 * 如果新增时,注意 {@link #isEndResult(Integer)} 是否需要变更
30 45 */
31 46 private final Integer result;
... ... @@ -36,14 +51,16 @@ public enum BpmProcessInstanceResultEnum {
36 51  
37 52 /**
38 53 * 判断该结果是否已经处于 End 最终结果
39   - *
  54 + * <p>
40 55 * 主要用于一些结果更新的逻辑,如果已经是最终结果,就不再进行更新
41 56 *
42 57 * @param result 结果
43 58 * @return 是否
44 59 */
45 60 public static boolean isEndResult(Integer result) {
46   - return ObjectUtils.equalsAny(result, APPROVE.getResult(), REJECT.getResult(), CANCEL.getResult(), BACK.getResult());
  61 + return ObjectUtils.equalsAny(result, APPROVE.getResult(), REJECT.getResult(),
  62 + CANCEL.getResult(), BACK.getResult(),
  63 + ADD_SIGN_AFTER.getResult());
47 64 }
48 65  
49 66 }
... ...
yudao-module-bpm/yudao-module-bpm-api/src/main/java/cn/iocoder/yudao/module/bpm/enums/task/BpmTaskAddSignTypeEnum.java 0 → 100644
  1 +package cn.iocoder.yudao.module.bpm.enums.task;
  2 +
  3 +import lombok.AllArgsConstructor;
  4 +import lombok.Getter;
  5 +
  6 +
  7 +/**
  8 + * 流程任务 -- 加签类型枚举类型
  9 + */
  10 +@Getter
  11 +@AllArgsConstructor
  12 +public enum BpmTaskAddSignTypeEnum {
  13 +
  14 + /**
  15 + * 向前加签,需要前置任务审批完成,才回到原审批人
  16 + */
  17 + BEFORE("before", "向前加签"),
  18 + /**
  19 + * 向后加签,需要后置任务全部审批完,才会通过原审批人节点
  20 + */
  21 + AFTER("after", "向后加签"),
  22 + /**
  23 + * 创建后置加签时的过度状态,用于控制向后加签生成的任务状态
  24 + */
  25 + AFTER_CHILDREN_TASK("afterChildrenTask", "向后加签生成的子任务");
  26 +
  27 + private final String type;
  28 +
  29 + private final String desc;
  30 +
  31 + public static String formatDesc(String type) {
  32 + for (BpmTaskAddSignTypeEnum value : values()) {
  33 + if (value.type.equals(type)) {
  34 + return value.desc;
  35 + }
  36 + }
  37 + return null;
  38 + }
  39 +}
  40 +
0 41 \ No newline at end of file
... ...
yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/controller/admin/task/BpmTaskController.java
... ... @@ -100,4 +100,11 @@ public class BpmTaskController {
100 100 return success(true);
101 101 }
102 102  
  103 + @PutMapping("/add-sign")
  104 + @Operation(summary = "加签", description = "before, after为前加签后加签")
  105 + @PreAuthorize("@ss.hasPermission('bpm:task:add-sign')")
  106 + public CommonResult<Boolean> addSign(@RequestBody @Valid BpmTaskAddSignReqVO reqVO) {
  107 + taskService.addSign(reqVO,getLoginUserId());
  108 + return success(true);
  109 + }
103 110 }
... ...
yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/controller/admin/task/vo/task/BpmTaskAddSignReqVO.java 0 → 100644
  1 +package cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task;
  2 +
  3 +import io.swagger.v3.oas.annotations.media.Schema;
  4 +import lombok.Data;
  5 +
  6 +import javax.validation.constraints.NotEmpty;
  7 +import java.util.List;
  8 +import java.util.Set;
  9 +
  10 +@Schema(description = "管理后台 - 加签流程任务的 Request VO")
  11 +@Data
  12 +public class BpmTaskAddSignReqVO {
  13 +
  14 + @Schema(description = "加签的用户 ID")
  15 + @NotEmpty(message = "加签用户ID不能为空")
  16 + private Set<Long> userIdList;
  17 +
  18 + @Schema(description = "加签类型,before 向前加签,after 向后加签")
  19 + @NotEmpty(message = "加签类型不能为空")
  20 + private String type;
  21 +
  22 + @Schema(description = "加签原因")
  23 + @NotEmpty(message = "加签原因不能为空")
  24 + private String reason;
  25 +
  26 + @Schema(description = "需要加签的任务 ID")
  27 + @NotEmpty(message = "任务编号不能为空")
  28 + private String id;
  29 +}
0 30 \ No newline at end of file
... ...
yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/convert/task/BpmTaskConvert.java
... ... @@ -18,9 +18,11 @@ import org.flowable.engine.history.HistoricProcessInstance;
18 18 import org.flowable.engine.runtime.ProcessInstance;
19 19 import org.flowable.task.api.Task;
20 20 import org.flowable.task.api.history.HistoricTaskInstance;
  21 +import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
21 22 import org.mapstruct.*;
22 23 import org.mapstruct.factory.Mappers;
23 24  
  25 +import java.util.Date;
24 26 import java.util.List;
25 27 import java.util.Map;
26 28  
... ... @@ -145,4 +147,19 @@ public interface BpmTaskConvert {
145 147 .setName(element.getName())
146 148 .setDefinitionKey(element.getId()));
147 149 }
  150 +
  151 + default TaskEntityImpl convert(TaskEntityImpl task,TaskEntityImpl parentTask){
  152 + task.setCategory(parentTask.getCategory());
  153 + task.setDescription(parentTask.getDescription());
  154 + task.setTenantId(parentTask.getTenantId());
  155 + task.setName(parentTask.getName());
  156 + task.setParentTaskId(parentTask.getId());
  157 + task.setProcessDefinitionId(parentTask.getProcessDefinitionId());
  158 + task.setProcessInstanceId(parentTask.getProcessInstanceId());
  159 + task.setTaskDefinitionKey(parentTask.getTaskDefinitionKey());
  160 + task.setTaskDefinitionId(parentTask.getTaskDefinitionId());
  161 + task.setPriority(parentTask.getPriority());
  162 + task.setCreateTime(new Date());
  163 + return task;
  164 + }
148 165 }
... ...
yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/dal/mysql/task/BpmTaskExtMapper.java
... ... @@ -23,4 +23,7 @@ public interface BpmTaskExtMapper extends BaseMapperX&lt;BpmTaskExtDO&gt; {
23 23 return selectOne(BpmTaskExtDO::getTaskId, taskId);
24 24 }
25 25  
  26 + default void updateBatchByTaskIdList(List<String> taskIdList, BpmTaskExtDO entity){
  27 + update(entity,new LambdaQueryWrapper<BpmTaskExtDO>().in(BpmTaskExtDO::getTaskId, taskIdList));
  28 + }
26 29 }
... ...
yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/task/BpmTaskService.java
... ... @@ -3,6 +3,7 @@ package cn.iocoder.yudao.module.bpm.service.task;
3 3 import cn.iocoder.yudao.framework.common.pojo.PageResult;
4 4 import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
5 5 import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.*;
  6 +import cn.iocoder.yudao.module.bpm.dal.dataobject.task.BpmTaskExtDO;
6 7 import org.flowable.task.api.Task;
7 8  
8 9 import javax.validation.Valid;
... ... @@ -62,6 +63,14 @@ public interface BpmTaskService {
62 63 */
63 64 List<BpmTaskRespVO> getTaskListByProcessInstanceId(String processInstanceId);
64 65  
  66 +
  67 + /**
  68 + * 通过任务 ID 集合,获取任务扩展表信息集合
  69 + * @param taskIdList 任务 ID
  70 + * @return 任务列表
  71 + */
  72 + List<BpmTaskExtDO> getTaskListByTaskIdList(List<String> taskIdList);
  73 +
65 74 /**
66 75 * 通过任务
67 76 *
... ... @@ -147,4 +156,11 @@ public interface BpmTaskService {
147 156 */
148 157 void delegateTask(BpmTaskDelegateReqVO reqVO, Long userId);
149 158  
  159 + /**
  160 + * 任务加签
  161 + * @param reqVO 被加签的用户和任务ID,加签类型
  162 + * @param userId 当前用户 ID
  163 + */
  164 + void addSign(BpmTaskAddSignReqVO reqVO, Long userId);
  165 +
150 166 }
... ...
yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/task/BpmTaskServiceImpl.java
... ... @@ -2,7 +2,9 @@ package cn.iocoder.yudao.module.bpm.service.task;
2 2  
3 3 import cn.hutool.core.collection.CollUtil;
4 4 import cn.hutool.core.util.ArrayUtil;
  5 +import cn.hutool.core.util.IdUtil;
5 6 import cn.hutool.core.util.StrUtil;
  7 +import cn.iocoder.yudao.framework.common.enums.SymbolConstant;
6 8 import cn.iocoder.yudao.framework.common.pojo.PageResult;
7 9 import cn.iocoder.yudao.framework.common.util.date.DateUtils;
8 10 import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
... ... @@ -13,8 +15,7 @@ import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.*;
13 15 import cn.iocoder.yudao.module.bpm.convert.task.BpmTaskConvert;
14 16 import cn.iocoder.yudao.module.bpm.dal.dataobject.task.BpmTaskExtDO;
15 17 import cn.iocoder.yudao.module.bpm.dal.mysql.task.BpmTaskExtMapper;
16   -import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceDeleteReasonEnum;
17   -import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceResultEnum;
  18 +import cn.iocoder.yudao.module.bpm.enums.task.*;
18 19 import cn.iocoder.yudao.module.bpm.service.definition.BpmModelService;
19 20 import cn.iocoder.yudao.module.bpm.service.message.BpmMessageService;
20 21 import cn.iocoder.yudao.module.system.api.dept.DeptApi;
... ... @@ -26,6 +27,7 @@ import org.flowable.bpmn.model.BpmnModel;
26 27 import org.flowable.bpmn.model.FlowElement;
27 28 import org.flowable.bpmn.model.UserTask;
28 29 import org.flowable.engine.HistoryService;
  30 +import org.flowable.engine.ManagementService;
29 31 import org.flowable.engine.RuntimeService;
30 32 import org.flowable.engine.TaskService;
31 33 import org.flowable.engine.history.HistoricProcessInstance;
... ... @@ -35,6 +37,8 @@ import org.flowable.task.api.Task;
35 37 import org.flowable.task.api.TaskQuery;
36 38 import org.flowable.task.api.history.HistoricTaskInstance;
37 39 import org.flowable.task.api.history.HistoricTaskInstanceQuery;
  40 +import org.flowable.task.service.impl.persistence.entity.TaskEntity;
  41 +import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
38 42 import org.springframework.stereotype.Service;
39 43 import org.springframework.transaction.annotation.Transactional;
40 44 import org.springframework.transaction.support.TransactionSynchronization;
... ... @@ -82,6 +86,9 @@ public class BpmTaskServiceImpl implements BpmTaskService {
82 86 @Resource
83 87 private BpmTaskExtMapper taskExtMapper;
84 88  
  89 + @Resource
  90 + private ManagementService managementService;
  91 +
85 92 @Override
86 93 public PageResult<BpmTaskTodoPageItemRespVO> getTodoTaskPage(Long userId, BpmTaskTodoPageReqVO pageVO) {
87 94 // 查询待办任务
... ... @@ -187,6 +194,11 @@ public class BpmTaskServiceImpl implements BpmTaskService {
187 194 }
188 195  
189 196 @Override
  197 + public List<BpmTaskExtDO> getTaskListByTaskIdList(List<String> taskIdList) {
  198 + return taskExtMapper.selectListByTaskIds(taskIdList);
  199 + }
  200 +
  201 + @Override
190 202 @Transactional(rollbackFor = Exception.class)
191 203 public void approveTask(Long userId, @Valid BpmTaskApproveReqVO reqVO) {
192 204 // 1.1 校验任务存在
... ... @@ -202,14 +214,151 @@ public class BpmTaskServiceImpl implements BpmTaskService {
202 214 approveDelegateTask(reqVO, task);
203 215 return;
204 216 }
205   -
206   - // 情况二:自己审批的任务,调用 complete 去完成任务
  217 + // 情况二:后加签的任务
  218 + if(BpmTaskAddSignTypeEnum.AFTER.getType().equals(task.getScopeType())) {
  219 + //后加签处理
  220 + handleAfterSignTask(task, reqVO);
  221 + return;
  222 + }
  223 + // 情况三:自己审批的任务,调用 complete 去完成任务
207 224 // 完成任务,审批通过
208 225 taskService.complete(task.getId(), instance.getProcessVariables());
209 226 // 更新任务拓展表为通过
210 227 taskExtMapper.updateByTaskId(
211 228 new BpmTaskExtDO().setTaskId(task.getId()).setResult(BpmProcessInstanceResultEnum.APPROVE.getResult())
212 229 .setReason(reqVO.getReason()));
  230 + //处理加签任务
  231 + this.approveTask0(task);
  232 + }
  233 +
  234 + /**
  235 + * 当前任务存在后加签任务,则不能马上完成,需要一个中间状态,并激活剩余所有子任务
  236 + * @param task 当前任务
  237 + * @param reqVO 前端请求参数
  238 + */
  239 + private void handleAfterSignTask(Task task,BpmTaskApproveReqVO reqVO){
  240 + //1.有向后加签,则该任务状态临时设置为 等待后加签任务完成 状态
  241 + taskExtMapper.updateByTaskId(
  242 + new BpmTaskExtDO().setTaskId(task.getId()).setResult(BpmProcessInstanceResultEnum.ADD_SIGN_AFTER.getResult())
  243 + .setReason(reqVO.getReason()).setEndTime(LocalDateTime.now()));
  244 + //2. 激活子任务
  245 + List<String> childrenTaskIdList = getChildrenTaskIdList(task.getId());
  246 + for (String childrenTaskId : childrenTaskIdList) {
  247 + taskService.resolveTask(childrenTaskId);
  248 + }
  249 + //更新任务扩展表中子任务为进行中
  250 + taskExtMapper.updateBatchByTaskIdList(childrenTaskIdList,
  251 + new BpmTaskExtDO().setResult(BpmProcessInstanceResultEnum.PROCESS.getResult()));
  252 + }
  253 +
  254 +
  255 + /**
  256 + * 处理当前任务的父任务
  257 + *
  258 + * @param task 当前任务
  259 + */
  260 + private void approveTask0(Task task) {
  261 + String parentTaskId = task.getParentTaskId();
  262 + if (StrUtil.isNotBlank(parentTaskId)) {
  263 + //1. 判断当前任务的父任务是否还有子任务
  264 + long subTaskCount = getSubTaskCount(parentTaskId);
  265 + if (subTaskCount == 0) {
  266 + //2. 获取父任务
  267 + Task parentTask = getTask(parentTaskId);
  268 + String scopeType = parentTask.getScopeType();
  269 + //3. 处理向前加签
  270 + if (BpmTaskAddSignTypeEnum.BEFORE.getType().equals(scopeType)) {
  271 + //3.1 如果是向前加签的任务,则调用 resolveTask 指派父任务,将 owner 重新赋值给父任务的 assignee
  272 + taskService.resolveTask(parentTaskId);
  273 + //3.2 更新任务拓展表为处理中
  274 + taskExtMapper.updateByTaskId(
  275 + new BpmTaskExtDO().setTaskId(parentTask.getId()).setResult(BpmProcessInstanceResultEnum.PROCESS.getResult()));
  276 + }
  277 + //4. 处理向后加签
  278 + if (BpmTaskAddSignTypeEnum.AFTER.getType().equals(scopeType)) {
  279 + handleAfterSign(parentTask, parentTaskId);
  280 + }
  281 + //5. 子任务已处理完成,清空 scopeType 字段,修改 parentTask 信息,方便后续可以继续向前后向后加签
  282 + // 再查询一次的原因是避免报错:Task was updated by another transaction concurrently
  283 + // 因为前面处理后可能会导致 parentTask rev 字段被修改,需要重新获取最新的
  284 + parentTask = getTask(parentTaskId);
  285 + if(parentTask !=null){
  286 + //为空的情况是:已经通过 handleAfterSign 方法将任务完成了,所以 ru_task 表会查不到数据
  287 + clearTaskScopeTypeAndSave(parentTask);
  288 + }
  289 +
  290 + }
  291 + }
  292 + }
  293 +
  294 + /**
  295 + * 处理后加签任务
  296 + *
  297 + * @param parentTask 当前审批任务的父任务
  298 + * @param parentTaskId 当前审批任务的父ID
  299 + */
  300 + private void handleAfterSign(Task parentTask, String parentTaskId) {
  301 + //4.1 更新 parentTask 的任务拓展表为通过
  302 + BpmTaskExtDO currentTaskExt = taskExtMapper.selectByTaskId(parentTask.getId());
  303 + BpmTaskExtDO currentTaskUpdateEntity = new BpmTaskExtDO().setTaskId(parentTask.getId())
  304 + .setResult(BpmProcessInstanceResultEnum.APPROVE.getResult());
  305 + if (currentTaskExt.getEndTime() == null) {
  306 + //有这个判断是因为
  307 + //4.2 以前没设置过结束时间,才去设置
  308 + currentTaskUpdateEntity.setEndTime(LocalDateTime.now());
  309 + }
  310 + taskExtMapper.updateByTaskId(currentTaskUpdateEntity);
  311 + //5. 继续往上处理,父任务继续往上查询
  312 + if (StrUtil.isEmpty(parentTask.getParentTaskId())) {
  313 + //5.1 该父任务为最顶级的祖先任务(没有父级ID), 则直接完成父任务流转到下一步
  314 + taskService.complete(parentTaskId);
  315 + } else {
  316 + //5.2 如果有父级,递归查询上级任务是否都已经完成
  317 + //判断整条链路的任务是否完成
  318 + //例如从 A 任务加签了一个 B 任务, B 任务又加签了一个 C 任务,C任务加签了 D 任务
  319 + //此时,D 任务完成,要一直往上找到祖先任务 A ,调用 complete 方法完成 A 任务
  320 + boolean allChildrenTaskFinish = true;
  321 + while (StrUtil.isNotBlank(parentTask.getParentTaskId())) {
  322 + parentTask = getTask(parentTask.getParentTaskId());
  323 + BpmTaskExtDO bpmTaskExtDO = taskExtMapper.selectByTaskId(parentTask.getId());
  324 + if (bpmTaskExtDO == null) {
  325 + break;
  326 + }
  327 + //任务已完成
  328 + allChildrenTaskFinish = BpmProcessInstanceResultEnum.isEndResult(bpmTaskExtDO.getResult());
  329 + if (!allChildrenTaskFinish) {
  330 + //有一个未完成,则退出循环
  331 + break;
  332 + }
  333 + }
  334 + if (allChildrenTaskFinish) {
  335 + //完成最后的顶级祖先任务
  336 + taskService.complete(parentTask.getId());
  337 + }
  338 + }
  339 + }
  340 +
  341 + /**
  342 + * 清空 scopeType 字段,用于任务没有子任务时使用该方法,方便任务可以再次被不同的方式加签
  343 + *
  344 + * @param task 需要被清空的任务
  345 + */
  346 + private void clearTaskScopeTypeAndSave(Task task) {
  347 + TaskEntityImpl taskImpl = (TaskEntityImpl) task;
  348 + taskImpl.setScopeType(null);
  349 + taskService.saveTask(task);
  350 + }
  351 +
  352 + /**
  353 + * 获取子任务个数
  354 + *
  355 + * @param parentTaskId 父类ID
  356 + * @return 剩余子任务个数
  357 + */
  358 + private Long getSubTaskCount(String parentTaskId) {
  359 + String tableName = managementService.getTableName(TaskEntity.class);
  360 + String sql = "select count(1) from " + tableName + " where PARENT_TASK_ID_=#{parentTaskId}";
  361 + return taskService.createNativeTaskQuery().sql(sql).parameter("parentTaskId", parentTaskId).count();
213 362 }
214 363  
215 364 /**
... ... @@ -226,7 +375,7 @@ public class BpmTaskServiceImpl implements BpmTaskService {
226 375 String comment = StrUtil.format("[{}]完成委派任务,任务重新回到[{}]手中,审批意见为:{}", currentUser.getNickname(),
227 376 sourceApproveUser.getNickname(), reqVO.getReason());
228 377 taskService.addComment(reqVO.getId(), task.getProcessInstanceId(),
229   - BpmProcessInstanceResultEnum.DELEGATE.getResult().toString(), comment);
  378 + BpmCommentTypeEnum.DELEGATE.getDesc(), comment);
230 379  
231 380 // 2.1 调用 resolveTask 完成任务。
232 381 // 底层调用 TaskHelper.changeTaskAssignee(task, task.getOwner()):将 owner 设置为 assignee
... ... @@ -290,6 +439,10 @@ public class BpmTaskServiceImpl implements BpmTaskService {
290 439 public void createTaskExt(Task task) {
291 440 BpmTaskExtDO taskExtDO =
292 441 BpmTaskConvert.INSTANCE.convert2TaskExt(task).setResult(BpmProcessInstanceResultEnum.PROCESS.getResult());
  442 + //向后加签生成的任务,状态不能为进行中,需要等前面父任务完成
  443 + if(BpmTaskAddSignTypeEnum.AFTER_CHILDREN_TASK.getType().equals(task.getScopeType())){
  444 + taskExtDO.setResult(BpmProcessInstanceResultEnum.WAIT_BEFORE_TASK.getResult());
  445 + }
293 446 taskExtMapper.insert(taskExtDO);
294 447 }
295 448  
... ... @@ -343,21 +496,19 @@ public class BpmTaskServiceImpl implements BpmTaskService {
343 496 TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
344 497 @Override
345 498 public void afterCommit() {
346   - ProcessInstance processInstance =
347   - processInstanceService.getProcessInstance(task.getProcessInstanceId());
348   - AdminUserRespDTO startUser = adminUserApi.getUser(Long.valueOf(processInstance.getStartUserId()));
349   - messageService.sendMessageWhenTaskAssigned(
350   - BpmTaskConvert.INSTANCE.convert(processInstance, startUser, task));
  499 + if(StrUtil.isNotEmpty(task.getAssignee())){
  500 + ProcessInstance processInstance =
  501 + processInstanceService.getProcessInstance(task.getProcessInstanceId());
  502 + AdminUserRespDTO startUser = adminUserApi.getUser(Long.valueOf(processInstance.getStartUserId()));
  503 + messageService.sendMessageWhenTaskAssigned(
  504 + BpmTaskConvert.INSTANCE.convert(processInstance, startUser, task));
  505 + }
351 506 }
352 507 });
353 508 }
354 509  
355 510 private Task getTask(String id) {
356   - Task task = taskService.createTaskQuery().taskId(id).singleResult();
357   - if (null == task) {
358   - throw exception(TASK_NOT_EXISTS);
359   - }
360   - return task;
  511 + return taskService.createTaskQuery().taskId(id).singleResult();
361 512 }
362 513  
363 514 private HistoricTaskInstance getHistoricTask(String id) {
... ... @@ -437,7 +588,7 @@ public class BpmTaskServiceImpl implements BpmTaskService {
437 588 /**
438 589 * 执行回退逻辑
439 590 *
440   - * @param currentTask 当前回退的任务
  591 + * @param currentTask 当前回退的任务
441 592 * @param targetElement 需要回退到的目标任务
442 593 * @param reqVO 前端参数封装
443 594 */
... ... @@ -458,7 +609,7 @@ public class BpmTaskServiceImpl implements BpmTaskService {
458 609 return;
459 610 }
460 611 taskService.addComment(task.getId(), currentTask.getProcessInstanceId(),
461   - BpmProcessInstanceResultEnum.BACK.getResult().toString(), reqVO.getReason());
  612 + BpmCommentTypeEnum.BACK.getDesc(), reqVO.getReason());
462 613 });
463 614  
464 615 // 3. 执行驳回
... ... @@ -485,9 +636,8 @@ public class BpmTaskServiceImpl implements BpmTaskService {
485 636 String comment = StrUtil.format("[{}]将任务委派给[{}],委派理由为:{}", currentUser.getNickname(),
486 637 delegateUser.getNickname(), reqVO.getReason());
487 638 String taskId = reqVO.getId();
488   - // TODO 海:后面改;感觉 comment 应该 type 做个枚举;不和 result 耦合在一起;
489 639 taskService.addComment(taskId, task.getProcessInstanceId(),
490   - BpmProcessInstanceResultEnum.DELEGATE.getResult().toString(), comment);
  640 + BpmCommentTypeEnum.DELEGATE.getDesc(), comment);
491 641  
492 642 // 3.1 设置任务所有人 (owner) 为原任务的处理人 (assignee)
493 643 taskService.setOwner(taskId, task.getAssignee());
... ... @@ -503,7 +653,7 @@ public class BpmTaskServiceImpl implements BpmTaskService {
503 653 * 校验任务委派参数
504 654 *
505 655 * @param userId 用户编号
506   - * @param reqVO 任务编号,接收人ID
  656 + * @param reqVO 任务编号,接收人ID
507 657 * @return 当前任务信息
508 658 */
509 659 private Task validateTaskCanDelegate(Long userId, BpmTaskDelegateReqVO reqVO) {
... ... @@ -516,4 +666,125 @@ public class BpmTaskServiceImpl implements BpmTaskService {
516 666 return task;
517 667 }
518 668  
  669 + @Override
  670 + @Transactional(rollbackFor = Exception.class)
  671 + public void addSign(BpmTaskAddSignReqVO reqVO, Long userId) {
  672 + //1.获取和校验任务
  673 + TaskEntityImpl taskEntity = validateAddSign(userId, reqVO);
  674 + AdminUserRespDTO currentUser = adminUserApi.getUser(userId);
  675 + List<AdminUserRespDTO> userList = adminUserApi.getUserList(reqVO.getUserIdList());
  676 + if (CollUtil.isEmpty(userList)) {
  677 + throw exception(TASK_ADD_SIGN_USER_NOT_EXIST);
  678 + }
  679 + //2.处理当前任务
  680 + //2.1 开启计数功能
  681 + taskEntity.setCountEnabled(true);
  682 + boolean addSignToBefore = reqVO.getType().equals(BpmTaskAddSignTypeEnum.BEFORE.getType());
  683 + if (addSignToBefore) {
  684 + //2.2 向前加签,设置 owner ,置空 assign ,等子任务都完成后,再调用 resolveTask 重新将 owner 设置为 assign
  685 + //原因是:不能和向前加签的子任务一起审批,需要等前面的子任务都完成才能审批
  686 + taskEntity.setOwner(taskEntity.getAssignee());
  687 + taskEntity.setAssignee(null);
  688 + //2.3 更新扩展表状态
  689 + taskExtMapper.updateByTaskId(
  690 + new BpmTaskExtDO().setTaskId(taskEntity.getId())
  691 + .setResult(BpmProcessInstanceResultEnum.ADD_SIGN_BEFORE.getResult())
  692 + .setReason(reqVO.getReason()));
  693 + }
  694 + //2.4 记录加签方式,完成任务时需要用到判断
  695 + taskEntity.setScopeType(reqVO.getType());
  696 + //2.5 保存当前任务修改后的值
  697 + taskService.saveTask(taskEntity);
  698 +
  699 + //3. 处理加签任务
  700 + this.createSignSubTasks(convertList(reqVO.getUserIdList(), String::valueOf), taskEntity);
  701 + //4. 记录加签 comment,拼接结果为: [当前用户]向前加签/向后加签给了[多个用户],理由为:reason
  702 + String comment = StrUtil.format("[{}]{}给了[{}],理由为:{}", currentUser.getNickname(), BpmTaskAddSignTypeEnum.formatDesc(reqVO.getType()),
  703 + String.join(SymbolConstant.D, convertList(userList, AdminUserRespDTO::getNickname)), reqVO.getReason());
  704 + taskService.addComment(reqVO.getId(), taskEntity.getProcessInstanceId(),
  705 + BpmCommentTypeEnum.ADD_SIGN.getDesc(), comment);
  706 + }
  707 +
  708 +
  709 + /**
  710 + * 校验任务存在和 存在 向前加签 的任务,则不能 向后加签,存在 向后加签 则不能 向前加签
  711 + *
  712 + * @param userId 当前用户 ID
  713 + * @param reqVO 请求参数,包含任务 ID 和加签类型
  714 + * @return 当前任务
  715 + */
  716 + private TaskEntityImpl validateAddSign(Long userId, BpmTaskAddSignReqVO reqVO) {
  717 + TaskEntityImpl taskEntity = (TaskEntityImpl) validateTask(userId, reqVO.getId());
  718 + //向前加签和向后加签不能同时存在
  719 + if (StrUtil.isNotBlank(taskEntity.getScopeType())
  720 + && !BpmTaskAddSignTypeEnum.AFTER_CHILDREN_TASK.getDesc().equals(taskEntity.getScopeType())) {
  721 + if (!taskEntity.getScopeType().equals(reqVO.getType())) {
  722 + throw exception(TASK_ADD_SIGN_TYPE_ERROR,
  723 + BpmTaskAddSignTypeEnum.formatDesc(taskEntity.getScopeType()), BpmTaskAddSignTypeEnum.formatDesc(reqVO.getType()));
  724 + }
  725 + }
  726 + //同一个 key 的任务,审批人不重复
  727 + List<Task> taskList = taskService.createTaskQuery().processInstanceId(taskEntity.getProcessInstanceId())
  728 + .taskDefinitionKey(taskEntity.getTaskDefinitionKey()).list();
  729 + List<String> currentAssigneeList = convertList(taskList, Task::getAssignee);
  730 + List<String> frontAssigneeList = convertList(reqVO.getUserIdList(), String::valueOf);
  731 + currentAssigneeList.retainAll(frontAssigneeList);
  732 + if (CollUtil.isNotEmpty(currentAssigneeList)) {
  733 + List<AdminUserRespDTO> userList = adminUserApi.getUserList(convertList(currentAssigneeList, NumberUtils::parseLong));
  734 + throw exception(TASK_ADD_SIGN_USER_REPEAT, String.join(SymbolConstant.D, convertList(userList, AdminUserRespDTO::getNickname)));
  735 + }
  736 + return taskEntity;
  737 + }
  738 +
  739 + /**
  740 + * 创建加签子任务
  741 + *
  742 + * @param addSingUserIdList 被加签的用户ID
  743 + * @param taskEntity 被加签的任务
  744 + */
  745 + private void createSignSubTasks(List<String> addSingUserIdList, TaskEntityImpl taskEntity) {
  746 + if (CollUtil.isNotEmpty(addSingUserIdList)) {
  747 + // 创建加签人的新任务,全部基于 taskEntity 为父任务来创建
  748 + addSingUserIdList.forEach(addSignId -> {
  749 + if (StrUtil.isNotBlank(addSignId)) {
  750 + this.createSubTask(taskEntity, addSignId);
  751 + }
  752 + });
  753 + }
  754 + }
  755 +
  756 + /**
  757 + * 创建子任务
  758 + *
  759 + * @param parentTask 父任务
  760 + * @param assignee 子任务的执行人
  761 + * @return
  762 + */
  763 + private void createSubTask(TaskEntityImpl parentTask, String assignee) {
  764 + //1.生成子任务
  765 + TaskEntityImpl task = (TaskEntityImpl) taskService.newTask(IdUtil.fastSimpleUUID());
  766 + task = BpmTaskConvert.INSTANCE.convert(task,parentTask);
  767 + if (BpmTaskAddSignTypeEnum.BEFORE.getType().equals(parentTask.getScopeType())) {
  768 + // 2. 前加签,才设置审批人,否则设置 owner
  769 + task.setAssignee(assignee);
  770 + } else {
  771 + //2.2 设置 owner 不设置 assignee 是因为不能同时审批,需要等父任务完成
  772 + task.setOwner(assignee);
  773 + //2.3 设置向后加签任务的 scopeType 为 afterChildrenTask,用于设置任务扩展表的状态
  774 + task.setScopeType(BpmTaskAddSignTypeEnum.AFTER_CHILDREN_TASK.getType());
  775 + }
  776 + taskService.saveTask(task);
  777 + }
  778 +
  779 + /**
  780 + * 获取指定父级任务的所有子任务 ID 集合
  781 + * @param parentTaskId 父任务 ID
  782 + * @return 所有子任务的 ID 集合
  783 + */
  784 + private List<String> getChildrenTaskIdList(String parentTaskId){
  785 + String tableName = managementService.getTableName(TaskEntity.class);
  786 + String sql = "select ID_ from " + tableName + " where PARENT_TASK_ID_=#{parentTaskId}";
  787 + List<Task> childrenTaskList = taskService.createNativeTaskQuery().sql(sql).parameter("parentTaskId", parentTaskId).list();
  788 + return convertList(childrenTaskList, Task::getId);
  789 + }
519 790 }
... ...