云
2026-10-25 d54fbc9d4f8981fa0f7f613b33a28a8cd4f764ea
yudao-module-mdm/src/main/java/cn/iocoder/yudao/module/mdm/service/item/MdmItemServiceImpl.java
@@ -2,29 +2,50 @@
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.mdm.controller.admin.item.vo.MdmItemImportExcelVO;
import cn.iocoder.yudao.module.mdm.controller.admin.item.vo.MdmItemImportReqVO;
import cn.iocoder.yudao.module.mdm.controller.admin.item.vo.MdmItemImportRespVO;
import cn.iocoder.yudao.module.mdm.controller.admin.item.vo.MdmItemPageReqVO;
import cn.iocoder.yudao.module.mdm.controller.admin.item.vo.MdmItemSaveReqVO;
import cn.iocoder.yudao.module.mdm.dal.dataobject.brand.MdmBrandDO;
import cn.iocoder.yudao.module.mdm.dal.dataobject.category.MdmItemCategoryDO;
import cn.iocoder.yudao.module.mdm.dal.dataobject.item.MdmItemBatchConfigDO;
import cn.iocoder.yudao.module.mdm.dal.dataobject.item.MdmItemDO;
import cn.iocoder.yudao.module.mdm.dal.dataobject.unit.MdmUnitMeasureDO;
import cn.iocoder.yudao.module.mdm.dal.mysql.brand.MdmBrandMapper;
import cn.iocoder.yudao.module.mdm.dal.mysql.category.MdmItemCategoryMapper;
import cn.iocoder.yudao.module.mdm.dal.mysql.item.MdmItemBatchConfigMapper;
import cn.iocoder.yudao.module.mdm.dal.mysql.item.MdmItemMapper;
import cn.iocoder.yudao.module.mdm.dal.mysql.unit.MdmUnitMeasureMapper;
import cn.iocoder.yudao.module.mdm.service.brand.MdmBrandService;
import cn.iocoder.yudao.module.mdm.service.category.MdmItemCategoryService;
import cn.iocoder.yudao.module.mdm.service.unit.MdmUnitMeasureService;
import cn.iocoder.yudao.module.mdm.service.brand.MdmBrandService;
import cn.iocoder.yudao.module.mes.api.item.MesMdItemApi;
import cn.iocoder.yudao.module.mes.api.item.dto.MesMdItemSyncReqDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import java.util.*;
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.convertSet;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList;
import static cn.iocoder.yudao.module.mdm.enums.ErrorCodeConstants.*;
/**
 * MDM 物料主数据 Service 实现类
 *
 * @author 芋道源码
 * @author 超级管理员
 */
