activiti使用实践案例

最进根据公司需求,需要使用工作流工具实现一套复杂的审核流程,

审批业务流程图如下:

activiti使用实践案例_第1张图片

根据业务流程图绘制的BPMN图:

主要实现思想:

 1.以vote变量为投票标识 1为通过,2为驳回

 2.使用脚本任务作为业务相关的操作(审核楼层你以外的业务操作,例如当前两部驳回后会修改采购清单的业务状态为编制中)

 3.通过监听器的方式实现消息的推送(例如审核通过发送站内信和短信通知下一步人员进行操作)

 4.其中有一步是平台干涉的(配货定价这一步,此处是非审核人的操作,此时审核任务需挂起等待平台配货),此处选择使用接收 任务,当配货完成,调用任务的signal()激活任务使之继续向下流转



activiti使用实践案例_第2张图片

bpmn图对应的bpmn20.xml代码(可直接将代码保存为bpmn后缀然后查看对应bpmn图):


xml version="1.0" encoding="UTF-8" standalone="yes"?>
xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" xmlns:tns="http://www.activiti.org/test" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" expressionLanguage="http://www.w3.org/1999/XPath" id="m1516329136940" name="" targetNamespace="http://www.activiti.org/test" typeLanguage="http://www.w3.org/2001/XMLSchema">
  id="auditListPurchase" isClosed="false" isExecutable="true" name="auditListPurchase" processType="None">
    id="auditListPurchaseStartEvent" name="开始"/>
    id="auditListPurchaseProcessEndEvent" name="结束"/>
    activiti:assignee="${startUser}" activiti:exclusive="true" id="startUser" name="提交采购需求">
      
        <activiti:taskListener class="com.sjgtw.business.service.workflow.ApprovalUserTaskListener" event="complete">
          <activiti:field name="passSendFlag">
            <activiti:string>0activiti:string>
          activiti:field>
        activiti:taskListener>
      
    
    activiti:assignee="${auditPM}" activiti:exclusive="true" id="auditPM" name="项目经理审核">
      
        <activiti:taskListener class="com.sjgtw.business.service.workflow.ApprovalUserTaskListener" event="complete">
          <activiti:field name="passSendFlag">
            <activiti:string>1activiti:string>
          activiti:field>
        activiti:taskListener>
      
    
    activiti:assignee="${auditMaterial}" activiti:exclusive="true" id="auditMaterial" name="物设部审核">
      
        <activiti:taskListener class="com.sjgtw.business.service.workflow.ApprovalUserTaskListener" event="complete">
          <activiti:field name="passSendFlag">
            <activiti:string>1activiti:string>
          activiti:field>
        activiti:taskListener>
      
    
    activiti:exclusive="true" id="distributionPricing" name="配货定价"/>
    activiti:assignee="${auditMaterial1}" activiti:exclusive="true" id="auditMaterial1" name="物设部负责人审核">
      
        <activiti:taskListener class="com.sjgtw.business.service.workflow.ApprovalUserTaskListener" event="complete">
          <activiti:field name="passSendFlag">
            <activiti:string>1activiti:string>
          activiti:field>
        activiti:taskListener>
      
    
    activiti:assignee="${auditMaterialManager}" activiti:exclusive="true" id="auditMaterialManager" name="物设部部长审核">
      
        <activiti:taskListener class="com.sjgtw.business.service.workflow.ApprovalUserTaskListener" event="complete">
          <activiti:field name="passSendFlag">
            <activiti:string>1activiti:string>
          activiti:field>
        activiti:taskListener>
      
    
    activiti:assignee="${auditMaterialMajor}" activiti:exclusive="true" id="auditMaterialMajor" name="分管副总审核">
      
        <activiti:taskListener class="com.sjgtw.business.service.workflow.ApprovalUserTaskListener" event="complete">
          <activiti:field name="passSendFlag">
            <activiti:string>1activiti:string>
          activiti:field>
        activiti:taskListener>
      
    
    id="_18" name="通过" sourceRef="startUser" targetRef="auditPM">
      xsi:type="tFormalExpression">
    
    id="_19" name="通过" sourceRef="auditPM" targetRef="auditMaterial">
      xsi:type="tFormalExpression">
    
    id="_20" sourceRef="distributionPricing" targetRef="auditMaterial1"/>
    id="_21" name="通过" sourceRef="auditMaterial1" targetRef="auditMaterialManager">
      xsi:type="tFormalExpression">
    
    id="_22" name="通过" sourceRef="auditMaterialManager" targetRef="auditMaterialMajor">
      xsi:type="tFormalExpression">
    
    id="_13" sourceRef="auditListPurchaseStartEvent" targetRef="startUser"/>
    activiti:exclusive="true" id="updateListPurchase2Edit" name="更新状态为编制中" scriptFormat="groovy">
      
    
    id="_17" name="驳回" sourceRef="auditMaterial" targetRef="updateListPurchase2Edit">
      xsi:type="tFormalExpression">
    
    id="_23" name="驳回" sourceRef="auditPM" targetRef="updateListPurchase2Edit">
      xsi:type="tFormalExpression">
    
    id="_24" sourceRef="updateListPurchase2Edit" targetRef="startUser"/>
    activiti:exclusive="true" id="updateListPurchase2Distribution" name="更新状态为配货" scriptFormat="groovy">
      
        <activiti:executionListener class="com.sjgtw.business.service.workflow.PriceExecutionListener" event="start">
          <activiti:field name="orderFlag">
            <activiti:string>0activiti:string>
          activiti:field>
        activiti:executionListener>
      
      
    
    id="_27" name="通过" sourceRef="auditMaterial" targetRef="updateListPurchase2Distribution">
      xsi:type="tFormalExpression">
    
    id="_28" name="驳回" sourceRef="auditMaterial1" targetRef="updateListPurchase2Distribution">
      xsi:type="tFormalExpression">
    
    id="_29" name="驳回" sourceRef="auditMaterialManager" targetRef="updateListPurchase2Distribution">
      xsi:type="tFormalExpression">
    
    id="_30" name="驳回" sourceRef="auditMaterialMajor" targetRef="updateListPurchase2Distribution">
      xsi:type="tFormalExpression">
    
    id="_31" sourceRef="updateListPurchase2Distribution" targetRef="distributionPricing"/>
    activiti:exclusive="true" id="updateListPurchase2Done" name="更新状态为确认" scriptFormat="groovy">
      
        <activiti:executionListener class="com.sjgtw.business.service.workflow.PriceExecutionListener" event="start">
          <activiti:field name="orderFlag">
            <activiti:string>1activiti:string>
          activiti:field>
        activiti:executionListener>
      
      
    
    id="_33" name="通过" sourceRef="auditMaterialMajor" targetRef="updateListPurchase2Done">
      xsi:type="tFormalExpression">
    
    id="_34" sourceRef="updateListPurchase2Done" targetRef="auditListPurchaseProcessEndEvent"/>
  
  <bpmndi:BPMNDiagram documentation="background=#3C3F41;count=1;horizontalcount=1;orientation=0;width=842.4;height=1195.2;imageableWidth=832.4;imageableHeight=1185.2;imageableX=5.0;imageableY=5.0" id="Diagram-_1" name="New Diagram">
    <bpmndi:BPMNPlane bpmnElement="auditListPurchase">
      <bpmndi:BPMNShape bpmnElement="auditListPurchaseStartEvent" id="Shape-auditListPurchaseStartEvent">
        <omgdc:Bounds height="32.0" width="32.0" x="205.0" y="175.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="32.0" width="32.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="auditListPurchaseProcessEndEvent" id="Shape-auditListPurchaseProcessEndEvent">
        <omgdc:Bounds height="32.0" width="32.0" x="970.0" y="680.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="32.0" width="32.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="startUser" id="Shape-startUser">
        <omgdc:Bounds height="55.0" width="85.0" x="350.0" y="165.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="auditPM" id="Shape-auditPM">
        <omgdc:Bounds height="55.0" width="85.0" x="525.0" y="165.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="auditMaterial" id="Shape-auditMaterial">
        <omgdc:Bounds height="55.0" width="85.0" x="700.0" y="170.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="distributionPricing" id="Shape-distributionPricing">
        <omgdc:Bounds height="55.0" width="85.0" x="1075.0" y="355.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="auditMaterial1" id="Shape-auditMaterial1">
        <omgdc:Bounds height="55.0" width="85.0" x="700.0" y="360.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="auditMaterialManager" id="Shape-auditMaterialManager">
        <omgdc:Bounds height="55.0" width="85.0" x="705.0" y="455.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="auditMaterialMajor" id="Shape-auditMaterialMajor">
        <omgdc:Bounds height="55.0" width="85.0" x="705.0" y="560.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="updateListPurchase2Edit" id="Shape-updateListPurchase2Edit">
        <omgdc:Bounds height="55.0" width="85.0" x="530.0" y="20.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="updateListPurchase2Distribution" id="Shape-updateListPurchase2Distribution">
        <omgdc:Bounds height="55.0" width="85.0" x="890.0" y="245.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="updateListPurchase2Done" id="Shape-updateListPurchase2Done">
        <omgdc:Bounds height="55.0" width="85.0" x="940.0" y="560.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="55.0" width="85.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="_13" id="BPMNEdge__13" sourceElement="auditListPurchaseStartEvent" targetElement="startUser">
        <omgdi:waypoint x="237.0" y="191.0"/>
        <omgdi:waypoint x="350.0" y="192.5"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_34" id="BPMNEdge__34" sourceElement="updateListPurchase2Done" targetElement="auditListPurchaseProcessEndEvent">
        <omgdi:waypoint x="986.0" y="615.0"/>
        <omgdi:waypoint x="986.0" y="680.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_17" id="BPMNEdge__17" sourceElement="auditMaterial" targetElement="updateListPurchase2Edit">
        <omgdi:waypoint x="740.0" y="155.0"/>
        <omgdi:waypoint x="740.0" y="50.0"/>
        <omgdi:waypoint x="615.0" y="50.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_19" id="BPMNEdge__19" sourceElement="auditPM" targetElement="auditMaterial">
        <omgdi:waypoint x="625.0" y="195.0"/>
        <omgdi:waypoint x="660.0" y="195.0"/>
        <omgdi:waypoint x="700.0" y="195.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_18" id="BPMNEdge__18" sourceElement="startUser" targetElement="auditPM">
        <omgdi:waypoint x="450.0" y="192.5"/>
        <omgdi:waypoint x="525.0" y="192.5"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_20" id="BPMNEdge__20" sourceElement="distributionPricing" targetElement="auditMaterial1">
        <omgdi:waypoint x="1075.0" y="390.0"/>
        <omgdi:waypoint x="935.0" y="390.0"/>
        <omgdi:waypoint x="785.0" y="390.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_22" id="BPMNEdge__22" sourceElement="auditMaterialManager" targetElement="auditMaterialMajor">
        <omgdi:waypoint x="747.5" y="525.0"/>
        <omgdi:waypoint x="747.5" y="560.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_21" id="BPMNEdge__21" sourceElement="auditMaterial1" targetElement="auditMaterialManager">
        <omgdi:waypoint x="745.0" y="430.0"/>
        <omgdi:waypoint x="745.0" y="455.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_24" id="BPMNEdge__24" sourceElement="updateListPurchase2Edit" targetElement="startUser">
        <omgdi:waypoint x="530.0" y="45.0"/>
        <omgdi:waypoint x="390.0" y="45.0"/>
        <omgdi:waypoint x="390.0" y="165.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_23" id="BPMNEdge__23" sourceElement="auditPM" targetElement="updateListPurchase2Edit">
        <omgdi:waypoint x="570.0" y="150.0"/>
        <omgdi:waypoint x="570.0" y="75.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_28" id="BPMNEdge__28" sourceElement="auditMaterial1" targetElement="updateListPurchase2Distribution">
        <omgdi:waypoint x="685.0" y="387.5"/>
        <omgdi:waypoint x="640.0" y="320.0"/>
        <omgdi:waypoint x="890.0" y="272.5"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_27" id="BPMNEdge__27" sourceElement="auditMaterial" targetElement="updateListPurchase2Distribution">
        <omgdi:waypoint x="800.0" y="195.0"/>
        <omgdi:waypoint x="925.0" y="195.0"/>
        <omgdi:waypoint x="925.0" y="245.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_29" id="BPMNEdge__29" sourceElement="auditMaterialManager" targetElement="updateListPurchase2Distribution">
        <omgdi:waypoint x="690.0" y="482.5"/>
        <omgdi:waypoint x="640.0" y="340.0"/>
        <omgdi:waypoint x="890.0" y="272.5"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_31" id="BPMNEdge__31" sourceElement="updateListPurchase2Distribution" targetElement="distributionPricing">
        <omgdi:waypoint x="975.0" y="270.0"/>
        <omgdi:waypoint x="1115.0" y="270.0"/>
        <omgdi:waypoint x="1115.0" y="355.0"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_30" id="BPMNEdge__30" sourceElement="auditMaterialMajor" targetElement="updateListPurchase2Distribution">
        <omgdi:waypoint x="690.0" y="587.5"/>
        <omgdi:waypoint x="640.0" y="420.0"/>
        <omgdi:waypoint x="890.0" y="272.5"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="_33" id="BPMNEdge__33" sourceElement="auditMaterialMajor" targetElement="updateListPurchase2Done">
        <omgdi:waypoint x="805.0" y="587.5"/>
        <omgdi:waypoint x="940.0" y="587.5"/>
        <bpmndi:BPMNLabel>
          <omgdc:Bounds height="0.0" width="0.0" x="0.0" y="0.0"/>
        bpmndi:BPMNLabel>
      bpmndi:BPMNEdge>
    bpmndi:BPMNPlane>
  bpmndi:BPMNDiagram>
