1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package com.ruoyi.production.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.production.dto.ProductMaterialSkuDto;
import com.ruoyi.production.mapper.ProductMaterialMapper;
import com.ruoyi.production.mapper.ProductMaterialSkuMapper;
import com.ruoyi.production.pojo.ProductMaterial;
import com.ruoyi.production.pojo.ProductMaterialSku;
import com.ruoyi.production.pojo.ProductMaterialSkuImportDto;
import com.ruoyi.production.service.ProductMaterialSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
 
/**
 * <br>
 * 物料规格接口实现类
 * </br>
 *
 * @author deslrey
 * @version 1.0
 * @since 2026/03/12 10:05
 */
@Slf4j
@Service
public class ProductMaterialSkuServiceImpl
        extends ServiceImpl<ProductMaterialSkuMapper, ProductMaterialSku>
        implements ProductMaterialSkuService {
 
    @Autowired
    private ProductMaterialMapper productMaterialMapper;
 
    /**
     * 查询物料规格列表
     */
    @Override
    public Page<ProductMaterialSkuDto> productMaterialSkuList(Page<ProductMaterialSku> page, ProductMaterialSkuDto dto) {
        if (dto == null || dto.getMaterialId() == null) {
            return new Page<>();
        }
        LambdaQueryWrapper<ProductMaterialSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductMaterialSku::getMaterialId, dto.getMaterialId())
                .like(StringUtils.isNotBlank(dto.getSpecification()),
                        ProductMaterialSku::getSpecification, dto.getSpecification())
                .like(StringUtils.isNotBlank(dto.getMaterialCode()),
                        ProductMaterialSku::getMaterialCode, dto.getMaterialCode())
                .orderByAsc(ProductMaterialSku::getId);
 
        Page<ProductMaterialSku> skuPage = this.page(page, queryWrapper);
        List<ProductMaterialSku> skuList = skuPage.getRecords();
        if (skuList == null || skuList.isEmpty()) {
            return new Page<>();
        }
 
        ProductMaterial material = productMaterialMapper.selectById(dto.getMaterialId());
        String materialName = material != null ? material.getMaterialName() : null;
        String baseUnit = material != null ? material.getBaseUnit() : null;
        List<ProductMaterialSkuDto> result = new ArrayList<>(skuList.size());
        for (ProductMaterialSku sku : skuList) {
            ProductMaterialSkuDto productMaterialSkuDto = new ProductMaterialSkuDto();
            productMaterialSkuDto.setMaterialId(dto.getMaterialId());
            productMaterialSkuDto.setMaterialName(materialName);
            productMaterialSkuDto.setMaterialCode(sku.getMaterialCode());
            productMaterialSkuDto.setBaseUnit(baseUnit);
            productMaterialSkuDto.setSkuId(sku.getId());
            productMaterialSkuDto.setSpecification(sku.getSpecification());
            productMaterialSkuDto.setSupplyType(sku.getSupplyType());
            result.add(productMaterialSkuDto);
        }
        Page<ProductMaterialSkuDto> dtoPage = new Page<>();
        dtoPage.setCurrent(skuPage.getCurrent());
        dtoPage.setSize(skuPage.getSize());
        dtoPage.setTotal(skuPage.getTotal());
        dtoPage.setRecords(result);
        return dtoPage;
    }
 
    /**
     * 新增物料规格
     */
    @Override
    public void addProductMaterialSku(ProductMaterialSku sku) {
        validateProductMaterialSku(sku, false);
        // 校验物料是否存在
        ProductMaterial material = productMaterialMapper.selectById(sku.getMaterialId());
        if (material == null) {
            throw new ServiceException("物料不存在");
        }
        // 校验规格是否重复
        if (existsSameSpecification(sku.getMaterialId(), sku.getSpecification(), null)) {
            throw new ServiceException("该物料已存在相同规格");
        }
        LocalDateTime now = LocalDateTime.now();
        if (sku.getCreateTime() == null) {
            sku.setCreateTime(now);
        }
        sku.setUpdateTime(now);
 
        if (!this.save(sku)) {
            throw new ServiceException("新增物料规格失败");
        }
        log.info("新增物料规格成功 materialId={}, specification={}", sku.getMaterialId(), sku.getSpecification());
    }
 
    /**
     * 修改物料规格
     */
    @Override
    public void updateProductMaterialSku(ProductMaterialSku sku) {
        validateProductMaterialSku(sku, true);
        // 校验规格是否重复
        if (existsSameSpecification(sku.getMaterialId(), sku.getSpecification(), sku.getId())) {
            throw new ServiceException("该物料已存在相同规格");
        }
        sku.setUpdateTime(LocalDateTime.now());
        if (!this.updateById(sku)) {
            throw new ServiceException("修改物料规格失败");
        }
        log.info("修改物料规格成功 id={}", sku.getId());
    }
 
    /**
     * 删除物料规格
     */
    @Override
    public void deleteProductMaterialSku(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new ServiceException("请选择至少一条数据");
        }
        if (!this.removeByIds(ids)) {
            throw new ServiceException("删除物料规格失败");
        }
        log.info("删除物料规格成功 ids={}", ids);
    }
 
    /**
     * 参数校验
     */
    private void validateProductMaterialSku(ProductMaterialSku sku, boolean requireId) {
        if (sku == null) {
            throw new ServiceException("参数不能为空");
        }
        if (requireId && sku.getId() == null) {
            throw new ServiceException("主键ID不能为空");
        }
        if (sku.getMaterialId() == null) {
            throw new ServiceException("物料ID不能为空");
        }
        if (StringUtils.isEmpty(sku.getSpecification())) {
            throw new ServiceException("规格不能为空");
        }
    }
 
    /**
     * 校验是否存在相同规格
     */
    private boolean existsSameSpecification(Long materialId, String specification, Long excludeId) {
        LambdaQueryWrapper<ProductMaterialSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductMaterialSku::getMaterialId, materialId)
                .eq(ProductMaterialSku::getSpecification, specification);
        if (excludeId != null) {
            queryWrapper.ne(ProductMaterialSku::getId, excludeId);
        }
 
        return this.count(queryWrapper) > 0;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importProdData(MultipartFile file, Long materialId) {
        if (materialId == null) {
            throw new ServiceException("物料ID不能为空");
        }
        if (file == null || file.isEmpty()) {
            throw new ServiceException("导入文件不能为空");
        }
 
        ProductMaterial material = productMaterialMapper.selectById(materialId);
        if (material == null) {
            throw new ServiceException("物料不存在");
        }
 
        ExcelUtil<ProductMaterialSkuImportDto> excelUtil = new ExcelUtil<>(ProductMaterialSkuImportDto.class);
        List<ProductMaterialSkuImportDto> importList;
        try {
            importList = excelUtil.importExcel(file.getInputStream());
        } catch (Exception e) {
            log.error("导入物料规格Excel解析失败", e);
            throw new ServiceException("Excel解析失败");
        }
 
        if (importList == null || importList.isEmpty()) {
            throw new ServiceException("Excel没有数据");
        }
 
        Map<String, ProductMaterialSkuImportDto> specMap = new LinkedHashMap<>();
        for (ProductMaterialSkuImportDto dto : importList) {
            if (dto == null || StringUtils.isEmpty(dto.getSpecification())) {
                continue;
            }
            String specification = dto.getSpecification().trim();
            if (specification.isEmpty()) {
                continue;
            }
            specMap.putIfAbsent(specification, dto);
        }
 
        if (specMap.isEmpty()) {
            throw new ServiceException("Excel没有有效的规格数据");
        }
 
        Set<String> specifications = specMap.keySet();
 
        List<ProductMaterialSku> existList = this.list(new LambdaQueryWrapper<ProductMaterialSku>()
                .eq(ProductMaterialSku::getMaterialId, materialId)
                .in(ProductMaterialSku::getSpecification, specifications));
        Map<String, ProductMaterialSku> existMap = existList.stream()
                .collect(Collectors.toMap(ProductMaterialSku::getSpecification, sku -> sku, (a, b) -> a));
 
        LocalDateTime now = LocalDateTime.now();
        List<ProductMaterialSku> saveList = new ArrayList<>();
        List<ProductMaterialSku> updateList = new ArrayList<>();
 
        for (Map.Entry<String, ProductMaterialSkuImportDto> entry : specMap.entrySet()) {
            String specification = entry.getKey();
            ProductMaterialSkuImportDto dto = entry.getValue();
            String supplyType = StringUtils.isNotEmpty(dto.getSupplyType()) ? dto.getSupplyType().trim() : null;
 
            ProductMaterialSku exist = existMap.get(specification);
            if (exist == null) {
                ProductMaterialSku sku = new ProductMaterialSku();
                sku.setMaterialId(materialId);
                sku.setSpecification(specification);
                sku.setSupplyType(supplyType);
                sku.setCreateTime(now);
                sku.setUpdateTime(now);
                saveList.add(sku);
            } else {
                boolean needUpdate = false;
                if (supplyType != null && !supplyType.equals(exist.getSupplyType())) {
                    exist.setSupplyType(supplyType);
                    needUpdate = true;
                }
                if (needUpdate) {
                    exist.setUpdateTime(now);
                    updateList.add(exist);
                }
            }
        }
 
        if (saveList.isEmpty() && updateList.isEmpty()) {
            throw new ServiceException("Excel与现有数据一致,无需导入");
        }
 
        if (!saveList.isEmpty()) {
            this.saveBatch(saveList);
        }
        if (!updateList.isEmpty()) {
            this.updateBatchById(updateList);
        }
 
        log.info("物料规格导入完成 materialId={}, 新增{}条,更新{}条", materialId, saveList.size(), updateList.size());
    }
}