liu
19 小时以前 79c416ea8a72aa9469deb14272135cca8dc01aac
feat(crm): 退费单/销户申请审核通过后禁止修改和删除

- updateRefund/deleteRefund、updateCancellation/deleteCancellation 增加审核通过(20)状态守卫
- 新增错误码:1020018015 退费修改、1020018016 退费删除、1020018017 销户修改、1020018018 销户删除
- 无数据库结构变更

Co-Authored-By Claude <noreply@anthropic.com>
已修改3个文件
445 ■■■■■ 文件已修改
yudao-module-crm/src/main/java/cn/iocoder/yudao/module/crm/enums/ErrorCodeConstants.java 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
yudao-module-crm/src/main/java/cn/iocoder/yudao/module/crm/service/cancellation/CrmCancellationServiceImpl.java 210 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
yudao-module-crm/src/main/java/cn/iocoder/yudao/module/crm/service/refund/CrmRefundServiceImpl.java 210 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
yudao-module-crm/src/main/java/cn/iocoder/yudao/module/crm/enums/ErrorCodeConstants.java
@@ -19,7 +19,9 @@
    ErrorCode CONTRACT_GENERATE_ORDER_FAIL_NOT_APPROVE = new ErrorCode(1_020_000_006, "生成销售订单失败,原因:合同未审批通过");
    ErrorCode CONTRACT_GENERATE_ORDER_FAIL_EXISTS_ORDER = new ErrorCode(1_020_000_007, "生成销售订单失败,原因:已关联销售订单【{}】");
    ErrorCode CONTRACT_GENERATE_ORDER_FAIL_NO_PRODUCT = new ErrorCode(1_020_000_008, "生成销售订单失败,原因:合同没有产品信息");
    ErrorCode CONTRACT_BPM_PROCESS_DEFINITION_NOT_EXISTS = new ErrorCode(1_020_000_009, "合同审批流程不存在或未激活,请检查 BPM 配置");
    ErrorCode CONTRACT_SUBMIT_FAIL_NOT_EDITABLE = new ErrorCode(1_020_000_010, "只有未提交或审核不通过状态的合同才能提交审批");
    ErrorCode CONTRACT_AUDIT_FAIL_NOT_PROCESS = new ErrorCode(1_020_000_012, "只有审批中状态的合同才能审核");
    ErrorCode CONTRACT_AUDIT_REJECT_REASON_REQUIRED = new ErrorCode(1_020_000_014, "审核不通过时必须填写不通过原因");
    // ========== 线索管理 1-020-001-000 ==========
    ErrorCode CLUE_NOT_EXISTS = new ErrorCode(1_020_001_000, "线索不存在");
@@ -126,8 +128,9 @@
    ErrorCode INVOICE_NO_EXISTS = new ErrorCode(1_020_016_001, "生成开票序列号重复,请重试");
    ErrorCode INVOICE_UPDATE_FAIL_EDITING_PROHIBITED = new ErrorCode(1_020_016_002, "更新开票失败,原因:禁止编辑");
    ErrorCode INVOICE_DELETE_FAIL_IS_APPROVE = new ErrorCode(1_020_016_003, "删除开票失败,原因:开票审批已通过");
    ErrorCode INVOICE_SUBMIT_FAIL_NOT_DRAFT = new ErrorCode(1_020_016_004, "开票提交审核失败,原因:开票没处在未提交状态");
    ErrorCode INVOICE_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS = new ErrorCode(1_020_016_005, "更新开票审核状态失败,原因:开票不是审核中状态");
    ErrorCode INVOICE_SUBMIT_FAIL_NOT_EDITABLE = new ErrorCode(1_020_016_004, "只有草稿或审核不通过状态的开票才能提交审批");
    ErrorCode INVOICE_AUDIT_FAIL_NOT_PROCESS = new ErrorCode(1_020_016_005, "只有审批中状态的开票才能审核");
    ErrorCode INVOICE_AUDIT_REJECT_REASON_REQUIRED = new ErrorCode(1_020_016_013, "审核不通过时必须填写不通过原因");
    ErrorCode INVOICE_CREATE_FAIL_CONTRACT_NOT_APPROVE = new ErrorCode(1_020_016_006, "创建开票失败,原因:合同不是审核通过状态");
    ErrorCode INVOICE_CREATE_FAIL_PRICE_EXCEEDS_LIMIT = new ErrorCode(1_020_016_007, "创建开票失败,原因:开票金额超出合同金额,目前可开票:{} 元");
    ErrorCode RECEIVABLE_CREATE_FAIL_INVOICE_NOT_EXISTS = new ErrorCode(1_020_016_008, "创建回款失败,原因:关联的开票不存在");
