liyong
4 天以前 be5783c8a7e13bbc76d33c95643d75779cce21db
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package cn.iocoder.yudao.module.mes.service.qc.oqc;
 
import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.mes.controller.admin.qc.oqc.vo.MesQcOqcPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.qc.oqc.vo.MesQcOqcSaveReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.qc.defectrecord.MesQcDefectRecordDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.qc.oqc.MesQcOqcDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.qc.template.MesQcTemplateItemDO;
import cn.iocoder.yudao.module.mes.dal.mysql.qc.oqc.MesQcOqcMapper;
import cn.iocoder.yudao.module.mes.enums.qc.MesQcDefectLevelEnum;
import cn.iocoder.yudao.module.mes.enums.qc.MesQcStatusEnum;
import cn.iocoder.yudao.module.mes.enums.qc.MesQcTypeEnum;
import cn.iocoder.yudao.module.mes.enums.MesBizTypeConstants;
import cn.iocoder.yudao.module.mes.service.md.item.MesMdItemService;
import cn.iocoder.yudao.module.mes.service.qc.defectrecord.MesQcDefectRecordService;
import cn.iocoder.yudao.module.mes.service.qc.indicatorresult.MesQcIndicatorResultService;
import cn.iocoder.yudao.module.mes.service.qc.template.MesQcTemplateItemService;
import cn.iocoder.yudao.module.mes.service.wm.productsales.MesWmProductSalesLineService;
import cn.iocoder.yudao.module.mes.service.wm.productsales.MesWmProductSalesService;
import cn.iocoder.yudao.module.mes.dal.dataobject.wm.productsales.MesWmProductSalesDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.wm.productsales.MesWmProductSalesLineDO;
import cn.iocoder.yudao.module.crm.api.customer.CrmCustomerApi;
import cn.iocoder.yudao.module.mdm.api.item.MdmItemApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
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.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;
 
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.mes.enums.ErrorCodeConstants.*;
 
