8 小时以前 3ce57820e618b704ce61487b7cdb38fdd6b0f44a
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
package cn.iocoder.yudao.module.mes.service.qc.ipqc;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.mes.dal.dataobject.wm.productproduce.MesWmProductProduceLineDO;
import cn.iocoder.yudao.module.mes.enums.wm.MesWmQualityStatusEnum;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.mes.controller.admin.qc.ipqc.vo.MesQcIpqcPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.qc.ipqc.vo.MesQcIpqcSaveReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.pro.feedback.MesProFeedbackDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.qc.defectrecord.MesQcDefectRecordDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.qc.ipqc.MesQcIpqcDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.qc.template.MesQcTemplateDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.qc.template.MesQcTemplateItemDO;
import cn.iocoder.yudao.module.mes.dal.mysql.qc.ipqc.MesQcIpqcMapper;
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.pro.feedback.MesProFeedbackService;
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.qc.template.MesQcTemplateService;
import cn.iocoder.yudao.module.mes.controller.admin.qc.ncr.vo.MesQcNcrSaveReqVO;
import cn.iocoder.yudao.module.mes.service.qc.ncr.MesQcNcrService;
import cn.iocoder.yudao.module.mes.service.wm.productproduce.MesWmProductProduceLineService;
import cn.iocoder.yudao.module.mdm.api.item.MdmItemApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
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 过程检验单(IPQC) Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
@Slf4j
public class MesQcIpqcServiceImpl implements MesQcIpqcService {
 
    @Resource
    private MesQcIpqcMapper ipqcMapper;
 
    @Resource
    private MesQcTemplateItemService templateItemService;
    @Resource
    @Lazy
    private MesQcTemplateService templateService;
    @Resource
    private MesQcIpqcLineService ipqcLineService;
    @Resource
    @Lazy
    private MesQcDefectRecordService defectRecordService;
    @Resource
    @Lazy
    private MesProFeedbackService feedbackService;
    @Resource
    @Lazy
    private MesQcIndicatorResultService indicatorResultService;
    @Resource
    @Lazy
    private MesWmProductProduceLineService productProduceLineService;
 
    @Resource
    @Lazy
    private MesQcNcrService ncrService;
 
    @Resource
    private AdminUserApi adminUserApi;
 
    @Resource
    private MdmItemApi mdmItemApi;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createIpqc(MesQcIpqcSaveReqVO createReqVO) {
        // 1.1 校验数据
        validateIpqcSaveData(createReqVO);
        // 1.2 根据产品物料 + IPQC 类型查找可用质检方案(支持前端显式指定)
        // 物料 ID 来自 MDM,模板服务直接按 MDM 物料匹配
        List<MesQcTemplateItemDO> templateItems = templateItemService.getTemplateItemList(
                createReqVO.getItemId(), MesQcTypeEnum.IPQC.getType(), null, null);
        if (CollUtil.isEmpty(templateItems)) {
            throw exception(QC_NO_TEMPLATE);
        }
        MesQcTemplateItemDO templateItem = templateItems.get(0);
        if (createReqVO.getTemplateId() != null) {
            templateItem = templateItems.stream()
                    .filter(available -> Objects.equals(available.getTemplateId(), createReqVO.getTemplateId()))
                    .findFirst().orElse(null);
            if (templateItem == null) {
                throw exception(QC_NO_TEMPLATE); // 指定了方案但不在匹配列表中,拒绝
            }
        }
        Long templateId = templateItem.getTemplateId();
        // 1.3 获取来源单据编号
        String sourceDocCode = validateAndGetSourceDocCode(
                createReqVO.getSourceDocType(), createReqVO.getSourceDocId(), createReqVO.getSourceLineId());
 
        // 2. 插入主表
        MesQcIpqcDO ipqc = BeanUtils.toBean(createReqVO, MesQcIpqcDO.class)
                .setTemplateId(templateId)
                .setSourceDocCode(sourceDocCode)
                .setStatus(MesQcStatusEnum.DRAFT.getStatus());
        // 执行标准:用户未填时回退模板默认值
        if (StrUtil.isBlank(ipqc.getExecuteStandard())) {
            MesQcTemplateDO template = templateService.getTemplate(templateId);
            if (template != null) {
                ipqc.setExecuteStandard(template.getDefaultExecuteStandard());
            }
        }
        ipqcMapper.insert(ipqc);
 
        // 3. 从模板指标自动生成检验行
        ipqcLineService.createLinesFromTemplate(ipqc.getId(), templateId);
        return ipqc.getId();
    }
 
