tuqin
4 天以前 f785e619ff7cbe99aa80fc7679a244224ab5024f
yudao-module-erp/src/main/java/cn/iocoder/yudao/module/erp/service/sale/ErpSaleOrderServiceImpl.java
@@ -52,9 +52,13 @@
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
@@ -98,6 +102,9 @@
    private CrmContractApi contractApi;
    @Resource
    private ErpAccountService accountService;
    @Resource
    private cn.iocoder.yudao.module.mes.api.wms.MesWmStockApi mesWmStockApi;
    @Resource
    private AdminUserApi adminUserApi;
@@ -561,6 +568,195 @@
        return mpsId;
    }
    // ==================== 从销售订单生成生产计划(生产车间视角) ====================
    @Override
    public List<cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderPendingProductionRespVO>
            getPendingProductionList() {
        // 1. 取全部已审核的销售订单
        List<ErpSaleOrderDO> orders = saleOrderMapper.selectList(
                new cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX<ErpSaleOrderDO>()
                        .eq(ErpSaleOrderDO::getStatus, ErpAuditStatus.APPROVE.getStatus())
                        .orderByDesc(ErpSaleOrderDO::getId));
        if (CollUtil.isEmpty(orders)) {
            return Collections.emptyList();
        }
        Map<Long, ErpSaleOrderDO> orderMap = orders.stream()
                .collect(Collectors.toMap(ErpSaleOrderDO::getId, o -> o, (a, b) -> a));
        // 2. 取订单明细
        List<ErpSaleOrderItemDO> items = saleOrderItemMapper.selectListByOrderIds(orderMap.keySet());
        if (CollUtil.isEmpty(items)) {
            return Collections.emptyList();
        }
        // 3. 已有有效 MPS 的明细要排除,避免重复安排生产
        Set<Long> plannedItemIds = new HashSet<>();
        List<Long> allItemIds = items.stream().map(ErpSaleOrderItemDO::getId).collect(Collectors.toList());
        try {
            // 注意:该 API 直接返回 List,不是 CommonResult
            List<cn.iocoder.yudao.module.mes.api.mps.dto.MesProMpsRespDTO> existMps =
                    mpsApi.getMpsListBySaleOrderItemIds(allItemIds);
            if (CollUtil.isNotEmpty(existMps)) {
                existMps.stream()
                        .filter(m -> ObjectUtil.notEqual(m.getStatus(), MPS_STATUS_CANCELED))
                        .map(cn.iocoder.yudao.module.mes.api.mps.dto.MesProMpsRespDTO::getSaleOrderItemId)
                        .filter(Objects::nonNull)
                        .forEach(plannedItemIds::add);
            }
        } catch (Exception e) {
            log.warn("[getPendingProductionList] 查询已有 MPS 失败,按全部可安排处理", e);
        }
        // 4. 组装:带出可用库存与建议生产数量
        List<cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderPendingProductionRespVO> result
                = new ArrayList<>();
        for (ErpSaleOrderItemDO item : items) {
            if (plannedItemIds.contains(item.getId())) {
                continue;
            }
            ErpSaleOrderDO order = orderMap.get(item.getOrderId());
            if (order == null) {
                continue;
            }
            cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderPendingProductionRespVO vo
                    = new cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderPendingProductionRespVO();
            vo.setSaleOrderId(order.getId());
            vo.setSaleOrderNo(order.getNo());
            vo.setSaleOrderItemId(item.getId());
            vo.setCustomerId(order.getCustomerId());
            vo.setCustomerName(getCustomerName(order.getCustomerId()));
            vo.setProductId(item.getProductId());
            // 明细表只存 productId,产品编码/名称/规格从 MDM 取
            try {
                MdmItemRespDTO mdmItem = mdmItemApi.getItem(item.getProductId()).getCheckedData();
                if (mdmItem != null) {
                    vo.setProductCode(mdmItem.getCode());
                    vo.setProductName(mdmItem.getName());
                    vo.setProductSpecification(mdmItem.getSpecification());
                }
            } catch (Exception e) {
                log.warn("[getPendingProductionList] 获取物料信息失败,productId={}", item.getProductId(), e);
            }
            vo.setOrderCount(item.getCount());
            vo.setOrderTime(order.getOrderTime());
            // 当前可用库存
            BigDecimal stock = BigDecimal.ZERO;
            try {
                BigDecimal qty = mesWmStockApi.getStockQuantity(item.getProductId());
                if (qty != null) {
                    stock = qty;
                }
            } catch (Exception e) {
                log.warn("[getPendingProductionList] 查询库存失败,productId={}", item.getProductId(), e);
            }
            vo.setStockQuantity(stock);
            // 建议生产数量 = 订购数量 - 可用库存,不足 0 则取 0
            BigDecimal count = item.getCount() == null ? BigDecimal.ZERO : item.getCount();
            BigDecimal suggest = count.subtract(stock);
            vo.setSuggestQuantity(suggest.compareTo(BigDecimal.ZERO) > 0 ? suggest : BigDecimal.ZERO);
            result.add(vo);
        }
        // 按建议生产数量降序,急需生产的排前面
        result.sort((a, b) -> b.getSuggestQuantity().compareTo(a.getSuggestQuantity()));
        return result;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int generateMpsFromSaleOrder(
            cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderGenerateMpsReqVO reqVO) {
        if (reqVO.getItems() == null || reqVO.getItems().isEmpty()) {
            return 0;
        }
        int success = 0;
        for (cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderGenerateMpsReqVO.Item reqItem
                : reqVO.getItems()) {
            ErpSaleOrderItemDO item = saleOrderItemMapper.selectById(reqItem.getSaleOrderItemId());
            if (item == null) {
                log.warn("[generateMpsFromSaleOrder] 销售订单明细不存在,id={}", reqItem.getSaleOrderItemId());
                continue;
            }
            ErpSaleOrderDO order = saleOrderMapper.selectById(item.getOrderId());
            if (order == null || !ErpAuditStatus.APPROVE.getStatus().equals(order.getStatus())) {
                log.warn("[generateMpsFromSaleOrder] 销售订单未审核,跳过,itemId={}", item.getId());
                continue;
            }
            // 幂等保护:已有有效 MPS 则跳过,避免重复安排
            try {
                List<cn.iocoder.yudao.module.mes.api.mps.dto.MesProMpsRespDTO> existMps =
                        mpsApi.getMpsListBySaleOrderItemIds(Collections.singletonList(item.getId()));
                if (CollUtil.isNotEmpty(existMps)
                        && existMps.stream().anyMatch(m -> ObjectUtil.notEqual(m.getStatus(), MPS_STATUS_CANCELED))) {
                    log.info("[generateMpsFromSaleOrder] 明细({}) 已存在有效 MPS,跳过", item.getId());
                    continue;
                }
            } catch (Exception e) {
                log.warn("[generateMpsFromSaleOrder] 幂等校验失败,继续生成,itemId={}", item.getId(), e);
            }
            try {
                createMpsForSaleOrderItemWithQuantity(order, item, reqItem.getQuantity());
                success++;
            } catch (Exception e) {
                log.error("[generateMpsFromSaleOrder] 生成 MPS 失败,itemId={}", item.getId(), e);
            }
        }
        log.info("[generateMpsFromSaleOrder] 共生成 MPS {} 条", success);
        return success;
    }
    /**
     * 按指定数量为销售订单明细创建 MPS
     *
     * 与 createMpsForSaleOrderItem 的差别:数量由车间自行指定(通常是 订购数量 - 可用库存),
     * 而不是直接用订单数量
     */
    private Long createMpsForSaleOrderItemWithQuantity(ErpSaleOrderDO saleOrder, ErpSaleOrderItemDO item,
                                                       BigDecimal quantity) {
        String productName = null;
        try {
            MdmItemRespDTO mdmItem = mdmItemApi.getItem(item.getProductId()).getCheckedData();
            if (mdmItem != null) {
                productName = mdmItem.getName();
            }
        } catch (Exception e) {
            log.warn("[createMpsForSaleOrderItemWithQuantity] 获取物料信息失败,productId={}", item.getProductId(), e);
        }
        MesProMpsCreateReqDTO createReqDTO = new MesProMpsCreateReqDTO();
        createReqDTO.setSaleOrderId(saleOrder.getId());
        createReqDTO.setSaleOrderNo(saleOrder.getNo());
        createReqDTO.setSaleOrderItemId(item.getId());
        createReqDTO.setMdmItemId(item.getProductId());
        createReqDTO.setProductName(productName);
        createReqDTO.setQuantity(quantity);
        createReqDTO.setClientId(saleOrder.getCustomerId());
        createReqDTO.setRequestDate(formatRequestDate(saleOrder.getOrderTime()));
        createReqDTO.setRemark("由生产车间从销售订单生成:" + saleOrder.getNo());
        return mpsApi.createMps(createReqDTO);
    }
    /**
     * 取客户名称,失败时返回 null 不影响主流程
     */
    private String getCustomerName(Long customerId) {
        if (customerId == null) {
            return null;
        }
        try {
            // 该 API 直接返回 DTO,不是 CommonResult
            cn.iocoder.yudao.module.crm.api.customer.dto.CrmCustomerRespDTO customer =
                    customerApi.getCustomer(customerId);
            return customer == null ? null : customer.getName();
        } catch (Exception e) {
            log.warn("[getCustomerName] 获取客户失败,customerId={}", customerId, e);
            return null;
        }
    }
    /**
     * 格式化需求日期
     */