fuliqi
2025-01-03 98c18b07b92f80a1885e56b3413068644d0c9a51
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package com.ycl.service.common;
 
import com.alibaba.fastjson2.JSONObject;
import com.ycl.common.constant.ProcessConstants;
import com.ycl.common.core.domain.entity.SysUser;
import com.ycl.common.enums.FlowComment;
import com.ycl.common.enums.business.TaskStatusEnum;
import com.ycl.domain.entity.SysForm;
import com.ycl.domain.vo.FormDetailVO;
import com.ycl.flow.FindNextNodeUtil;
import com.ycl.service.ISysFormService;
import lombok.RequiredArgsConstructor;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
 
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author:xp
 * @date:2024/12/4 23:22
 */
@Service
@RequiredArgsConstructor
public class TaskCommonService {
 
    private final RuntimeService runtimeService;
    private final RepositoryService repositoryService;
    private final TaskService taskService;
    private final HistoryService historyService;
 
    /**
     * 通过当前节点定义key,获取其上一个节点的信息,如果前面是并行的会返回多个(包含当前节点)
     *
     * @param processDefId 流程定义id
     * @param currentNodeDefId 当前节点定义id
     * @param sysFormService 表单服务层
     * @param needInitCurrentForm 是否需要初始化当前节点的表单数据,一般查询已完成的任务详情需要
     * @return
     */
    public List<FormDetailVO> getBeforeNodeDefInfo(String processDefId, String currentNodeDefId, ISysFormService sysFormService, Boolean needInitCurrentForm) {
        // 获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processDefId)
                .singleResult();
 
        // 获取流程模型
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefId);
        if (bpmnModel == null) {
            throw new RuntimeException("BpmnModel not found for processDefinitionId: " + processDefId);
        }
 
        // 获取流程对象
        Process process = bpmnModel.getProcessById(processDefinition.getKey());
        if (process == null) {
            throw new RuntimeException("Process not found for processDefinitionId: " + processDefId);
        }
 
        // 遍历流程元素,找到对应的任务节点
        Collection<FlowElement> flowElements = process.getFlowElements();
        UserTask currentElement = null;
        for (FlowElement flowElement : flowElements) {
            if (flowElement instanceof UserTask && flowElement.getId().equals(currentNodeDefId)) {
                currentElement = (UserTask) flowElement;
                break;
            }
        }
        if (Objects.isNull(currentElement)) {
            throw new RuntimeException("未找到该任务的流程定义节点");
        }
 
        // 获取当前节点的输入
        List<FormDetailVO> defKeys = new ArrayList<>(2);
        if (StringUtils.hasText(currentElement.getFormKey())) {
            FormDetailVO formDetailVO = new FormDetailVO();
            formDetailVO.setBeforeNodeDefId(currentElement.getId());
            formDetailVO.setBeforeNodeName(currentElement.getName());
            formDetailVO.setCurrent(Boolean.TRUE);
 
            if (needInitCurrentForm) {
                SysForm sysForm = sysFormService.selectSysFormById(Long.parseLong(currentElement.getFormKey()));
                if (Objects.isNull(sysForm)) {
                    throw new RuntimeException("该流程绑定的表单不存在或已被删除");
                }
                Map<String, Object> data = new HashMap<>(1);
                data.put(ProcessConstants.TASK_FORM_KEY, JSONObject.parseObject(sysForm.getFormContent()));
 
                formDetailVO.setFormJsonObj(data);
            }
 
            defKeys.add(formDetailVO);
        }
        this.beforeNodeInfo(currentElement, defKeys);
 
