gssong
2024-04-08 040ecb2532859f369518cb49287c5c2d4cf22308
ruoyi-modules/ruoyi-workflow/src/main/java/org/dromara/workflow/service/impl/ActProcessDefinitionServiceImpl.java
@@ -4,8 +4,10 @@
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
@@ -17,25 +19,36 @@
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.workflow.common.constant.FlowConstant;
import org.dromara.workflow.domain.WfCategory;
import org.dromara.workflow.domain.WfDefinitionConfig;
import org.dromara.workflow.domain.WfNodeConfig;
import org.dromara.workflow.domain.bo.ProcessDefinitionBo;
import org.dromara.workflow.domain.bo.WfDefinitionConfigBo;
import org.dromara.workflow.domain.vo.ProcessDefinitionVo;
import org.dromara.workflow.domain.vo.WfDefinitionConfigVo;
import org.dromara.workflow.mapper.WfDefinitionConfigMapper;
import org.dromara.workflow.service.IActProcessDefinitionService;
import org.dromara.workflow.service.IWfCategoryService;
import org.dromara.workflow.service.IWfDefinitionConfigService;
import org.dromara.workflow.service.IWfNodeConfigService;
import org.dromara.workflow.utils.ModelUtils;
import org.dromara.workflow.utils.QueryUtils;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.ProcessMigrationService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.impl.bpmn.deployer.ResourceNameUtil;
import org.flowable.engine.repository.*;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
@@ -50,6 +63,9 @@
    private final RepositoryService repositoryService;
    private final ProcessMigrationService processMigrationService;
    private final IWfCategoryService wfCategoryService;
    private final IWfDefinitionConfigService iWfDefinitionConfigService;
    private final WfDefinitionConfigMapper wfDefinitionConfigMapper;
    private final IWfNodeConfigService iWfNodeConfigService;
    /**
     * 分页查询
@@ -78,20 +94,29 @@
            List<String> deploymentIds = StreamUtils.toList(definitionList, ProcessDefinition::getDeploymentId);
            deploymentList = QueryUtils.deploymentQuery(deploymentIds).list();
        }
        for (ProcessDefinition processDefinition : definitionList) {
            ProcessDefinitionVo processDefinitionVo = BeanUtil.toBean(processDefinition, ProcessDefinitionVo.class);
            if (CollUtil.isNotEmpty(deploymentList)) {
                // 部署时间
                deploymentList.stream().filter(e -> e.getId().equals(processDefinition.getDeploymentId())).findFirst().ifPresent(e -> {
                    processDefinitionVo.setDeploymentTime(e.getDeploymentTime());
                });
        if (CollUtil.isNotEmpty(definitionList)) {
            List<String> ids = StreamUtils.toList(definitionList, ProcessDefinition::getId);
            List<WfDefinitionConfigVo> wfDefinitionConfigVos = iWfDefinitionConfigService.queryList(ids);
            for (ProcessDefinition processDefinition : definitionList) {
                ProcessDefinitionVo processDefinitionVo = BeanUtil.toBean(processDefinition, ProcessDefinitionVo.class);
                if (CollUtil.isNotEmpty(deploymentList)) {
                    // 部署时间
                    deploymentList.stream().filter(e -> e.getId().equals(processDefinition.getDeploymentId())).findFirst().ifPresent(e -> {
                        processDefinitionVo.setDeploymentTime(e.getDeploymentTime());
                    });
                }
                if (CollUtil.isNotEmpty(wfDefinitionConfigVos)) {
                    wfDefinitionConfigVos.stream().filter(e -> e.getDefinitionId().equals(processDefinition.getId())).findFirst().ifPresent(processDefinitionVo::setWfDefinitionConfigVo);
                }
                processDefinitionVoList.add(processDefinitionVo);
            }
            processDefinitionVoList.add(processDefinitionVo);
        }
        // 总记录数
        long total = query.count();
        return new TableDataInfo<>(processDefinitionVoList, total);
        TableDataInfo<ProcessDefinitionVo> build = TableDataInfo.build();
        build.setRows(processDefinitionVoList);
        build.setTotal(total);
        return build;
    }
    /**
@@ -106,18 +131,25 @@
        List<ProcessDefinition> definitionList = query.processDefinitionKey(key).list();
        List<Deployment> deploymentList = null;
        if (CollUtil.isNotEmpty(definitionList)) {
            List<String> deploymentIds = definitionList.stream().map(ProcessDefinition::getDeploymentId).collect(Collectors.toList());
            List<String> deploymentIds = StreamUtils.toList(definitionList, ProcessDefinition::getDeploymentId);
            deploymentList = QueryUtils.deploymentQuery(deploymentIds).list();
        }
        for (ProcessDefinition processDefinition : definitionList) {
            ProcessDefinitionVo processDefinitionVo = BeanUtil.toBean(processDefinition, ProcessDefinitionVo.class);
            if (CollUtil.isNotEmpty(deploymentList)) {
                // 部署时间
                deploymentList.stream().filter(e -> e.getId().equals(processDefinition.getDeploymentId())).findFirst().ifPresent(e -> {
                    processDefinitionVo.setDeploymentTime(e.getDeploymentTime());
                });
        if (CollUtil.isNotEmpty(definitionList)) {
            List<String> ids = StreamUtils.toList(definitionList, ProcessDefinition::getId);
            List<WfDefinitionConfigVo> wfDefinitionConfigVos = iWfDefinitionConfigService.queryList(ids);
            for (ProcessDefinition processDefinition : definitionList) {
                ProcessDefinitionVo processDefinitionVo = BeanUtil.toBean(processDefinition, ProcessDefinitionVo.class);
                if (CollUtil.isNotEmpty(deploymentList)) {
                    // 部署时间
                    deploymentList.stream().filter(e -> e.getId().equals(processDefinition.getDeploymentId())).findFirst().ifPresent(e -> {
                        processDefinitionVo.setDeploymentTime(e.getDeploymentTime());
                    });
                    if (CollUtil.isNotEmpty(wfDefinitionConfigVos)) {
                        wfDefinitionConfigVos.stream().filter(e -> e.getDefinitionId().equals(processDefinition.getId())).findFirst().ifPresent(processDefinitionVo::setWfDefinitionConfigVo);
                    }
                }
                processDefinitionVoList.add(processDefinitionVo);
            }
            processDefinitionVoList.add(processDefinitionVo);
        }
        return CollectionUtil.reverse(processDefinitionVoList);
    }
@@ -160,6 +192,7 @@
     * @param processDefinitionId 流程定义id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDeployment(String deploymentId, String processDefinitionId) {
        try {
            List<HistoricTaskInstance> taskInstanceList = QueryUtils.hisTaskInstanceQuery()
@@ -169,6 +202,10 @@
            }
            //删除流程定义
            repositoryService.deleteDeployment(deploymentId);
            //删除流程定义配置
            iWfDefinitionConfigService.deleteByDefIds(Collections.singletonList(processDefinitionId));
            //删除节点配置
            iWfNodeConfigService.deleteByDefIds(Collections.singletonList(processDefinitionId));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
@@ -265,59 +302,137 @@
     * @param file         文件
     * @param categoryCode 分类
     */
    @SneakyThrows
    @Override
    public boolean deployByFile(MultipartFile file, String categoryCode) {
        try {
            WfCategory wfCategory = wfCategoryService.queryByCategoryCode(categoryCode);
            if (wfCategory == null) {
                throw new ServiceException("流程分类不存在");
            }
            // 文件名 = 流程名称-流程key
            String filename = file.getOriginalFilename();
            assert filename != null;
            String[] splitFilename = filename.substring(0, filename.lastIndexOf(".")).split("-");
            if (splitFilename.length < 2) {
                throw new ServiceException("流程分类不能为空(文件名 = 流程名称-流程key)");
            }
            //流程名称
            String processName = splitFilename[0];
            //流程key
            String processKey = splitFilename[1];
            // 文件后缀名
            String suffix = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            InputStream inputStream = file.getInputStream();
            Deployment deployment;
            if (FlowConstant.ZIP.equals(suffix)) {
                DeploymentBuilder builder = repositoryService.createDeployment();
                deployment = builder.addZipInputStream(new ZipInputStream(inputStream))
                    .tenantId(TenantHelper.getTenantId())
                    .name(processName).key(processKey).category(categoryCode).deploy();
            } else {
                String[] list = ResourceNameUtil.BPMN_RESOURCE_SUFFIXES;
                boolean flag = false;
                for (String str : list) {
                    if (filename.contains(str)) {
                        flag = true;
                        break;
                    }
                }
                if (flag) {
    @Transactional(rollbackFor = Exception.class)
    public void deployByFile(MultipartFile file, String categoryCode) {
        WfCategory wfCategory = wfCategoryService.queryByCategoryCode(categoryCode);
        if (wfCategory == null) {
            throw new ServiceException("流程分类不存在");
        }
        // 文件后缀名
        String suffix = FileUtil.extName(file.getOriginalFilename());
        InputStream inputStream = file.getInputStream();
        if (FlowConstant.ZIP.equalsIgnoreCase(suffix)) {
            ZipInputStream zipInputStream = null;
            try {
                zipInputStream = new ZipInputStream(inputStream);
                ZipEntry zipEntry;
                while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                    String filename = zipEntry.getName();
                    String[] splitFilename = filename.substring(0, filename.lastIndexOf(".")).split("-");
                    //流程名称
                    String processName = splitFilename[0];
                    //流程key
                    String processKey = splitFilename[1];
                    ProcessDefinition oldProcessDefinition = QueryUtils.definitionQuery().processDefinitionKey(processKey).latestVersion().singleResult();
                    DeploymentBuilder builder = repositoryService.createDeployment();
                    deployment = builder.addInputStream(filename, inputStream)
                    Deployment deployment = builder.addInputStream(filename, zipInputStream)
                        .tenantId(TenantHelper.getTenantId())
                        .name(processName).key(processKey).category(categoryCode).deploy();
                } else {
                    throw new ServiceException("文件类型上传错误!");
                    ProcessDefinition definition = QueryUtils.definitionQuery().deploymentId(deployment.getId()).singleResult();
                    repositoryService.setProcessDefinitionCategory(definition.getId(), categoryCode);
                    setWfConfig(oldProcessDefinition, definition);
                    zipInputStream.closeEntry();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (zipInputStream != null) {
                    zipInputStream.close();
                }
            }
            // 更新分类
            ProcessDefinition definition = QueryUtils.definitionQuery().deploymentId(deployment.getId()).singleResult();
            repositoryService.setProcessDefinitionCategory(definition.getId(), categoryCode);
            //初始化配置数据(demo使用,不用可删除)
            initWfDefConfig();
        } else {
            String originalFilename = file.getOriginalFilename();
            String bpmnResourceSuffix = ResourceNameUtil.BPMN_RESOURCE_SUFFIXES[0];
            if (originalFilename.contains(bpmnResourceSuffix)) {
                // 文件名 = 流程名称-流程key
                String[] splitFilename = originalFilename.substring(0, originalFilename.lastIndexOf(".")).split("-");
                if (splitFilename.length < 2) {
                    throw new ServiceException("文件名 = 流程名称-流程KEY");
                }
                //流程名称
                String processName = splitFilename[0];
                //流程key
                String processKey = splitFilename[1];
                ProcessDefinition oldProcessDefinition = QueryUtils.definitionQuery().processDefinitionKey(processKey).latestVersion().singleResult();
                DeploymentBuilder builder = repositoryService.createDeployment();
                Deployment deployment = builder.addInputStream(originalFilename, inputStream)
                    .tenantId(TenantHelper.getTenantId())
                    .name(processName).key(processKey).category(categoryCode).deploy();
                // 更新分类
                ProcessDefinition definition = QueryUtils.definitionQuery().deploymentId(deployment.getId()).singleResult();
                repositoryService.setProcessDefinitionCategory(definition.getId(), categoryCode);
                setWfConfig(oldProcessDefinition, definition);
            } else {
                throw new ServiceException("文件类型上传错误!");
            }
        }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("部署失败" + e.getMessage());
    }
    /**
     * 初始化配置数据(demo使用,不用可删除)
     */
    private void initWfDefConfig() {
        List<WfDefinitionConfig> wfDefinitionConfigs = wfDefinitionConfigMapper.selectList();
        if (CollUtil.isEmpty(wfDefinitionConfigs)) {
            ProcessDefinition processDefinition = QueryUtils.definitionQuery().processDefinitionKey("leave1").latestVersion().singleResult();
            if (processDefinition != null) {
                WfDefinitionConfigBo wfFormDefinition = new WfDefinitionConfigBo();
                wfFormDefinition.setDefinitionId(processDefinition.getId());
                wfFormDefinition.setProcessKey(processDefinition.getKey());
                wfFormDefinition.setTableName("test_leave");
                wfFormDefinition.setVersion(processDefinition.getVersion());
                iWfDefinitionConfigService.saveOrUpdate(wfFormDefinition);
            }
        }
    }
    /**
     * 设置表单内容
     *
     * @param oldProcessDefinition 部署前最新流程定义
     * @param definition           部署后最新流程定义
     */
    private void setWfConfig(ProcessDefinition oldProcessDefinition, ProcessDefinition definition) {
        //更新流程定义表单
        if (oldProcessDefinition != null) {
            WfDefinitionConfigVo definitionVo = iWfDefinitionConfigService.getByDefId(oldProcessDefinition.getId());
            if (definitionVo != null) {
                iWfDefinitionConfigService.deleteByDefIds(Collections.singletonList(oldProcessDefinition.getId()));
                WfDefinitionConfigBo wfFormDefinition = new WfDefinitionConfigBo();
                wfFormDefinition.setDefinitionId(definition.getId());
                wfFormDefinition.setProcessKey(definition.getKey());
                wfFormDefinition.setTableName(definitionVo.getTableName());
                wfFormDefinition.setVersion(definition.getVersion());
                wfFormDefinition.setRemark(definitionVo.getRemark());
                iWfDefinitionConfigService.saveOrUpdate(wfFormDefinition);
            }
        }
        //更新流程节点配置表单
        List<UserTask> userTasks = ModelUtils.getUserTaskFlowElements(definition.getId());
        UserTask applyUserTask = ModelUtils.getApplyUserTask(definition.getId());
        List<WfNodeConfig> wfNodeConfigList = new ArrayList<>();
        for (UserTask userTask : userTasks) {
            if (StringUtils.isNotBlank(userTask.getFormKey()) && userTask.getFormKey().contains(StrUtil.COLON)) {
                WfNodeConfig wfNodeConfig = new WfNodeConfig();
                wfNodeConfig.setNodeId(userTask.getId());
                wfNodeConfig.setNodeName(userTask.getName());
                wfNodeConfig.setDefinitionId(definition.getId());
                String[] split = userTask.getFormKey().split(StrUtil.COLON);
                wfNodeConfig.setFormType(split[0]);
                wfNodeConfig.setFormId(Long.valueOf(split[1]));
                wfNodeConfig.setApplyUserTask(applyUserTask.getId().equals(userTask.getId()) ? FlowConstant.TRUE : FlowConstant.FALSE);
                wfNodeConfigList.add(wfNodeConfig);
            }
        }
        if (CollUtil.isNotEmpty(wfNodeConfigList)) {
            iWfNodeConfigService.saveOrUpdate(wfNodeConfigList);
        }
    }
}