整合在线工作流

原创
2018/08/31 18:07
阅读数 171

整合在线工作流

https://blog.csdn.net/zhengyidi1357/article/details/80858865

关闭工作流模型创建编辑器,报错与关闭工作流编辑器

https://blog.csdn.net/u010924288/article/details/51933140

@RequestMapping("/service")
@RestController
@Slf4j
public class ModelEditorJsonRestResource implements ModelDataJsonConstants {
  

  @Autowired
  private RepositoryService repositoryService;
  
  @Autowired
  private ObjectMapper objectMapper;

  @RequestMapping(value="/model/{modelId}/json", method = RequestMethod.GET, produces = "application/json")
  public ObjectNode getEditorJson(@PathVariable String modelId) {
    ObjectNode modelNode = null;
    
    Model model = repositoryService.getModel(modelId);
      
    if (model != null) {
      try {
        if (StringUtils.isNotEmpty(model.getMetaInfo())) {
          modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
        } else {
          modelNode = objectMapper.createObjectNode();
          modelNode.put(MODEL_NAME, model.getName());
        }
        modelNode.put(MODEL_ID, model.getId());
        ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(
            new String(repositoryService.getModelEditorSource(model.getId()), "utf-8"));
        modelNode.set("model", editorJsonNode);
        
      } catch (Exception e) {
        log.error("Error creating model JSON", e);
        throw new ActivitiException("Error creating model JSON", e);
      }
    }
    //modify 将BitunHttpMessageConverter配置一条过滤信息,不用fastjson解析ObjectNode对象
    return modelNode;
  }
}
@RequestMapping("/service")
@RestController
public class ModelSaveRestResource implements ModelDataJsonConstants {
  
  protected static final Logger LOGGER = LoggerFactory.getLogger(ModelSaveRestResource.class);

  @Autowired
  private RepositoryService repositoryService;
  
  @Autowired
  private ObjectMapper objectMapper;

  @RequestMapping(value="/model/{modelId}/save", method = RequestMethod.PUT)
  @ResponseStatus(value = HttpStatus.OK)
  public void saveModel(@PathVariable String modelId, @RequestParam("name") String name,
                        @RequestParam("json_xml") String json_xml, @RequestParam("svg_xml") String svg_xml,
                        @RequestParam("description") String description) {
    try {

      Model model = repositoryService.getModel(modelId);

      ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());

      modelJson.put(MODEL_NAME, name);
      modelJson.put(MODEL_DESCRIPTION, description);
      model.setMetaInfo(modelJson.toString());
      model.setName(name);

      repositoryService.saveModel(model);

      repositoryService.addModelEditorSource(model.getId(), json_xml.getBytes("utf-8"));

      InputStream svgStream = new ByteArrayInputStream(svg_xml.getBytes("utf-8"));
      TranscoderInput input = new TranscoderInput(svgStream);

      PNGTranscoder transcoder = new PNGTranscoder();
      // Setup output
      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      TranscoderOutput output = new TranscoderOutput(outStream);

      // Do the transformation
      transcoder.transcode(input, output);
      final byte[] result = outStream.toByteArray();
      repositoryService.addModelEditorSourceExtra(model.getId(), result);
      outStream.close();

    } catch (Exception e) {
      LOGGER.error("Error saving model", e);
      throw new ActivitiException("Error saving model", e);
    }
  }

}
/**
 * @author Tijs Rademakers
 */
@RequestMapping("/service")
@RestController
public class StencilsetRestResource {
  
  @RequestMapping(value="/editor/stencilset", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
  public JSONObject getStencilset() {
    InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("assets-boss/stencilset.json");
    try {
      //这里必须要经过一次对象转换,不然fastjson解析字符串会出问题
      JSONObject jsonObject = JSON.parseObject(IOUtils.toString(stencilsetStream, "utf-8"));
      return jsonObject;
    } catch (Exception e) {
      throw new ActivitiException("Error while loading stencil set", e);
    }
  }
}
/**
 * @author xiongwei
 * @date 2018/10/31 17:01
*/
@Slf4j
@Controller
@RequestMapping("/activiti/model")
public class ActivitiModelController extends BossBaseController{
 

    @Autowired
    ProcessEngine processEngine;
    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    ModelEditorJsonRestResource modelEditorJsonRestResource;

    @Autowired
    private WorkflowService workflowService;