java代码实现:

package com.sjgtw.business.service.workflow;

import com.gt.util.common.DateUtils;
import com.gt.util.page.Pager;
import com.gt.util.page.PagerResult;
import com.sjgtw.entity.user.UserVO;
import com.sjgtw.entity.workflow.*;
import com.sjgtw.service.user.UserService;
import com.sjgtw.service.workflow.WorkflowService;
import org.activiti.engine.*;
import org.activiti.engine.history.*;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 类名:
 * 创建人: wdd
 * 创建时间: 2018/1/18
 */
@Service
public class WorkflowServiceImpl implements WorkflowService, InitializingBean {


    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private UserService userService;


    /**
     * 初始化类时创建工作流(如果未创建的话)
     * 创建人:zph
     * 创建时间:2018年1月18日16:16:24
     */
    @Override
    public void afterPropertiesSet() throws Exception {
//        查询SayHelloToLeave工作流是否已经创建
        ProcessDefinition processDefinition = repositoryService
                .createProcessDefinitionQuery().processDefinitionKey("auditListPurchase").singleResult();
        if (processDefinition == null) { //auditListPurchase流程不存在则在库中创建该流程所对应的流程数据结构
            String bpmnFileName = "auditListPurchase.bpmn20.xml";
            repositoryService
                    .createDeployment()
                    .addInputStream(
                            "auditListPurchase.bpmn",
                            this.getClass().getClassLoader()
                                    .getResourceAsStream(bpmnFileName)).deploy();
            //将此流程单独创建一个用户分组(也可以是一组)
            Group group = identityService.newGroup("deptLeader");
            group.setName("部门领导");
            group.setType("assignment");
            identityService.saveGroup(group);

            Group group1 = identityService.newGroup("sjgtwDept");
            group1.setName("世界高铁网");
            group1.setType("assignment");
            identityService.saveGroup(group1);
            User user = identityService.newUser("sjgtw");
            user.setFirstName("black");
            user.setLastName("zhang");
            user.setEmail("[email protected]");
            identityService.saveUser(user);
            identityService.createMembership("sjgtw", "sjgtwDept");


        }
    }

