zhangherong
2025-06-25 23855599412c4d61b38d78f0f3abd3430a48b5b1
lxzn-module-flowable/src/main/java/org/jeecg/modules/flowable/service/impl/FlowInstanceServiceImpl.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,185 @@
package org.jeecg.modules.flowable.service.impl;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.flowable.apithird.business.entity.FlowMyBusiness;
import org.jeecg.modules.flowable.apithird.business.service.impl.FlowMyBusinessServiceImpl;
import org.jeecg.modules.flowable.apithird.common.exception.CustomException;
import org.jeecg.modules.flowable.apithird.entity.SysUser;
import org.jeecg.modules.flowable.apithird.service.FlowCallBackServiceI;
import org.jeecg.modules.flowable.apithird.service.IFlowThirdService;
import org.jeecg.modules.flowable.domain.vo.FlowTaskVo;
import org.jeecg.modules.flowable.factory.FlowServiceFactory;
import org.jeecg.modules.flowable.service.IFlowInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
 * <p>工作流流程实例管理<p>
 *
 */
@Service
@Slf4j
public class FlowInstanceServiceImpl extends FlowServiceFactory implements IFlowInstanceService {
    @Autowired
    IFlowThirdService iFlowThirdService;
    @Autowired
    FlowMyBusinessServiceImpl flowMyBusinessService;
    @Override
    public List<Task> queryListByInstanceId(String instanceId) {
        List<Task> list = taskService.createTaskQuery().processInstanceId(instanceId).active().list();
        return list;
    }
    /**
     * ç»“束流程实例
     *
     * @param vo
     */
    @Override
    public void stopProcessInstance(FlowTaskVo vo) {
        String taskId = vo.getTaskId();
    }
    /**
     * æ¿€æ´»æˆ–挂起流程实例
     *
     * @param state      çŠ¶æ€
     * @param instanceId æµç¨‹å®žä¾‹ID
     */
    @Override
    public void updateState(Integer state, String instanceId) {
        // æ¿€æ´»
        if (state == 1) {
            runtimeService.activateProcessInstanceById(instanceId);
        }
        // æŒ‚èµ·
        if (state == 2) {
            runtimeService.suspendProcessInstanceById(instanceId);
        }
    }
    /**
     * åˆ é™¤æµç¨‹å®žä¾‹ID
     *
     * @param instanceId   æµç¨‹å®žä¾‹ID
     * @param deleteReason åˆ é™¤åŽŸå› 
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String instanceId, String deleteReason) {
        List<Task> task = taskService.createTaskQuery().processInstanceId(instanceId).list();
        if (CollectionUtils.isEmpty(task)) {
            throw new CustomException("流程未启动或已执行完成,取消申请失败");
        }
        // æŸ¥è¯¢åŽ†å²æ•°æ®
        HistoricProcessInstance historicProcessInstance = getHistoricProcessInstanceById(instanceId);
        if (historicProcessInstance.getEndTime() != null) {
            historyService.deleteHistoricProcessInstance(historicProcessInstance.getId());
            return;
        }
        // åˆ é™¤æµç¨‹å®žä¾‹
        runtimeService.deleteProcessInstance(instanceId, deleteReason);
        // åˆ é™¤åŽ†å²æµç¨‹å®žä¾‹
        historyService.deleteHistoricProcessInstance(instanceId);
        /*======================撤回删除 å›žè°ƒä»¥åŠå…³é”®æ•°æ®ä¿å­˜======================*/
        LambdaQueryWrapper<FlowMyBusiness> flowMyBusinessLambdaQueryWrapper = new LambdaQueryWrapper<>();
        flowMyBusinessLambdaQueryWrapper.eq(FlowMyBusiness::getProcessInstanceId,instanceId)
        ;
        //如果保存数据前未调用必调的FlowCommonService.initActBusiness方法,就会有问题
        FlowMyBusiness business = flowMyBusinessService.getOne(flowMyBusinessLambdaQueryWrapper);
        //设置数据
        String doneUsers = business.getDoneUsers();
        SysUser sysUser = iFlowThirdService.getLoginUser();
        // å¤„理过流程的人
        JSONArray doneUserList = new JSONArray();
        if (StrUtil.isNotBlank(doneUsers)){
            doneUserList = JSON.parseArray(doneUsers);
        }
        if (!doneUserList.contains(sysUser.getUsername())){
            doneUserList.add(sysUser.getUsername());
        }
            business
//                    .setActStatus(ActStatus.recall)
                    .setTaskId("")
                    .setTaskName("已撤回")
                    .setPriority("")
                    .setDoneUsers(doneUserList.toJSONString())
                    .setTodoUsers("")
            ;
        flowMyBusinessService.updateById(business);
        //spring容器类名
        String serviceImplName = business.getServiceImplName();
        FlowCallBackServiceI flowCallBackService = (FlowCallBackServiceI) SpringContextUtils.getBean(serviceImplName);
        // æµç¨‹å¤„理完后,进行回调业务层
        if (flowCallBackService!=null)flowCallBackService.afterFlowHandle(business);
    }
    @Override
    public void deleteByDataId(String dataId, String deleteReason) {
        LambdaQueryWrapper<FlowMyBusiness> flowMyBusinessLambdaQueryWrapper = new LambdaQueryWrapper<>();
        flowMyBusinessLambdaQueryWrapper.eq(FlowMyBusiness::getDataId, dataId)
        ;
        //如果保存数据前未调用必调的FlowCommonService.initActBusiness方法,就会有问题
        FlowMyBusiness business = flowMyBusinessService.getOne(flowMyBusinessLambdaQueryWrapper);
        this.delete(business.getProcessInstanceId(),deleteReason);
    }
    /**
     * æ ¹æ®å®žä¾‹ID查询历史实例数据
     *
     * @param processInstanceId
     * @return
     */
    @Override
    public HistoricProcessInstance getHistoricProcessInstanceById(String processInstanceId) {
        HistoricProcessInstance historicProcessInstance =
                historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if (Objects.isNull(historicProcessInstance)) {
            throw new FlowableObjectNotFoundException("流程实例不存在: " + processInstanceId);
        }
        return historicProcessInstance;
    }
    /**
     * æ ¹æ®æµç¨‹å®šä¹‰ID启动流程实例
     *
     * @param procDefId æµç¨‹å®šä¹‰Id
     * @param variables æµç¨‹å˜é‡
     * @return
     */
    @Override
    public Result startProcessInstanceById(String procDefId, Map<String, Object> variables) {
            // è®¾ç½®æµç¨‹å‘起人Id到流程中
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String username = user.getUsername();
//            identityService.setAuthenticatedUserId(userId.toString());
            variables.put("initiator",username);
            variables.put("_FLOWABLE_SKIP_EXPRESSION_ENABLED", true);
            ProcessInstance processInstance = runtimeService.startProcessInstanceById(procDefId, variables);
            processInstance.getProcessInstanceId();
            return Result.OK("流程启动成功");
    }
}