        return defKeys;
    }
 
 
    /**
     * 获取当前节点的前置节点,不包含当前节点
     *
     * @param processDefId
     * @param currentNodeDefId
     * @return
     */
    public List<FormDetailVO> getBeforeNodeList(String processDefId, String currentNodeDefId) {
        // 获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processDefId)
                .singleResult();
 
        // 获取流程模型
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefId);
        if (bpmnModel == null) {
            throw new RuntimeException("BpmnModel not found for processDefinitionId: " + processDefId);
        }
 
        // 获取流程对象
        Process process = bpmnModel.getProcessById(processDefinition.getKey());
        if (process == null) {
            throw new RuntimeException("Process not found for processDefinitionId: " + processDefId);
        }
 
        // 遍历流程元素,找到对应的任务节点
        Collection<FlowElement> flowElements = process.getFlowElements();
        UserTask currentElement = null;
        for (FlowElement flowElement : flowElements) {
            if (flowElement instanceof UserTask && flowElement.getId().equals(currentNodeDefId)) {
                currentElement = (UserTask) flowElement;
                break;
            }
        }
        if (Objects.isNull(currentElement)) {
            throw new RuntimeException("未找到该任务的流程定义节点");
        }
 
        List<FormDetailVO> defKeys = new ArrayList<>(2);
 
        this.beforeNodeInfo(currentElement, defKeys);
 
        return defKeys;
    }
 
    /**
     * 递归获取当前节点的前一个任务节点信息
     *
     * @param currentElement
     * @param defKeys
     */
    private void beforeNodeInfo(FlowElement currentElement, List<FormDetailVO> defKeys) {
        if (currentElement instanceof UserTask) {
            UserTask userTask = (UserTask) currentElement;
            if (! CollectionUtils.isEmpty(userTask.getIncomingFlows())) {
                for (SequenceFlow incomingFlow : userTask.getIncomingFlows()) {
                    if (incomingFlow.getSourceFlowElement() instanceof UserTask) {
                        FormDetailVO formDetailVO = new FormDetailVO();
                        formDetailVO.setBeforeNodeDefId(incomingFlow.getSourceFlowElement().getId());
                        formDetailVO.setBeforeNodeName(incomingFlow.getSourceFlowElement().getName());
                        defKeys.add(formDetailVO);
                    } else {
                        beforeNodeInfo(incomingFlow.getSourceFlowElement(), defKeys);
                    }
                }
            }
        } else if (currentElement instanceof Gateway ){
            Gateway gateway = (Gateway) currentElement;
            if (! CollectionUtils.isEmpty(gateway.getIncomingFlows())) {
                for (SequenceFlow incomingFlow : gateway.getIncomingFlows()) {
                    if (incomingFlow.getSourceFlowElement() instanceof UserTask) {
                        FormDetailVO formDetailVO = new FormDetailVO();
                        formDetailVO.setBeforeNodeDefId(incomingFlow.getSourceFlowElement().getId());
                        formDetailVO.setBeforeNodeName(incomingFlow.getSourceFlowElement().getName());
                        defKeys.add(formDetailVO);
                    } else {
                        beforeNodeInfo(incomingFlow.getSourceFlowElement(), defKeys);
                    }
                }
            }
        }
    }
 
 
    /**
     * 获取当前节点的上一节点id,不反悔当前节点信息,如果前面是并行,那么会返回多个
     *
     * @param processDefId 流程定义id
     * @param currentNodeDefId 当前节点定义id
     * @return
     */
    public List<String> getBeforeNodeInfo(String processDefId, String currentNodeDefId) {
        // 获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processDefId)
                .singleResult();
 
        // 获取流程模型
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefId);
        if (bpmnModel == null) {
            throw new RuntimeException("BpmnModel not found for processDefinitionId: " + processDefId);
        }
 
        // 获取流程对象
        Process process = bpmnModel.getProcessById(processDefinition.getKey());
        if (process == null) {
            throw new RuntimeException("Process not found for processDefinitionId: " + processDefId);
        }
 
        // 遍历流程元素,找到对应的任务节点
        Collection<FlowElement> flowElements = process.getFlowElements();
        UserTask currentElement = null;
        for (FlowElement flowElement : flowElements) {
            if (flowElement instanceof UserTask && flowElement.getId().equals(currentNodeDefId)) {
                currentElement = (UserTask) flowElement;
                break;
            }
        }
        if (Objects.isNull(currentElement)) {
            throw new RuntimeException("未找到该任务的流程定义节点");
        }
 
        // 获取当前节点的输入
        List<FormDetailVO> defKeys = new ArrayList<>(2);
        this.beforeNodeInfo(currentElement, defKeys);
 
        return defKeys.stream().map(FormDetailVO::getBeforeNodeDefId).collect(Collectors.toList());
    }
 
 
    /**
     * 检查任务节点是否配置了:需要审核  的扩展属性
     *
     * @param extensionElements 扩展列表
     * @return
     */
    public Boolean checkTaskNeedAuditing(List<ExtensionElement> extensionElements) {
        if (CollectionUtils.isEmpty(extensionElements)) {
            return Boolean.FALSE;
        }
        for (ExtensionElement extensionElement : extensionElements) {
            if (CollectionUtils.isEmpty(extensionElement.getAttributes())) { // 如果本身没有属性,则递归child
                return checkTaskNeedAuditing(extensionElement.getChildElements().get("property"));
            } else {
                // 否则先查本身的属性有不有:需要审核 的属性,没有也是递归child
                if (extensionElement.getAttributes().get("name").stream().anyMatch(attribute -> ProcessConstants.EXTENSION_PROPERTY_NEED_AUDITING_TEXT.equals(attribute.getValue()))
                    && extensionElement.getAttributes().get("value").stream().anyMatch(attribute -> ProcessConstants.EXTENSION_PROPERTY_NEED_AUDITING_VALUE.equals(attribute.getValue()))
                ) {
                    return Boolean.TRUE;
                } else {
                    return checkTaskNeedAuditing(extensionElement.getChildElements().get("property"));
                }
            }
        }
        return Boolean.FALSE;
    }
 
 
    /**
     * 驳回任务
     *
     * @param rejectedTaskDefKey 被驳回的任务key
     * @param rejectTaskDefKey 执行驳回操作所在的任务key
     * @param processInsId 流程实例id
     * @param taskId 当前任务id
     * @param msg 审核意见
     */
    public void reject(String rejectedTaskDefKey, String rejectTaskDefKey, String processInsId, String taskId, String msg) {
        // 驳回的核心api:runtimeService.createChangeActivityStateBuilder().moveXXX 的api,可以设置从当前节点移动到目标节点
        // 驳回的核心:需要找到当前节点、以及要流转到的目标节点。其中比较麻烦的是处理并行等比较复杂的情况
        /**
         * 驳回的情况分为以下三种:
         *
         * 1. 如果执行驳回操作的任务是在并行结束的后一个节点,那么被驳回的任务属于并行中的某个分支的结束节点
         * 2. 如果执行驳回操作的节点是并行开始后的某一分支的开始节点,那么该节点和被驳回节点实际上属于串行,          只不过需要同时把其它并行分支也驳回了(这里并不需要手动处理)
         * 3. 如果 被驳回节点和驳回节点属于串行,则直接驳回无需考虑其它
         */
        // 所以重要的是判断两个任务之间是否存在特殊节点,目前只先考虑并行网关
 
        // 设置两条评论
        List<HistoricTaskInstance> rejectedTaskList = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInsId).taskDefinitionKey(rejectedTaskDefKey).orderByHistoricTaskInstanceStartTime().desc().list();
        String msg1 = "驳回了:【" + rejectedTaskList.get(0).getName() + "】,驳回原因:";
        taskService.addComment(taskId, processInsId,  FlowComment.REJECT.getType(), msg1 + msg);
        // TODO 直接使用这个api好像有问题
        runtimeService.createChangeActivityStateBuilder().processInstanceId(processInsId).moveActivityIdTo(rejectTaskDefKey, rejectedTaskDefKey).changeState();
        runtimeService.createChangeActivityStateBuilder().processInstanceId(processInsId).moveExecutionToActivityId(rejectTaskDefKey, rejectedTaskDefKey).changeState();
    }
 
 
 
 
}