/**
 * MES 出货检验单(OQC) Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class MesQcOqcServiceImpl implements MesQcOqcService {
 
    @Resource
    private MesQcOqcMapper oqcMapper;
 
    @Resource
    private MesQcTemplateItemService templateItemService;
    @Resource
    private MesQcOqcLineService oqcLineService;
    @Resource
    @Lazy
    private MesQcDefectRecordService defectRecordService;
    @Resource
    @Lazy
    private MesMdItemService itemService;
    @Resource
    @Lazy
    private MesWmProductSalesLineService productSalesLineService;
    @Resource
    @Lazy
    private MesWmProductSalesService productSalesService;
    @Resource
    @Lazy
    private MesQcIndicatorResultService indicatorResultService;
 
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private MdmItemApi mdmItemApi;
    @Resource
    private CrmCustomerApi customerApi;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOqc(MesQcOqcSaveReqVO createReqVO) {
        // 1.1 校验数据
        validateOqcSaveData(createReqVO);
        // 1.2 校验来源单据参数,并验证数据存在
        String sourceDocCode = validateAndGetSourceDocCode(
                createReqVO.getSourceDocType(), createReqVO.getSourceLineId());
        // 1.3 根据产品 + 检验类型自动匹配模板
        MesQcTemplateItemDO templateItem = templateItemService.getRequiredTemplateByItemIdAndType(
                createReqVO.getItemId(), MesQcTypeEnum.OQC.getType());
        Long templateId = templateItem.getTemplateId();
 
        // 2. 插入主表
        MesQcOqcDO oqc = BeanUtils.toBean(createReqVO, MesQcOqcDO.class)
                .setTemplateId(templateId)
                .setSourceDocCode(sourceDocCode)
                .setStatus(MesQcStatusEnum.DRAFT.getStatus());
        oqcMapper.insert(oqc);
 
        // 3. 从模板指标自动生成检验行
        oqcLineService.createLinesFromTemplate(oqc.getId(), templateId);
        return oqc.getId();
    }
 
    @Override
    public void updateOqc(MesQcOqcSaveReqVO updateReqVO) {
        // 1.1 校验存在 + 草稿状态
        validateOqcStatusPrepare(updateReqVO.getId());
        // 1.2 校验数据
        validateOqcSaveData(updateReqVO);
 
        // 2. 更新
        MesQcOqcDO updateObj = BeanUtils.toBean(updateReqVO, MesQcOqcDO.class);
        updateObj.setSourceDocType(null).setSourceDocId(null).setSourceLineId(null); // 不允许修改来源单据
        updateObj.setTemplateId(null); // 不允许修改模板
        updateObj.setItemId(null); // 不允许修改物料
        oqcMapper.updateById(updateObj);
    }
 
    private void validateOqcSaveData(MesQcOqcSaveReqVO reqVO) {
        // 校验编号唯一
        validateOqcCodeUnique(reqVO.getId(), reqVO.getCode());
        // 校验物料、检测人员存在
        // 注:客户 ID 来自 CRM,不需要在 MES 中校验
        itemService.validateItemExists(reqVO.getItemId());
        adminUserApi.validateUser(reqVO.getInspectorUserId());
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finishOqc(Long id) {
        // 1.1 校验存在 + 草稿状态
        MesQcOqcDO oqc = validateOqcStatusPrepare(id);
        // 1.2 校验检测结论必填
        if (oqc.getCheckResult() == null) {
            throw exception(QC_OQC_CHECK_RESULT_EMPTY);
        }
        // 1.3 校验至少存在一条检测结果
        indicatorResultService.validateIndicatorResultExistsByQcIdAndType(id, MesQcTypeEnum.OQC.getType());
 
        // 2. 更新状态为已完成
        MesQcOqcDO updateObj = new MesQcOqcDO()
                .setId(id).setStatus(MesQcStatusEnum.FINISHED.getStatus());
        oqcMapper.updateById(updateObj);
 
        // 3. 回写来源单据
        writeBackSourceDoc(oqc);
    }
 
    /**
     * 回写来源单据(OQC 完成后)
     *
     * <p>当来源为销售出库单时,调用
     * {@link MesWmProductSalesLineService#updateProductSalesLineWhenOqcFinish}
     * 回写行的 oqcId、qualityStatus,并由该方法内部联动检查出库单整体状态
     *
     * @param oqc 出货检验单
     */
    private void writeBackSourceDoc(MesQcOqcDO oqc) {
        if (oqc.getSourceDocType() == null) {
            return;
        }
        if (oqc.getSourceLineId() == null) {
            throw new IllegalArgumentException(
                    "OQC 单[" + oqc.getId() + "] sourceDocType 非空但 sourceLineId 为空");
        }
 
        if (Objects.equals(oqc.getSourceDocType(), MesBizTypeConstants.WM_PRODUCT_SALES)) {
            productSalesLineService.updateProductSalesLineWhenOqcFinish(
                    oqc.getSourceLineId(), oqc.getId(), oqc.getCheckResult());
        } else {
            throw new IllegalArgumentException(
                    "OQC 单[" + oqc.getId() + "] sourceDocType=" + oqc.getSourceDocType() + " 无法识别,无法回写来源单据");
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOqc(Long id) {
        // 1. 校验存在 + 草稿状态
        validateOqcStatusPrepare(id);
 
        // 2.1 删除主表
        oqcMapper.deleteById(id);
        // 2.2 级联删除行
        oqcLineService.deleteByOqcId(id);
        // 2.3 级联删除缺陷记录
        defectRecordService.deleteListByQcTypeAndQcId(MesQcTypeEnum.OQC.getType(), id);
    }
 
    @Override
    public MesQcOqcDO validateOqcExists(Long id) {
        MesQcOqcDO oqc = oqcMapper.selectById(id);
        if (oqc == null) {
            throw exception(QC_OQC_NOT_EXISTS);
        }
        return oqc;
    }
 
    /**
     * 校验出货检验单存在且为草稿状态
     */
    private MesQcOqcDO validateOqcStatusPrepare(Long id) {
        MesQcOqcDO oqc = validateOqcExists(id);
        if (ObjUtil.notEqual(oqc.getStatus(), MesQcStatusEnum.DRAFT.getStatus())) {
            throw exception(QC_OQC_NOT_PREPARE);
        }
        return oqc;
    }
 
    private void validateOqcCodeUnique(Long id, String code) {
        MesQcOqcDO oqc = oqcMapper.selectByCode(code);
        if (oqc == null) {
            return;
        }
        if (ObjUtil.notEqual(oqc.getId(), id)) {
            throw exception(QC_OQC_CODE_DUPLICATE);
        }
    }
 
    /**
     * 校验来源单据参数,并验证数据存在
     *
     * @param sourceDocType 来源单据类型
     * @param sourceLineId  来源单据行 ID
     * @return 来源单据编号
     */
    private String validateAndGetSourceDocCode(Integer sourceDocType, Long sourceLineId) {
        if (sourceDocType == null || sourceLineId == null) {
            return null;
        }
        if (Objects.equals(sourceDocType, MesBizTypeConstants.WM_PRODUCT_SALES)) {
            MesWmProductSalesLineDO salesLine = productSalesLineService.validateProductSalesLineExists(sourceLineId);
            if (salesLine.getSalesId() != null) {
                MesWmProductSalesDO sales = productSalesService.getProductSales(salesLine.getSalesId());
                return sales != null ? sales.getCode() : null;
            }
            return null;
        }
        // 未知来源类型应报错,而不是静默忽略
        throw exception(QC_OQC_SOURCE_DOC_TYPE_UNKNOWN);
    }
 
    @Override
    public MesQcOqcDO getOqc(Long id) {
        return oqcMapper.selectById(id);
    }
 
    @Override
    public PageResult<MesQcOqcDO> getOqcPage(MesQcOqcPageReqVO pageReqVO) {
        // 获取用户有权限的客户 ID 列表
        List<Long> permittedClientIds = customerApi.getPermittedCustomerIds();
        return oqcMapper.selectPage(pageReqVO, permittedClientIds);
    }
 
    @Override
    public void recalculateDefectStats(Long oqcId, List<MesQcDefectRecordDO> records) {
        // 1. 行级缺陷统计
        oqcLineService.recalculateLineDefectStats(oqcId, records);
 
        // 2.1 汇总主表的缺陷数量
        int totalCritical = 0, totalMajor = 0, totalMinor = 0;
        for (MesQcDefectRecordDO record : records) {
            int quantity = ObjUtil.defaultIfNull(record.getQuantity(), 1);
            if (Objects.equals(record.getLevel(), MesQcDefectLevelEnum.CRITICAL.getType())) {
                totalCritical += quantity;
            } else if (Objects.equals(record.getLevel(), MesQcDefectLevelEnum.MAJOR.getType())) {
                totalMajor += quantity;
            } else if (Objects.equals(record.getLevel(), MesQcDefectLevelEnum.MINOR.getType())) {
                totalMinor += quantity;
            } else {
                throw exception(QC_DEFECT_RECORD_LEVEL_UNKNOWN);
            }
        }
        // 2.2 计算缺陷率
        MesQcOqcDO oqc = validateOqcExists(oqcId);
        BigDecimal criticalRate = BigDecimal.ZERO;
        BigDecimal majorRate = BigDecimal.ZERO;
        BigDecimal minorRate = BigDecimal.ZERO;
        if (oqc.getCheckQuantity() != null && oqc.getCheckQuantity().compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal checkQty = oqc.getCheckQuantity();
            criticalRate = BigDecimal.valueOf(totalCritical).multiply(BigDecimal.valueOf(100))
                    .divide(checkQty, 2, RoundingMode.HALF_UP);
            majorRate = BigDecimal.valueOf(totalMajor).multiply(BigDecimal.valueOf(100))
                    .divide(checkQty, 2, RoundingMode.HALF_UP);
            minorRate = BigDecimal.valueOf(totalMinor).multiply(BigDecimal.valueOf(100))
                    .divide(checkQty, 2, RoundingMode.HALF_UP);
        }
        // 2.3 更新主表
        MesQcOqcDO updateOqc = new MesQcOqcDO().setId(oqcId)
                .setCriticalQuantity(totalCritical).setMajorQuantity(totalMajor).setMinorQuantity(totalMinor)
                .setCriticalRate(criticalRate).setMajorRate(majorRate).setMinorRate(minorRate);
        oqcMapper.updateById(updateOqc);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOqcFromProductSales(Long salesId, MesWmProductSalesLineDO line, String salesCode, Long clientId) {
        // 1. 校验物料是否配置了 OQC 检验模板
        MesQcTemplateItemDO templateItem;
        try {
            templateItem = templateItemService.getRequiredTemplateByItemIdAndType(
                    line.getItemId(), MesQcTypeEnum.OQC.getType());
        } catch (Exception e) {
            // 获取物料信息,提供更明确的错误提示
            String itemInfo = getItemInfo(line.getItemId());
            throw exception(QC_NO_TEMPLATE_FOR_ITEM, itemInfo);
        }
        Long templateId = templateItem.getTemplateId();
 
        // 2. 生成检验单编码
        String code = "OQC" + System.currentTimeMillis();
 
        // 3. 创建 OQC 主表(待检验状态,初始数量为 0)
        MesQcOqcDO oqc = new MesQcOqcDO();
        oqc.setCode(code);
        oqc.setName(salesCode + "-出货检验");
        oqc.setTemplateId(templateId);
        oqc.setSourceDocType(MesBizTypeConstants.WM_PRODUCT_SALES);
        oqc.setSourceDocId(salesId);
        oqc.setSourceLineId(line.getId());
        oqc.setSourceDocCode(salesCode);
        oqc.setClientId(clientId);
        oqc.setItemId(line.getItemId());
        oqc.setBatchCode(line.getBatchCode());
        oqc.setOutQuantity(line.getQuantity());
        oqc.setCheckQuantity(BigDecimal.ZERO); // 待填写
        oqc.setQualifiedQuantity(BigDecimal.ZERO); // 待填写
        oqc.setUnqualifiedQuantity(BigDecimal.ZERO); // 待填写
        oqc.setOutDate(java.time.LocalDateTime.now());
        oqc.setStatus(MesQcStatusEnum.DRAFT.getStatus());
        oqcMapper.insert(oqc);
 
        // 4. 从模板指标自动生成检验行
        oqcLineService.createLinesFromTemplate(oqc.getId(), templateId);
 
        return oqc.getId();
    }
 
    /**
     * 获取物料信息(编码+名称)
     */
    private String getItemInfo(Long itemId) {
        if (itemId == null) {
            return "未知物料";
        }
        try {
            cn.iocoder.yudao.module.mdm.api.item.dto.MdmItemRespDTO item = mdmItemApi.getItem(itemId).getCheckedData();
            if (item != null) {
                return item.getCode() + "-" + item.getName();
            }
        } catch (Exception e) {
            // 忽略异常
        }
        return "物料ID:" + itemId;
    }
 
}