package cn.iocoder.yudao.module.crm.service.quotation; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.lang.Assert; 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.BpmTaskStatusEnum; 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; import cn.iocoder.yudao.module.crm.dal.dataobject.contract.CrmContractDO; import cn.iocoder.yudao.module.crm.dal.dataobject.quotation.CrmSaleQuotationDO; import cn.iocoder.yudao.module.crm.dal.dataobject.quotation.CrmSaleQuotationProductDO; import cn.iocoder.yudao.module.crm.dal.mysql.quotation.CrmSaleQuotationMapper; import cn.iocoder.yudao.module.crm.dal.mysql.quotation.CrmSaleQuotationProductMapper; import cn.iocoder.yudao.module.crm.dal.redis.no.CrmNoRedisDAO; import cn.iocoder.yudao.module.crm.enums.common.CrmBizTypeEnum; import cn.iocoder.yudao.module.crm.enums.permission.CrmPermissionLevelEnum; import cn.iocoder.yudao.module.crm.enums.quotation.CrmSaleQuotationStatusEnum; import cn.iocoder.yudao.module.crm.service.business.CrmBusinessService; import cn.iocoder.yudao.module.crm.service.contact.CrmContactService; import cn.iocoder.yudao.module.crm.service.contract.CrmContractService; import cn.iocoder.yudao.module.crm.service.customer.CrmCustomerService; import cn.iocoder.yudao.module.crm.service.permission.CrmPermissionService; import cn.iocoder.yudao.module.crm.service.permission.bo.CrmPermissionCreateReqBO; import cn.iocoder.yudao.module.mdm.api.item.MdmItemApi; import cn.iocoder.yudao.module.mdm.api.item.dto.MdmItemRespDTO; 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.math.BigDecimal; import java.util.*; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*; import static cn.iocoder.yudao.module.crm.enums.ErrorCodeConstants.*; /** * CRM 销售报价单 Service 实现类 * * @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; @Resource private CrmSaleQuotationProductMapper saleQuotationProductMapper; @Resource private CrmNoRedisDAO noRedisDAO; @Resource private MdmItemApi mdmItemApi; @Resource private CrmCustomerService customerService; @Resource private CrmBusinessService businessService; @Resource private CrmContactService contactService; @Resource private CrmPermissionService permissionService; @Resource private CrmContractService contractService; @Resource private BpmCategoryService bpmCategoryService; @Resource private BpmProcessDefinitionService bpmProcessDefinitionService; @Resource private BpmProcessInstanceApi bpmProcessInstanceApi; @Override @Transactional(rollbackFor = Exception.class) public Long createSaleQuotation(CrmSaleQuotationSaveReqVO createReqVO, Long userId) { // 1.1 校验物料项的有效性 List 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.3 校验关联字段 validateRelationDataExists(createReqVO); // 2.1 插入报价单 CrmSaleQuotationDO saleQuotation = BeanUtils.toBean(createReqVO, CrmSaleQuotationDO.class, q -> q .setNo(no) .setStatus(CrmSaleQuotationStatusEnum.DRAFT.getStatus())); calculateTotalPrice(saleQuotation, quotationProducts); saleQuotationMapper.insert(saleQuotation); // 2.2 插入报价明细 quotationProducts.forEach(p -> p.setQuotationId(saleQuotation.getId())); saleQuotationProductMapper.insertBatch(quotationProducts); // 2.3 创建数据权限 permissionService.createPermission(new CrmPermissionCreateReqBO() .setUserId(userId) .setBizType(CrmBizTypeEnum.CRM_SALE_QUOTATION.getType()) .setBizId(saleQuotation.getId()) .setLevel(CrmPermissionLevelEnum.OWNER.getLevel())); return saleQuotation.getId(); } @Override @Transactional(rollbackFor = Exception.class) public void updateSaleQuotation(CrmSaleQuotationSaveReqVO updateReqVO) { // 1.1 校验存在 CrmSaleQuotationDO saleQuotation = validateSaleQuotationExists(updateReqVO.getId()); // 1.2 校验状态,只有草稿状态才能修改 if (!CrmSaleQuotationStatusEnum.DRAFT.getStatus().equals(saleQuotation.getStatus())) { throw exception(SALE_QUOTATION_UPDATE_FAIL_NOT_DRAFT, saleQuotation.getNo()); } // 1.3 校验物料项的有效性 List quotationProducts = validateQuotationItems(updateReqVO.getItems()); // 1.4 校验关联字段 validateRelationDataExists(updateReqVO); // 2.1 更新报价单 CrmSaleQuotationDO updateObj = BeanUtils.toBean(updateReqVO, CrmSaleQuotationDO.class); calculateTotalPrice(updateObj, quotationProducts); saleQuotationMapper.updateById(updateObj); // 2.2 更新报价明细 updateQuotationProductList(updateReqVO.getId(), quotationProducts); } @Override @Transactional(rollbackFor = Exception.class) public void deleteSaleQuotation(List ids) { // 1. 校验不处于非草稿状态 List saleQuotations = saleQuotationMapper.selectByIds(ids); if (CollUtil.isEmpty(saleQuotations)) { return; } saleQuotations.forEach(saleQuotation -> { if (!CrmSaleQuotationStatusEnum.DRAFT.getStatus().equals(saleQuotation.getStatus())) { throw exception(SALE_QUOTATION_DELETE_FAIL_NOT_DRAFT, saleQuotation.getNo()); } }); // 2. 遍历删除 saleQuotations.forEach(saleQuotation -> { // 2.1 删除报价单 saleQuotationMapper.deleteById(saleQuotation.getId()); // 2.2 删除报价明细 saleQuotationProductMapper.deleteByQuotationId(saleQuotation.getId()); // 2.3 删除数据权限 permissionService.deletePermission(CrmBizTypeEnum.CRM_SALE_QUOTATION.getType(), saleQuotation.getId()); }); } private CrmSaleQuotationDO validateSaleQuotationExists(Long id) { CrmSaleQuotationDO saleQuotation = saleQuotationMapper.selectById(id); if (saleQuotation == null) { throw exception(SALE_QUOTATION_NOT_EXISTS); } return saleQuotation; } private List validateQuotationItems(List list) { // 1. 校验物料存在且启用 Set itemIds = convertSet(list, CrmSaleQuotationSaveReqVO.Item::getItemId); Map itemMap = mdmItemApi.getItemMap(itemIds); // 2. 转换为 CrmSaleQuotationProductDO 列表 return convertList(list, o -> BeanUtils.toBean(o, CrmSaleQuotationProductDO.class, item -> { MdmItemRespDTO mdmItem = itemMap.get(item.getItemId()); if (mdmItem == null) { throw exception(SALE_QUOTATION_ITEM_NOT_EXISTS); } item.setItemUnitId(mdmItem.getUnitMeasureId()); item.setItemPrice(mdmItem.getSalesPrice()); if (item.getQuotationPrice() != null && item.getCount() != null) { item.setTotalPrice(MoneyUtils.priceMultiply(item.getQuotationPrice(), item.getCount())); if (item.getTaxPercent() != null) { item.setTaxPrice(MoneyUtils.priceMultiplyPercent(item.getTotalPrice(), item.getTaxPercent())); } } })); } private void validateRelationDataExists(CrmSaleQuotationSaveReqVO reqVO) { // 1. 校验客户 customerService.validateCustomer(reqVO.getCustomerId()); // 2. 校验商机(可选) if (reqVO.getBusinessId() != null) { businessService.validateBusiness(reqVO.getBusinessId()); } // 3. 校验联系人(可选) if (reqVO.getContactId() != null) { contactService.validateContact(reqVO.getContactId()); } } private void updateQuotationProductList(Long id, List newList) { // 第一步,对比新老数据,获得添加、修改、删除的列表 List oldList = saleQuotationProductMapper.selectListByQuotationId(id); List> diffList = diffList(oldList, newList, (oldVal, newVal) -> oldVal.getId().equals(newVal.getId())); // 第二步,批量添加、修改、删除 if (CollUtil.isNotEmpty(diffList.get(0))) { diffList.get(0).forEach(o -> o.setQuotationId(id)); saleQuotationProductMapper.insertBatch(diffList.get(0)); } if (CollUtil.isNotEmpty(diffList.get(1))) { saleQuotationProductMapper.updateBatch(diffList.get(1)); } if (CollUtil.isNotEmpty(diffList.get(2))) { saleQuotationProductMapper.deleteByIds(convertList(diffList.get(2), CrmSaleQuotationProductDO::getId)); } } private void calculateTotalPrice(CrmSaleQuotationDO saleQuotation, List items) { saleQuotation.setTotalProductPrice(getSumValue(items, CrmSaleQuotationProductDO::getTotalPrice, BigDecimal::add, BigDecimal.ZERO)); BigDecimal totalTaxPrice = getSumValue(items, CrmSaleQuotationProductDO::getTaxPrice, BigDecimal::add, BigDecimal.ZERO); saleQuotation.setTaxPrice(totalTaxPrice); // 计算优惠价格 if (saleQuotation.getDiscountPercent() == null) { saleQuotation.setDiscountPercent(BigDecimal.ZERO); } BigDecimal basePrice = saleQuotation.getTotalProductPrice().add(totalTaxPrice); saleQuotation.setDiscountPrice(MoneyUtils.priceMultiplyPercent(basePrice, saleQuotation.getDiscountPercent())); saleQuotation.setTotalPrice(basePrice.subtract(saleQuotation.getDiscountPrice())); } @Override public CrmSaleQuotationDO getSaleQuotation(Long id) { return saleQuotationMapper.selectById(id); } @Override public PageResult getSaleQuotationPage(CrmSaleQuotationPageReqVO pageReqVO, Long userId) { return saleQuotationMapper.selectPage(pageReqVO, userId); } @Override public PageResult getSaleQuotationPageByCustomerId(CrmSaleQuotationPageReqVO pageReqVO) { return saleQuotationMapper.selectPageByCustomerId(pageReqVO); } @Override public PageResult getSaleQuotationPageByBusinessId(CrmSaleQuotationPageReqVO pageReqVO) { return saleQuotationMapper.selectPageByBusinessId(pageReqVO); } @Override public List getSaleQuotationProductListByQuotationId(Long quotationId) { return saleQuotationProductMapper.selectListByQuotationId(quotationId); } @Override public List getSaleQuotationProductListByQuotationIds(Collection quotationIds) { if (CollUtil.isEmpty(quotationIds)) { return Collections.emptyList(); } return saleQuotationProductMapper.selectListByQuotationIds(quotationIds); } @Override @Transactional(rollbackFor = Exception.class) public void submitSaleQuotation(Long id, String processDefinitionKey, Long userId) { // 1. 校验报价单存在且为草稿状态 CrmSaleQuotationDO saleQuotation = validateSaleQuotationExists(id); if (!CrmSaleQuotationStatusEnum.DRAFT.getStatus().equals(saleQuotation.getStatus())) { throw exception(SALE_QUOTATION_SUBMIT_FAIL_NOT_DRAFT); } // 2. 校验分类和流程定义是否存在 validateSaleQuotationApproveCategoryAndProcessDefinition(); // 3. 校验传入的流程定义 Key 是否属于该分类且处于激活状态 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())); } /** * 校验 BPM 销售报价审批分类和流程定义是否存在 */ private void validateSaleQuotationApproveCategoryAndProcessDefinition() { // 1. 校验分类是否存在 List codes = Collections.singletonList(SALE_QUOTATION_APPROVE_CATEGORY_CODE); Map categoryMap = bpmCategoryService.getCategoryMap(codes); if (!categoryMap.containsKey(SALE_QUOTATION_APPROVE_CATEGORY_CODE)) { throw exception(SALE_QUOTATION_BPM_CATEGORY_NOT_EXISTS); } // 2. 校验分类下是否有可用的流程定义 List definitionInfoList = bpmProcessDefinitionService .getProcessDefinitionInfoListByCategory(SALE_QUOTATION_APPROVE_CATEGORY_CODE); if (CollUtil.isEmpty(definitionInfoList)) { throw exception(SALE_QUOTATION_BPM_PROCESS_DEFINITION_NOT_EXISTS); } // 3. 校验是否有激活状态的流程定义 Set processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId); List processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds); boolean hasActiveDefinition = processDefinitions.stream() .anyMatch(pd -> !pd.isSuspended()); if (!hasActiveDefinition) { throw exception(SALE_QUOTATION_BPM_PROCESS_DEFINITION_NOT_EXISTS); } } @Override public void updateSaleQuotationAuditStatus(Long id, Integer bpmResult) { // 1. 校验报价单存在且为审批中状态 CrmSaleQuotationDO saleQuotation = validateSaleQuotationExists(id); if (!CrmSaleQuotationStatusEnum.PROCESS.getStatus().equals(saleQuotation.getStatus())) { log.error("[updateSaleQuotationAuditStatus] 报价单({}) 不处于审批中", id); throw exception(SALE_QUOTATION_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS); } // 2. 转换审批结果 Integer auditStatus = convertBpmResultToAuditStatus(bpmResult); saleQuotationMapper.updateById(new CrmSaleQuotationDO() .setId(id) .setStatus(auditStatus)); } /** * BPM 审批结果转换 */ private Integer convertBpmResultToAuditStatus(Integer bpmResult) { Integer auditStatus = BpmTaskStatusEnum.APPROVE.getStatus().equals(bpmResult) ? CrmSaleQuotationStatusEnum.APPROVE.getStatus() : BpmTaskStatusEnum.REJECT.getStatus().equals(bpmResult) ? CrmSaleQuotationStatusEnum.REJECT.getStatus() : BpmTaskStatusEnum.CANCEL.getStatus().equals(bpmResult) ? CrmSaleQuotationStatusEnum.CANCEL.getStatus() : null; Assert.notNull(auditStatus, "BPM 审批结果({}) 转换失败", bpmResult); return auditStatus; } @Override public List> getSaleQuotationApproveProcessDefinitionList() { // 1. 校验分类和流程定义是否存在 validateSaleQuotationApproveCategoryAndProcessDefinition(); // 2. 获取分类下的流程定义信息 List definitionInfoList = bpmProcessDefinitionService .getProcessDefinitionInfoListByCategory(SALE_QUOTATION_APPROVE_CATEGORY_CODE); // 3. 获取流程定义详情 Set processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId); List processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds); // 4. 过滤:只保留激活状态,且相同 key 只保留最新版本 Map 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); } } // 5. 返回流程定义列表 List> result = new ArrayList<>(); for (ProcessDefinition pd : latestVersionMap.values()) { Map 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; } @Override @Transactional(rollbackFor = Exception.class) public Long convertToContract(Long id, Long userId) { // 1. 校验报价单存在且已审批通过 CrmSaleQuotationDO saleQuotation = validateSaleQuotationExists(id); if (!CrmSaleQuotationStatusEnum.APPROVE.getStatus().equals(saleQuotation.getStatus())) { throw exception(SALE_QUOTATION_NOT_APPROVE); } // 校验是否已转合同 if (saleQuotation.getContractId() != null) { throw exception(SALE_QUOTATION_CONTRACT_EXISTS); } // 2. 获取报价明细 List quotationProducts = saleQuotationProductMapper.selectListByQuotationId(id); // 3. 构建合同创建 VO CrmContractSaveReqVO contractVO = new CrmContractSaveReqVO(); contractVO.setName(saleQuotation.getName() + "-合同"); contractVO.setCustomerId(saleQuotation.getCustomerId()); contractVO.setBusinessId(saleQuotation.getBusinessId()); contractVO.setOwnerUserId(saleQuotation.getOwnerUserId()); contractVO.setOrderDate(saleQuotation.getQuotationTime()); contractVO.setDiscountPercent(saleQuotation.getDiscountPercent()); contractVO.setRemark("由报价单[" + saleQuotation.getNo() + "]生成"); // 转换明细项:报价单物料 -> 合同产品 List contractProducts = convertList(quotationProducts, qp -> { CrmContractSaveReqVO.Product product = new CrmContractSaveReqVO.Product(); product.setItemId(qp.getItemId()); product.setItemPrice(qp.getItemPrice()); product.setContractPrice(qp.getQuotationPrice()); product.setCount(qp.getCount().intValue()); return product; }); contractVO.setProducts(contractProducts); // 4. 创建合同 Long contractId = contractService.createContract(contractVO, userId); // 5. 更新报价单关联信息 CrmContractDO contract = contractService.getContract(contractId); saleQuotationMapper.updateById(new CrmSaleQuotationDO() .setId(id) .setContractId(contractId) .setContractNo(contract.getNo()) .setStatus(CrmSaleQuotationStatusEnum.CONVERTED.getStatus())); return contractId; } }