| | |
| | | package cn.iocoder.yudao.module.erp.service.sale; |
| | | |
| | | import cn.hutool.core.collection.CollUtil; |
| | | import cn.hutool.extra.spring.SpringUtil; |
| | | import cn.hutool.core.util.ObjectUtil; |
| | | import cn.hutool.core.util.StrUtil; |
| | | import cn.iocoder.yudao.framework.common.exception.ServiceException; |
| | | 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.crm.api.customer.CrmCustomerApi; |
| | | import cn.iocoder.yudao.module.crm.api.contract.CrmContractApi; |
| | | import cn.iocoder.yudao.module.crm.api.contract.dto.CrmContractForSaleDTO; |
| | | import cn.iocoder.yudao.module.crm.api.customer.dto.CrmCustomerRespDTO; |
| | | import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderImportExcelVO; |
| | | import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderImportReqVO; |
| | | import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderImportRespVO; |
| | | import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderPageReqVO; |
| | | import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderSaveReqVO; |
| | | import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO; |
| | | import cn.iocoder.yudao.module.erp.dal.dataobject.finance.ErpAccountDO; |
| | | import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleOrderDO; |
| | | import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleOrderItemDO; |
| | | import cn.iocoder.yudao.module.erp.dal.mysql.finance.ErpAccountMapper; |
| | | import cn.iocoder.yudao.module.erp.dal.mysql.sale.ErpSaleOrderItemMapper; |
| | | import cn.iocoder.yudao.module.erp.dal.mysql.sale.ErpSaleOrderMapper; |
| | | import cn.iocoder.yudao.module.erp.dal.redis.no.ErpNoRedisDAO; |
| | | import cn.iocoder.yudao.module.erp.enums.ErpAuditStatus; |
| | | import cn.iocoder.yudao.module.erp.enums.ErpSaleOrderProductionStatusEnum; |
| | | import cn.iocoder.yudao.module.erp.api.sale.enums.ErpSaleOrderOutStatusEnum; |
| | | import cn.iocoder.yudao.module.erp.service.finance.ErpAccountService; |
| | | import cn.iocoder.yudao.module.erp.service.product.ErpProductService; |
| | | import cn.iocoder.yudao.module.mdm.api.item.MdmItemApi; |
| | | import cn.iocoder.yudao.module.mdm.api.item.dto.MdmItemRespDTO; |
| | | import cn.iocoder.yudao.module.mdm.enums.MdmItemTypeEnum; |
| | | import cn.iocoder.yudao.module.mdm.api.unit.MdmUnitMeasureApi; |
| | | import cn.iocoder.yudao.module.mdm.api.unit.dto.MdmUnitMeasureRespDTO; |
| | | import cn.iocoder.yudao.module.mes.api.mps.MesProMpsApi; |
| | | import cn.iocoder.yudao.module.mes.api.mps.dto.MesProMpsCreateReqDTO; |
| | | import cn.iocoder.yudao.module.mes.api.mps.dto.MesProMpsRespDTO; |
| | | import cn.iocoder.yudao.module.system.api.storage.StorageAttachmentApi; |
| | | import cn.iocoder.yudao.module.system.api.user.AdminUserApi; |
| | | import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; |
| | | import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; |
| | | import jakarta.annotation.Resource; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.stereotype.Service; |
| | |
| | | import org.springframework.validation.annotation.Validated; |
| | | |
| | | import java.math.BigDecimal; |
| | | import java.time.LocalDateTime; |
| | | import java.time.format.DateTimeFormatter; |
| | | import java.util.ArrayList; |
| | | import java.util.Collection; |
| | | import java.util.Collections; |
| | | import java.util.LinkedHashMap; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | |
| | |
| | | /** |
| | | * ERP 销售订单 Service 实现类 |
| | | * |
| | | * @author 芋道源码 |
| | | * @author 超级管理员 |
| | | */ |
| | | @Service |
| | | @Validated |
| | | @Slf4j |
| | | public class ErpSaleOrderServiceImpl implements ErpSaleOrderService { |
| | | |
| | | /** |
| | | * BPM 销售订单审批流程标识 |
| | | */ |
| | | public static final String BPM_PROCESS_DEFINITION_KEY = "erp-sale-order-audit"; |
| | | private static final Integer MPS_STATUS_CANCELED = 3; |
| | | |
| | | @Resource |
| | | private ErpSaleOrderMapper saleOrderMapper; |
| | |
| | | private ErpNoRedisDAO noRedisDAO; |
| | | |
| | | @Resource |
| | | private ErpProductService productService; |
| | | private CrmCustomerApi customerApi; |
| | | @Resource |
| | | private ErpCustomerService customerService; |
| | | private CrmContractApi contractApi; |
| | | @Resource |
| | | private ErpAccountService accountService; |
| | | |
| | |
| | | private AdminUserApi adminUserApi; |
| | | |
| | | @Resource |
| | | private BpmProcessInstanceApi bpmProcessInstanceApi; |
| | | private MdmItemApi mdmItemApi; |
| | | @Resource |
| | | private MdmUnitMeasureApi mdmUnitMeasureApi; |
| | | @Resource |
| | | private ErpAccountMapper accountMapper; |
| | | @Resource |
| | | private MesProMpsApi mpsApi; |
| | | |
| | | @Resource |
| | | private StorageAttachmentApi storageAttachmentApi; |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public Long createSaleOrder(ErpSaleOrderSaveReqVO createReqVO) { |
| | | // 1.1 校验订单项的有效性 |
| | | List<ErpSaleOrderItemDO> saleOrderItems = validateSaleOrderItems(createReqVO.getItems()); |
| | | // 1.2 校验客户 |
| | | customerService.validateCustomer(createReqVO.getCustomerId()); |
| | | // 1.2 校验客户(使用 CRM 客户 API) |
| | | customerApi.validateCustomer(createReqVO.getCustomerId()); |
| | | // 1.3 校验结算账户 |
| | | if (createReqVO.getAccountId() != null) { |
| | | accountService.validateAccount(createReqVO.getAccountId()); |
| | |
| | | // 1.4 校验销售人员 |
| | | if (createReqVO.getSaleUserId() != null) { |
| | | adminUserApi.validateUser(createReqVO.getSaleUserId()); |
| | | } |
| | | if (createReqVO.getContractId() != null && saleOrderMapper.selectByContractId(createReqVO.getContractId()) != null) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "该合同已关联销售订单"); |
| | | } |
| | | // 1.5 生成订单号,并校验唯一性 |
| | | String no = noRedisDAO.generate(ErpNoRedisDAO.SALE_ORDER_NO_PREFIX); |
| | |
| | | |
| | | // 2.1 插入订单 |
| | | ErpSaleOrderDO saleOrder = BeanUtils.toBean(createReqVO, ErpSaleOrderDO.class, in -> in |
| | | .setNo(no).setStatus(ErpAuditStatus.DRAFT.getStatus())); |
| | | .setNo(no).setStatus(ErpAuditStatus.PROCESS.getStatus()) |
| | | .setDepositPrice(ObjectUtil.defaultIfNull(createReqVO.getDepositPrice(), BigDecimal.ZERO)) |
| | | .setOutCount(BigDecimal.ZERO).setOutStatus(ErpSaleOrderOutStatusEnum.NOT_OUT.getStatus())); |
| | | calculateTotalPrice(saleOrder, saleOrderItems); |
| | | saleOrderMapper.insert(saleOrder); |
| | | // 2.2 插入订单项 |
| | | saleOrderItems.forEach(o -> o.setOrderId(saleOrder.getId())); |
| | | saleOrderItemMapper.insertBatch(saleOrderItems); |
| | | // 2.3 绑定附件 |
| | | storageAttachmentApi.bindAttachments("file", "erp_sale_order", |
| | | saleOrder.getId(), createReqVO.getBlobIds()); |
| | | return saleOrder.getId(); |
| | | } |
| | | |
| | |
| | | public void updateSaleOrder(ErpSaleOrderSaveReqVO updateReqVO) { |
| | | // 1.1 校验存在 |
| | | ErpSaleOrderDO saleOrder = validateSaleOrderExists(updateReqVO.getId()); |
| | | if (ErpAuditStatus.APPROVE.getStatus().equals(saleOrder.getStatus())) { |
| | | if (!ErpAuditStatus.PROCESS.getStatus().equals(saleOrder.getStatus())) { |
| | | throw exception(SALE_ORDER_UPDATE_FAIL_APPROVE, saleOrder.getNo()); |
| | | } |
| | | // 1.2 校验客户 |
| | | customerService.validateCustomer(updateReqVO.getCustomerId()); |
| | | // 1.2 校验客户(使用 CRM 客户 API) |
| | | customerApi.validateCustomer(updateReqVO.getCustomerId()); |
| | | // 1.3 校验结算账户 |
| | | if (updateReqVO.getAccountId() != null) { |
| | | accountService.validateAccount(updateReqVO.getAccountId()); |
| | |
| | | |
| | | // 2.1 更新订单 |
| | | ErpSaleOrderDO updateObj = BeanUtils.toBean(updateReqVO, ErpSaleOrderDO.class); |
| | | updateObj.setDepositPrice(ObjectUtil.defaultIfNull(updateReqVO.getDepositPrice(), BigDecimal.ZERO)); |
| | | calculateTotalPrice(updateObj, saleOrderItems); |
| | | saleOrderMapper.updateById(updateObj); |
| | | // 2.2 更新订单项 |
| | | updateSaleOrderItemList(updateReqVO.getId(), saleOrderItems); |
| | | // 2.3 更新附件 |
| | | storageAttachmentApi.updateAttachments("file", "erp_sale_order", updateReqVO.getId(), updateReqVO.getBlobIds()); |
| | | } |
| | | |
| | | private void calculateTotalPrice(ErpSaleOrderDO saleOrder, List<ErpSaleOrderItemDO> saleOrderItems) { |
| | |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void updateSaleOrderStatus(Long id, Integer status) { |
| | | boolean approve = ErpAuditStatus.APPROVE.getStatus().equals(status); |
| | | // 1.1 校验存在 |
| | | ErpSaleOrderDO saleOrder = validateSaleOrderExists(id); |
| | | // 1.2 校验状态 |
| | | if (saleOrder.getStatus().equals(status)) { |
| | | ErpSaleOrderDO order = validateSaleOrderExists(id); |
| | | if (approve && !ErpAuditStatus.PROCESS.getStatus().equals(order.getStatus()) |
| | | || !approve && (!ErpAuditStatus.PROCESS.getStatus().equals(status) |
| | | || !ErpAuditStatus.APPROVE.getStatus().equals(order.getStatus()))) { |
| | | throw exception(approve ? SALE_ORDER_APPROVE_FAIL : SALE_ORDER_PROCESS_FAIL); |
| | | } |
| | | // 1.3 存在销售出库单,无法反审核 |
| | | if (!approve && saleOrder.getOutCount().compareTo(BigDecimal.ZERO) > 0) { |
| | | throw exception(SALE_ORDER_PROCESS_FAIL_EXISTS_OUT); |
| | | if (!approve) { |
| | | BigDecimal outCount = order.getOutCount() == null ? BigDecimal.ZERO : order.getOutCount(); |
| | | if (outCount.signum() > 0) throw exception(SALE_ORDER_PROCESS_FAIL_EXISTS_OUT); |
| | | validateNoActiveMps(id); |
| | | } |
| | | // 1.4 存在销售退货单,无法反审核 |
| | | if (!approve && saleOrder.getReturnCount().compareTo(BigDecimal.ZERO) > 0) { |
| | | throw exception(SALE_ORDER_PROCESS_FAIL_EXISTS_RETURN); |
| | | } |
| | | |
| | | // 2. 更新状态 |
| | | int updateCount = saleOrderMapper.updateByIdAndStatus(id, saleOrder.getStatus(), |
| | | new ErpSaleOrderDO().setStatus(status)); |
| | | if (updateCount == 0) { |
| | | if (saleOrderMapper.updateByIdAndStatus(id, order.getStatus(), new ErpSaleOrderDO().setStatus(status)) != 1) { |
| | | throw exception(approve ? SALE_ORDER_APPROVE_FAIL : SALE_ORDER_PROCESS_FAIL); |
| | | } |
| | | if (approve) createMpsForSaleOrder(id, order); |
| | | } |
| | | |
| | | /** |
| | | * 为销售订单中需要生产的明细创建 MPS |
| | | * |
| | | * @param orderId 销售订单编号 |
| | | * @param saleOrder 销售订单 |
| | | */ |
| | | private void createMpsForSaleOrder(Long orderId, ErpSaleOrderDO saleOrder) { |
| | | List<ErpSaleOrderItemDO> items = saleOrderItemMapper.selectListByOrderId(orderId); |
| | | if (CollUtil.isEmpty(items)) { |
| | | return; |
| | | } |
| | | |
| | | int createdCount = 0; |
| | | int reusedCount = 0; |
| | | int skippedCount = 0; |
| | | for (ErpSaleOrderItemDO item : items) { |
| | | if (item.getNeedProduction() == null || item.getNeedProduction() != 1) { |
| | | continue; |
| | | } |
| | | |
| | | MdmItemRespDTO mdmItem = mdmItemApi.getItem(item.getProductId()).getCheckedData(); |
| | | if (mdmItem == null || !MdmItemTypeEnum.isProduct(mdmItem.getItemType())) { |
| | | // 兼容修复前由合同生成的历史订单:当时所有明细都会被标记为需要生产。 |
| | | // 非产品明细不应创建 MPS,同时纠正标记,避免后续发货状态一直等待生产完成。 |
| | | saleOrderItemMapper.updateById(new ErpSaleOrderItemDO() |
| | | .setId(item.getId()) |
| | | .setNeedProduction(0)); |
| | | skippedCount++; |
| | | log.info("[createMpsForSaleOrder] 销售订单明细({}) 为非产品物料({}),跳过 MPS 并取消需要生产标记", |
| | | item.getId(), item.getProductId()); |
| | | continue; |
| | | } |
| | | |
| | | // 同一销售明细只保留一条有效 MPS,避免反审核后再次审核产生重复计划 |
| | | MesProMpsRespDTO existingMps = mpsApi.getMpsBySaleOrderItemId(item.getId()); |
| | | if (existingMps != null && ObjectUtil.notEqual(existingMps.getStatus(), MPS_STATUS_CANCELED)) { |
| | | if (ObjectUtil.notEqual(item.getMpsId(), existingMps.getId())) { |
| | | saleOrderItemMapper.updateById(new ErpSaleOrderItemDO() |
| | | .setId(item.getId()) |
| | | .setMpsId(existingMps.getId())); |
| | | } |
| | | reusedCount++; |
| | | log.info("[createMpsForSaleOrder] 销售订单明细({}) 已存在有效 MPS({}),跳过重复创建", |
| | | item.getId(), existingMps.getId()); |
| | | continue; |
| | | } |
| | | |
| | | // 与销售订单审核共用事务;任一明细创建失败都会回滚审核状态和本次已创建的 MPS |
| | | Long mpsId = createMpsForSaleOrderItem(saleOrder, item, mdmItem); |
| | | saleOrderItemMapper.updateById(new ErpSaleOrderItemDO() |
| | | .setId(item.getId()) |
| | | .setMpsId(mpsId)); |
| | | createdCount++; |
| | | } |
| | | // 重新生成生产计划后,订单生产状态回到未完成(覆盖此前的“已取消”) |
| | | if (createdCount > 0) { |
| | | saleOrderMapper.update(null, new LambdaUpdateWrapper<ErpSaleOrderDO>() |
| | | .eq(ErpSaleOrderDO::getId, orderId) |
| | | .set(ErpSaleOrderDO::getProductionStatus, ErpSaleOrderProductionStatusEnum.NOT_FINISHED.getStatus()) |
| | | .set(ErpSaleOrderDO::getProductionFinishTime, null)); |
| | | } |
| | | log.info("[createMpsForSaleOrder] 销售订单({}) 审核完成,创建 MPS {} 条,复用 MPS {} 条,跳过非产品 {} 条", |
| | | orderId, createdCount, reusedCount, skippedCount); |
| | | } |
| | | |
| | | /** |
| | | * 为销售订单明细创建 MPS |
| | | */ |
| | | private Long createMpsForSaleOrderItem(ErpSaleOrderDO saleOrder, ErpSaleOrderItemDO item, |
| | | MdmItemRespDTO mdmItem) { |
| | | MesProMpsCreateReqDTO createReqDTO = new MesProMpsCreateReqDTO(); |
| | | createReqDTO.setSaleOrderId(saleOrder.getId()); |
| | | createReqDTO.setSaleOrderNo(saleOrder.getNo()); |
| | | createReqDTO.setSaleOrderItemId(item.getId()); |
| | | createReqDTO.setMdmItemId(item.getProductId()); |
| | | createReqDTO.setProductName(mdmItem.getName()); |
| | | createReqDTO.setQuantity(item.getCount()); |
| | | createReqDTO.setClientId(saleOrder.getCustomerId()); |
| | | createReqDTO.setRequestDate(formatRequestDate(saleOrder.getOrderTime())); |
| | | createReqDTO.setRemark("自动生成,来自销售订单:" + saleOrder.getNo()); |
| | | |
| | | Long mpsId = mpsApi.createMps(createReqDTO); |
| | | log.info("[createMpsForSaleOrderItem] MPS 创建成功,mpsId={}, saleOrderItemId={}", mpsId, item.getId()); |
| | | return mpsId; |
| | | } |
| | | |
| | | /** |
| | | * 格式化需求日期 |
| | | */ |
| | | private String formatRequestDate(LocalDateTime dateTime) { |
| | | if (dateTime == null) { |
| | | return null; |
| | | } |
| | | return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void cancelSaleOrder(Long id) { |
| | | // 1.1 校验存在 |
| | | ErpSaleOrderDO saleOrder = validateSaleOrderExists(id); |
| | | // 1.2 校验状态:只有已审核的订单才能作废 |
| | | if (!ErpAuditStatus.APPROVE.getStatus().equals(saleOrder.getStatus())) { |
| | | throw exception(SALE_ORDER_CANCEL_FAIL_NOT_APPROVE, saleOrder.getNo()); |
| | | } |
| | | // 1.3 存在销售出库单,无法作废 |
| | | BigDecimal outCount = saleOrder.getOutCount() != null ? saleOrder.getOutCount() : BigDecimal.ZERO; |
| | | if (outCount.compareTo(BigDecimal.ZERO) > 0) { |
| | | throw exception(SALE_ORDER_CANCEL_FAIL_EXISTS_OUT); |
| | | } |
| | | |
| | | validateNoActiveMps(id); |
| | | |
| | | // 2. 更新状态为已作废 |
| | | int updateCount = saleOrderMapper.updateByIdAndStatus(id, saleOrder.getStatus(), |
| | | new ErpSaleOrderDO().setStatus(ErpAuditStatus.CANCEL.getStatus())); |
| | | if (updateCount == 0) { |
| | | throw exception(SALE_ORDER_CANCEL_FAIL); |
| | | } |
| | | |
| | | // 合同审批状态由合同及其 BPM 流程维护,订单作废不改变合同审批结果。 |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void enableSaleOrder(Long id) { |
| | | // 1.1 校验存在 |
| | | ErpSaleOrderDO saleOrder = validateSaleOrderExists(id); |
| | | // 1.2 校验状态:只有已作废的订单才能重新启用 |
| | | if (!ErpAuditStatus.CANCEL.getStatus().equals(saleOrder.getStatus())) { |
| | | throw exception(SALE_ORDER_ENABLE_FAIL_NOT_CANCEL, saleOrder.getNo()); |
| | | } |
| | | |
| | | // 2. 更新状态为已审核 |
| | | int updateCount = saleOrderMapper.updateByIdAndStatus(id, saleOrder.getStatus(), |
| | | new ErpSaleOrderDO().setStatus(ErpAuditStatus.APPROVE.getStatus())); |
| | | if (updateCount == 0) { |
| | | throw exception(SALE_ORDER_ENABLE_FAIL); |
| | | } |
| | | |
| | | // 订单启用不改变关联合同的审批结果。 |
| | | } |
| | | |
| | | private void validateNoActiveMps(Long orderId) { |
| | | for (ErpSaleOrderItemDO item : saleOrderItemMapper.selectListByOrderId(orderId)) { |
| | | MesProMpsRespDTO mps = mpsApi.getMpsBySaleOrderItemId(item.getId()); |
| | | if (mps != null && ObjectUtil.notEqual(mps.getStatus(), MPS_STATUS_CANCELED)) { |
| | | throw exception(SALE_ORDER_HAS_ACTIVE_MPS); |
| | | } |
| | | } |
| | | } |
| | | private List<ErpSaleOrderItemDO> validateSaleOrderItems(List<ErpSaleOrderSaveReqVO.Item> list) { |
| | | // 1. 校验产品存在 |
| | | List<ErpProductDO> productList = productService.validProductList( |
| | | convertSet(list, ErpSaleOrderSaveReqVO.Item::getProductId)); |
| | | Map<Long, ErpProductDO> productMap = convertMap(productList, ErpProductDO::getId); |
| | | // 2. 转化为 ErpSaleOrderItemDO 列表 |
| | | // 转化为 ErpSaleOrderItemDO 列表(产品验证已移除) |
| | | return convertList(list, o -> BeanUtils.toBean(o, ErpSaleOrderItemDO.class, item -> { |
| | | item.setProductUnitId(productMap.get(item.getProductId()).getUnitId()); |
| | | item.setTotalPrice(MoneyUtils.priceMultiply(item.getProductPrice(), item.getCount())); |
| | | if (item.getTotalPrice() == null) { |
| | | return; |
| | |
| | | } |
| | | if (outCount.compareTo(item.getCount()) > 0) { |
| | | throw exception(SALE_ORDER_ITEM_OUT_FAIL_PRODUCT_EXCEED, |
| | | productService.getProduct(item.getProductId()).getName(), item.getCount()); |
| | | "产品ID:" + item.getProductId(), item.getCount()); |
| | | } |
| | | saleOrderItemMapper.updateById(new ErpSaleOrderItemDO().setId(item.getId()).setOutCount(outCount)); |
| | | }); |
| | | // 2. 更新销售订单 |
| | | BigDecimal totalOutCount = getSumValue(outCountMap.values(), value -> value, BigDecimal::add, BigDecimal.ZERO); |
| | | saleOrderMapper.updateById(new ErpSaleOrderDO().setId(id).setOutCount(totalOutCount)); |
| | | } |
| | | |
| | | @Override |
| | | public void updateSaleOrderReturnCount(Long orderId, Map<Long, BigDecimal> returnCountMap) { |
| | | List<ErpSaleOrderItemDO> orderItems = saleOrderItemMapper.selectListByOrderId(orderId); |
| | | // 1. 更新每个销售订单项 |
| | | orderItems.forEach(item -> { |
| | | BigDecimal returnCount = returnCountMap.getOrDefault(item.getId(), BigDecimal.ZERO); |
| | | if (item.getReturnCount().equals(returnCount)) { |
| | | return; |
| | | } |
| | | if (returnCount.compareTo(item.getOutCount()) > 0) { |
| | | throw exception(SALE_ORDER_ITEM_RETURN_FAIL_OUT_EXCEED, |
| | | productService.getProduct(item.getProductId()).getName(), item.getOutCount()); |
| | | } |
| | | saleOrderItemMapper.updateById(new ErpSaleOrderItemDO().setId(item.getId()).setReturnCount(returnCount)); |
| | | }); |
| | | // 2. 更新销售订单 |
| | | BigDecimal totalReturnCount = getSumValue(returnCountMap.values(), value -> value, BigDecimal::add, BigDecimal.ZERO); |
| | | saleOrderMapper.updateById(new ErpSaleOrderDO().setId(orderId).setReturnCount(totalReturnCount)); |
| | | } |
| | | |
| | | @Override |
| | |
| | | return; |
| | | } |
| | | saleOrders.forEach(saleOrder -> { |
| | | if (ErpAuditStatus.APPROVE.getStatus().equals(saleOrder.getStatus())) { |
| | | if (!ErpAuditStatus.PROCESS.getStatus().equals(saleOrder.getStatus())) { |
| | | throw exception(SALE_ORDER_DELETE_FAIL_APPROVE, saleOrder.getNo()); |
| | | } |
| | | }); |
| | | |
| | | // 2. 遍历删除,并记录操作日志 |
| | | saleOrders.forEach(saleOrder -> { |
| | | // 2.1 删除订单 |
| | | // 2.1 删除附件 |
| | | storageAttachmentApi.deleteAttachmentsByRecord("erp_sale_order", saleOrder.getId()); |
| | | // 2.2 删除订单 |
| | | saleOrderMapper.deleteById(saleOrder.getId()); |
| | | // 2.2 删除订单项 |
| | | // 2.3 删除订单项 |
| | | saleOrderItemMapper.deleteByOrderId(saleOrder.getId()); |
| | | }); |
| | | } |
| | |
| | | |
| | | @Override |
| | | public PageResult<ErpSaleOrderDO> getSaleOrderPage(ErpSaleOrderPageReqVO pageReqVO) { |
| | | return saleOrderMapper.selectPage(pageReqVO); |
| | | List<Long> permittedCustomerIds = customerApi.getPermittedCustomerIds(); |
| | | return saleOrderMapper.selectPage(pageReqVO, permittedCustomerIds); |
| | | } |
| | | |
| | | // ==================== 订单项 ==================== |
| | |
| | | return saleOrderItemMapper.selectListByOrderIds(orderIds); |
| | | } |
| | | |
| | | // ==================== BPM 流程审批 ==================== |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void submitSaleOrder(Long id, Long userId) { |
| | | // 1. 校验销售订单处于草稿状态 |
| | | ErpSaleOrderDO saleOrder = validateSaleOrderExists(id); |
| | | if (ObjectUtil.notEqual(saleOrder.getStatus(), ErpAuditStatus.DRAFT.getStatus())) { |
| | | throw exception(SALE_ORDER_SUBMIT_FAIL_NOT_DRAFT); |
| | | public void updateSaleOrderOutStatus(Long orderId) { |
| | | // 1. 获取销售订单 |
| | | ErpSaleOrderDO order = validateSaleOrderExists(orderId); |
| | | // 2. 获取销售订单明细 |
| | | List<ErpSaleOrderItemDO> items = saleOrderItemMapper.selectListByOrderId(orderId); |
| | | if (CollUtil.isEmpty(items)) { |
| | | return; |
| | | } |
| | | |
| | | // 2. 创建销售订单审批流程实例 |
| | | String processInstanceId = bpmProcessInstanceApi.createProcessInstance(userId, new BpmProcessInstanceCreateReqDTO() |
| | | .setProcessDefinitionKey(BPM_PROCESS_DEFINITION_KEY) |
| | | .setBusinessKey(String.valueOf(id))); |
| | | |
| | | // 3. 更新销售订单工作流编号、状态 |
| | | // 3. 计算出库状态 |
| | | int outStatus = calculateOutStatus(items); |
| | | // 4. 更新销售订单出库状态 |
| | | saleOrderMapper.updateById(new ErpSaleOrderDO() |
| | | .setId(id) |
| | | .setProcessInstanceId(processInstanceId) |
| | | .setStatus(ErpAuditStatus.PROCESS.getStatus())); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void updateSaleOrderAuditStatus(Long id, Integer bpmResult) { |
| | | // 1. 校验销售订单存在 |
| | | ErpSaleOrderDO saleOrder = validateSaleOrderExists(id); |
| | | |
| | | // 2. 校验销售订单处于审批中 |
| | | if (ObjectUtil.notEqual(saleOrder.getStatus(), ErpAuditStatus.PROCESS.getStatus())) { |
| | | log.error("[updateSaleOrderAuditStatus][saleOrder({}) 不处于审批中,无法更新审批结果({})]", |
| | | saleOrder.getId(), bpmResult); |
| | | throw exception(SALE_ORDER_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS); |
| | | } |
| | | |
| | | // 3. 更新销售订单审批结果 |
| | | Integer auditStatus = convertBpmResultToAuditStatus(bpmResult); |
| | | saleOrderMapper.updateById(new ErpSaleOrderDO() |
| | | .setId(id) |
| | | .setStatus(auditStatus)); |
| | | .setId(orderId).setOutStatus(outStatus)); |
| | | } |
| | | |
| | | /** |
| | | * 将 BPM 审批结果转换为 ERP 审批状态 |
| | | * 计算出库状态 |
| | | * |
| | | * @param bpmResult BPM 审批结果 |
| | | * @return ERP 审批状态 |
| | | * @param items 销售订单明细列表 |
| | | * @return 出库状态 |
| | | */ |
| | | private Integer convertBpmResultToAuditStatus(Integer bpmResult) { |
| | | // BPM 审批结果:2=通过,3=不通过,4=已取消 |
| | | if (bpmResult == 2) { |
| | | return ErpAuditStatus.APPROVE.getStatus(); |
| | | } else if (bpmResult == 3) { |
| | | return ErpAuditStatus.REJECT.getStatus(); |
| | | } else if (bpmResult == 4) { |
| | | return ErpAuditStatus.DRAFT.getStatus(); |
| | | } else { |
| | | log.warn("[convertBpmResultToAuditStatus][未知的 BPM 审批结果({})]", bpmResult); |
| | | return ErpAuditStatus.PROCESS.getStatus(); |
| | | private int calculateOutStatus(List<ErpSaleOrderItemDO> items) { |
| | | boolean allOut = true; |
| | | boolean anyOut = false; |
| | | |
| | | for (ErpSaleOrderItemDO item : items) { |
| | | BigDecimal count = item.getCount() != null ? item.getCount() : BigDecimal.ZERO; |
| | | BigDecimal outCount = item.getOutCount() != null ? item.getOutCount() : BigDecimal.ZERO; |
| | | |
| | | if (outCount.compareTo(BigDecimal.ZERO) > 0) { |
| | | anyOut = true; |
| | | } |
| | | if (outCount.compareTo(count) < 0) { |
| | | allOut = false; |
| | | } |
| | | } |
| | | |
| | | if (allOut) { |
| | | return ErpSaleOrderOutStatusEnum.ALL_OUT.getStatus(); |
| | | } else if (anyOut) { |
| | | return ErpSaleOrderOutStatusEnum.PART_OUT.getStatus(); |
| | | } else { |
| | | return ErpSaleOrderOutStatusEnum.NOT_OUT.getStatus(); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public ErpSaleOrderImportRespVO importSaleOrderList(List<ErpSaleOrderImportExcelVO> importOrders, |
| | | ErpSaleOrderImportReqVO importReqVO) { |
| | | if (Boolean.TRUE.equals(importReqVO.getUpdateSupport())) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "销售订单导入仅支持新增,不支持覆盖"); |
| | | } |
| | | // 1. 校验非空(过滤完全空白的行) |
| | | importOrders = filterList(importOrders, item -> item != null && (StrUtil.isNotBlank(item.getNo()) || StrUtil.isNotBlank(item.getCustomerName()) || StrUtil.isNotBlank(item.getProductCode()) || item.getCount() != null || item.getProductPrice() != null)); |
| | | if (CollUtil.isEmpty(importOrders)) { |
| | | throw exception(SALE_ORDER_IMPORT_LIST_IS_EMPTY); |
| | | } |
| | | // 2. 按「单号」分组:相同单号的多行合并成一张销售订单;单号为空时每行各自成一张订单 |
| | | List<List<ErpSaleOrderImportExcelVO>> groups = new ArrayList<>(); |
| | | Map<String, Integer> groupIndexMap = new LinkedHashMap<>(); |
| | | for (ErpSaleOrderImportExcelVO row : importOrders) { |
| | | if (StrUtil.isBlank(row.getNo())) { |
| | | groups.add(new ArrayList<>(Collections.singletonList(row))); |
| | | continue; |
| | | } |
| | | String groupKey = row.getNo().trim(); |
| | | Integer index = groupIndexMap.get(groupKey); |
| | | if (index == null) { |
| | | index = groups.size(); |
| | | groupIndexMap.put(groupKey, index); |
| | | groups.add(new ArrayList<>()); |
| | | } |
| | | groups.get(index).add(row); |
| | | } |
| | | // 3. 逐组合并创建销售订单 |
| | | ErpSaleOrderImportRespVO respVO = ErpSaleOrderImportRespVO.builder() |
| | | .createSaleOrderNos(new ArrayList<>()) |
| | | .failureSaleOrderNos(new LinkedHashMap<>()) |
| | | .build(); |
| | | for (List<ErpSaleOrderImportExcelVO> group : groups) { |
| | | String groupKey = StrUtil.isNotBlank(group.get(0).getNo()) ? group.get(0).getNo() |
| | | : "第" + (importOrders.indexOf(group.get(0)) + 1) + "行"; |
| | | try { |
| | | Long orderId = SpringUtil.getBean(ErpSaleOrderServiceImpl.class).createImportedOrder(group); |
| | | respVO.getCreateSaleOrderNos().add(saleOrderMapper.selectById(orderId).getNo()); |
| | | } catch (ServiceException ex) { |
| | | respVO.getFailureSaleOrderNos().put(groupKey, ex.getMessage()); |
| | | } |
| | | } |
| | | return respVO; |
| | | } |
| | | |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public Long createImportedOrder(List<ErpSaleOrderImportExcelVO> group) { |
| | | return createSaleOrder(buildSaleOrderImportSaveReqVO(group)); |
| | | } |
| | | /** |
| | | * 将同一张销售订单的多行明细转换成创建 Request VO |
| | | */ |
| | | private ErpSaleOrderSaveReqVO buildSaleOrderImportSaveReqVO(List<ErpSaleOrderImportExcelVO> group) { |
| | | ErpSaleOrderImportExcelVO first = group.get(0); |
| | | for (ErpSaleOrderImportExcelVO row : group) { |
| | | if (StrUtil.isNotBlank(row.getCustomerName()) && !StrUtil.equals(first.getCustomerName(), row.getCustomerName()) |
| | | || row.getOrderTime() != null && !row.getOrderTime().equals(first.getOrderTime()) |
| | | || StrUtil.isNotBlank(row.getSaleUserName()) && !StrUtil.equals(first.getSaleUserName(), row.getSaleUserName()) |
| | | || StrUtil.isNotBlank(row.getAccountName()) && !StrUtil.equals(first.getAccountName(), row.getAccountName()) |
| | | || StrUtil.isNotBlank(row.getContractNo()) && !StrUtil.equals(first.getContractNo(), row.getContractNo())) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "同一订单的客户、下单时间、销售员和结算账户必须一致"); |
| | | } |
| | | } |
| | | // 1. 校验并解析客户 |
| | | if (StrUtil.isBlank(first.getCustomerName())) { |
| | | throw exception(SALE_ORDER_IMPORT_CUSTOMER_NOT_EXISTS, ""); |
| | | } |
| | | CrmCustomerRespDTO customer = customerApi.getCustomerByName(first.getCustomerName()); |
| | | if (customer == null) { |
| | | throw exception(SALE_ORDER_IMPORT_CUSTOMER_NOT_EXISTS, first.getCustomerName()); |
| | | } |
| | | if (first.getOrderTime() == null) { |
| | | throw exception(SALE_ORDER_IMPORT_ORDER_TIME_REQUIRED); |
| | | } |
| | | if (first.getDiscountPercent() != null && (first.getDiscountPercent().signum() < 0 || first.getDiscountPercent().compareTo(new BigDecimal("100")) > 0)) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "优惠率必须在 0 到 100 之间"); |
| | | } |
| | | if (first.getDepositPrice() != null && first.getDepositPrice().signum() < 0) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "定金不能为负数"); |
| | | } |
| | | // 2. 解析结算账户(可选) |
| | | Long accountId = null; |
| | | if (StrUtil.isNotBlank(first.getAccountName())) { |
| | | ErpAccountDO account = accountMapper.selectByName(first.getAccountName()); |
| | | if (account == null) { |
| | | throw exception(SALE_ORDER_IMPORT_ACCOUNT_NOT_EXISTS, first.getAccountName()); |
| | | } |
| | | accountId = account.getId(); |
| | | } |
| | | // 3. 解析销售员(可选) |
| | | Long saleUserId = null; |
| | | if (StrUtil.isNotBlank(first.getSaleUserName())) { |
| | | List<AdminUserRespDTO> users = adminUserApi.getUserListByNickname(first.getSaleUserName()); |
| | | if (CollUtil.isEmpty(users)) { |
| | | throw exception(SALE_ORDER_IMPORT_SALE_USER_NOT_EXISTS, first.getSaleUserName()); |
| | | } |
| | | saleUserId = users.get(0).getId(); |
| | | } |
| | | // 4. 组装明细 |
| | | List<ErpSaleOrderSaveReqVO.Item> items = new ArrayList<>(); |
| | | for (ErpSaleOrderImportExcelVO row : group) { |
| | | if (StrUtil.isBlank(row.getProductCode()) || StrUtil.isBlank(row.getProductUnitCode())) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "物料编码和单位编码不能为空"); |
| | | } |
| | | if (row.getCount() == null || row.getCount().compareTo(BigDecimal.ZERO) <= 0) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "物料 " + row.getProductCode() + " 的数量必须大于零"); |
| | | } |
| | | if (row.getProductPrice() == null || row.getProductPrice().compareTo(BigDecimal.ZERO) < 0) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "物料 " + row.getProductCode() + " 的单价不能为空或为负数"); |
| | | } |
| | | if (row.getNeedProduction() != null && row.getNeedProduction() != 0 && row.getNeedProduction() != 1) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "是否需要生产只能填写 0 或 1"); |
| | | } |
| | | if (row.getTaxPercent() != null && (row.getTaxPercent().signum() < 0 || row.getTaxPercent().compareTo(new BigDecimal("100")) > 0)) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "税率必须在 0 到 100 之间"); |
| | | } |
| | | MdmItemRespDTO product = mdmItemApi.getItemByCode(row.getProductCode()).getCheckedData(); |
| | | if (product == null) { |
| | | throw exception(SALE_ORDER_IMPORT_PRODUCT_NOT_EXISTS, row.getProductCode()); |
| | | } |
| | | MdmUnitMeasureRespDTO unit = mdmUnitMeasureApi.getUnitMeasureByCode(row.getProductUnitCode()).getCheckedData(); |
| | | if (unit == null) { |
| | | throw exception(SALE_ORDER_IMPORT_UNIT_NOT_EXISTS, row.getProductUnitCode()); |
| | | } |
| | | ErpSaleOrderSaveReqVO.Item item = new ErpSaleOrderSaveReqVO.Item() |
| | | .setProductId(product.getId()) |
| | | .setProductUnitId(unit.getId()) |
| | | .setProductPrice(row.getProductPrice()) |
| | | .setCount(row.getCount()) |
| | | .setTaxPercent(row.getTaxPercent()) |
| | | .setNeedProduction(row.getNeedProduction()) |
| | | .setRemark(row.getItemRemark()); |
| | | items.add(item); |
| | | } |
| | | CrmContractForSaleDTO contract = null; |
| | | if (StrUtil.isNotBlank(first.getContractNo())) { |
| | | contract = contractApi.getContractForSaleByNo(first.getContractNo().trim()).getCheckedData(); |
| | | if (contract == null || !Integer.valueOf(20).equals(contract.getAuditStatus())) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "合同不存在或尚未审批通过"); |
| | | } |
| | | if (!customer.getId().equals(contract.getCustomerId())) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "合同客户与订单客户不一致"); |
| | | } |
| | | if (saleOrderMapper.selectByContractId(contract.getId()) != null) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "该合同已关联销售订单"); |
| | | } |
| | | Map<String, BigDecimal> expected = new LinkedHashMap<>(); |
| | | if (contract.getItems() != null) { |
| | | for (CrmContractForSaleDTO.Item item : contract.getItems()) { |
| | | if (item.getItemId() == null || item.getItemUnitId() == null || item.getContractPrice() == null || item.getCount() == null) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "合同明细不完整,无法关联订单"); |
| | | } |
| | | String key = item.getItemId() + ":" + item.getItemUnitId() + ":" + item.getContractPrice().stripTrailingZeros().toPlainString(); |
| | | expected.merge(key, item.getCount(), BigDecimal::add); |
| | | } |
| | | } |
| | | Map<String, BigDecimal> actual = new LinkedHashMap<>(); |
| | | for (ErpSaleOrderSaveReqVO.Item item : items) { |
| | | String key = item.getProductId() + ":" + item.getProductUnitId() + ":" + item.getProductPrice().stripTrailingZeros().toPlainString(); |
| | | actual.merge(key, item.getCount(), BigDecimal::add); |
| | | } |
| | | if (expected.isEmpty() || expected.size() != actual.size() || expected.entrySet().stream() |
| | | .anyMatch(entry -> !actual.containsKey(entry.getKey()) || entry.getValue().compareTo(actual.get(entry.getKey())) != 0)) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "订单物料、单位、单价及数量须与合同明细一致"); |
| | | } |
| | | BigDecimal expectedDiscount = ObjectUtil.defaultIfNull(contract.getDiscountPercent(), BigDecimal.ZERO); |
| | | if (expectedDiscount.compareTo(ObjectUtil.defaultIfNull(first.getDiscountPercent(), BigDecimal.ZERO)) != 0) { |
| | | throw exception(SALE_ORDER_IMPORT_INVALID_ROW, "订单优惠率须与合同一致"); |
| | | } |
| | | } |
| | | // 5. 组装主表 |
| | | ErpSaleOrderSaveReqVO createReqVO = new ErpSaleOrderSaveReqVO() |
| | | .setCustomerId(customer.getId()) |
| | | .setContractId(contract == null ? null : contract.getId()) |
| | | .setContractNo(contract == null ? null : first.getContractNo().trim()) |
| | | .setOrderTime(first.getOrderTime()) |
| | | .setSaleUserId(saleUserId) |
| | | .setAccountId(accountId) |
| | | .setDiscountPercent(ObjectUtil.defaultIfNull(first.getDiscountPercent(), BigDecimal.ZERO)) |
| | | .setDepositPrice(ObjectUtil.defaultIfNull(first.getDepositPrice(), BigDecimal.ZERO)) |
| | | .setRemark(first.getRemark()) |
| | | .setItems(items); |
| | | return createReqVO; |
| | | } |
| | | |
| | | } |