houzhongjian
3 天以前 f4f9405f99cb35e2fd6cfeae4c54617304228fda
提交 | 用户 | 时间
e7c126 1 package com.iailab.module.bpm.service.task;
H 2
3 import cn.hutool.core.collection.CollUtil;
bb2880 4 import cn.hutool.core.lang.Assert;
H 5 import cn.hutool.core.util.*;
6 import cn.hutool.extra.spring.SpringUtil;
e7c126 7 import com.iailab.framework.common.pojo.PageResult;
H 8 import com.iailab.framework.common.util.date.DateUtils;
9 import com.iailab.framework.common.util.number.NumberUtils;
bb2880 10 import com.iailab.framework.common.util.object.ObjectUtils;
e7c126 11 import com.iailab.framework.common.util.object.PageUtils;
49b4b6 12 import com.iailab.framework.datapermission.core.annotation.DataPermission;
e7c126 13 import com.iailab.framework.web.core.util.WebFrameworkUtils;
H 14 import com.iailab.module.bpm.controller.admin.task.vo.task.*;
15 import com.iailab.module.bpm.convert.task.BpmTaskConvert;
f4f940 16 import com.iailab.module.bpm.dal.dataobject.definition.BpmFormDO;
bb2880 17 import com.iailab.module.bpm.enums.definition.*;
e7c126 18 import com.iailab.module.bpm.enums.task.BpmCommentTypeEnum;
bb2880 19 import com.iailab.module.bpm.enums.task.BpmReasonEnum;
e7c126 20 import com.iailab.module.bpm.enums.task.BpmTaskSignTypeEnum;
H 21 import com.iailab.module.bpm.enums.task.BpmTaskStatusEnum;
bb2880 22 import com.iailab.module.bpm.framework.flowable.core.enums.BpmnVariableConstants;
H 23 import com.iailab.module.bpm.framework.flowable.core.util.BpmnModelUtils;
24 import com.iailab.module.bpm.framework.flowable.core.util.FlowableUtils;
f4f940 25 import com.iailab.module.bpm.service.definition.BpmFormService;
e7c126 26 import com.iailab.module.bpm.service.definition.BpmModelService;
bb2880 27 import com.iailab.module.bpm.service.definition.BpmProcessDefinitionService;
e7c126 28 import com.iailab.module.bpm.service.message.BpmMessageService;
bb2880 29 import com.iailab.module.bpm.service.message.dto.BpmMessageSendWhenTaskTimeoutReqDTO;
H 30 import com.iailab.module.system.api.dept.DeptApi;
31 import com.iailab.module.system.api.dept.dto.DeptRespDTO;
e7c126 32 import com.iailab.module.system.api.user.AdminUserApi;
H 33 import com.iailab.module.system.api.user.dto.AdminUserRespDTO;
34 import lombok.extern.slf4j.Slf4j;
35 import org.flowable.bpmn.model.BpmnModel;
bb2880 36 import org.flowable.bpmn.model.EndEvent;
e7c126 37 import org.flowable.bpmn.model.FlowElement;
H 38 import org.flowable.bpmn.model.UserTask;
39 import org.flowable.engine.HistoryService;
40 import org.flowable.engine.ManagementService;
41 import org.flowable.engine.RuntimeService;
42 import org.flowable.engine.TaskService;
bb2880 43 import org.flowable.engine.history.HistoricActivityInstance;
e7c126 44 import org.flowable.engine.runtime.ProcessInstance;
H 45 import org.flowable.task.api.DelegationState;
46 import org.flowable.task.api.Task;
bb2880 47 import org.flowable.task.api.TaskInfo;
e7c126 48 import org.flowable.task.api.TaskQuery;
H 49 import org.flowable.task.api.history.HistoricTaskInstance;
50 import org.flowable.task.api.history.HistoricTaskInstanceQuery;
51 import org.flowable.task.service.impl.persistence.entity.TaskEntity;
52 import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
53 import org.springframework.stereotype.Service;
54 import org.springframework.transaction.annotation.Transactional;
55 import org.springframework.transaction.support.TransactionSynchronization;
56 import org.springframework.transaction.support.TransactionSynchronizationManager;
57
58 import javax.annotation.Resource;
59 import javax.validation.Valid;
60 import java.util.*;
61 import java.util.stream.Stream;
62
63 import static com.iailab.framework.common.exception.util.ServiceExceptionUtil.exception;
64 import static com.iailab.framework.common.util.collection.CollectionUtils.*;
65 import static com.iailab.module.bpm.enums.ErrorCodeConstants.*;
bb2880 66 import static com.iailab.module.bpm.framework.flowable.core.enums.BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_RETURN_FLAG;
e7c126 67
H 68 /**
69  * 流程任务实例 Service 实现类
70  *
bb2880 71  * @author 芋道源码
e7c126 72  * @author jason
H 73  */
74 @Slf4j
75 @Service
76 public class BpmTaskServiceImpl implements BpmTaskService {
77
78     @Resource
79     private TaskService taskService;
80     @Resource
81     private HistoryService historyService;
82     @Resource
83     private RuntimeService runtimeService;
84     @Resource
85     private ManagementService managementService;
86
87     @Resource
88     private BpmProcessInstanceService processInstanceService;
89     @Resource
bb2880 90     private BpmProcessDefinitionService bpmProcessDefinitionService;
H 91     @Resource
e7c126 92     private BpmProcessInstanceCopyService processInstanceCopyService;
H 93     @Resource
bb2880 94     private BpmModelService modelService;
e7c126 95     @Resource
H 96     private BpmMessageService messageService;
f4f940 97     @Resource
H 98     private BpmFormService formService;
e7c126 99
H 100     @Resource
101     private AdminUserApi adminUserApi;
bb2880 102     @Resource
H 103     private DeptApi deptApi;
104
105     // ========== Query 查询相关方法 ==========
e7c126 106
H 107     @Override
108     public PageResult<Task> getTaskTodoPage(Long userId, BpmTaskPageReqVO pageVO) {
109         TaskQuery taskQuery = taskService.createTaskQuery()
110                 .taskAssignee(String.valueOf(userId)) // 分配给自己
111                 .active()
112                 .includeProcessVariables()
113                 .orderByTaskCreateTime().desc(); // 创建时间倒序
114         if (StrUtil.isNotBlank(pageVO.getName())) {
115             taskQuery.taskNameLike("%" + pageVO.getName() + "%");
f4f940 116         }
H 117         if (StrUtil.isNotEmpty(pageVO.getCategory())) {
118             taskQuery.taskCategory(pageVO.getCategory());
e7c126 119         }
H 120         if (ArrayUtil.isNotEmpty(pageVO.getCreateTime())) {
121             taskQuery.taskCreatedAfter(DateUtils.of(pageVO.getCreateTime()[0]));
bb2880 122             taskQuery.taskCreatedBefore(DateUtils.of(pageVO.getCreateTime()[1]));
e7c126 123         }
H 124         long count = taskQuery.count();
125         if (count == 0) {
126             return PageResult.empty();
127         }
128         List<Task> tasks = taskQuery.listPage(PageUtils.getStart(pageVO), pageVO.getPageSize());
129         return new PageResult<>(tasks, count);
bb2880 130     }
H 131
132     @Override
133     public BpmTaskRespVO getFirstTodoTask(Long userId, String processInstanceId) {
134         if (processInstanceId == null) {
135             return null;
136         }
137         // 1. 查询所有任务
138         List<Task> tasks = taskService.createTaskQuery()
139                 .active()
140                 .processInstanceId(processInstanceId)
141                 .includeTaskLocalVariables()
142                 .includeProcessVariables()
143                 .orderByTaskCreateTime().asc() // 按创建时间升序
144                 .list();
145         if (CollUtil.isEmpty(tasks)) {
146             return null;
147         }
148
149         // 2.1 查询我的首个任务
150         Task todoTask = CollUtil.findOne(tasks, task -> {
151             return isAssignUserTask(userId, task) // 当前用户为审批人
152                     || isAddSignUserTask(userId, task); // 当前用户为加签人(为了减签)
153         });
154         if (todoTask == null) {
155             return null;
156         }
157         // 2.2 查询该任务的子任务
158         List<Task> childrenTasks = getAllChildrenTaskListByParentTaskId(todoTask.getId(), tasks);
159
160         // 3. 转换返回
161         BpmnModel bpmnModel = bpmProcessDefinitionService.getProcessDefinitionBpmnModel(todoTask.getProcessDefinitionId());
162         Map<Integer, BpmTaskRespVO.OperationButtonSetting> buttonsSetting = BpmnModelUtils.parseButtonsSetting(
163                 bpmnModel, todoTask.getTaskDefinitionKey());
f4f940 164
H 165         // 4. 任务表单
166         BpmFormDO taskForm = null;
167         if (StrUtil.isNotBlank(todoTask.getFormKey())){
168             taskForm = formService.getForm(NumberUtils.parseLong(todoTask.getFormKey()));
169         }
170         return BpmTaskConvert.INSTANCE.buildTodoTask(todoTask, childrenTasks, buttonsSetting, taskForm);
e7c126 171     }
H 172
173     @Override
174     public PageResult<HistoricTaskInstance> getTaskDonePage(Long userId, BpmTaskPageReqVO pageVO) {
175         HistoricTaskInstanceQuery taskQuery = historyService.createHistoricTaskInstanceQuery()
176                 .finished() // 已完成
177                 .taskAssignee(String.valueOf(userId)) // 分配给自己
178                 .includeTaskLocalVariables()
179                 .orderByHistoricTaskInstanceEndTime().desc(); // 审批时间倒序
180         if (StrUtil.isNotBlank(pageVO.getName())) {
181             taskQuery.taskNameLike("%" + pageVO.getName() + "%");
182         }
183         if (ArrayUtil.isNotEmpty(pageVO.getCreateTime())) {
184             taskQuery.taskCreatedAfter(DateUtils.of(pageVO.getCreateTime()[0]));
bb2880 185             taskQuery.taskCreatedBefore(DateUtils.of(pageVO.getCreateTime()[1]));
e7c126 186         }
H 187         // 执行查询
188         long count = taskQuery.count();
189         if (count == 0) {
190             return PageResult.empty();
191         }
192         List<HistoricTaskInstance> tasks = taskQuery.listPage(PageUtils.getStart(pageVO), pageVO.getPageSize());
193         return new PageResult<>(tasks, count);
194     }
195
196     @Override
197     public PageResult<HistoricTaskInstance> getTaskPage(Long userId, BpmTaskPageReqVO pageVO) {
198         HistoricTaskInstanceQuery taskQuery = historyService.createHistoricTaskInstanceQuery()
199                 .includeTaskLocalVariables()
200                 .taskTenantId(FlowableUtils.getTenantId())
201                 .orderByHistoricTaskInstanceEndTime().desc(); // 审批时间倒序
202         if (StrUtil.isNotBlank(pageVO.getName())) {
203             taskQuery.taskNameLike("%" + pageVO.getName() + "%");
f4f940 204         }
H 205         if (StrUtil.isNotEmpty(pageVO.getCategory())) {
206             taskQuery.taskCategory(pageVO.getCategory());
e7c126 207         }
H 208         if (ArrayUtil.isNotEmpty(pageVO.getCreateTime())) {
209             taskQuery.taskCreatedAfter(DateUtils.of(pageVO.getCreateTime()[0]));
bb2880 210             taskQuery.taskCreatedBefore(DateUtils.of(pageVO.getCreateTime()[1]));
e7c126 211         }
H 212         // 执行查询
213         long count = taskQuery.count();
214         if (count == 0) {
215             return PageResult.empty();
216         }
217         List<HistoricTaskInstance> tasks = taskQuery.listPage(PageUtils.getStart(pageVO), pageVO.getPageSize());
218         return new PageResult<>(tasks, count);
219     }
220
221     @Override
222     public List<Task> getTasksByProcessInstanceIds(List<String> processInstanceIds) {
223         if (CollUtil.isEmpty(processInstanceIds)) {
224             return Collections.emptyList();
225         }
226         return taskService.createTaskQuery().processInstanceIdIn(processInstanceIds).list();
227     }
228
229     @Override
bb2880 230     public List<HistoricTaskInstance> getTaskListByProcessInstanceId(String processInstanceId, Boolean asc) {
H 231         HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery()
e7c126 232                 .includeTaskLocalVariables()
bb2880 233                 .processInstanceId(processInstanceId);
H 234         if (Boolean.TRUE.equals(asc)) {
235             query.orderByHistoricTaskInstanceStartTime().asc();
236         } else {
237             query.orderByHistoricTaskInstanceStartTime().desc();
238         }
239         return query.list();
240     }
241
242     /**
243      * 校验任务是否存在,并且是否是分配给自己的任务
244      *
245      * @param userId 用户 id
246      * @param taskId task id
247      */
248     private Task validateTask(Long userId, String taskId) {
249         Task task = validateTaskExist(taskId);
250         // 为什么判断 assignee 非空的情况下?
251         // 例如说:在审批人为空时,我们会有“自动审批通过”的策略,此时 userId 为 null,允许通过
252         if (StrUtil.isNotBlank(task.getAssignee())
253                 && ObjectUtil.notEqual(userId, NumberUtils.parseLong(task.getAssignee()))) {
254             throw exception(TASK_OPERATE_FAIL_ASSIGN_NOT_SELF);
255         }
256         return task;
257     }
258
259     private Task validateTaskExist(String id) {
260         Task task = getTask(id);
261         if (task == null) {
262             throw exception(TASK_NOT_EXISTS);
263         }
264         return task;
265     }
266
267     @Override
268     public Task getTask(String id) {
269         return taskService.createTaskQuery().taskId(id).includeTaskLocalVariables().singleResult();
270     }
271
272     @Override
273     public HistoricTaskInstance getHistoricTask(String id) {
274         return historyService.createHistoricTaskInstanceQuery().taskId(id).includeTaskLocalVariables().singleResult();
275     }
276
277     @Override
278     public List<HistoricTaskInstance> getHistoricTasks(Collection<String> taskIds) {
279         return historyService.createHistoricTaskInstanceQuery().taskIds(taskIds).includeTaskLocalVariables().list();
280     }
281
282     @Override
283     public List<Task> getRunningTaskListByProcessInstanceId(String processInstanceId, Boolean assigned, String defineKey) {
284         Assert.notNull(processInstanceId, "processInstanceId 不能为空");
285         TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(processInstanceId).active()
286                 .includeTaskLocalVariables();
287         if (BooleanUtil.isTrue(assigned)) {
288             taskQuery.taskAssigned();
289         } else if (BooleanUtil.isFalse(assigned)) {
290             taskQuery.taskUnassigned();
291         }
292         if (StrUtil.isNotEmpty(defineKey)) {
293             taskQuery.taskDefinitionKey(defineKey);
294         }
295         return taskQuery.list();
296     }
297
298     @Override
299     public List<UserTask> getUserTaskListByReturn(String id) {
300         // 1.1 校验当前任务 task 存在
301         Task task = validateTaskExist(id);
302         // 1.2 根据流程定义获取流程模型信息
303         BpmnModel bpmnModel = modelService.getBpmnModelByDefinitionId(task.getProcessDefinitionId());
304         FlowElement source = BpmnModelUtils.getFlowElementById(bpmnModel, task.getTaskDefinitionKey());
305         if (source == null) {
306             throw exception(TASK_NOT_EXISTS);
307         }
308
309         // 2.1 查询该任务的前置任务节点的 key 集合
310         List<UserTask> previousUserList = BpmnModelUtils.getPreviousUserTaskList(source, null, null);
311         if (CollUtil.isEmpty(previousUserList)) {
312             return Collections.emptyList();
313         }
314         // 2.2 过滤:只有串行可到达的节点,才可以退回。类似非串行、子流程无法退回
315         previousUserList.removeIf(userTask -> !BpmnModelUtils.isSequentialReachable(source, userTask, null));
316         return previousUserList;
317     }
318
319     @Override
320     public <T extends TaskInfo> List<T> getAllChildrenTaskListByParentTaskId(String parentTaskId, List<T> tasks) {
e7c126 321         if (CollUtil.isEmpty(tasks)) {
H 322             return Collections.emptyList();
323         }
bb2880 324         Map<String, List<T>> parentTaskMap = convertMultiMap(
H 325                 filterList(tasks, task -> StrUtil.isNotEmpty(task.getParentTaskId())), TaskInfo::getParentTaskId);
326         if (CollUtil.isEmpty(parentTaskMap)) {
327             return Collections.emptyList();
328         }
329
330         List<T> result = new ArrayList<>();
331         // 1. 递归获取子级
332         Stack<String> stack = new Stack<>();
333         stack.push(parentTaskId);
334         // 2. 递归遍历
335         for (int i = 0; i < Short.MAX_VALUE; i++) {
336             if (stack.isEmpty()) {
337                 break;
338             }
339             // 2.1 获取子任务们
340             String taskId = stack.pop();
341             List<T> childTaskList = filterList(tasks, task -> StrUtil.equals(task.getParentTaskId(), taskId));
342             // 2.2 如果非空,则添加到 stack 进一步递归
343             if (CollUtil.isNotEmpty(childTaskList)) {
344                 stack.addAll(convertList(childTaskList, TaskInfo::getId));
345                 result.addAll(childTaskList);
346             }
347         }
348         return result;
e7c126 349     }
bb2880 350
H 351     /**
352      * 获得所有子任务列表
353      *
354      * @param parentTask 父任务
355      * @return 所有子任务列表
356      */
357     private List<Task> getAllChildTaskList(Task parentTask) {
358         List<Task> result = new ArrayList<>();
359         // 1. 递归获取子级
360         Stack<Task> stack = new Stack<>();
361         stack.push(parentTask);
362         // 2. 递归遍历
363         for (int i = 0; i < Short.MAX_VALUE; i++) {
364             if (stack.isEmpty()) {
365                 break;
366             }
367             // 2.1 获取子任务们
368             Task task = stack.pop();
369             List<Task> childTaskList = getTaskListByParentTaskId(task.getId());
370             // 2.2 如果非空,则添加到 stack 进一步递归
371             if (CollUtil.isNotEmpty(childTaskList)) {
372                 stack.addAll(childTaskList);
373                 result.addAll(childTaskList);
374             }
375         }
376         return result;
377     }
378
379     @Override
380     public List<Task> getTaskListByParentTaskId(String parentTaskId) {
381         String tableName = managementService.getTableName(TaskEntity.class);
382         // taskService.createTaskQuery() 没有 parentId 参数,所以写 sql 查询
383         String sql = "select ID_,NAME_,OWNER_,ASSIGNEE_ from " + tableName + " where PARENT_TASK_ID_=#{parentTaskId}";
384         return taskService.createNativeTaskQuery().sql(sql).parameter("parentTaskId", parentTaskId).list();
385     }
386
387     /**
388      * 获取子任务个数
389      *
390      * @param parentTaskId 父任务 ID
391      * @return 剩余子任务个数
392      */
393     private Long getTaskCountByParentTaskId(String parentTaskId) {
394         String tableName = managementService.getTableName(TaskEntity.class);
395         String sql = "SELECT COUNT(1) from " + tableName + " WHERE PARENT_TASK_ID_=#{parentTaskId}";
396         return taskService.createNativeTaskQuery().sql(sql).parameter("parentTaskId", parentTaskId).count();
397     }
398
399     /**
400      * 获得任务根任务的父任务编号
401      *
402      * @param task 任务
403      * @return 根任务的父任务编号
404      */
405     private String getTaskRootParentId(Task task) {
406         if (task == null || task.getParentTaskId() == null) {
407             return null;
408         }
409         for (int i = 0; i < Short.MAX_VALUE; i++) {
410             Task parentTask = getTask(task.getParentTaskId());
411             if (parentTask == null) {
412                 return null;
413             }
414             if (parentTask.getParentTaskId() == null) {
415                 return parentTask.getId();
416             }
417             task = parentTask;
418         }
419         throw new IllegalArgumentException(String.format("Task(%s) 层级过深,无法获取父节点编号", task.getId()));
420     }
421
422     @Override
423     public List<HistoricActivityInstance> getActivityListByProcessInstanceId(String processInstanceId) {
424         return historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId)
425                 .orderByHistoricActivityInstanceStartTime().asc().list();
426     }
427
428     @Override
429     public List<HistoricActivityInstance> getHistoricActivityListByExecutionId(String executionId) {
430         return historyService.createHistoricActivityInstanceQuery().executionId(executionId).list();
431     }
432
433     /**
434      * 判断指定用户,是否是当前任务的审批人
435      *
436      * @param userId 用户编号
437      * @param task   任务
438      * @return 是否
439      */
440     private boolean isAssignUserTask(Long userId, Task task) {
441         Long assignee = NumberUtil.parseLong(task.getAssignee(), null);
442         return ObjectUtil.equals(userId, assignee);
443     }
444
445     /**
446      * 判断指定用户,是否是当前任务的拥有人
447      *
448      * @param userId 用户编号
449      * @param task   任务
450      * @return 是否
451      */
452     private boolean isOwnerUserTask(Long userId, Task task) {
453         Long assignee = NumberUtil.parseLong(task.getOwner(), null);
454         return ObjectUtil.equal(userId, assignee);
455     }
456
457     /**
458      * 判断指定用户,是否是当前任务的加签人
459      *
460      * @param userId 用户 Id
f4f940 461      * @param task   任务
bb2880 462      * @return 是否
H 463      */
464     private boolean isAddSignUserTask(Long userId, Task task) {
465         return (isAssignUserTask(userId, task) || isOwnerUserTask(userId, task))
466                 && BpmTaskSignTypeEnum.of(task.getScopeType()) != null;
467     }
468
469     // ========== Update 写入相关方法 ==========
e7c126 470
H 471     @Override
472     @Transactional(rollbackFor = Exception.class)
473     public void approveTask(Long userId, @Valid BpmTaskApproveReqVO reqVO) {
474         // 1.1 校验任务存在
475         Task task = validateTask(userId, reqVO.getId());
476         // 1.2 校验流程实例存在
477         ProcessInstance instance = processInstanceService.getProcessInstance(task.getProcessInstanceId());
478         if (instance == null) {
479             throw exception(PROCESS_INSTANCE_NOT_EXISTS);
480         }
481
482         // 情况一:被委派的任务,不调用 complete 去完成任务
483         if (DelegationState.PENDING.equals(task.getDelegationState())) {
484             approveDelegateTask(reqVO, task);
485             return;
486         }
487
488         // 情况二:审批有【后】加签的任务
489         if (BpmTaskSignTypeEnum.AFTER.getType().equals(task.getScopeType())) {
490             approveAfterSignTask(task, reqVO);
491             return;
492         }
493
494         // 情况三:审批普通的任务。大多数情况下,都是这样
bb2880 495         // 2.1 更新 task 状态、原因
e7c126 496         updateTaskStatusAndReason(task.getId(), BpmTaskStatusEnum.APPROVE.getStatus(), reqVO.getReason());
bb2880 497         // 2.2 添加评论
e7c126 498         taskService.addComment(task.getId(), task.getProcessInstanceId(), BpmCommentTypeEnum.APPROVE.getType(),
H 499                 BpmCommentTypeEnum.APPROVE.formatComment(reqVO.getReason()));
bb2880 500         // 2.3 调用 BPM complete 去完成任务
e7c126 501         // 其中,variables 是存储动态表单到 local 任务级别。过滤一下,避免 ProcessInstance 系统级的变量被占用
H 502         if (CollUtil.isNotEmpty(reqVO.getVariables())) {
503             Map<String, Object> variables = FlowableUtils.filterTaskFormVariable(reqVO.getVariables());
bb2880 504             // 修改表单的值需要存储到 ProcessInstance 变量
H 505             runtimeService.setVariables(task.getProcessInstanceId(), variables);
e7c126 506             taskService.complete(task.getId(), variables, true);
H 507         } else {
508             taskService.complete(task.getId());
509         }
510
511         // 【加签专属】处理加签任务
512         handleParentTaskIfSign(task.getParentTaskId());
513     }
514
515     /**
516      * 审批通过存在“后加签”的任务。
517      * <p>
518      * 注意:该任务不能马上完成,需要一个中间状态(APPROVING),并激活剩余所有子任务(PROCESS)为可审批处理
519      * 如果马上完成,则会触发下一个任务,甚至如果没有下一个任务则流程实例就直接结束了!
520      *
521      * @param task  当前任务
522      * @param reqVO 前端请求参数
523      */
524     private void approveAfterSignTask(Task task, BpmTaskApproveReqVO reqVO) {
525         // 更新父 task 状态 + 原因
526         updateTaskStatusAndReason(task.getId(), BpmTaskStatusEnum.APPROVING.getStatus(), reqVO.getReason());
527
528         // 2. 激活子任务
529         List<Task> childrenTaskList = getTaskListByParentTaskId(task.getId());
530         for (Task childrenTask : childrenTaskList) {
531             taskService.resolveTask(childrenTask.getId());
532             // 更新子 task 状态
533             updateTaskStatus(childrenTask.getId(), BpmTaskStatusEnum.RUNNING.getStatus());
534         }
535     }
536
537     /**
538      * 如果父任务是有前后【加签】的任务,如果它【加签】出来的子任务都被处理,需要处理父任务:
bb2880 539      * <p>
e7c126 540      * 1. 如果是【向前】加签,则需要重新激活父任务,让它可以被审批
H 541      * 2. 如果是【向后】加签,则需要完成父任务,让它完成审批
542      *
543      * @param parentTaskId 父任务编号
544      */
545     private void handleParentTaskIfSign(String parentTaskId) {
546         if (StrUtil.isBlank(parentTaskId)) {
547             return;
548         }
549         // 1.1 判断是否还有子任务。如果没有,就不处理
550         Long childrenTaskCount = getTaskCountByParentTaskId(parentTaskId);
551         if (childrenTaskCount > 0) {
552             return;
553         }
554         // 1.2 只处理加签的父任务
555         Task parentTask = validateTaskExist(parentTaskId);
556         String scopeType = parentTask.getScopeType();
557         if (BpmTaskSignTypeEnum.of(scopeType) == null) {
558             return;
559         }
560
561         // 2. 子任务已处理完成,清空 scopeType 字段,修改 parentTask 信息,方便后续可以继续向前后向后加签
562         TaskEntityImpl parentTaskImpl = (TaskEntityImpl) parentTask;
563         parentTaskImpl.setScopeType(null);
564         taskService.saveTask(parentTaskImpl);
565
566         // 3.1 情况一:处理向【向前】加签
567         if (BpmTaskSignTypeEnum.BEFORE.getType().equals(scopeType)) {
568             // 3.1.1 owner 重新赋值给父任务的 assignee,这样它就可以被审批
569             taskService.resolveTask(parentTaskId);
570             // 3.1.2 更新流程任务 status
571             updateTaskStatus(parentTaskId, BpmTaskStatusEnum.RUNNING.getStatus());
bb2880 572             // 3.2 情况二:处理向【向后】加签
e7c126 573         } else if (BpmTaskSignTypeEnum.AFTER.getType().equals(scopeType)) {
H 574             // 只有 parentTask 处于 APPROVING 的情况下,才可以继续 complete 完成
575             // 否则,一个未审批的 parentTask 任务,在加签出来的任务都被减签的情况下,就直接完成审批,这样会存在问题
bb2880 576             Integer status = (Integer) parentTask.getTaskLocalVariables().get(BpmnVariableConstants.TASK_VARIABLE_STATUS);
e7c126 577             if (ObjectUtil.notEqual(status, BpmTaskStatusEnum.APPROVING.getStatus())) {
H 578                 return;
579             }
580             // 3.2.2 完成自己(因为它已经没有子任务,所以也可以完成)
581             updateTaskStatus(parentTaskId, BpmTaskStatusEnum.APPROVE.getStatus());
582             taskService.complete(parentTaskId);
583         }
584
585         // 4. 递归处理父任务
586         handleParentTaskIfSign(parentTask.getParentTaskId());
587     }
588
589     /**
590      * 审批被委派的任务
591      *
592      * @param reqVO 前端请求参数,包含当前任务ID,审批意见等
593      * @param task  当前被审批的任务
594      */
595     private void approveDelegateTask(BpmTaskApproveReqVO reqVO, Task task) {
596         // 1. 添加审批意见
597         AdminUserRespDTO currentUser = adminUserApi.getUser(WebFrameworkUtils.getLoginUserId()).getCheckedData();
598         AdminUserRespDTO ownerUser = adminUserApi.getUser(NumberUtils.parseLong(task.getOwner())).getCheckedData(); // 发起委托的用户
599         Assert.notNull(ownerUser, "委派任务找不到原审批人,需要检查数据");
600         taskService.addComment(reqVO.getId(), task.getProcessInstanceId(), BpmCommentTypeEnum.DELEGATE_END.getType(),
601                 BpmCommentTypeEnum.DELEGATE_END.formatComment(currentUser.getNickname(), ownerUser.getNickname(), reqVO.getReason()));
602
603         // 2.1 调用 resolveTask 完成任务。
604         // 底层调用 TaskHelper.changeTaskAssignee(task, task.getOwner()):将 owner 设置为 assignee
605         taskService.resolveTask(task.getId());
606         // 2.2 更新 task 状态 + 原因
607         updateTaskStatusAndReason(task.getId(), BpmTaskStatusEnum.RUNNING.getStatus(), reqVO.getReason());
608     }
609
610     @Override
611     @Transactional(rollbackFor = Exception.class)
612     public void rejectTask(Long userId, @Valid BpmTaskRejectReqVO reqVO) {
613         // 1.1 校验任务存在
614         Task task = validateTask(userId, reqVO.getId());
615         // 1.2 校验流程实例存在
616         ProcessInstance instance = processInstanceService.getProcessInstance(task.getProcessInstanceId());
617         if (instance == null) {
618             throw exception(PROCESS_INSTANCE_NOT_EXISTS);
619         }
620
bb2880 621         // 2.1 更新流程任务为不通过
e7c126 622         updateTaskStatusAndReason(task.getId(), BpmTaskStatusEnum.REJECT.getStatus(), reqVO.getReason());
bb2880 623         // 2.2 添加流程评论
e7c126 624         taskService.addComment(task.getId(), task.getProcessInstanceId(), BpmCommentTypeEnum.REJECT.getType(),
H 625                 BpmCommentTypeEnum.REJECT.formatComment(reqVO.getReason()));
bb2880 626         // 2.3 如果当前任务时被加签的,则加它的根任务也标记成未通过
H 627         // 疑问:为什么要标记未通过呢?
628         // 回答:例如说 A 任务被向前加签除 B 任务时,B 任务被审批不通过,此时 A 会被取消。而 yudao-ui-admin-vue3 不展示“已取消”的任务,导致展示不出审批不通过的细节。
629         if (task.getParentTaskId() != null) {
630             String rootParentId = getTaskRootParentId(task);
631             updateTaskStatusAndReason(rootParentId, BpmTaskStatusEnum.REJECT.getStatus(),
632                     BpmCommentTypeEnum.REJECT.formatComment("加签任务不通过"));
633             taskService.addComment(rootParentId, task.getProcessInstanceId(), BpmCommentTypeEnum.REJECT.getType(),
634                     BpmCommentTypeEnum.REJECT.formatComment("加签任务不通过"));
635         }
e7c126 636
bb2880 637         // 3. 根据不同的 RejectHandler 处理策略
H 638         BpmnModel bpmnModel = modelService.getBpmnModelByDefinitionId(task.getProcessDefinitionId());
639         FlowElement userTaskElement = BpmnModelUtils.getFlowElementById(bpmnModel, task.getTaskDefinitionKey());
640         // 3.1 情况一:驳回到指定的任务节点
641         BpmUserTaskRejectHandlerType userTaskRejectHandlerType = BpmnModelUtils.parseRejectHandlerType(userTaskElement);
642         if (userTaskRejectHandlerType == BpmUserTaskRejectHandlerType.RETURN_USER_TASK) {
643             String returnTaskId = BpmnModelUtils.parseReturnTaskId(userTaskElement);
644             Assert.notNull(returnTaskId, "退回的节点不能为空");
645             returnTask(userId, new BpmTaskReturnReqVO().setId(task.getId())
646                     .setTargetTaskDefinitionKey(returnTaskId).setReason(reqVO.getReason()));
647             return;
648         }
649         // 3.2 情况二:直接结束,审批不通过
650         processInstanceService.updateProcessInstanceReject(instance, reqVO.getReason()); // 标记不通过
651         moveTaskToEnd(task.getProcessInstanceId()); // 结束流程
e7c126 652     }
H 653
654     /**
655      * 更新流程任务的 status 状态
656      *
bb2880 657      * @param id     任务编号
e7c126 658      * @param status 状态
H 659      */
660     private void updateTaskStatus(String id, Integer status) {
bb2880 661         taskService.setVariableLocal(id, BpmnVariableConstants.TASK_VARIABLE_STATUS, status);
e7c126 662     }
H 663
664     /**
665      * 更新流程任务的 status 状态、reason 理由
666      *
bb2880 667      * @param id     任务编号
e7c126 668      * @param status 状态
H 669      * @param reason 理由(审批通过、审批不通过的理由)
670      */
671     private void updateTaskStatusAndReason(String id, Integer status, String reason) {
672         updateTaskStatus(id, status);
bb2880 673         taskService.setVariableLocal(id, BpmnVariableConstants.TASK_VARIABLE_REASON, reason);
e7c126 674     }
H 675
676     @Override
677     @Transactional(rollbackFor = Exception.class)
678     public void returnTask(Long userId, BpmTaskReturnReqVO reqVO) {
679         // 1.1 当前任务 task
680         Task task = validateTask(userId, reqVO.getId());
681         if (task.isSuspended()) {
682             throw exception(TASK_IS_PENDING);
683         }
684         // 1.2 校验源头和目标节点的关系,并返回目标元素
685         FlowElement targetElement = validateTargetTaskCanReturn(task.getTaskDefinitionKey(),
686                 reqVO.getTargetTaskDefinitionKey(), task.getProcessDefinitionId());
687
bb2880 688         // 2. 调用 Flowable 框架的退回逻辑
f4f940 689         returnTask(userId, task, targetElement, reqVO);
e7c126 690     }
H 691
692     /**
bb2880 693      * 退回流程节点时,校验目标任务节点是否可退回
e7c126 694      *
H 695      * @param sourceKey           当前任务节点 Key
696      * @param targetKey           目标任务节点 key
697      * @param processDefinitionId 当前流程定义 ID
698      * @return 目标任务节点元素
699      */
700     private FlowElement validateTargetTaskCanReturn(String sourceKey, String targetKey, String processDefinitionId) {
701         // 1.1 获取流程模型信息
bb2880 702         BpmnModel bpmnModel = modelService.getBpmnModelByDefinitionId(processDefinitionId);
e7c126 703         // 1.3 获取当前任务节点元素
H 704         FlowElement source = BpmnModelUtils.getFlowElementById(bpmnModel, sourceKey);
705         // 1.3 获取跳转的节点元素
706         FlowElement target = BpmnModelUtils.getFlowElementById(bpmnModel, targetKey);
707         if (target == null) {
708             throw exception(TASK_TARGET_NODE_NOT_EXISTS);
709         }
710
bb2880 711         // 2.2 只有串行可到达的节点,才可以退回。类似非串行、子流程无法退回
e7c126 712         if (!BpmnModelUtils.isSequentialReachable(source, target, null)) {
H 713             throw exception(TASK_RETURN_FAIL_SOURCE_TARGET_ERROR);
714         }
715         return target;
716     }
717
718     /**
bb2880 719      * 执行退回逻辑
e7c126 720      *
f4f940 721      * @param userId        用户编号
bb2880 722      * @param currentTask   当前退回的任务
H 723      * @param targetElement 需要退回到的目标任务
e7c126 724      * @param reqVO         前端参数封装
H 725      */
f4f940 726     public void returnTask(Long userId, Task currentTask, FlowElement targetElement, BpmTaskReturnReqVO reqVO) {
e7c126 727         // 1. 获得所有需要回撤的任务 taskDefinitionKey,用于稍后的 moveActivityIdsToSingleActivityId 回撤
H 728         // 1.1 获取所有正常进行的任务节点 Key
729         List<Task> taskList = taskService.createTaskQuery().processInstanceId(currentTask.getProcessInstanceId()).list();
730         List<String> runTaskKeyList = convertList(taskList, Task::getTaskDefinitionKey);
731         // 1.2 通过 targetElement 的出口连线,计算在 runTaskKeyList 有哪些 key 需要被撤回
732         // 为什么不直接使用 runTaskKeyList 呢?因为可能存在多个审批分支,例如说:A -> B -> C 和 D -> F,而只要 C 撤回到 A,需要排除掉 F
733         List<UserTask> returnUserTaskList = BpmnModelUtils.iteratorFindChildUserTasks(targetElement, runTaskKeyList, null, null);
734         List<String> returnTaskKeyList = convertList(returnUserTaskList, UserTask::getId);
735
bb2880 736         // 2. 给当前要被退回的 task 数组,设置退回意见
e7c126 737         taskList.forEach(task -> {
bb2880 738             // 需要排除掉,不需要设置退回意见的任务
e7c126 739             if (!returnTaskKeyList.contains(task.getTaskDefinitionKey())) {
H 740                 return;
741             }
f4f940 742
H 743             // 判断是否分配给自己任务,因为会签任务,一个节点会有多个任务
744             if (isAssignUserTask(userId, task)) { // 情况一:自己的任务,进行 RETURN 标记
745                 // 2.1.1 添加评论
746                 taskService.addComment(task.getId(), currentTask.getProcessInstanceId(), BpmCommentTypeEnum.RETURN.getType(),
747                         BpmCommentTypeEnum.RETURN.formatComment(reqVO.getReason()));
748                 // 2.1.2 更新 task 状态 + 原因
749                 updateTaskStatusAndReason(task.getId(), BpmTaskStatusEnum.RETURN.getStatus(), reqVO.getReason());
750             } else { // 情况二:别人的任务,进行 CANCEL 标记
751                 processTaskCanceled(task.getId());
752             }
e7c126 753         });
H 754
bb2880 755         // 3. 设置流程变量节点驳回标记:用于驳回到节点,不执行 BpmUserTaskAssignStartUserHandlerTypeEnum 策略。导致自动通过
H 756         runtimeService.setVariable(currentTask.getProcessInstanceId(),
757                 String.format(PROCESS_INSTANCE_VARIABLE_RETURN_FLAG, reqVO.getTargetTaskDefinitionKey()), Boolean.TRUE);
758         // 4. 执行驳回
f4f940 759         // 使用 moveExecutionsToSingleActivityId 替换 moveActivityIdsToSingleActivityId 原因:
H 760         // 当多实例任务回退的时候有问题。相关 issue: https://github.com/flowable/flowable-engine/issues/3944
761         List<String> runExecutionIds = convertList(taskList, Task::getExecutionId);
e7c126 762         runtimeService.createChangeActivityStateBuilder()
H 763                 .processInstanceId(currentTask.getProcessInstanceId())
f4f940 764                 .moveExecutionsToSingleActivityId(runExecutionIds, reqVO.getTargetTaskDefinitionKey())
e7c126 765                 .changeState();
H 766     }
767
768     @Override
769     @Transactional(rollbackFor = Exception.class)
770     public void delegateTask(Long userId, BpmTaskDelegateReqVO reqVO) {
771         String taskId = reqVO.getId();
772         // 1.1 校验任务
773         Task task = validateTask(userId, reqVO.getId());
774         if (task.getAssignee().equals(reqVO.getDelegateUserId().toString())) { // 校验当前审批人和被委派人不是同一人
775             throw exception(TASK_DELEGATE_FAIL_USER_REPEAT);
776         }
777         // 1.2 校验目标用户存在
778         AdminUserRespDTO delegateUser = adminUserApi.getUser(reqVO.getDelegateUserId()).getCheckedData();
779         if (delegateUser == null) {
780             throw exception(TASK_DELEGATE_FAIL_USER_NOT_EXISTS);
781         }
782
783         // 2. 添加委托意见
784         AdminUserRespDTO currentUser = adminUserApi.getUser(userId).getCheckedData();
785         taskService.addComment(taskId, task.getProcessInstanceId(), BpmCommentTypeEnum.DELEGATE_START.getType(),
786                 BpmCommentTypeEnum.DELEGATE_START.formatComment(currentUser.getNickname(), delegateUser.getNickname(), reqVO.getReason()));
787
788         // 3.1 设置任务所有人 (owner) 为原任务的处理人 (assignee)
789         taskService.setOwner(taskId, task.getAssignee());
790         // 3.2 执行委派,将任务委派给 delegateUser
791         taskService.delegateTask(taskId, reqVO.getDelegateUserId().toString());
bb2880 792         // 补充说明:委托不单独设置状态。如果需要,可通过 Task 的 DelegationState 字段,判断是否为 DelegationState.PENDING 委托中
e7c126 793     }
H 794
795     @Override
796     public void transferTask(Long userId, BpmTaskTransferReqVO reqVO) {
797         String taskId = reqVO.getId();
798         // 1.1 校验任务
799         Task task = validateTask(userId, reqVO.getId());
800         if (task.getAssignee().equals(reqVO.getAssigneeUserId().toString())) { // 校验当前审批人和被转派人不是同一人
801             throw exception(TASK_TRANSFER_FAIL_USER_REPEAT);
802         }
803         // 1.2 校验目标用户存在
804         AdminUserRespDTO assigneeUser = adminUserApi.getUser(reqVO.getAssigneeUserId()).getCheckedData();
805         if (assigneeUser == null) {
806             throw exception(TASK_TRANSFER_FAIL_USER_NOT_EXISTS);
807         }
808
809         // 2. 添加委托意见
810         AdminUserRespDTO currentUser = adminUserApi.getUser(userId).getCheckedData();
811         taskService.addComment(taskId, task.getProcessInstanceId(), BpmCommentTypeEnum.TRANSFER.getType(),
812                 BpmCommentTypeEnum.TRANSFER.formatComment(currentUser.getNickname(), assigneeUser.getNickname(), reqVO.getReason()));
813
814         // 3.1 设置任务所有人 (owner) 为原任务的处理人 (assignee)
815         taskService.setOwner(taskId, task.getAssignee());
816         // 3.2 执行转派(审批人),将任务转派给 assigneeUser
817         // 委托( delegate)和转派(transfer)的差别,就在这块的调用!!!!
818         taskService.setAssignee(taskId, reqVO.getAssigneeUserId().toString());
bb2880 819     }
H 820
821     @Override
822     public void moveTaskToEnd(String processInstanceId) {
823         List<Task> taskList = getRunningTaskListByProcessInstanceId(processInstanceId, null, null);
824         if (CollUtil.isEmpty(taskList)) {
825             return;
826         }
827
828         // 1. 其它未结束的任务,直接取消
829         // 疑问:为什么不通过 updateTaskStatusWhenCanceled 监听取消,而是直接提前调用呢?
830         // 回答:详细见 updateTaskStatusWhenCanceled 的方法,加签的场景
831         taskList.forEach(task -> {
832             Integer otherTaskStatus = (Integer) task.getTaskLocalVariables().get(BpmnVariableConstants.TASK_VARIABLE_STATUS);
833             if (BpmTaskStatusEnum.isEndStatus(otherTaskStatus)) {
834                 return;
835             }
836             processTaskCanceled(task.getId());
837         });
838
839         // 2. 终止流程
840         BpmnModel bpmnModel = modelService.getBpmnModelByDefinitionId(taskList.get(0).getProcessDefinitionId());
841         List<String> activityIds = CollUtil.newArrayList(convertSet(taskList, Task::getTaskDefinitionKey));
842         EndEvent endEvent = BpmnModelUtils.getEndEvent(bpmnModel);
843         Assert.notNull(endEvent, "结束节点不能未空");
844         runtimeService.createChangeActivityStateBuilder()
845                 .processInstanceId(processInstanceId)
846                 .moveActivityIdsToSingleActivityId(activityIds, endEvent.getId())
847                 .changeState();
e7c126 848     }
H 849
850     @Override
851     @Transactional(rollbackFor = Exception.class)
852     public void createSignTask(Long userId, BpmTaskSignCreateReqVO reqVO) {
853         // 1. 获取和校验任务
854         TaskEntityImpl taskEntity = validateTaskCanCreateSign(userId, reqVO);
855         List<AdminUserRespDTO> userList = adminUserApi.getUserList(reqVO.getUserIds()).getCheckedData();
856         if (CollUtil.isEmpty(userList)) {
857             throw exception(TASK_SIGN_CREATE_USER_NOT_EXIST);
858         }
859
860         // 2. 处理当前任务
861         // 2.1 开启计数功能,主要用于为了让表 ACT_RU_TASK 中的 SUB_TASK_COUNT_ 字段记录下总共有多少子任务,后续可能有用
862         taskEntity.setCountEnabled(true);
863         // 2.2 向前加签,设置 owner,置空 assign。等子任务都完成后,再调用 resolveTask 重新将 owner 设置为 assign
864         // 原因是:不能和向前加签的子任务一起审批,需要等前面的子任务都完成才能审批
865         if (reqVO.getType().equals(BpmTaskSignTypeEnum.BEFORE.getType())) {
866             taskEntity.setOwner(taskEntity.getAssignee());
867             taskEntity.setAssignee(null);
868         }
869         // 2.4 记录加签方式,完成任务时需要用到判断
870         taskEntity.setScopeType(reqVO.getType());
871         // 2.5 保存当前任务修改后的值
872         taskService.saveTask(taskEntity);
873         // 2.6 更新 task 状态为 WAIT,只有在向前加签的时候
874         if (reqVO.getType().equals(BpmTaskSignTypeEnum.BEFORE.getType())) {
875             updateTaskStatus(taskEntity.getId(), BpmTaskStatusEnum.WAIT.getStatus());
876         }
877
878         // 3. 创建加签任务
879         createSignTaskList(convertList(reqVO.getUserIds(), String::valueOf), taskEntity);
880
881         // 4. 记录加签的评论到 task 任务
882         AdminUserRespDTO currentUser = adminUserApi.getUser(userId).getCheckedData();
883         String comment = StrUtil.format(BpmCommentTypeEnum.ADD_SIGN.getComment(),
884                 currentUser.getNickname(), BpmTaskSignTypeEnum.nameOfType(reqVO.getType()),
885                 String.join(",", convertList(userList, AdminUserRespDTO::getNickname)), reqVO.getReason());
886         taskService.addComment(reqVO.getId(), taskEntity.getProcessInstanceId(), BpmCommentTypeEnum.ADD_SIGN.getType(), comment);
887     }
888
889     /**
890      * 校验任务是否可以加签,主要校验加签类型是否一致:
891      * <p>
892      * 1. 如果存在“向前加签”的任务,则不能“向后加签”
893      * 2. 如果存在“向后加签”的任务,则不能“向前加签”
894      *
895      * @param userId 当前用户 ID
896      * @param reqVO  请求参数,包含任务 ID 和加签类型
897      * @return 当前任务
898      */
899     private TaskEntityImpl validateTaskCanCreateSign(Long userId, BpmTaskSignCreateReqVO reqVO) {
900         TaskEntityImpl taskEntity = (TaskEntityImpl) validateTask(userId, reqVO.getId());
901         // 向前加签和向后加签不能同时存在
902         if (taskEntity.getScopeType() != null
903                 && ObjectUtil.notEqual(taskEntity.getScopeType(), reqVO.getType())) {
904             throw exception(TASK_SIGN_CREATE_TYPE_ERROR,
905                     BpmTaskSignTypeEnum.nameOfType(taskEntity.getScopeType()), BpmTaskSignTypeEnum.nameOfType(reqVO.getType()));
906         }
907
908         // 同一个 key 的任务,审批人不重复
909         List<Task> taskList = taskService.createTaskQuery().processInstanceId(taskEntity.getProcessInstanceId())
910                 .taskDefinitionKey(taskEntity.getTaskDefinitionKey()).list();
911         List<Long> currentAssigneeList = convertListByFlatMap(taskList, task -> // 需要考虑 owner 的情况,因为向后加签时,它暂时没 assignee 而是 owner
912                 Stream.of(NumberUtils.parseLong(task.getAssignee()), NumberUtils.parseLong(task.getOwner())));
913         if (CollUtil.containsAny(currentAssigneeList, reqVO.getUserIds())) {
bb2880 914             List<AdminUserRespDTO> userList = adminUserApi.getUserList(CollUtil.intersection(currentAssigneeList, reqVO.getUserIds())).getCheckedData();
e7c126 915             throw exception(TASK_SIGN_CREATE_USER_REPEAT, String.join(",", convertList(userList, AdminUserRespDTO::getNickname)));
H 916         }
917         return taskEntity;
918     }
919
920     /**
921      * 创建加签子任务
922      *
bb2880 923      * @param userIds    被加签的用户 ID
H 924      * @param taskEntity 被加签的任务
e7c126 925      */
H 926     private void createSignTaskList(List<String> userIds, TaskEntityImpl taskEntity) {
927         if (CollUtil.isEmpty(userIds)) {
928             return;
929         }
930         // 创建加签人的新任务,全部基于 taskEntity 为父任务来创建
931         for (String addSignId : userIds) {
932             if (StrUtil.isBlank(addSignId)) {
933                 continue;
934             }
935             createSignTask(taskEntity, addSignId);
936         }
937     }
938
939     /**
940      * 创建加签子任务
941      *
942      * @param parentTask 父任务
943      * @param assignee   子任务的执行人
944      */
945     private void createSignTask(TaskEntityImpl parentTask, String assignee) {
946         // 1. 生成子任务
947         TaskEntityImpl task = (TaskEntityImpl) taskService.newTask(IdUtil.fastSimpleUUID());
948         BpmTaskConvert.INSTANCE.copyTo(parentTask, task);
949
950         // 2.1 向前加签,设置审批人
951         if (BpmTaskSignTypeEnum.BEFORE.getType().equals(parentTask.getScopeType())) {
952             task.setAssignee(assignee);
bb2880 953             // 2.2 向后加签,设置 owner 不设置 assignee 是因为不能同时审批,需要等父任务完成
e7c126 954         } else {
H 955             task.setOwner(assignee);
956         }
957         // 2.3 保存子任务
958         taskService.saveTask(task);
959
960         // 3. 向后前签,设置子任务的状态为 WAIT,因为需要等父任务审批完
961         if (BpmTaskSignTypeEnum.AFTER.getType().equals(parentTask.getScopeType())) {
962             updateTaskStatus(task.getId(), BpmTaskStatusEnum.WAIT.getStatus());
963         }
964     }
965
966     @Override
967     @Transactional(rollbackFor = Exception.class)
968     public void deleteSignTask(Long userId, BpmTaskSignDeleteReqVO reqVO) {
969         // 1.1 校验 task 可以被减签
970         Task task = validateTaskCanSignDelete(reqVO.getId());
971         // 1.2 校验取消人存在
972         AdminUserRespDTO cancelUser = null;
973         if (StrUtil.isNotBlank(task.getAssignee())) {
974             cancelUser = adminUserApi.getUser(NumberUtils.parseLong(task.getAssignee())).getCheckedData();
975         }
976         if (cancelUser == null && StrUtil.isNotBlank(task.getOwner())) {
977             cancelUser = adminUserApi.getUser(NumberUtils.parseLong(task.getOwner())).getCheckedData();
978         }
979         Assert.notNull(cancelUser, "任务中没有所有者和审批人,数据错误");
980
981         // 2.1 获得子任务列表,包括子任务的子任务
982         List<Task> childTaskList = getAllChildTaskList(task);
983         childTaskList.add(task);
984         // 2.2 更新子任务为已取消
985         String cancelReason = StrUtil.format("任务被取消,原因:由于[{}]操作[减签],", cancelUser.getNickname());
986         childTaskList.forEach(childTask -> updateTaskStatusAndReason(childTask.getId(), BpmTaskStatusEnum.CANCEL.getStatus(), cancelReason));
987         // 2.3 删除任务和所有子任务
988         taskService.deleteTasks(convertList(childTaskList, Task::getId));
989
990         // 3. 记录日志到父任务中。先记录日志是因为,通过 handleParentTask 方法之后,任务可能被完成了,并且不存在了,会报异常,所以先记录
991         AdminUserRespDTO user = adminUserApi.getUser(userId).getCheckedData();
992         taskService.addComment(task.getParentTaskId(), task.getProcessInstanceId(), BpmCommentTypeEnum.SUB_SIGN.getType(),
993                 StrUtil.format(BpmCommentTypeEnum.SUB_SIGN.getComment(), user.getNickname(), cancelUser.getNickname()));
994
995         // 4. 处理当前任务的父任务
996         handleParentTaskIfSign(task.getParentTaskId());
997     }
998
bb2880 999     @Override
H 1000     public void copyTask(Long userId, BpmTaskCopyReqVO reqVO) {
1001         processInstanceCopyService.createProcessInstanceCopy(reqVO.getCopyUserIds(), reqVO.getReason(), reqVO.getId());
1002     }
1003
e7c126 1004     /**
H 1005      * 校验任务是否能被减签
1006      *
1007      * @param id 任务编号
1008      * @return 任务信息
1009      */
1010     private Task validateTaskCanSignDelete(String id) {
1011         Task task = validateTaskExist(id);
1012         if (task.getParentTaskId() == null) {
1013             throw exception(TASK_SIGN_DELETE_NO_PARENT);
1014         }
1015         Task parentTask = getTask(task.getParentTaskId());
1016         if (parentTask == null) {
1017             throw exception(TASK_SIGN_DELETE_NO_PARENT);
1018         }
1019         if (BpmTaskSignTypeEnum.of(parentTask.getScopeType()) == null) {
1020             throw exception(TASK_SIGN_DELETE_NO_PARENT);
1021         }
1022         return task;
1023     }
1024
bb2880 1025     // ========== Event 事件相关方法 ==========
e7c126 1026
H 1027     @Override
bb2880 1028     public void processTaskCreated(Task task) {
H 1029         // 1. 设置为待办中
1030         Integer status = (Integer) task.getTaskLocalVariables().get(BpmnVariableConstants.TASK_VARIABLE_STATUS);
1031         if (status != null) {
1032             log.error("[updateTaskStatusWhenCreated][taskId({}) 已经有状态({})]", task.getId(), status);
1033             return;
1034         }
1035         updateTaskStatus(task.getId(), BpmTaskStatusEnum.RUNNING.getStatus());
1036
1037         // 2. 处理自动通过的情况,例如说:1)无审批人时,是否自动通过、不通过;2)非【人工审核】时,是否自动通过、不通过
1038         ProcessInstance processInstance = processInstanceService.getProcessInstance(task.getProcessInstanceId());
1039         if (processInstance == null) {
1040             log.error("[processTaskCreated][taskId({}) 没有找到流程实例]", task.getId());
1041             return;
1042         }
1043         BpmnModel bpmnModel = modelService.getBpmnModelByDefinitionId(processInstance.getProcessDefinitionId());
1044         FlowElement userTaskElement = BpmnModelUtils.getFlowElementById(bpmnModel, task.getTaskDefinitionKey());
1045         Integer approveType = BpmnModelUtils.parseApproveType(userTaskElement);
1046         Integer assignEmptyHandlerType = BpmnModelUtils.parseAssignEmptyHandlerType(userTaskElement);
1047         TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
1048
f4f940 1049             /**
H 1050              * 特殊情况:部分情况下,TransactionSynchronizationManager 注册 afterCommit 监听时,不会被调用,但是 afterCompletion 可以
1051              * 例如说:第一个 task 就是配置【自动通过】或者【自动拒绝】时
1052              * 参见 <a href="https://gitee.com/zhijiantianya/yudao-cloud/issues/IB7V7Q">issue</a> 反馈
1053              */
bb2880 1054             @Override
H 1055             public void afterCompletion(int transactionStatus) {
f4f940 1056                 // 回滚情况,直接返回
H 1057                 if (ObjectUtil.equal(transactionStatus, TransactionSynchronization.STATUS_ROLLED_BACK)) {
bb2880 1058                     return;
H 1059                 }
f4f940 1060                 // 特殊情况:第一个 task 【自动通过】时,第二个任务设置审批人时 transactionStatus 会为 STATUS_UNKNOWN,不知道啥原因
H 1061                 if (ObjectUtil.equal(transactionStatus, TransactionSynchronization.STATUS_UNKNOWN)
1062                         && getTask(task.getId()) == null) {
1063                     return;
1064                 }
bb2880 1065                 // 特殊情况一:【人工审核】审批人为空,根据配置是否要自动通过、自动拒绝
H 1066                 if (ObjectUtil.equal(approveType, BpmUserTaskApproveTypeEnum.USER.getType())) {
1067                     // 如果有审批人、或者拥有人,则说明不满足情况一,不自动通过、不自动拒绝
1068                     if (!ObjectUtil.isAllEmpty(task.getAssignee(), task.getOwner())) {
1069                         return;
1070                     }
1071                     if (ObjectUtil.equal(assignEmptyHandlerType, BpmUserTaskAssignEmptyHandlerTypeEnum.APPROVE.getType())) {
f4f940 1072                         getSelf().approveTask(null, new BpmTaskApproveReqVO()
bb2880 1073                                 .setId(task.getId()).setReason(BpmReasonEnum.ASSIGN_EMPTY_APPROVE.getReason()));
H 1074                     } else if (ObjectUtil.equal(assignEmptyHandlerType, BpmUserTaskAssignEmptyHandlerTypeEnum.REJECT.getType())) {
f4f940 1075                         getSelf().rejectTask(null, new BpmTaskRejectReqVO()
bb2880 1076                                 .setId(task.getId()).setReason(BpmReasonEnum.ASSIGN_EMPTY_REJECT.getReason()));
H 1077                     }
1078                     // 特殊情况二:【自动审核】审批类型为自动通过、不通过
1079                 } else {
1080                     if (ObjectUtil.equal(approveType, BpmUserTaskApproveTypeEnum.AUTO_APPROVE.getType())) {
f4f940 1081                         getSelf().approveTask(null, new BpmTaskApproveReqVO()
bb2880 1082                                 .setId(task.getId()).setReason(BpmReasonEnum.APPROVE_TYPE_AUTO_APPROVE.getReason()));
H 1083                     } else if (ObjectUtil.equal(approveType, BpmUserTaskApproveTypeEnum.AUTO_REJECT.getType())) {
f4f940 1084                         getSelf().rejectTask(null, new BpmTaskRejectReqVO()
bb2880 1085                                 .setId(task.getId()).setReason(BpmReasonEnum.APPROVE_TYPE_AUTO_REJECT.getReason()));
H 1086                     }
1087                 }
1088             }
1089
1090         });
e7c126 1091     }
H 1092
1093     /**
bb2880 1094      * 重要补充说明:该方法目前主要有两个情况会调用到:
H 1095      * <p>
1096      * 1. 或签场景 + 审批通过:一个或签有多个审批时,如果 A 审批通过,其它或签 B、C 等任务会被 Flowable 自动删除,此时需要通过该方法更新状态为已取消
1097      * 2. 审批不通过:在 {@link #rejectTask(Long, BpmTaskRejectReqVO)} 不通过时,对于加签的任务,不会被 Flowable 删除,此时需要通过该方法更新状态为已取消
e7c126 1098      */
bb2880 1099     @Override
H 1100     public void processTaskCanceled(String taskId) {
1101         Task task = getTask(taskId);
1102         // 1. 可能只是活动,不是任务,所以查询不到
1103         if (task == null) {
1104             log.error("[updateTaskStatusWhenCanceled][taskId({}) 任务不存在]", taskId);
1105             return;
1106         }
1107
1108         // 2. 更新 task 状态 + 原因
1109         Integer status = (Integer) task.getTaskLocalVariables().get(BpmnVariableConstants.TASK_VARIABLE_STATUS);
1110         if (BpmTaskStatusEnum.isEndStatus(status)) {
1111             log.error("[updateTaskStatusWhenCanceled][taskId({}) 处于结果({}),无需进行更新]", taskId, status);
1112             return;
1113         }
1114         updateTaskStatusAndReason(taskId, BpmTaskStatusEnum.CANCEL.getStatus(), BpmReasonEnum.CANCEL_BY_SYSTEM.getReason());
1115         // 补充说明:由于 Task 被删除成 HistoricTask 后,无法通过 taskService.addComment 添加理由,所以无法存储具体的取消理由
e7c126 1116     }
H 1117
1118     @Override
bb2880 1119     public void processTaskAssigned(Task task) {
H 1120         // 发送通知。在事务提交时,批量执行操作,所以直接查询会无法查询到 ProcessInstance,所以这里是通过监听事务的提交来实现。
1121         TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
1122
f4f940 1123             /**
H 1124              * 特殊情况:部分情况下,TransactionSynchronizationManager 注册 afterCommit 监听时,不会被调用,但是 afterCompletion 可以
1125              * 例如说:第一个 task 就是配置【自动通过】或者【自动拒绝】时
1126              * 参见 <a href="https://gitee.com/zhijiantianya/yudao-cloud/issues/IB7V7Q">issue</a> 反馈
1127              */
bb2880 1128             @Override
f4f940 1129             public void afterCompletion(int transactionStatus) {
H 1130                 // 回滚情况,直接返回
1131                 if (ObjectUtil.equal(transactionStatus, TransactionSynchronization.STATUS_ROLLED_BACK)) {
1132                     return;
1133                 }
1134                 // 特殊情况:第一个 task 【自动通过】时,第二个任务设置审批人时 transactionStatus 会为 STATUS_UNKNOWN,不知道啥原因
1135                 if (ObjectUtil.equal(transactionStatus, TransactionSynchronization.STATUS_UNKNOWN)
1136                         && getTask(task.getId()) == null) {
1137                     return;
1138                 }
bb2880 1139                 if (StrUtil.isEmpty(task.getAssignee())) {
H 1140                     log.error("[processTaskAssigned][taskId({}) 没有分配到负责人]", task.getId());
1141                     return;
1142                 }
1143                 ProcessInstance processInstance = processInstanceService.getProcessInstance(task.getProcessInstanceId());
1144                 if (processInstance == null) {
1145                     log.error("[processTaskAssigned][taskId({}) 没有找到流程实例]", task.getId());
1146                     return;
1147                 }
1148                 // 审批人与提交人为同一人时,根据 BpmUserTaskAssignStartUserHandlerTypeEnum 策略进行处理
1149                 if (StrUtil.equals(task.getAssignee(), processInstance.getStartUserId())) {
1150                     // 判断是否为退回或者驳回:如果是退回或者驳回不走这个策略
1151                     // TODO 芋艿:【优化】未来有没更好的判断方式?!另外,还要考虑清理机制。就是说,下次处理了之后,就移除这个标识
1152                     Boolean returnTaskFlag = runtimeService.getVariable(processInstance.getProcessInstanceId(),
1153                             String.format(PROCESS_INSTANCE_VARIABLE_RETURN_FLAG, task.getTaskDefinitionKey()), Boolean.class);
1154                     if (ObjUtil.notEqual(returnTaskFlag, Boolean.TRUE)) {
1155                         BpmnModel bpmnModel = modelService.getBpmnModelByDefinitionId(processInstance.getProcessDefinitionId());
1156                         if (bpmnModel == null) {
1157                             log.error("[processTaskAssigned][taskId({}) 没有找到流程模型]", task.getId());
1158                             return;
1159                         }
1160                         FlowElement userTaskElement = BpmnModelUtils.getFlowElementById(bpmnModel, task.getTaskDefinitionKey());
1161                         Integer assignStartUserHandlerType = BpmnModelUtils.parseAssignStartUserHandlerType(userTaskElement);
1162
1163                         // 情况一:自动跳过
1164                         if (ObjectUtils.equalsAny(assignStartUserHandlerType,
1165                                 BpmUserTaskAssignStartUserHandlerTypeEnum.SKIP.getType())) {
1166                             getSelf().approveTask(Long.valueOf(task.getAssignee()), new BpmTaskApproveReqVO().setId(task.getId())
1167                                     .setReason(BpmReasonEnum.ASSIGN_START_USER_APPROVE_WHEN_SKIP.getReason()));
1168                             return;
1169                         }
1170                         // 情况二:转交给部门负责人审批
1171                         if (ObjectUtils.equalsAny(assignStartUserHandlerType,
1172                                 BpmUserTaskAssignStartUserHandlerTypeEnum.TRANSFER_DEPT_LEADER.getType())) {
1173                             AdminUserRespDTO startUser = adminUserApi.getUser(Long.valueOf(processInstance.getStartUserId())).getCheckedData();
1174                             Assert.notNull(startUser, "提交人({})信息为空", processInstance.getStartUserId());
1175                             DeptRespDTO dept = startUser.getDeptId() != null ? deptApi.getDept(startUser.getDeptId()).getCheckedData() : null;
1176                             Assert.notNull(dept, "提交人({})部门({})信息为空", processInstance.getStartUserId(), startUser.getDeptId());
1177                             // 找不到部门负责人的情况下,自动审批通过
1178                             // noinspection DataFlowIssue
1179                             if (dept.getLeaderUserId() == null) {
1180                                 getSelf().approveTask(Long.valueOf(task.getAssignee()), new BpmTaskApproveReqVO().setId(task.getId())
1181                                         .setReason(BpmReasonEnum.ASSIGN_START_USER_APPROVE_WHEN_DEPT_LEADER_NOT_FOUND.getReason()));
1182                                 return;
1183                             }
1184                             // 找得到部门负责人的情况下,修改负责人
1185                             if (ObjectUtil.notEqual(dept.getLeaderUserId(), startUser.getId())) {
1186                                 getSelf().transferTask(Long.valueOf(task.getAssignee()), new BpmTaskTransferReqVO()
1187                                         .setId(task.getId()).setAssigneeUserId(dept.getLeaderUserId())
1188                                         .setReason(BpmReasonEnum.ASSIGN_START_USER_TRANSFER_DEPT_LEADER.getReason()));
1189                                 return;
1190                             }
1191                             // 如果部门负责人是自己,还是自己审批吧~
1192                         }
1193                     }
1194                 }
f4f940 1195
bb2880 1196                 AdminUserRespDTO startUser = adminUserApi.getUser(Long.valueOf(processInstance.getStartUserId())).getCheckedData();
H 1197                 messageService.sendMessageWhenTaskAssigned(BpmTaskConvert.INSTANCE.convert(processInstance, startUser, task));
1198             }
1199
1200         });
1201     }
1202
1203     @Override
1204     @Transactional(rollbackFor = Exception.class)
1205     public void processTaskTimeout(String processInstanceId, String taskDefineKey, Integer handlerType) {
1206         ProcessInstance processInstance = processInstanceService.getProcessInstance(processInstanceId);
1207         if (processInstance == null) {
1208             log.error("[processTaskTimeout][processInstanceId({}) 没有找到流程实例]", processInstanceId);
1209             return;
e7c126 1210         }
bb2880 1211         List<Task> taskList = getRunningTaskListByProcessInstanceId(processInstanceId, true, taskDefineKey);
H 1212         // TODO 优化:未来需要考虑加签的情况
1213         if (CollUtil.isEmpty(taskList)) {
1214             log.error("[processTaskTimeout][processInstanceId({}) 定义Key({}) 没有找到任务]", processInstanceId, taskDefineKey);
1215             return;
1216         }
1217
1218         taskList.forEach(task -> FlowableUtils.execute(task.getTenantId(), () -> {
1219             // 情况一:自动提醒
1220             if (Objects.equals(handlerType, BpmUserTaskTimeoutHandlerTypeEnum.REMINDER.getType())) {
1221                 messageService.sendMessageWhenTaskTimeout(new BpmMessageSendWhenTaskTimeoutReqDTO()
1222                         .setProcessInstanceId(processInstanceId).setProcessInstanceName(processInstance.getName())
1223                         .setTaskId(task.getId()).setTaskName(task.getName()).setAssigneeUserId(Long.parseLong(task.getAssignee())));
1224                 return;
1225             }
1226
1227             // 情况二:自动同意
1228             if (Objects.equals(handlerType, BpmUserTaskTimeoutHandlerTypeEnum.APPROVE.getType())) {
1229                 approveTask(Long.parseLong(task.getAssignee()),
1230                         new BpmTaskApproveReqVO().setId(task.getId()).setReason(BpmReasonEnum.TIMEOUT_APPROVE.getReason()));
1231                 return;
1232             }
1233
1234             // 情况三:自动拒绝
1235             if (Objects.equals(handlerType, BpmUserTaskTimeoutHandlerTypeEnum.REJECT.getType())) {
1236                 rejectTask(Long.parseLong(task.getAssignee()),
1237                         new BpmTaskRejectReqVO().setId(task.getId()).setReason(BpmReasonEnum.REJECT_TASK.getReason()));
1238             }
1239         }));
1240     }
1241
1242     /**
1243      * 获得自身的代理对象,解决 AOP 生效问题
1244      *
1245      * @return 自己
1246      */
1247     private BpmTaskServiceImpl getSelf() {
1248         return SpringUtil.getBean(getClass());
e7c126 1249     }
H 1250
1251 }