@@ -154,12 +157,16 @@
    ErrorCode CRM_CANCELLATION_NOT_EXISTS = new ErrorCode(1_020_018_006, "销户申请不存在");
    ErrorCode CRM_CANCELLATION_NO_DUPLICATE = new ErrorCode(1_020_018_007, "销户申请编号已存在");
    ErrorCode CRM_REFUND_SUBMIT_FAIL_NOT_DRAFT = new ErrorCode(1_020_018_008, "退费单审批失败,原因:退费单不处于草稿状态");
    ErrorCode CRM_REFUND_BPM_PROCESS_DEFINITION_NOT_EXISTS = new ErrorCode(1_020_018_009, "退费单审批失败,原因:BPM 审批流程不存在,请先在 BPM 管理后台配置退费审批流程");
    ErrorCode CRM_REFUND_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS = new ErrorCode(1_020_018_010, "退费单审批失败,原因:退费单不处于审批中,无法更新审批结果");
    ErrorCode CRM_REFUND_UPDATE_FAIL_APPROVE = new ErrorCode(1_020_018_015, "修改退费单失败,原因:退费单已审核通过,不允许修改");
    ErrorCode CRM_REFUND_DELETE_FAIL_APPROVE = new ErrorCode(1_020_018_016, "删除退费单失败,原因:退费单已审核通过,不允许删除");
    ErrorCode CRM_REFUND_SUBMIT_FAIL_NOT_EDITABLE = new ErrorCode(1_020_018_008, "只有草稿或审核不通过状态的退费单才能提交审批");
    ErrorCode CRM_REFUND_AUDIT_FAIL_NOT_PROCESS = new ErrorCode(1_020_018_009, "只有审批中状态的退费单才能审核");
    ErrorCode CRM_REFUND_AUDIT_REJECT_REASON_REQUIRED = new ErrorCode(1_020_018_010, "审核不通过时必须填写不通过原因");
    ErrorCode CRM_CANCELLATION_SUBMIT_FAIL_NOT_DRAFT = new ErrorCode(1_020_018_011, "销户申请审批失败,原因:销户申请不处于草稿状态");
    ErrorCode CRM_CANCELLATION_BPM_PROCESS_DEFINITION_NOT_EXISTS = new ErrorCode(1_020_018_012, "销户申请审批失败,原因:BPM 审批流程不存在,请先在 BPM 管理后台配置销户审批流程");
    ErrorCode CRM_CANCELLATION_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS = new ErrorCode(1_020_018_013, "销户申请审批失败,原因:销户申请不处于审批中,无法更新审批结果");
    ErrorCode CRM_CANCELLATION_UPDATE_FAIL_APPROVE = new ErrorCode(1_020_018_017, "修改销户申请失败,原因:销户申请已审核通过,不允许修改");
    ErrorCode CRM_CANCELLATION_DELETE_FAIL_APPROVE = new ErrorCode(1_020_018_018, "删除销户申请失败,原因:销户申请已审核通过,不允许删除");
    ErrorCode CRM_CANCELLATION_SUBMIT_FAIL_NOT_EDITABLE = new ErrorCode(1_020_018_011, "只有草稿或审核不通过状态的销户申请才能提交审批");
    ErrorCode CRM_CANCELLATION_AUDIT_FAIL_NOT_PROCESS = new ErrorCode(1_020_018_012, "只有审批中状态的销户申请才能审核");
    ErrorCode CRM_CANCELLATION_AUDIT_REJECT_REASON_REQUIRED = new ErrorCode(1_020_018_013, "审核不通过时必须填写不通过原因");
}
yudao-module-crm/src/main/java/cn/iocoder/yudao/module/crm/service/cancellation/CrmCancellationServiceImpl.java
@@ -1,12 +1,10 @@
package cn.iocoder.yudao.module.crm.service.cancellation;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.crm.controller.admin.cancellation.vo.CrmCancellationAuditReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.cancellation.vo.CrmCancellationPageReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.cancellation.vo.CrmCancellationRespVO;
import cn.iocoder.yudao.module.crm.controller.admin.cancellation.vo.CrmCancellationSaveReqVO;
@@ -14,55 +12,45 @@
import cn.iocoder.yudao.module.crm.dal.dataobject.customer.CrmCustomerDO;
import cn.iocoder.yudao.module.crm.dal.mysql.cancellation.CrmCancellationMapper;
import cn.iocoder.yudao.module.crm.dal.mysql.customer.CrmCustomerMapper;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.definition.BpmProcessDefinitionInfoDO;
import cn.iocoder.yudao.module.bpm.service.definition.BpmCategoryService;
import cn.iocoder.yudao.module.bpm.service.definition.BpmProcessDefinitionService;
import cn.iocoder.yudao.module.crm.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.crm.enums.common.CrmAuditStatusEnum;
import cn.iocoder.yudao.module.system.api.approval.ApprovalConfigApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.module.crm.util.CrmAuditStatusUtils.convertBpmResultToAuditStatus;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
@Service
@Validated
@Slf4j
public class CrmCancellationServiceImpl implements CrmCancellationService {
    private static final Integer AUDIT_DRAFT = 0;
    /**
     * BPM 销户审批分类编码
     * CRM 销户申请审批的业务类型编码
     *
     * 与 system_approval_config.biz_type 对应,审批人在「系统管理 - 审批配置」中维护。
     */
    private static final String CANCELLATION_APPROVE_CATEGORY_CODE = "cancellation_approve";
    private static final String CANCELLATION_APPROVE_BIZ_TYPE = "cancellation_approve";
    @Resource
    private CrmCancellationMapper cancellationMapper;
    @Resource
    private CrmCustomerMapper customerMapper;
    @Resource
    private BpmProcessInstanceApi bpmProcessInstanceApi;
    private AdminUserApi adminUserApi;
    @Resource
    private BpmCategoryService bpmCategoryService;
    @Resource
    private BpmProcessDefinitionService bpmProcessDefinitionService;
    private ApprovalConfigApi approvalConfigApi;
    @Override
    @Transactional(rollbackFor = Exception.class)
@@ -82,9 +70,7 @@
        if (createReqVO.getApplyTime() == null) {
            createReqVO.setApplyTime(LocalDateTime.now());
        }
        if (createReqVO.getAuditStatus() == null) {
            createReqVO.setAuditStatus(AUDIT_DRAFT);
        }
        createReqVO.setAuditStatus(CrmAuditStatusEnum.DRAFT.getStatus()); // 默认为未提交状态
        CrmCancellationDO entity = BeanUtils.toBean(createReqVO, CrmCancellationDO.class);
        cancellationMapper.insert(entity);
        return entity.getId();
@@ -92,19 +78,23 @@
    @Override
    public void updateCancellation(CrmCancellationSaveReqVO updateReqVO) {
        CrmCancellationDO exists = cancellationMapper.selectById(updateReqVO.getId());
        if (exists == null) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_NOT_EXISTS);
        // 1. 校验存在 + 审核通过的销户申请不允许修改
        CrmCancellationDO cancellation = validateCancellationExists(updateReqVO.getId());
        if (ObjUtil.equal(cancellation.getAuditStatus(), CrmAuditStatusEnum.APPROVE.getStatus())) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_UPDATE_FAIL_APPROVE);
        }
        // 2. 更新销户申请
        CrmCancellationDO entity = BeanUtils.toBean(updateReqVO, CrmCancellationDO.class);
        entity.setAuditStatus(null); // 审批状态只能由提交/审核变更
        cancellationMapper.updateById(entity);
    }
    @Override
    public void deleteCancellation(Long id) {
        CrmCancellationDO exists = cancellationMapper.selectById(id);
        if (exists == null) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_NOT_EXISTS);
        // 校验存在 + 审核通过的销户申请不允许删除
        CrmCancellationDO cancellation = validateCancellationExists(id);
        if (ObjUtil.equal(cancellation.getAuditStatus(), CrmAuditStatusEnum.APPROVE.getStatus())) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_DELETE_FAIL_APPROVE);
        }
        cancellationMapper.deleteById(id);
    }
