云
5 天以前 9265065bea5a40bcaced67857cb3ba22324ce06c
yudao-module-mes/src/main/java/cn/iocoder/yudao/module/mes/service/qc/ipqc/MesQcIpqcServiceImpl.java
@@ -9,6 +9,7 @@
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.framework.operatelog.core.util.OperateLogUtils;
import cn.iocoder.yudao.module.mes.controller.admin.qc.ipqc.vo.MesQcIpqcImportExcelVO;
import cn.iocoder.yudao.module.mes.controller.admin.qc.ipqc.vo.MesQcIpqcPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.qc.ipqc.vo.MesQcIpqcSaveReqVO;
@@ -44,6 +45,7 @@
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.system.api.user.AdminUserApi;
import com.mzt.logapi.starter.annotation.LogRecord;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
@@ -62,6 +64,7 @@
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.mes.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.mes.enums.LogRecordConstants.*;
/**
 * MES 过程检验单(IPQC) Service 实现类
@@ -72,6 +75,9 @@
@Validated
@Slf4j
public class MesQcIpqcServiceImpl implements MesQcIpqcService {
    @Resource
    private cn.iocoder.yudao.module.mes.service.qc.MesQcCompletionHelper completionHelper;
    /**
     * IPQC 保存数据校验上下文
@@ -128,6 +134,10 @@
    @Resource
    private MesQcImportHelper qcImportHelper;
    @Resource
    private cn.iocoder.yudao.module.mes.service.qc.template.MesQcTemplateProcessService templateProcessService;
    @Resource
    private cn.iocoder.yudao.module.mes.service.md.autocode.MesMdAutoCodeRecordService autoCodeRecordService;
    @Override
    @Transactional(rollbackFor = Exception.class)
@@ -136,40 +146,75 @@
        SaveDataContext ctx = validateIpqcSaveData(createReqVO);
        // 1.2 校验工单存在
        MesProWorkOrderDO workOrder = workOrderService.validateWorkOrderExists(createReqVO.getWorkOrderId());
        // 1.3 确定检验物料:有任务时取任务的物料,无任务时取工单的产品
        Long itemId = (ctx.task() != null) ? ctx.task().getItemId() : workOrder.getProductId();
        // 1.4 根据物料 + IPQC 类型查找可用质检方案(支持前端显式指定)
        List<MesQcTemplateItemDO> templateItems = templateItemService.getTemplateItemList(
                itemId, 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 确定检验物料:手工选择优先;否则有任务时取任务物料,无任务时取工单产品
        Long itemId = createReqVO.getItemId() != null ? createReqVO.getItemId()
                : (ctx.task() != null) ? ctx.task().getItemId() : workOrder.getProductId();
        // 新建质检单不依赖质检方案。
        // 1.5 获取来源单据编号
        String sourceDocCode = validateAndGetSourceDocCode(
                createReqVO.getSourceDocType(), createReqVO.getSourceDocId(), createReqVO.getSourceLineId());
        // 2. 插入主表
        // 2. 插入主表(未指定质检方案时,按工序默认绑定解析)
        Long processId = createReqVO.getProcessId() != null ? createReqVO.getProcessId()
                : getProcessId(itemId, ctx.workstation() != null ? ctx.workstation().getProcessId() : null);
        Long templateId = createReqVO.getTemplateId() != null ? createReqVO.getTemplateId()
                : templateProcessService.resolveTemplateId(processId, MesQcTypeEnum.IPQC.getType());
        String reelNo = StrUtil.isNotBlank(createReqVO.getReelNo()) ? createReqVO.getReelNo()
                : workOrder.getReelNo();
        MesQcIpqcDO ipqc = BeanUtils.toBean(createReqVO, MesQcIpqcDO.class)
                .setItemId(itemId)
                .setProcessId(getProcessId(itemId, ctx.workstation().getProcessId()))
                .setReelNo(reelNo)
                .setProcessId(processId)
                .setTemplateId(templateId)
                .setSourceDocCode(sourceDocCode)
                .setStatus(MesQcStatusEnum.DRAFT.getStatus());
        ipqcMapper.insert(ipqc);
        // 3. 从模板指标自动生成检验行
        ipqcLineService.createLinesFromTemplate(ipqc.getId(), templateId);
        // 3. 按质检方案生成检测指标行,前端直接带出需要填写的字段
        if (templateId != null) {
            ipqcLineService.createLinesFromTemplate(ipqc.getId(), templateId);
        }
        return ipqc.getId();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createInspectionForFeedback(MesProFeedbackDO feedback) {
        // 已存在关联检验单时直接复用,避免重复生成
        List<MesQcIpqcDO> existingList = ipqcMapper.selectListBySourceDoc(
                MesBizTypeConstants.PRO_FEEDBACK, feedback.getId());
        if (CollUtil.isNotEmpty(existingList)) {
            return existingList.get(0).getId();
        }
        MesProWorkOrderDO workOrder = workOrderService.getWorkOrder(feedback.getWorkOrderId());
        if (workOrder == null) {
            throw exception(PRO_WORK_ORDER_NOT_EXISTS);
        }
        BigDecimal quantity = ObjectUtil.defaultIfNull(feedback.getFeedbackQuantity(), BigDecimal.ZERO);
        MesQcIpqcSaveReqVO reqVO = new MesQcIpqcSaveReqVO();
        reqVO.setCode(autoCodeRecordService.generateAutoCode(MesMdAutoCodeRuleCodeEnum.QC_IPQC_CODE.getCode()));
        reqVO.setName(StrUtil.format("报工单[{}]过程检验", feedback.getCode()));
        reqVO.setType(MesQcTypeEnum.IPQC.getType());
        reqVO.setSourceDocType(MesBizTypeConstants.PRO_FEEDBACK);
        reqVO.setSourceDocId(feedback.getId());
        reqVO.setWorkOrderId(feedback.getWorkOrderId());
        reqVO.setTaskId(feedback.getTaskId());
        reqVO.setWorkstationId(feedback.getWorkstationId());
        reqVO.setProcessId(feedback.getProcessId());
        // 报工单已明确工序,直接按「工序 + 过程检验」解析默认质检方案,避免工位缺失时生成空检验单
        reqVO.setTemplateId(templateProcessService.resolveTemplateId(
                feedback.getProcessId(), MesQcTypeEnum.IPQC.getType()));
        reqVO.setItemId(feedback.getItemId());
        // 默认检测数量取报工数量,默认为全部合格,质检填写时再调整不合格数量
        reqVO.setCheckQuantity(quantity);
        reqVO.setQualifiedQuantity(quantity);
        reqVO.setUnqualifiedQuantity(BigDecimal.ZERO);
        reqVO.setLaborScrapQuantity(BigDecimal.ZERO);
        reqVO.setMaterialScrapQuantity(BigDecimal.ZERO);
        reqVO.setOtherScrapQuantity(BigDecimal.ZERO);
        reqVO.setInspectDate(java.time.LocalDateTime.now());
        reqVO.setInspectorUserId(cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId());
        reqVO.setRemark(StrUtil.format("报工提交自动生成,工序 ID={}", feedback.getProcessId()));
        return createIpqc(reqVO);
    }
    @Override
@@ -186,31 +231,42 @@
        updateObj.setTemplateId(null); // 不允许修改模板
        updateObj.setItemId(null); // 不允许修改物料
        updateObj.setWorkOrderId(null); // 不允许修改工单
        updateObj.setProcessId(getProcessId(existIpqc.getItemId(), ctx.workstation().getProcessId()));
        updateObj.setProcessId(updateReqVO.getProcessId() != null ? updateReqVO.getProcessId()
                : getProcessId(existIpqc.getItemId(), ctx.workstation() != null ? ctx.workstation().getProcessId() : null));
        if (StrUtil.isBlank(updateReqVO.getReelNo())) {
            updateObj.setReelNo(null); // 未填写盘号时保留原值
        }
        ipqcMapper.updateById(updateObj);
    }
    private SaveDataContext validateIpqcSaveData(MesQcIpqcSaveReqVO reqVO) {
        // 校验编号唯一
        validateIpqcCodeUnique(reqVO.getId(), reqVO.getCode());
        // 校验工位、检测人员存在
        MesMdWorkstationDO workstation = workstationService.validateWorkstationExists(reqVO.getWorkstationId());
        // 校验工位、检测人员存在(手工指定工序时工位可不填)
        MesMdWorkstationDO workstation = reqVO.getWorkstationId() != null
                ? workstationService.validateWorkstationExists(reqVO.getWorkstationId()) : null;
        if (workstation == null && reqVO.getProcessId() == null) {
            throw exception(QC_IPQC_PROCESS_REQUIRED);
        }
        adminUserApi.validateUser(reqVO.getInspectorUserId());
        // 校验工单存在
        MesProWorkOrderDO workOrder = workOrderService.validateWorkOrderConfirmed(reqVO.getWorkOrderId());
        if (reqVO.getProcessId() != null && ObjUtil.notEqual(workstation.getProcessId(), reqVO.getProcessId())) {
        MesProWorkOrderDO workOrder = workOrderService.validateWorkOrderExists(reqVO.getWorkOrderId());
        if (!Objects.equals(workOrder.getStatus(), cn.iocoder.yudao.module.mes.enums.pro.MesProWorkOrderStatusEnum.CONFIRMED.getStatus())
                && !Objects.equals(workOrder.getStatus(), cn.iocoder.yudao.module.mes.enums.pro.MesProWorkOrderStatusEnum.FINISHED.getStatus())) {
            throw exception(QC_IPQC_WORK_ORDER_STATUS_INVALID);
        }
        if (workstation != null && reqVO.getProcessId() != null
                && ObjUtil.notEqual(workstation.getProcessId(), reqVO.getProcessId())) {
            throw exception(PRO_WORKSTATION_PROCESS_MISMATCH);
        }
        // 校验任务关系(如果指定了任务)
        MesProTaskDO task = null;
        if (reqVO.getTaskId() != null) {
            task = taskService.validateTaskNotFinished(reqVO.getTaskId());
            validateTaskRelation(task, workstation, workOrder, reqVO);
        } else {
            // 无任务时,itemId 仍需与工单产品一致
            if (reqVO.getItemId() != null && ObjUtil.notEqual(reqVO.getItemId(), workOrder.getProductId())) {
                throw exception(PRO_WORK_ORDER_PRODUCT_MISMATCH);
            task = taskService.validateTaskExists(reqVO.getTaskId());
            if (Objects.equals(task.getStatus(), cn.iocoder.yudao.module.mes.enums.pro.MesProTaskStatusEnum.CANCELED.getStatus())) {
                throw exception(PRO_TASK_ALREADY_FINISHED);
            }
            validateTaskRelation(task, workstation, workOrder, reqVO);
        }
        return new SaveDataContext(workstation, task);
    }
@@ -220,10 +276,11 @@
        if (ObjUtil.notEqual(task.getWorkOrderId(), workOrder.getId())) {
            throw exception(PRO_TASK_WORK_ORDER_MISMATCH);
        }
        if (ObjUtil.notEqual(task.getWorkstationId(), workstation.getId())) {
        if (workstation != null && ObjUtil.notEqual(task.getWorkstationId(), workstation.getId())) {
            throw exception(PRO_TASK_WORKSTATION_MISMATCH);
        }
        Long expectedProcessId = reqVO.getProcessId() != null ? reqVO.getProcessId() : workstation.getProcessId();
        Long expectedProcessId = reqVO.getProcessId() != null ? reqVO.getProcessId()
                : workstation != null ? workstation.getProcessId() : null;
        if (expectedProcessId != null && ObjUtil.notEqual(task.getProcessId(), expectedProcessId)) {
            throw exception(PRO_TASK_ROUTE_PROCESS_MISMATCH);
        }
@@ -236,18 +293,16 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finishIpqc(Long id) {
        completionHelper.lockDocument("ipqc", 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());
        int result = completionHelper.validateAndGetResult("ipqc", id, ipqc.getQualifiedQuantity(), ipqc.getUnqualifiedQuantity(), ipqc.getCheckQuantity());
        ipqc.setCheckResult(result);
        // 2. 更新状态为已完成
        ipqcMapper.updateById(new MesQcIpqcDO()
                .setId(id).setStatus(MesQcStatusEnum.FINISHED.getStatus()));
                .setId(id).setStatus(MesQcStatusEnum.FINISHED.getStatus()).setCheckResult(result));
        // 3. 不合格时自动创建 NCR
        generateNcrIfNeeded(ipqc);
@@ -292,20 +347,19 @@
        Long sourceDocId = ipqc.getSourceDocId();
        Long sourceLineId = ipqc.getSourceLineId();
        // 如果 IPQC 单没有设置来源,尝试通过 taskId 查找关联的待检验报工
        if (sourceDocId == null && ipqc.getTaskId() != null) {
            MesProFeedbackDO feedback = feedbackService.getFeedbackListByTaskId(ipqc.getTaskId()).stream()
                    .filter(f -> MesProFeedbackStatusEnum.UNCHECK.getStatus().equals(f.getStatus()))
                    .findFirst().orElse(null);
            if (feedback != null) {
                sourceDocId = feedback.getId();
                log.info("[writeBackSourceDoc] IPQC({}) 未设置来源单据,通过 taskId({}) 找到待检验报工({})",
                        ipqc.getId(), ipqc.getTaskId(), feedback.getId());
            }
        }
        if (sourceDocId == null) {
        // 独立检验不推测关联报工:同一任务可能有多次报工和不同盘号。
        if (ipqc.getSourceDocType() == null && sourceDocId == null && sourceLineId == null) {
            log.warn("[writeBackSourceDoc] IPQC({}) 无法确定来源报工,跳过回写", ipqc.getId());
            return;
        }
        if (!Objects.equals(ipqc.getSourceDocType(), MesBizTypeConstants.PRO_FEEDBACK)
                || sourceDocId == null) {
            throw new IllegalArgumentException("过程检验的报工来源不完整");
        }
        // 报工审批前的过程检验(由报工提交自动生成):只记录检验结果供审批做质量工资调整,
        // 此时尚未生成产出行,不做产出行拆分与报工状态回写
        if (sourceLineId == null) {
            log.info("[writeBackSourceDoc] IPQC({}) 无产出行(报工审批前检验),跳过回写", ipqc.getId());
            return;
        }
@@ -472,10 +526,14 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    @LogRecord(type = MES_QC_IPQC_TYPE, subType = MES_QC_IPQC_IMPORT_SUB_TYPE, bizNo = "0",
            success = MES_QC_IPQC_IMPORT_SUCCESS)
    public MesQcImportRespVO importIpqcList(List<MesQcIpqcImportExcelVO> importList) {
        MesQcImportRespVO respVO = MesQcImportRespVO.builder()
                .createList(new ArrayList<>()).failureList(new LinkedHashMap<>()).build();
        if (CollUtil.isEmpty(importList)) {
            // 空文件也要给日志文案兜底,避免 {{#importSummary}} 取不到值
            OperateLogUtils.putImportSummary(respVO.getCreateList(), null, respVO.getFailureList());
            return respVO;
        }
        qcImportHelper.startImport();
@@ -499,6 +557,8 @@
                respVO.getFailureList().put(label, MesQcImportHelper.resolveImportErrorMessage(ex));
            }
        }
        // 记录导入结果汇总,供 @LogRecord 的 success 文案引用
        OperateLogUtils.putImportSummary(respVO.getCreateList(), null, respVO.getFailureList());
        return respVO;
    }