| | |
| | | package cn.iocoder.yudao.module.crm.service.contract; |
| | | |
| | | import cn.hutool.core.collection.CollUtil; |
| | | import cn.hutool.core.util.StrUtil; |
| | | import cn.hutool.core.collection.ListUtil; |
| | | import cn.hutool.core.lang.Assert; |
| | | import cn.hutool.core.util.ObjUtil; |
| | | import cn.iocoder.yudao.framework.common.pojo.CommonResult; |
| | | 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.framework.common.util.object.ObjectUtils; |
| | | 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.controller.admin.contract.vo.contract.CrmContractPageReqVO; |
| | | import cn.iocoder.yudao.module.crm.controller.admin.contract.vo.contract.CrmContractSaveReqVO; |
| | | import cn.iocoder.yudao.module.crm.controller.admin.contract.vo.contract.CrmContractImportExcelVO; |
| | | import cn.iocoder.yudao.module.crm.controller.admin.contract.vo.contract.CrmContractImportRespVO; |
| | | import cn.iocoder.yudao.module.crm.controller.admin.contract.vo.contract.CrmContractTransferReqVO; |
| | | import cn.iocoder.yudao.module.crm.dal.dataobject.contract.CrmContractConfigDO; |
| | | import cn.iocoder.yudao.module.crm.dal.dataobject.contract.CrmContractDO; |
| | | import cn.iocoder.yudao.module.crm.dal.dataobject.contract.CrmContractProductDO; |
| | | 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.dataobject.customer.CrmCustomerDO; |
| | | import cn.iocoder.yudao.module.crm.dal.mysql.contract.CrmContractMapper; |
| | | import cn.iocoder.yudao.module.crm.dal.mysql.customer.CrmCustomerMapper; |
| | | import cn.iocoder.yudao.module.crm.dal.mysql.contract.CrmContractProductMapper; |
| | | import cn.iocoder.yudao.module.crm.dal.redis.no.CrmNoRedisDAO; |
| | | import cn.iocoder.yudao.module.crm.enums.common.CrmAuditStatusEnum; |
| | |
| | | import cn.iocoder.yudao.module.crm.framework.permission.core.annotations.CrmPermission; |
| | | import cn.iocoder.yudao.module.crm.service.business.CrmBusinessService; |
| | | import cn.iocoder.yudao.module.crm.service.contact.CrmContactService; |
| | | import cn.iocoder.yudao.module.crm.api.customer.CrmCustomerApi; |
| | | 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.crm.service.permission.bo.CrmPermissionTransferReqBO; |
| | | import cn.iocoder.yudao.module.crm.service.product.CrmProductService; |
| | | import cn.iocoder.yudao.module.crm.service.quotation.CrmSaleQuotationService; |
| | | import cn.iocoder.yudao.module.crm.service.receivable.CrmReceivableService; |
| | | import cn.iocoder.yudao.module.erp.api.sale.ErpSaleOrderApi; |
| | | import cn.iocoder.yudao.module.erp.api.sale.dto.ErpSaleOrderCreateReqDTO; |
| | | import cn.iocoder.yudao.module.erp.api.sale.dto.ErpSaleOrderRespDTO; |
| | | import cn.iocoder.yudao.module.mdm.api.item.MdmItemApi; |
| | | import cn.iocoder.yudao.module.mdm.api.item.dto.MdmItemRespDTO; |
| | | import cn.iocoder.yudao.module.system.api.user.AdminUserApi; |
| | | import com.mzt.logapi.context.LogRecordContext; |
| | | import com.mzt.logapi.service.impl.DiffParseFunction; |
| | |
| | | |
| | | import java.math.BigDecimal; |
| | | import java.time.LocalDateTime; |
| | | import java.util.ArrayList; |
| | | import java.util.Collection; |
| | | import java.util.Collections; |
| | | import java.util.HashMap; |
| | | import java.util.LinkedHashMap; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.Set; |
| | | import java.time.format.DateTimeFormatter; |
| | | |
| | | import org.flowable.engine.repository.ProcessDefinition; |
| | | |
| | | 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.*; |
| | | import static cn.iocoder.yudao.module.crm.enums.LogRecordConstants.*; |
| | | import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; |
| | | import static cn.iocoder.yudao.module.crm.util.CrmAuditStatusUtils.convertBpmResultToAuditStatus; |
| | | |
| | | /** |
| | |
| | | */ |
| | | public static final String BPM_PROCESS_DEFINITION_KEY = "crm-contract-audit"; |
| | | |
| | | /** |
| | | * BPM 合同审批分类编码 |
| | | */ |
| | | private static final String CONTRACT_APPROVE_CATEGORY_CODE = "contract_approve"; |
| | | |
| | | @Resource |
| | | private CrmContractMapper contractMapper; |
| | | @Resource |
| | |
| | | |
| | | @Resource |
| | | private CrmNoRedisDAO noRedisDAO; |
| | | @Resource |
| | | private CrmCustomerMapper customerMapper; |
| | | |
| | | @Resource |
| | | private CrmPermissionService crmPermissionService; |
| | | @Resource |
| | | private CrmProductService productService; |
| | | @Resource |
| | | private CrmCustomerService customerService; |
| | | @Resource |
| | | private CrmCustomerApi customerApi; |
| | | @Resource |
| | | private CrmBusinessService businessService; |
| | | @Resource |
| | |
| | | private AdminUserApi adminUserApi; |
| | | @Resource |
| | | private BpmProcessInstanceApi bpmProcessInstanceApi; |
| | | @Resource |
| | | private BpmCategoryService bpmCategoryService; |
| | | @Resource |
| | | private BpmProcessDefinitionService bpmProcessDefinitionService; |
| | | @Resource |
| | | private ErpSaleOrderApi saleOrderApi; |
| | | @Resource |
| | | private MdmItemApi mdmItemApi; |
| | | @Resource |
| | | @Lazy // 延迟加载,避免循环依赖(quotation 内部引用了 contractService) |
| | | private CrmSaleQuotationService crmSaleQuotationService; |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | |
| | | } |
| | | |
| | | // 2.1 插入合同 |
| | | CrmContractDO contract = BeanUtils.toBean(createReqVO, CrmContractDO.class).setNo(no); |
| | | CrmContractDO contract = BeanUtils.toBean(createReqVO, CrmContractDO.class) |
| | | .setNo(no) |
| | | .setAuditStatus(CrmAuditStatusEnum.DRAFT.getStatus()); // 默认为未提交状态 |
| | | calculateTotalPrice(contract, contractProducts); |
| | | contractMapper.insert(contract); |
| | | // 2.2 插入合同关联商品 |
| | |
| | | } |
| | | |
| | | private List<CrmContractProductDO> validateContractProducts(List<CrmContractSaveReqVO.Product> list) { |
| | | // 1. 校验产品存在 |
| | | productService.validProductList(convertSet(list, CrmContractSaveReqVO.Product::getProductId)); |
| | | // 1. 校验物料存在且启用 |
| | | Set<Long> itemIds = convertSet(list, CrmContractSaveReqVO.Product::getItemId); |
| | | Map<Long, MdmItemRespDTO> itemMap = mdmItemApi.getItemMap(itemIds); |
| | | // 2. 转化为 CrmContractProductDO 列表 |
| | | return convertList(list, o -> BeanUtils.toBean(o, CrmContractProductDO.class, |
| | | item -> item.setTotalPrice(MoneyUtils.priceMultiply(item.getContractPrice(), item.getCount())))); |
| | | return convertList(list, o -> BeanUtils.toBean(o, CrmContractProductDO.class, item -> { |
| | | MdmItemRespDTO mdmItem = itemMap.get(item.getItemId()); |
| | | if (mdmItem == null) { |
| | | throw exception(PRODUCT_NOT_EXISTS); |
| | | } |
| | | item.setItemUnitId(mdmItem.getUnitMeasureId()); |
| | | item.setItemPrice(mdmItem.getSalesPrice()); |
| | | item.setTotalPrice(MoneyUtils.priceMultiply(item.getContractPrice(), item.getCount())); |
| | | })); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public CrmContractImportRespVO importContractList(List<CrmContractImportExcelVO> importList) { |
| | | CrmContractImportRespVO respVO = CrmContractImportRespVO.builder() |
| | | .createList(new ArrayList<>()) |
| | | .updateList(new ArrayList<>()) |
| | | .failureList(new LinkedHashMap<>()) |
| | | .build(); |
| | | if (CollUtil.isEmpty(importList)) { |
| | | return respVO; |
| | | } |
| | | |
| | | // 1. 预热“客户名称 -> 客户编号”映射 |
| | | Map<String, Long> customerIdMap = new HashMap<>(); |
| | | List<CrmCustomerDO> customers = customerMapper.selectList(); |
| | | if (CollUtil.isNotEmpty(customers)) { |
| | | customers.forEach(customer -> { |
| | | if (StrUtil.isNotBlank(customer.getName())) { |
| | | customerIdMap.putIfAbsent(customer.getName().trim(), customer.getId()); |
| | | } |
| | | }); |
| | | } |
| | | |
| | | // 2. 按“合同编号”分组 |
| | | Map<String, List<CrmContractImportExcelVO>> groups = new LinkedHashMap<>(); |
| | | for (int i = 0; i < importList.size(); i++) { |
| | | CrmContractImportExcelVO row = importList.get(i); |
| | | if (row == null || (StrUtil.isBlank(row.getName()) && StrUtil.isBlank(row.getCustomerName()) |
| | | && StrUtil.isBlank(row.getNo()))) { |
| | | continue; // 跳过空行 |
| | | } |
| | | String key = StrUtil.isNotBlank(row.getNo()) ? row.getNo().trim() : "__row_" + (i + 2); |
| | | groups.computeIfAbsent(key, k -> new ArrayList<>()).add(row); |
| | | } |
| | | |
| | | // 3. 逐张合同导入 |
| | | for (Map.Entry<String, List<CrmContractImportExcelVO>> entry : groups.entrySet()) { |
| | | List<CrmContractImportExcelVO> rows = entry.getValue(); |
| | | String label = StrUtil.isNotBlank(rows.get(0).getNo()) ? rows.get(0).getNo().trim() |
| | | : "第 " + entry.getKey().substring("__row_".length()) + " 行"; |
| | | try { |
| | | CrmContractDO contract = createContractByImport(rows, customerIdMap); |
| | | respVO.getCreateList().add(contract.getNo()); |
| | | } catch (Exception ex) { |
| | | respVO.getFailureList().put(label, resolveImportErrorMessage(ex)); |
| | | } |
| | | } |
| | | return respVO; |
| | | } |
| | | |
| | | /** |
| | | * 依据导入数据创建一张合同(含明细)。负责人=当前登录用户;状态=未提交;金额按明细与优惠率自动计算。 |
| | | */ |
| | | private CrmContractDO createContractByImport(List<CrmContractImportExcelVO> rows, Map<String, Long> customerIdMap) { |
| | | CrmContractImportExcelVO head = rows.get(0); |
| | | // 1. 主表必填 |
| | | if (StrUtil.isBlank(head.getName())) { |
| | | throw new IllegalArgumentException("合同名称不能为空"); |
| | | } |
| | | if (StrUtil.isBlank(head.getCustomerName())) { |
| | | throw new IllegalArgumentException("客户名称不能为空"); |
| | | } |
| | | Long customerId = customerIdMap.get(head.getCustomerName().trim()); |
| | | if (customerId == null) { |
| | | throw new IllegalArgumentException("客户不存在:" + head.getCustomerName()); |
| | | } |
| | | customerService.validateCustomer(customerId); |
| | | |
| | | // 2. 明细 |
| | | List<CrmContractSaveReqVO.Product> products = new ArrayList<>(); |
| | | for (CrmContractImportExcelVO row : rows) { |
| | | if (StrUtil.isBlank(row.getProductCode())) { |
| | | throw new IllegalArgumentException("产品编码不能为空"); |
| | | } |
| | | CommonResult<MdmItemRespDTO> itemResult = mdmItemApi.getItemByCode(row.getProductCode().trim()); |
| | | MdmItemRespDTO item = itemResult == null ? null : itemResult.getData(); |
| | | if (item == null) { |
| | | throw new IllegalArgumentException("产品不存在:" + row.getProductCode()); |
| | | } |
| | | if (row.getCount() == null || row.getCount() <= 0) { |
| | | throw new IllegalArgumentException("产品[" + row.getProductCode() + "]的数量必须为正整数"); |
| | | } |
| | | BigDecimal contractPrice = row.getContractPrice() != null ? row.getContractPrice() |
| | | : (item.getSalesPrice() != null ? item.getSalesPrice() : BigDecimal.ZERO); |
| | | CrmContractSaveReqVO.Product product = new CrmContractSaveReqVO.Product(); |
| | | product.setItemId(item.getId()); |
| | | product.setItemPrice(item.getSalesPrice() != null ? item.getSalesPrice() : contractPrice); |
| | | product.setContractPrice(contractPrice); |
| | | product.setCount(row.getCount()); |
| | | products.add(product); |
| | | } |
| | | |
| | | // 3. 合同编号 |
| | | String no = StrUtil.isNotBlank(head.getNo()) ? head.getNo().trim() |
| | | : noRedisDAO.generate(CrmNoRedisDAO.CONTRACT_NO_PREFIX); |
| | | if (contractMapper.selectByNo(no) != null) { |
| | | throw new IllegalArgumentException("合同编号已存在:" + no); |
| | | } |
| | | |
| | | // 4. 组装主表(负责人=登录用户;状态=未提交) |
| | | CrmContractDO contract = new CrmContractDO(); |
| | | contract.setNo(no); |
| | | contract.setName(head.getName().trim()); |
| | | contract.setCustomerId(customerId); |
| | | contract.setOwnerUserId(getLoginUserId()); |
| | | contract.setOrderDate(parseImportDateTime(head.getOrderDate())); |
| | | contract.setStartTime(parseImportDate(head.getStartTime())); |
| | | contract.setEndTime(parseImportDate(head.getEndTime())); |
| | | contract.setDiscountPercent(head.getDiscountPercent() != null ? head.getDiscountPercent() : BigDecimal.ZERO); |
| | | contract.setDepositPrice(head.getDepositPrice() != null ? head.getDepositPrice() : BigDecimal.ZERO); |
| | | contract.setRemark(head.getRemark()); |
| | | contract.setAuditStatus(CrmAuditStatusEnum.DRAFT.getStatus()); |
| | | |
| | | // 5. 明细落库 + 自动算价 |
| | | List<CrmContractProductDO> productDOs = validateContractProducts(products); |
| | | calculateTotalPrice(contract, productDOs); |
| | | contractMapper.insert(contract); |
| | | productDOs.forEach(product -> product.setContractId(contract.getId())); |
| | | contractProductMapper.insertBatch(productDOs); |
| | | |
| | | // 6. 创建数据权限(否则当前用户看不到该合同) |
| | | crmPermissionService.createPermission(new CrmPermissionCreateReqBO().setUserId(contract.getOwnerUserId()) |
| | | .setBizType(CrmBizTypeEnum.CRM_CONTRACT.getType()).setBizId(contract.getId()) |
| | | .setLevel(CrmPermissionLevelEnum.OWNER.getLevel())); |
| | | return contract; |
| | | } |
| | | |
| | | private LocalDateTime parseImportDateTime(String text) { |
| | | if (StrUtil.isBlank(text)) { |
| | | return LocalDateTime.now(); |
| | | } |
| | | String value = text.trim(); |
| | | for (String pattern : new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd HH:mm:ss"}) { |
| | | try { |
| | | return LocalDateTime.parse(value, DateTimeFormatter.ofPattern(pattern)); |
| | | } catch (Exception ignored) { |
| | | // 继续尝试下一个格式 |
| | | } |
| | | } |
| | | for (String pattern : new String[]{"yyyy-MM-dd", "yyyy/M/d"}) { |
| | | try { |
| | | return java.time.LocalDate.parse(value, DateTimeFormatter.ofPattern(pattern)).atStartOfDay(); |
| | | } catch (Exception ignored) { |
| | | // 继续尝试下一个格式 |
| | | } |
| | | } |
| | | throw new IllegalArgumentException("下单时间格式不正确:" + text + ",示例 2026-01-01 10:00:00"); |
| | | } |
| | | |
| | | private LocalDateTime parseImportDate(String text) { |
| | | if (StrUtil.isBlank(text)) { |
| | | return null; |
| | | } |
| | | String value = text.trim(); |
| | | for (String pattern : new String[]{"yyyy-MM-dd", "yyyy/M/d"}) { |
| | | try { |
| | | return java.time.LocalDate.parse(value, DateTimeFormatter.ofPattern(pattern)).atStartOfDay(); |
| | | } catch (Exception ignored) { |
| | | // 继续尝试下一个格式 |
| | | } |
| | | } |
| | | try { |
| | | return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); |
| | | } catch (Exception ignored) { |
| | | // 忽略 |
| | | } |
| | | throw new IllegalArgumentException("日期格式不正确:" + text + ",示例 2026-01-01"); |
| | | } |
| | | |
| | | private String resolveImportErrorMessage(Exception ex) { |
| | | if (ex instanceof cn.iocoder.yudao.framework.common.exception.ServiceException serviceException) { |
| | | return serviceException.getMessage(); |
| | | } |
| | | return StrUtil.blankToDefault(ex.getMessage(), "导入失败"); |
| | | } |
| | | |
| | | private void calculateTotalPrice(CrmContractDO contract, List<CrmContractProductDO> contractProducts) { |
| | |
| | | |
| | | // 2.1 删除合同 |
| | | contractMapper.deleteById(id); |
| | | // 2.2 删除合同时,解除关联的报价单引用 |
| | | CrmSaleQuotationDO quotation = crmSaleQuotationService.getByContractId(id); |
| | | if (quotation != null) { |
| | | crmSaleQuotationService.clearContractReference(quotation.getId()); |
| | | } |
| | | // 2.2 删除数据权限 |
| | | crmPermissionService.deletePermission(CrmBizTypeEnum.CRM_CONTRACT.getType(), id); |
| | | |
| | |
| | | @Transactional(rollbackFor = Exception.class) |
| | | @LogRecord(type = CRM_CONTRACT_TYPE, subType = CRM_CONTRACT_SUBMIT_SUB_TYPE, bizNo = "{{#id}}", |
| | | success = CRM_CONTRACT_SUBMIT_SUCCESS) |
| | | public void submitContract(Long id, Long userId) { |
| | | public void submitContract(Long id, String processDefinitionKey, Long userId) { |
| | | // 1. 校验合同是否在审批 |
| | | CrmContractDO contract = validateContractExists(id); |
| | | if (ObjUtil.notEqual(contract.getAuditStatus(), CrmAuditStatusEnum.DRAFT.getStatus())) { |
| | | throw exception(CONTRACT_SUBMIT_FAIL_NOT_DRAFT); |
| | | } |
| | | |
| | | // 2. 创建合同审批流程实例 |
| | | String processInstanceId = bpmProcessInstanceApi.createProcessInstance(userId, new BpmProcessInstanceCreateReqDTO() |
| | | .setProcessDefinitionKey(BPM_PROCESS_DEFINITION_KEY).setBusinessKey(String.valueOf(id))); |
| | | // 2. 校验分类和流程定义是否存在 |
| | | validateContractApproveCategoryAndProcessDefinition(); |
| | | |
| | | // 3. 更新合同工作流编号 |
| | | // 3. 校验传入的流程定义 Key 是否属于该分类且处于激活状态 |
| | | ProcessDefinition processDefinition = bpmProcessDefinitionService.getActiveProcessDefinition(processDefinitionKey); |
| | | if (processDefinition == null) { |
| | | throw exception(CONTRACT_BPM_PROCESS_DEFINITION_NOT_EXISTS); |
| | | } |
| | | |
| | | // 4. 创建合同审批流程实例 |
| | | String processInstanceId = bpmProcessInstanceApi.createProcessInstance(userId, new BpmProcessInstanceCreateReqDTO() |
| | | .setProcessDefinitionKey(processDefinitionKey).setBusinessKey(String.valueOf(id))); |
| | | |
| | | // 5. 更新合同工作流编号 |
| | | contractMapper.updateById(new CrmContractDO().setId(id).setProcessInstanceId(processInstanceId) |
| | | .setAuditStatus(CrmAuditStatusEnum.PROCESS.getStatus())); |
| | | |
| | | // 3. 记录日志 |
| | | // 6. 记录日志 |
| | | LogRecordContext.putVariable("contractName", contract.getName()); |
| | | } |
| | | |
| | | /** |
| | | * 校验 BPM 合同审批分类和流程定义是否存在 |
| | | */ |
| | | private void validateContractApproveCategoryAndProcessDefinition() { |
| | | // 1. 校验分类是否存在 |
| | | List<String> codes = Collections.singletonList(CONTRACT_APPROVE_CATEGORY_CODE); |
| | | Map<String, ?> categoryMap = bpmCategoryService.getCategoryMap(codes); |
| | | if (!categoryMap.containsKey(CONTRACT_APPROVE_CATEGORY_CODE)) { |
| | | throw exception(CONTRACT_BPM_PROCESS_DEFINITION_NOT_EXISTS); |
| | | } |
| | | |
| | | // 2. 校验分类下是否有可用的流程定义 |
| | | List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService |
| | | .getProcessDefinitionInfoListByCategory(CONTRACT_APPROVE_CATEGORY_CODE); |
| | | if (CollUtil.isEmpty(definitionInfoList)) { |
| | | throw exception(CONTRACT_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(CONTRACT_BPM_PROCESS_DEFINITION_NOT_EXISTS); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public List<Map<String, Object>> getContractApproveProcessDefinitionList() { |
| | | // 1. 校验分类和流程定义是否存在 |
| | | validateContractApproveCategoryAndProcessDefinition(); |
| | | |
| | | // 2. 获取分类下的流程定义信息 |
| | | List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService |
| | | .getProcessDefinitionInfoListByCategory(CONTRACT_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); |
| | | } |
| | | } |
| | | |
| | | // 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; |
| | | } |
| | | |
| | | @Override |
| | |
| | | return PageResult.empty(); |
| | | } |
| | | } |
| | | // 2. 查询分页 |
| | | return contractMapper.selectPage(pageReqVO, userId, config); |
| | | // 2. 获取用户有权限的客户 ID 列表 |
| | | List<Long> permittedCustomerIds = customerApi.getPermittedCustomerIds(); |
| | | // 3. 查询分页 |
| | | return contractMapper.selectPage(pageReqVO, userId, config, permittedCustomerIds); |
| | | } |
| | | |
| | | @Override |
| | |
| | | return contractMapper.selectListByCustomerIdOwnerUserId(customerId, ownerUserId); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | @LogRecord(type = CRM_CONTRACT_TYPE, subType = "生成销售订单", bizNo = "{{#id}}", |
| | | success = "合同【{{#contractName}}】生成销售订单【{{#orderNo}}】成功") |
| | | @CrmPermission(bizType = CrmBizTypeEnum.CRM_CONTRACT, bizId = "#id", level = CrmPermissionLevelEnum.WRITE) |
| | | public Long generateSaleOrder(Long id, Long userId) { |
| | | // 1. 校验合同存在且已审批通过 |
| | | CrmContractDO contract = validateContractExists(id); |
| | | if (!CrmAuditStatusEnum.APPROVE.getStatus().equals(contract.getAuditStatus())) { |
| | | throw exception(CONTRACT_GENERATE_ORDER_FAIL_NOT_APPROVE); |
| | | } |
| | | // 2. 校验是否已生成销售订单 |
| | | ErpSaleOrderRespDTO existOrder = saleOrderApi.getSaleOrderByContractId(id).getCheckedData(); |
| | | if (existOrder != null) { |
| | | throw exception(CONTRACT_GENERATE_ORDER_FAIL_EXISTS_ORDER, existOrder.getNo()); |
| | | } |
| | | |
| | | // 3. 获取合同产品列表 |
| | | List<CrmContractProductDO> contractProducts = contractProductMapper.selectListByContractId(id); |
| | | if (CollUtil.isEmpty(contractProducts)) { |
| | | throw exception(CONTRACT_GENERATE_ORDER_FAIL_NO_PRODUCT); |
| | | } |
| | | |
| | | // 4. 构建销售订单创建请求 |
| | | ErpSaleOrderCreateReqDTO createReqDTO = new ErpSaleOrderCreateReqDTO(); |
| | | createReqDTO.setCustomerId(contract.getCustomerId()); |
| | | createReqDTO.setContractId(contract.getId()); |
| | | createReqDTO.setContractNo(contract.getNo()); |
| | | createReqDTO.setSaleUserId(contract.getOwnerUserId()); |
| | | createReqDTO.setOrderTime(LocalDateTime.now().toString()); |
| | | createReqDTO.setDiscountPercent(contract.getDiscountPercent() != null ? contract.getDiscountPercent() : BigDecimal.ZERO); |
| | | createReqDTO.setDepositPrice(contract.getDepositPrice() != null ? contract.getDepositPrice() : BigDecimal.ZERO); |
| | | createReqDTO.setRemark("由合同【" + contract.getNo() + "】自动生成"); |
| | | |
| | | // 5. 构建订单项 |
| | | List<ErpSaleOrderCreateReqDTO.Item> items = contractProducts.stream() |
| | | .map(cp -> { |
| | | ErpSaleOrderCreateReqDTO.Item item = new ErpSaleOrderCreateReqDTO.Item(); |
| | | item.setProductId(cp.getItemId()); |
| | | item.setProductPrice(cp.getContractPrice()); |
| | | item.setCount(cp.getCount()); |
| | | return item; |
| | | }) |
| | | .toList(); |
| | | createReqDTO.setItems(items); |
| | | |
| | | // 6. 创建销售订单 |
| | | Long orderId = saleOrderApi.createSaleOrder(createReqDTO).getCheckedData(); |
| | | ErpSaleOrderRespDTO order = saleOrderApi.getSaleOrder(orderId).getCheckedData(); |
| | | |
| | | // 7. 更新合同关联订单信息 |
| | | contractMapper.updateById(new CrmContractDO() |
| | | .setId(id) |
| | | .setOrderId(orderId) |
| | | .setOrderNo(order.getNo())); |
| | | |
| | | // 8. 记录操作日志 |
| | | LogRecordContext.putVariable("contractName", contract.getName()); |
| | | LogRecordContext.putVariable("orderNo", order.getNo()); |
| | | |
| | | return orderId; |
| | | } |
| | | |
| | | @Override |
| | | public void updateContractStatus(Long id, Integer status) { |
| | | contractMapper.updateById(new CrmContractDO() |
| | | .setId(id) |
| | | .setAuditStatus(status)); |
| | | } |
| | | |
| | | @Override |
| | | public void updateContractStatusByOrderId(Long orderId, Integer status) { |
| | | CrmContractDO contract = contractMapper.selectByOrderId(orderId); |
| | | if (contract != null) { |
| | | contractMapper.updateById(new CrmContractDO() |
| | | .setId(contract.getId()) |
| | | .setAuditStatus(status)); |
| | | } |
| | | } |
| | | |
| | | } |