yudao-module-erp/src/main/java/cn/iocoder/yudao/module/erp/api/purchase/ErpPurchaseOrderApiImpl.java
@@ -17,8 +17,12 @@
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
@@ -134,4 +138,43 @@
        return success(BeanUtils.toBean(items, ErpPurchaseOrderItemRespDTO.class));
    }
    @Override
    public CommonResult<Map<Long, BigDecimal>> getItemAveragePurchasePriceMap(Collection<Long> productIds) {
        if (productIds == null || productIds.isEmpty()) {
            return success(Collections.emptyMap());
        }
        // 1. 查询已审核采购订单中这些物料的明细
        List<ErpPurchaseOrderItemDO> items = purchaseOrderItemMapper
                .selectListByApprovedOrderAndProductIds(productIds);
        if (items.isEmpty()) {
            return success(Collections.emptyMap());
        }
        // 2. 按物料汇总数量和金额,计算加权平均价:SUM(总价) / SUM(数量)
        Map<Long, BigDecimal> totalPriceMap = new HashMap<>();
        Map<Long, BigDecimal> totalCountMap = new HashMap<>();
        for (ErpPurchaseOrderItemDO item : items) {
            if (item.getProductId() == null || item.getCount() == null
                    || item.getCount().compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            BigDecimal totalPrice = item.getTotalPrice();
            if (totalPrice == null && item.getProductPrice() != null) {
                totalPrice = item.getProductPrice().multiply(item.getCount());
            }
            if (totalPrice == null) {
                continue;
            }
            totalPriceMap.merge(item.getProductId(), totalPrice, BigDecimal::add);
            totalCountMap.merge(item.getProductId(), item.getCount(), BigDecimal::add);
        }
        Map<Long, BigDecimal> result = new HashMap<>(totalCountMap.size());
        totalCountMap.forEach((productId, totalCount) -> {
            BigDecimal totalPrice = totalPriceMap.get(productId);
            if (totalPrice != null && totalCount.compareTo(BigDecimal.ZERO) > 0) {
                result.put(productId, totalPrice.divide(totalCount, 6, RoundingMode.HALF_UP));
            }
        });
        return success(result);
    }
}