// 查询当前用户已完成的任务列表
List<HistoricTaskInstance> completedTasks = historyService.createHistoricTaskInstanceQuery()
.taskAssignee(sysUser.getUserName())
//.taskCandidateUser(sysUser.getUserName())
.finished()
.orderByTaskCreateTime()
.desc()
.listPage((int)((page.getCurrent() - 1) * page.getSize()), (int)page.getSize());
// 处理已完成任务列表,创建 ActTaskDTO 对象列表
List<ActTaskDTO> completedTasksDTOs = new ArrayList<>();
for (HistoricTaskInstance his : completedTasks) {
HistoricProcessInstance hpi = processEngine.getHistoryService()// 与历史数据(历史表)相关的Service
.createHistoricProcessInstanceQuery()// 创建历史流程实例查询
.processInstanceId(his.getProcessInstanceId())// 使用流程实例ID查询
.orderByProcessInstanceStartTime().asc().singleResult();
ActTaskDTO taskDTO = new ActTaskDTO(hpi);
completedTasksDTOs.add(taskDTO);
}
// 设置总记录数和返回 ActTaskDTO 列表
pageOut.setTotal(completedTasksDTOs.size());
pageOut.setRecords(completedTasksDTOs);
return pageOut;
}
@Override
public Page<ActTaskDTO> selectInvoledTasks(Page page) {
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
Page<ActTaskDTO> pageOut = new Page<ActTaskDTO>();
List<HistoricProcessInstance> historicProcessInstances = historyService.createHistoricProcessInstanceQuery()
.involvedUser(sysUser.getUserName())
.orderByProcessInstanceStartTime()
.desc()
.listPage((int)((page.getCurrent() - 1) * page.getSize()), (int)page.getSize());
// 处理已完成任务列表,创建 ActTaskDTO 对象列表
List<ActTaskDTO> completedTasksDTOs = new ArrayList<>();
for (HistoricProcessInstance his : historicProcessInstances) {
ActTaskDTO taskDTO = new ActTaskDTO(his);
completedTasksDTOs.add(taskDTO);
}
// 设置总记录数和返回 ActTaskDTO 列表
pageOut.setTotal(completedTasksDTOs.size());
pageOut.setRecords(completedTasksDTOs);
return pageOut;
}
@Override
public Page<ActTaskDTO> selectInitiatorTasks(Page page) {
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
Page<ActTaskDTO> pageOut = new Page<ActTaskDTO>();
List<HistoricProcessInstance> historicProcessInstances = historyService.createHistoricProcessInstanceQuery()
.startedBy(sysUser.getUserName())
.orderByProcessInstanceStartTime()
.desc()
.listPage((int)((page.getCurrent() - 1) * page.getSize()), (int)page.getSize());
// 处理已完成任务列表,创建 ActTaskDTO 对象列表
List<ActTaskDTO> completedTasksDTOs = new ArrayList<>();
for (HistoricProcessInstance his : historicProcessInstances) {
ActTaskDTO taskDTO = new ActTaskDTO(his);
completedTasksDTOs.add(taskDTO);
}
// 设置总记录数和返回 ActTaskDTO 列表
pageOut.setTotal(completedTasksDTOs.size());
pageOut.setRecords(completedTasksDTOs);
return pageOut;
}
@Override
public Page<ActTaskDTO> selectAllTasks(Page page) {
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
Page<ActTaskDTO> pageOut = new Page<ActTaskDTO>();
List<HistoricProcessInstance> historicProcessInstances = historyService.createHistoricProcessInstanceQuery()
.orderByProcessInstanceStartTime()
.desc()
.listPage((int)((page.getCurrent() - 1) * page.getSize()), (int)page.getSize());
// 处理已完成任务列表,创建 ActTaskDTO 对象列表
List<ActTaskDTO> completedTasksDTOs = new ArrayList<>();
for (HistoricProcessInstance his : historicProcessInstances) {
ActTaskDTO taskDTO = new ActTaskDTO(his);
completedTasksDTOs.add(taskDTO);
}
// 设置总记录数和返回 ActTaskDTO 列表
pageOut.setTotal(completedTasksDTOs.size());
pageOut.setRecords(completedTasksDTOs);
return pageOut;
}
@Override
public List<String> formDataShow(String taskID) {
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
Task task = taskRuntime.task(taskID);
UserTask userTask = (UserTask) repositoryService.getBpmnModel(task.getProcessDefinitionId())
.getFlowElement(task.getFormKey());
if (userTask == null) {
return null;
}
List<FormProperty> formProperties = userTask.getFormProperties();
List<String> collect = formProperties.stream().map(fp -> fp.getId()).collect(Collectors.toList());
return collect;
}
@Override
@Transactional
public void Taskhandle (String taskID,TaskHandleDTO taskHandleDTO) throws Exception{
SpActLogDTO logdto = new SpActLogDTO();
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
Task task = taskRuntime.task(taskID);
String processInstanceId = task.getProcessInstanceId();
UserTask userTask = (UserTask) repositoryService.getBpmnModel(task.getProcessDefinitionId())
.getFlowElement(task.getFormKey());
if (userTask == null) {
throw new ServiceException("该业务已处理,请刷新页面重试");
}
//记录日志
logdto.setYwid(taskHandleDTO.getYwid());
logdto.setPid(task.getProcessInstanceId());
logdto.setOpinion(taskHandleDTO.getOpinion());
logdto.setCzry(sysUser.getNickName());
if("2".equals(taskHandleDTO.getFlag())){//审核驳回
//审核驳回,请校验参数,审核驳回必须得有驳回节点和审核人信息
if(StringUtils.isBlank(taskHandleDTO.getBackAssignee())){
throw new ServiceException("驳回节点审核人不能为空");
}
if(StringUtils.isBlank(taskHandleDTO.getRunNodeId())){
throw new ServiceException("驳回节点不能为空");
}
boolean f = runNodes(task,taskHandleDTO.getRunNodeId());
if(!f){
throw new ServiceException("操作异常,请刷新页面重试");
}
org.activiti.engine.task.Task nextTask = taskService.createTaskQuery()
.processInstanceId(task.getProcessInstanceId()) // 根据流程实例ID过滤
.singleResult();
// 获取当前任务的候选人
handleCandidateUser(nextTask);
taskService.addCandidateUser(nextTask.getId(),taskHandleDTO.getBackAssignee());
//记录日志
logdto.setSpStatus("2");
logdto.setNextNode(taskHandleDTO.getRunNodeId());
logdto.setNextAssignee(taskHandleDTO.getNextAssignee());
String describe = "驳回了任务,驳回到节点["+taskHandleDTO.getRunNodeName()+"],指定下一审批人:"+taskHandleDTO.getAssigneeName();
logdto.setYwms(describe);
}else if("3".equals(taskHandleDTO.getFlag()) || "99".equals(taskHandleDTO.getFlag())){//代表直接退回修改,日志表重新建立一个,即为退办
// 完成当前节点任务
//taskService.complete(task.getId());
// 结束流程
//String processInstanceId = taskService.createTaskQuery().taskId(task.getId()).singleResult().getProcessInstanceId();
runtimeService.deleteProcessInstance(processInstanceId, sysUser.getNickName()+"选择退办结束流程");
//记录日志
logdto.setSpStatus(taskHandleDTO.getFlag());
String describe = "退办了任务";
logdto.setYwms(describe);
//更新中间表状态
SpScActDTO ssadto = new SpScActDTO();
ssadto.setPid(processInstanceId);
List<SpScActDTO> ssaList = spScActService.listByEntity(ssadto);
if(CollectionUtils.isNotEmpty(ssaList)){
SpScActDTO ssa = ssaList.get(0);
if("3".equals(taskHandleDTO.getFlag())){
ssa.setSpResultStatus("2");
}else{
ssa.setSpResultStatus("99");
}
spScActService.updateEntityById(ssa);
}
String sp_result_status = null;
if("3".equals(taskHandleDTO.getFlag())){
sp_result_status = "2";
}else{
sp_result_status = "3";
}
//根据业务类型和ywid更新业务状态为 审批退办
R<Boolean> rsc = remoteScService.changeSpywStatus(taskHandleDTO.getType(),taskHandleDTO.getYwid(),sp_result_status, taskHandleDTO.getOpinion(),SecurityConstants.INNER);
if(rsc.getCode()!= Constants.SUCCESS){
throw new ServiceException(rsc.getMsg());
}
}else{//一般下一节点是多个userTask
// 声明任务
if (StringUtils.isEmpty(task.getAssignee())) {
taskService.claim(task.getId(), sysUser.getUserName());
}
HashMap<String, Object> variables = new HashMap<String, Object>();
//设定网关审核通过的路线表达式为 {userTask.getFormKey()==1},固定设置,表单字段我们不设置
variables.put(userTask.getFormKey(),taskHandleDTO.getFlag());
taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID)
.withVariables(variables)
.build());
//寻找下一任务task
org.activiti.engine.task.Task nextTask = taskService.createTaskQuery()
.processInstanceId(task.getProcessInstanceId()) // 根据流程实例ID过滤
.singleResult();
if(nextTask==null){//结束节点,记录业务
//记录日志
logdto.setSpStatus("1");
String describe = "审批通过";
logdto.setYwms(describe);
//更新中间表状态
SpScActDTO ssadto = new SpScActDTO();
ssadto.setPid(processInstanceId);
List<SpScActDTO> ssaList = spScActService.listByEntity(ssadto);
if(CollectionUtils.isNotEmpty(ssaList)){
SpScActDTO ssa = ssaList.get(0);
ssa.setSpResultStatus("1");
spScActService.updateEntityById(ssa);
}
//根据业务类型和ywid更新业务状态为 审批通过
R<Boolean> rsc = remoteScService.changeSpywStatus(taskHandleDTO.getType(),taskHandleDTO.getYwid(),"1","审核通过", SecurityConstants.INNER);
if(rsc.getCode()!= Constants.SUCCESS){
throw new ServiceException(rsc.getMsg());
}
}else{
String formKey = task.getFormKey();
if(formKey.contains("comm_")){//沟通节点
List<SpActLog> logs = spActLogService.findbyYwidAndPId(taskHandleDTO.getYwid(), task.getProcessInstanceId());
if(CollectionUtils.isNotEmpty(logs)){
SpActLog log = logs.get(0);
// 获取当前任务的候选人
handleCandidateUser(nextTask);
com.ruoyi.activiti.domain.SysUser user = sysUserService.getById(log.getCreateBy());
taskService.addCandidateUser(nextTask.getId(),user.getUserName());
}
//记录日志
logdto.setSpStatus("5");
String describe = "沟通结束,给出意见为"+taskHandleDTO.getOpinion();
logdto.setYwms(describe);
}else{
if(StringUtils.isBlank(taskHandleDTO.getNextAssignee())){
throw new ServiceException("下一节点审核人不能为空");
}
if(StringUtils.isBlank(taskHandleDTO.getNodeId())){
throw new ServiceException("下一审核节点不能为空");
}
// 获取当前任务的候选人
List<IdentityLink> candidateUsers = taskService.getIdentityLinksForTask(nextTask.getId());
for (IdentityLink identityLink : candidateUsers) {
if (identityLink.getType().equals(IdentityLinkType.CANDIDATE)) {
String userId = identityLink.getUserId();
if (userId != null) {
//删除原有的
taskService.deleteCandidateUser(nextTask.getId(), identityLink.getUserId());
}
}
}
//指定页面指定的候选人
taskService.addCandidateUser(nextTask.getId(),taskHandleDTO.getNextAssignee());
//记录日志
logdto.setSpStatus("4");
logdto.setNextNode(taskHandleDTO.getNodeId());
logdto.setNextAssignee(taskHandleDTO.getNextAssignee());
String describe = "审批通过,并指定下一审核节点为:"+taskHandleDTO.getNodeName()+",下一节点审批人为:"+taskHandleDTO.getAssigneeName();
logdto.setYwms(describe);
}
}
}
spActLogService.saveEntity(logdto);
}
private void handleCandidateUser(org.activiti.engine.task.Task nextTask) {
List<IdentityLink> candidateUsers = taskService.getIdentityLinksForTask(nextTask.getId());
for (IdentityLink identityLink : candidateUsers) {
if (identityLink.getType().equals(IdentityLinkType.CANDIDATE)) {
String userId = identityLink.getUserId();
if (userId != null) {
//删除原有的
taskService.deleteCandidateUser(nextTask.getId(), identityLink.getUserId());
}
}
}
}
@Transactional
@Override
public void stopAct(String ywid,String processInstanceId) throws Exception{
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
SpActLogDTO logdto = new SpActLogDTO();
logdto.setYwid(ywid);
logdto.setPid(processInstanceId);
logdto.setOpinion("管理员关闭了流程实例");
logdto.setCzry(sysUser.getNickName());
runtimeService.deleteProcessInstance(processInstanceId, sysUser.getNickName()+"选择退办结束流程");
//记录日志
logdto.setSpStatus("3");
String describe = "退办了任务";
logdto.setYwms(describe);
//更新中间表状态
SpScActDTO ssadto = new SpScActDTO();
ssadto.setPid(processInstanceId);
List<SpScActDTO> ssaList = spScActService.listByEntity(ssadto);
String type =null;
if(CollectionUtils.isNotEmpty(ssaList)){
SpScActDTO ssa = ssaList.get(0);
ssa.setSpResultStatus("2");
spScActService.updateEntityById(ssa);
type = ssa.getActType();
String sp_result_status = "2";
//根据业务类型和ywid更新业务状态为 审批退办
R<Boolean> rsc = remoteScService.changeSpywStatus(type, ywid, sp_result_status, "管理员关闭了流程实例", SecurityConstants.INNER);
if (rsc.getCode() != Constants.SUCCESS) {
if ("操作异常,记录不存在".equals(rsc.getMsg()) || "操作异常,业务类型不存在".equals(rsc.getMsg())) {
} else {
throw new ServiceException(rsc.getMsg());
}
}
spActLogService.saveEntity(logdto);
}
}
/**
*
* @param task
* @param runNodeId 历史节点
* @return
*/
public boolean runNodes(Task task,String runNodeId) {
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
//获取当前节点
String currActivityId = task.getTaskDefinitionKey();
String processDefinitionId = task.getProcessDefinitionId();
BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
FlowNode currFlow = (FlowNode) bpmnModel.getMainProcess().getFlowElement(currActivityId);
if (null == currFlow) {
List<SubProcess> subProcessList = bpmnModel.getMainProcess().findFlowElementsOfType(SubProcess.class, true);
for (SubProcess subProcess : subProcessList) {
FlowElement flowElement = subProcess.getFlowElement(currActivityId);
if (flowElement != null) {
currFlow = (FlowNode) flowElement;
break;
}
}
}
//获取目标节点
FlowNode targetFlow = (FlowNode) bpmnModel.getFlowElement(runNodeId);
//如果不是同一个流程(子流程)不能驳回
if (!(currFlow.getParentContainer().equals(targetFlow.getParentContainer()))) {
throw new ServiceException("此处无法进行驳回操作");
}
//记录原活动方向
List<SequenceFlow> oriSequenceFlows = Lists.newArrayList();
oriSequenceFlows.addAll(currFlow.getOutgoingFlows());
//清理活动方向
currFlow.getOutgoingFlows().clear();
//建立新的方向
List<SequenceFlow> newSequenceFlows = Lists.newArrayList();
SequenceFlow newSequenceFlow = new SequenceFlow();
String uuid = UUID.randomUUID().toString().replace("-", "");
newSequenceFlow.setId(uuid);
newSequenceFlow.setSourceFlowElement(currFlow); //原节点
newSequenceFlow.setTargetFlowElement(targetFlow); //目标节点
newSequenceFlows.add(newSequenceFlow);
currFlow.setOutgoingFlows(newSequenceFlows);
//完成节点任务
taskService.complete(task.getId());
//恢复原方向
currFlow.setOutgoingFlows(oriSequenceFlows);
//删除新建立的连线
deleteNewSequenceFlow(bpmnModel,currFlow,uuid);
return true;
}
// 删除新建立的连线的方法
private void deleteNewSequenceFlow(BpmnModel bpmnModel, FlowNode sourceNode, String sequenceFlowId) {
List<Process> processes = bpmnModel.getProcesses();
for (Process process : processes) {
Collection<FlowElement> flowElements = process.getFlowElements();
for (FlowElement flowElement : flowElements) {
if (flowElement instanceof SequenceFlow) {
SequenceFlow sequenceFlow = (SequenceFlow) flowElement;
if (sequenceFlow.getId().equals(sequenceFlowId) && sequenceFlow.getSourceFlowElement().equals(sourceNode)) {
flowElements.remove(sequenceFlow);
return;
}
}
}
}
}
@Override
public int formDataSave(String taskID, List<ActWorkflowFormDataDTO> awfs) {
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
Task task = taskRuntime.task(taskID);
ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
Boolean hasVariables = false;//没有任何参数
HashMap<String, Object> variables = new HashMap<String, Object>();
//前端传来的字符串,拆分成每个控件
List<ActWorkflowFormData> acwfds = new ArrayList<>();
for (ActWorkflowFormDataDTO awf : awfs) {
ActWorkflowFormData actWorkflowFormData = new ActWorkflowFormData(processInstance.getBusinessKey(),awf, task);
acwfds.add(actWorkflowFormData);
//构建参数集合
if(!"f".equals(awf.getControlIsParam())) {
variables.put(awf.getControlId(), awf.getControlValue());
hasVariables = true;
}
}//for结束
if (task.getAssignee() == null) {
taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
}
if (hasVariables) {
//带参数完成任务
taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID)
.withVariables(variables)
.build());
} else {
taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID)
.build());
}
//写入数据库
return actWorkflowFormDataService.insertActWorkflowFormDatas(acwfds);
}
@Override
public List<UserDTO> getUserTaskAssignByFlowElemet(String taskId,String flowElemetId){
List<UserDTO> userList = new ArrayList<>();
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
DynamicFormConf dynamicFormConf = new DynamicFormConf();
Task task = taskRuntime.task(taskId);
//流程定义Id
String processDefId= task.getProcessDefinitionId();
//当前流程节点Id,在任务表里面对应TASK_DEF_KEY_字段,可以根据taskId获取该字段数据
BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefId);
Process process = bpmnModel.getProcesses().get(0);
//获取所有普通任务节点
List<UserTask> UserTaskList = process.findFlowElementsOfType(UserTask.class);
for(UserTask userTask:UserTaskList){
//获取当前任务节点Id
String id = userTask.getId();
if(id.equals(flowElemetId)){
List<String> candidateGroups = userTask.getCandidateGroups();
// List<String> users = userTask.getCandidateUsers();
for (String group:candidateGroups
) {
String[] parts = parseStringUtils.parseString(group);
if (parts != null && parts.length == 2) {
String departmentId = parts[0];
String post = parts[1];
if(StringUtils.isBlank(departmentId)){
departmentId = getActivitiDeptId(task.getProcessInstanceId());
}
userList.addAll(sysUserService.selectUserByPostCodeAndDeptId(post, Long.valueOf(departmentId)));
}
}
}
}
return userList;
}
private String getActivitiDeptId(String processInstanceId){
String deptId = null;
// 创建历史流程实例查询
HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery();
// 设置查询条件,根据流程实例 ID 查询
HistoricProcessInstance historicProcessInstance = historicProcessInstanceQuery.processInstanceId(processInstanceId).singleResult();
if (historicProcessInstance != null) {
// 获取流程的启动者(创建者)
String createdBy = historicProcessInstance.getStartUserId();
com.ruoyi.activiti.domain.SysUser user = sysUserService.selectUserByUserName(createdBy);
SysUser sysUser = new SysUser();
sysUser.setUserType(user.getUserType());
sysUser.setEnterpriseCode(user.getEnterpriseCode());
sysUser.setCertNumber(user.getCertNumber());
if("6".equals(user.getUserType()) || "7".equals(user.getUserType())||"8".equals(user.getUserType())){
//需要获取他的管辖部门
R<ExamineDeptDTO> rsc = remoteScResultService.queryExamineDept(sysUser);
if(rsc.getCode()!= Constants.SUCCESS){
throw new ServiceException(rsc.getMsg());
}
ExamineDeptDTO examineDeptDTO= rsc.getData();
deptId = examineDeptDTO.getDeptId();
}else{
deptId = user.getDeptId()+"";
}
}
return deptId;
}
/**
* 获取当前任务节点的下一个任务节点
*
* @param task 当前任务节点
* @return 下个任务节点
* @throws Exception
*/
public UserTask getNextUserFlowElement(Task task) {
ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
HistoryService historyService = processEngine.getHistoryService();
// 取得已提交的任务
HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery()
.taskId(task.getId()).singleResult();
// 获得流程定义
ProcessDefinition processDefinition = repositoryService.getProcessDefinition(historicTaskInstance.getProcessDefinitionId());
//获得当前流程的活动ID
ExecutionQuery executionQuery = runtimeService.createExecutionQuery();
Execution execution = executionQuery.executionId(historicTaskInstance.getExecutionId()).singleResult();
String activityId = execution.getActivityId();
UserTask userTask = null;
while (true) {
//根据活动节点获取当前的组件信息
FlowNode flowNode = getFlowNode(processDefinition.getId(), activityId);
//获取该节点之后的流向
List<SequenceFlow> sequenceFlowListOutGoing = flowNode.getOutgoingFlows();
// 获取的下个节点不一定是userTask的任务节点,所以要判断是否是任务节点
if (sequenceFlowListOutGoing.size() > 1) {
// 如果有1条以上的出线,表示有分支,需要判断分支的条件才能知道走哪个分支
// 遍历节点的出线得到下个activityId
activityId = getNextActivityId(execution.getId(),task.getProcessInstanceId(), sequenceFlowListOutGoing);
} else if (sequenceFlowListOutGoing.size() == 1) {
// 只有1条出线,直接取得下个节点
SequenceFlow sequenceFlow = sequenceFlowListOutGoing.get(0);
// 下个节点
FlowElement flowElement = sequenceFlow.getTargetFlowElement();
if (flowElement instanceof UserTask) {
// 下个节点为UserTask时
userTask = (UserTask) flowElement;
//System.out.println("下个任务为:" + userTask.getName());
return userTask;
} else if (flowElement instanceof ExclusiveGateway) {
// 下个节点为排它网关时
ExclusiveGateway exclusiveGateway = (ExclusiveGateway) flowElement;
List<SequenceFlow> outgoingFlows = exclusiveGateway.getOutgoingFlows();
// 遍历网关的出线得到下个activityId
activityId = getNextActivityId(execution.getId(), task.getProcessInstanceId(), outgoingFlows);
//找到出口的节点
flowNode = getFlowNode(processDefinition.getId(), activityId);
//找不到符合条件的节点,就返回null
if(flowNode==null) {
return null;
}
//如果出口处是结束节点,则返回空
if(flowNode instanceof EndEvent){
return null;
}
//如果出口处就是一个UserTask,就返回它
if (flowNode instanceof UserTask) {
userTask = (UserTask) flowNode;
return userTask;
}
}else{
return null;
}
} else {
// 没有出线,则表明是结束节点
return null;
}
}
}
/**
* 根据活动节点和流程定义ID获取该活动节点的组件信息
*/
public FlowNode getFlowNode(String processDefinitionId, String flowElementId) {
BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(flowElementId);
return flowNode;
}
/**
* 根据el表达式取得满足条件的下一个activityId
* @param executionId
* @param processInstanceId
* @param outgoingFlows
* @return
*/
public String getNextActivityId(String executionId,String processInstanceId,List<SequenceFlow> outgoingFlows) {
String activityId = null;
// 遍历出线
for (SequenceFlow outgoingFlow : outgoingFlows) {
// 取得线上的条件
String conditionExpression = outgoingFlow.getConditionExpression();
if(StringUtils.isBlank(conditionExpression)){
continue;
}
// 取得所有变量
Map<String, Object> variables = runtimeService.getVariables(executionId);
String variableName = "";
// 判断网关条件里是否包含变量名
for (String s : variables.keySet()) {
if (conditionExpression.contains(s)) {
// 找到网关条件里的变量名
variableName = s;
}
}
String conditionVal = getVariableValue(variableName, processInstanceId);
// 判断el表达式是否成立
if (isCondition(variableName, conditionExpression, conditionVal)) {
// 取得目标节点
FlowElement targetFlowElement = outgoingFlow.getTargetFlowElement();
activityId = targetFlowElement.getId();
continue;
}
}
return activityId;
}
/**
* 取得流程变量的值
*
* @param variableName 变量名
* @param processInstanceId 流程实例Id
* @return
*/
public String getVariableValue(String variableName, String processInstanceId) {
Execution execution = runtimeService
.createExecutionQuery().processInstanceId(processInstanceId).list().get(0);
Object object = runtimeService.getVariable(execution.getId(), variableName);
return object == null ? "" : object.toString();
}
/**
* 根据key和value判断el表达式是否通过
*
* @param key el表达式key
* @param el el表达式
* @param value el表达式传入值
* @return
* */
public boolean isCondition(String key, String el, String value) {
ExpressionFactory factory = new ExpressionFactoryImpl();
SimpleContext context = new SimpleContext();
context.setVariable(key, factory.createValueExpression(value, String.class));
ValueExpression e = factory.createValueExpression(context, el, boolean.class);
return (Boolean) e.getValue(context);
}
public List<UserTask> getNextUserTask(Task task) {
List<UserTask> taskList = new ArrayList<>();
ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
HistoryService historyService = processEngine.getHistoryService();
// 取得已提交的任务
HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery()
.taskId(task.getId()).singleResult();
// 获得流程定义
ProcessDefinition processDefinition = repositoryService.getProcessDefinition(historicTaskInstance.getProcessDefinitionId());
//获得当前流程的活动ID
ExecutionQuery executionQuery = runtimeService.createExecutionQuery();
Execution execution = executionQuery.executionId(historicTaskInstance.getExecutionId()).singleResult();
String activityId = execution.getActivityId();
UserTask userTask = null;
//根据活动节点获取当前的组件信息
FlowNode flowNode = getFlowNode(processDefinition.getId(), activityId);
//获取该节点之后的流向
List<SequenceFlow> sequenceFlowListOutGoing = flowNode.getOutgoingFlows();
// 获取的下个节点不一定是userTask的任务节点,所以要判断是否是任务节点
if (sequenceFlowListOutGoing.size() > 1) {
// 如果有1条以上的出线,表示有分支,需要判断分支的条件才能知道走哪个分支
// 遍历节点的出线得到下个activityId
activityId = getNextActivityId(execution.getId(),task.getProcessInstanceId(), sequenceFlowListOutGoing);
} else if (sequenceFlowListOutGoing.size() == 1) {
// 只有1条出线,直接取得下个节点
SequenceFlow sequenceFlow = sequenceFlowListOutGoing.get(0);
// 下个节点
FlowElement flowElement = sequenceFlow.getTargetFlowElement();
if (flowElement instanceof UserTask) {
// 下个节点为UserTask时
userTask = (UserTask) flowElement;
//System.out.println("下个任务为:" + userTask.getName());
taskList.add(userTask);
} else if (flowElement instanceof ExclusiveGateway) {
// 下个节点为排它网关时
ExclusiveGateway exclusiveGateway = (ExclusiveGateway) flowElement;
List<SequenceFlow> outgoingFlows = exclusiveGateway.getOutgoingFlows();
// 遍历网关的出线得到下个activityId
activityId = getNextActivityId(execution.getId(), task.getProcessInstanceId(), outgoingFlows);
//找到出口的节点
flowNode = getFlowNode(processDefinition.getId(), activityId);
//找不到符合条件的节点,就返回null
if(flowNode==null) {
return null;
}
//如果出口处是结束节点,则返回空
if(flowNode instanceof EndEvent){
return null;
}
//如果出口处就是一个UserTask,就返回它
if (flowNode instanceof UserTask) {
userTask = (UserTask) flowNode;
taskList.add(userTask);
}
}
}
return taskList;
}
private List<NextNodeDTO> getNextUserTask(String taskId,DynamicFormConf conf,String ywid,String processInstanceId){
List<NextNodeDTO> dtos = new ArrayList<>();
long startTime = System.currentTimeMillis();
// 获取 Activiti 引擎
ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
/* String processInstanceId = processEngine.getTaskService().createTaskQuery()
.taskId(taskId)
.singleResult()
.getProcessInstanceId();*/
// 根据流程实例 ID 查询流程定义
ProcessDefinition processDefinition = processEngine.getRepositoryService()
.createProcessDefinitionQuery()
.processDefinitionId(processEngine.getRuntimeService().createProcessInstanceQuery()
.processInstanceId(processInstanceId)
.singleResult()
.getProcessDefinitionId())
.singleResult();
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("方法执行时长5:" + duration + " 毫秒");
startTime = System.currentTimeMillis();
String currentActivityId = runtimeService.getActiveActivityIds(processInstanceId).iterator().next();
// 获取 BPMN 模型
BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
// 获取当前任务节点
FlowNode currentTask = (FlowNode) bpmnModel.getMainProcess().getFlowElement(currentActivityId);
endTime = System.currentTimeMillis();
duration = endTime - startTime;
System.out.println("方法执行时长6:" + duration + " 毫秒");
startTime = System.currentTimeMillis();
// 获取出口连线
for (SequenceFlow sequenceFlow : currentTask.getOutgoingFlows()) {
FlowElement targetFlowElement = bpmnModel.getFlowElement(sequenceFlow.getTargetRef());
// 判断目标节点是否为网关
if (targetFlowElement instanceof Gateway) {
// 如果是网关,则递归获取网关后的 User Task
dtos.addAll(getUserTasksAfterGateway(ywid,processInstanceId,bpmnModel, targetFlowElement.getId(),conf));
} else if (targetFlowElement instanceof UserTask) {
// 如果是 User Task,则将其添加到列表中
dtos.add(getElementInfo(ywid,processInstanceId,targetFlowElement,sequenceFlow));
}else if(targetFlowElement instanceof EndEvent){
conf.setHavEnd("2");
}
}
endTime = System.currentTimeMillis();
duration = endTime - startTime;
System.out.println("方法执行时长7:" + duration + " 毫秒");
return dtos;
}
private List<NextNodeDTO> getUserTasksAfterGateway(String ywid,String processInstanceId,BpmnModel bpmnModel, String gatewayId,DynamicFormConf conf) {
List<NextNodeDTO> dtos = new ArrayList<>();
FlowNode gateway = (FlowNode) bpmnModel.getMainProcess().getFlowElement(gatewayId);
// 获取出口连线
for (SequenceFlow sequenceFlow : gateway.getOutgoingFlows()) {
FlowElement targetFlowElement = bpmnModel.getFlowElement(sequenceFlow.getTargetRef());
// 判断目标节点是否为网关
if (targetFlowElement instanceof Gateway) {
// 如果是网关,则递归获取网关后的 User Task
dtos.addAll(getUserTasksAfterGateway(ywid,processInstanceId,bpmnModel, targetFlowElement.getId(),conf));
} else if (targetFlowElement instanceof UserTask) {
// 如果是 User Task,则将其添加到列表中
dtos.add(getElementInfo(ywid,processInstanceId,targetFlowElement,sequenceFlow));
}else if(targetFlowElement instanceof EndEvent){
conf.setHavEnd("2");
}
}
return dtos;
}
private NextNodeDTO getElementInfo(String ywid,String processInstanceId,FlowElement targetFlowElement,SequenceFlow sequenceFlow ){
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
NextNodeDTO dto = new NextNodeDTO();
dto.setNodeId(targetFlowElement.getId());
dto.setNodeName(targetFlowElement.getName());
String conditionExpression = sequenceFlow.getConditionExpression();
if(StringUtils.isNotBlank(conditionExpression)){
String condition = getDept(conditionExpression);
String value = condition.substring(condition.length()-1);
dto.setNodeValue(value);
}
if(sequenceFlow.getSourceRef().contains("comm_")){//交流节点
//通过查询日志来确定
List<SpActLog> logList = spActLogService.findbyYwidAndPId(ywid, processInstanceId);
if(CollectionUtils.isNotEmpty(logList)){
SpActLog log = logList.get(0);
com.ruoyi.activiti.domain.SysUser user = sysUserService.getById(log.getCreateBy());
List<UserDTO> usrlist = new ArrayList<>();
UserDTO userdto = new UserDTO();
userdto.setAccount(user.getUserName());
userdto.setUserName(user.getNickName());
usrlist.add(userdto);
dto.setUsers(usrlist);
}
}else{
UserTask ut = (UserTask) targetFlowElement;
List<String> cg = ut.getCandidateGroups();
if(CollectionUtils.isNotEmpty(cg)){
String[] parts = parseStringUtils.parseString(cg.get(0));
if (parts != null && parts.length ==4) {
String deptNames = parts[0];
String departmentId = parts[1];
String dg = parts[2];
String jc = parts[3];
dto.setDeptNames(deptNames);
dto.setDeptId(departmentId);
dto.setDg(dg);
dto.setJc(jc);
}
}
if(StringUtils.isBlank(dto.getDeptId())){
String cd = null;
//没有部门就用登录用户部门
//dto.setDeptId(getActivitiDeptId(processInstanceId));
long startTime = System.currentTimeMillis();
if(StringUtils.isNotBlank(dto.getJc()) && "1".equals(dto.getJc())){ //继承审批者的部门,并递归找到根节点部门
cd =sysUser.getDeptId()+"";
}else{
cd =getActivitiDeptId(processInstanceId);
}
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("方法执行时长8:" + duration + " 毫秒");
//改为归获取录入人的上级部门以《XXX海事局》为“海事局”结尾的部门 来限制审核部门的范围
startTime = System.currentTimeMillis();
if(StringUtils.isNotBlank(dto.getDg())){
SysDept father_deptId = sysUserService.findHierarchy(cd,dto.getDg());
dto.setDeptId(father_deptId.getDeptId()+"");
}else{
dto.setDeptId(cd);
}
endTime = System.currentTimeMillis();
duration = endTime - startTime;
System.out.println("方法执行时长9:" + duration + " 毫秒");
}
}
return dto;
}
private String getDept(String text) {
Pattern pattern = Pattern.compile("\\{([^\\}]*)\\}");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
return matcher.group(1);
}
return null;
}
@Override
public DynamicFormConf getNodeInfo(String taskId,String ywid){
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
long startTime = System.currentTimeMillis();
Task task = taskRuntime.task(taskId);
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("方法执行时长1:" + duration + " 毫秒");
String formKey = task.getFormKey();
DynamicFormConf conf = new DynamicFormConf();
if(formKey.contains("comm_")){//如果包含这个开头,说明是属于沟通节点
conf.setIsComm("2");
}
startTime = System.currentTimeMillis();
//获取历史节点
Set<RunNodesDTO> set= new HashSet<>();
// 查询已完成的历史流程实例
List<HistoricActivityInstance> completedInstances = historyService.createHistoricActivityInstanceQuery()
.processInstanceId(task.getProcessInstanceId())
.activityType("userTask") //用户任务
.finished() //已经执行的任务节点
.orderByHistoricActivityInstanceEndTime()
.asc()
.list();
List<HistoricActivityInstance> oldList = new ArrayList<>();
endTime = System.currentTimeMillis();
duration = endTime - startTime;
System.out.println("方法执行时长2:" + duration + " 毫秒");
startTime = System.currentTimeMillis();
//排除驳回到指定节点和之后已经执行的节点,只保留之前的
if(CollectionUtils.isNotEmpty(completedInstances)){
for (HistoricActivityInstance historicActivityInstance:completedInstances){
if(!historicActivityInstance.getActivityId().equals(task.getTaskDefinitionKey())){
if(!historicActivityInstance.getActivityId().contains("comm_")){//过滤咨询节点
oldList.add(historicActivityInstance);
}
}else{
break;
}
}
}
for (int i = 0; i < oldList.size(); i++) {
RunNodesDTO dto = new RunNodesDTO();
/*String tzaskId =oldList.get(i).getProcessDefinitionId();
String[] pasrs = getHisCandiateGroupUser(oldList.get(i).getTaskId(),oldList.get(i).getActivityId(),oldList.get(i).getProcessDefinitionId());
dto.setDeptId(pasrs[1]);
dto.setDeptNames(pasrs[0]);*/
com.ruoyi.activiti.domain.SysUser runUser = sysUserService.selectUserByUserName(oldList.get(i).getAssignee());
if(runUser==null){
throw new ServiceException("用户不存在,数据错误!");
}
dto.setAssignee(runUser.getUserName());
dto.setAssigneeName(runUser.getNickName());
dto.setRunNodeId(oldList.get(i).getActivityId());
dto.setRunNodeName(oldList.get(i).getActivityName());
/*if(StringUtils.isBlank(dto.getDeptId())){
//没有部门就用登录用户部门
//dto.setDeptId(getActivitiDeptId(processInstanceId));
String create_dept =getActivitiDeptId(task.getProcessInstanceId());
if(i==0){//第一个审核节点
dto.setDeptId(create_dept);
}else{
//改为归获取录入人的上级部门以《XXX海事局》为“海事局”结尾的部门 来限制审核部门的范围
String father_deptId = sysUserService.findHierarchy(create_dept);
dto.setDeptId(father_deptId);
}
}*/
set.add(dto);
}
endTime = System.currentTimeMillis();
duration = endTime - startTime;
System.out.println("方法执行时长3:" + duration + " 毫秒");
//获取
startTime = System.currentTimeMillis();
List<NextNodeDTO> nodeDtos = getNextUserTask(taskId, conf,ywid,task.getProcessInstanceId());
endTime = System.currentTimeMillis();
duration = endTime - startTime;
System.out.println("方法执行时长4:" + duration + " 毫秒");
if(CollectionUtils.isNotEmpty(set)){
conf.setHavHis("2");
conf.setRunNodes(set);
}
if(CollectionUtils.isNotEmpty(nodeDtos)){
conf.setNextAssign("1");
conf.setNextNodes(nodeDtos);
}
return conf;
}
private String[] getHisCandiateGroupUser(String taskId,String flowElemetId,String processDefId) {
String[] grroups = new String[3];
DynamicFormConf dynamicFormConf = new DynamicFormConf();
//当前流程节点Id,在任务表里面对应TASK_DEF_KEY_字段,可以根据taskId获取该字段数据
BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefId);
Process process = bpmnModel.getProcesses().get(0);
//获取所有普通任务节点
List<UserTask> UserTaskList = process.findFlowElementsOfType(UserTask.class);
for(UserTask userTask:UserTaskList){
//获取当前任务节点Id
String id = userTask.getId();
if(id.equals(flowElemetId)){
List<String> candidateGroups = userTask.getCandidateGroups();
// List<String> users = userTask.getCandidateUsers();
for (String group:candidateGroups
) {
grroups = parseStringUtils.parseString(group);
}
}
}
return grroups;
}
/**
*
* @param startActiviti
* @return
*/
@Override
@Transactional
public String startActiviti(StartActiviti startActiviti) throws Exception{
long startTime = System.currentTimeMillis();
String processInsTanceId = startAct(startActiviti);
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("方法执行时长:" + duration + " 毫秒");
return processInsTanceId;
}
/**
* 异步启动工作流
* @param startActiviti
*/
@Override
@Transactional
public void AsynstartActiviti(StartActiviti startActiviti) throws Exception{
long startTime = System.currentTimeMillis();
String processInsTanceId = startAct(startActiviti);
R<Boolean> rsc = remoteScService.changeSpywStatusAndSavePid(startActiviti.getType(),startActiviti.getId(),processInsTanceId,"0", SecurityConstants.INNER);
if(rsc.getCode()!= Constants.SUCCESS){
throw new ServiceException(rsc.getMsg());
}
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("方法执行时长:" + duration + " 毫秒");
}
public String startAct(StartActiviti startActiviti) throws Exception{
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
securityUtil.logInAs(sysUser.getUserName());
// 启动流程实例
org.activiti.api.process.model.ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
.start()
.withProcessDefinitionKey(startActiviti.getProcessDefinitionKey())
.withName(startActiviti.getTitle())//原本存业务名称,为了更好的关联业务改存为业务类型
.withBusinessKey(startActiviti.getId())
.withVariable("actType",startActiviti.getType())
.withVariable("assignee",sysUser.getUserName())
.build());
// 获取流程实例当前任务
org.activiti.engine.task.Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
String dg = null; //是否需要递归到父节点
String[] deptNames = null;
String jc = null;//第一节点
// 获取当前任务的候选人
List<IdentityLink> candidateUsers = taskService.getIdentityLinksForTask(task.getId());
for (IdentityLink identityLink : candidateUsers) {
if (identityLink.getType().equals(IdentityLinkType.CANDIDATE)) {
String userId = identityLink.getUserId();
if (userId != null) {
//删除原有的
//taskService.deleteCandidateUser(task.getId(), identityLink.getUserId());
startActiviti.setDeptId(getDept(userId)) ;
}
}
}
// 获取当前任务的候选组
List<IdentityLink> candidateGroups = taskService.getIdentityLinksForTask(task.getId());
for (IdentityLink identityLink : candidateGroups) {
if (identityLink.getType().equals(IdentityLinkType.CANDIDATE)) {
String groupId = identityLink.getGroupId();
if (groupId != null) {
//删除原有的
taskService.deleteCandidateGroup(task.getId(), identityLink.getGroupId());
String[] parts = parseStringUtils.parseString(groupId);
if (parts != null && parts.length == 4) {
if(StringUtils.isNotBlank(parts[0])){
deptNames = parts[0].split("#");
}
if(StringUtil.isNotBlank(parts[1])){
startActiviti.setDeptId(parts[1]);//先优先配置的部门信息
}
dg = parts[2];
jc = parts[3];
}
}
}
}
//传参部门和配置部门都为空,就以录入人部门为准
if(StringUtils.isBlank(startActiviti.getDeptId())){
if(StringUtils.isNotBlank(dg) && deptNames!=null && deptNames.length>0){//需要递归到父节点
long startTime = System.currentTimeMillis();
SysDept f_deptId = sysUserService.findHierarchy(startActiviti.getDepts(),dg);//找到父节点
if(f_deptId==null){
throw new ServiceException("找不到父节点,配置有问题,请联系管理员");
}
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("找父节点耗时:" + duration + " 毫秒");
startTime = System.currentTimeMillis();
List<String> sonList = sysUserService.getByAncestors(f_deptId.getDeptCode(),deptNames);
if(CollectionUtils.isEmpty(sonList)){
throw new ServiceException("找不到配置节点,配置有问题,请联系管理员");
}
endTime = System.currentTimeMillis();
duration = endTime - startTime;
System.out.println("找子节点耗时:" + duration + " 毫秒");
startActiviti.setDeptId(String.join(",", sonList));
}else{
startActiviti.setDeptId(startActiviti.getDepts());
}
}
List<com.ruoyi.activiti.domain.SysUser> userList = new ArrayList<>();
if(startActiviti.getAssigeners()!=null && startActiviti.getAssigeners().length>0){
if("0".equals(startActiviti.getSfbdm())){//0本单位审核
String dps = startActiviti.getDeptId();
String[] dp = dps.split("#");
//第一阶段只允许本单位审批,则需要判断第一审批人是否属于本单位
List<com.ruoyi.activiti.domain.SysUser> ul = sysUserService.checkUserDepts(startActiviti.getAssigeners(), dp);
userList.addAll(ul);
if(!org.springframework.util.CollectionUtils.isEmpty(userList)){//如果有
for (int i = 0; i < userList.size(); i++) {
taskService.addCandidateUser(task.getId(),userList.get(i).getUserName());
}
}
}else{//允许非本单位审批
//允许非单位审批,直接指定审批人
for (String userName:startActiviti.getAssigeners()
) {
taskService.addCandidateUser(task.getId(),userName);
}
}
}
if(userList.size()==0){//说明第一审核节点未指定审核人
String dps = startActiviti.getDeptId();
String[] dp = dps.split(",");
List<com.ruoyi.activiti.domain.SysUser> joins = sysUserService.selectUserNameByPostCodeAndDeptId2(null,null, dp);
if(CollectionUtils.isNotEmpty(joins)){
for (com.ruoyi.activiti.domain.SysUser join:joins
) {
//指定新的候选人
taskService.addCandidateUser(task.getId(),join.getUserName());
}
}else{
throw new ServiceException("该部门没有审批人,请检查审批配置");
}
}
//保存中间表
SpScActDTO spScActDTO = new SpScActDTO();
spScActDTO.setPid(processInstance.getId());
spScActDTO.setActType(startActiviti.getType());
spScActDTO.setActKey(startActiviti.getProcessDefinitionKey());
spScActDTO.setName(startActiviti.getTitle());
spScActDTO.setSpResultStatus("0");
spScActDTO.setGlbm(startActiviti.getDeptId());
spScActService.saveEntity(spScActDTO);
//记录日志
SpActLogDTO logdto = new SpActLogDTO();
logdto.setYwid(startActiviti.getId());
logdto.setPid(processInstance.getId());
logdto.setSpStatus("0");
String describe = "任务启动";
logdto.setYwms(describe);
logdto.setCzry(sysUser.getNickName());
spActLogService.saveEntity(logdto);
return processInstance.getId();
}