diff --git a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/task/BpmProcessInstanceServiceImpl.java b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/task/BpmProcessInstanceServiceImpl.java
index 0ea434134..f7bc24223 100644
--- a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/task/BpmProcessInstanceServiceImpl.java
+++ b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/task/BpmProcessInstanceServiceImpl.java
@@ -1 +1 @@
-package cn.iocoder.yudao.module.bpm.service.task;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.common.util.object.PageUtils;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.BpmProcessInstanceCancelReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.BpmProcessInstanceCreateReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.BpmProcessInstancePageReqVO;
import cn.iocoder.yudao.module.bpm.convert.task.BpmProcessInstanceConvert;
import cn.iocoder.yudao.module.bpm.enums.task.BpmDeleteReasonEnum;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceStatusEnum;
import cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.strategy.BpmTaskCandidateStartUserSelectStrategy;
import cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmConstants;
import cn.iocoder.yudao.module.bpm.framework.flowable.core.event.BpmProcessInstanceEventPublisher;
import cn.iocoder.yudao.module.bpm.framework.flowable.core.util.FlowableUtils;
import cn.iocoder.yudao.module.bpm.service.definition.BpmProcessDefinitionService;
import cn.iocoder.yudao.module.bpm.service.message.BpmMessageService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.FlowableCancelledEvent;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.*;
/**
* 流程实例 Service 实现类
*
* ProcessDefinition & ProcessInstance & Execution & Task 的关系:
* 1.
*
* HistoricProcessInstance & ProcessInstance 的关系:
* 1.
*
* 简单来说,前者 = 历史 + 运行中的流程实例,后者仅是运行中的流程实例
*
* @author 芋道源码
*/
@Service
@Validated
@Slf4j
public class BpmProcessInstanceServiceImpl implements BpmProcessInstanceService {
@Resource
private RuntimeService runtimeService;
@Resource
private HistoryService historyService;
@Resource
private BpmProcessDefinitionService processDefinitionService;
@Resource
private BpmMessageService messageService;
@Resource
private AdminUserApi adminUserApi;
@Resource
private BpmProcessInstanceEventPublisher processInstanceEventPublisher;
@Override
public ProcessInstance getProcessInstance(String id) {
return runtimeService.createProcessInstanceQuery()
.includeProcessVariables()
.processInstanceId(id)
.singleResult();
}
@Override
public List getProcessInstances(Set ids) {
return runtimeService.createProcessInstanceQuery().processInstanceIds(ids).list();
}
@Override
public HistoricProcessInstance getHistoricProcessInstance(String id) {
return historyService.createHistoricProcessInstanceQuery().processInstanceId(id).includeProcessVariables().singleResult();
}
@Override
public List getHistoricProcessInstances(Set ids) {
return historyService.createHistoricProcessInstanceQuery().processInstanceIds(ids).list();
}
@Override
public PageResult getProcessInstancePage(Long userId,
BpmProcessInstancePageReqVO pageReqVO) {
// 通过 BpmProcessInstanceExtDO 表,先查询到对应的分页
HistoricProcessInstanceQuery processInstanceQuery = historyService.createHistoricProcessInstanceQuery()
.includeProcessVariables()
.processInstanceTenantId(FlowableUtils.getTenantId())
.orderByProcessInstanceStartTime().desc();
if (userId != null) { // 【我的流程】菜单时,需要传递该字段
processInstanceQuery.startedBy(String.valueOf(userId));
} else if (pageReqVO.getStartUserId() != null) { // 【管理流程】菜单时,才会传递该字段
processInstanceQuery.startedBy(String.valueOf(pageReqVO.getStartUserId()));
}
if (StrUtil.isNotEmpty(pageReqVO.getName())) {
processInstanceQuery.processInstanceNameLike("%" + pageReqVO.getName() + "%");
}
if (StrUtil.isNotEmpty(pageReqVO.getProcessDefinitionId())) {
processInstanceQuery.processDefinitionId("%" + pageReqVO.getProcessDefinitionId() + "%");
}
if (StrUtil.isNotEmpty(pageReqVO.getCategory())) {
processInstanceQuery.processDefinitionCategory(pageReqVO.getCategory());
}
if (pageReqVO.getStatus() != null) {
processInstanceQuery.variableValueEquals(BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, pageReqVO.getStatus());
}
if (ArrayUtil.isNotEmpty(pageReqVO.getCreateTime())) {
processInstanceQuery.startedAfter(DateUtils.of(pageReqVO.getCreateTime()[0]));
processInstanceQuery.startedBefore(DateUtils.of(pageReqVO.getCreateTime()[1]));
}
// 查询数量
long processInstanceCount = processInstanceQuery.count();
if (processInstanceCount == 0) {
return PageResult.empty(processInstanceCount);
}
// 查询列表
List processInstanceList = processInstanceQuery.listPage(PageUtils.getStart(pageReqVO), pageReqVO.getPageSize());
return new PageResult<>(processInstanceList, processInstanceCount);
}
@Override
@Transactional(rollbackFor = Exception.class)
public String createProcessInstance(Long userId, @Valid BpmProcessInstanceCreateReqVO createReqVO) {
// 获得流程定义
ProcessDefinition definition = processDefinitionService.getProcessDefinition(createReqVO.getProcessDefinitionId());
// 发起流程
return createProcessInstance0(userId, definition, createReqVO.getVariables(), null,
createReqVO.getStartUserSelectAssignees());
}
@Override
public String createProcessInstance(Long userId, @Valid BpmProcessInstanceCreateReqDTO createReqDTO) {
// 获得流程定义
ProcessDefinition definition = processDefinitionService.getActiveProcessDefinition(createReqDTO.getProcessDefinitionKey());
// 发起流程
return createProcessInstance0(userId, definition, createReqDTO.getVariables(), createReqDTO.getBusinessKey(),
createReqDTO.getStartUserSelectAssignees());
}
private String createProcessInstance0(Long userId, ProcessDefinition definition,
Map variables, String businessKey,
Map> startUserSelectAssignees) {
// 1.1 校验流程定义
if (definition == null) {
throw exception(PROCESS_DEFINITION_NOT_EXISTS);
}
if (definition.isSuspended()) {
throw exception(PROCESS_DEFINITION_IS_SUSPENDED);
}
// 1.2 校验发起人自选审批人
validateStartUserSelectAssignees(definition, startUserSelectAssignees);
// 2. 创建流程实例
FlowableUtils.filterProcessInstanceFormVariable(variables); // 过滤一下,避免 ProcessInstance 系统级的变量被占用
variables.put(BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, // 流程实例状态:审批中
BpmProcessInstanceStatusEnum.RUNNING.getStatus());
if (CollUtil.isNotEmpty(startUserSelectAssignees)) {
variables.put(BpmConstants.PROCESS_INSTANCE_VARIABLE_START_USER_SELECT_ASSIGNEES, startUserSelectAssignees);
}
ProcessInstance instance = runtimeService.createProcessInstanceBuilder()
.processDefinitionId(definition.getId())
.businessKey(businessKey)
.name(definition.getName().trim())
.variables(variables)
.start();
return instance.getId();
}
private void validateStartUserSelectAssignees(ProcessDefinition definition, Map> startUserSelectAssignees) {
// 1. 获得发起人自选审批人的 UserTask 列表
BpmnModel bpmnModel = processDefinitionService.getProcessDefinitionBpmnModel(definition.getId());
List userTaskList = BpmTaskCandidateStartUserSelectStrategy.getStartUserSelectUserTaskList(bpmnModel);
if (CollUtil.isEmpty(userTaskList)) {
return;
}
// 2. 校验发起人自选审批人的 UserTask 是否都配置了
userTaskList.forEach(userTask -> {
List assignees = startUserSelectAssignees != null ? startUserSelectAssignees.get(userTask.getId()) : null;
if (CollUtil.isEmpty(assignees)) {
throw exception(PROCESS_INSTANCE_START_USER_SELECT_ASSIGNEES_NOT_CONFIG, userTask.getName());
}
Map userMap = adminUserApi.getUserMap(assignees);
assignees.forEach(assignee -> {
if (userMap.get(assignee) == null) {
throw exception(PROCESS_INSTANCE_START_USER_SELECT_ASSIGNEES_NOT_EXISTS, userTask.getName(), assignee);
}
});
});
}
@Override
public void cancelProcessInstanceByStartUser(Long userId, @Valid BpmProcessInstanceCancelReqVO cancelReqVO) {
// 1.1 校验流程实例存在
ProcessInstance instance = getProcessInstance(cancelReqVO.getId());
if (instance == null) {
throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS);
}
// 1.2 只能取消自己的
if (!Objects.equals(instance.getStartUserId(), String.valueOf(userId))) {
throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_SELF);
}
// 2. 通过删除流程实例,实现流程实例的取消,
// 删除流程实例,正则执行任务 ACT_RU_TASK. 任务会被删除。
deleteProcessInstance(cancelReqVO.getId(),
BpmDeleteReasonEnum.CANCEL_PROCESS_INSTANCE_BY_START_USER.format(cancelReqVO.getReason()));
// 3. 进一步的处理,交给 updateProcessInstanceCancel 方法
}
@Override
public void cancelProcessInstanceByAdmin(Long userId, BpmProcessInstanceCancelReqVO cancelReqVO) {
// 1.1 校验流程实例存在
ProcessInstance instance = getProcessInstance(cancelReqVO.getId());
if (instance == null) {
throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS);
}
// 1.2 管理员取消,不用校验是否为自己的
AdminUserRespDTO user = adminUserApi.getUser(userId);
// 2. 通过删除流程实例,实现流程实例的取消,
// 删除流程实例,正则执行任务 ACT_RU_TASK. 任务会被删除。
deleteProcessInstance(cancelReqVO.getId(),
BpmDeleteReasonEnum.CANCEL_PROCESS_INSTANCE_BY_ADMIN.format(user.getNickname(), cancelReqVO.getReason()));
// 3. 进一步的处理,交给 updateProcessInstanceCancel 方法
}
@Override
public void updateProcessInstanceWhenCancel(FlowableCancelledEvent event) {
// 1. 判断是否为 Reject 不通过。如果是,则不进行更新.
// 因为,updateProcessInstanceReject 方法(审批不通过),已经进行更新了
if (BpmDeleteReasonEnum.isRejectReason((String) event.getCause())) {
return;
}
// 2. 更新流程实例 status
runtimeService.setVariable(event.getProcessInstanceId(), BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS,
BpmProcessInstanceStatusEnum.CANCEL.getStatus());
// 3. 发送流程实例的状态事件
// 注意:此时如果去查询 ProcessInstance 的话,字段是不全的,所以去查询了 HistoricProcessInstance
HistoricProcessInstance processInstance = getHistoricProcessInstance(event.getProcessInstanceId());
// 发送流程实例的状态事件
processInstanceEventPublisher.sendProcessInstanceResultEvent(
BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceStatusEvent(this, processInstance, BpmProcessInstanceStatusEnum.CANCEL.getStatus()));
}
@Override
public void updateProcessInstanceWhenApprove(ProcessInstance instance) {
// 1. 更新流程实例 status
runtimeService.setVariable(instance.getId(), BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS,
BpmProcessInstanceStatusEnum.APPROVE.getStatus());
// 2. 发送流程被【通过】的消息
messageService.sendMessageWhenProcessInstanceApprove(BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceApproveMessage(instance));
// 3. 发送流程实例的状态事件
// 注意:此时如果去查询 ProcessInstance 的话,字段是不全的,所以去查询了 HistoricProcessInstance
HistoricProcessInstance processInstance = getHistoricProcessInstance(instance.getId());
processInstanceEventPublisher.sendProcessInstanceResultEvent(
BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceStatusEvent(this, processInstance, BpmProcessInstanceStatusEnum.APPROVE.getStatus()));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateProcessInstanceReject(String id, String reason) {
// 1. 更新流程实例 status
runtimeService.setVariable(id, BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, BpmProcessInstanceStatusEnum.REJECT.getStatus());
// 2. 删除流程实例,以实现驳回任务时,取消整个审批流程
ProcessInstance processInstance = getProcessInstance(id);
deleteProcessInstance(id, StrUtil.format(BpmDeleteReasonEnum.REJECT_TASK.format(reason)));
// 3. 发送流程被【不通过】的消息
messageService.sendMessageWhenProcessInstanceReject(BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceRejectMessage(processInstance, reason));
// 4. 发送流程实例的状态事件
processInstanceEventPublisher.sendProcessInstanceResultEvent(
BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceStatusEvent(this, processInstance, BpmProcessInstanceStatusEnum.REJECT.getStatus()));
}
private void deleteProcessInstance(String id, String reason) {
runtimeService.deleteProcessInstance(id, reason);
}
}
\ No newline at end of file
+package cn.iocoder.yudao.module.bpm.service.task;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.common.util.object.PageUtils;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.BpmProcessInstanceCancelReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.BpmProcessInstanceCreateReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.instance.BpmProcessInstancePageReqVO;
import cn.iocoder.yudao.module.bpm.convert.task.BpmProcessInstanceConvert;
import cn.iocoder.yudao.module.bpm.enums.task.BpmDeleteReasonEnum;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceStatusEnum;
import cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.strategy.BpmTaskCandidateStartUserSelectStrategy;
import cn.iocoder.yudao.module.bpm.framework.flowable.core.enums.BpmConstants;
import cn.iocoder.yudao.module.bpm.framework.flowable.core.event.BpmProcessInstanceEventPublisher;
import cn.iocoder.yudao.module.bpm.framework.flowable.core.util.FlowableUtils;
import cn.iocoder.yudao.module.bpm.service.definition.BpmProcessDefinitionService;
import cn.iocoder.yudao.module.bpm.service.message.BpmMessageService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.FlowableCancelledEvent;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import java.util.*;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.*;
/**
* 流程实例 Service 实现类
*
* ProcessDefinition & ProcessInstance & Execution & Task 的关系:
* 1.
*
* HistoricProcessInstance & ProcessInstance 的关系:
* 1.
*
* 简单来说,前者 = 历史 + 运行中的流程实例,后者仅是运行中的流程实例
*
* @author 芋道源码
*/
@Service
@Validated
@Slf4j
public class BpmProcessInstanceServiceImpl implements BpmProcessInstanceService {
@Resource
private RuntimeService runtimeService;
@Resource
private HistoryService historyService;
@Resource
private BpmProcessDefinitionService processDefinitionService;
@Resource
private BpmMessageService messageService;
@Resource
private AdminUserApi adminUserApi;
@Resource
private BpmProcessInstanceEventPublisher processInstanceEventPublisher;
@Override
public ProcessInstance getProcessInstance(String id) {
return runtimeService.createProcessInstanceQuery()
.includeProcessVariables()
.processInstanceId(id)
.singleResult();
}
@Override
public List getProcessInstances(Set ids) {
return runtimeService.createProcessInstanceQuery().processInstanceIds(ids).list();
}
@Override
public HistoricProcessInstance getHistoricProcessInstance(String id) {
return historyService.createHistoricProcessInstanceQuery().processInstanceId(id).includeProcessVariables().singleResult();
}
@Override
public List getHistoricProcessInstances(Set ids) {
return historyService.createHistoricProcessInstanceQuery().processInstanceIds(ids).list();
}
@Override
public PageResult getProcessInstancePage(Long userId,
BpmProcessInstancePageReqVO pageReqVO) {
// 通过 BpmProcessInstanceExtDO 表,先查询到对应的分页
HistoricProcessInstanceQuery processInstanceQuery = historyService.createHistoricProcessInstanceQuery()
.includeProcessVariables()
.processInstanceTenantId(FlowableUtils.getTenantId())
.orderByProcessInstanceStartTime().desc();
if (userId != null) { // 【我的流程】菜单时,需要传递该字段
processInstanceQuery.startedBy(String.valueOf(userId));
} else if (pageReqVO.getStartUserId() != null) { // 【管理流程】菜单时,才会传递该字段
processInstanceQuery.startedBy(String.valueOf(pageReqVO.getStartUserId()));
}
if (StrUtil.isNotEmpty(pageReqVO.getName())) {
processInstanceQuery.processInstanceNameLike("%" + pageReqVO.getName() + "%");
}
if (StrUtil.isNotEmpty(pageReqVO.getProcessDefinitionId())) {
processInstanceQuery.processDefinitionId("%" + pageReqVO.getProcessDefinitionId() + "%");
}
if (StrUtil.isNotEmpty(pageReqVO.getCategory())) {
processInstanceQuery.processDefinitionCategory(pageReqVO.getCategory());
}
if (pageReqVO.getStatus() != null) {
processInstanceQuery.variableValueEquals(BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, pageReqVO.getStatus());
}
if (ArrayUtil.isNotEmpty(pageReqVO.getCreateTime())) {
processInstanceQuery.startedAfter(DateUtils.of(pageReqVO.getCreateTime()[0]));
processInstanceQuery.startedBefore(DateUtils.of(pageReqVO.getCreateTime()[1]));
}
// 查询数量
long processInstanceCount = processInstanceQuery.count();
if (processInstanceCount == 0) {
return PageResult.empty(processInstanceCount);
}
// 查询列表
List processInstanceList = processInstanceQuery.listPage(PageUtils.getStart(pageReqVO), pageReqVO.getPageSize());
return new PageResult<>(processInstanceList, processInstanceCount);
}
@Override
@Transactional(rollbackFor = Exception.class)
public String createProcessInstance(Long userId, @Valid BpmProcessInstanceCreateReqVO createReqVO) {
// 获得流程定义
ProcessDefinition definition = processDefinitionService.getProcessDefinition(createReqVO.getProcessDefinitionId());
// 发起流程
return createProcessInstance0(userId, definition, createReqVO.getVariables(), null,
createReqVO.getStartUserSelectAssignees());
}
@Override
public String createProcessInstance(Long userId, @Valid BpmProcessInstanceCreateReqDTO createReqDTO) {
// 获得流程定义
ProcessDefinition definition = processDefinitionService.getActiveProcessDefinition(createReqDTO.getProcessDefinitionKey());
// 发起流程
return createProcessInstance0(userId, definition, createReqDTO.getVariables(), createReqDTO.getBusinessKey(),
createReqDTO.getStartUserSelectAssignees());
}
private String createProcessInstance0(Long userId, ProcessDefinition definition,
Map variables, String businessKey,
Map> startUserSelectAssignees) {
// 1.1 校验流程定义
if (definition == null) {
throw exception(PROCESS_DEFINITION_NOT_EXISTS);
}
if (definition.isSuspended()) {
throw exception(PROCESS_DEFINITION_IS_SUSPENDED);
}
// 1.2 校验发起人自选审批人
validateStartUserSelectAssignees(definition, startUserSelectAssignees);
// 2. 创建流程实例
if (variables == null) {
variables = new HashMap<>();
}
FlowableUtils.filterProcessInstanceFormVariable(variables); // 过滤一下,避免 ProcessInstance 系统级的变量被占用
variables.put(BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, // 流程实例状态:审批中
BpmProcessInstanceStatusEnum.RUNNING.getStatus());
if (CollUtil.isNotEmpty(startUserSelectAssignees)) {
variables.put(BpmConstants.PROCESS_INSTANCE_VARIABLE_START_USER_SELECT_ASSIGNEES, startUserSelectAssignees);
}
ProcessInstance instance = runtimeService.createProcessInstanceBuilder()
.processDefinitionId(definition.getId())
.businessKey(businessKey)
.name(definition.getName().trim())
.variables(variables)
.start();
return instance.getId();
}
private void validateStartUserSelectAssignees(ProcessDefinition definition, Map> startUserSelectAssignees) {
// 1. 获得发起人自选审批人的 UserTask 列表
BpmnModel bpmnModel = processDefinitionService.getProcessDefinitionBpmnModel(definition.getId());
List userTaskList = BpmTaskCandidateStartUserSelectStrategy.getStartUserSelectUserTaskList(bpmnModel);
if (CollUtil.isEmpty(userTaskList)) {
return;
}
// 2. 校验发起人自选审批人的 UserTask 是否都配置了
userTaskList.forEach(userTask -> {
List assignees = startUserSelectAssignees != null ? startUserSelectAssignees.get(userTask.getId()) : null;
if (CollUtil.isEmpty(assignees)) {
throw exception(PROCESS_INSTANCE_START_USER_SELECT_ASSIGNEES_NOT_CONFIG, userTask.getName());
}
Map userMap = adminUserApi.getUserMap(assignees);
assignees.forEach(assignee -> {
if (userMap.get(assignee) == null) {
throw exception(PROCESS_INSTANCE_START_USER_SELECT_ASSIGNEES_NOT_EXISTS, userTask.getName(), assignee);
}
});
});
}
@Override
public void cancelProcessInstanceByStartUser(Long userId, @Valid BpmProcessInstanceCancelReqVO cancelReqVO) {
// 1.1 校验流程实例存在
ProcessInstance instance = getProcessInstance(cancelReqVO.getId());
if (instance == null) {
throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS);
}
// 1.2 只能取消自己的
if (!Objects.equals(instance.getStartUserId(), String.valueOf(userId))) {
throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_SELF);
}
// 2. 通过删除流程实例,实现流程实例的取消,
// 删除流程实例,正则执行任务 ACT_RU_TASK. 任务会被删除。
deleteProcessInstance(cancelReqVO.getId(),
BpmDeleteReasonEnum.CANCEL_PROCESS_INSTANCE_BY_START_USER.format(cancelReqVO.getReason()));
// 3. 进一步的处理,交给 updateProcessInstanceCancel 方法
}
@Override
public void cancelProcessInstanceByAdmin(Long userId, BpmProcessInstanceCancelReqVO cancelReqVO) {
// 1.1 校验流程实例存在
ProcessInstance instance = getProcessInstance(cancelReqVO.getId());
if (instance == null) {
throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS);
}
// 1.2 管理员取消,不用校验是否为自己的
AdminUserRespDTO user = adminUserApi.getUser(userId);
// 2. 通过删除流程实例,实现流程实例的取消,
// 删除流程实例,正则执行任务 ACT_RU_TASK. 任务会被删除。
deleteProcessInstance(cancelReqVO.getId(),
BpmDeleteReasonEnum.CANCEL_PROCESS_INSTANCE_BY_ADMIN.format(user.getNickname(), cancelReqVO.getReason()));
// 3. 进一步的处理,交给 updateProcessInstanceCancel 方法
}
@Override
public void updateProcessInstanceWhenCancel(FlowableCancelledEvent event) {
// 1. 判断是否为 Reject 不通过。如果是,则不进行更新.
// 因为,updateProcessInstanceReject 方法(审批不通过),已经进行更新了
if (BpmDeleteReasonEnum.isRejectReason((String) event.getCause())) {
return;
}
// 2. 更新流程实例 status
runtimeService.setVariable(event.getProcessInstanceId(), BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS,
BpmProcessInstanceStatusEnum.CANCEL.getStatus());
// 3. 发送流程实例的状态事件
// 注意:此时如果去查询 ProcessInstance 的话,字段是不全的,所以去查询了 HistoricProcessInstance
HistoricProcessInstance processInstance = getHistoricProcessInstance(event.getProcessInstanceId());
// 发送流程实例的状态事件
processInstanceEventPublisher.sendProcessInstanceResultEvent(
BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceStatusEvent(this, processInstance, BpmProcessInstanceStatusEnum.CANCEL.getStatus()));
}
@Override
public void updateProcessInstanceWhenApprove(ProcessInstance instance) {
// 1. 更新流程实例 status
runtimeService.setVariable(instance.getId(), BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS,
BpmProcessInstanceStatusEnum.APPROVE.getStatus());
// 2. 发送流程被【通过】的消息
messageService.sendMessageWhenProcessInstanceApprove(BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceApproveMessage(instance));
// 3. 发送流程实例的状态事件
// 注意:此时如果去查询 ProcessInstance 的话,字段是不全的,所以去查询了 HistoricProcessInstance
HistoricProcessInstance processInstance = getHistoricProcessInstance(instance.getId());
processInstanceEventPublisher.sendProcessInstanceResultEvent(
BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceStatusEvent(this, processInstance, BpmProcessInstanceStatusEnum.APPROVE.getStatus()));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateProcessInstanceReject(String id, String reason) {
// 1. 更新流程实例 status
runtimeService.setVariable(id, BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS, BpmProcessInstanceStatusEnum.REJECT.getStatus());
// 2. 删除流程实例,以实现驳回任务时,取消整个审批流程
ProcessInstance processInstance = getProcessInstance(id);
deleteProcessInstance(id, StrUtil.format(BpmDeleteReasonEnum.REJECT_TASK.format(reason)));
// 3. 发送流程被【不通过】的消息
messageService.sendMessageWhenProcessInstanceReject(BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceRejectMessage(processInstance, reason));
// 4. 发送流程实例的状态事件
processInstanceEventPublisher.sendProcessInstanceResultEvent(
BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceStatusEvent(this, processInstance, BpmProcessInstanceStatusEnum.REJECT.getStatus()));
}
private void deleteProcessInstance(String id, String reason) {
runtimeService.deleteProcessInstance(id, reason);
}
}
\ No newline at end of file
diff --git a/yudao-module-crm/yudao-module-crm-biz/src/main/java/cn/iocoder/yudao/module/crm/service/statistics/CrmStatisticsPerformanceServiceImpl.java b/yudao-module-crm/yudao-module-crm-biz/src/main/java/cn/iocoder/yudao/module/crm/service/statistics/CrmStatisticsPerformanceServiceImpl.java
index 450d691ff..fcd7267a8 100644
--- a/yudao-module-crm/yudao-module-crm-biz/src/main/java/cn/iocoder/yudao/module/crm/service/statistics/CrmStatisticsPerformanceServiceImpl.java
+++ b/yudao-module-crm/yudao-module-crm-biz/src/main/java/cn/iocoder/yudao/module/crm/service/statistics/CrmStatisticsPerformanceServiceImpl.java
@@ -1,6 +1,7 @@
package cn.iocoder.yudao.module.crm.service.statistics;
import cn.hutool.core.collection.CollUtil;
+import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.module.crm.controller.admin.statistics.vo.performance.CrmStatisticsPerformanceReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.statistics.vo.performance.CrmStatisticsPerformanceRespVO;
@@ -13,8 +14,9 @@ import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import jakarta.annotation.Resource;
-import java.util.Collections;
-import java.util.List;
+
+import java.math.BigDecimal;
+import java.util.*;
import java.util.function.Function;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
@@ -38,7 +40,7 @@ public class CrmStatisticsPerformanceServiceImpl implements CrmStatisticsPerform
@Override
public List getContractCountPerformance(CrmStatisticsPerformanceReqVO performanceReqVO) {
- // TODO @scholar:我们可以换个思路实现,减少数据库的计算量;
+ // TODO @scholar:可以把下面这个注释,你理解后,重新整理下,写到 getPerformance 里;
// 比如说,2024 年的合同数据,是不是 2022-12 到 2024-12-31,每个月的统计呢?
// 理解之后,我们可以数据 group by 年-月,20222-12 到 2024-12-31 的,然后内存在聚合出 CrmStatisticsPerformanceRespVO 这样
// 这样,我们就可以减少数据库的计算量,提升性能;同时 SQL 也会很简单,开发者理解起来也简单哈;
@@ -55,28 +57,99 @@ public class CrmStatisticsPerformanceServiceImpl implements CrmStatisticsPerform
return getPerformance(performanceReqVO, performanceMapper::selectReceivablePricePerformance);
}
+ // TODO @scholar:代码注释,应该有 3 个变量哈;
/**
* 获得员工业绩数据
*
* @param performanceReqVO 参数
- * @param performanceFunction 排行榜方法
- * @return 排行版数据
+ * @param performanceFunction 员工业绩统计方法
+ * @return 员工业绩数据
*/
+ // TODO @scholar:下面一行的变量,超过一行了,阅读不美观;可以考虑每一行一个变量;
private List getPerformance(CrmStatisticsPerformanceReqVO performanceReqVO, Function> performanceFunction) {
+ // TODO @scholar:没使用到的变量,建议删除;
+ List performanceRespVOList;
+
// 1. 获得用户编号数组
final List userIds = getUserIds(performanceReqVO);
if (CollUtil.isEmpty(userIds)) {
return Collections.emptyList();
}
performanceReqVO.setUserIds(userIds);
- // 2. 获得排行数据
+ // TODO @scholar:1. 和 2. 之间,可以考虑换一行;保证每一块逻辑的间隔;
+ // 2. 获得业绩数据
+ // TODO @scholar:复数变量,建议使用 s 或者 list 结果;这里用 performanceList 好列;
List performance = performanceFunction.apply(performanceReqVO);
- if (CollUtil.isEmpty(performance)) {
- return Collections.emptyList();
+
+ // 获取查询的年份
+ // TODO @scholar:逻辑可以简化一下;
+ // TODO 1)把 performance 转换成 map;key 是 time,value 是 count
+ // TODO 2)当前年,遍历 1-12 月份,去 map 拿到 count;接着月份 -1,去 map 拿 count;再年份 -1,拿 count
+ String currentYear = LocalDateTimeUtil.format(performanceReqVO.getTimes()[0],"yyyy");
+
+ // 构造查询当年和前一年,每年12个月的年月组合
+ List allMonths = new ArrayList<>();
+ for (int year = Integer.parseInt(currentYear)-1; year <= Integer.parseInt(currentYear); year++) {
+ for (int month = 1; month <= 12; month++) {
+ allMonths.add(String.format("%d%02d", year, month));
+ }
}
- return performance;
+
+ List computedList = new ArrayList<>();
+ List respVOList = new ArrayList<>();
+
+ // 生成computedList基础数据
+ // 构造完整的2*12个月的数据,如果某月数据缺失,需要补上0,一年12个月不能有缺失
+ for (String month : allMonths) {
+ CrmStatisticsPerformanceRespVO foundData = performance.stream()
+ .filter(data -> data.getTime().equals(month))
+ .findFirst()
+ .orElse(null);
+
+ if (foundData != null) {
+ computedList.add(foundData);
+ } else {
+ CrmStatisticsPerformanceRespVO missingData = new CrmStatisticsPerformanceRespVO();
+ missingData.setTime(month);
+ missingData.setCurrentMonthCount(BigDecimal.ZERO);
+ missingData.setLastMonthCount(BigDecimal.ZERO);
+ missingData.setLastYearCount(BigDecimal.ZERO);
+ computedList.add(missingData);
+ }
+ }
+ //根据查询年份和前一年的数据,计算查询年份的同比环比数据
+ for (CrmStatisticsPerformanceRespVO currentData : computedList) {
+ String currentMonth = currentData.getTime();
+
+ // 根据当年和前一年的月销售数据,计算currentYear的完整数据
+ if (currentMonth.startsWith(currentYear)) {
+ // 计算 LastMonthCount
+ int currentIndex = computedList.indexOf(currentData);
+ if (currentIndex > 0) {
+ CrmStatisticsPerformanceRespVO lastMonthData = computedList.get(currentIndex - 1);
+ currentData.setLastMonthCount(lastMonthData.getCurrentMonthCount());
+ } else {
+ currentData.setLastMonthCount(BigDecimal.ZERO); // 第一个月的 LastMonthCount 设为0
+ }
+
+ // 计算 LastYearCount
+ String lastYearMonth = String.valueOf(Integer.parseInt(currentMonth) - 100);
+ CrmStatisticsPerformanceRespVO lastYearData = computedList.stream()
+ .filter(data -> data.getTime().equals(lastYearMonth))
+ .findFirst()
+ .orElse(null);
+
+ if (lastYearData != null) {
+ currentData.setLastYearCount(lastYearData.getCurrentMonthCount());
+ } else {
+ currentData.setLastYearCount(BigDecimal.ZERO); // 如果去年同月数据不存在,设为0
+ }
+ respVOList.add(currentData);//给前端只需要返回查询当年的数据,不需要前一年数据
+ }
+ }
+ return respVOList;
}
/**
diff --git a/yudao-module-crm/yudao-module-crm-biz/src/main/resources/mapper/statistics/CrmStatisticsPerformanceMapper.xml b/yudao-module-crm/yudao-module-crm-biz/src/main/resources/mapper/statistics/CrmStatisticsPerformanceMapper.xml
index 10b952bac..79ff45471 100644
--- a/yudao-module-crm/yudao-module-crm-biz/src/main/resources/mapper/statistics/CrmStatisticsPerformanceMapper.xml
+++ b/yudao-module-crm/yudao-module-crm-biz/src/main/resources/mapper/statistics/CrmStatisticsPerformanceMapper.xml
@@ -5,75 +5,28 @@
+
+
+
-
diff --git a/yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/delivery/DeliveryExpressTemplateServiceImpl.java b/yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/delivery/DeliveryExpressTemplateServiceImpl.java
index c939e8531..7aed42803 100644
--- a/yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/delivery/DeliveryExpressTemplateServiceImpl.java
+++ b/yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/delivery/DeliveryExpressTemplateServiceImpl.java
@@ -88,7 +88,7 @@ public class DeliveryExpressTemplateServiceImpl implements DeliveryExpressTempla
List oldList = expressTemplateFreeMapper.selectListByTemplateId(templateId);
List newList = INSTANCE.convertTemplateFreeList(templateId, frees);
List> diffList = CollectionUtils.diffList(oldList, newList,
- (oldVal, newVal) -> ObjectUtil.equal(oldVal.getId(), newVal.getTemplateId()));
+ (oldVal, newVal) -> ObjectUtil.equal(oldVal.getId(), newVal.getId()));
// 第二步,批量添加、修改、删除
if (CollUtil.isNotEmpty(diffList.get(0))) {
diff --git a/yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceImpl.java b/yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceImpl.java
index 036d73d04..58c36c312 100644
--- a/yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceImpl.java
+++ b/yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceImpl.java
@@ -36,13 +36,15 @@ public class PayWalletServiceImpl implements PayWalletService {
@Resource
private PayWalletMapper walletMapper;
+
@Resource
+ @Lazy // 延迟加载,避免循环依赖
private PayWalletTransactionService walletTransactionService;
@Resource
- @Lazy
+ @Lazy // 延迟加载,避免循环依赖
private PayOrderService orderService;
@Resource
- @Lazy
+ @Lazy // 延迟加载,避免循环依赖
private PayRefundService refundService;
@Override
diff --git a/yudao-server/src/main/resources/application-dev.yaml b/yudao-server/src/main/resources/application-dev.yaml
index 8caf15b08..91ea2b2a7 100644
--- a/yudao-server/src/main/resources/application-dev.yaml
+++ b/yudao-server/src/main/resources/application-dev.yaml
@@ -198,6 +198,16 @@ justauth:
client-secret: 1wTb7hYxnpT2TUbIeHGXGo7T0odav1ic10mLdyyATOw
agent-id: 1000004
ignore-check-redirect-uri: true
+ # noinspection SpringBootApplicationYaml
+ WECHAT_MINI_APP: # 微信小程序
+ client-id: ${wx.miniapp.appid}
+ client-secret: ${wx.miniapp.secret}
+ ignore-check-redirect-uri: true
+ ignore-check-state: true # 微信小程序,不会使用到 state,所以不进行校验
+ WECHAT_MP: # 微信公众号
+ client-id: ${wx.mp.app-id}
+ client-secret: ${wx.mp.secret}
+ ignore-check-redirect-uri: true
cache:
type: REDIS
prefix: 'social_auth_state:' # 缓存前缀,目前只对 Redis 缓存生效,默认 JUSTAUTH::STATE::
diff --git a/yudao-server/src/main/resources/application-local.yaml b/yudao-server/src/main/resources/application-local.yaml
index 89a037830..c08317115 100644
--- a/yudao-server/src/main/resources/application-local.yaml
+++ b/yudao-server/src/main/resources/application-local.yaml
@@ -254,6 +254,7 @@ justauth:
client-secret: 1wTb7hYxnpT2TUbIeHGXGo7T0odav1ic10mLdyyATOw
agent-id: 1000004
ignore-check-redirect-uri: true
+ # noinspection SpringBootApplicationYaml
WECHAT_MINI_APP: # 微信小程序
client-id: ${wx.miniapp.appid}
client-secret: ${wx.miniapp.secret}