@Service
@Validated
@@ -40,56 +61,306 @@
    @Resource
    private MdmBrandService brandService;
    @Resource
    private MdmItemCategoryMapper itemCategoryMapper;
    @Resource
    private MdmUnitMeasureMapper unitMeasureMapper;
    @Resource
    private MdmBrandMapper brandMapper;
    @Resource
    @Lazy
    private MesMdItemApi mesMdItemApi;
    @Resource
    private MdmItemBatchConfigMapper itemBatchConfigMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createItem(MdmItemSaveReqVO createReqVO) {
        // 校验数据
        validateItemSaveData(createReqVO);
        // 插入
        // 插入 MDM 物料
        MdmItemDO item = BeanUtils.toBean(createReqVO, MdmItemDO.class);
        itemMapper.insert(item);
        // 保存批次配置(如果有)
        saveBatchConfig(item.getId(), createReqVO);
        // 勾选同步时,同步到 MES
        if (Boolean.TRUE.equals(createReqVO.getSyncMes())) {
            createReqVO.setId(item.getId());
            syncItemToMes(createReqVO);
        }
        return item.getId();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateItem(MdmItemSaveReqVO updateReqVO) {
        // 校验存在
        validateItemExists(updateReqVO.getId());
        // 校验数据
        validateItemSaveData(updateReqVO);
        // 更新
        // 更新 MDM 物料
        MdmItemDO updateObj = BeanUtils.toBean(updateReqVO, MdmItemDO.class);
        itemMapper.updateById(updateObj);
        // 保存批次配置(如果有)
        saveBatchConfig(updateReqVO.getId(), updateReqVO);
        // 根据同步开关决定:打开则同步到 MES,关闭则取消同步(从 MES 删除)
        if (Boolean.TRUE.equals(updateReqVO.getSyncMes())) {
            syncItemToMes(updateReqVO);
        } else {
            mesMdItemApi.deleteItem(updateReqVO.getId());
        }
    }
    private void validateItemSaveData(MdmItemSaveReqVO reqVO) {
        // 校验物料编码的唯一性
        validateItemCodeUnique(reqVO.getId(), reqVO.getCode());
        // 校验物料分类存在
        validateCategoryExists(reqVO.getCategoryId());
        // 校验计量单位存在
        validateUnitMeasureExists(reqVO.getUnitMeasureId());
        // 校验品牌存在(如果有)
        if (reqVO.getBrandId() != null) {
            validateBrandExists(reqVO.getBrandId());
    }
    /**
     * 同步物料到 MES(单位/分类按 code 映射)
     *
     * MDM 的 unitMeasureId/categoryId 与 MES 的 unitMeasureId/itemTypeId 分属两套主数据,
     * 这里先在 MDM 侧解析出 code,再交由 MesMdItemApi 在 MES 侧解析为对应 id。
     * 同步失败将抛出异常,触发外层 @Transactional 整体回滚(MDM 操作一并回滚)。
     */
    private void syncItemToMes(MdmItemSaveReqVO reqVO) {
        // 解析计量单位 id -> code
        String unitCode = null;
        if (reqVO.getUnitMeasureId() != null) {
            MdmUnitMeasureDO unitMeasure = unitMeasureService.getUnitMeasure(reqVO.getUnitMeasureId());
            if (unitMeasure == null) {
                throw exception(MDM_UNIT_MEASURE_NOT_EXISTS);
            }
            unitCode = unitMeasure.getCode();
        }
        // 解析分类 id -> code(使用 MDM 本地分类服务)
        String itemTypeCode = null;
        if (reqVO.getCategoryId() != null) {
            MdmItemCategoryDO category = itemCategoryService.getItemCategory(reqVO.getCategoryId());
            if (category == null) {
                throw exception(MDM_ITEM_CATEGORY_NOT_EXISTS);
            }
            itemTypeCode = category.getCode();
        }
        // 组装同步 DTO
        MesMdItemSyncReqDTO syncReqDTO = new MesMdItemSyncReqDTO();
        syncReqDTO.setCode(reqVO.getCode());
        syncReqDTO.setMdmItemId(reqVO.getId());
        syncReqDTO.setName(reqVO.getName());
        syncReqDTO.setSpecification(reqVO.getSpecification());
        syncReqDTO.setUnitCode(unitCode);
        syncReqDTO.setItemTypeCode(itemTypeCode);
        syncReqDTO.setSafeStockFlag(Boolean.TRUE); // 保留 MDM 的 minStock/maxStock,避免被 MES 清零
        syncReqDTO.setMinStock(reqVO.getMinStock());
        syncReqDTO.setMaxStock(reqVO.getMaxStock());
        syncReqDTO.setHighValue(reqVO.getIsHighValue());
        syncReqDTO.setBatchFlag(reqVO.getIsBatchManaged());
        syncReqDTO.setStatus(reqVO.getStatus());
        syncReqDTO.setRemark(reqVO.getRemark());
        // 批次配置字段
        syncReqDTO.setProduceDateFlag(reqVO.getProduceDateFlag());
        syncReqDTO.setExpireDateFlag(reqVO.getExpireDateFlag());
        syncReqDTO.setReceiptDateFlag(reqVO.getReceiptDateFlag());
        syncReqDTO.setVendorFlag(reqVO.getVendorFlag());
        syncReqDTO.setPurchaseOrderCodeFlag(reqVO.getPurchaseOrderCodeFlag());
        syncReqDTO.setLotNumberFlag(reqVO.getLotNumberFlag());
        syncReqDTO.setQualityStatusFlag(reqVO.getQualityStatusFlag());
        // create 走 createItem,update 走 updateItem(MES 侧按 code upsert)
        if (reqVO.getId() == null) {
            mesMdItemApi.createItem(syncReqDTO);
        } else {
            mesMdItemApi.updateItem(syncReqDTO);
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateItemStatus(Long id, Integer status) {
        // 校验存在
        validateItemExists(id);
        // 更新状态
        itemMapper.updateById(new MdmItemDO().setId(id).setStatus(status));
        // 同步状态到 MES
        mesMdItemApi.updateItemStatus(id, status);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteItem(Long id) {
        // 校验存在
        validateItemExists(id);
        // 删除
        MdmItemDO item = validateItemExists(id);
        // 校验物料是否被业务引用
        validateItemNoReference(id);
        // 软删除当前记录
        itemMapper.deleteById(id);
        // 同步删除到 MES
        mesMdItemApi.deleteItem(id);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateItemSync(Long id, Boolean sync) {
        // 校验存在
        MdmItemDO item = validateItemExists(id);
        if (Boolean.TRUE.equals(sync)) {
            // 同步到 MES:从 DB 读取完整物料数据组装后走 syncItemToMes
            MdmItemSaveReqVO reqVO = BeanUtils.toBean(item, MdmItemSaveReqVO.class);
            // DO 字段名为 highValue,与 VO 的 isHighValue 不自动匹配,手动补齐
            reqVO.setIsHighValue(item.getHighValue());
            // 补齐批次属性配置
            MdmItemBatchConfigDO config = itemBatchConfigMapper.selectOne(
                    MdmItemBatchConfigDO::getItemId, id);
            if (config != null) {
                reqVO.setProduceDateFlag(config.getProduceDateFlag());
                reqVO.setExpireDateFlag(config.getExpireDateFlag());
                reqVO.setReceiptDateFlag(config.getReceiptDateFlag());
                reqVO.setVendorFlag(config.getVendorFlag());
                reqVO.setPurchaseOrderCodeFlag(config.getPurchaseOrderCodeFlag());
                reqVO.setLotNumberFlag(config.getLotNumberFlag());
                reqVO.setQualityStatusFlag(config.getQualityStatusFlag());
            }
            syncItemToMes(reqVO);
        } else {
            // 取消同步:从 MES 删除该物料(MES 无此物料时内部为空操作)
            mesMdItemApi.deleteItem(id);
        }
    }
    /**
     * 校验物料未被业务引用(销售、采购、生产、质检、库存等)
     *
     * @param id 物料编号
     */
    private void validateItemNoReference(Long id) {
        List<Map<String, Object>> references = itemMapper.selectItemReferenceCount(id);
        if (CollUtil.isNotEmpty(references)) {
            String refDesc = references.stream()
                    .map(r -> r.get("source") + "(" + r.get("cnt") + ")")
                    .collect(Collectors.joining("、"));
            throw exception(MDM_ITEM_EXISTS_REFERENCE, refDesc);
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteItemList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return;
        }
        // 逐个删除(复用单条删除逻辑,保持校验)
        ids.forEach(this::deleteItem);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MdmItemImportRespVO importItemList(List<MdmItemImportExcelVO> importItems,
                                              MdmItemImportReqVO importReqVO) {
        // 1. 校验非空(以物料编码作为导入主键)
        importItems = filterList(importItems, item -> StrUtil.isNotBlank(item.getCode()));
        if (CollUtil.isEmpty(importItems)) {
            throw exception(MDM_ITEM_IMPORT_LIST_IS_EMPTY);
        }
        // 2. 逐条处理
        MdmItemImportRespVO respVO = MdmItemImportRespVO.builder()
                .createItemCodes(new ArrayList<>())
                .updateItemCodes(new ArrayList<>())
                .failureItemCodes(new LinkedHashMap<>())
                .build();
        importItems.forEach(importItem -> {
            try {
                // 2.1 解析外键:分类 / 主单位 / 辅单位 / 品牌(按名称解析)
                Long categoryId = resolveCategoryId(importItem.getCategoryName());
                Long unitMeasureId = resolveUnitMeasureId(importItem.getUnitMeasureName());
                Long unitMeasureId2 = resolveUnitMeasureId(importItem.getUnitMeasureName2());
                Long unitMeasureId3 = resolveUnitMeasureId(importItem.getUnitMeasureName3());
                Long brandId = resolveBrandId(importItem.getBrandName());
                // 2.2 判断是否存在(按编码唯一)
                MdmItemDO existItem = itemMapper.selectByCode(importItem.getCode());
                if (existItem == null) {
                    // 2.2.1 新增
                    MdmItemDO item = BeanUtils.toBean(importItem, MdmItemDO.class)
                            .setCategoryId(categoryId)
                            .setUnitMeasureId(unitMeasureId)
                            .setUnitMeasureId2(unitMeasureId2)
                            .setUnitMeasureId3(unitMeasureId3)
                            .setBrandId(brandId);
                    if (item.getStatus() == null) {
                        item.setStatus(CommonStatusEnum.ENABLE.getStatus());
                    }
                    itemMapper.insert(item);
                    respVO.getCreateItemCodes().add(importItem.getCode());
                    return;
                }
                // 2.2.2 已存在,判断是否允许更新
                if (!importReqVO.getUpdateSupport()) {
                    respVO.getFailureItemCodes().put(importItem.getCode(),
                            StrUtil.format(MDM_ITEM_CODE_EXISTS.getMsg(), importItem.getCode()));
                    return;
                }
                MdmItemDO updateItem = BeanUtils.toBean(importItem, MdmItemDO.class)
                        .setId(existItem.getId())
                        .setCategoryId(categoryId)
                        .setUnitMeasureId(unitMeasureId)
                        .setUnitMeasureId2(unitMeasureId2)
                        .setUnitMeasureId3(unitMeasureId3)
                        .setBrandId(brandId);
                itemMapper.updateById(updateItem);
                respVO.getUpdateItemCodes().add(importItem.getCode());
            } catch (ServiceException ex) {
                respVO.getFailureItemCodes().put(importItem.getCode(), ex.getMessage());
            }
        });
        return respVO;
    }
    /**
     * 按名称解析物料分类编号
     */
    private Long resolveCategoryId(String categoryName) {
        if (StrUtil.isBlank(categoryName)) {
            return null;
        }
        MdmItemCategoryDO category = itemCategoryMapper.selectByName(categoryName);
        if (category == null) {
            throw exception(MDM_ITEM_IMPORT_CATEGORY_NOT_EXISTS, categoryName);
        }
        return category.getId();
    }
    /**
     * 按名称解析计量单位编号
     */
    private Long resolveUnitMeasureId(String unitMeasureName) {
        if (StrUtil.isBlank(unitMeasureName)) {
            return null;
        }
        MdmUnitMeasureDO unitMeasure = unitMeasureMapper.selectByName(unitMeasureName);
        if (unitMeasure == null) {
            throw exception(MDM_ITEM_IMPORT_UNIT_NOT_EXISTS, unitMeasureName);
        }
        return unitMeasure.getId();
    }
    /**
     * 按名称解析品牌编号
     */
    private Long resolveBrandId(String brandName) {
        if (StrUtil.isBlank(brandName)) {
            return null;
        }
        MdmBrandDO brand = brandMapper.selectByName(brandName);
        if (brand == null) {
            throw exception(MDM_ITEM_IMPORT_BRAND_NOT_EXISTS, brandName);
        }
        return brand.getId();
    }
    @Override
@@ -121,7 +392,12 @@
    }
    private void validateCategoryExists(Long categoryId) {
        if (itemCategoryService.getItemCategory(categoryId) == null) {
        if (categoryId == null) {
            return;
        }
        // 使用 MDM 本地分类服务校验
        MdmItemCategoryDO category = itemCategoryService.getItemCategory(categoryId);
        if (category == null) {
            throw exception(MDM_ITEM_CATEGORY_NOT_EXISTS);
        }
    }
@@ -135,6 +411,30 @@
    private void validateBrandExists(Long brandId) {
        if (brandService.getBrand(brandId) == null) {
            throw exception(MDM_BRAND_NOT_EXISTS);
        }
    }
    /**
     * 将 itemType 转换为中文名称
     *
     * @param itemType 物料类型:1原料, 2半成品, 3成品, 4辅料
     * @return 中文名称
     */
    private String convertItemTypeToName(Integer itemType) {
        if (itemType == null) {
            return null;
        }
        switch (itemType) {
            case 1:
                return "原料";
            case 2:
                return "半成品";
            case 3:
                return "成品";
            case 4:
                return "辅料";
            default:
                return null;
        }
    }
@@ -186,4 +486,57 @@
        return itemMapper.selectByCode(code);
    }
}
    @Override
    public List<MdmItemDO> getItemSimpleList() {
        return itemMapper.selectList(MdmItemDO::getStatus,
                cn.iocoder.yudao.framework.common.enums.CommonStatusEnum.ENABLE.getStatus());
    }
    /**
     * 保存批次配置(到 MDM 本地表)
     */
    private void saveBatchConfig(Long itemId, MdmItemSaveReqVO reqVO) {
        // 检查是否有批次配置数据
        if (reqVO.getProduceDateFlag() == null
                && reqVO.getExpireDateFlag() == null
                && reqVO.getReceiptDateFlag() == null
                && reqVO.getVendorFlag() == null
                && reqVO.getPurchaseOrderCodeFlag() == null
                && reqVO.getLotNumberFlag() == null
                && reqVO.getQualityStatusFlag() == null) {
            return;
        }
        // 查询已有配置
        cn.iocoder.yudao.module.mdm.dal.dataobject.item.MdmItemBatchConfigDO existing =
                itemBatchConfigMapper.selectOne(
                        cn.iocoder.yudao.module.mdm.dal.dataobject.item.MdmItemBatchConfigDO::getItemId, itemId);
        cn.iocoder.yudao.module.mdm.dal.dataobject.item.MdmItemBatchConfigDO config =
                new cn.iocoder.yudao.module.mdm.dal.dataobject.item.MdmItemBatchConfigDO();
        config.setItemId(itemId);
        config.setProduceDateFlag(Boolean.TRUE.equals(reqVO.getProduceDateFlag()));
        config.setExpireDateFlag(Boolean.TRUE.equals(reqVO.getExpireDateFlag()));
        config.setReceiptDateFlag(Boolean.TRUE.equals(reqVO.getReceiptDateFlag()));
        config.setVendorFlag(Boolean.TRUE.equals(reqVO.getVendorFlag()));
        config.setPurchaseOrderCodeFlag(Boolean.TRUE.equals(reqVO.getPurchaseOrderCodeFlag()));
        config.setLotNumberFlag(Boolean.TRUE.equals(reqVO.getLotNumberFlag()));
        config.setQualityStatusFlag(Boolean.TRUE.equals(reqVO.getQualityStatusFlag()));
        // 清空不需要的字段
        config.setClientFlag(false);
        config.setSalesOrderCodeFlag(false);
        config.setWorkOrderFlag(false);
        config.setTaskFlag(false);
        config.setWorkstationFlag(false);
        config.setToolFlag(false);
        config.setMoldFlag(false);
        if (existing != null) {
            config.setId(existing.getId());
            itemBatchConfigMapper.updateById(config);
        } else {
            itemBatchConfigMapper.insert(config);
        }
    }
}