    /**
     * 新建一个空模型
     */
    @RequestMapping("/create")
    public void newModel(HttpServletResponse response) throws IOException {

        RepositoryService repositoryService = processEngine.getRepositoryService();
        //初始化一个空模型
        Model model = repositoryService.newModel();

        //设置一些默认信息
        String name = "new-process";
        String description = "";
        int revision = 1;
        String key = "process";

        ObjectNode modelNode = objectMapper.createObjectNode();
        modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
        modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
        modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);

        model.setName(name);
        model.setKey(key);
        model.setMetaInfo(modelNode.toString());

        repositoryService.saveModel(model);
        String id = model.getId();

        //完善ModelEditorSource
        ObjectNode editorNode = objectMapper.createObjectNode();
        editorNode.put("id", "canvas");
        editorNode.put("resourceId", "canvas");
        ObjectNode stencilSetNode = objectMapper.createObjectNode();
        stencilSetNode.put("namespace",
                "http://b3mn.org/stencilset/bpmn2.0#");
        editorNode.set("stencilset", stencilSetNode);
        repositoryService.addModelEditorSource(id,editorNode.toString().getBytes("utf-8"));
        response.sendRedirect("/assets-boss/modeler.html?modelId="+id);
    }
 
    /**
     * 获取所有模型
     */
    @RequestMapping("/list")
    public String modelList(HttpServletRequest request, org.springframework.ui.Model model, BossPageVO bossPageVO){
        commonModel(request,model);

        RepositoryService repositoryService = processEngine.getRepositoryService();
        ModelQuery modelQuery = repositoryService.createModelQuery();
        long count = modelQuery.count();
        List<Model> models = modelQuery.orderByCreateTime().desc().listPage((bossPageVO.getPage() - 1) * bossPageVO.getLimit(),bossPageVO.getLimit());

        BossResultPageVO result = new BossResultPageVO();
        result.setPage(bossPageVO.getPage());
        result.setLimit(bossPageVO.getLimit());
        result.setCount(count);
        result.setData(models);
        model.addAttribute("list",result);
        return "activiti/model/list";
    }
 
    /**
     * 发布模型为流程定义
     */
    @RequestMapping("/deploy")
    public Object deploy(HttpServletRequest request, org.springframework.ui.Model sModel, String modelId) throws Exception {

        commonModel(request,sModel);

        //获取模型
        RepositoryService repositoryService = processEngine.getRepositoryService();
        Model modelData = repositoryService.getModel(modelId);
        byte[] bytes = repositoryService.getModelEditorSource(modelData.getId());
 
        if (bytes == null) {
            return "模型数据为空,请先设计流程并成功保存,再进行发布。";
        }
 
        JsonNode modelNode = new ObjectMapper().readTree(bytes);
 
        BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
        if(model.getProcesses().size()==0){
            return "数据模型不符要求,请至少设计一条主线流程。";
        }
        byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);
 
        //发布流程
        String processName = modelData.getName() + ".bpmn20.xml";
        Deployment deployment = repositoryService.createDeployment()
                .name(modelData.getName())
                .addString(processName, new String(bpmnBytes, "UTF-8"))
                .deploy();
        modelData.setDeploymentId(deployment.getId());
        repositoryService.saveModel(modelData);

        sModel.addAttribute(SUCCESS,modelData.getName() + "部署成功");

