gaoluyang
5 天以前 8c65f898ed6e5b0c7a94c792c4562f6ec831dccd
yudao-module-crm/src/main/java/cn/iocoder/yudao/module/crm/service/quotation/CrmSaleQuotationServiceImpl.java
@@ -1,9 +1,17 @@
package cn.iocoder.yudao.module.crm.service.quotation;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
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.enums.task.BpmProcessInstanceStatusEnum;
import cn.iocoder.yudao.module.bpm.service.definition.BpmCategoryService;
import cn.iocoder.yudao.module.bpm.service.definition.BpmProcessDefinitionService;
import cn.iocoder.yudao.module.crm.controller.admin.contract.vo.contract.CrmContractSaveReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.quotation.vo.CrmSaleQuotationPageReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.quotation.vo.CrmSaleQuotationSaveReqVO;
@@ -26,8 +34,10 @@
import cn.iocoder.yudao.module.system.api.storage.StorageAttachmentApi;
import cn.iocoder.yudao.module.mdm.api.item.MdmItemApi;
import cn.iocoder.yudao.module.mdm.api.item.dto.MdmItemRespDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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;
@@ -42,12 +52,17 @@
/**
 * CRM 销售报价单 Service 实现类
 *
 * @author 芋道源码
 * @author 超级管理员
 */