    /**
     * 同步人员信息
     * 创建人:zph
     * 创建时间:2018年1月18日16:16:24
     */
    public Boolean syncUserInfo(List list) {
        for (int i = 0; i < list.size(); i++) {
            // 创建并保存用户对象
            User user = identityService.newUser("henryyan");
            user.setFirstName("Henry");
            user.setLastName("Yan");
            user.setEmail("[email protected]");
            identityService.saveUser(user);

            // 把用户henryyan加入到组deptLeader中
            identityService.createMembership("henryyan", "deptLeader");
        }
        return true;
    }

    /**
     * 待办事项
     *
     * @param pager  分页对象
     * @param taskQO
     * @return
     */
    @Override
    public PagerResult toDoList(Pager pager, TaskQO taskQO, TaskStateEnum taskStateEnum) {

        List businessVOList = new ArrayList<>();
        Long total = 0L;
        switch (taskStateEnum) {
            case DOING_APPROVE: {
                HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery();
                historicProcessInstanceQuery.involvedUser(taskQO.getTaskUserId()).unfinished();
                total = historicProcessInstanceQuery.count();
                List list = historicProcessInstanceQuery.listPage(pager.getOffset(), pager.getOffset() + pager.getLimit());
                if (list != null) {
                    for (HistoricProcessInstance historicProcessInstance : list) {
                        BusinessVO businessVO = new BusinessVO();
                        businessVO.setBusinessId(historicProcessInstance.getBusinessKey());
                        businessVO.setTaskStateEnum(TaskStateEnum.DOING_APPROVE);
                        businessVOList.add(businessVO);
                    }
                }

                break;
            }
            case WAIT_APPROVE: {
                TaskQuery taskQuery = taskService.createTaskQuery();
                taskQuery.taskAssignee(taskQO.getTaskUserId());
                total = taskQuery.count();
                List taskList = taskQuery.orderByTaskCreateTime().desc().listPage(pager.getOffset(), pager.getOffset() + pager.getLimit());
                if (taskList != null) {
                    for (Task task : taskList) {
                        HistoricProcessInstance historicProcessInstance = (HistoricProcessInstance) historyService
                                .createHistoricProcessInstanceQuery().processInstanceId(
                                        task.getProcessInstanceId()).singleResult();
                        BusinessVO businessVO = new BusinessVO();
                        businessVO.setBusinessId(historicProcessInstance.getBusinessKey());
                        businessVO.setTaskStateEnum(TaskStateEnum.WAIT_APPROVE);
                        businessVOList.add(businessVO);
                    }
                }
                break;
            }
            case PASS: {
                HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery();
                historicProcessInstanceQuery.involvedUser(taskQO.getTaskUserId()).finished();
                total = historicProcessInstanceQuery.count();
                List list = historicProcessInstanceQuery.listPage(pager.getOffset(), pager.getOffset() + pager.getLimit());
                if (list != null) {
                    for (HistoricProcessInstance historicProcessInstance : list) {
                        BusinessVO businessVO = new BusinessVO();
                        businessVO.setBusinessId(historicProcessInstance.getBusinessKey());
                        businessVO.setTaskStateEnum(TaskStateEnum.PASS);
                        businessVOList.add(businessVO);
                    }
                }

                break;
            }
            default: {
                return new PagerResult();
            }
        }


        PagerResult pagerResult = new PagerResult();
        pagerResult.setTotal(total.intValue());
        pagerResult.setRows(businessVOList);

        return pagerResult;
    }