        return "activiti/model/list";
    }

    /**
     *
     * @return
     */
    @RequestMapping("/queryUnfinishedTask")
    public String queryUnfinishedTask(HttpServletRequest request,org.springframework.ui.Model model, QueryTaskVO queryTaskVO){
        commonModel(request,model);
        BossResultPageVO<Task> list = workflowService.queryUnfinishedTasks(queryTaskVO);
        model.addAttribute("list",list);
        return "activiti/model/unFinishedTaskList";
    }

    /**
     *  提交任务
     */
    @RequestMapping("/complete")
    public String complete(HttpServletRequest request,org.springframework.ui.Model model,ActivitiCompleteTaskBO activitiCompleteTaskBO) {
        commonModel(request,model);
        log.info("complete task the param={}", activitiCompleteTaskBO);
        workflowService.completeTask(activitiCompleteTaskBO);
        return "redirect:/activiti/model/queryUnfinishedTask";
    }

    /**
     * 查询流程图 (中文乱码情况)
     * @param request
     * @param response
     * @param model
     * @param processDefinitionId
     * @return
     * @throws IOException
     */
    @RequestMapping("/showView")
    public String showView(HttpServletRequest request,HttpServletResponse response,org.springframework.ui.Model model,String processDefinitionId) throws IOException {
        commonModel(request,model);
        RepositoryService repositoryService = processEngine.getRepositoryService();

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processDefinitionId)
                .singleResult();
        InputStream inputStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(),
                processDefinition.getDiagramResourceName());
        OutputStream out = response.getOutputStream();
        for(int b = -1;(b=inputStream.read())!=-1;){
            out.write(b);
        }
        out.close();
        inputStream.close();
        return null;
    }

    /**
     * 查询高亮流程图
     * @param request
     * @param response
     * @param model
     * @param processInstanceId
     * @return
     */
    @RequestMapping("/showActiveView")
    public String showActiveView(HttpServletRequest request,HttpServletResponse response,org.springframework.ui.Model model,String processInstanceId) throws IOException {
        commonModel(request,model);
        ProcessInstance pi = this.processEngine.getRuntimeService().createProcessInstanceQuery()
                .processInstanceId(processInstanceId).singleResult();
        BpmnModel bpmnModel = this.processEngine.getRepositoryService().getBpmnModel(pi.getProcessDefinitionId());
        List<String> activeIds = this.processEngine.getRuntimeService().getActiveActivityIds(pi.getId());
        ProcessDiagramGenerator p = new DefaultProcessDiagramGenerator();
        InputStream is = p.generateDiagram(bpmnModel,"png",activeIds, Collections.<String>emptyList(),"宋体","宋体","宋体",null,1.0);

        OutputStream os = response.getOutputStream();

        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }

        os.close();
        is.close();
        return null;
    }

    /**
     * 查询所有已完成节点
     * @param processInstanceId
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/showAllFinishView")
    public String showAllFinishView(String processInstanceId,HttpServletResponse response) throws IOException {
        ProcessInstance processInstance = processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if(processInstance == null){
            throw new RuntimeException("获取流程图异常");
        }else{
            BpmnModel bpmnModel = processEngine.getRepositoryService().getBpmnModel(processInstance.getProcessDefinitionId());
            List<HistoricActivityInstance> activityInstances = processEngine.getHistoryService().createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceStartTime().asc().list();
            List<String> activityIds = new ArrayList<String>();
            ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity)((RepositoryServiceImpl)processEngine.getRepositoryService()).getDeployedProcessDefinition(processInstance.getProcessDefinitionId());
            //获取流程走过的线
            List<String> flowIds = getHighLightedFlows(processDefinition,activityInstances);
            for(HistoricActivityInstance hai:activityInstances){
                //获取流程走过的节点
                activityIds.add(hai.getActivityId());
            }
            InputStream inputStream = new DefaultProcessDiagramGenerator().generateDiagram(bpmnModel, "png", activityIds, flowIds,"宋体","宋体","宋体",null,1.0);
            OutputStream out = response.getOutputStream();
            for(int b = -1;(b=inputStream.read())!=-1;){
                out.write(b);
            }
            out.close();
            inputStream.close();
        }
        return null;
    }

    /**
     * 跳转查看流程图页面
     * @param model
     * @param processInstanceId
     * @return
     */
    @RequestMapping("/redirectShowView")
    public String redirectShowView(org.springframework.ui.Model model,String processInstanceId){
        model.addAttribute("processInstanceId",processInstanceId);
        return "activiti/model/currentView";
    }

    /**
     * 查询用户已办任务(整个流程实例已经结束)
     * @param request
     * @param model
     * @param queryTaskVO
     * @return
     */
    @RequestMapping("/queryFinishedTask")
    public String queryFinishedTask(HttpServletRequest request,org.springframework.ui.Model model, QueryTaskVO queryTaskVO){
        commonModel(request,model);
        BossResultPageVO<HistoricTaskInstance> list = workflowService.queryCompletedTask(queryTaskVO);
        model.addAttribute("list",list);
        return "activiti/model/finishedTaskList";
    }

    /**
     * 查询任务备注
     * @param taskId
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryTaskComment")
    public List<Comment> queryTaskComment(String taskId){
        return workflowService.queryTaskComment(taskId);
    }

    /**
     * 获取流程走过的线
     * @author xiongwei
     * @date 2018/10/31 16:48
    */
    private List<String> getHighLightedFlows(ProcessDefinitionEntity processDefinitionEntity,List<HistoricActivityInstance> haiList){
        //用来保存高亮的线 flowId
        List<String> highFlows = new ArrayList<String>();
        for (int i = 0; i < haiList.size() - 1; i++) {
            //对历史流程节点进行遍历
            //得到节点定义的详细信息
            ActivityImpl activityImpl = processDefinitionEntity.findActivity(haiList.get(i).getActivityId());
            //用以保存后需要开始时间相同的节点
            List<ActivityImpl> sameStartTimeNodes = new ArrayList<ActivityImpl>();
            ActivityImpl sameActivityImpl1 = processDefinitionEntity.findActivity(haiList.get(i + 1).getActivityId());
            //讲后面第一个节点放在时间相同节点的集合里
            sameStartTimeNodes.add(sameActivityImpl1);
            for (int j = i + 1; j < haiList.size() - 1; j++) {
                //后续第一个节点
                HistoricActivityInstance activityImpl1 = haiList.get(j);
                //后续第二个节点
                HistoricActivityInstance activityImpl2 = haiList.get(j + 1);
                if(activityImpl1.getStartTime().equals(activityImpl2.getStartTime())){
                    //如果第一个节点和第二个节点开始时间相同保存
                    ActivityImpl sameActivityImpl2 = processDefinitionEntity.findActivity(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);
                }else{
                    //不同就调查循环
                    break;
                }
            }
            //取出节点的所有出去的线
            List<PvmTransition> pvmTransitions = activityImpl.getOutgoingTransitions();
            for(PvmTransition pvmTransition : pvmTransitions){
                //对所有的线进行遍历
                ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition.getDestination();
                //如果取出的线的目标节点存在时间相同的节点里,保存该线的id,进行高亮显示
                if(sameStartTimeNodes.contains(pvmActivityImpl)){
                    highFlows.add(pvmTransition.getId());
                }
            }
        }
        return highFlows;
    }
}
/**
 * 工作流审核结果全局监听器
 * @author xiongwei
 * @date 2018/10/31 17:02
*/
@Slf4j
public class AuditExecutionListener implements ExecutionListener {
    @Override
    public void notify(DelegateExecution delegateExecution) throws Exception {
        log.info("process event name={},the processBusinessKey={},processInstanceId={}"
                ,delegateExecution.getEventName(),delegateExecution.getProcessBusinessKey()
                ,delegateExecution.getProcessInstanceId());
        //判断是否是结束流程
        if (delegateExecution.getEventName().equals(ExecutionListener.EVENTNAME_END)){
            //获取流程变量
            int auditStatus = (int)delegateExecution.getVariable(ActivitiProcessVariableKey.AUDIT_STATUS.name());
            //设置更新审核记录
            AuditRecord auditRecord = new AuditRecord();
            //判断流程变量的值是否为成功
            auditRecord.setAuditStatus(auditStatus == AuditStatus.FAIL.getCode()
                    ? AuditStatus.FAIL.getCode() : AuditStatus.SUCCESS.getCode());
            auditRecord.setProcessInstanceId(delegateExecution.getProcessInstanceId());
            auditRecord.setUpdateAt(new Date());

            //获取spring ioc容器 bean
            AuditRecordServiceImpl auditRecordService = SpringBeanUtil.getBean(AuditRecordServiceImpl.class);

            //执行更新,当监听器执行失败时,流程是会回滚的
            auditRecordService.update(auditRecord);
        }
    }
}

 

