Commit c0140a41f42aeec328df53df0cc6b1b22db72bf5
1 parent
2c2512e4
【代码优化】工作流:进一步完善 SimpleModelUtils 的注释
【代码优化】工作流:新增 ConditionNodeConvert
Showing
3 changed files
with
201 additions
and
134 deletions
yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/framework/flowable/core/el/VariableConvertByTypeExpressionFunction.java
| @@ -4,9 +4,10 @@ import org.flowable.common.engine.api.variable.VariableContainer; | @@ -4,9 +4,10 @@ import org.flowable.common.engine.api.variable.VariableContainer; | ||
| 4 | import org.flowable.common.engine.impl.el.function.AbstractFlowableVariableExpressionFunction; | 4 | import org.flowable.common.engine.impl.el.function.AbstractFlowableVariableExpressionFunction; |
| 5 | import org.springframework.stereotype.Component; | 5 | import org.springframework.stereotype.Component; |
| 6 | 6 | ||
| 7 | -// TODO @jason:这个自定义转换的原因是啥呀? | ||
| 8 | /** | 7 | /** |
| 9 | - * 根据流程变量 variable 的类型, 转换参数的值 | 8 | + * 根据流程变量 variable 的类型,转换参数的值 |
| 9 | + * | ||
| 10 | + * 目前用于 ConditionNodeConvert 的 buildConditionExpression 方法中 | ||
| 10 | * | 11 | * |
| 11 | * @author jason | 12 | * @author jason |
| 12 | */ | 13 | */ |
| @@ -20,11 +21,12 @@ public class VariableConvertByTypeExpressionFunction extends AbstractFlowableVar | @@ -20,11 +21,12 @@ public class VariableConvertByTypeExpressionFunction extends AbstractFlowableVar | ||
| 20 | public static Object convertByType(VariableContainer variableContainer, String variableName, Object parmaValue) { | 21 | public static Object convertByType(VariableContainer variableContainer, String variableName, Object parmaValue) { |
| 21 | Object variable = variableContainer.getVariable(variableName); | 22 | Object variable = variableContainer.getVariable(variableName); |
| 22 | if (variable != null && parmaValue != null) { | 23 | if (variable != null && parmaValue != null) { |
| 23 | - // 如果值不是字符串类型, 流程变量的类型是字符串。 把值转成字符串 | 24 | + // 如果值不是字符串类型,流程变量的类型是字符串,把值转成字符串 |
| 24 | if (!(parmaValue instanceof String) && variable instanceof String ) { | 25 | if (!(parmaValue instanceof String) && variable instanceof String ) { |
| 25 | return parmaValue.toString(); | 26 | return parmaValue.toString(); |
| 26 | } | 27 | } |
| 27 | } | 28 | } |
| 28 | return parmaValue; | 29 | return parmaValue; |
| 29 | } | 30 | } |
| 31 | + | ||
| 30 | } | 32 | } |
yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/framework/flowable/core/util/SimpleModelUtils.java
| @@ -18,10 +18,6 @@ import org.flowable.bpmn.model.*; | @@ -18,10 +18,6 @@ import org.flowable.bpmn.model.*; | ||
| 18 | 18 | ||
| 19 | import java.util.*; | 19 | import java.util.*; |
| 20 | 20 | ||
| 21 | -import static cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.model.simple.BpmSimpleModelNodeVO.TimeoutHandler; | ||
| 22 | -import static cn.iocoder.yudao.module.bpm.enums.definition.BpmSimpleModelNodeType.*; | ||
| 23 | -import static cn.iocoder.yudao.module.bpm.enums.definition.BpmUserTaskApproveTypeEnum.USER; | ||
| 24 | -import static cn.iocoder.yudao.module.bpm.enums.definition.BpmUserTaskTimeoutHandlerTypeEnum.REMINDER; | ||
| 25 | import static cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmnModelConstants.*; | 21 | import static cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmnModelConstants.*; |
| 26 | import static cn.iocoder.yudao.module.bpm.framework.flowable.core.util.BpmnModelUtils.*; | 22 | import static cn.iocoder.yudao.module.bpm.framework.flowable.core.util.BpmnModelUtils.*; |
| 27 | import static java.util.Arrays.asList; | 23 | import static java.util.Arrays.asList; |
| @@ -33,11 +29,6 @@ import static java.util.Arrays.asList; | @@ -33,11 +29,6 @@ import static java.util.Arrays.asList; | ||
| 33 | */ | 29 | */ |
| 34 | public class SimpleModelUtils { | 30 | public class SimpleModelUtils { |
| 35 | 31 | ||
| 36 | - /** | ||
| 37 | - * 聚合网关节点 Id 后缀 | ||
| 38 | - */ | ||
| 39 | - public static final String JOIN_GATE_WAY_NODE_ID_SUFFIX = "_join"; | ||
| 40 | - | ||
| 41 | private static final Map<BpmSimpleModelNodeType, NodeConvert> NODE_CONVERTS = MapUtil.newHashMap(); | 32 | private static final Map<BpmSimpleModelNodeType, NodeConvert> NODE_CONVERTS = MapUtil.newHashMap(); |
| 42 | 33 | ||
| 43 | static { | 34 | static { |
| @@ -83,9 +74,16 @@ public class SimpleModelUtils { | @@ -83,9 +74,16 @@ public class SimpleModelUtils { | ||
| 83 | } | 74 | } |
| 84 | 75 | ||
| 85 | private static BpmSimpleModelNodeVO buildStartNode() { | 76 | private static BpmSimpleModelNodeVO buildStartNode() { |
| 86 | - return new BpmSimpleModelNodeVO().setId(START_EVENT_NODE_ID).setName(START_EVENT_NODE_NAME).setType(START_NODE.getType()); | 77 | + return new BpmSimpleModelNodeVO().setId(START_EVENT_NODE_ID).setName(START_EVENT_NODE_NAME) |
| 78 | + .setType(BpmSimpleModelNodeType.START_NODE.getType()); | ||
| 87 | } | 79 | } |
| 88 | 80 | ||
| 81 | + /** | ||
| 82 | + * 遍历节点,构建 FlowNode 元素 | ||
| 83 | + * | ||
| 84 | + * @param node SIMPLE 节点 | ||
| 85 | + * @param process BPMN 流程 | ||
| 86 | + */ | ||
| 89 | private static void traverseNodeToBuildFlowNode(BpmSimpleModelNodeVO node, Process process) { | 87 | private static void traverseNodeToBuildFlowNode(BpmSimpleModelNodeVO node, Process process) { |
| 90 | // 1. 判断是否有效节点 | 88 | // 1. 判断是否有效节点 |
| 91 | if (!isValidNode(node)) { | 89 | if (!isValidNode(node)) { |
| @@ -100,18 +98,24 @@ public class SimpleModelUtils { | @@ -100,18 +98,24 @@ public class SimpleModelUtils { | ||
| 100 | List<? extends FlowElement> flowElements = nodeConvert.convertList(node); | 98 | List<? extends FlowElement> flowElements = nodeConvert.convertList(node); |
| 101 | flowElements.forEach(process::addFlowElement); | 99 | flowElements.forEach(process::addFlowElement); |
| 102 | 100 | ||
| 103 | - // 如果不是网关类型的接口, 并且chileNode为空退出 | ||
| 104 | - // 如果是“分支”节点,则递归处理条件 | 101 | + // 3.1 情况一:如果当前是分支节点,并且存在条件节点,则处理每个条件的子节点 |
| 105 | if (BpmSimpleModelNodeType.isBranchNode(node.getType()) | 102 | if (BpmSimpleModelNodeType.isBranchNode(node.getType()) |
| 106 | - && ArrayUtil.isNotEmpty(node.getConditionNodes())) { | 103 | + && CollUtil.isNotEmpty(node.getConditionNodes())) { |
| 104 | + // 注意:这里的 item.getChildNode() 处理的是每个条件的子节点,不是处理条件 | ||
| 107 | node.getConditionNodes().forEach(item -> traverseNodeToBuildFlowNode(item.getChildNode(), process)); | 105 | node.getConditionNodes().forEach(item -> traverseNodeToBuildFlowNode(item.getChildNode(), process)); |
| 108 | } | 106 | } |
| 109 | 107 | ||
| 110 | - // 如果有“子”节点,则递归处理子节点 | 108 | + // 3.2 情况二:如果有“子”节点,则递归处理子节点 |
| 111 | traverseNodeToBuildFlowNode(node.getChildNode(), process); | 109 | traverseNodeToBuildFlowNode(node.getChildNode(), process); |
| 112 | } | 110 | } |
| 113 | 111 | ||
| 114 | - // TODO @芋艿:在优化下这个注释 | 112 | + /** |
| 113 | + * 遍历节点,构建 SequenceFlow 元素 | ||
| 114 | + * | ||
| 115 | + * @param process Bpmn 流程 | ||
| 116 | + * @param node 当前节点 | ||
| 117 | + * @param targetNodeId 目标节点 ID | ||
| 118 | + */ | ||
| 115 | private static void traverseNodeToBuildSequenceFlow(Process process, BpmSimpleModelNodeVO node, String targetNodeId) { | 119 | private static void traverseNodeToBuildSequenceFlow(Process process, BpmSimpleModelNodeVO node, String targetNodeId) { |
| 116 | // 1.1 无效节点返回 | 120 | // 1.1 无效节点返回 |
| 117 | if (!isValidNode(node)) { | 121 | if (!isValidNode(node)) { |
| @@ -123,81 +127,107 @@ public class SimpleModelUtils { | @@ -123,81 +127,107 @@ public class SimpleModelUtils { | ||
| 123 | if (nodeType == BpmSimpleModelNodeType.END_NODE) { | 127 | if (nodeType == BpmSimpleModelNodeType.END_NODE) { |
| 124 | return; | 128 | return; |
| 125 | } | 129 | } |
| 130 | + | ||
| 126 | // 2.1 情况一:普通节点 | 131 | // 2.1 情况一:普通节点 |
| 127 | - BpmSimpleModelNodeVO childNode = node.getChildNode(); | ||
| 128 | if (!BpmSimpleModelNodeType.isBranchNode(node.getType())) { | 132 | if (!BpmSimpleModelNodeType.isBranchNode(node.getType())) { |
| 129 | - if (!isValidNode(childNode)) { | ||
| 130 | - // 2.1.1 普通节点且无孩子节点。分两种情况 | ||
| 131 | - // a.结束节点 b. 条件分支的最后一个节点.与分支节点的孩子节点或聚合节点建立连线。 | ||
| 132 | - if (StrUtil.isNotEmpty(node.getAttachNodeId())) { | ||
| 133 | - // 2.1.1.1 如果有附加节点. 需要先建立和附加节点的连线。再建立附加节点和目标节点的连线 | ||
| 134 | - List<SequenceFlow> sequenceFlows = buildAttachNodeSequenceFlow(node.getId(), node.getAttachNodeId(), targetNodeId); | ||
| 135 | - sequenceFlows.forEach(process::addFlowElement); | ||
| 136 | - } else { | ||
| 137 | - SequenceFlow sequenceFlow = buildBpmnSequenceFlow(node.getId(), targetNodeId, null, null, null); | ||
| 138 | - process.addFlowElement(sequenceFlow); | ||
| 139 | - } | ||
| 140 | - } else { | ||
| 141 | - // 2.1.2 普通节点且有孩子节点。建立连线 | ||
| 142 | - if (StrUtil.isNotEmpty(node.getAttachNodeId())) { | ||
| 143 | - // 2.1.1.2 如果有附加节点. 需要先建立和附加节点的连线。再建立附加节点和目标节点的连线 | ||
| 144 | - List<SequenceFlow> sequenceFlows = buildAttachNodeSequenceFlow(node.getId(), node.getAttachNodeId(), childNode.getId()); | ||
| 145 | - sequenceFlows.forEach(process::addFlowElement); | ||
| 146 | - } else { | ||
| 147 | - SequenceFlow sequenceFlow = buildBpmnSequenceFlow(node.getId(), childNode.getId(), null, null, null); | ||
| 148 | - process.addFlowElement(sequenceFlow); | ||
| 149 | - } | ||
| 150 | - // 递归调用后续节点 | ||
| 151 | - traverseNodeToBuildSequenceFlow(process, childNode, targetNodeId); | ||
| 152 | - } | 133 | + traverseNormalNodeToBuildSequenceFlow(process, node, targetNodeId); |
| 153 | } else { | 134 | } else { |
| 154 | // 2.2 情况二:分支节点 | 135 | // 2.2 情况二:分支节点 |
| 155 | - List<BpmSimpleModelNodeVO> conditionNodes = node.getConditionNodes(); | ||
| 156 | - Assert.notEmpty(conditionNodes, "分支节点的条件节点不能为空"); | ||
| 157 | - // 分支终点节点 Id | ||
| 158 | - String branchEndNodeId = null; | ||
| 159 | - if (nodeType == CONDITION_BRANCH_NODE) { // 条件分支 | ||
| 160 | - // 分两种情况 1. 分支节点有孩子节点为孩子节点 Id 2. 分支节点孩子为无效节点时 (分支嵌套且为分支最后一个节点) 为分支终点节点Id | ||
| 161 | - branchEndNodeId = isValidNode(childNode) ? childNode.getId() : targetNodeId; | ||
| 162 | - } else if (nodeType == PARALLEL_BRANCH_NODE) { // 并行分支 | ||
| 163 | - // 分支节点:分支终点节点 Id 为程序创建的网关集合节点。目前不会从前端传入。 | ||
| 164 | - branchEndNodeId = node.getId() + JOIN_GATE_WAY_NODE_ID_SUFFIX; | 136 | + traverseBranchNodeToBuildSequenceFlow(process, node, targetNodeId); |
| 137 | + } | ||
| 138 | + } | ||
| 139 | + | ||
| 140 | + /** | ||
| 141 | + * 遍历普通(非条件)节点,构建 SequenceFlow 元素 | ||
| 142 | + * | ||
| 143 | + * @param process Bpmn 流程 | ||
| 144 | + * @param node 当前节点 | ||
| 145 | + * @param targetNodeId 目标节点 ID | ||
| 146 | + */ | ||
| 147 | + private static void traverseNormalNodeToBuildSequenceFlow(Process process, BpmSimpleModelNodeVO node, String targetNodeId) { | ||
| 148 | + BpmSimpleModelNodeVO childNode = node.getChildNode(); | ||
| 149 | + // 情况一:有“子”节点,则建立连线 | ||
| 150 | + if (isValidNode(childNode)) { | ||
| 151 | + // TODO @jason:attachNodeId 是不是可以删除啦 | ||
| 152 | + if (StrUtil.isNotEmpty(node.getAttachNodeId())) { | ||
| 153 | + // 2.1.1.2 如果有附加节点. 需要先建立和附加节点的连线。再建立附加节点和目标节点的连线 | ||
| 154 | + List<SequenceFlow> sequenceFlows = buildAttachNodeSequenceFlow(node.getId(), node.getAttachNodeId(), childNode.getId()); | ||
| 155 | + sequenceFlows.forEach(process::addFlowElement); | ||
| 156 | + } else { | ||
| 157 | + SequenceFlow sequenceFlow = buildBpmnSequenceFlow(node.getId(), childNode.getId()); | ||
| 158 | + process.addFlowElement(sequenceFlow); | ||
| 165 | } | 159 | } |
| 166 | - // TODO 包容网关待实现 | ||
| 167 | - Assert.notEmpty(branchEndNodeId, "分支终点节点 Id 不能为空"); | ||
| 168 | - // 3.1 遍历分支节点. 如下情况: | ||
| 169 | - // 分支1、A->B->C->D->E 和 分支2、A->D->E。 A为分支节点, D为A孩子节点 | ||
| 170 | - for (BpmSimpleModelNodeVO item : conditionNodes) { | ||
| 171 | - // TODO @jason:条件分支的情况下,需要分 item 搞的条件,和 conditionNodes 搞的条件 | ||
| 172 | - // @芋艿 这个是啥意思。 这里的 item 的节点类型为 BpmSimpleModelNodeType.CONDITION_NODE 类型,没有对应的 bpmn 的节点。 仅仅用于构建条件表达式。 | ||
| 173 | - Assert.isTrue(Objects.equals(item.getType(), CONDITION_NODE.getType()), "条件节点类型不符合"); | ||
| 174 | - // 构建表达式,可以为空. 并行分支为空 | ||
| 175 | - String conditionExpression = buildConditionExpression(item); | ||
| 176 | - BpmSimpleModelNodeVO nextNodeOnCondition = item.getChildNode(); | ||
| 177 | - // 3.2 分支有后续节点, 分支1: A->B->C->D | ||
| 178 | - if (isValidNode(nextNodeOnCondition)) { | ||
| 179 | - // 3.2.1 建立 A->B | ||
| 180 | - SequenceFlow sequenceFlow = buildBpmnSequenceFlow(node.getId(), nextNodeOnCondition.getId(), | ||
| 181 | - item.getId(), item.getName(), conditionExpression); | ||
| 182 | - process.addFlowElement(sequenceFlow); | ||
| 183 | - // 3.2.2 递归调用后续节点连线。 建立 B->C->D 的连线 | ||
| 184 | - traverseNodeToBuildSequenceFlow(process, nextNodeOnCondition, branchEndNodeId); | ||
| 185 | - } else { | ||
| 186 | - // 3.3 分支无后续节点 建立 A->D | ||
| 187 | - SequenceFlow sequenceFlow = buildBpmnSequenceFlow(node.getId(), branchEndNodeId, | ||
| 188 | - item.getId(), item.getName(), conditionExpression); | ||
| 189 | - process.addFlowElement(sequenceFlow); | ||
| 190 | - } | 160 | + |
| 161 | + // 因为有子节点,递归调用后续子节点 | ||
| 162 | + traverseNodeToBuildSequenceFlow(process, childNode, targetNodeId); | ||
| 163 | + } else { | ||
| 164 | + // 情况二:没有“子节点”,则直接跟 targetNodeId 建立连线。例如说,结束节点、条件分支(分支节点的孩子节点或聚合节点)的最后一个节点 | ||
| 165 | + // TODO @jason:attachNodeId 是不是可以删除啦 | ||
| 166 | + if (StrUtil.isNotEmpty(node.getAttachNodeId())) { | ||
| 167 | + List<SequenceFlow> sequenceFlows = buildAttachNodeSequenceFlow(node.getId(), node.getAttachNodeId(), targetNodeId); | ||
| 168 | + sequenceFlows.forEach(process::addFlowElement); | ||
| 169 | + } else { | ||
| 170 | + SequenceFlow sequenceFlow = buildBpmnSequenceFlow(node.getId(), targetNodeId); | ||
| 171 | + process.addFlowElement(sequenceFlow); | ||
| 191 | } | 172 | } |
| 192 | - // 如果是并行分支。由于是程序创建的聚合网关。需要手工创建聚合网关和下一个节点的连线 | ||
| 193 | - if (nodeType == PARALLEL_BRANCH_NODE) { | ||
| 194 | - String nextNodeId = isValidNode(childNode) ? childNode.getId() : targetNodeId; | ||
| 195 | - SequenceFlow sequenceFlow = buildBpmnSequenceFlow(branchEndNodeId, nextNodeId, null, null, null); | 173 | + } |
| 174 | + } | ||
| 175 | + | ||
| 176 | + /** | ||
| 177 | + * 遍历条件节点,构建 SequenceFlow 元素 | ||
| 178 | + * | ||
| 179 | + * @param process Bpmn 流程 | ||
| 180 | + * @param node 当前节点 | ||
| 181 | + * @param targetNodeId 目标节点 ID | ||
| 182 | + */ | ||
| 183 | + private static void traverseBranchNodeToBuildSequenceFlow(Process process, BpmSimpleModelNodeVO node, String targetNodeId) { | ||
| 184 | + BpmSimpleModelNodeType nodeType = BpmSimpleModelNodeType.valueOf(node.getType()); | ||
| 185 | + BpmSimpleModelNodeVO childNode = node.getChildNode(); | ||
| 186 | + List<BpmSimpleModelNodeVO> conditionNodes = node.getConditionNodes(); | ||
| 187 | + Assert.notEmpty(conditionNodes, "分支节点的条件节点不能为空"); | ||
| 188 | + // 分支终点节点 ID | ||
| 189 | + String branchEndNodeId = null; | ||
| 190 | + if (nodeType == BpmSimpleModelNodeType.CONDITION_BRANCH_NODE) { // 条件分支 | ||
| 191 | + // 分两种情况 1. 分支节点有孩子节点为孩子节点 Id 2. 分支节点孩子为无效节点时 (分支嵌套且为分支最后一个节点) 为分支终点节点 ID | ||
| 192 | + branchEndNodeId = isValidNode(childNode) ? childNode.getId() : targetNodeId; | ||
| 193 | + } else if (nodeType == BpmSimpleModelNodeType.PARALLEL_BRANCH_NODE) { // 并行分支 | ||
| 194 | + // 分支节点:分支终点节点 Id 为程序创建的网关集合节点。目前不会从前端传入。 | ||
| 195 | + branchEndNodeId = ParallelBranchNodeConvert.buildJoinId(node.getId()); | ||
| 196 | + } else if (nodeType == BpmSimpleModelNodeType.INCLUSIVE_BRANCH_NODE) { | ||
| 197 | + // TODO @jason:包容网关待实现 | ||
| 198 | + throw new UnsupportedOperationException("未支持!!"); | ||
| 199 | + } | ||
| 200 | + Assert.notEmpty(branchEndNodeId, "分支终点节点 Id 不能为空"); | ||
| 201 | + | ||
| 202 | + // 3. 遍历分支节点 | ||
| 203 | + // 下面的注释,以如下情况举例子。分支 1:A->B->C->D->E,分支 2:A->D->E。其中,A 为分支节点, D 为 A 孩子节点 | ||
| 204 | + for (BpmSimpleModelNodeVO item : conditionNodes) { | ||
| 205 | + Assert.isTrue(Objects.equals(item.getType(), BpmSimpleModelNodeType.CONDITION_NODE.getType()), | ||
| 206 | + "条件节点类型({})不符合", item.getType()); | ||
| 207 | + BpmSimpleModelNodeVO conditionChildNode = item.getChildNode(); | ||
| 208 | + // 3.1 分支有后续节点。即分支 1: A->B->C->D 的情况 | ||
| 209 | + if (isValidNode(conditionChildNode)) { | ||
| 210 | + // 3.1.1 建立与后续的节点的连线。例如说,建立 A->B 的连线 | ||
| 211 | + SequenceFlow sequenceFlow = ConditionNodeConvert.buildSequenceFlow(node.getId(), conditionChildNode.getId(), item); | ||
| 212 | + process.addFlowElement(sequenceFlow); | ||
| 213 | + // 3.1.2 递归调用后续节点连线。例如说,建立 B->C->D 的连线 | ||
| 214 | + traverseNodeToBuildSequenceFlow(process, conditionChildNode, branchEndNodeId); | ||
| 215 | + } else { | ||
| 216 | + // 3.2 分支没有后续节点。例如说,建立 A->D 的连线 | ||
| 217 | + SequenceFlow sequenceFlow = ConditionNodeConvert.buildSequenceFlow(node.getId(), branchEndNodeId, item); | ||
| 196 | process.addFlowElement(sequenceFlow); | 218 | process.addFlowElement(sequenceFlow); |
| 197 | } | 219 | } |
| 198 | - // 4.递归调用后续节点 继续递归建立 D->E 的连线 | ||
| 199 | - traverseNodeToBuildSequenceFlow(process, childNode, targetNodeId); | ||
| 200 | } | 220 | } |
| 221 | + | ||
| 222 | + // 4. 如果是并行分支,由于是程序创建的聚合网关,需要手工创建聚合网关和下一个节点的连线 | ||
| 223 | + if (nodeType == BpmSimpleModelNodeType.PARALLEL_BRANCH_NODE) { | ||
| 224 | + String nextNodeId = isValidNode(childNode) ? childNode.getId() : targetNodeId; | ||
| 225 | + SequenceFlow sequenceFlow = buildBpmnSequenceFlow(branchEndNodeId, nextNodeId); | ||
| 226 | + process.addFlowElement(sequenceFlow); | ||
| 227 | + } | ||
| 228 | + | ||
| 229 | + // 5. 递归调用后续节点 继续递归。例如说,建立 D->E 的连线 | ||
| 230 | + traverseNodeToBuildSequenceFlow(process, childNode, targetNodeId); | ||
| 201 | } | 231 | } |
| 202 | 232 | ||
| 203 | /** | 233 | /** |
| @@ -213,53 +243,26 @@ public class SimpleModelUtils { | @@ -213,53 +243,26 @@ public class SimpleModelUtils { | ||
| 213 | return CollUtil.newArrayList(sequenceFlow, attachSequenceFlow); | 243 | return CollUtil.newArrayList(sequenceFlow, attachSequenceFlow); |
| 214 | } | 244 | } |
| 215 | 245 | ||
| 216 | - /** | ||
| 217 | - * 构造条件表达式 | ||
| 218 | - * | ||
| 219 | - * @param conditionNode 条件节点 | ||
| 220 | - */ | ||
| 221 | - public static String buildConditionExpression(BpmSimpleModelNodeVO conditionNode) { | ||
| 222 | - BpmSimpleModeConditionType conditionTypeEnum = BpmSimpleModeConditionType.valueOf(conditionNode.getConditionType()); | ||
| 223 | - String conditionExpression = null; | ||
| 224 | - if (conditionTypeEnum == BpmSimpleModeConditionType.EXPRESSION) { | ||
| 225 | - conditionExpression = conditionNode.getConditionExpression(); | ||
| 226 | - } else if (conditionTypeEnum == BpmSimpleModeConditionType.RULE) { | ||
| 227 | - ConditionGroups conditionGroups = conditionNode.getConditionGroups(); | ||
| 228 | - if (conditionGroups != null && CollUtil.isNotEmpty(conditionGroups.getConditions())) { | ||
| 229 | - List<String> strConditionGroups = conditionGroups.getConditions().stream().map(item -> { | ||
| 230 | - if (CollUtil.isNotEmpty(item.getRules())) { | ||
| 231 | - Boolean and = item.getAnd(); | ||
| 232 | - List<String> list = CollectionUtils.convertList(item.getRules(), (rule) -> { | ||
| 233 | - // 如果非数值类型加引号 | ||
| 234 | - String rightSide = NumberUtil.isNumber(rule.getRightSide()) ? rule.getRightSide() : "\"" + rule.getRightSide() + "\""; | ||
| 235 | - return String.format(" %s %s var:convertByType(%s,%s)", rule.getLeftSide(), rule.getOpCode(), rule.getLeftSide(), rightSide); | ||
| 236 | - }); | ||
| 237 | - return "(" + CollUtil.join(list, and ? " && " : " || ") + ")"; | ||
| 238 | - } else { | ||
| 239 | - return ""; | ||
| 240 | - } | ||
| 241 | - }).toList(); | ||
| 242 | - conditionExpression = String.format("${%s}", CollUtil.join(strConditionGroups, conditionGroups.getAnd() ? " && " : " || ")); | ||
| 243 | - } | ||
| 244 | - } | ||
| 245 | - // TODO 待增加其它类型 | ||
| 246 | - return conditionExpression; | 246 | + private static SequenceFlow buildBpmnSequenceFlow(String sourceId, String targetId) { |
| 247 | + return buildBpmnSequenceFlow(sourceId, targetId, null, null, null); | ||
| 247 | } | 248 | } |
| 248 | 249 | ||
| 249 | - private static SequenceFlow buildBpmnSequenceFlow(String sourceId, String targetId, String seqFlowId, String seqName, String conditionExpression) { | 250 | + private static SequenceFlow buildBpmnSequenceFlow(String sourceId, String targetId, |
| 251 | + String sequenceFlowId, String sequenceFlowName, | ||
| 252 | + String conditionExpression) { | ||
| 250 | Assert.notEmpty(sourceId, "sourceId 不能为空"); | 253 | Assert.notEmpty(sourceId, "sourceId 不能为空"); |
| 251 | Assert.notEmpty(targetId, "targetId 不能为空"); | 254 | Assert.notEmpty(targetId, "targetId 不能为空"); |
| 252 | - // TODO @jason:如果 seqFlowId 不存在的时候,是不是要生成一个默认的 seqFlowId? @芋艿: 貌似不需要,Flowable 会默认生成 | ||
| 253 | - // TODO @jason:如果 name 不存在的时候,是不是要生成一个默认的 name? @芋艿: 不需要生成默认的吧? 这个会在流程图展示的, 一般用户填写的。不好生成默认的吧 | 255 | + // TODO @jason:如果 sequenceFlowId 不存在的时候,是不是要生成一个默认的 sequenceFlowId? @芋艿: 貌似不需要,Flowable 会默认生成;TODO @jason:建议还是搞一个,主要是后续好排查问题。 |
| 256 | + // TODO @jason:如果 name 不存在的时候,是不是要生成一个默认的 name? @芋艿: 不需要生成默认的吧? 这个会在流程图展示的, 一般用户填写的。不好生成默认的吧;TODO @jason:建议还是搞一个,主要是后续好排查问题。 | ||
| 254 | SequenceFlow sequenceFlow = new SequenceFlow(sourceId, targetId); | 257 | SequenceFlow sequenceFlow = new SequenceFlow(sourceId, targetId); |
| 255 | - if (StrUtil.isNotEmpty(conditionExpression)) { | ||
| 256 | - sequenceFlow.setConditionExpression(conditionExpression); | 258 | + if (StrUtil.isNotEmpty(sequenceFlowId)) { |
| 259 | + sequenceFlow.setId(sequenceFlowId); | ||
| 257 | } | 260 | } |
| 258 | - if (StrUtil.isNotEmpty(seqFlowId)) { | ||
| 259 | - sequenceFlow.setId(seqFlowId); | 261 | + if (StrUtil.isNotEmpty(sequenceFlowName)) { |
| 262 | + sequenceFlow.setName(sequenceFlowName); | ||
| 260 | } | 263 | } |
| 261 | - if (StrUtil.isNotEmpty(seqName)) { | ||
| 262 | - sequenceFlow.setName(seqName); | 264 | + if (StrUtil.isNotEmpty(conditionExpression)) { |
| 265 | + sequenceFlow.setConditionExpression(conditionExpression); | ||
| 263 | } | 266 | } |
| 264 | return sequenceFlow; | 267 | return sequenceFlow; |
| 265 | } | 268 | } |
| @@ -269,10 +272,11 @@ public class SimpleModelUtils { | @@ -269,10 +272,11 @@ public class SimpleModelUtils { | ||
| 269 | } | 272 | } |
| 270 | 273 | ||
| 271 | public static boolean isSequentialApproveNode(BpmSimpleModelNodeVO node) { | 274 | public static boolean isSequentialApproveNode(BpmSimpleModelNodeVO node) { |
| 272 | - return APPROVE_NODE.getType().equals(node.getType()) | 275 | + return BpmSimpleModelNodeType.APPROVE_NODE.getType().equals(node.getType()) |
| 273 | && BpmUserTaskApproveMethodEnum.SEQUENTIAL.getMethod().equals(node.getApproveMethod()); | 276 | && BpmUserTaskApproveMethodEnum.SEQUENTIAL.getMethod().equals(node.getApproveMethod()); |
| 274 | } | 277 | } |
| 275 | 278 | ||
| 279 | + // TODO @jason:这个方法,是不是要对接 Inclusive 包容分支哈 | ||
| 276 | private static InclusiveGateway convertInclusiveBranchNode(BpmSimpleModelNodeVO node, Boolean isFork) { | 280 | private static InclusiveGateway convertInclusiveBranchNode(BpmSimpleModelNodeVO node, Boolean isFork) { |
| 277 | InclusiveGateway inclusiveGateway = new InclusiveGateway(); | 281 | InclusiveGateway inclusiveGateway = new InclusiveGateway(); |
| 278 | inclusiveGateway.setId(node.getId()); | 282 | inclusiveGateway.setId(node.getId()); |
| @@ -400,7 +404,8 @@ public class SimpleModelUtils { | @@ -400,7 +404,8 @@ public class SimpleModelUtils { | ||
| 400 | * @param timeoutHandler 超时处理器 | 404 | * @param timeoutHandler 超时处理器 |
| 401 | * @return BoundaryEvent 超时事件 | 405 | * @return BoundaryEvent 超时事件 |
| 402 | */ | 406 | */ |
| 403 | - private BoundaryEvent buildUserTaskTimeoutBoundaryEvent(UserTask userTask, TimeoutHandler timeoutHandler) { | 407 | + private BoundaryEvent buildUserTaskTimeoutBoundaryEvent(UserTask userTask, |
| 408 | + BpmSimpleModelNodeVO.TimeoutHandler timeoutHandler) { | ||
| 404 | // 1.1 定时器边界事件 | 409 | // 1.1 定时器边界事件 |
| 405 | BoundaryEvent boundaryEvent = new BoundaryEvent(); | 410 | BoundaryEvent boundaryEvent = new BoundaryEvent(); |
| 406 | boundaryEvent.setId("Event-" + IdUtil.fastUUID()); | 411 | boundaryEvent.setId("Event-" + IdUtil.fastUUID()); |
| @@ -409,7 +414,7 @@ public class SimpleModelUtils { | @@ -409,7 +414,7 @@ public class SimpleModelUtils { | ||
| 409 | // 1.2 定义超时时间、最大提醒次数 | 414 | // 1.2 定义超时时间、最大提醒次数 |
| 410 | TimerEventDefinition eventDefinition = new TimerEventDefinition(); | 415 | TimerEventDefinition eventDefinition = new TimerEventDefinition(); |
| 411 | eventDefinition.setTimeDuration(timeoutHandler.getTimeDuration()); | 416 | eventDefinition.setTimeDuration(timeoutHandler.getTimeDuration()); |
| 412 | - if (Objects.equals(REMINDER.getType(), timeoutHandler.getType()) && | 417 | + if (Objects.equals(BpmUserTaskTimeoutHandlerTypeEnum.REMINDER.getType(), timeoutHandler.getType()) && |
| 413 | timeoutHandler.getMaxRemindCount() != null && timeoutHandler.getMaxRemindCount() > 1) { | 418 | timeoutHandler.getMaxRemindCount() != null && timeoutHandler.getMaxRemindCount() > 1) { |
| 414 | eventDefinition.setTimeCycle(String.format("R%d/%s", | 419 | eventDefinition.setTimeCycle(String.format("R%d/%s", |
| 415 | timeoutHandler.getMaxRemindCount(), timeoutHandler.getTimeDuration())); | 420 | timeoutHandler.getMaxRemindCount(), timeoutHandler.getTimeDuration())); |
| @@ -417,9 +422,9 @@ public class SimpleModelUtils { | @@ -417,9 +422,9 @@ public class SimpleModelUtils { | ||
| 417 | boundaryEvent.addEventDefinition(eventDefinition); | 422 | boundaryEvent.addEventDefinition(eventDefinition); |
| 418 | 423 | ||
| 419 | // 2.1 添加定时器边界事件类型 | 424 | // 2.1 添加定时器边界事件类型 |
| 420 | - addExtensionElement(boundaryEvent, BOUNDARY_EVENT_TYPE, BpmBoundaryEventType.USER_TASK_TIMEOUT.getType().toString()); | 425 | + addExtensionElement(boundaryEvent, BOUNDARY_EVENT_TYPE, BpmBoundaryEventType.USER_TASK_TIMEOUT.getType()); |
| 421 | // 2.2 添加超时执行动作元素 | 426 | // 2.2 添加超时执行动作元素 |
| 422 | - addExtensionElement(boundaryEvent, USER_TASK_TIMEOUT_HANDLER_TYPE, StrUtil.toStringOrNull(timeoutHandler.getType())); | 427 | + addExtensionElement(boundaryEvent, USER_TASK_TIMEOUT_HANDLER_TYPE, timeoutHandler.getType()); |
| 423 | return boundaryEvent; | 428 | return boundaryEvent; |
| 424 | } | 429 | } |
| 425 | 430 | ||
| @@ -429,8 +434,8 @@ public class SimpleModelUtils { | @@ -429,8 +434,8 @@ public class SimpleModelUtils { | ||
| 429 | userTask.setName(node.getName()); | 434 | userTask.setName(node.getName()); |
| 430 | 435 | ||
| 431 | // 如果不是审批人节点,则直接返回 | 436 | // 如果不是审批人节点,则直接返回 |
| 432 | - addExtensionElement(userTask, USER_TASK_APPROVE_TYPE, StrUtil.toStringOrNull(node.getApproveType())); | ||
| 433 | - if (ObjectUtil.notEqual(node.getApproveType(), USER.getType())) { | 437 | + addExtensionElement(userTask, USER_TASK_APPROVE_TYPE, node.getApproveType()); |
| 438 | + if (ObjectUtil.notEqual(node.getApproveType(), BpmUserTaskApproveTypeEnum.USER.getType())) { | ||
| 434 | return userTask; | 439 | return userTask; |
| 435 | } | 440 | } |
| 436 | 441 | ||
| @@ -459,7 +464,7 @@ public class SimpleModelUtils { | @@ -459,7 +464,7 @@ public class SimpleModelUtils { | ||
| 459 | BpmUserTaskApproveMethodEnum approveMethodEnum = BpmUserTaskApproveMethodEnum.valueOf(approveMethod); | 464 | BpmUserTaskApproveMethodEnum approveMethodEnum = BpmUserTaskApproveMethodEnum.valueOf(approveMethod); |
| 460 | Assert.notNull(approveMethodEnum, "审批方式({})不能为空", approveMethodEnum); | 465 | Assert.notNull(approveMethodEnum, "审批方式({})不能为空", approveMethodEnum); |
| 461 | // 添加审批方式的扩展属性 | 466 | // 添加审批方式的扩展属性 |
| 462 | - addExtensionElement(userTask, BpmnModelConstants.USER_TASK_APPROVE_METHOD, approveMethod.toString()); | 467 | + addExtensionElement(userTask, BpmnModelConstants.USER_TASK_APPROVE_METHOD, approveMethod); |
| 463 | if (approveMethodEnum == BpmUserTaskApproveMethodEnum.RANDOM) { | 468 | if (approveMethodEnum == BpmUserTaskApproveMethodEnum.RANDOM) { |
| 464 | // 随机审批,不需要设置多实例属性 | 469 | // 随机审批,不需要设置多实例属性 |
| 465 | return; | 470 | return; |
| @@ -544,7 +549,8 @@ public class SimpleModelUtils { | @@ -544,7 +549,8 @@ public class SimpleModelUtils { | ||
| 544 | 549 | ||
| 545 | // 并行聚合网关由程序创建,前端不需要传入 | 550 | // 并行聚合网关由程序创建,前端不需要传入 |
| 546 | ParallelGateway joinParallelGateway = new ParallelGateway(); | 551 | ParallelGateway joinParallelGateway = new ParallelGateway(); |
| 547 | - joinParallelGateway.setId(node.getId() + JOIN_GATE_WAY_NODE_ID_SUFFIX); | 552 | + joinParallelGateway.setId(buildJoinId(node.getId())); |
| 553 | + // TODO @jason:setName | ||
| 548 | return CollUtil.newArrayList(parallelGateway, joinParallelGateway); | 554 | return CollUtil.newArrayList(parallelGateway, joinParallelGateway); |
| 549 | } | 555 | } |
| 550 | 556 | ||
| @@ -553,6 +559,65 @@ public class SimpleModelUtils { | @@ -553,6 +559,65 @@ public class SimpleModelUtils { | ||
| 553 | return BpmSimpleModelNodeType.PARALLEL_BRANCH_NODE; | 559 | return BpmSimpleModelNodeType.PARALLEL_BRANCH_NODE; |
| 554 | } | 560 | } |
| 555 | 561 | ||
| 562 | + public static String buildJoinId(String id) { | ||
| 563 | + return id + "_join"; | ||
| 564 | + } | ||
| 565 | + | ||
| 566 | + } | ||
| 567 | + | ||
| 568 | + public static class ConditionNodeConvert implements NodeConvert { | ||
| 569 | + | ||
| 570 | + @Override | ||
| 571 | + public List<? extends FlowElement> convertList(BpmSimpleModelNodeVO node) { | ||
| 572 | + // 原因是:正常情况下,它不会被调用到 | ||
| 573 | + throw new UnsupportedOperationException("条件节点不支持转换"); | ||
| 574 | + } | ||
| 575 | + | ||
| 576 | + @Override | ||
| 577 | + public BpmSimpleModelNodeType getType() { | ||
| 578 | + return BpmSimpleModelNodeType.CONDITION_NODE; | ||
| 579 | + } | ||
| 580 | + | ||
| 581 | + public static SequenceFlow buildSequenceFlow(String sourceId, String targetId, | ||
| 582 | + BpmSimpleModelNodeVO node) { | ||
| 583 | + String conditionExpression = buildConditionExpression(node); | ||
| 584 | + return buildBpmnSequenceFlow(sourceId, targetId, node.getId(), node.getName(), conditionExpression); | ||
| 585 | + } | ||
| 586 | + | ||
| 587 | + /** | ||
| 588 | + * 构造条件表达式 | ||
| 589 | + * | ||
| 590 | + * @param node 条件节点 | ||
| 591 | + */ | ||
| 592 | + public static String buildConditionExpression(BpmSimpleModelNodeVO node) { | ||
| 593 | + BpmSimpleModeConditionType conditionTypeEnum = BpmSimpleModeConditionType.valueOf(node.getConditionType()); | ||
| 594 | + if (conditionTypeEnum == BpmSimpleModeConditionType.EXPRESSION) { | ||
| 595 | + return node.getConditionExpression(); | ||
| 596 | + } | ||
| 597 | + if (conditionTypeEnum == BpmSimpleModeConditionType.RULE) { | ||
| 598 | + ConditionGroups conditionGroups = node.getConditionGroups(); | ||
| 599 | + if (conditionGroups == null || CollUtil.isEmpty(conditionGroups.getConditions())) { | ||
| 600 | + return null; | ||
| 601 | + } | ||
| 602 | + List<String> strConditionGroups = CollectionUtils.convertList(conditionGroups.getConditions(), item -> { | ||
| 603 | + if (CollUtil.isEmpty(item.getRules())) { | ||
| 604 | + return ""; | ||
| 605 | + } | ||
| 606 | + // 构造规则表达式 | ||
| 607 | + List<String> list = CollectionUtils.convertList(item.getRules(), (rule) -> { | ||
| 608 | + String rightSide = NumberUtil.isNumber(rule.getRightSide()) ? rule.getRightSide() | ||
| 609 | + : "\"" + rule.getRightSide() + "\""; // 如果非数值类型加引号 | ||
| 610 | + return String.format(" %s %s var:convertByType(%s,%s)", rule.getLeftSide(), rule.getOpCode(), rule.getLeftSide(), rightSide); | ||
| 611 | + }); | ||
| 612 | + // 构造条件组的表达式 | ||
| 613 | + Boolean and = item.getAnd(); | ||
| 614 | + return "(" + CollUtil.join(list, and ? " && " : " || ") + ")"; | ||
| 615 | + }); | ||
| 616 | + return String.format("${%s}", CollUtil.join(strConditionGroups, conditionGroups.getAnd() ? " && " : " || ")); | ||
| 617 | + } | ||
| 618 | + return null; | ||
| 619 | + } | ||
| 620 | + | ||
| 556 | } | 621 | } |
| 557 | 622 | ||
| 558 | } | 623 | } |
yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/task/BpmProcessInstanceServiceImpl.java
| 1 | -package cn.iocoder.yudao.module.bpm.service.task; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.*; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.framework.common.util.collection.SetUtils; import cn.iocoder.yudao.framework.common.util.date.DateUtils; import cn.iocoder.yudao.framework.common.util.json.JsonUtils; import cn.iocoder.yudao.framework.common.util.number.NumberUtils; import cn.iocoder.yudao.framework.common.util.object.BeanUtils; import cn.iocoder.yudao.framework.common.util.object.PageUtils; import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO; import cn.iocoder.yudao.module.bpm.controller.admin.base.user.UserSimpleBaseVO; import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.model.simple.BpmSimpleModelNodeVO; import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.process.BpmProcessDefinitionRespVO; import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.*; import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.BpmApprovalDetailRespVO.ApprovalTaskInfo; import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.BpmTaskRespVO; import cn.iocoder.yudao.module.bpm.convert.definition.BpmProcessDefinitionConvert; import cn.iocoder.yudao.module.bpm.dal.dataobject.definition.BpmProcessDefinitionInfoDO; import cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants; import cn.iocoder.yudao.module.bpm.enums.definition.BpmModelTypeEnum; import cn.iocoder.yudao.module.bpm.enums.definition.BpmSimpleModelNodeType; import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceStatusEnum; import cn.iocoder.yudao.module.bpm.enums.task.BpmReasonEnum; import cn.iocoder.yudao.module.bpm.enums.task.BpmTaskStatusEnum; import cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.BpmTaskCandidateInvoker; import cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.BpmTaskCandidateStrategy; import cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.strategy.BpmTaskCandidateStartUserSelectStrategy; import cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmnVariableConstants; import cn.iocoder.yudao.module.bpm.framework.flowable.core.event.BpmProcessInstanceEventPublisher; import cn.iocoder.yudao.module.bpm.framework.flowable.core.util.BpmnModelUtils; import cn.iocoder.yudao.module.bpm.framework.flowable.core.util.FlowableUtils; import cn.iocoder.yudao.module.bpm.framework.flowable.core.util.SimpleModelUtils; import cn.iocoder.yudao.module.bpm.service.definition.BpmProcessDefinitionService; import cn.iocoder.yudao.module.bpm.service.message.BpmMessageService; import cn.iocoder.yudao.module.bpm.service.task.bo.AlreadyRunApproveNodeRespBO; import cn.iocoder.yudao.module.system.api.dept.DeptApi; import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import jakarta.annotation.Resource; import jakarta.validation.Valid; import lombok.extern.slf4j.Slf4j; import org.flowable.bpmn.constants.BpmnXMLConstants; import org.flowable.bpmn.model.BpmnModel; import org.flowable.bpmn.model.UserTask; import org.flowable.common.engine.api.FlowableException; import org.flowable.common.engine.api.variable.VariableContainer; import org.flowable.engine.HistoryService; import org.flowable.engine.ManagementService; import org.flowable.engine.RuntimeService; import org.flowable.engine.history.HistoricActivityInstance; import org.flowable.engine.history.HistoricProcessInstance; import org.flowable.engine.history.HistoricProcessInstanceQuery; import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.task.api.history.HistoricTaskInstance; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import java.util.*; import java.util.stream.Stream; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*; import static cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.BpmApprovalDetailRespVO.ApprovalNodeInfo; import static cn.iocoder.yudao.module.bpm.convert.task.BpmProcessInstanceConvert.INSTANCE; import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.*; import static cn.iocoder.yudao.module.bpm.enums.definition.BpmSimpleModelNodeType.*; import static cn.iocoder.yudao.module.bpm.enums.definition.BpmUserTaskApproveTypeEnum.USER; import static cn.iocoder.yudao.module.bpm.enums.task.BpmTaskStatusEnum.NOT_START; import static cn.iocoder.yudao.module.bpm.enums.task.BpmTaskStatusEnum.RUNNING; import static cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmTaskCandidateStrategyEnum.START_USER; import static cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmnModelConstants.START_USER_NODE_ID; /** * 流程实例 Service 实现类 * <p> * ProcessDefinition & ProcessInstance & Execution & Task 的关系: * 1. <a href="https://blog.csdn.net/bobozai86/article/details/105210414" /> * <p> * HistoricProcessInstance & ProcessInstance 的关系: * 1. <a href=" https://my.oschina.net/843294669/blog/71902" /> * <p> * 简单来说,前者 = 历史 + 运行中的流程实例,后者仅是运行中的流程实例 * * @author 芋道源码 */ @Service @Validated @Slf4j public class BpmProcessInstanceServiceImpl implements BpmProcessInstanceService { @Resource private RuntimeService runtimeService; @Resource private HistoryService historyService; @Resource private ManagementService managementService; @Resource private BpmActivityService activityService; @Resource private BpmProcessDefinitionService processDefinitionService; @Resource @Lazy // 避免循环依赖 private BpmTaskService taskService; @Resource private BpmMessageService messageService; @Resource private BpmTaskCandidateInvoker bpmTaskCandidateInvoker; @Resource private AdminUserApi adminUserApi; @Resource private DeptApi deptApi; @Resource private BpmProcessInstanceEventPublisher processInstanceEventPublisher; // ========== Query 查询相关方法 ========== @Override public ProcessInstance getProcessInstance(String id) { return runtimeService.createProcessInstanceQuery() .includeProcessVariables() .processInstanceId(id) .singleResult(); } @Override public List<ProcessInstance> getProcessInstances(Set<String> ids) { return runtimeService.createProcessInstanceQuery().processInstanceIds(ids).list(); } @Override public HistoricProcessInstance getHistoricProcessInstance(String id) { return historyService.createHistoricProcessInstanceQuery().processInstanceId(id).includeProcessVariables().singleResult(); } @Override public List<HistoricProcessInstance> getHistoricProcessInstances(Set<String> ids) { return historyService.createHistoricProcessInstanceQuery().processInstanceIds(ids).list(); } @Override public PageResult<HistoricProcessInstance> getProcessInstancePage(Long userId, BpmProcessInstancePageReqVO pageReqVO) { // 通过 BpmProcessInstanceExtDO 表,先查询到对应的分页 HistoricProcessInstanceQuery processInstanceQuery = historyService.createHistoricProcessInstanceQuery() .includeProcessVariables() .processInstanceTenantId(FlowableUtils.getTenantId()) .orderByProcessInstanceStartTime().desc(); if (userId != null) { // 【我的流程】菜单时,需要传递该字段 processInstanceQuery.startedBy(String.valueOf(userId)); } else if (pageReqVO.getStartUserId() != null) { // 【管理流程】菜单时,才会传递该字段 processInstanceQuery.startedBy(String.valueOf(pageReqVO.getStartUserId())); } if (StrUtil.isNotEmpty(pageReqVO.getName())) { processInstanceQuery.processInstanceNameLike("%" + pageReqVO.getName() + "%"); } if (StrUtil.isNotEmpty(pageReqVO.getProcessDefinitionKey())) { processInstanceQuery.processDefinitionKey(pageReqVO.getProcessDefinitionKey()); } if (StrUtil.isNotEmpty(pageReqVO.getCategory())) { processInstanceQuery.processDefinitionCategory(pageReqVO.getCategory()); } if (pageReqVO.getStatus() != null) { processInstanceQuery.variableValueEquals(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, pageReqVO.getStatus()); } if (ArrayUtil.isNotEmpty(pageReqVO.getCreateTime())) { processInstanceQuery.startedAfter(DateUtils.of(pageReqVO.getCreateTime()[0])); processInstanceQuery.startedBefore(DateUtils.of(pageReqVO.getCreateTime()[1])); } // 查询数量 long processInstanceCount = processInstanceQuery.count(); if (processInstanceCount == 0) { return PageResult.empty(processInstanceCount); } // 查询列表 List<HistoricProcessInstance> processInstanceList = processInstanceQuery.listPage(PageUtils.getStart(pageReqVO), pageReqVO.getPageSize()); return new PageResult<>(processInstanceList, processInstanceCount); } private Map<String, String> getFormFieldsPermission(BpmnModel bpmnModel, String activityId, String taskId) { // 1. 获取流程活动编号。流程活动 Id 为空事,从流程任务中获取流程活动 Id if (StrUtil.isEmpty(activityId) && StrUtil.isNotEmpty(taskId)) { activityId = Optional.ofNullable(taskService.getHistoricTask(taskId)) .map(HistoricTaskInstance::getTaskDefinitionKey).orElse(null); } if (StrUtil.isEmpty(activityId)) { return null; } // 2. 从 BpmnModel 中解析表单字段权限 return BpmnModelUtils.parseFormFieldsPermission(bpmnModel, activityId); } @Override public BpmApprovalDetailRespVO getApprovalDetail(Long loginUserId, BpmApprovalDetailReqVO reqVO) { // 1. 设置流程未发起的值 // 1.1 流程状态 Integer processInstanceStatus = BpmProcessInstanceStatusEnum.NOT_START.getStatus(); // 流程未发起的状态 // 1.2 流程定义 Id String processDefinitionId = reqVO.getProcessDefinitionId(); // 流程未发起前端传入 // 1.3. 流程实例 BpmProcessInstanceRespVO processInstanceResp = null; // 流程未发起时为 null // 1.4 以下是用于流程预测的值 Long startUserId = loginUserId; // 流程发起人。流程未发起时,发起人设置成登录人 ProcessInstance runProcessInstance = null; // 正在运行的流程实例,流程未发起时为 null Set<String> runNodeIds = new HashSet<>(); // 已经运行的节点 Ids (BPMN XML 节点 Id) Map<String, ApprovalNodeInfo> runningApprovalNodes = new HashMap<>(); // 正在运行的节点的审批信息 List<ApprovalNodeInfo> approvalNodes = new ArrayList<>(); // 审批节点的信息。流程未发起时为空 // 2 设置流程已发起的值 if (reqVO.getProcessInstanceId() != null) { // 2.1 流程状态 HistoricProcessInstance processInstance = getHistoricProcessInstance(reqVO.getProcessInstanceId()); if (processInstance == null) { throw exception(ErrorCodeConstants.PROCESS_INSTANCE_NOT_EXISTS); } processInstanceStatus = FlowableUtils.getProcessInstanceStatus(processInstance); // 2.2 流程定义 Id processDefinitionId = processInstance.getProcessDefinitionId(); // 2.3 流程实例 AdminUserRespDTO startUser = adminUserApi.getUser(NumberUtils.parseLong(processInstance.getStartUserId())); DeptRespDTO dept = null; if (startUser != null && startUser.getDeptId() != null) { dept = deptApi.getDept(startUser.getDeptId()); } processInstanceResp = INSTANCE.buildProcessInstance(processInstance, null, null, startUser, dept); // 2.4 以下是用于流程预测的值 startUserId = Long.valueOf(processInstance.getStartUserId()); // 流程发起人 runProcessInstance = getProcessInstance(processInstance.getId()); // 正在运行的流程实例 List<HistoricActivityInstance> historicActivityList = activityService.getActivityListByProcessInstanceId(processInstance.getId()); AlreadyRunApproveNodeRespBO respBO = buildAlreadyRunApproveNodes(processInstance.getId(), processInstanceStatus, historicActivityList); runNodeIds = respBO.getRunNodeIds(); // 已经运行的节点 Ids approvalNodes = respBO.getApproveNodes(); // // 获取已运行节点的审批的信息 runningApprovalNodes = respBO.getRunningApprovalNodes(); // 正在运行的节点的审批信息 } // 3. 流程定义 ProcessDefinition processDefinition = processDefinitionService.getProcessDefinition(processDefinitionId); BpmProcessDefinitionInfoDO processDefinitionInfo = processDefinitionService.getProcessDefinitionInfo(processDefinitionId); BpmnModel bpmnModel = processDefinitionService.getProcessDefinitionBpmnModel(processDefinitionId); List<UserTask> userTaskList = BpmTaskCandidateStartUserSelectStrategy.getStartUserSelectUserTaskList(bpmnModel); BpmProcessDefinitionRespVO definitionResp = BpmProcessDefinitionConvert.INSTANCE.buildProcessDefinition( processDefinition,null,processDefinitionInfo,null, null,bpmnModel,userTaskList ); // 4. 表单权限 Map<String, String> formFieldsPermission = getFormFieldsPermission(bpmnModel, reqVO.getActivityId(), reqVO.getTaskId()); // 5 .登录用户的待办任务 BpmTaskRespVO todoTask = taskService.getFirstTodoTask(loginUserId, reqVO.getProcessInstanceId()); // 流程已经结束,直接 return,无需预测 if (BpmProcessInstanceStatusEnum.isProcessEndStatus(processInstanceStatus)) { return new BpmApprovalDetailRespVO().setStatus(processInstanceStatus) .setProcessDefinition(definitionResp).setProcessInstance(processInstanceResp) .setFormFieldsPermission(formFieldsPermission) .setTodoTask(todoTask).setApproveNodes(approvalNodes); } // 6,预测未运行节点的审批信息。需要区分 BPMN 设计器 和 SIMPLE 设计器 // 6.1 情况一:仿钉钉流程设计器 if (Objects.equals(BpmModelTypeEnum.SIMPLE.getType(), processDefinitionInfo.getModelType())) { BpmSimpleModelNodeVO simpleModel = JsonUtils.parseObject(processDefinitionInfo.getSimpleModel(), BpmSimpleModelNodeVO.class); List<ApprovalNodeInfo> notRunApproveNodes = new ArrayList<>(); traverseSimpleModelNodeToBuildNotRunApproveNodes( startUserId, runProcessInstance, simpleModel, runNodeIds, runningApprovalNodes, notRunApproveNodes); approvalNodes.addAll(notRunApproveNodes); // 6.2 情况二:BPMN 流程设计器 } else if (Objects.equals(BpmModelTypeEnum.BPMN.getType(), processDefinitionInfo.getModelType())) { // TODO 芋艿:需要把 start 节点加出来 // TODO Bpmn 设计器,构建未运行节点的审批信息;未完全实现 } return new BpmApprovalDetailRespVO().setStatus(processInstanceStatus) .setProcessDefinition(definitionResp).setProcessInstance(processInstanceResp) .setFormFieldsPermission(formFieldsPermission) .setTodoTask(todoTask).setApproveNodes(approvalNodes); } /** * 遍历 SIMPLE 设计器模型 构建未运行节点的审批信息 * * @param startUserId 流程发起人编号 * @param processInstance 流程实例 * @param simpleModelNode SIMPLE 设计器模型 * @param runNodeIds 已经运行节点的 Ids * @param runningApprovalNodes 正在运行的节点的审批信息 * @param approveNodeList 未运行节点的审批信息列表 */ private void traverseSimpleModelNodeToBuildNotRunApproveNodes(Long startUserId, ProcessInstance processInstance, BpmSimpleModelNodeVO simpleModelNode, Set<String> runNodeIds, Map<String, ApprovalNodeInfo> runningApprovalNodes, List<ApprovalNodeInfo> approveNodeList) { if (!SimpleModelUtils.isValidNode(simpleModelNode)) { return; } buildNotRunApproveNodes(startUserId, processInstance, simpleModelNode, runNodeIds, runningApprovalNodes, approveNodeList); // 如果有子节点递归遍历子节点 traverseSimpleModelNodeToBuildNotRunApproveNodes( startUserId, processInstance, simpleModelNode.getChildNode(), runNodeIds, runningApprovalNodes, approveNodeList); } private void buildNotRunApproveNodes(Long startUserId, ProcessInstance processInstance, BpmSimpleModelNodeVO node, Set<String> runNodeIds, Map<String, ApprovalNodeInfo> runningApprovalNodes, List<ApprovalNodeInfo> approveNodeList) { // 情况一:节点未运行:需要进行预测 if (!runNodeIds.contains(node.getId())) { // 1. 对需要人工审批的审批节点,进行预测 if (APPROVE_NODE.getType().equals(node.getType()) && USER.getType().equals(node.getApproveType()) || START_USER_NODE.getType().equals(node.getType())) { ApprovalNodeInfo approvalNodeInfo = new ApprovalNodeInfo().setNodeType(node.getType()) .setName(node.getName()).setStatus(NOT_START.getStatus()); Integer candidateStrategy = START_USER_NODE.getType().equals(node.getType()) ? START_USER.getStrategy() : node.getCandidateStrategy(); approvalNodeInfo.setCandidateUsers( getNotRunTaskCandidateUserList(startUserId, processInstance, node.getId(), candidateStrategy, node.getCandidateParam())); approveNodeList.add(approvalNodeInfo); // 2. 对分支节点,进行预测 } else if (BpmSimpleModelNodeType.isBranchNode(node.getType())) { // 并行分支,不用预测条件。所有分支都需要遍历 if (PARALLEL_BRANCH_NODE.getType().equals(node.getType())) { node.getConditionNodes().forEach(conditionNode -> traverseSimpleModelNodeToBuildNotRunApproveNodes(startUserId, processInstance, conditionNode.getChildNode() , runNodeIds, runningApprovalNodes, approveNodeList)); } else if (CONDITION_BRANCH_NODE.getType().equals(node.getType())) { for (BpmSimpleModelNodeVO conditionNode : node.getConditionNodes()) { // 满足一个条件, 遍历该分支并 if ((processInstance != null && evalConditionExpress(processInstance, SimpleModelUtils.buildConditionExpression(conditionNode))) // 预测条件表达式的值 || BooleanUtil.isTrue(conditionNode.getDefaultFlow())) { // 是否默认的序列 traverseSimpleModelNodeToBuildNotRunApproveNodes(startUserId, processInstance, conditionNode.getChildNode(), runNodeIds, runningApprovalNodes, approveNodeList); break; } } } // TODO 包容分支待实现 // 3. 结束节点 } else if (END_NODE.getType().equals(node.getType())) { ApprovalNodeInfo nodeProgress = new ApprovalNodeInfo(); nodeProgress.setNodeType(node.getType()); nodeProgress.setName(node.getName()); nodeProgress.setStatus(NOT_START.getStatus()); approveNodeList.add(nodeProgress); } } else { // 情况二:节点已经运行 // 如果是分支节点,需要检查分支节点的运行情况 if (BpmSimpleModelNodeType.isBranchNode(node.getType()) && ArrayUtil.isNotEmpty(node.getConditionNodes())) { node.getConditionNodes().forEach(conditionNode -> { // 只有运行的条件,才需要遍历 if (runNodeIds.contains(conditionNode.getId())) { traverseSimpleModelNodeToBuildNotRunApproveNodes(startUserId, processInstance, conditionNode.getChildNode() , runNodeIds, runningApprovalNodes, approveNodeList); } }); // 如果是依次审批, 需要加其它未审批候选人 } else if (SimpleModelUtils.isSequentialApproveNode(node) && runningApprovalNodes.containsKey(node.getId())) { ApprovalNodeInfo approvalNodeInfo = runningApprovalNodes.get(node.getId()); List<UserSimpleBaseVO> candidateUserList = getNotRunTaskCandidateUserList( startUserId, processInstance, node.getId(), node.getCandidateStrategy(), node.getCandidateParam()); // TODO @jason:这里的逻辑,可能可以简化成,直接拿已经审批过的人的 userId 集合,从 candidateUserList remove 下。一方面简单一点,方面 calculateUsers 返回的是 set,目前不是很有序。 // TODO @芋艿 已经审批过的人的 userId 集合。不知道如何获取,不知道有啥好方法没。 如果取这个节点已经完成的审批任务。 是不是有可能包含回退的情况。就不太对了。 另外 candidateUserList 是按返回 set 遍历顺序返回的。和 set 的顺序是一致的。就不会有问题了 ApprovalTaskInfo approvalTaskInfo = CollUtil.getFirst(approvalNodeInfo.getTasks()); Long currentAssignedUserId = null; if (approvalTaskInfo != null && approvalTaskInfo.getAssigneeUser() != null) { currentAssignedUserId = approvalTaskInfo.getAssigneeUser().getId(); } // 找到当前审批人在候选人列表的位置 int index = 0; for (UserSimpleBaseVO user : candidateUserList) { if (user.getId().equals(currentAssignedUserId)) { break; } index++; } // 截取当前审批人位置后面的候选人, 不包含当前审批人 approvalNodeInfo.setCandidateUsers(CollUtil.sub(candidateUserList, ++index, candidateUserList.size())); } } } /** * 从已经运行活动节点构建的审批信息列表 * * @param processInstanceId 流程实例 Id * @param processInstanceStatus 流程实例状态 * @param historicActivityList 已经运行活动 */ private AlreadyRunApproveNodeRespBO buildAlreadyRunApproveNodes(String processInstanceId, Integer processInstanceStatus, List<HistoricActivityInstance> historicActivityList) { // 1.1 获取待处理活动:只有 "userTask" 和 "endEvent" 需要处理 List<HistoricActivityInstance> pendingActivityNodes = filterList(historicActivityList, item -> BpmSimpleModelNodeType.isRecordNode(item.getActivityType())); // 1.2 已运行节点的 activityId Set<String> runNodeIds = convertSet(historicActivityList, HistoricActivityInstance::getActivityId); // 2.1 获取已运行的任务(包括运行中的任务) List<HistoricTaskInstance> taskList = taskService.getTaskListByProcessInstanceId(processInstanceId, false); Map<String, HistoricTaskInstance> taskMap = convertMap(taskList, HistoricTaskInstance::getId); // 2.2 获取加签的任务 Map<String, List<HistoricTaskInstance>> addSignTaskMap = convertMultiMap( filterList(taskList, task -> StrUtil.isNotEmpty(task.getParentTaskId())), HistoricTaskInstance::getParentTaskId); // 3.1 获取节点的用户信息 Set<Long> userIds = CollectionUtils.convertSetByFlatMap(pendingActivityNodes, activity -> { if (BPMN_USER_TASK_TYPE.equals(activity.getActivityType())) { HistoricTaskInstance task = taskMap.get(activity.getTaskId()); Set<Long> taskUsers = CollUtil.newHashSet(); CollUtil.addIfAbsent(taskUsers, NumberUtil.parseLong(task.getAssignee(), null)); CollUtil.addIfAbsent(taskUsers, NumberUtil.parseLong(task.getOwner(), null)); List<HistoricTaskInstance> addSignTasks = addSignTaskMap.get(activity.getTaskId()); if (CollUtil.isNotEmpty(addSignTasks)) { addSignTasks.forEach(item -> { CollUtil.addIfAbsent(taskUsers, NumberUtil.parseLong(item.getAssignee(), null)); CollUtil.addIfAbsent(taskUsers, NumberUtil.parseLong(item.getOwner(), null)); }); } return taskUsers.stream(); } else { return Stream.empty(); } }); Map<Long, AdminUserRespDTO> userMap = convertMap(adminUserApi.getUserList(userIds), AdminUserRespDTO::getId); // 3.2 已经结束的任务转换为审批信息 final Multimap<String, HistoricActivityInstance> runningTask = ArrayListMultimap.create(); // 运行中的任务 List<ApprovalNodeInfo> approvalNodeList = convertList(pendingActivityNodes, activity -> { ApprovalNodeInfo approvalNodeInfo = new ApprovalNodeInfo().setId(activity.getId()).setName(activity.getActivityName()) .setStartTime(DateUtils.of(activity.getStartTime())).setEndTime(DateUtils.of(activity.getEndTime())); if (BPMN_USER_TASK_TYPE.equals(activity.getActivityType())) { // 用户任务 // nodeType approvalNodeInfo.setNodeType(START_USER_NODE_ID.equals(activity.getActivityId()) ? START_USER_NODE.getType() : APPROVE_NODE.getType()); // status HistoricTaskInstance task = taskMap.get(activity.getTaskId()); Integer taskStatus = FlowableUtils.getTaskStatus(task); // 运行中的任务, 会签,或签任务聚合在一起。 if (!BpmTaskStatusEnum.isEndStatus(taskStatus)) { runningTask.put(activity.getActivityId(), activity); return null; } // tasks ApprovalTaskInfo approveTask = convertApproveTaskInfo(task, userMap); List<ApprovalTaskInfo> approveTasks = CollUtil.newArrayList(approveTask); List<HistoricTaskInstance> addSignTasks = addSignTaskMap.get(activity.getTaskId()); if (CollUtil.isNotEmpty(addSignTasks)) { // 处理加签任务 approveTasks.addAll(convertList(addSignTasks, item -> convertApproveTaskInfo(item, userMap))); } approvalNodeInfo.setStatus(taskStatus); approvalNodeInfo.setTasks(approveTasks); } else if (END_NODE.getBpmnType().equals(activity.getActivityType())) { approvalNodeInfo.setNodeType(END_NODE.getType()); approvalNodeInfo.setStatus(processInstanceStatus); } return approvalNodeInfo; }); // 3.3 运行中的任务转换为审批信息。 final Map<String, ApprovalNodeInfo> runningApprovalNodes = new HashMap<>(); // 正在运行节点的审批信息 runningTask.asMap().forEach((activityId, activities) -> { if (CollUtil.isNotEmpty(activities)) { ApprovalNodeInfo approvalNodeInfo = new ApprovalNodeInfo(); approvalNodeInfo.setNodeType(APPROVE_NODE.getType()); approvalNodeInfo.setStatus(RUNNING.getStatus()); List<ApprovalTaskInfo> approveTasks = CollUtil.newArrayList(); int i = 0; for (HistoricActivityInstance activity : activities) { HistoricTaskInstance task = taskMap.get(activity.getTaskId()); // 取第一个任务, 会签/或签的任务。开始时间相同的 if (i == 0) { approvalNodeInfo.setId(activity.getId()).setName(activity.getActivityName()). setStartTime(DateUtils.of(activity.getStartTime())); } // tasks ApprovalTaskInfo approveTask = convertApproveTaskInfo(task, userMap); approveTasks.add(approveTask); List<HistoricTaskInstance> addSignTasks = addSignTaskMap.get(activity.getTaskId()); if (CollUtil.isNotEmpty(addSignTasks)) { // 处理加签任务 approveTasks.addAll(convertList(addSignTasks, item -> convertApproveTaskInfo(item, userMap))); } i++; } approvalNodeInfo.setTasks(approveTasks); approvalNodeList.add(approvalNodeInfo); runningApprovalNodes.put(activityId, approvalNodeInfo); } }); return new AlreadyRunApproveNodeRespBO().setApproveNodes(approvalNodeList).setRunNodeIds(runNodeIds) .setRunningApprovalNodes(runningApprovalNodes); } private ApprovalTaskInfo convertApproveTaskInfo(HistoricTaskInstance task, Map<Long, AdminUserRespDTO> userMap) { if (task == null) { return null; } ApprovalTaskInfo approveTask = BeanUtils.toBean(task, ApprovalTaskInfo.class); approveTask.setStatus(FlowableUtils.getTaskStatus(task)).setReason(FlowableUtils.getTaskReason(task)); Long taskAssignee = NumberUtil.parseLong(task.getAssignee(), null); if (taskAssignee != null) { approveTask.setAssigneeUser(BeanUtils.toBean(userMap.get(taskAssignee), UserSimpleBaseVO.class)); } Long taskOwner = NumberUtil.parseLong(task.getOwner(), null); if (taskOwner != null) { approveTask.setOwnerUser(BeanUtils.toBean(userMap.get(taskOwner), UserSimpleBaseVO.class)); } return approveTask; } private List<UserSimpleBaseVO> getNotRunTaskCandidateUserList(Long startUserId, ProcessInstance processInstance, String activityId, Integer candidateStrategy, String candidateParam) { BpmTaskCandidateStrategy taskCandidateStrategy = bpmTaskCandidateInvoker.getCandidateStrategy(candidateStrategy); Set<Long> userIds = taskCandidateStrategy.calculateUsers(startUserId, processInstance, activityId, candidateParam); Map<Long, AdminUserRespDTO> adminUserMap = adminUserApi.getUserMap(userIds); // 需要按照候选人的顺序返回。原因是,依次审批需要按顺序展示用户 return convertList(userIds, userId -> BeanUtils.toBean(adminUserMap.get(userId), UserSimpleBaseVO.class)); } /** * 计算条件表达式的值 * * @param processInstance 流程实例 * @param express 条件表达式 */ private Boolean evalConditionExpress(ProcessInstance processInstance, String express) { if (express == null) { return Boolean.FALSE; } Object result = managementService.executeCommand(context -> { try { return FlowableUtils.getExpressionValue((VariableContainer) processInstance, express); } catch (FlowableException ex) { log.error("[evalConditionExpress][条件表达式({}) 解析报错", express, ex); return Boolean.FALSE; } }); return Boolean.TRUE.equals(result); } @Override public BpmProcessInstanceBpmnModelViewRespVO getProcessInstanceBpmnModelView(String id) { // 1.1 获得流程实例 HistoricProcessInstance processInstance = getHistoricProcessInstance(id); if (processInstance == null) { return null; } // 1.2 获得流程定义 BpmnModel bpmnModel = processDefinitionService.getProcessDefinitionBpmnModel(processInstance.getProcessDefinitionId()); if (bpmnModel == null) { return null; } // 1.3 获得流程实例对应的活动实例列表 + 任务列表 List<HistoricActivityInstance> activityInstances = getActivityListByProcessInstanceId(id); List<HistoricTaskInstance> taskInstances = taskService.getTaskListByProcessInstanceId(id, true); // 1.4 查询关联用户、部门信息 Set<Long> userIds = SetUtils.asSet(Long.valueOf(processInstance.getStartUserId())); taskInstances.forEach(task -> { CollUtil.addIfAbsent(userIds, NumberUtils.parseLong((task.getAssignee()))); CollUtil.addIfAbsent(userIds, NumberUtils.parseLong((task.getOwner()))); }); Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(userIds); Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap( convertSet(userMap.values(), AdminUserRespDTO::getDeptId)); // 2.1 拼接进度信息 Set<String> unfinishedTaskActivityIds = convertSet(activityInstances, HistoricActivityInstance::getActivityId, activityInstance -> activityInstance.getEndTime() == null); Set<String> finishedTaskActivityIds = convertSet(activityInstances, HistoricActivityInstance::getActivityId, activityInstance -> activityInstance.getEndTime() != null && ObjectUtil.notEqual(activityInstance.getActivityType(), BpmnXMLConstants.ELEMENT_SEQUENCE_FLOW)); Set<String> finishedSequenceFlowActivityIds = convertSet(activityInstances, HistoricActivityInstance::getActivityId, activityInstance -> activityInstance.getEndTime() != null && ObjectUtil.equals(activityInstance.getActivityType(), BpmnXMLConstants.ELEMENT_SEQUENCE_FLOW)); // 特殊:会签情况下,会有部分已完成(审批)、部分未完成(待审批),此时需要 finishedTaskActivityIds 移除掉 unfinishedTaskActivityIds.removeAll(finishedTaskActivityIds); // 特殊:如果流程实例被拒绝,则需要计算是哪个活动节点。 // 注意,只取最后一个。因为会存在多次拒绝的情况,拒绝驳回到指定节点 Set<String> rejectTaskActivityIds = CollUtil.newHashSet(); if (BpmProcessInstanceStatusEnum.isRejectStatus(FlowableUtils.getProcessInstanceStatus(processInstance))) { taskInstances.stream() .filter(task -> BpmTaskStatusEnum.isRejectStatus(FlowableUtils.getTaskStatus(task))) .max(Comparator.comparing(HistoricTaskInstance::getEndTime)) .ifPresent(reject -> rejectTaskActivityIds.add(reject.getTaskDefinitionKey())); finishedTaskActivityIds.removeAll(rejectTaskActivityIds); } // 2.2 拼接基础信息 return INSTANCE.buildProcessInstanceBpmnModelView(processInstance, taskInstances, bpmnModel, unfinishedTaskActivityIds, finishedTaskActivityIds, finishedSequenceFlowActivityIds, rejectTaskActivityIds, userMap, deptMap); } private List<HistoricActivityInstance> getActivityListByProcessInstanceId(String id) { return historyService.createHistoricActivityInstanceQuery().processInstanceId(id) .orderByHistoricActivityInstanceStartTime().asc().list(); } // ========== Update 写入相关方法 ========== @Override @Transactional(rollbackFor = Exception.class) public String createProcessInstance(Long userId, @Valid BpmProcessInstanceCreateReqVO createReqVO) { // 获得流程定义 ProcessDefinition definition = processDefinitionService.getProcessDefinition(createReqVO.getProcessDefinitionId()); // 发起流程 return createProcessInstance0(userId, definition, createReqVO.getVariables(), null, createReqVO.getStartUserSelectAssignees()); } @Override public String createProcessInstance(Long userId, @Valid BpmProcessInstanceCreateReqDTO createReqDTO) { // 获得流程定义 ProcessDefinition definition = processDefinitionService.getActiveProcessDefinition(createReqDTO.getProcessDefinitionKey()); // 发起流程 return createProcessInstance0(userId, definition, createReqDTO.getVariables(), createReqDTO.getBusinessKey(), createReqDTO.getStartUserSelectAssignees()); } private String createProcessInstance0(Long userId, ProcessDefinition definition, Map<String, Object> variables, String businessKey, Map<String, List<Long>> startUserSelectAssignees) { // 1.1 校验流程定义 if (definition == null) { throw exception(PROCESS_DEFINITION_NOT_EXISTS); } if (definition.isSuspended()) { throw exception(PROCESS_DEFINITION_IS_SUSPENDED); } BpmProcessDefinitionInfoDO processDefinitionInfo = processDefinitionService.getProcessDefinitionInfo(definition.getId()); if (processDefinitionInfo == null) { throw exception(PROCESS_DEFINITION_NOT_EXISTS); } // 1.2 校验是否能够发起 if (!processDefinitionService.canUserStartProcessDefinition(processDefinitionInfo, userId)) { throw exception(PROCESS_INSTANCE_START_USER_CAN_START); } // 1.3 校验发起人自选审批人 validateStartUserSelectAssignees(definition, startUserSelectAssignees); // 2. 创建流程实例 if (variables == null) { variables = new HashMap<>(); } FlowableUtils.filterProcessInstanceFormVariable(variables); // 过滤一下,避免 ProcessInstance 系统级的变量被占用 variables.put(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, // 流程实例状态:审批中 BpmProcessInstanceStatusEnum.RUNNING.getStatus()); if (CollUtil.isNotEmpty(startUserSelectAssignees)) { variables.put(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_START_USER_SELECT_ASSIGNEES, startUserSelectAssignees); } ProcessInstance instance = runtimeService.createProcessInstanceBuilder() .processDefinitionId(definition.getId()) .businessKey(businessKey) .name(definition.getName().trim()) .variables(variables) .start(); return instance.getId(); } private void validateStartUserSelectAssignees(ProcessDefinition definition, Map<String, List<Long>> startUserSelectAssignees) { // 1. 获得发起人自选审批人的 UserTask 列表 BpmnModel bpmnModel = processDefinitionService.getProcessDefinitionBpmnModel(definition.getId()); List<UserTask> userTaskList = BpmTaskCandidateStartUserSelectStrategy.getStartUserSelectUserTaskList(bpmnModel); if (CollUtil.isEmpty(userTaskList)) { return; } // 2. 校验发起人自选审批人的 UserTask 是否都配置了 userTaskList.forEach(userTask -> { List<Long> assignees = startUserSelectAssignees != null ? startUserSelectAssignees.get(userTask.getId()) : null; if (CollUtil.isEmpty(assignees)) { throw exception(PROCESS_INSTANCE_START_USER_SELECT_ASSIGNEES_NOT_CONFIG, userTask.getName()); } Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(assignees); assignees.forEach(assignee -> { if (userMap.get(assignee) == null) { throw exception(PROCESS_INSTANCE_START_USER_SELECT_ASSIGNEES_NOT_EXISTS, userTask.getName(), assignee); } }); }); } @Override public void cancelProcessInstanceByStartUser(Long userId, @Valid BpmProcessInstanceCancelReqVO cancelReqVO) { // 1.1 校验流程实例存在 ProcessInstance instance = getProcessInstance(cancelReqVO.getId()); if (instance == null) { throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS); } // 1.2 只能取消自己的 if (!Objects.equals(instance.getStartUserId(), String.valueOf(userId))) { throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_SELF); } // 2. 取消流程 updateProcessInstanceCancel(cancelReqVO.getId(), BpmReasonEnum.CANCEL_PROCESS_INSTANCE_BY_START_USER.format(cancelReqVO.getReason())); } @Override public void cancelProcessInstanceByAdmin(Long userId, BpmProcessInstanceCancelReqVO cancelReqVO) { // 1.1 校验流程实例存在 ProcessInstance instance = getProcessInstance(cancelReqVO.getId()); if (instance == null) { throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS); } // 2. 取消流程 AdminUserRespDTO user = adminUserApi.getUser(userId); updateProcessInstanceCancel(cancelReqVO.getId(), BpmReasonEnum.CANCEL_PROCESS_INSTANCE_BY_ADMIN.format(user.getNickname(), cancelReqVO.getReason())); } private void updateProcessInstanceCancel(String id, String reason) { // 1. 更新流程实例 status runtimeService.setVariable(id, BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, BpmProcessInstanceStatusEnum.CANCEL.getStatus()); runtimeService.setVariable(id, BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_REASON, reason); // 2. 结束流程 taskService.moveTaskToEnd(id); } @Override public void updateProcessInstanceReject(ProcessInstance processInstance, String reason) { runtimeService.setVariable(processInstance.getProcessInstanceId(), BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, BpmProcessInstanceStatusEnum.REJECT.getStatus()); runtimeService.setVariable(processInstance.getProcessInstanceId(), BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_REASON, BpmReasonEnum.REJECT_TASK.format(reason)); } // ========== Event 事件相关方法 ========== @Override public void processProcessInstanceCompleted(ProcessInstance instance) { // 注意:需要基于 instance 设置租户编号,避免 Flowable 内部异步时,丢失租户编号 FlowableUtils.execute(instance.getTenantId(), () -> { // 1.1 获取当前状态 Integer status = (Integer) instance.getProcessVariables().get(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS); String reason = (String) instance.getProcessVariables().get(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_REASON); // 1.2 当流程状态还是审批状态中,说明审批通过了,则变更下它的状态 // 为什么这么处理?因为流程完成,并且完成了,说明审批通过了 if (Objects.equals(status, BpmProcessInstanceStatusEnum.RUNNING.getStatus())) { status = BpmProcessInstanceStatusEnum.APPROVE.getStatus(); runtimeService.setVariable(instance.getId(), BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, status); } // 2. 发送对应的消息通知 if (Objects.equals(status, BpmProcessInstanceStatusEnum.APPROVE.getStatus())) { messageService.sendMessageWhenProcessInstanceApprove(INSTANCE.buildProcessInstanceApproveMessage(instance)); } else if (Objects.equals(status, BpmProcessInstanceStatusEnum.REJECT.getStatus())) { messageService.sendMessageWhenProcessInstanceReject( INSTANCE.buildProcessInstanceRejectMessage(instance, reason)); } // 3. 发送流程实例的状态事件 processInstanceEventPublisher.sendProcessInstanceResultEvent( INSTANCE.buildProcessInstanceStatusEvent(this, instance, status)); }); } } | ||
| 2 | \ No newline at end of file | 1 | \ No newline at end of file |
| 2 | +package cn.iocoder.yudao.module.bpm.service.task; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.*; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.framework.common.util.collection.SetUtils; import cn.iocoder.yudao.framework.common.util.date.DateUtils; import cn.iocoder.yudao.framework.common.util.json.JsonUtils; import cn.iocoder.yudao.framework.common.util.number.NumberUtils; import cn.iocoder.yudao.framework.common.util.object.BeanUtils; import cn.iocoder.yudao.framework.common.util.object.PageUtils; import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO; import cn.iocoder.yudao.module.bpm.controller.admin.base.user.UserSimpleBaseVO; import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.model.simple.BpmSimpleModelNodeVO; import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.process.BpmProcessDefinitionRespVO; import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.*; import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.BpmApprovalDetailRespVO.ApprovalTaskInfo; import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.BpmTaskRespVO; import cn.iocoder.yudao.module.bpm.convert.definition.BpmProcessDefinitionConvert; import cn.iocoder.yudao.module.bpm.dal.dataobject.definition.BpmProcessDefinitionInfoDO; import cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants; import cn.iocoder.yudao.module.bpm.enums.definition.BpmModelTypeEnum; import cn.iocoder.yudao.module.bpm.enums.definition.BpmSimpleModelNodeType; import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceStatusEnum; import cn.iocoder.yudao.module.bpm.enums.task.BpmReasonEnum; import cn.iocoder.yudao.module.bpm.enums.task.BpmTaskStatusEnum; import cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.BpmTaskCandidateInvoker; import cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.BpmTaskCandidateStrategy; import cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.strategy.BpmTaskCandidateStartUserSelectStrategy; import cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmnVariableConstants; import cn.iocoder.yudao.module.bpm.framework.flowable.core.event.BpmProcessInstanceEventPublisher; import cn.iocoder.yudao.module.bpm.framework.flowable.core.util.BpmnModelUtils; import cn.iocoder.yudao.module.bpm.framework.flowable.core.util.FlowableUtils; import cn.iocoder.yudao.module.bpm.framework.flowable.core.util.SimpleModelUtils; import cn.iocoder.yudao.module.bpm.service.definition.BpmProcessDefinitionService; import cn.iocoder.yudao.module.bpm.service.message.BpmMessageService; import cn.iocoder.yudao.module.bpm.service.task.bo.AlreadyRunApproveNodeRespBO; import cn.iocoder.yudao.module.system.api.dept.DeptApi; import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO; import cn.iocoder.yudao.module.system.api.user.AdminUserApi; import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import jakarta.annotation.Resource; import jakarta.validation.Valid; import lombok.extern.slf4j.Slf4j; import org.flowable.bpmn.constants.BpmnXMLConstants; import org.flowable.bpmn.model.BpmnModel; import org.flowable.bpmn.model.UserTask; import org.flowable.common.engine.api.FlowableException; import org.flowable.common.engine.api.variable.VariableContainer; import org.flowable.engine.HistoryService; import org.flowable.engine.ManagementService; import org.flowable.engine.RuntimeService; import org.flowable.engine.history.HistoricActivityInstance; import org.flowable.engine.history.HistoricProcessInstance; import org.flowable.engine.history.HistoricProcessInstanceQuery; import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.task.api.history.HistoricTaskInstance; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import java.util.*; import java.util.stream.Stream; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*; import static cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.BpmApprovalDetailRespVO.ApprovalNodeInfo; import static cn.iocoder.yudao.module.bpm.convert.task.BpmProcessInstanceConvert.INSTANCE; import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.*; import static cn.iocoder.yudao.module.bpm.enums.definition.BpmSimpleModelNodeType.*; import static cn.iocoder.yudao.module.bpm.enums.definition.BpmUserTaskApproveTypeEnum.USER; import static cn.iocoder.yudao.module.bpm.enums.task.BpmTaskStatusEnum.NOT_START; import static cn.iocoder.yudao.module.bpm.enums.task.BpmTaskStatusEnum.RUNNING; import static cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmTaskCandidateStrategyEnum.START_USER; import static cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmnModelConstants.START_USER_NODE_ID; /** * 流程实例 Service 实现类 * <p> * ProcessDefinition & ProcessInstance & Execution & Task 的关系: * 1. <a href="https://blog.csdn.net/bobozai86/article/details/105210414" /> * <p> * HistoricProcessInstance & ProcessInstance 的关系: * 1. <a href=" https://my.oschina.net/843294669/blog/71902" /> * <p> * 简单来说,前者 = 历史 + 运行中的流程实例,后者仅是运行中的流程实例 * * @author 芋道源码 */ @Service @Validated @Slf4j public class BpmProcessInstanceServiceImpl implements BpmProcessInstanceService { @Resource private RuntimeService runtimeService; @Resource private HistoryService historyService; @Resource private ManagementService managementService; @Resource private BpmActivityService activityService; @Resource private BpmProcessDefinitionService processDefinitionService; @Resource @Lazy // 避免循环依赖 private BpmTaskService taskService; @Resource private BpmMessageService messageService; @Resource private BpmTaskCandidateInvoker bpmTaskCandidateInvoker; @Resource private AdminUserApi adminUserApi; @Resource private DeptApi deptApi; @Resource private BpmProcessInstanceEventPublisher processInstanceEventPublisher; // ========== Query 查询相关方法 ========== @Override public ProcessInstance getProcessInstance(String id) { return runtimeService.createProcessInstanceQuery() .includeProcessVariables() .processInstanceId(id) .singleResult(); } @Override public List<ProcessInstance> getProcessInstances(Set<String> ids) { return runtimeService.createProcessInstanceQuery().processInstanceIds(ids).list(); } @Override public HistoricProcessInstance getHistoricProcessInstance(String id) { return historyService.createHistoricProcessInstanceQuery().processInstanceId(id).includeProcessVariables().singleResult(); } @Override public List<HistoricProcessInstance> getHistoricProcessInstances(Set<String> ids) { return historyService.createHistoricProcessInstanceQuery().processInstanceIds(ids).list(); } @Override public PageResult<HistoricProcessInstance> getProcessInstancePage(Long userId, BpmProcessInstancePageReqVO pageReqVO) { // 通过 BpmProcessInstanceExtDO 表,先查询到对应的分页 HistoricProcessInstanceQuery processInstanceQuery = historyService.createHistoricProcessInstanceQuery() .includeProcessVariables() .processInstanceTenantId(FlowableUtils.getTenantId()) .orderByProcessInstanceStartTime().desc(); if (userId != null) { // 【我的流程】菜单时,需要传递该字段 processInstanceQuery.startedBy(String.valueOf(userId)); } else if (pageReqVO.getStartUserId() != null) { // 【管理流程】菜单时,才会传递该字段 processInstanceQuery.startedBy(String.valueOf(pageReqVO.getStartUserId())); } if (StrUtil.isNotEmpty(pageReqVO.getName())) { processInstanceQuery.processInstanceNameLike("%" + pageReqVO.getName() + "%"); } if (StrUtil.isNotEmpty(pageReqVO.getProcessDefinitionKey())) { processInstanceQuery.processDefinitionKey(pageReqVO.getProcessDefinitionKey()); } if (StrUtil.isNotEmpty(pageReqVO.getCategory())) { processInstanceQuery.processDefinitionCategory(pageReqVO.getCategory()); } if (pageReqVO.getStatus() != null) { processInstanceQuery.variableValueEquals(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, pageReqVO.getStatus()); } if (ArrayUtil.isNotEmpty(pageReqVO.getCreateTime())) { processInstanceQuery.startedAfter(DateUtils.of(pageReqVO.getCreateTime()[0])); processInstanceQuery.startedBefore(DateUtils.of(pageReqVO.getCreateTime()[1])); } // 查询数量 long processInstanceCount = processInstanceQuery.count(); if (processInstanceCount == 0) { return PageResult.empty(processInstanceCount); } // 查询列表 List<HistoricProcessInstance> processInstanceList = processInstanceQuery.listPage(PageUtils.getStart(pageReqVO), pageReqVO.getPageSize()); return new PageResult<>(processInstanceList, processInstanceCount); } private Map<String, String> getFormFieldsPermission(BpmnModel bpmnModel, String activityId, String taskId) { // 1. 获取流程活动编号。流程活动 Id 为空事,从流程任务中获取流程活动 Id if (StrUtil.isEmpty(activityId) && StrUtil.isNotEmpty(taskId)) { activityId = Optional.ofNullable(taskService.getHistoricTask(taskId)) .map(HistoricTaskInstance::getTaskDefinitionKey).orElse(null); } if (StrUtil.isEmpty(activityId)) { return null; } // 2. 从 BpmnModel 中解析表单字段权限 return BpmnModelUtils.parseFormFieldsPermission(bpmnModel, activityId); } @Override public BpmApprovalDetailRespVO getApprovalDetail(Long loginUserId, BpmApprovalDetailReqVO reqVO) { // 1. 设置流程未发起的值 // 1.1 流程状态 Integer processInstanceStatus = BpmProcessInstanceStatusEnum.NOT_START.getStatus(); // 流程未发起的状态 // 1.2 流程定义 Id String processDefinitionId = reqVO.getProcessDefinitionId(); // 流程未发起前端传入 // 1.3. 流程实例 BpmProcessInstanceRespVO processInstanceResp = null; // 流程未发起时为 null // 1.4 以下是用于流程预测的值 Long startUserId = loginUserId; // 流程发起人。流程未发起时,发起人设置成登录人 ProcessInstance runProcessInstance = null; // 正在运行的流程实例,流程未发起时为 null Set<String> runNodeIds = new HashSet<>(); // 已经运行的节点 Ids (BPMN XML 节点 Id) Map<String, ApprovalNodeInfo> runningApprovalNodes = new HashMap<>(); // 正在运行的节点的审批信息 List<ApprovalNodeInfo> approvalNodes = new ArrayList<>(); // 审批节点的信息。流程未发起时为空 // 2 设置流程已发起的值 if (reqVO.getProcessInstanceId() != null) { // 2.1 流程状态 HistoricProcessInstance processInstance = getHistoricProcessInstance(reqVO.getProcessInstanceId()); if (processInstance == null) { throw exception(ErrorCodeConstants.PROCESS_INSTANCE_NOT_EXISTS); } processInstanceStatus = FlowableUtils.getProcessInstanceStatus(processInstance); // 2.2 流程定义 Id processDefinitionId = processInstance.getProcessDefinitionId(); // 2.3 流程实例 AdminUserRespDTO startUser = adminUserApi.getUser(NumberUtils.parseLong(processInstance.getStartUserId())); DeptRespDTO dept = null; if (startUser != null && startUser.getDeptId() != null) { dept = deptApi.getDept(startUser.getDeptId()); } processInstanceResp = INSTANCE.buildProcessInstance(processInstance, null, null, startUser, dept); // 2.4 以下是用于流程预测的值 startUserId = Long.valueOf(processInstance.getStartUserId()); // 流程发起人 runProcessInstance = getProcessInstance(processInstance.getId()); // 正在运行的流程实例 List<HistoricActivityInstance> historicActivityList = activityService.getActivityListByProcessInstanceId(processInstance.getId()); AlreadyRunApproveNodeRespBO respBO = buildAlreadyRunApproveNodes(processInstance.getId(), processInstanceStatus, historicActivityList); runNodeIds = respBO.getRunNodeIds(); // 已经运行的节点 Ids approvalNodes = respBO.getApproveNodes(); // // 获取已运行节点的审批的信息 runningApprovalNodes = respBO.getRunningApprovalNodes(); // 正在运行的节点的审批信息 } // 3. 流程定义 ProcessDefinition processDefinition = processDefinitionService.getProcessDefinition(processDefinitionId); BpmProcessDefinitionInfoDO processDefinitionInfo = processDefinitionService.getProcessDefinitionInfo(processDefinitionId); BpmnModel bpmnModel = processDefinitionService.getProcessDefinitionBpmnModel(processDefinitionId); List<UserTask> userTaskList = BpmTaskCandidateStartUserSelectStrategy.getStartUserSelectUserTaskList(bpmnModel); BpmProcessDefinitionRespVO definitionResp = BpmProcessDefinitionConvert.INSTANCE.buildProcessDefinition( processDefinition,null,processDefinitionInfo,null, null,bpmnModel,userTaskList ); // 4. 表单权限 Map<String, String> formFieldsPermission = getFormFieldsPermission(bpmnModel, reqVO.getActivityId(), reqVO.getTaskId()); // 5 .登录用户的待办任务 BpmTaskRespVO todoTask = taskService.getFirstTodoTask(loginUserId, reqVO.getProcessInstanceId()); // 流程已经结束,直接 return,无需预测 if (BpmProcessInstanceStatusEnum.isProcessEndStatus(processInstanceStatus)) { return new BpmApprovalDetailRespVO().setStatus(processInstanceStatus) .setProcessDefinition(definitionResp).setProcessInstance(processInstanceResp) .setFormFieldsPermission(formFieldsPermission) .setTodoTask(todoTask).setApproveNodes(approvalNodes); } // 6,预测未运行节点的审批信息。需要区分 BPMN 设计器 和 SIMPLE 设计器 // 6.1 情况一:仿钉钉流程设计器 if (Objects.equals(BpmModelTypeEnum.SIMPLE.getType(), processDefinitionInfo.getModelType())) { BpmSimpleModelNodeVO simpleModel = JsonUtils.parseObject(processDefinitionInfo.getSimpleModel(), BpmSimpleModelNodeVO.class); List<ApprovalNodeInfo> notRunApproveNodes = new ArrayList<>(); traverseSimpleModelNodeToBuildNotRunApproveNodes( startUserId, runProcessInstance, simpleModel, runNodeIds, runningApprovalNodes, notRunApproveNodes); approvalNodes.addAll(notRunApproveNodes); // 6.2 情况二:BPMN 流程设计器 } else if (Objects.equals(BpmModelTypeEnum.BPMN.getType(), processDefinitionInfo.getModelType())) { // TODO 芋艿:需要把 start 节点加出来 // TODO Bpmn 设计器,构建未运行节点的审批信息;未完全实现 } return new BpmApprovalDetailRespVO().setStatus(processInstanceStatus) .setProcessDefinition(definitionResp).setProcessInstance(processInstanceResp) .setFormFieldsPermission(formFieldsPermission) .setTodoTask(todoTask).setApproveNodes(approvalNodes); } /** * 遍历 SIMPLE 设计器模型 构建未运行节点的审批信息 * * @param startUserId 流程发起人编号 * @param processInstance 流程实例 * @param simpleModelNode SIMPLE 设计器模型 * @param runNodeIds 已经运行节点的 Ids * @param runningApprovalNodes 正在运行的节点的审批信息 * @param approveNodeList 未运行节点的审批信息列表 */ private void traverseSimpleModelNodeToBuildNotRunApproveNodes(Long startUserId, ProcessInstance processInstance, BpmSimpleModelNodeVO simpleModelNode, Set<String> runNodeIds, Map<String, ApprovalNodeInfo> runningApprovalNodes, List<ApprovalNodeInfo> approveNodeList) { if (!SimpleModelUtils.isValidNode(simpleModelNode)) { return; } buildNotRunApproveNodes(startUserId, processInstance, simpleModelNode, runNodeIds, runningApprovalNodes, approveNodeList); // 如果有子节点递归遍历子节点 traverseSimpleModelNodeToBuildNotRunApproveNodes( startUserId, processInstance, simpleModelNode.getChildNode(), runNodeIds, runningApprovalNodes, approveNodeList); } private void buildNotRunApproveNodes(Long startUserId, ProcessInstance processInstance, BpmSimpleModelNodeVO node, Set<String> runNodeIds, Map<String, ApprovalNodeInfo> runningApprovalNodes, List<ApprovalNodeInfo> approveNodeList) { // 情况一:节点未运行:需要进行预测 if (!runNodeIds.contains(node.getId())) { // 1. 对需要人工审批的审批节点,进行预测 if (APPROVE_NODE.getType().equals(node.getType()) && USER.getType().equals(node.getApproveType()) || START_USER_NODE.getType().equals(node.getType())) { ApprovalNodeInfo approvalNodeInfo = new ApprovalNodeInfo().setNodeType(node.getType()) .setName(node.getName()).setStatus(NOT_START.getStatus()); Integer candidateStrategy = START_USER_NODE.getType().equals(node.getType()) ? START_USER.getStrategy() : node.getCandidateStrategy(); approvalNodeInfo.setCandidateUsers( getNotRunTaskCandidateUserList(startUserId, processInstance, node.getId(), candidateStrategy, node.getCandidateParam())); approveNodeList.add(approvalNodeInfo); // 2. 对分支节点,进行预测 } else if (BpmSimpleModelNodeType.isBranchNode(node.getType())) { // 并行分支,不用预测条件。所有分支都需要遍历 if (PARALLEL_BRANCH_NODE.getType().equals(node.getType())) { node.getConditionNodes().forEach(conditionNode -> traverseSimpleModelNodeToBuildNotRunApproveNodes(startUserId, processInstance, conditionNode.getChildNode() , runNodeIds, runningApprovalNodes, approveNodeList)); } else if (CONDITION_BRANCH_NODE.getType().equals(node.getType())) { for (BpmSimpleModelNodeVO conditionNode : node.getConditionNodes()) { // 满足一个条件, 遍历该分支并 if ((processInstance != null // 预测条件表达式的值 && evalConditionExpress(processInstance, SimpleModelUtils.ConditionNodeConvert.buildConditionExpression(conditionNode))) || BooleanUtil.isTrue(conditionNode.getDefaultFlow())) { // 是否默认的序列 traverseSimpleModelNodeToBuildNotRunApproveNodes(startUserId, processInstance, conditionNode.getChildNode(), runNodeIds, runningApprovalNodes, approveNodeList); break; } } } // TODO 包容分支待实现 // 3. 结束节点 } else if (END_NODE.getType().equals(node.getType())) { ApprovalNodeInfo nodeProgress = new ApprovalNodeInfo(); nodeProgress.setNodeType(node.getType()); nodeProgress.setName(node.getName()); nodeProgress.setStatus(NOT_START.getStatus()); approveNodeList.add(nodeProgress); } } else { // 情况二:节点已经运行 // 如果是分支节点,需要检查分支节点的运行情况 if (BpmSimpleModelNodeType.isBranchNode(node.getType()) && ArrayUtil.isNotEmpty(node.getConditionNodes())) { node.getConditionNodes().forEach(conditionNode -> { // 只有运行的条件,才需要遍历 if (runNodeIds.contains(conditionNode.getId())) { traverseSimpleModelNodeToBuildNotRunApproveNodes(startUserId, processInstance, conditionNode.getChildNode() , runNodeIds, runningApprovalNodes, approveNodeList); } }); // 如果是依次审批, 需要加其它未审批候选人 } else if (SimpleModelUtils.isSequentialApproveNode(node) && runningApprovalNodes.containsKey(node.getId())) { ApprovalNodeInfo approvalNodeInfo = runningApprovalNodes.get(node.getId()); List<UserSimpleBaseVO> candidateUserList = getNotRunTaskCandidateUserList( startUserId, processInstance, node.getId(), node.getCandidateStrategy(), node.getCandidateParam()); // TODO @jason:这里的逻辑,可能可以简化成,直接拿已经审批过的人的 userId 集合,从 candidateUserList remove 下。一方面简单一点,方面 calculateUsers 返回的是 set,目前不是很有序。 // TODO @芋艿 已经审批过的人的 userId 集合。不知道如何获取,不知道有啥好方法没。 如果取这个节点已经完成的审批任务。 是不是有可能包含回退的情况。就不太对了。 另外 candidateUserList 是按返回 set 遍历顺序返回的。和 set 的顺序是一致的。就不会有问题了 ApprovalTaskInfo approvalTaskInfo = CollUtil.getFirst(approvalNodeInfo.getTasks()); Long currentAssignedUserId = null; if (approvalTaskInfo != null && approvalTaskInfo.getAssigneeUser() != null) { currentAssignedUserId = approvalTaskInfo.getAssigneeUser().getId(); } // 找到当前审批人在候选人列表的位置 int index = 0; for (UserSimpleBaseVO user : candidateUserList) { if (user.getId().equals(currentAssignedUserId)) { break; } index++; } // 截取当前审批人位置后面的候选人, 不包含当前审批人 approvalNodeInfo.setCandidateUsers(CollUtil.sub(candidateUserList, ++index, candidateUserList.size())); } } } /** * 从已经运行活动节点构建的审批信息列表 * * @param processInstanceId 流程实例 Id * @param processInstanceStatus 流程实例状态 * @param historicActivityList 已经运行活动 */ private AlreadyRunApproveNodeRespBO buildAlreadyRunApproveNodes(String processInstanceId, Integer processInstanceStatus, List<HistoricActivityInstance> historicActivityList) { // 1.1 获取待处理活动:只有 "userTask" 和 "endEvent" 需要处理 List<HistoricActivityInstance> pendingActivityNodes = filterList(historicActivityList, item -> BpmSimpleModelNodeType.isRecordNode(item.getActivityType())); // 1.2 已运行节点的 activityId Set<String> runNodeIds = convertSet(historicActivityList, HistoricActivityInstance::getActivityId); // 2.1 获取已运行的任务(包括运行中的任务) List<HistoricTaskInstance> taskList = taskService.getTaskListByProcessInstanceId(processInstanceId, false); Map<String, HistoricTaskInstance> taskMap = convertMap(taskList, HistoricTaskInstance::getId); // 2.2 获取加签的任务 Map<String, List<HistoricTaskInstance>> addSignTaskMap = convertMultiMap( filterList(taskList, task -> StrUtil.isNotEmpty(task.getParentTaskId())), HistoricTaskInstance::getParentTaskId); // 3.1 获取节点的用户信息 Set<Long> userIds = CollectionUtils.convertSetByFlatMap(pendingActivityNodes, activity -> { if (BPMN_USER_TASK_TYPE.equals(activity.getActivityType())) { HistoricTaskInstance task = taskMap.get(activity.getTaskId()); Set<Long> taskUsers = CollUtil.newHashSet(); CollUtil.addIfAbsent(taskUsers, NumberUtil.parseLong(task.getAssignee(), null)); CollUtil.addIfAbsent(taskUsers, NumberUtil.parseLong(task.getOwner(), null)); List<HistoricTaskInstance> addSignTasks = addSignTaskMap.get(activity.getTaskId()); if (CollUtil.isNotEmpty(addSignTasks)) { addSignTasks.forEach(item -> { CollUtil.addIfAbsent(taskUsers, NumberUtil.parseLong(item.getAssignee(), null)); CollUtil.addIfAbsent(taskUsers, NumberUtil.parseLong(item.getOwner(), null)); }); } return taskUsers.stream(); } else { return Stream.empty(); } }); Map<Long, AdminUserRespDTO> userMap = convertMap(adminUserApi.getUserList(userIds), AdminUserRespDTO::getId); // 3.2 已经结束的任务转换为审批信息 final Multimap<String, HistoricActivityInstance> runningTask = ArrayListMultimap.create(); // 运行中的任务 List<ApprovalNodeInfo> approvalNodeList = convertList(pendingActivityNodes, activity -> { ApprovalNodeInfo approvalNodeInfo = new ApprovalNodeInfo().setId(activity.getId()).setName(activity.getActivityName()) .setStartTime(DateUtils.of(activity.getStartTime())).setEndTime(DateUtils.of(activity.getEndTime())); if (BPMN_USER_TASK_TYPE.equals(activity.getActivityType())) { // 用户任务 // nodeType approvalNodeInfo.setNodeType(START_USER_NODE_ID.equals(activity.getActivityId()) ? START_USER_NODE.getType() : APPROVE_NODE.getType()); // status HistoricTaskInstance task = taskMap.get(activity.getTaskId()); Integer taskStatus = FlowableUtils.getTaskStatus(task); // 运行中的任务, 会签,或签任务聚合在一起。 if (!BpmTaskStatusEnum.isEndStatus(taskStatus)) { runningTask.put(activity.getActivityId(), activity); return null; } // tasks ApprovalTaskInfo approveTask = convertApproveTaskInfo(task, userMap); List<ApprovalTaskInfo> approveTasks = CollUtil.newArrayList(approveTask); List<HistoricTaskInstance> addSignTasks = addSignTaskMap.get(activity.getTaskId()); if (CollUtil.isNotEmpty(addSignTasks)) { // 处理加签任务 approveTasks.addAll(convertList(addSignTasks, item -> convertApproveTaskInfo(item, userMap))); } approvalNodeInfo.setStatus(taskStatus); approvalNodeInfo.setTasks(approveTasks); } else if (END_NODE.getBpmnType().equals(activity.getActivityType())) { approvalNodeInfo.setNodeType(END_NODE.getType()); approvalNodeInfo.setStatus(processInstanceStatus); } return approvalNodeInfo; }); // 3.3 运行中的任务转换为审批信息。 final Map<String, ApprovalNodeInfo> runningApprovalNodes = new HashMap<>(); // 正在运行节点的审批信息 runningTask.asMap().forEach((activityId, activities) -> { if (CollUtil.isNotEmpty(activities)) { ApprovalNodeInfo approvalNodeInfo = new ApprovalNodeInfo(); approvalNodeInfo.setNodeType(APPROVE_NODE.getType()); approvalNodeInfo.setStatus(RUNNING.getStatus()); List<ApprovalTaskInfo> approveTasks = CollUtil.newArrayList(); int i = 0; for (HistoricActivityInstance activity : activities) { HistoricTaskInstance task = taskMap.get(activity.getTaskId()); // 取第一个任务, 会签/或签的任务。开始时间相同的 if (i == 0) { approvalNodeInfo.setId(activity.getId()).setName(activity.getActivityName()). setStartTime(DateUtils.of(activity.getStartTime())); } // tasks ApprovalTaskInfo approveTask = convertApproveTaskInfo(task, userMap); approveTasks.add(approveTask); List<HistoricTaskInstance> addSignTasks = addSignTaskMap.get(activity.getTaskId()); if (CollUtil.isNotEmpty(addSignTasks)) { // 处理加签任务 approveTasks.addAll(convertList(addSignTasks, item -> convertApproveTaskInfo(item, userMap))); } i++; } approvalNodeInfo.setTasks(approveTasks); approvalNodeList.add(approvalNodeInfo); runningApprovalNodes.put(activityId, approvalNodeInfo); } }); return new AlreadyRunApproveNodeRespBO().setApproveNodes(approvalNodeList).setRunNodeIds(runNodeIds) .setRunningApprovalNodes(runningApprovalNodes); } private ApprovalTaskInfo convertApproveTaskInfo(HistoricTaskInstance task, Map<Long, AdminUserRespDTO> userMap) { if (task == null) { return null; } ApprovalTaskInfo approveTask = BeanUtils.toBean(task, ApprovalTaskInfo.class); approveTask.setStatus(FlowableUtils.getTaskStatus(task)).setReason(FlowableUtils.getTaskReason(task)); Long taskAssignee = NumberUtil.parseLong(task.getAssignee(), null); if (taskAssignee != null) { approveTask.setAssigneeUser(BeanUtils.toBean(userMap.get(taskAssignee), UserSimpleBaseVO.class)); } Long taskOwner = NumberUtil.parseLong(task.getOwner(), null); if (taskOwner != null) { approveTask.setOwnerUser(BeanUtils.toBean(userMap.get(taskOwner), UserSimpleBaseVO.class)); } return approveTask; } private List<UserSimpleBaseVO> getNotRunTaskCandidateUserList(Long startUserId, ProcessInstance processInstance, String activityId, Integer candidateStrategy, String candidateParam) { BpmTaskCandidateStrategy taskCandidateStrategy = bpmTaskCandidateInvoker.getCandidateStrategy(candidateStrategy); Set<Long> userIds = taskCandidateStrategy.calculateUsers(startUserId, processInstance, activityId, candidateParam); Map<Long, AdminUserRespDTO> adminUserMap = adminUserApi.getUserMap(userIds); // 需要按照候选人的顺序返回。原因是,依次审批需要按顺序展示用户 return convertList(userIds, userId -> BeanUtils.toBean(adminUserMap.get(userId), UserSimpleBaseVO.class)); } /** * 计算条件表达式的值 * * @param processInstance 流程实例 * @param express 条件表达式 */ private Boolean evalConditionExpress(ProcessInstance processInstance, String express) { if (express == null) { return Boolean.FALSE; } Object result = managementService.executeCommand(context -> { try { return FlowableUtils.getExpressionValue((VariableContainer) processInstance, express); } catch (FlowableException ex) { log.error("[evalConditionExpress][条件表达式({}) 解析报错", express, ex); return Boolean.FALSE; } }); return Boolean.TRUE.equals(result); } @Override public BpmProcessInstanceBpmnModelViewRespVO getProcessInstanceBpmnModelView(String id) { // 1.1 获得流程实例 HistoricProcessInstance processInstance = getHistoricProcessInstance(id); if (processInstance == null) { return null; } // 1.2 获得流程定义 BpmnModel bpmnModel = processDefinitionService.getProcessDefinitionBpmnModel(processInstance.getProcessDefinitionId()); if (bpmnModel == null) { return null; } // 1.3 获得流程实例对应的活动实例列表 + 任务列表 List<HistoricActivityInstance> activityInstances = getActivityListByProcessInstanceId(id); List<HistoricTaskInstance> taskInstances = taskService.getTaskListByProcessInstanceId(id, true); // 1.4 查询关联用户、部门信息 Set<Long> userIds = SetUtils.asSet(Long.valueOf(processInstance.getStartUserId())); taskInstances.forEach(task -> { CollUtil.addIfAbsent(userIds, NumberUtils.parseLong((task.getAssignee()))); CollUtil.addIfAbsent(userIds, NumberUtils.parseLong((task.getOwner()))); }); Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(userIds); Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap( convertSet(userMap.values(), AdminUserRespDTO::getDeptId)); // 2.1 拼接进度信息 Set<String> unfinishedTaskActivityIds = convertSet(activityInstances, HistoricActivityInstance::getActivityId, activityInstance -> activityInstance.getEndTime() == null); Set<String> finishedTaskActivityIds = convertSet(activityInstances, HistoricActivityInstance::getActivityId, activityInstance -> activityInstance.getEndTime() != null && ObjectUtil.notEqual(activityInstance.getActivityType(), BpmnXMLConstants.ELEMENT_SEQUENCE_FLOW)); Set<String> finishedSequenceFlowActivityIds = convertSet(activityInstances, HistoricActivityInstance::getActivityId, activityInstance -> activityInstance.getEndTime() != null && ObjectUtil.equals(activityInstance.getActivityType(), BpmnXMLConstants.ELEMENT_SEQUENCE_FLOW)); // 特殊:会签情况下,会有部分已完成(审批)、部分未完成(待审批),此时需要 finishedTaskActivityIds 移除掉 unfinishedTaskActivityIds.removeAll(finishedTaskActivityIds); // 特殊:如果流程实例被拒绝,则需要计算是哪个活动节点。 // 注意,只取最后一个。因为会存在多次拒绝的情况,拒绝驳回到指定节点 Set<String> rejectTaskActivityIds = CollUtil.newHashSet(); if (BpmProcessInstanceStatusEnum.isRejectStatus(FlowableUtils.getProcessInstanceStatus(processInstance))) { taskInstances.stream() .filter(task -> BpmTaskStatusEnum.isRejectStatus(FlowableUtils.getTaskStatus(task))) .max(Comparator.comparing(HistoricTaskInstance::getEndTime)) .ifPresent(reject -> rejectTaskActivityIds.add(reject.getTaskDefinitionKey())); finishedTaskActivityIds.removeAll(rejectTaskActivityIds); } // 2.2 拼接基础信息 return INSTANCE.buildProcessInstanceBpmnModelView(processInstance, taskInstances, bpmnModel, unfinishedTaskActivityIds, finishedTaskActivityIds, finishedSequenceFlowActivityIds, rejectTaskActivityIds, userMap, deptMap); } private List<HistoricActivityInstance> getActivityListByProcessInstanceId(String id) { return historyService.createHistoricActivityInstanceQuery().processInstanceId(id) .orderByHistoricActivityInstanceStartTime().asc().list(); } // ========== Update 写入相关方法 ========== @Override @Transactional(rollbackFor = Exception.class) public String createProcessInstance(Long userId, @Valid BpmProcessInstanceCreateReqVO createReqVO) { // 获得流程定义 ProcessDefinition definition = processDefinitionService.getProcessDefinition(createReqVO.getProcessDefinitionId()); // 发起流程 return createProcessInstance0(userId, definition, createReqVO.getVariables(), null, createReqVO.getStartUserSelectAssignees()); } @Override public String createProcessInstance(Long userId, @Valid BpmProcessInstanceCreateReqDTO createReqDTO) { // 获得流程定义 ProcessDefinition definition = processDefinitionService.getActiveProcessDefinition(createReqDTO.getProcessDefinitionKey()); // 发起流程 return createProcessInstance0(userId, definition, createReqDTO.getVariables(), createReqDTO.getBusinessKey(), createReqDTO.getStartUserSelectAssignees()); } private String createProcessInstance0(Long userId, ProcessDefinition definition, Map<String, Object> variables, String businessKey, Map<String, List<Long>> startUserSelectAssignees) { // 1.1 校验流程定义 if (definition == null) { throw exception(PROCESS_DEFINITION_NOT_EXISTS); } if (definition.isSuspended()) { throw exception(PROCESS_DEFINITION_IS_SUSPENDED); } BpmProcessDefinitionInfoDO processDefinitionInfo = processDefinitionService.getProcessDefinitionInfo(definition.getId()); if (processDefinitionInfo == null) { throw exception(PROCESS_DEFINITION_NOT_EXISTS); } // 1.2 校验是否能够发起 if (!processDefinitionService.canUserStartProcessDefinition(processDefinitionInfo, userId)) { throw exception(PROCESS_INSTANCE_START_USER_CAN_START); } // 1.3 校验发起人自选审批人 validateStartUserSelectAssignees(definition, startUserSelectAssignees); // 2. 创建流程实例 if (variables == null) { variables = new HashMap<>(); } FlowableUtils.filterProcessInstanceFormVariable(variables); // 过滤一下,避免 ProcessInstance 系统级的变量被占用 variables.put(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, // 流程实例状态:审批中 BpmProcessInstanceStatusEnum.RUNNING.getStatus()); if (CollUtil.isNotEmpty(startUserSelectAssignees)) { variables.put(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_START_USER_SELECT_ASSIGNEES, startUserSelectAssignees); } ProcessInstance instance = runtimeService.createProcessInstanceBuilder() .processDefinitionId(definition.getId()) .businessKey(businessKey) .name(definition.getName().trim()) .variables(variables) .start(); return instance.getId(); } private void validateStartUserSelectAssignees(ProcessDefinition definition, Map<String, List<Long>> startUserSelectAssignees) { // 1. 获得发起人自选审批人的 UserTask 列表 BpmnModel bpmnModel = processDefinitionService.getProcessDefinitionBpmnModel(definition.getId()); List<UserTask> userTaskList = BpmTaskCandidateStartUserSelectStrategy.getStartUserSelectUserTaskList(bpmnModel); if (CollUtil.isEmpty(userTaskList)) { return; } // 2. 校验发起人自选审批人的 UserTask 是否都配置了 userTaskList.forEach(userTask -> { List<Long> assignees = startUserSelectAssignees != null ? startUserSelectAssignees.get(userTask.getId()) : null; if (CollUtil.isEmpty(assignees)) { throw exception(PROCESS_INSTANCE_START_USER_SELECT_ASSIGNEES_NOT_CONFIG, userTask.getName()); } Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(assignees); assignees.forEach(assignee -> { if (userMap.get(assignee) == null) { throw exception(PROCESS_INSTANCE_START_USER_SELECT_ASSIGNEES_NOT_EXISTS, userTask.getName(), assignee); } }); }); } @Override public void cancelProcessInstanceByStartUser(Long userId, @Valid BpmProcessInstanceCancelReqVO cancelReqVO) { // 1.1 校验流程实例存在 ProcessInstance instance = getProcessInstance(cancelReqVO.getId()); if (instance == null) { throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS); } // 1.2 只能取消自己的 if (!Objects.equals(instance.getStartUserId(), String.valueOf(userId))) { throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_SELF); } // 2. 取消流程 updateProcessInstanceCancel(cancelReqVO.getId(), BpmReasonEnum.CANCEL_PROCESS_INSTANCE_BY_START_USER.format(cancelReqVO.getReason())); } @Override public void cancelProcessInstanceByAdmin(Long userId, BpmProcessInstanceCancelReqVO cancelReqVO) { // 1.1 校验流程实例存在 ProcessInstance instance = getProcessInstance(cancelReqVO.getId()); if (instance == null) { throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS); } // 2. 取消流程 AdminUserRespDTO user = adminUserApi.getUser(userId); updateProcessInstanceCancel(cancelReqVO.getId(), BpmReasonEnum.CANCEL_PROCESS_INSTANCE_BY_ADMIN.format(user.getNickname(), cancelReqVO.getReason())); } private void updateProcessInstanceCancel(String id, String reason) { // 1. 更新流程实例 status runtimeService.setVariable(id, BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, BpmProcessInstanceStatusEnum.CANCEL.getStatus()); runtimeService.setVariable(id, BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_REASON, reason); // 2. 结束流程 taskService.moveTaskToEnd(id); } @Override public void updateProcessInstanceReject(ProcessInstance processInstance, String reason) { runtimeService.setVariable(processInstance.getProcessInstanceId(), BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, BpmProcessInstanceStatusEnum.REJECT.getStatus()); runtimeService.setVariable(processInstance.getProcessInstanceId(), BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_REASON, BpmReasonEnum.REJECT_TASK.format(reason)); } // ========== Event 事件相关方法 ========== @Override public void processProcessInstanceCompleted(ProcessInstance instance) { // 注意:需要基于 instance 设置租户编号,避免 Flowable 内部异步时,丢失租户编号 FlowableUtils.execute(instance.getTenantId(), () -> { // 1.1 获取当前状态 Integer status = (Integer) instance.getProcessVariables().get(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS); String reason = (String) instance.getProcessVariables().get(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_REASON); // 1.2 当流程状态还是审批状态中,说明审批通过了,则变更下它的状态 // 为什么这么处理?因为流程完成,并且完成了,说明审批通过了 if (Objects.equals(status, BpmProcessInstanceStatusEnum.RUNNING.getStatus())) { status = BpmProcessInstanceStatusEnum.APPROVE.getStatus(); runtimeService.setVariable(instance.getId(), BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, status); } // 2. 发送对应的消息通知 if (Objects.equals(status, BpmProcessInstanceStatusEnum.APPROVE.getStatus())) { messageService.sendMessageWhenProcessInstanceApprove(INSTANCE.buildProcessInstanceApproveMessage(instance)); } else if (Objects.equals(status, BpmProcessInstanceStatusEnum.REJECT.getStatus())) { messageService.sendMessageWhenProcessInstanceReject( INSTANCE.buildProcessInstanceRejectMessage(instance, reason)); } // 3. 发送流程实例的状态事件 processInstanceEventPublisher.sendProcessInstanceResultEvent( INSTANCE.buildProcessInstanceStatusEvent(this, instance, status)); }); } } | ||
| 3 | \ No newline at end of file | 3 | \ No newline at end of file |