    /**
     * 根据businessKey 获取processInstanceId
     *
     * @param businessId
     * @return
     */
    private String getProcessInstanceId(String businessId) {

        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceBusinessKey(businessId).singleResult();

        String processInstanceId;
        if (processInstance != null) {
            processInstanceId = processInstance.getProcessInstanceId();
        } else {
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessId).singleResult();
            processInstanceId = historicProcessInstance.getSuperProcessInstanceId();
        }

        return processInstanceId;
    }

    /**
     * 查询当前进程批注
     *
     * @param taskQO
     * @return
     */
    @Override
    public PagerResult getHistoryComment(TaskQO taskQO) {

        String processInstanceId = getProcessInstanceId(taskQO.getBusinessId());

        List list = historyService
                .createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricTaskInstanceEndTime().desc()
                .list();
        List commentList = new ArrayList();
        if (list != null && list.size() > 0) {
            for (HistoricTaskInstance history : list) {
                TaskHistoryVO taskHistoryVO = new TaskHistoryVO();

                List commentList1 = taskService.getTaskComments(history.getId(), "comment");
                if (commentList1 != null && commentList1.size() > 0) {
                    Comment comment = commentList1.get(0);
                    String[] tmpStr = comment.getFullMessage().split(WorkflowConstants.SEPARATOR_COMMENT);
                    if (tmpStr != null && tmpStr.length > 1) {
                        taskHistoryVO.setState(tmpStr[0]);
                        taskHistoryVO.setComment(tmpStr[1]);
                    }
                }
                if (history.getEndTime() != null) {
                    taskHistoryVO.setDueTime(DateUtils.getDateStr(history.getEndTime()));
                }
                taskHistoryVO.setDueName(history.getName());
                if (history.getAssignee() != null) {
                    UserVO userVO = userService.getUserById(Long.parseLong(history.getAssignee()));
                    taskHistoryVO.setDuePerson(userVO.getUserName());
                }
                commentList.add(taskHistoryVO);
            }
        }
//        Collections.reverse(commentList);
        PagerResult pagerResult = new PagerResult();
        pagerResult.setLimit(100);
        pagerResult.setRows(commentList);
        return pagerResult;

    }

    /**
     * 启动任务
     *
     * @param processInstanceKey
     * @param taskQO
     */
    @Override
    public void start(String processInstanceKey, TaskQO taskQO) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceBusinessKey(taskQO.getBusinessId()).singleResult();
        Map, Object> variables = getVariables(taskQO);
        variables.put("vote", ApprovingResultEnum.PASSED.getCode());
        variables.put("userId", taskQO.getUserId());
        if (processInstance == null) {
            processInstance = runtimeService.startProcessInstanceByKey(processInstanceKey, taskQO.getBusinessId(), variables);
        }
        // 根据流程实例Id查询任务
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();