@Service
@Validated
@Slf4j
public class CrmSaleQuotationServiceImpl implements CrmSaleQuotationService {
    /**
     * BPM 销售报价审批分类编码
     */
    private static final String SALE_QUOTATION_APPROVE_CATEGORY_CODE = "sale_quotation_approve";
    @Resource
    private CrmSaleQuotationMapper saleQuotationMapper;
@@ -75,16 +90,23 @@
    @Resource
    private CrmContractService contractService;
    @Resource
    private BpmProcessInstanceApi bpmProcessInstanceApi;
    @Resource
    private BpmCategoryService bpmCategoryService;
    @Resource
    private BpmProcessDefinitionService bpmProcessDefinitionService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createSaleQuotation(CrmSaleQuotationSaveReqVO createReqVO, Long userId) {
        // 1.1 校验物料项的有效性
        List<CrmSaleQuotationProductDO> quotationProducts = validateQuotationItems(createReqVO.getItems());
        // 1.2 生成报价单号,并校验唯一性
        String no = noRedisDAO.generate(CrmNoRedisDAO.SALE_QUOTATION_NO_PREFIX);
        if (saleQuotationMapper.selectByNo(no) != null) {
            throw exception(SALE_QUOTATION_NO_EXISTS);
        }
        // 1.2 确定报价单号(前端填写则用自定义单号,留空则自动生成),并校验唯一性
        String customNo = StrUtil.trim(createReqVO.getNo());
        String no = StrUtil.isBlank(customNo)
                ? noRedisDAO.generate(CrmNoRedisDAO.SALE_QUOTATION_NO_PREFIX) : customNo;
        validateQuotationNoUnique(no, null);
        // 1.3 校验关联字段
        validateRelationDataExists(createReqVO);
@@ -122,8 +144,15 @@
        // 1.4 校验关联字段
        validateRelationDataExists(updateReqVO);
        // 2.1 更新报价单
        // 2.1 更新报价单(报价单号留空表示保持原值,填写则校验唯一性后替换)
        CrmSaleQuotationDO updateObj = BeanUtils.toBean(updateReqVO, CrmSaleQuotationDO.class);
        String no = StrUtil.trim(updateReqVO.getNo());
        if (StrUtil.isBlank(no)) {
            updateObj.setNo(saleQuotation.getNo());
        } else {
            validateQuotationNoUnique(no, saleQuotation.getId());
            updateObj.setNo(no);
        }
        calculateTotalPrice(updateObj, quotationProducts);
        saleQuotationMapper.updateById(updateObj);
        // 2.2 更新报价明细
@@ -158,12 +187,136 @@
        });
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitSaleQuotation(Long id, String processDefinitionKey, Long userId) {
        // 1. 校验报价单存在且为草稿状态
        CrmSaleQuotationDO saleQuotation = validateSaleQuotationExists(id);
        if (ObjUtil.notEqual(saleQuotation.getStatus(), CrmSaleQuotationStatusEnum.DRAFT.getStatus())) {
            throw exception(SALE_QUOTATION_SUBMIT_FAIL_NOT_DRAFT, saleQuotation.getNo());
        }
        // 2. 全局免审批:直接置为审批通过,无需流程模型
        if (bpmProcessInstanceApi.isGlobalAutoApprove()) {
            saleQuotationMapper.updateById(new CrmSaleQuotationDO().setId(id).setProcessInstanceId("")
                    .setStatus(CrmSaleQuotationStatusEnum.PROCESS.getStatus()));
            updateSaleQuotationAuditStatus(id, BpmProcessInstanceStatusEnum.APPROVE.getStatus());
            return;
        }
        // 3. 校验审批分类和流程定义
        validateSaleQuotationApproveCategoryAndProcessDefinition();
        ProcessDefinition processDefinition = bpmProcessDefinitionService.getActiveProcessDefinition(processDefinitionKey);
        if (processDefinition == null) {
            throw exception(SALE_QUOTATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
        // 4. 创建审批流程实例
        String processInstanceId = bpmProcessInstanceApi.createProcessInstance(userId, new BpmProcessInstanceCreateReqDTO()
                .setProcessDefinitionKey(processDefinitionKey).setBusinessKey(String.valueOf(id)));
        // 5. 更新流程实例编号和状态
        saleQuotationMapper.updateById(new CrmSaleQuotationDO().setId(id).setProcessInstanceId(processInstanceId)
                .setStatus(CrmSaleQuotationStatusEnum.PROCESS.getStatus()));
    }
    @Override
    public void updateSaleQuotationAuditStatus(Long id, Integer bpmResult) {
        // 1.1 校验报价单是否存在
        CrmSaleQuotationDO saleQuotation = validateSaleQuotationExists(id);
        // 1.2 只有审批中,才可以更新审批结果
        if (ObjUtil.notEqual(saleQuotation.getStatus(), CrmSaleQuotationStatusEnum.PROCESS.getStatus())) {
            log.error("[updateSaleQuotationAuditStatus][报价单({}) 不处于审批中,无法更新审批结果({})]",
                    saleQuotation.getNo(), bpmResult);
            throw exception(SALE_QUOTATION_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS, saleQuotation.getNo());
        }
        // 2. 转换 BPM 审批结果并更新
        Integer status;
        if (ObjUtil.equal(bpmResult, BpmProcessInstanceStatusEnum.APPROVE.getStatus())) {
            status = CrmSaleQuotationStatusEnum.APPROVE.getStatus();
        } else if (ObjUtil.equal(bpmResult, BpmProcessInstanceStatusEnum.REJECT.getStatus())) {
            status = CrmSaleQuotationStatusEnum.REJECT.getStatus();
        } else if (ObjUtil.equal(bpmResult, BpmProcessInstanceStatusEnum.CANCEL.getStatus())) {
            status = CrmSaleQuotationStatusEnum.CANCEL.getStatus();
        } else {
            log.warn("[updateSaleQuotationAuditStatus][报价单({}) 收到未知审批结果({}),忽略]", id, bpmResult);
            return;
        }
        saleQuotationMapper.updateById(new CrmSaleQuotationDO().setId(id).setStatus(status));
    }
    @Override
    public List<Map<String, Object>> getSaleQuotationApproveProcessDefinitionList() {
        validateSaleQuotationApproveCategoryAndProcessDefinition();
        List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService
                .getProcessDefinitionInfoListByCategory(SALE_QUOTATION_APPROVE_CATEGORY_CODE);
        Set<String> processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId);
        List<ProcessDefinition> processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds);
        // 只保留激活状态,且相同 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);
            }
        }
        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;
    }
    /**
     * 校验 BPM 销售报价审批分类和流程定义是否存在
     */
    private void validateSaleQuotationApproveCategoryAndProcessDefinition() {
        List<String> codes = Collections.singletonList(SALE_QUOTATION_APPROVE_CATEGORY_CODE);
        Map<String, ?> categoryMap = bpmCategoryService.getCategoryMap(codes);
        if (!categoryMap.containsKey(SALE_QUOTATION_APPROVE_CATEGORY_CODE)) {
            throw exception(SALE_QUOTATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
        List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService
                .getProcessDefinitionInfoListByCategory(SALE_QUOTATION_APPROVE_CATEGORY_CODE);
        if (CollUtil.isEmpty(definitionInfoList)) {
            throw exception(SALE_QUOTATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
        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(SALE_QUOTATION_BPM_PROCESS_DEFINITION_NOT_EXISTS);
        }
    }
    private CrmSaleQuotationDO validateSaleQuotationExists(Long id) {
        CrmSaleQuotationDO saleQuotation = saleQuotationMapper.selectById(id);
        if (saleQuotation == null) {
            throw exception(SALE_QUOTATION_NOT_EXISTS);
        }
        return saleQuotation;
    }
    /**
     * 校验报价单号唯一(含已逻辑删除的报价单,因 uk_no 唯一索引覆盖已删除行)
     *
     * @param no       报价单号
     * @param selfId   自身编号(修改时排除自己,新增传 null)
     */
    private void validateQuotationNoUnique(String no, Long selfId) {
        CrmSaleQuotationDO exists = saleQuotationMapper.selectAnyByNo(no);
        if (exists != null && !exists.getId().equals(selfId)) {
            throw exception(SALE_QUOTATION_NO_EXISTS, no);
        }
    }
    private List<CrmSaleQuotationProductDO> validateQuotationItems(List<CrmSaleQuotationSaveReqVO.Item> list) {
@@ -271,10 +424,13 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long convertToContract(Long id, Long userId) {
        // 1. 校验报价单存在且为草稿状态
        // 1. 校验报价单存在,且为草稿或审批通过状态
        CrmSaleQuotationDO saleQuotation = validateSaleQuotationExists(id);
        if (!CrmSaleQuotationStatusEnum.DRAFT.getStatus().equals(saleQuotation.getStatus())) {
            throw exception(SALE_QUOTATION_CONVERT_FAIL_NOT_DRAFT, saleQuotation.getNo());
        if (!CrmSaleQuotationStatusEnum.DRAFT.getStatus().equals(saleQuotation.getStatus())
                && !CrmSaleQuotationStatusEnum.APPROVE.getStatus().equals(saleQuotation.getStatus())) {
            CrmSaleQuotationStatusEnum current = CrmSaleQuotationStatusEnum.getByStatus(saleQuotation.getStatus());
            throw exception(SALE_QUOTATION_CONVERT_FAIL_NOT_DRAFT, saleQuotation.getNo(),
                    current != null ? current.getName() : String.valueOf(saleQuotation.getStatus()));
        }
        // 校验是否已转合同
        if (saleQuotation.getContractId() != null) {
@@ -299,7 +455,7 @@
            product.setItemId(qp.getItemId());
            product.setItemPrice(qp.getItemPrice());
            product.setContractPrice(qp.getQuotationPrice());
            product.setCount(qp.getCount().intValue());
            product.setCount(qp.getCount());
            return product;
        });
        contractVO.setProducts(contractProducts);
@@ -318,4 +474,14 @@
        return contractId;
    }
}
    @Override
    public CrmSaleQuotationDO getByContractId(Long id) {
        return saleQuotationMapper.selectOne(new LambdaQueryWrapper<CrmSaleQuotationDO>().eq(CrmSaleQuotationDO::getContractId,id));
    }
    @Override
    public void clearContractReference(Long quotationId) {
        saleQuotationMapper.clearContractReference(quotationId);
    }
}