/**
 * @author xiongwei
 * @date 2018/11/1 10:39
*/
@Slf4j
@Service
public class WorkflowServiceImpl implements WorkflowService {

    @Autowired
    ProcessEngine processEngine;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private AuditRecordService auditRecordService;

    /**
     * 开启流程
     * 入参:外部订单号,开启key
     */
    @Override
    public ActivitiStartProcessRespBO startProcess(ActivitiStartProcessBO processBO){

        ActivitiStartProcessRespBO respBO = new ActivitiStartProcessRespBO();
        respBO.setActivitiProcessKey(processBO.getActivitiProcessKey());
        respBO.setAuditStatus(AuditStatus.INIT.getCode());

        //幂等校验
        AuditRecord auditRecord = auditRecordService.queryByOutOrderIdWithKey(processBO.getOutOrderId(),processBO.getActivitiProcessKey().name());
        if (auditRecord != null){
            respBO.setAuditStatus(auditRecord.getAuditStatus());
            respBO.setProcessInstanceId(auditRecord.getProcessInstanceId());
            return respBO;
        }
        //开启事务
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                //启动流程
                ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceByKey(processBO.getActivitiProcessKey().name(),processBO.getOutOrderId().toString());
                //流程实例Id
                String pId = processInstance.getProcessInstanceId();
                //设置审核记录
                AuditRecord record = setAuditRecord(processBO,pId);
                //往审核记录表插入一条处理数据
                auditRecordService.create(record);

                respBO.setProcessInstanceId(pId);
            }
        });
        //返回结果
        return respBO;
    }

    /**
     * 查询待办任务
     * @return
     */
    @Override
    public BossResultPageVO<Task> queryUnfinishedTasks(QueryTaskVO param){
        //获取当前登录用户角色集合
        Set<BossRoleVO> roles = BossAppContext.getCurrentUser().getRoles();
        //获取用户所有角色ID
        List<String> roleIds = new ArrayList<>(roles.size());
        //Long变成String
        roles.forEach(o ->{
            roleIds.add(o.getId().toString());
        });

        //查询所有类型审核待办任务
        TaskQuery taskQuery = processEngine.getTaskService().createTaskQuery().taskCandidateGroupIn(roleIds);
        //判断是否查询特定待办任务
        if (param.getActivitProcessKey() != null){
            //查询特定审核待办任务
            taskQuery.processDefinitionKey(param.getActivitProcessKey().name());
        }
        //不为空则查询流程所有阶段用户任务
        if (StringUtils.isNotBlank(param.getTaskKey())){
            taskQuery.taskDefinitionKey(param.getTaskKey());
        }
        //记录条数
        long count = taskQuery.count();

        //查询记录
        List<Task> tasks;
        if (count > 0){
            tasks = taskQuery.orderByTaskCreateTime().desc().listPage(param.getStartPage(),param.getLimit());
        }else {
            tasks = new ArrayList<>();
        }

        //设置结果
        BossResultPageVO<Task> result = new BossResultPageVO<Task>();
        result.setPage(param.getPage() - 1);
        result.setLimit(param.getLimit());
        result.setCount(count);
        result.setData(tasks);
        return result;
    }

    @Override
    public BossResultPageVO<AuditTaskVO> queryAuditTasks(QueryTaskVO param) {
        //获取任务
        BossResultPageVO<Task> data = queryUnfinishedTasks(param);
        //设置结果
        BossResultPageVO<AuditTaskVO> result = new BossResultPageVO<AuditTaskVO>();
        //结果复制
        BeanUtils.copyProperties(data,result);


        List<AuditTaskVO> auditVOList = new ArrayList<>();

        data.getData().forEach(o -> {

            //查询审核记录
            AuditRecord auditRecord = auditRecordService.queryByProcessInstanceIdWithBLOBs(o.getProcessInstanceId());

            JSONObject jsonObject = JSONObject.parseObject(auditRecord.getAuditData());

            AuditTaskVO vo = new AuditTaskVO();
            vo.setTask(o);
            vo.setAuditData(jsonObject);

            auditVOList.add(vo);
        });

        result.setData(auditVOList);

        return result;
    }

    /**
     * 查询已完成任务
     * @param queryTaskVO
     * @return
     */
    @Override
    public BossResultPageVO<HistoricTaskInstance> queryCompletedTask(QueryTaskVO queryTaskVO){
        log.info("query user completed task the param={}",queryTaskVO);
        //获取用户名
        String username = BossAppContext.getCurrentUser().getUsername();
        //仅仅查询当前用户办过的任务
        HistoricTaskInstanceQuery hisTaskInsQuery = processEngine.getHistoryService().createHistoricTaskInstanceQuery().taskAssignee(username);

        //不为空则查询特定流程任务
        if (queryTaskVO.getActivitProcessKey() != null){
            hisTaskInsQuery.processFinished().processDefinitionKey(queryTaskVO.getActivitProcessKey().name());
        }
        //不为空则查询流程所有阶段用户任务
        if (StringUtils.isNotBlank(queryTaskVO.getTaskKey())){
            hisTaskInsQuery.taskDefinitionKey(queryTaskVO.getTaskKey());
        }

        //统计记录条数
        long count = hisTaskInsQuery.count();
        //查询记录
        List<HistoricTaskInstance> tasks = hisTaskInsQuery.orderByTaskCreateTime().desc().listPage(queryTaskVO.getStartPage(),queryTaskVO.getLimit());
        //设置返回对象
        BossResultPageVO<HistoricTaskInstance> result = new BossResultPageVO<HistoricTaskInstance>();
        result.setPage(queryTaskVO.getPage() - 1);
        result.setLimit(queryTaskVO.getLimit());
        result.setCount(count);
        result.setData(tasks);
        log.info("query user completed task the param={}",queryTaskVO);
        return result;
    }

    /**
     * 完成任务
     * @param activitiCompleteTaskBO
     */
    @Override
    public void completeTask(ActivitiCompleteTaskBO activitiCompleteTaskBO){
        log.info("user complete task the param={}",activitiCompleteTaskBO);
        String taskId = activitiCompleteTaskBO.getTaskId();
        //设置流程变量
        Map<String, Object> var = new HashMap(1);
        //设置审核状态
        var.put(ActivitiProcessVariableKey.AUDIT_STATUS.name(),activitiCompleteTaskBO.getAuditStatus());
        //获取taskService
        TaskService taskService = processEngine.getTaskService();
        //查询任务判断任务十分存在
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //判断查询结果
        if (task == null){
            throw new BossNotExistException("query task is not exist by taskId = " + taskId);
        }
        //判断备注是否为null
        if (activitiCompleteTaskBO.getRemark() == null){
            activitiCompleteTaskBO.setRemark(activitiCompleteTaskBO.getAuditStatus().equals(AuditStatus.SUCCESS.getCode())
                    ? "同意" : "不同意");
        }
        //获取当前系统登录用户
        BossUserVO user = BossAppContext.getCurrentUser();
        //开启事务
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                //签收任务
                taskService.claim(taskId, user.getUsername());
                //设置当前用户
                Authentication.setAuthenticatedUserId(user.getUsername());
                //设置备注
                taskService.addComment(taskId,task.getProcessInstanceId(),activitiCompleteTaskBO.getRemark());
                //完成任务
                taskService.complete(taskId,var);
            }
        });

    }

    @Override
    public List<Comment> queryTaskComment(String taskId) {
        return processEngine.getTaskService().getTaskComments(taskId);
    }

    @Override
    public ProcessInstance queryProcessInstanceById(String processInstance) {
        return processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstance).singleResult();
    }

    /**
     * 保存用户
     * @param username 用户名
     */
    @Override
    public void saveUser(String username){
        log.info("save activiti user,the username = {}",username);
        IdentityService identityService=processEngine.getIdentityService();
        User user = new UserEntity(username);
        identityService.saveUser(user);
    }

    /**
     * 删除用户
     * @param username 用户名
     */
    @Override
    public void delUser(String username){
        IdentityService identityService=processEngine.getIdentityService();
        identityService.deleteUser(username);
    }

    /**
     * 创建组
     * @param roleNo
     */
    @Override
    public void saveGroup(Long roleNo){
        IdentityService identityService=processEngine.getIdentityService();
        Group group = new GroupEntity(roleNo.toString());
        identityService.saveGroup(group);
    }

    /**
     * 删除组
     * @param roleNo
     */
    @Override
    public void delGroup(Long roleNo){
        IdentityService identityService=processEngine.getIdentityService();
        identityService.deleteGroup(roleNo.toString());
    }

    /**
     * 创建用户和组关联
     * @param username
     * @param roleNo
     */
    @Override
    public void saveMembership(String username,Long roleNo){
        log.info("create member ship,the userId={},groupId={}",username,roleNo);
        IdentityService identityService=processEngine.getIdentityService();
        identityService.createMembership(username,roleNo.toString());
    }

    /**
     * 删除用户和组关联
     * @param username
     * @param roleNo
     */
    @Override
    public void delMembership(String username,Long roleNo){
        IdentityService identityService=processEngine.getIdentityService();
        identityService.deleteMembership(username,roleNo.toString());
    }

    /**
     * 设置审核记录
     * @param activitiStartProcessBO
     * @param pId
     * @return
     */
    private AuditRecord setAuditRecord(ActivitiStartProcessBO activitiStartProcessBO,String pId){
        AuditRecord record = new AuditRecord();
        record.setOutOrderId(activitiStartProcessBO.getOutOrderId());
        record.setProcessInstanceId(pId);
        record.setProcessInstanceKey(activitiStartProcessBO.getActivitiProcessKey().name());
        record.setAuditStatus(AuditStatus.INIT.getCode());
        record.setAuditData(activitiStartProcessBO.getAuditData());
        record.setCallbackStatus(CallbackStatus.INIT.getCode());
        Date now = new Date();
        record.setCreateAt(now);
        record.setUpdateAt(now);
        return record;
    }
}

 

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部