@@ -126,129 +116,73 @@
    }
    @Override
    public void auditCancellation(CrmCancellationAuditReqVO auditReqVO) {
        CrmCancellationDO exists = cancellationMapper.selectById(auditReqVO.getId());
        if (exists == null) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_NOT_EXISTS);
    @Transactional(rollbackFor = Exception.class)
    public void submitCancellation(Long id) {
        // 1. 校验存在 + 可提交状态(未提交 / 审核不通过)
        CrmCancellationDO cancellation = validateCancellationExists(id);
        if (ObjUtil.notEqual(cancellation.getAuditStatus(), CrmAuditStatusEnum.DRAFT.getStatus())
                && ObjUtil.notEqual(cancellation.getAuditStatus(), CrmAuditStatusEnum.REJECT.getStatus())) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_SUBMIT_FAIL_NOT_EDITABLE);
        }
        CrmCancellationDO update = new CrmCancellationDO();
        update.setId(exists.getId());
        update.setAuditStatus(auditReqVO.getAuditStatus());
        if (StrUtil.isNotBlank(auditReqVO.getRemark())) {
            update.setRemark(auditReqVO.getRemark());
        }
        cancellationMapper.updateById(update);
        // 2. 校验审批配置已启用且配置了有效审批人(未配置时抛出带明确提示的业务异常)
        approvalConfigApi.validateApprovalEnabledAndGetApprovers(CANCELLATION_APPROVE_BIZ_TYPE);
        // 3. 状态置为审批中,并清空上一轮审核结果,避免残留「审核不通过」的原因
        cancellationMapper.submitAndResetAuditInfo(id, CrmAuditStatusEnum.PROCESS.getStatus());
    }
    @Override
    public void submitCancellation(Long id, String processDefinitionKey, Long userId) {
        // 1. 校验销户申请是否在草稿状态
        CrmCancellationDO cancellation = cancellationMapper.selectById(id);
        if (cancellation == null) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_NOT_EXISTS);
        }
        if (ObjUtil.notEqual(cancellation.getAuditStatus(), CrmAuditStatusEnum.DRAFT.getStatus())) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_SUBMIT_FAIL_NOT_DRAFT);
        }
        // 2. 校验销户审批分类和流程定义是否存在,且传入的流程定义处于激活状态
        validateCancellationApproveCategoryAndProcessDefinition();
        ProcessDefinition processDefinition = bpmProcessDefinitionService.getActiveProcessDefinition(processDefinitionKey);
        if (processDefinition == null) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
        // 3. 创建销户审批流程实例
        String processInstanceId = bpmProcessInstanceApi.createProcessInstance(userId,
                new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(processDefinitionKey)
                        .setBusinessKey(String.valueOf(id)));
        // 4. 更新销户申请流程编号与审批状态
        cancellationMapper.updateById(new CrmCancellationDO().setId(id).setProcessInstanceId(processInstanceId)
                .setAuditStatus(CrmAuditStatusEnum.PROCESS.getStatus()));
    public Set<Long> getCancellationApproverUserIds() {
        return approvalConfigApi.getApproverUserIds(CANCELLATION_APPROVE_BIZ_TYPE);
    }
    @Override
    public void updateCancellationAuditStatus(Long id, Integer bpmResult) {
        // 1.1 校验销户申请是否存在
        CrmCancellationDO cancellation = cancellationMapper.selectById(id);
        if (cancellation == null) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_NOT_EXISTS);
        }
        // 1.2 只有审批中,可以更新审批结果
    @Transactional(rollbackFor = Exception.class)
    public void auditCancellation(Long id, Boolean pass, String reviewRemark) {
        // 1. 校验存在
        CrmCancellationDO cancellation = validateCancellationExists(id);
        // 2. 校验处于审批中状态
        if (ObjUtil.notEqual(cancellation.getAuditStatus(), CrmAuditStatusEnum.PROCESS.getStatus())) {
            log.error("[updateCancellationAuditStatus][cancellation({}) 不处于审批中,无法更新审批结果({})]",
                    cancellation.getId(), bpmResult);
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS);
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_AUDIT_FAIL_NOT_PROCESS);
        }
        // 2. 更新销户申请审批结果
        Integer auditStatus = convertBpmResultToAuditStatus(bpmResult);
        cancellationMapper.updateById(new CrmCancellationDO().setId(id).setAuditStatus(auditStatus));
        // 3. 校验当前登录用户是该业务类型的审批人(或签:任一人均可审核)
        Long userId = getLoginUserId();
        approvalConfigApi.validateApprover(CANCELLATION_APPROVE_BIZ_TYPE, userId);
        // 4. 审核不通过:必须填写原因,状态置为审核不通过,退回提交人修改后可重新提交
        if (!Boolean.TRUE.equals(pass)) {
            if (StrUtil.isBlank(reviewRemark)) {
                throw exception(ErrorCodeConstants.CRM_CANCELLATION_AUDIT_REJECT_REASON_REQUIRED);
            }
            cancellationMapper.auditCancellation(id, CrmAuditStatusEnum.REJECT.getStatus(),
                    userId, getUserNickname(userId), reviewRemark);
            return;
        }
        // 5. 审核通过:记录审核人与审核意见,状态置为审核通过
        cancellationMapper.auditCancellation(id, CrmAuditStatusEnum.APPROVE.getStatus(),
                userId, getUserNickname(userId), reviewRemark);
    }
    @Override
    public List<Map<String, Object>> getCancellationApproveProcessDefinitionList() {
        // 1. 校验销户审批分类和流程定义是否存在
        validateCancellationApproveCategoryAndProcessDefinition();
        // 2. 获取分类下的流程定义信息
        List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService
                .getProcessDefinitionInfoListByCategory(CANCELLATION_APPROVE_CATEGORY_CODE);
        // 3. 获取流程定义详情
        Set<String> processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId);
        List<ProcessDefinition> processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds);
        // 4. 过滤:只保留激活状态,且相同 key 只保留最新版本
        Map<String, ProcessDefinition> latestVersionMap = new HashMap<>();
        for (ProcessDefinition pd : processDefinitions) {
            if (pd.isSuspended()) {
                continue;
            }
            ProcessDefinition existing = latestVersionMap.get(pd.getKey());
            if (existing == null || pd.getVersion() > existing.getVersion()) {
                latestVersionMap.put(pd.getKey(), pd);
            }
    private CrmCancellationDO validateCancellationExists(Long id) {
        CrmCancellationDO cancellation = cancellationMapper.selectById(id);
        if (cancellation == null) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_NOT_EXISTS);
        }
        // 5. 返回流程定义列表
        List<Map<String, Object>> result = new ArrayList<>();
        for (ProcessDefinition pd : latestVersionMap.values()) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", pd.getId());
            item.put("key", pd.getKey());
            item.put("name", pd.getName());
            item.put("version", pd.getVersion());
            result.add(item);
        }
        return result;
        return cancellation;
    }
    /**
     * 校验 BPM 销户审批分类和流程定义是否存在
     * 获取用户昵称
     *
     * @param userId 用户编号
     * @return 昵称,用户不存在时返回 null
     */
    private void validateCancellationApproveCategoryAndProcessDefinition() {
        // 1. 校验分类是否存在
        Map<String, ?> categoryMap = bpmCategoryService.getCategoryMap(Collections.singletonList(CANCELLATION_APPROVE_CATEGORY_CODE));
        if (!categoryMap.containsKey(CANCELLATION_APPROVE_CATEGORY_CODE)) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
    private String getUserNickname(Long userId) {
        if (userId == null) {
            return null;
        }
        // 2. 校验分类下是否有可用的流程定义
        List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService
                .getProcessDefinitionInfoListByCategory(CANCELLATION_APPROVE_CATEGORY_CODE);
        if (CollUtil.isEmpty(definitionInfoList)) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
        // 3. 校验是否有激活状态的流程定义
        Set<String> processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId);
        List<ProcessDefinition> processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds);
        boolean hasActiveDefinition = processDefinitions.stream().anyMatch(pd -> !pd.isSuspended());
        if (!hasActiveDefinition) {
            throw exception(ErrorCodeConstants.CRM_CANCELLATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
        AdminUserRespDTO user = adminUserApi.getUser(userId);
        return user == null ? null : user.getNickname();
    }
    private String generateCancellationNo() {
@@ -256,4 +190,4 @@
                + RandomUtil.randomNumbers(4);
    }
}
}
yudao-module-crm/src/main/java/cn/iocoder/yudao/module/crm/service/refund/CrmRefundServiceImpl.java
@@ -1,12 +1,10 @@
package cn.iocoder.yudao.module.crm.service.refund;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.crm.controller.admin.refund.vo.CrmRefundAuditReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.refund.vo.CrmRefundPageReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.refund.vo.CrmRefundRespVO;
import cn.iocoder.yudao.module.crm.controller.admin.refund.vo.CrmRefundSaveReqVO;
@@ -14,56 +12,45 @@
import cn.iocoder.yudao.module.crm.dal.dataobject.refund.CrmRefundDO;
import cn.iocoder.yudao.module.crm.dal.mysql.customer.CrmCustomerMapper;
import cn.iocoder.yudao.module.crm.dal.mysql.refund.CrmRefundMapper;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.definition.BpmProcessDefinitionInfoDO;
import cn.iocoder.yudao.module.bpm.service.definition.BpmCategoryService;
import cn.iocoder.yudao.module.bpm.service.definition.BpmProcessDefinitionService;
import cn.iocoder.yudao.module.crm.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.crm.enums.common.CrmAuditStatusEnum;
import cn.iocoder.yudao.module.system.api.approval.ApprovalConfigApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.module.crm.util.CrmAuditStatusUtils.convertBpmResultToAuditStatus;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
@Service
@Validated
@Slf4j
public class CrmRefundServiceImpl implements CrmRefundService {
    private static final Integer AUDIT_DRAFT = 0;
    private static final Integer AUDIT_PASS = 20;
    /**
     * BPM 退费审批分类编码
     * CRM 退费单审批的业务类型编码
     *
     * 与 system_approval_config.biz_type 对应,审批人在「系统管理 - 审批配置」中维护。
     */
    private static final String REFUND_APPROVE_CATEGORY_CODE = "refund_approve";
    private static final String REFUND_APPROVE_BIZ_TYPE = "refund_approve";
    @Resource
    private CrmRefundMapper refundMapper;
    @Resource
    private CrmCustomerMapper customerMapper;
    @Resource
    private BpmProcessInstanceApi bpmProcessInstanceApi;
    private AdminUserApi adminUserApi;
    @Resource
    private BpmCategoryService bpmCategoryService;
    @Resource
    private BpmProcessDefinitionService bpmProcessDefinitionService;
    private ApprovalConfigApi approvalConfigApi;
    @Override
    @Transactional(rollbackFor = Exception.class)
@@ -83,9 +70,7 @@
        if (createReqVO.getApplyTime() == null) {
            createReqVO.setApplyTime(LocalDateTime.now());
        }
        if (createReqVO.getAuditStatus() == null) {
            createReqVO.setAuditStatus(AUDIT_DRAFT);
        }
        createReqVO.setAuditStatus(CrmAuditStatusEnum.DRAFT.getStatus()); // 默认为未提交状态
        CrmRefundDO entity = BeanUtils.toBean(createReqVO, CrmRefundDO.class);
        refundMapper.insert(entity);
        return entity.getId();
@@ -93,19 +78,23 @@
    @Override
    public void updateRefund(CrmRefundSaveReqVO updateReqVO) {
        CrmRefundDO exists = refundMapper.selectById(updateReqVO.getId());
        if (exists == null) {
            throw exception(ErrorCodeConstants.CRM_REFUND_NOT_EXISTS);
        // 1. 校验存在 + 审核通过的退费单不允许修改
        CrmRefundDO refund = validateRefundExists(updateReqVO.getId());
        if (ObjUtil.equal(refund.getAuditStatus(), CrmAuditStatusEnum.APPROVE.getStatus())) {
            throw exception(ErrorCodeConstants.CRM_REFUND_UPDATE_FAIL_APPROVE);
        }
        // 2. 更新退费单
        CrmRefundDO entity = BeanUtils.toBean(updateReqVO, CrmRefundDO.class);
        entity.setAuditStatus(null); // 审批状态只能由提交/审核变更
        refundMapper.updateById(entity);
    }
    @Override
    public void deleteRefund(Long id) {
        CrmRefundDO exists = refundMapper.selectById(id);
        if (exists == null) {
            throw exception(ErrorCodeConstants.CRM_REFUND_NOT_EXISTS);
        // 校验存在 + 审核通过的退费单不允许删除
        CrmRefundDO refund = validateRefundExists(id);
        if (ObjUtil.equal(refund.getAuditStatus(), CrmAuditStatusEnum.APPROVE.getStatus())) {
            throw exception(ErrorCodeConstants.CRM_REFUND_DELETE_FAIL_APPROVE);
        }
        refundMapper.deleteById(id);
    }
@@ -127,128 +116,73 @@
    }
    @Override
    public void auditRefund(CrmRefundAuditReqVO auditReqVO) {
        CrmRefundDO exists = refundMapper.selectById(auditReqVO.getId());
        if (exists == null) {
            throw exception(ErrorCodeConstants.CRM_REFUND_NOT_EXISTS);
    @Transactional(rollbackFor = Exception.class)
    public void submitRefund(Long id) {
        // 1. 校验存在 + 可提交状态(未提交 / 审核不通过)
        CrmRefundDO refund = validateRefundExists(id);
        if (ObjUtil.notEqual(refund.getAuditStatus(), CrmAuditStatusEnum.DRAFT.getStatus())
                && ObjUtil.notEqual(refund.getAuditStatus(), CrmAuditStatusEnum.REJECT.getStatus())) {
            throw exception(ErrorCodeConstants.CRM_REFUND_SUBMIT_FAIL_NOT_EDITABLE);
        }
        CrmRefundDO update = new CrmRefundDO();
        update.setId(exists.getId());
        update.setAuditStatus(auditReqVO.getAuditStatus());
        if (StrUtil.isNotBlank(auditReqVO.getRemark())) {
            update.setRemark(auditReqVO.getRemark());
        }
        refundMapper.updateById(update);
        // 2. 校验审批配置已启用且配置了有效审批人(未配置时抛出带明确提示的业务异常)
        approvalConfigApi.validateApprovalEnabledAndGetApprovers(REFUND_APPROVE_BIZ_TYPE);
        // 3. 状态置为审批中,并清空上一轮审核结果,避免残留「审核不通过」的原因
        refundMapper.submitAndResetAuditInfo(id, CrmAuditStatusEnum.PROCESS.getStatus());
    }
    @Override
    public void submitRefund(Long id, String processDefinitionKey, Long userId) {
        // 1. 校验退费单是否在草稿状态
        CrmRefundDO refund = refundMapper.selectById(id);
        if (refund == null) {
            throw exception(ErrorCodeConstants.CRM_REFUND_NOT_EXISTS);
        }
        if (ObjUtil.notEqual(refund.getAuditStatus(), CrmAuditStatusEnum.DRAFT.getStatus())) {
            throw exception(ErrorCodeConstants.CRM_REFUND_SUBMIT_FAIL_NOT_DRAFT);
        }
        // 2. 校验退费审批分类和流程定义是否存在,且传入的流程定义处于激活状态
        validateRefundApproveCategoryAndProcessDefinition();
        ProcessDefinition processDefinition = bpmProcessDefinitionService.getActiveProcessDefinition(processDefinitionKey);
        if (processDefinition == null) {
            throw exception(ErrorCodeConstants.CRM_REFUND_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
        // 3. 创建退费审批流程实例
        String processInstanceId = bpmProcessInstanceApi.createProcessInstance(userId,
                new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(processDefinitionKey)
                        .setBusinessKey(String.valueOf(id)));
        // 4. 更新退费单流程编号与审批状态
        refundMapper.updateById(new CrmRefundDO().setId(id).setProcessInstanceId(processInstanceId)
                .setAuditStatus(CrmAuditStatusEnum.PROCESS.getStatus()));
    public Set<Long> getRefundApproverUserIds() {
        return approvalConfigApi.getApproverUserIds(REFUND_APPROVE_BIZ_TYPE);
    }
    @Override
    public void updateRefundAuditStatus(Long id, Integer bpmResult) {
        // 1.1 校验退费单是否存在
        CrmRefundDO refund = refundMapper.selectById(id);
        if (refund == null) {
            throw exception(ErrorCodeConstants.CRM_REFUND_NOT_EXISTS);
        }
        // 1.2 只有审批中,可以更新审批结果
    @Transactional(rollbackFor = Exception.class)
    public void auditRefund(Long id, Boolean pass, String reviewRemark) {
        // 1. 校验存在
        CrmRefundDO refund = validateRefundExists(id);
        // 2. 校验处于审批中状态
        if (ObjUtil.notEqual(refund.getAuditStatus(), CrmAuditStatusEnum.PROCESS.getStatus())) {
            log.error("[updateRefundAuditStatus][refund({}) 不处于审批中,无法更新审批结果({})]", refund.getId(), bpmResult);
            throw exception(ErrorCodeConstants.CRM_REFUND_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS);
            throw exception(ErrorCodeConstants.CRM_REFUND_AUDIT_FAIL_NOT_PROCESS);
        }
        // 2. 更新退费单审批结果
        Integer auditStatus = convertBpmResultToAuditStatus(bpmResult);
        refundMapper.updateById(new CrmRefundDO().setId(id).setAuditStatus(auditStatus));
        // 3. 校验当前登录用户是该业务类型的审批人(或签:任一人均可审核)
        Long userId = getLoginUserId();
        approvalConfigApi.validateApprover(REFUND_APPROVE_BIZ_TYPE, userId);
        // 4. 审核不通过:必须填写原因,状态置为审核不通过,退回提交人修改后可重新提交
        if (!Boolean.TRUE.equals(pass)) {
            if (StrUtil.isBlank(reviewRemark)) {
                throw exception(ErrorCodeConstants.CRM_REFUND_AUDIT_REJECT_REASON_REQUIRED);
            }
            refundMapper.auditRefund(id, CrmAuditStatusEnum.REJECT.getStatus(),
                    userId, getUserNickname(userId), reviewRemark);
            return;
        }
        // 5. 审核通过:记录审核人与审核意见,状态置为审核通过
        refundMapper.auditRefund(id, CrmAuditStatusEnum.APPROVE.getStatus(),
                userId, getUserNickname(userId), reviewRemark);
    }
    @Override
    public List<Map<String, Object>> getRefundApproveProcessDefinitionList() {
        // 1. 校验退费审批分类和流程定义是否存在
        validateRefundApproveCategoryAndProcessDefinition();
        // 2. 获取分类下的流程定义信息
        List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService
                .getProcessDefinitionInfoListByCategory(REFUND_APPROVE_CATEGORY_CODE);
        // 3. 获取流程定义详情
        Set<String> processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId);
        List<ProcessDefinition> processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds);
        // 4. 过滤:只保留激活状态,且相同 key 只保留最新版本
        Map<String, ProcessDefinition> latestVersionMap = new HashMap<>();
        for (ProcessDefinition pd : processDefinitions) {
            if (pd.isSuspended()) {
                continue;
            }
            ProcessDefinition existing = latestVersionMap.get(pd.getKey());
            if (existing == null || pd.getVersion() > existing.getVersion()) {
                latestVersionMap.put(pd.getKey(), pd);
            }
    private CrmRefundDO validateRefundExists(Long id) {
        CrmRefundDO refund = refundMapper.selectById(id);
        if (refund == null) {
            throw exception(ErrorCodeConstants.CRM_REFUND_NOT_EXISTS);
        }
        // 5. 返回流程定义列表
        List<Map<String, Object>> result = new ArrayList<>();
        for (ProcessDefinition pd : latestVersionMap.values()) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", pd.getId());
            item.put("key", pd.getKey());
            item.put("name", pd.getName());
            item.put("version", pd.getVersion());
            result.add(item);
        }
        return result;
        return refund;
    }
    /**
     * 校验 BPM 退费审批分类和流程定义是否存在
     * 获取用户昵称
     *
     * @param userId 用户编号
     * @return 昵称,用户不存在时返回 null
     */
    private void validateRefundApproveCategoryAndProcessDefinition() {
        // 1. 校验分类是否存在
        Map<String, ?> categoryMap = bpmCategoryService.getCategoryMap(Collections.singletonList(REFUND_APPROVE_CATEGORY_CODE));
        if (!categoryMap.containsKey(REFUND_APPROVE_CATEGORY_CODE)) {
            throw exception(ErrorCodeConstants.CRM_REFUND_BPM_PROCESS_DEFINITION_NOT_EXISTS);
    private String getUserNickname(Long userId) {
        if (userId == null) {
            return null;
        }
        // 2. 校验分类下是否有可用的流程定义
        List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService
                .getProcessDefinitionInfoListByCategory(REFUND_APPROVE_CATEGORY_CODE);
        if (CollUtil.isEmpty(definitionInfoList)) {
            throw exception(ErrorCodeConstants.CRM_REFUND_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
        // 3. 校验是否有激活状态的流程定义
        Set<String> processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId);
        List<ProcessDefinition> processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds);
        boolean hasActiveDefinition = processDefinitions.stream().anyMatch(pd -> !pd.isSuspended());
        if (!hasActiveDefinition) {
            throw exception(ErrorCodeConstants.CRM_REFUND_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
        AdminUserRespDTO user = adminUserApi.getUser(userId);
        return user == null ? null : user.getNickname();
    }
    private String generateRefundNo() {
@@ -256,4 +190,4 @@
                + RandomUtil.randomNumbers(4);
    }
}
}