//        taskService.complete(task.getId(), variables,true);
        taskService.complete(task.getId(), variables);
    }


    private Map, Object> getVariables(TaskQO taskQO) {
        Map, Object> variables = new HashMap, Object>();
        String[] user = taskQO.getAudits().split(",");
        variables.put("businessId", taskQO.getBusinessId());
        variables.put("businessVO", taskQO.getBusinessId());
        variables.put("startUser", taskQO.getTaskUserId());
        variables.put("auditPM", user[0]);
        variables.put("auditMaterial", user[1]);
        variables.put("auditMaterial1", user[2]);
        variables.put("auditMaterialManager", user[3]);
        variables.put("auditMaterialMajor", user[4]);
        return variables;
    }

    /**
     * 签收任务
     *
     * @param taskQO
     */
    @Override
    public void claim(TaskQO taskQO) {
        Task task = getActiveTaskByBusinessId(taskQO.getBusinessId());
        taskService.claim(task.getId(), taskQO.getTaskUserId());
    }


    /**
     * 驳回任务
     *
     * @param taskQO
     */
    @Override
    public void reject(TaskQO taskQO) {
        complete(taskQO, ApprovingResultEnum.TURN_DOWN);
    }

    /**
     * 通过任务
     *
     * @param taskQO
     */
    @Override
    public void pass(TaskQO taskQO) {
        complete(taskQO, ApprovingResultEnum.PASSED);
    }


    @Override
    public void signal(TaskQO taskQO) {

        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceBusinessKey(taskQO.getBusinessId()).singleResult();
        String processInstanceId = processInstance.getId();
        Execution execution = runtimeService.createExecutionQuery()
                .processInstanceId(processInstanceId)
                .activityId("distributionPricing")
                .singleResult();
        runtimeService.signal(execution.getId());
    }

    /**
     * 根据businessId 获得processDefinitionId
     * @param businessId
     * @return
     */
    private String getProcessDefinitionId(String businessId){

        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceBusinessKey(businessId).singleResult();
        String ProcessDefinitionId;
        if (processInstance != null) {
            ProcessDefinitionId = processInstance.getProcessDefinitionId();
        } else {
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessId).singleResult();
            ProcessDefinitionId = historicProcessInstance.getProcessDefinitionId();
        }
        return  ProcessDefinitionId;
    }


    /**
     * 业务id获取工作流状态,返回包含displayName和active的map
     *
     * @param taskQO
     * @return
     */
    @Override
    public List, Object>> getProcessStateMap(TaskQO taskQO) {


        String ProcessDefinitionId =getProcessDefinitionId(taskQO.getBusinessId());
        String processInstanceId =getProcessInstanceId(taskQO.getBusinessId());


        //根据processInstance获得流程定义
        ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(ProcessDefinitionId);
        //获得所有流程节点
        List activitiList = def.getActivities();
        //获得所有历史流程节点
        List historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
        // 根据流程实例Id查询任务
        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();

        // 查询当前活动节点
        String excId = task.getExecutionId();
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createExecutionQuery().executionId(excId).singleResult();

        String activitiId = execution.getActivityId();

        List highLightedActivitis = new ArrayList();
        boolean flag = true;
        Map variablesMap = taskService.getVariables(task.getId());
        for (ActivityImpl activityImpl : activitiList) {
            if ("userTask".equals(activityImpl.getProperty("type"))) {
                String id = activityImpl.getId();
                Map, Object> map = new HashMap<>();
                map.put("displayName", activityImpl.getProperty("name"));
                String userid = variablesMap.get(activityImpl.getId()).toString();
                UserVO userVO = userService.getUserById(Long.parseLong(userid));
                map.put("actors", userVO.getUserName());
                if (activitiId.equals(id)) {
                    flag = false;
                }
                map.put("active", flag);
                highLightedActivitis.add(map);
            }
        }
        return highLightedActivitis;
    }


    /**
     * 通过businessId 获取当前示例
     *
     * @param businessId
     * @return
     */
    private ProcessInstance getProcessInstanceByBusinessId(String businessId) {
        return runtimeService.createProcessInstanceQuery()
                .processInstanceBusinessKey(businessId).singleResult();
    }

    private Task getActiveTaskByBusinessId(String businessId) {
        ProcessInstance processInstance = getProcessInstanceByBusinessId(businessId);
        return taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
    }

    /**
     * 完成任务
     *
     * @param taskQO
     * @param approvingResultEnum
     */

    public void complete(TaskQO taskQO, ApprovingResultEnum approvingResultEnum) {
        // 根据流程实例Id查询任务
        Task task = getActiveTaskByBusinessId(taskQO.getBusinessId());
        Map, Object> variables = new HashMap<>();
        Map, Object> initVariables = taskService.getVariables(task.getId());
        variables.put("userId", taskQO.getUserId());
        variables.putAll(initVariables);
        variables.put("vote", approvingResultEnum.getCode());
        // 设置审批人id
        Authentication.setAuthenticatedUserId(taskQO.getTaskUserId());

        String comment = (approvingResultEnum.getCode() == 1 ? "通过" : "驳回") + WorkflowConstants.SEPARATOR_COMMENT + taskQO.getComment();

        variables.put("comment", taskQO.getComment());
        //设置审批意见
        taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);
        //完成审批
