gongchunyi
2 天以前 2a4b95fd5718712ab08f63db49702dbbab2a158d
fix: 添加产品导入模板,基础产品导入修改
已添加1个文件
已修改5个文件
260 ■■■■ 文件已修改
src/main/java/com/ruoyi/basic/controller/ProductController.java 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/basic/service/IProductModelService.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/basic/service/IProductService.java 5 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/basic/service/impl/ProductModelServiceImpl.java 200 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/basic/service/impl/ProductServiceImpl.java 44 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/resources/static/产品导入模板.xlsx 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/basic/controller/ProductController.java
@@ -5,13 +5,11 @@
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.basic.dto.ProductDto;
import com.ruoyi.basic.dto.ProductModelDto;
import com.ruoyi.basic.dto.ProductModelExportDto;
import com.ruoyi.basic.dto.ProductTreeDto;
import com.ruoyi.basic.pojo.ProductModel;
import com.ruoyi.basic.service.IProductModelService;
import com.ruoyi.basic.service.IProductService;
import com.ruoyi.basic.vo.ProductModelVo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
@@ -125,8 +123,8 @@
     */
    @PostMapping("/import")
    @Log(title = "导入产品", businessType = BusinessType.IMPORT)
    public AjaxResult importProductModel(@RequestParam("file") MultipartFile file, Integer productId) {
        return productModelService.importProductModel(file, productId);
    public AjaxResult importProductModel(@RequestParam("file") MultipartFile file) {
        return productModelService.importProductModel(file);
    }
    /**
@@ -136,7 +134,6 @@
    @Operation(summary = "产品导入模板")
    @Log(title = "产品导入模板", businessType = BusinessType.EXPORT)
    public void importProduct(HttpServletResponse response) {
        ExcelUtil<ProductModelExportDto> excelUtil = new ExcelUtil<>(ProductModelExportDto.class);
        excelUtil.importTemplateExcel(response, "产品规格导入模板");
        productService.exportImportTemplate(response);
    }
}
src/main/java/com/ruoyi/basic/service/IProductModelService.java
@@ -34,5 +34,5 @@
     */
    IPage<ProductModel> modelListPage(Page page , ProductDto productDto);
    AjaxResult importProductModel(MultipartFile file, Integer productId);
    AjaxResult importProductModel(MultipartFile file);
}
src/main/java/com/ruoyi/basic/service/IProductService.java
@@ -8,11 +8,12 @@
import com.ruoyi.basic.pojo.Product;
import com.ruoyi.basic.pojo.ProductModel;
import com.ruoyi.basic.vo.ProductModelVo;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
public interface IProductService extends IService<Product> {
    int addOrEditProduct(ProductDto productDto);
    int delProductByIds(Long[] ids);
@@ -20,4 +21,6 @@
    List<ProductTreeDto> selectProductList(ProductDto productDto);
    IPage<ProductModelVo> listPageProductModel(Page<ProductModelVo> page, ProductModel productModel);
    void exportImportTemplate(HttpServletResponse response);
}
src/main/java/com/ruoyi/basic/service/impl/ProductModelServiceImpl.java
@@ -7,6 +7,7 @@
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.dto.ProductDto;
import com.ruoyi.basic.dto.ProductImportRowDto;
import com.ruoyi.basic.dto.ProductModelDto;
import com.ruoyi.basic.mapper.ProductMapper;
import com.ruoyi.basic.mapper.ProductModelMapper;
@@ -18,7 +19,6 @@
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.sales.dto.LossProductModelDto;
import com.ruoyi.sales.mapper.SalesLedgerProductMapper;
import com.ruoyi.sales.pojo.SalesLedgerProduct;
import com.ruoyi.technology.mapper.TechnologyBomMapper;
@@ -28,11 +28,13 @@
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.concurrent.ThreadLocalRandom;
/**
 * ã€è¯·å¡«å†™åŠŸèƒ½åç§°ã€‘Service业务层处理
@@ -48,6 +50,8 @@
    private final SalesLedgerProductMapper salesLedgerProductMapper;
    private final TechnologyBomMapper technologyBomMapper;
    private ProductModelMapper productModelMapper;
    private static final List<String> IMPORT_SHEET_NAMES = Arrays.asList("原料", "半成品", "成品");
    @Override
    public int addOrEditProductModel(ProductModelDto productModelDto) {
@@ -124,69 +128,161 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importProductModel(MultipartFile file, Integer productId) {
        if (productId == null) {
            return AjaxResult.error("请先选择产品再导入规格型号");
    public AjaxResult importProductModel(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return AjaxResult.error("请选择要导入的文件");
        }
        Product product = productMapper.selectById(productId);
        if (product == null) {
            return AjaxResult.error("选择的产品不存在");
        }
        Map<String, List<ProductImportRowDto>> sheetMap;
        try {
            ExcelUtil<ProductModel> productModelExcelUtil = new ExcelUtil<>(ProductModel.class);
            List<ProductModel> productModelList = productModelExcelUtil.importExcel(file.getInputStream());
            ExcelUtil<ProductImportRowDto> excelUtil = new ExcelUtil<>(ProductImportRowDto.class);
            sheetMap = excelUtil.importExcelMultiSheet(IMPORT_SHEET_NAMES, file.getInputStream(), 0);
        } catch (Exception e) {
            log.error("解析产品导入文件异常", e);
            throw new ServiceException("产品导入文件解析失败");
        }
        if (sheetMap.isEmpty()) {
            return AjaxResult.error("未找到 [原料/半成品/成品] å·¥ä½œè¡¨ï¼Œæˆ–文件中没有数据");
        }
            if (CollectionUtils.isEmpty(productModelList)) {
                return AjaxResult.error("导入数据不能为空");
        int successCount = 0;
        int skipCount = 0;
        Set<String> generatedCodes = new HashSet<>();
        for (String sheetName : IMPORT_SHEET_NAMES) {
            List<ProductImportRowDto> rows = sheetMap.get(sheetName);
            if (CollectionUtils.isEmpty(rows)) {
                continue;
            }
            //  èŽ·å–å½“å‰äº§å“ä¸‹æ‰€æœ‰çš„è§„æ ¼åž‹å·å
            List<ProductModel> existingModels = list(new LambdaQueryWrapper<ProductModel>().eq(ProductModel::getProductId, productId));
            Set<String> existingModelNames = existingModels.stream().map(ProductModel::getModel).collect(Collectors.toSet());
            List<ProductModel> waitToSaveList = new ArrayList<>();
            int skipCount = 0;
            for (int i = 0; i < productModelList.size(); i++) {
                ProductModel item = productModelList.get(i);
            Long topId = findOrCreateTopProduct(sheetName);
            Map<String, Long> nodeCache = new HashMap<>();
            Map<Long, Set<String>> codeCache = new HashMap<>();
            for (int i = 0; i < rows.size(); i++) {
                ProductImportRowDto row = rows.get(i);
                int rowNum = i + 2;
                if (StringUtils.isEmpty(item.getProductCode())) {
                    return AjaxResult.error("第 " + rowNum + " è¡Œå¯¼å…¥å¤±è´¥: [产品编码] ä¸èƒ½ä¸ºç©º");
                String parentName = trimToNull(row.getProductParentName());
                String categoryName = trimToNull(row.getProductCategoryName());
                String productName = trimToNull(row.getProductName());
                if (categoryName == null) {
                    throw new ServiceException("第 " + rowNum + " è¡Œ [产品大类] ä¸èƒ½ä¸ºç©º");
                }
                if (StringUtils.isEmpty(item.getModel())) {
                    return AjaxResult.error("第 " + rowNum + " è¡Œå¯¼å…¥å¤±è´¥: [规格型号] ä¸èƒ½ä¸ºç©º");
                }
                if (StringUtils.isEmpty(item.getUnit())) {
                    return AjaxResult.error("第 " + rowNum + " è¡Œå¯¼å…¥å¤±è´¥: [单位] ä¸èƒ½ä¸ºç©º");
                if (productName == null) {
                    throw new ServiceException("第 " + rowNum + " è¡Œ [产品名称] ä¸èƒ½ä¸ºç©º");
                }
                //  åŽ»é‡,如果已包含该型号,则跳过
                if (existingModelNames.contains(item.getModel())) {
                String path = String.valueOf(topId);
                Long parentNodeId = topId;
                if (parentName != null) {
                    path = path + ">" + parentName;
                    parentNodeId = ensureChildNode(nodeCache, path, parentNodeId, parentName);
                }
                path = path + ">" + categoryName;
                Long categoryId = ensureChildNode(nodeCache, path, parentNodeId, categoryName);
                path = path + ">" + productName;
                Long leafId = ensureChildNode(nodeCache, path, categoryId, productName);
                String code = trimToNull(row.getProductCode());
                if (code == null) {
                    code = generateUniqueCode(generatedCodes);
                }
                Set<String> codes = codeCache.computeIfAbsent(leafId, this::loadProductCodes);
                if (!codes.add(code)) {
                    skipCount++;
                    continue;
                }
                item.setProductId(product.getId());
                waitToSaveList.add(item);
                existingModelNames.add(item.getModel());
                ProductModel productModel = new ProductModel();
                productModel.setProductId(leafId);
                productModel.setProductCode(code);
                productModel.setModel(StringUtils.isEmpty(row.getModel()) ? "/" : row.getModel().trim());
                productModel.setUnit(trimToNull(row.getUnit()));
                productModelMapper.insert(productModel);
                successCount++;
            }
            if (!waitToSaveList.isEmpty()) {
                saveBatch(waitToSaveList);
            }
            if (skipCount == 0) {
                return AjaxResult.success(String.format("成功导入 %d æ¡æ•°æ®", waitToSaveList.size()));
            } else {
                return AjaxResult.success(String.format("成功导入 %d æ¡ï¼Œè·³è¿‡å·²å­˜åœ¨æ•°æ® %d æ¡", waitToSaveList.size(), skipCount));
            }
        } catch (Exception e) {
            log.error("导入产品规格异常", e);
            throw new ServiceException("导入失败");
        }
        String message = skipCount > 0
                ? String.format("成功导入 %d æ¡ï¼Œè·³è¿‡å·²å­˜åœ¨ %d æ¡", successCount, skipCount)
                : String.format("成功导入 %d æ¡", successCount);
        return AjaxResult.success(message);
    }
    private Long findOrCreateTopProduct(String name) {
        Product root = productMapper.selectOne(new LambdaQueryWrapper<Product>()
                .isNull(Product::getParentId)
                .eq(Product::getProductName, name)
                .last("limit 1"));
        if (root != null) {
            return root.getId();
        }
        Product product = new Product();
        product.setProductName(name);
        productMapper.insert(product);
        return product.getId();
    }
    private Long ensureChildNode(Map<String, Long> nodeCache, String path, Long parentId, String name) {
        Long id = nodeCache.get(path);
        if (id != null) {
            return id;
        }
        Product existing = productMapper.selectOne(new LambdaQueryWrapper<Product>()
                .eq(Product::getParentId, parentId)
                .eq(Product::getProductName, name)
                .last("limit 1"));
        if (existing != null) {
            nodeCache.put(path, existing.getId());
            return existing.getId();
        }
        Product product = new Product();
        product.setParentId(parentId);
        product.setProductName(name);
        productMapper.insert(product);
        nodeCache.put(path, product.getId());
        return product.getId();
    }
    private Set<String> loadProductCodes(Long productId) {
        List<ProductModel> list = productModelMapper.selectList(new LambdaQueryWrapper<ProductModel>()
                .eq(ProductModel::getProductId, productId));
        Set<String> codes = new HashSet<>();
        for (ProductModel productModel : list) {
            if (productModel.getProductCode() != null) {
                codes.add(productModel.getProductCode().trim());
            }
        }
        return codes;
    }
    private String generateUniqueCode(Set<String> generatedCodes) {
        for (int i = 0; i < 200; i++) {
            String code = randomCode(5);
            if (generatedCodes.contains(code)) {
                continue;
            }
            Long count = productModelMapper.selectCount(new LambdaQueryWrapper<ProductModel>()
                    .eq(ProductModel::getProductCode, code));
            if (count == null || count == 0) {
                generatedCodes.add(code);
                return code;
            }
        }
        throw new ServiceException("生成唯一产品编码失败,请重试");
    }
    private static String randomCode(int length) {
        String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(ThreadLocalRandom.current().nextInt(chars.length())));
        }
        return sb.toString();
    }
    private static String trimToNull(String value) {
        if (value == null) {
            return null;
        }
        String trimmed = value.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }
}
src/main/java/com/ruoyi/basic/service/impl/ProductServiceImpl.java
@@ -15,15 +15,23 @@
import com.ruoyi.basic.vo.ProductModelVo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Service
@AllArgsConstructor
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    private ProductMapper productMapper;
@@ -130,16 +138,40 @@
    }
    @Override
    public void exportImportTemplate(HttpServletResponse response) {
        String templatePath = "static/产品导入模板.xlsx";
        try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(templatePath)) {
            if (inputStream == null) {
                throw new FileNotFoundException("模板文件不存在:" + templatePath);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("产品导入模板.xlsx", "utf-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
            try (OutputStream outputStream = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, len);
                }
                outputStream.flush();
            }
        } catch (IOException e) {
            log.error("导出产品导入模板失败", e);
            try {
                response.getWriter().write("模板导出失败:" + e.getMessage());
            } catch (IOException ex) {
                log.error("响应输出错误", ex);
            }
        }
    }
    @Override
    public int delProductByIds(Long[] ids) {
        // 1. åˆ é™¤å­è¡¨ product_model ä¸­å…³è”的数据
        LambdaQueryWrapper<ProductModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProductModel::getProductId, ids);
        productModelMapper.delete(queryWrapper);
        // 2. åˆ é™¤ä¸»è¡¨ product æ•°æ®
        int deleteCount = productMapper.deleteBatchIds(Arrays.asList(ids));
        return deleteCount;
        return productMapper.deleteBatchIds(Arrays.asList(ids));
    }
}
src/main/resources/static/²úÆ·µ¼ÈëÄ£°å.xlsx
Binary files differ