    @Override
    public void updateIpqc(MesQcIpqcSaveReqVO updateReqVO) {
        // 1.1 校验存在 + 草稿状态
        validateIpqcStatusPrepare(updateReqVO.getId());
        // 1.2 校验数据
        validateIpqcSaveData(updateReqVO);
 
        // 2. 更新主表
        MesQcIpqcDO updateObj = BeanUtils.toBean(updateReqVO, MesQcIpqcDO.class);
        updateObj.setSourceDocType(null).setSourceDocId(null).setSourceLineId(null); // 不允许修改来源单据
        updateObj.setTemplateId(null); // 不允许修改模板
        updateObj.setItemId(null); // 不允许修改物料
        ipqcMapper.updateById(updateObj);
    }
 
    private void validateIpqcSaveData(MesQcIpqcSaveReqVO reqVO) {
        // 校验编号唯一
        validateIpqcCodeUnique(reqVO.getId(), reqVO.getCode());
        // 校验物料、检测人员存在
        // 注:物料 ID 来自 MDM
        mdmItemApi.validateItemExists(reqVO.getItemId());
        adminUserApi.validateUser(reqVO.getInspectorUserId());
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finishIpqc(Long id) {
        // 1.1 校验存在 + 草稿状态
        MesQcIpqcDO ipqc = validateIpqcStatusPrepare(id);
        // 1.2 校验检测结论必填
        if (ipqc.getCheckResult() == null) {
            throw exception(QC_IPQC_CHECK_RESULT_EMPTY);
        }
        // 1.3 校验至少存在一条检测结果
        indicatorResultService.validateIndicatorResultExistsByQcIdAndType(id, MesQcTypeEnum.IPQC.getType());
 
        // 2. 更新状态为已完成
        ipqcMapper.updateById(new MesQcIpqcDO()
                .setId(id).setStatus(MesQcStatusEnum.FINISHED.getStatus()));
 
        // 3. 不合格时自动创建 NCR
        generateNcrIfNeeded(ipqc);
 
        // 4. 回写来源单据
        writeBackSourceDoc(ipqc);
    }
 
    /**
     * 不合格时自动创建 NCR(不合格品处理单)
     *
     * @param ipqc 过程检验单
     */
    private void generateNcrIfNeeded(MesQcIpqcDO ipqc) {
        BigDecimal unqualifiedQty = ipqc.getUnqualifiedQuantity();
        if (unqualifiedQty == null || unqualifiedQty.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }
        String ncrCode = "NCR" + java.time.LocalDateTime.now()
                .format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        MesQcNcrSaveReqVO saveReqVO = new MesQcNcrSaveReqVO();
        saveReqVO.setCode(ncrCode);
        saveReqVO.setName("不合格品处理单");
        saveReqVO.setQcType(MesQcTypeEnum.IPQC.getType());
        saveReqVO.setQcId(ipqc.getId());
        saveReqVO.setItemId(ipqc.getItemId());
        saveReqVO.setUnqualifiedQuantity(unqualifiedQty);
        saveReqVO.setDefectDescription("由过程检验(" + ipqc.getCode() + ")自动生成");
        ncrService.createNcr(saveReqVO);
        log.info("[generateNcrIfNeeded] IPQC({}) 不合格,自动创建 NCR", ipqc.getId());
    }
 
    /**
     * 回写来源单据(IPQC 完成后)
     *
     * <p>当来源为报工时,拆分待检产出行、完成产出入库、回写报工状态和任务/工单进度
     *
     * @param ipqc 过程检验单
     */
    private void writeBackSourceDoc(MesQcIpqcDO ipqc) {
        // 1. 确定 sourceDocType/sourceDocId
        Long sourceDocId = ipqc.getSourceDocId();
        Long sourceLineId = ipqc.getSourceLineId();
        if (sourceDocId == null) {
            log.warn("[writeBackSourceDoc] IPQC({}) 未设置来源报工,跳过回写", ipqc.getId());
            return;
        }
 
        // 2. 回写报工
        feedbackService.updateProFeedbackWhenIpqcFinish(sourceDocId, sourceLineId,
                ObjectUtil.defaultIfNull(ipqc.getQualifiedQuantity(), BigDecimal.ZERO),
                ObjectUtil.defaultIfNull(ipqc.getUnqualifiedQuantity(), BigDecimal.ZERO),
                ObjectUtil.defaultIfNull(ipqc.getLaborScrapQuantity(), BigDecimal.ZERO),
                ObjectUtil.defaultIfNull(ipqc.getMaterialScrapQuantity(), BigDecimal.ZERO),
                ObjectUtil.defaultIfNull(ipqc.getOtherScrapQuantity(), BigDecimal.ZERO));
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteIpqc(Long id) {
        // 1. 校验存在 + 草稿状态
        validateIpqcStatusPrepare(id);
 
        // 2.1 删除主表
        ipqcMapper.deleteById(id);
        // 2.2 级联删除行
        ipqcLineService.deleteListByIpqcId(id);
        // 2.3 级联删除缺陷记录
        defectRecordService.deleteListByQcTypeAndQcId(MesQcTypeEnum.IPQC.getType(), id);
    }
 
    @Override
    public MesQcIpqcDO validateIpqcExists(Long id) {
        MesQcIpqcDO ipqc = ipqcMapper.selectById(id);
        if (ipqc == null) {
            throw exception(QC_IPQC_NOT_EXISTS);
        }
        return ipqc;
    }
 
    /**
     * 校验过程检验单存在且为草稿状态
     *
     * @param id 过程检验单 ID
     * @return 过程检验单
     */
    private MesQcIpqcDO validateIpqcStatusPrepare(Long id) {
        MesQcIpqcDO ipqc = validateIpqcExists(id);
        if (ObjUtil.notEqual(ipqc.getStatus(), MesQcStatusEnum.DRAFT.getStatus())) {
            throw exception(QC_IPQC_NOT_PREPARE);
        }
        return ipqc;
    }
 
    private void validateIpqcCodeUnique(Long id, String code) {
        MesQcIpqcDO ipqc = ipqcMapper.selectByCode(code);
        if (ipqc == null) {
            return;
        }
        if (ObjUtil.notEqual(ipqc.getId(), id)) {
            throw exception(QC_IPQC_CODE_DUPLICATE);
        }
    }
 
    private String validateAndGetSourceDocCode(Integer sourceDocType, Long sourceDocId, Long sourceLineId) {
        if (sourceDocType == null || sourceDocId == null) {
            return null;
        }
        if (Objects.equals(sourceDocType, MesBizTypeConstants.PRO_FEEDBACK)) {
            MesProFeedbackDO feedback = feedbackService.validateFeedbackExists(sourceDocId);
            // 校验 sourceLineId 必填
            if (sourceLineId == null) {
                throw exception(QC_IPQC_SOURCE_LINE_REQUIRED);
            }
            // 校验 sourceLineId 存在,且属于该报工的产出行
            MesWmProductProduceLineDO targetLine = productProduceLineService
                    .validateProductProduceLineExists(sourceLineId);
            if (ObjUtil.notEqual(targetLine.getFeedbackId(), sourceDocId)) {
                throw exception(QC_IPQC_SOURCE_LINE_NOT_BELONG);
            }
            // 校验该产出行为待检验状态
            if (ObjUtil.notEqual(targetLine.getQualityStatus(), MesWmQualityStatusEnum.PENDING.getStatus())) {
                throw exception(QC_IPQC_SOURCE_LINE_NOT_PENDING);
            }
            return feedback.getCode();
        }
        // 未知来源类型应报错,而不是静默忽略
        throw exception(QC_IPQC_SOURCE_DOC_TYPE_UNKNOWN);
    }
 
    @Override
    public MesQcIpqcDO getIpqc(Long id) {
        return ipqcMapper.selectById(id);
    }
 
    @Override
    public PageResult<MesQcIpqcDO> getIpqcPage(MesQcIpqcPageReqVO pageReqVO) {
        return ipqcMapper.selectPage(pageReqVO);
    }
 
    @Override
    public void recalculateDefectStats(Long ipqcId, List<MesQcDefectRecordDO> records) {
        MesQcIpqcDO ipqc = validateIpqcExists(ipqcId);
        // 1. 行级缺陷统计
        ipqcLineService.recalculateLineDefectStats(ipqcId, records);
 
        // 2.1 汇总主表的缺陷数量
        int totalCritical = 0;
        int totalMajor = 0;
        int 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 计算缺陷率
        BigDecimal criticalRate = BigDecimal.ZERO;
        BigDecimal majorRate = BigDecimal.ZERO;
        BigDecimal minorRate = BigDecimal.ZERO;
        if (ipqc.getCheckQuantity() != null && ipqc.getCheckQuantity().compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal checkQty = ipqc.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 更新主表
        MesQcIpqcDO updateIpqc = new MesQcIpqcDO().setId(ipqcId)
                .setCriticalQuantity(totalCritical).setMajorQuantity(totalMajor).setMinorQuantity(totalMinor)
                .setCriticalRate(criticalRate).setMajorRate(majorRate).setMinorRate(minorRate);
        ipqcMapper.updateById(updateIpqc);
    }
 
}