//        taskService.complete(task.getId(), variables,true);
        taskService.complete(task.getId(), variables);

    }

    private TaskVO getTask(String taskId) {
        HistoricTaskInstance historicTaskInstance = (HistoricTaskInstance) historyService
                .createHistoricTaskInstanceQuery().taskId(taskId)
                .singleResult();
        return setTaskVO(historicTaskInstance);

    }

    private TaskVO setTaskVO(HistoricTaskInstance task) {
        TaskVO taskVO = new TaskVO();
        taskVO.setTaskId(task.getId());
        taskVO.setTaskName(task.getName());
        taskVO.setApproveUserName(task.getAssignee() != null ? task.getAssignee() : "");
        taskVO.setCreateTime(task.getStartTime() != null ? DateUtils.getDateStr(task.getStartTime()) : "");
        taskVO.setEndTime(task.getEndTime() != null ? DateUtils.getDateStr(task.getEndTime()) : "");
        taskVO.setDueTime(task.getDueDate() != null ? DateUtils.getDateStr(task.getDueDate()) : "");

        ProcessDefinition processDefinition = (ProcessDefinition) repositoryService
                .createProcessDefinitionQuery().processDefinitionId(
                        task.getProcessDefinitionId()).singleResult();
        taskVO.setBusinessName(processDefinition.getName());
        taskVO.setWorkflowName(processDefinition.getKey());
        taskVO.setStatus(processDefinition.isSuspended() ? "已挂起" : "正常");
        taskVO.setVersion(String.valueOf(processDefinition.getVersion()));
        HistoricProcessInstance historicProcessInstance = (HistoricProcessInstance) historyService
                .createHistoricProcessInstanceQuery().processInstanceId(
                        task.getProcessInstanceId()).singleResult();

        //得到业务id即eventid
        taskVO.setBusinessEventId(historicProcessInstance.getBusinessKey());
        //发起人姓名
        if (historicProcessInstance.getStartUserId() != null) {
            taskVO.setStartUserName(historicProcessInstance
                    .getStartUserId().toString());
        } else {
            taskVO.setStartUserName("");
        }
        return taskVO;
    }


}

你可能感兴趣的:(activiti使用实践案例)