cl
5 天以前 400881f9103218313c552b254c8312b54a24f563
rsf-server/src/main/java/com/vincent/rsf/server/manager/service/impl/TaskServiceImpl.java
@@ -4,7 +4,6 @@
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.CoercionAction;
import com.fasterxml.jackson.databind.cfg.CoercionInputShape;
@@ -13,6 +12,7 @@
import com.vincent.rsf.server.api.config.RemotesInfoProperties;
import com.vincent.rsf.server.api.controller.erp.params.InOutResultReportParam;
import com.vincent.rsf.server.api.controller.erp.params.TaskInParam;
import com.vincent.rsf.server.api.service.RcsBusTaskNoticeService;
import com.vincent.rsf.server.api.entity.CommonResponse;
import com.vincent.rsf.server.api.entity.constant.RcsConstant;
import com.vincent.rsf.server.api.entity.dto.InTaskMsgDto;
@@ -27,6 +27,7 @@
import com.vincent.rsf.framework.common.R;
import com.vincent.rsf.framework.exception.CoolException;
import com.vincent.rsf.server.api.utils.LocUtils;
import com.vincent.rsf.server.manager.constant.CloudWmsInoutReportMode;
import com.vincent.rsf.server.manager.controller.params.GenerateTaskParams;
import com.vincent.rsf.server.manager.entity.CloudWmsNotifyLog;
import com.vincent.rsf.server.manager.entity.*;
@@ -55,8 +56,13 @@
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
@@ -131,6 +137,8 @@
    private CloudWmsNotifyLogService cloudWmsNotifyLogService;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private RcsBusTaskNoticeService rcsBusTaskNoticeService;
    @Override
    @Transactional(rollbackFor = Exception.class)
@@ -172,7 +180,9 @@
                throw new CoolException("任务保存失败!!");
            }
            if (!locService.update(new LambdaUpdateWrapper<Loc>().eq(Loc::getCode, task.getTargLoc())
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_S.type).set(Loc::getBarcode, pakin.getBarcode()))) {
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_S.type)
                    .set(Loc::getBarcode, pakin.getBarcode())
                    .set(Loc::getWeight, task.getWeight()))) {
                throw new CoolException("库位预约失败!!");
            }
            /**获取组拖明细**/
@@ -204,6 +214,7 @@
                    throw new CoolException("组托明细修执行数量修改失败!!");
                }
            });
            syncAsnOrderItemBarcodeByPakin(waitPakinItems, pakin.getBarcode(), loginUserId);
        });
        if (!waitPakinService.update(new LambdaUpdateWrapper<WaitPakin>()
@@ -261,7 +272,8 @@
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_S.type)
                    .set(Loc::getUpdateBy, loginUserId)
                    .set(Loc::getUpdateTime, new Date())
                    .set(Loc::getBarcode, pakin.getBarcode()))) {
                    .set(Loc::getBarcode, pakin.getBarcode())
                    .set(Loc::getWeight, task.getWeight()))) {
                throw new CoolException("库位预约失败!!");
            }
            /**获取组拖明细**/
@@ -293,6 +305,7 @@
                    throw new CoolException("组托明细修执行数量修改失败!!");
                }
            });
            syncAsnOrderItemBarcodeByPakin(waitPakinItems, pakin.getBarcode(), loginUserId);
        });
        if (!waitPakinService.update(new LambdaUpdateWrapper<WaitPakin>()
@@ -403,7 +416,9 @@
            if (!locService.update(new LambdaUpdateWrapper<Loc>().eq(Loc::getCode, task.getTargLoc())
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_S.type).set(Loc::getBarcode, pakin.getBarcode()))) {
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_S.type)
                    .set(Loc::getBarcode, pakin.getBarcode())
                    .set(Loc::getWeight, task.getWeight()))) {
                throw new CoolException("库位预约失败!!");
            }
            /**获取组拖明细**/
@@ -443,6 +458,7 @@
                    throw new CoolException("组托明细修执行数量修改失败!!");
                }
            });
            syncAsnOrderItemBarcodeByPakin(waitPakinItems, pakin.getBarcode(), loginUserId);
        });
        if (!waitPakinService.update(new LambdaUpdateWrapper<WaitPakin>()
@@ -453,6 +469,27 @@
            throw new CoolException("组拖状态修改失败!!");
        }
        return R.ok("任务生成完毕!");
    }
    /** 组托后将通知单明细条码回写为料箱码 */
    private void syncAsnOrderItemBarcodeByPakin(List<WaitPakinItem> waitPakinItems, String pakinBarcode, Long loginUserId) {
        if (waitPakinItems == null || waitPakinItems.isEmpty() || StringUtils.isBlank(pakinBarcode)) {
            return;
        }
        Set<Long> asnItemIds = waitPakinItems.stream()
                .map(WaitPakinItem::getAsnItemId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        if (asnItemIds.isEmpty()) {
            return;
        }
        if (!asnOrderItemService.update(new LambdaUpdateWrapper<WkOrderItem>()
                .in(WkOrderItem::getId, asnItemIds)
                .set(WkOrderItem::getBarcode, pakinBarcode)
                .set(WkOrderItem::getUpdateBy, loginUserId)
                .set(WkOrderItem::getUpdateTime, new Date()))) {
            throw new CoolException("通知单明细条码回写失败!!");
        }
    }
    /**
@@ -509,7 +546,7 @@
    }
    /**
     * 手动完成任务
     * 手动完成任务:入库类置 98、出库类置 198,库位/单据扣减与上报由对应定时任务执行
     *
     * @param id
     * @param loginUserId
@@ -549,13 +586,22 @@
        }
        modiftyTaskSort(task, loginUserId);
        // 如果任务状态已经是AWAIT (196),再次点击完结时,直接完成
        if (task.getTaskStatus().equals(TaskStsType.AWAIT.id)) {
            // AWAIT状态的任务再次完结,直接设置为出库完成
        // 入库:->98,出库:-> 198,由 complateOutStock 定时任务 更新库存
        if (task.getTaskType() < 100) {
            task.setTaskStatus(TaskStsType.COMPLETE_IN.id);
            if (StringUtils.isNotBlank(task.getOrgSite())) {
                BasStation station = basStationService.getOne(new LambdaQueryWrapper<BasStation>()
                        .eq(BasStation::getStationName, task.getOrgSite()));
                if (Objects.nonNull(station) && station.getType().equals(StationTypeEnum.STATION_TYPE_NORMAL.type)) {
                    station.setUseStatus(LocStsType.LOC_STS_TYPE_O.type);
                    if (!basStationService.updateById(station)) {
                        throw new CoolException("入库站点状态修改失败!!");
                    }
                }
            }
        } else {
            task.setTaskStatus(TaskStsType.COMPLETE_OUT.id);
            // 更新出库站点状态(与RCS通知完结保持一致)
            if (task.getTaskType() >= TaskType.TASK_TYPE_OUT.type && StringUtils.isNotBlank(task.getTargSite())) {
                BasStation station = basStationService.getOne(new LambdaQueryWrapper<BasStation>()
                        .eq(BasStation::getStationName, task.getTargSite()));
@@ -566,42 +612,61 @@
                    }
                }
            }
        } else {
            // 其他情况按原有逻辑处理
            // 入库任务(taskType < 100):设置为入库完成
            // 出库任务(taskType >= 100):设置为等待确认
            Integer newStatus = task.getTaskType() < 100 ? TaskStsType.COMPLETE_IN.id : TaskStsType.AWAIT.id;
            task.setTaskStatus(newStatus);
            // 如果是入库任务完成,更新入库站点状态(与RCS通知完结保持一致)
            if (newStatus.equals(TaskStsType.COMPLETE_IN.id) && StringUtils.isNotBlank(task.getOrgSite())) {
                BasStation station = basStationService.getOne(new LambdaQueryWrapper<BasStation>()
                        .eq(BasStation::getStationName, task.getOrgSite()));
                if (Objects.nonNull(station) && station.getType().equals(StationTypeEnum.STATION_TYPE_NORMAL.type)) {
                    station.setUseStatus(LocStsType.LOC_STS_TYPE_O.type);
                    if (!basStationService.updateById(station)) {
                        throw new CoolException("入库站点状态修改失败!!");
                    }
                }
            }
        }
        // 原:196 时再点一次才置 198;出库首次点击曾置 196(AWAIT)
        // if (task.getTaskStatus().equals(TaskStsType.AWAIT.id)) { task.setTaskStatus(TaskStsType.COMPLETE_OUT.id); ... }
        // else { Integer newStatus = task.getTaskType() < 100 ? COMPLETE_IN.id : AWAIT.id; ... }
        
        if (!this.updateById(task)) {
            throw new CoolException("完成任务失败");
        }
        // 管理后台「完成任务」通知 RCS
        if (StringUtils.isNotBlank(task.getTaskCode())) {
            rcsBusTaskNoticeService.notifyTaskStatus(task.getTaskCode(), task.getTaskStatus());
        }
        final Long taskIdForFinish = task.getId();
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    taskService.runStockFinishAfterManualComplete(taskIdForFinish);
                }
            });
        }
        return task;
    }
    @Override
    public void runStockFinishAfterManualComplete(Long taskId) {
        if (taskId == null) {
            return;
        }
        try {
            Task t = taskService.getById(taskId);
            if (t == null) {
                return;
            }
            if (Objects.equals(t.getTaskStatus(), TaskStsType.COMPLETE_IN.id)) {
                taskService.complateInTask(Collections.singletonList(t));
            } else if (Objects.equals(t.getTaskStatus(), TaskStsType.COMPLETE_OUT.id)) {
                taskService.completeTask(Collections.singletonList(t));
            }
        } catch (Exception e) {
            log.warn("手动完结后立即库存收尾失败,将由定时任务重试,taskId={}:{}", taskId, e.getMessage());
        }
    }
    /**
     * 全版出库完结:扣除库位数量,将库位状态设为空
     * 全板出库完结:扣除库位数量,将库位状态设为空
     *
     * @param id 任务ID
     * @param loginUserId 登录用户ID
     * @param notifyRcsFromAdmin 管理后台全板出库完结接口为 true 时通知 RCS;定时/PDA 等为 false
     * @return 任务对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Task completeFullOutStock(Long id, Long loginUserId) {
    public Task completeFullOutStock(Long id, Long loginUserId, boolean notifyRcsFromAdmin) {
        // 查询任务
        Task task = taskService.getOne(new LambdaQueryWrapper<Task>()
                .eq(Task::getId, id));
@@ -610,9 +675,9 @@
            throw new CoolException("任务不存在!!");
        }
        // 检查任务类型是否为全版出库
        // 检查任务类型是否为全板出库
        if (!task.getTaskType().equals(TaskType.TASK_TYPE_OUT.type)) {
            throw new CoolException("当前任务不是全版出库任务,无法执行此操作!!");
            throw new CoolException("当前任务不是全板出库任务,无法执行此操作!!");
        }
        // 检查任务状态:必须是199(WAVE_SEED)状态才能手动完结
@@ -641,6 +706,7 @@
        // 将库位状态设为空(O状态)
        if (!locService.update(new LambdaUpdateWrapper<Loc>()
                .set(Loc::getBarcode, null)
                .set(Loc::getWeight, null)
                .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_O.type)
                .set(Loc::getUpdateBy, loginUserId)
                .set(Loc::getUpdateTime, new Date())
@@ -668,6 +734,9 @@
        if (!this.updateById(task)) {
            throw new CoolException("任务状态更新失败!!");
        }
        if (notifyRcsFromAdmin && StringUtils.isNotBlank(task.getTaskCode())) {
            rcsBusTaskNoticeService.notifyTaskStatus(task.getTaskCode(), TaskStsType.UPDATED_OUT.id);
        }
        return task;
    }
@@ -682,6 +751,11 @@
        String curLoc;
        if (task.getTaskType().equals(TaskType.TASK_TYPE_IN.type)) {
            curLoc = task.getTargLoc();
        } else if (task.getTaskType().equals(TaskType.TASK_TYPE_EMPITY_IN.type)) {
            curLoc = task.getTargLoc();
            if (StringUtils.isBlank(curLoc)) {
                return task;
            }
        } else {
            curLoc = task.getOrgLoc();
        }
@@ -792,6 +866,7 @@
        /**修改库位状态为F.在库*/
        if (!locService.update(new LambdaUpdateWrapper<Loc>()
                .set(Loc::getBarcode, task.getBarcode())
                .set(Loc::getWeight, task.getWeight())
                .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_F.type)
                .set(Loc::getUpdateBy, loginUserId)
                .set(Loc::getUpdateTime, new Date())
@@ -801,6 +876,7 @@
        if (!locService.update(new LambdaUpdateWrapper<Loc>()
                .set(Loc::getBarcode, null)
                .set(Loc::getWeight, null)
                .set(Loc::getUpdateBy, loginUserId)
                .set(Loc::getUpdateTime, new Date())
                .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_O.type)
@@ -863,6 +939,7 @@
//        }
        loc.setUseStatus(LocStsType.LOC_STS_TYPE_F.type)
                .setBarcode(task.getBarcode())
                .setWeight(task.getWeight())
                .setUpdateBy(loginUserId).setUpdateTime(new Date());
        if (!locService.updateById(loc)) {
@@ -917,8 +994,11 @@
        if (!taskService.updateById(task)) {
            throw new CoolException("任务状态修改失败!!");
        }
        // 9.1 入/出库结果上报:拣料再入库/盘点再入库完成后通知云仓(与定时任务闭环一致)
        reportInOutResultToCloud(task, loc, taskItems, null, true);
        // 盘点再入库上报云仓入库完成;拣料再入库跳过(入库侧 qty 取 anfme 为托盘余量;云仓出库实发在出库完成侧)
        // reportInOutResultToCloud(task, loc, taskItems, null, true);
        if (!TaskType.TASK_TYPE_PICK_IN.type.equals(task.getTaskType())) {
            reportInOutResultToCloud(task, loc, taskItems, null, true);
        }
    }
    /**
@@ -935,14 +1015,24 @@
        List<Integer> list = Arrays.asList(TaskType.TASK_TYPE_IN.type, TaskType.TASK_TYPE_OUT.type, TaskType.TASK_TYPE_PICK_AGAIN_OUT.type,
                TaskType.TASK_TYPE_CHECK_OUT.type, TaskType.TASK_TYPE_EMPITY_IN.type, TaskType.TASK_TYPE_LOC_MOVE.type,
                TaskType.TASK_TYPE_EMPITY_OUT.type, TaskType.TASK_TYPE_MERGE_OUT.type);
        List<Task> allTasks = this.list(new LambdaQueryWrapper<Task>()
                .in(Task::getTaskType, list)
                .in(Task::getId, (Object[]) ids));
        if (allTasks.isEmpty()) {
        List<Task> tasksById = this.list(new LambdaQueryWrapper<Task>().in(Task::getId, (Object[]) ids));
        if (tasksById.isEmpty()) {
            throw new CoolException("任务不存在!!");
        }
        // 拣料出库/盘点出库进入再入库阶段后禁止取消(任务类型已由 103/107 变为再入库)
        for (Task t : tasksById) {
            if (TaskType.TASK_TYPE_PICK_IN.type.equals(t.getTaskType())
                    || TaskType.TASK_TYPE_CHECK_IN.type.equals(t.getTaskType())) {
                throw new CoolException("拣料/盘点出库已进入再入库阶段,禁止取消!!");
            }
        }
        List<Task> allTasks = tasksById.stream()
                .filter(t -> list.contains(t.getTaskType()))
                .collect(Collectors.toList());
        if (allTasks.isEmpty()) {
            throw new CoolException("当前任务类型不支持取消!!");
        }
        // 收集需要取消的RCS任务编号和批次编号(不限制状态,只要已下发到RCS就需要取消)
        List<String> rcsTaskCodes = new ArrayList<>();
        String batchNo = null;
@@ -979,59 +1069,60 @@
            }
        }
        
        // 如果有任务已下发到RCS,先调用RCS取消接口
        // 已下发 RCS 的工作档:必须先调 RCS 取消接口成功,否则不允许取消工作档
        boolean rcsCancelSuccess = false;
        if (!rcsTaskCodes.isEmpty()) {
            // 检查 RCS API 配置是否有效
            if (rcsApi == null || StringUtils.isBlank(rcsApi.getHost()) || StringUtils.isBlank(rcsApi.getPort())) {
                log.error("========== RCS任务取消失败 ==========");
                log.error("RCS API 配置无效!host: {}, port: {}",
                        rcsApi != null ? rcsApi.getHost() : "null",
                        rcsApi != null ? rcsApi.getPort() : "null");
                // 即使配置无效,也继续执行任务删除操作
            } else {
                try {
                    log.info("========== 开始取消RCS任务 ==========");
                    log.info("需要取消的RCS任务编号:{}", rcsTaskCodes);
                    String rcsUrl = rcsApi.getHost() + ":" + rcsApi.getPort() + RcsConstant.cancelTask;
                    log.info("RCS取消任务请求地址:{}", rcsUrl);
                // 如果没有批次编号,使用第一个任务编号作为批次编号
                if (StringUtils.isBlank(batchNo) && !rcsTaskCodes.isEmpty()) {
                throw new CoolException("任务已下发RCS,但未配置RCS地址,无法取消!!");
            }
            if (restTemplate == null) {
                throw new CoolException("任务已下发RCS,但无法调用RCS取消接口,无法取消!!");
            }
            try {
                log.info("========== 开始取消RCS任务 ==========");
                log.info("需要取消的RCS任务编号:{}", rcsTaskCodes);
                String rcsUrl = rcsApi.getHost() + ":" + rcsApi.getPort() + RcsConstant.cancelTask;
                log.info("RCS取消任务请求地址:{}", rcsUrl);
                if (StringUtils.isBlank(batchNo)) {
                    batchNo = rcsTaskCodes.get(0);
                }
                Map<String, Object> cancelParams = new HashMap<>();
                cancelParams.put("tasks", rcsTaskCodes);
                if (StringUtils.isNotBlank(batchNo)) {
                    cancelParams.put("batchNo", batchNo);
                }
                log.info("RCS取消任务请求参数:{}", JSONObject.toJSONString(cancelParams));
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Type", "application/json");
                headers.add("api-version", "v2.0");
                HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(cancelParams, headers);
                long startTime = System.currentTimeMillis();
                ResponseEntity<String> exchange = restTemplate.exchange(rcsUrl, HttpMethod.POST, httpEntity, String.class);
                long endTime = System.currentTimeMillis();
                log.info("RCS取消任务响应耗时:{}ms", (endTime - startTime));
                log.info("RCS取消任务响应状态码:{}", exchange.getStatusCode());
                log.info("RCS取消任务响应体:{}", exchange.getBody());
                if (!exchange.getStatusCode().is2xxSuccessful()) {
                    throw new CoolException("RCS取消任务失败:HTTP " + exchange.getStatusCode().value());
                }
                if (Objects.isNull(exchange.getBody())) {
                    log.error("RCS取消任务失败:响应体为空");
                    throw new CoolException("RCS取消任务失败:响应体为空");
                }
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.coercionConfigDefaults()
                        .setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsEmpty);
                CommonResponse result = objectMapper.readValue(exchange.getBody(), CommonResponse.class);
                if (result.getCode() == 200) {
                    log.info("========== RCS任务取消成功 ==========");
                    log.info("成功取消的RCS任务编号:{}", rcsTaskCodes);
@@ -1040,22 +1131,28 @@
                    log.error("RCS取消任务失败:{}", result.getMsg());
                    throw new CoolException("RCS取消任务失败:" + result.getMsg());
                }
                } catch (JsonProcessingException e) {
                    log.error("RCS取消任务响应解析失败:{}", e.getMessage(), e);
                    throw new CoolException("RCS取消任务响应解析失败:" + e.getMessage());
                } catch (Exception e) {
                    log.error("RCS取消任务异常:{}", e.getMessage(), e);
                    throw new CoolException("RCS取消任务异常:" + e.getMessage());
                }
            } catch (CoolException e) {
                throw e;
            } catch (JsonProcessingException e) {
                log.error("RCS取消任务响应解析失败:{}", e.getMessage(), e);
                throw new CoolException("RCS取消任务响应解析失败:" + e.getMessage());
            } catch (Exception e) {
                log.error("RCS取消任务异常:{}", e.getMessage(), e);
                throw new CoolException("RCS取消任务异常:" + e.getMessage());
            }
        }
        
        // 查询符合取消条件的任务(状态为1、101、199)
        List<Integer> allowedStatuses = Arrays.asList(TaskStsType.GENERATE_IN.id, TaskStsType.GENERATE_OUT.id, TaskStsType.WAVE_SEED.id);
        // 可取消状态:原 1/101(不含 199);拣料/盘点出库 RCS 执行中(<198);再入库(53/57)在方法入口已禁止取消
        List<Task> tasks = this.list(new LambdaQueryWrapper<Task>()
                .in(Task::getTaskType, list)
                .in(Task::getId, (Object[]) ids)
                .in(Task::getTaskStatus, allowedStatuses));
                .and(w -> w
                        .in(Task::getTaskStatus, Arrays.asList(
                                TaskStsType.GENERATE_IN.id,
                                TaskStsType.GENERATE_OUT.id))
                        .or(w2 -> w2
                                .in(Task::getTaskType, TaskType.TASK_TYPE_PICK_AGAIN_OUT.type, TaskType.TASK_TYPE_CHECK_OUT.type)
                                .lt(Task::getTaskStatus, TaskStsType.COMPLETE_OUT.id))));
        
        // 如果符合取消条件的任务为空,但RCS取消成功,允许继续(可能是任务状态已变更)
        if (tasks.isEmpty() && !rcsCancelSuccess) {
@@ -1077,7 +1174,9 @@
                }
                if (!locService.update(new LambdaUpdateWrapper<Loc>()
                        .eq(Loc::getCode, task.getTargLoc())
                        .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_O.type))) {
                        .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_O.type)
                        .set(Loc::getBarcode, null)
                        .set(Loc::getWeight, null))) {
                    throw new CoolException("移库目标库位状态修改失败!!");
                }
@@ -1129,6 +1228,14 @@
                        .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_F.type))) {
                    throw new CoolException("源库位状态修改失败!!");
                }
            } else if (task.getTaskType().equals(TaskType.TASK_TYPE_EMPITY_OUT.type)) {
                // 空板出库:建单时 D→R,取消恢复为空板 D
                if (!locService.update(new LambdaUpdateWrapper<Loc>()
                        .eq(Loc::getCode, task.getOrgLoc())
                        .eq(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_R.type)
                        .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_D.type))) {
                    throw new CoolException("空板出库源库位恢复空板失败!!");
                }
            }
            if (!Objects.isNull(task.getWarehType()) && task.getWarehType().equals(WarehType.WAREHOUSE_TYPE_AGV.val)) {
@@ -1165,13 +1272,14 @@
                        }
                        loc.setUseStatus(LocStsType.LOC_STS_TYPE_F.type)
                                .setBarcode(task.getBarcode())
                                .setWeight(task.getWeight())
                                .setUpdateBy(loginUserId)
                                .setUpdateTime(new Date());
                        if (!locService.updateById(loc)) {
                            throw new CoolException("库位信息修改失败!!");
                        }
                        //出库
                        if (item.getWkType().equals(Short.parseShort(OrderWorkType.ORDER_WORK_TYPE_STOCK_OUT.type))) {
                        if (Objects.equals(item.getWkType(), OrderWorkType.ORDER_WORK_TYPE_STOCK_OUT.type)) {
                            //库存出库
                        } else if (task.getResource().equals(TaskResouceType.TASK_RESOUCE_WAVE_TYPE.val)) {
                            WaveItem waveItem = waveItemService.getById(item.getSource());
@@ -1193,7 +1301,7 @@
                                throw new CoolException("波次更新失败!!");
                            }
                        } else if (item.getWkType().equals(Short.parseShort(OrderWorkType.ORDER_WORK_TYPE_OTHER.type))) {
                        } else if (Objects.equals(item.getWkType(), OrderWorkType.ORDER_WORK_TYPE_OTHER.type)) {
                            //其它出库
                        } else {
@@ -1239,7 +1347,9 @@
                        Loc loc = locService.getOne(new LambdaQueryWrapper<Loc>().eq(Loc::getCode, task.getTaskType() < TaskStsType.UPDATED_IN.id ? task.getTargLoc() : task.getOrgLoc()));
                        if (null != loc && (loc.getUseStatus().equals(LocStsType.LOC_STS_TYPE_S.type)
                                || loc.getUseStatus().equals(LocStsType.LOC_STS_TYPE_R.type))) {
                            loc.setUseStatus(LocStsType.LOC_STS_TYPE_O.type);
                            loc.setUseStatus(LocStsType.LOC_STS_TYPE_O.type)
                                    .setBarcode(null)
                                    .setWeight(null);
                            if (!locService.updateById(loc)) {
                                throw new CoolException("更新库位状态失败!!");
                            }
@@ -1370,6 +1480,7 @@
                        log.debug("[拣料入库] 计算后 pickedQty={}, minQty(剩余)={}, 将更新 taskItem.anfme={}, taskItem.qty={}",
                                pickedQty, minQty, minQty, pickedQty);
                        if (QuantityUtils.isNonNegative(minQty)) {
                            enqueueCloudWmsOutNotifyLogEarly(task, taskItem, QuantityUtils.toScaledBigDecimal(pickedQty));
                            taskItem.setAnfme(minQty);
                            taskItem.setQty(pickedQty);
                            if (!taskItemService.updateById(taskItem)) {
@@ -1478,7 +1589,8 @@
                throw new CoolException("临时库存更新失败!!");
            }
        }
        loc1.setUseStatus(LocStsType.LOC_STS_TYPE_S.type);
        loc1.setUseStatus(LocStsType.LOC_STS_TYPE_S.type)
                .setWeight(task.getWeight());
        locService.updateById(loc1);
//        if (!locService.updateById(loc1)) {
//            throw new CoolException("库位预约入库失败!!");
@@ -1504,6 +1616,8 @@
        if (allItems.isEmpty()) {
            throw new CoolException("任务明细为空");
        }
        List<Long> allItemIds = allItems.stream().map(TaskItem::getId).filter(Objects::nonNull).collect(Collectors.toList());
        Map<Long, BigDecimal> preQtyByItem = cloudWmsNotifyLogService.mapOutQtyFromInOutNotifyLogByTaskItemIds(allItemIds);
        Long loginUserId = SystemAuthUtils.getLoginUserId();
        if (loginUserId == null) {
            loginUserId = 1L;
@@ -1520,7 +1634,15 @@
        Map<String, Double> remainderByKey = new LinkedHashMap<>();
        for (Map.Entry<String, List<TaskItem>> e : byKey.entrySet()) {
            List<TaskItem> group = e.getValue();
            double totalQty = group.stream().mapToDouble(ti -> ti.getQty() != null && ti.getQty() > 0 ? ti.getQty() : (ti.getAnfme() != null ? ti.getAnfme() : 0)).sum();
            BigDecimal totalBd = BigDecimal.ZERO;
            for (TaskItem ti : group) {
                BigDecimal q = preQtyByItem.get(ti.getId());
                if (q == null) {
                    throw new CoolException("云仓待办无出库数量,taskItemId=" + ti.getId());
                }
                totalBd = totalBd.add(q);
            }
            double totalQty = totalBd.setScale(6, RoundingMode.HALF_UP).doubleValue();
            TaskItem rep = group.get(0);
            TaskItem forDeduct = new TaskItem();
            forDeduct.setMatnrId(rep.getMatnrId()).setBatch(rep.getBatch()).setFieldsIndex(rep.getFieldsIndex()).setQty(totalQty);
@@ -1586,10 +1708,16 @@
                if (group == null || group.isEmpty()) continue;
                TaskItem rep = group.get(0);
                TaskItem ti = new TaskItem();
                ti.setTaskId(pickInTask.getId());
                ti.setMatnrId(rep.getMatnrId()).setMaktx(rep.getMaktx()).setMatnrCode(rep.getMatnrCode());
                ti.setBatch(rep.getBatch()).setFieldsIndex(rep.getFieldsIndex()).setUnit(rep.getUnit()).setSpec(rep.getSpec()).setModel(rep.getModel());
                ti.setAnfme(rem).setQty(0.0);
                BeanUtils.copyProperties(rep, ti);
                ti.setId(null)
                        .setTaskId(pickInTask.getId())
                        .setAnfme(rem)
                        .setQty(0.0)
                        .setWorkQty(0.0)
                        .setCreateBy(loginUserId)
                        .setUpdateBy(loginUserId)
                        .setCreateTime(new Date())
                        .setUpdateTime(new Date());
                taskItemService.save(ti);
                LocItemWorking w = new LocItemWorking();
                w.setTaskId(pickInTask.getId());
@@ -1603,11 +1731,13 @@
            if (!workings.isEmpty()) {
                locItemWorkingService.saveBatch(workings);
            }
            loc.setUseStatus(LocStsType.LOC_STS_TYPE_S.type);
            loc.setUseStatus(LocStsType.LOC_STS_TYPE_S.type)
                    .setWeight(first.getWeight());
            locService.updateById(loc);
        } else {
            loc.setUseStatus(LocStsType.LOC_STS_TYPE_O.type);
            loc.setBarcode(null);
            loc.setWeight(null);
            loc.setUpdateBy(loginUserId);
            loc.setUpdateTime(new Date());
            locService.updateById(loc);
@@ -1646,6 +1776,7 @@
                        .eq(Loc::getId, loc.getId())
                        .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_O.type)
                        .set(Loc::getBarcode, null)
                        .set(Loc::getWeight, null)
                        .set(Loc::getUpdateBy, loginUserId)
                        .set(Loc::getUpdateTime, new Date()))) {
                    throw new CoolException("空板出库库位状态更新失败!!");
@@ -1712,7 +1843,7 @@
            try {
                // 根据任务类型更新库位明细
                if (task.getTaskType().equals(TaskType.TASK_TYPE_OUT.type)) {
                    // 全版出库:不删除库位明细,等待PDA快速拣货确认时再删除
                    // 全板出库:不删除库位明细,等待PDA快速拣货确认时再删除
                    // subtractLocItem(loc); // 已移除,改为在completeFullOutStock中删除
                } else if (!TaskType.TASK_TYPE_PICK_AGAIN_OUT.type.equals(task.getTaskType())) {
                    // 部分出库(如盘点出库):根据TaskItem数量扣减库位明细;拣料出库在生成拣料入库单时扣减
@@ -1725,12 +1856,12 @@
        }
        //添加出入库记录信息
        Map<Short, List<TaskItem>> listMap = taskItems.stream().collect(Collectors.groupingBy(TaskItem::getWkType));
        Map<String, List<TaskItem>> listMap = taskItems.stream().collect(Collectors.groupingBy(TaskItem::getWkType));
        /***获取库存出库值,如果为空表示正常单据出库,非空表明是库存出库
         * 1. 库存出库没有单据信息,单据信息默认为空
         * 2. 单据库存需通过波次查询原始单据信息,将单据信息填入stock中
         * */
        List<TaskItem> list = listMap.get(Short.parseShort(OrderWorkType.ORDER_WORK_TYPE_STOCK_OUT.type));
        List<TaskItem> list = listMap.get(OrderWorkType.ORDER_WORK_TYPE_STOCK_OUT.type);
        if (Objects.isNull(list) || list.isEmpty()) {
            Map<Long, List<TaskItem>> maps = taskItems.stream().collect(Collectors.groupingBy(TaskItem::getSource));
            maps.keySet().forEach(key -> {
@@ -1781,13 +1912,14 @@
            // 拣料出库/盘点出库:在未生成拣料入库单之前保持 R.预约出库,否则下发任务时查不到该库位(只查 F+R)导致“库存不足”
            // 等 PDA 确认并生成拣料入库任务时,再在 pickOrCheckTask 中将目标库位改为 S.预约入库
        } else if (task.getTaskType().equals(TaskType.TASK_TYPE_OUT.type)) {
            // 全版出库:不更新库位状态为O,等待PDA快速拣货确认时再更新
            // 全板出库:不更新库位状态为O,等待PDA快速拣货确认时再更新
            // 库位状态保持原样(R.出库预约状态)
        } else {
            /**修改为库位状态为O.空库*/
            if (!locService.update(new LambdaUpdateWrapper<Loc>()
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_O.type)
                    .set(Loc::getBarcode, null)
                    .set(Loc::getWeight, null)
                    .set(Loc::getUpdateBy, loginUserId)
                    .set(Loc::getUpdateTime, new Date())
                    .eq(Loc::getId, loc.getId()))) {
@@ -1858,7 +1990,18 @@
        if (StringUtils.isBlank(ruleCode)) {
            throw new CoolException("当前业务:" + SerialRuleCode.SYS_STOCK_CODE + ",编码规则不存在!!");
        }
        Double sum = taskItems.stream().mapToDouble(TaskItem::getAnfme).sum();
        List<Long> itemIds = taskItems.stream().map(TaskItem::getId).filter(Objects::nonNull).collect(Collectors.toList());
        Map<Long, BigDecimal> preMap = cloudWmsNotifyLogService.mapOutQtyFromInOutNotifyLogByTaskItemIds(itemIds);
        BigDecimal sumBd = BigDecimal.ZERO;
        for (TaskItem ti : taskItems) {
            BigDecimal q = preMap.get(ti.getId());
            if (q == null) {
                throw new CoolException("云仓待办无出库数量,taskItemId=" + ti.getId());
            }
            sumBd = sumBd.add(q);
        }
        sumBd = sumBd.setScale(6, RoundingMode.HALF_UP);
        Double sum = sumBd.doubleValue();
        stock.setCode(ruleCode)
                .setUpdateBy(loginUserId)
                .setUpdateTime(new Date())
@@ -1871,22 +2014,26 @@
                WkOrder wkOrder = asnOrderService.getById(orderId);
                if (wkOrder != null) {
                    Double curQty = wkOrder.getQty() != null ? wkOrder.getQty() : 0.0;
                    Double newQty = QuantityUtils.roundToScale(curQty + sum);
                    wkOrder.setExceStatus(AsnExceStatus.OUT_STOCK_STATUS_TASK_WORKING.val).setQty(newQty);
                    BigDecimal newQtyBd = BigDecimal.valueOf(curQty).add(sumBd).setScale(6, RoundingMode.HALF_UP);
                    wkOrder.setExceStatus(AsnExceStatus.OUT_STOCK_STATUS_TASK_WORKING.val).setQty(newQtyBd.doubleValue());
                    if (!asnOrderService.updateById(wkOrder)) {
                        throw new CoolException("出库单完成数量更新失败!!");
                    }
                }
                // 按出库单明细汇总本次任务数量,更新各明细 workQty
                Map<Long, Double> sumByOrderItemId = taskItems.stream()
                        .filter(ti -> ti.getOrderItemId() != null)
                        .collect(Collectors.groupingBy(TaskItem::getOrderItemId,
                                Collectors.summingDouble(ti -> ti.getAnfme() != null ? ti.getAnfme() : 0.0)));
                for (Map.Entry<Long, Double> e : sumByOrderItemId.entrySet()) {
                Map<Long, BigDecimal> sumByOrderItemId = new HashMap<>();
                for (TaskItem ti : taskItems) {
                    if (ti.getOrderItemId() == null) {
                        continue;
                    }
                    BigDecimal q = preMap.get(ti.getId());
                    sumByOrderItemId.merge(ti.getOrderItemId(), q, BigDecimal::add);
                }
                for (Map.Entry<Long, BigDecimal> e : sumByOrderItemId.entrySet()) {
                    WkOrderItem oi = outStockItemService.getById(e.getKey());
                    if (oi != null) {
                        Double wq = oi.getWorkQty() != null ? oi.getWorkQty() : 0.0;
                        oi.setWorkQty(QuantityUtils.roundToScale(wq + e.getValue()));
                        BigDecimal nwq = BigDecimal.valueOf(wq).add(e.getValue()).setScale(6, RoundingMode.HALF_UP);
                        oi.setWorkQty(nwq.doubleValue());
                        if (!outStockItemService.updateById(oi)) {
                            throw new CoolException("出库单明细执行数量更新失败!!");
                        }
@@ -1895,19 +2042,20 @@
            }
        } else if (!Objects.isNull(orderItem) && StringUtils.isNotBlank(orderItem.getId() + "")) {
            WkOrder wkOrder = asnOrderService.getById(orderItem.getOrderId());
            Double qty = Math.round((wkOrder.getQty() + sum) * 1000000) / 1000000.0;
            double curHeaderQty = wkOrder.getQty() != null ? wkOrder.getQty() : 0.0;
            Double qty = QuantityUtils.roundToScale(QuantityUtils.add(curHeaderQty, sum));
            wkOrder.setExceStatus(AsnExceStatus.OUT_STOCK_STATUS_TASK_WORKING.val)
                    .setQty(qty);
            if (!asnOrderService.updateById(wkOrder)) {
                throw new CoolException("出库单更新失败!!");
            }
            stock.setWkType(Short.parseShort(wkOrder.getWkType()))
            stock.setWkType(wkOrder.getWkType())
                    .setType(OrderType.ORDER_OUT.type);
        } else if (!Objects.isNull(diffItem)) {
            stock.setWkType(Short.parseShort(OrderWorkType.ORDER_WORK_TYPE_STOCK_CHECK.type))
            stock.setWkType(OrderWorkType.ORDER_WORK_TYPE_STOCK_CHECK.type)
                    .setType(OrderType.ORDER_CHECK.type);
        } else {
            stock.setWkType(Short.parseShort(OrderWorkType.ORDER_WORK_TYPE_STOCK_OUT.type))
            stock.setWkType(OrderWorkType.ORDER_WORK_TYPE_STOCK_OUT.type)
                    .setMemo("库存出库,无单据信息!!")
                    .setType(OrderType.ORDER_OUT.type);
        }
@@ -1919,6 +2067,7 @@
            /**通过任务明细中的taskId查询,获取TASK的目标库位信息*/
            StockItem stockItem = new StockItem();
            BeanUtils.copyProperties(item, stockItem);
            stockItem.setAnfme(QuantityUtils.roundToScale(preMap.get(item.getId())));
            stockItem.setSourceItemId(item.getOrderItemId())
                    .setUpdateBy(loginUserId)
                    .setUpdateTime(new Date())
@@ -2033,6 +2182,15 @@
                    log.error("========== RCS任务下发失败 ==========");
                    log.error("站点不存在!!任务编码:{},目标站点:{}", task.getTaskCode(), task.getTargSite());
                    continue;
                }
                // 出库下发前校验站点状态与出库能力
                if (task.getTaskType() >= TaskType.TASK_TYPE_OUT.type) {
                    if (!Integer.valueOf(1).equals(station.getStatus()) || !Integer.valueOf(1).equals(station.getOutAble())) {
                        log.error("========== RCS任务下发失败 ==========");
                        log.error("站点不可出库下发!!任务编码:{},目标站点:{},站点状态(status):{},能出(outAble):{}",
                                task.getTaskCode(), task.getTargSite(), station.getStatus(), station.getOutAble());
                        continue;
                    }
                }
            }
@@ -2206,6 +2364,13 @@
                    log.error("RCS资源访问异常,任务下发失败!任务编码:{},错误信息:{}", task.getTaskCode(), errorMsg);
                }
                continue;
            } catch (HttpStatusCodeException e) {
                long endTime = System.currentTimeMillis();
                log.error("========== RCS任务下发异常 ==========");
                log.error("请求RCS-HTTP状态异常,耗时:{}ms,任务编码:{},status:{},body:{}", (endTime - startTime), task.getTaskCode(), e.getRawStatusCode(), e.getResponseBodyAsString(), e);
                log.error("请求RCS-地址:{}", pubTakUrl);
                log.error("请求RCS-参数:{}", JSONObject.toJSONString(taskParams));
                continue;
            } catch (Exception e) {
                long endTime = System.currentTimeMillis();
                log.error("========== RCS任务下发异常 ==========");
@@ -2331,7 +2496,7 @@
    /**
     * @author Ryan
     * @date 2025/5/20
     * @description: 扣减库存明细(全版出库:删除所有库位明细)
     * @description: 扣减库存明细(全板出库:删除所有库位明细)
     * @version 1.0
     */
    @Transactional(rollbackFor = Exception.class)
@@ -2421,6 +2586,21 @@
        }
        List<TaskItem> taskItems = taskItemService.list(new LambdaQueryWrapper<TaskItem>().eq(TaskItem::getTaskId, task.getId()));
        // 空板入库无任务明细,仅更新库位为空板(D)、任务状态为库存更新完成
        if (TaskType.TASK_TYPE_EMPITY_IN.type.equals(task.getTaskType())) {
            if (!locService.update(new LambdaUpdateWrapper<Loc>().eq(Loc::getCode, task.getTargLoc())
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_D.type)
                    .set(Loc::getWeight, task.getWeight())
                    .set(Loc::getUpdateBy, loginUserId)
                    .set(Loc::getUpdateTime, new Date()))) {
                throw new CoolException("空板入库库位状态修改失败!!");
            }
            if (!this.update(new LambdaUpdateWrapper<Task>().eq(Task::getId, task.getId()).set(Task::getTaskStatus, TaskStsType.UPDATED_IN.id))) {
                throw new CoolException("空板入库任务状态修改失败!!");
            }
            reportInOutResultToCloud(task, loc, Collections.emptyList(), null, true);
            return;
        }
        if (taskItems.isEmpty()) {
            throw new CoolException("任务明细不存在!!");
        }
@@ -2458,8 +2638,57 @@
            throw new CoolException("组拖状态修改失败!!");
        }
        // 组托入库完成后累加订单及明细的已收数量,用于后续判断整单是否可置为已完成
        Map<Long, Double> orderIdToAdd = new HashMap<>();
        Map<Long, Double> itemIdToAdd = new HashMap<>();
        for (WaitPakinItem p : pakinItems) {
            if (StringUtils.isBlank(p.getAsnCode())) {
                continue;
            }
            WkOrder order = asnOrderService.getOne(new LambdaQueryWrapper<WkOrder>().eq(WkOrder::getCode, p.getAsnCode()));
            if (order == null) {
                continue;
            }
            double addQty = (p.getAnfme() != null ? p.getAnfme() : 0.0);
            orderIdToAdd.merge(order.getId(), addQty, Double::sum);
            if (p.getAsnItemId() != null) {
                itemIdToAdd.merge(p.getAsnItemId(), addQty, Double::sum);
            }
        }
        for (Map.Entry<Long, Double> e : orderIdToAdd.entrySet()) {
            WkOrder o = asnOrderService.getById(e.getKey());
            if (o != null) {
                Double newQty = QuantityUtils.roundToScale(QuantityUtils.add(o.getQty() != null ? o.getQty() : 0.0, e.getValue()));
                Double planQty = QuantityUtils.roundToScale(o.getAnfme() != null ? o.getAnfme() : 0.0);
                if (QuantityUtils.compare(newQty, planQty) > 0) {
                    newQty = planQty;
                }
                o.setQty(newQty);
                if (!asnOrderService.updateById(o)) {
                    throw new CoolException("入库单完成数量更新失败!!");
                }
            }
        }
        for (Map.Entry<Long, Double> e : itemIdToAdd.entrySet()) {
            WkOrderItem oi = asnOrderItemService.getById(e.getKey());
            if (oi != null) {
                Double newQty = QuantityUtils.roundToScale(QuantityUtils.add(oi.getQty() != null ? oi.getQty() : 0.0, e.getValue()));
                Double planQty = QuantityUtils.roundToScale(oi.getAnfme() != null ? oi.getAnfme() : 0.0);
                if (QuantityUtils.compare(newQty, planQty) > 0) {
                    newQty = planQty;
                }
                oi.setQty(newQty);
                if (!asnOrderItemService.updateById(oi)) {
                    throw new CoolException("入库单明细完成数量更新失败!!");
                }
            }
        }
        /**修改库位状态为F.在库*/
        if (!locService.update(new LambdaUpdateWrapper<Loc>().set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_F.type).eq(Loc::getCode, task.getTargLoc()))) {
        if (!locService.update(new LambdaUpdateWrapper<Loc>()
                .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_F.type)
                .set(Loc::getWeight, task.getWeight())
                .eq(Loc::getCode, task.getTargLoc()))) {
            throw new CoolException("库位状态修改失败!!");
        }
        if (!this.update(new LambdaUpdateWrapper<Task>().eq(Task::getId, task.getId()).set(Task::getTaskStatus, TaskStsType.UPDATED_IN.id))) {
@@ -2580,7 +2809,7 @@
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public synchronized void saveStockItems(List<TaskItem> items, Task task, Long id, String code, Short wkType, String type, Long loginUserId) {
    public synchronized void saveStockItems(List<TaskItem> items, Task task, Long id, String code, String wkType, String type, Long loginUserId) {
        Stock stock = new Stock();
        String ruleCode = SerialRuleUtils.generateRuleCode(SerialRuleCode.SYS_STOCK_CODE, null);
        if (StringUtils.isBlank(ruleCode)) {
@@ -2604,12 +2833,27 @@
        } else {
            stock.setLocCode(task.getOrgLoc());
        }
        BigDecimal trayWeight = task.getWeight();
        BigDecimal groupWeight = null;
        if (trayWeight != null && sum > 0) {
            List<TaskItem> allLines = taskItemService.list(new LambdaQueryWrapper<TaskItem>().eq(TaskItem::getTaskId, task.getId()));
            double totalQty = allLines.stream().mapToDouble(t -> t.getAnfme() != null ? t.getAnfme() : 0.0).sum();
            if (totalQty > 0) {
                groupWeight = trayWeight.multiply(BigDecimal.valueOf(sum)).divide(BigDecimal.valueOf(totalQty), 4, RoundingMode.HALF_UP);
            } else {
                groupWeight = trayWeight;
            }
            stock.setWeight(groupWeight);
        }
        if (!stockService.save(stock)) {
            throw new CoolException("库存保存失败!!");
        }
        List<StockItem> stockItems = new ArrayList<>();
        for (TaskItem item : items) {
        BigDecimal allocatedWeight = BigDecimal.ZERO;
        BigDecimal sumBd = sum > 0 ? BigDecimal.valueOf(sum) : null;
        for (int i = 0; i < items.size(); i++) {
            TaskItem item = items.get(i);
            /**通过任务明细中的taskId查询,获取TASK的目标库位信息*/
            StockItem stockItem = new StockItem();
            BeanUtils.copyProperties(item, stockItem);
@@ -2620,6 +2864,16 @@
                    .setUpdateBy(loginUserId)
                    .setId(null)
                    .setStockId(stock.getId());
            if (groupWeight != null && sumBd != null) {
                if (i == items.size() - 1) {
                    stockItem.setWeight(groupWeight.subtract(allocatedWeight));
                } else {
                    double lineQty = item.getAnfme() != null ? item.getAnfme() : 0.0;
                    BigDecimal lineW = groupWeight.multiply(BigDecimal.valueOf(lineQty)).divide(sumBd, 4, RoundingMode.HALF_UP);
                    stockItem.setWeight(lineW);
                    allocatedWeight = allocatedWeight.add(lineW);
                }
            }
            stockItems.add(stockItem);
        }
        if (!stockItemService.saveBatch(stockItems)) {
@@ -2636,6 +2890,32 @@
        }
    }
    @Override
    public void enqueueCloudWmsOutNotifyLogEarly(Task task, TaskItem taskItem, BigDecimal outQty) {
        if (task == null || taskItem == null || outQty == null) {
            return;
        }
        try {
            Loc loc = locService.getOne(new LambdaQueryWrapper<Loc>().eq(Loc::getCode, task.getOrgLoc()));
            if (loc == null) {
                return;
            }
            CloudInOutReportContext ctx = loadCloudInOutReportContext(task, loc, Collections.singletonList(taskItem), null, false);
            if (ctx == null) {
                return;
            }
            InOutResultReportParam param = buildInOutParamForItem(task, taskItem, false, outQty, ctx);
            if (param == null) {
                return;
            }
            String mode = resolveCloudWmsInoutReportMode();
            boolean sendHold = CloudWmsInoutReportMode.MANUAL.equals(mode) || CloudWmsInoutReportMode.WAIT_ORDER.equals(mode);
            cloudWmsNotifyLogService.saveOrUpdateInOutNotifyEarly(param, task.getId(), taskItem.getId(), sendHold, taskItem.getTenantId());
        } catch (Exception e) {
            log.warn("云仓9.1早Enqueue失败 taskId={} taskItemId={}:{}", task.getId(), taskItem.getId(), e.getMessage());
        }
    }
    /**
     * 9.1 入/出库结果上报待办
     * @param isInbound true 入库完成,false 出库完成
@@ -2643,64 +2923,239 @@
     */
    private void reportInOutResultToCloud(Task task, Loc loc, List<TaskItem> taskItems, Set<Long> pkinItemIds, boolean isInbound) {
        try {
            String locId = isInbound ? task.getTargLoc() : task.getOrgLoc();
            String wareHouseId = null;
            if (loc.getWarehouseId() != null) {
                Warehouse wh = warehouseService.getById(loc.getWarehouseId());
                if (wh != null) {
                    wareHouseId = wh.getCode();
                }
            }
            if (wareHouseId == null) {
                log.warn("入/出库结果上报待办跳过:仓库编码为空,taskId={}", task.getId());
            CloudInOutReportContext ctx = loadCloudInOutReportContext(task, loc, taskItems, pkinItemIds, isInbound);
            if (ctx == null) {
                return;
            }
            Map<Long, String> sourceToOrderNo = new HashMap<>();
            if (isInbound && pkinItemIds != null && !pkinItemIds.isEmpty()) {
                List<WaitPakinItem> pakinItems = waitPakinItemService.list(new LambdaQueryWrapper<WaitPakinItem>().in(WaitPakinItem::getId, pkinItemIds));
                for (WaitPakinItem p : pakinItems) {
                    if (p.getAsnCode() != null) {
                        sourceToOrderNo.put(p.getId(), p.getAsnCode());
                    }
                }
            }
            List<Long> reportItemIds = taskItems.stream().map(TaskItem::getId).filter(Objects::nonNull).collect(Collectors.toList());
            Map<Long, BigDecimal> outQtyByItem = isInbound ? Collections.emptyMap()
                    : cloudWmsNotifyLogService.mapOutQtyFromInOutNotifyLogByTaskItemIds(reportItemIds);
            ObjectMapper om = new ObjectMapper();
            Date now = new Date();
            String mode = resolveCloudWmsInoutReportMode();
            boolean sendHold = CloudWmsInoutReportMode.MANUAL.equals(mode) || CloudWmsInoutReportMode.WAIT_ORDER.equals(mode);
            for (TaskItem item : taskItems) {
                String orderNo = isInbound ? sourceToOrderNo.get(item.getSource()) : (item.getPlatOrderCode() != null ? item.getPlatOrderCode() : item.getPlatWorkCode());
                if (orderNo == null && isInbound) {
                    orderNo = item.getPlatOrderCode() != null ? item.getPlatOrderCode() : item.getPlatWorkCode();
                }
                if (orderNo == null || item.getMatnrCode() == null) {
                if (item == null || item.getId() == null) {
                    continue;
                }
                InOutResultReportParam param = new InOutResultReportParam()
                        .setOrderNo(orderNo)
                        .setPlanNo(item.getPlatWorkCode())
                        .setLineId(item.getPlatItemId())
                        .setWareHouseId(wareHouseId)
                        .setLocId(locId)
                        .setMatNr(item.getMatnrCode())
                        .setQty(item.getAnfme() != null ? String.valueOf(item.getAnfme()) : "0")
                        .setBatch(item.getBatch());
                BigDecimal outboundQty = isInbound ? null : outQtyByItem.get(item.getId());
                if (!isInbound && outboundQty == null) {
                    log.warn("云仓9.1跳过:待办无出库数量,taskId={},taskItemId={}", task.getId(), item.getId());
                    continue;
                }
                InOutResultReportParam param = buildInOutParamForItem(task, item, isInbound, outboundQty, ctx);
                if (param == null) {
                    continue;
                }
                if (!isInbound && cloudWmsNotifyLogService.hasInOutNotifyRowForTaskItem(item.getId(), false)) {
                    continue;
                }
                if (isInbound && cloudWmsNotifyLogService.hasInOutNotifyRowForTaskItem(item.getId(), true)) {
                    continue;
                }
                String orderNo = param.getOrderNo();
                try {
                    String requestBody = om.writeValueAsString(param);
                    String bizRef = "taskId=" + task.getId() + ",taskItemId=" + item.getId() + ",orderNo=" + orderNo;
                    CloudWmsNotifyLog notifyLog = new CloudWmsNotifyLog()
                            .setReportType(cloudWmsNotifyLogService.getReportTypeInOutResult())
                            .setRequestBody(requestBody)
                            .setNotifyStatus(cloudWmsNotifyLogService.getNotifyStatusPending())
                            .setRetryCount(0)
                            .setBizRef("taskId=" + task.getId() + ",orderNo=" + orderNo)
                            .setBizRef(bizRef)
                            .setCreateTime(now)
                            .setUpdateTime(now);
                            .setUpdateTime(now)
                            .setSourceOrderNo(orderNo)
                            .setInboundFlag(isInbound ? 1 : 0)
                            .setWareHouseCode(ctx.wareHouseId)
                            .setSendHold(sendHold ? 1 : 0)
                            .setSending(0);
                    cloudWmsNotifyLogService.fillFromConfig(notifyLog);
                    cloudWmsNotifyLogService.save(notifyLog);
                } catch (JsonProcessingException e) {
                    log.warn("入/出库结果上报待办落库失败(不影响主流程),taskId={},orderNo={}:{}", task.getId(), orderNo, e.getMessage());
                } catch (JsonProcessingException ex) {
                    log.warn("入/出库结果上报待办落库失败(不影响主流程),taskId={},orderNo={}:{}", task.getId(), orderNo, ex.getMessage());
                }
            }
        } catch (Exception e) {
            log.warn("入/出库结果上报待办失败,taskId={},isInbound={}:{}", task.getId(), isInbound, e.getMessage());
        }
    }
    private CloudInOutReportContext loadCloudInOutReportContext(Task task, Loc loc, List<TaskItem> taskItems, Set<Long> pkinItemIds, boolean isInbound) {
        if (task == null || loc == null || taskItems == null || taskItems.isEmpty()) {
            return null;
        }
        String locId = isInbound ? task.getTargLoc() : task.getOrgLoc();
        String wareHouseId = null;
        if (loc.getWarehouseId() != null) {
            Warehouse wh = warehouseService.getById(loc.getWarehouseId());
            if (wh != null) {
                wareHouseId = wh.getCode();
            }
        }
        if (wareHouseId == null) {
            log.warn("入/出库结果上报待办跳过:仓库编码为空,taskId={}", task.getId());
            return null;
        }
        Map<Long, String> sourceToOrderNo = new HashMap<>();
        if (isInbound && pkinItemIds != null && !pkinItemIds.isEmpty()) {
            List<WaitPakinItem> pakinItems = waitPakinItemService.list(new LambdaQueryWrapper<WaitPakinItem>().in(WaitPakinItem::getId, pkinItemIds));
            for (WaitPakinItem p : pakinItems) {
                if (p.getAsnCode() != null) {
                    sourceToOrderNo.put(p.getId(), p.getAsnCode());
                }
            }
        }
        boolean hasOutboundCloudLine = !isInbound && taskItems.stream().anyMatch(ti ->
                ti != null && ti.getOrderId() != null && StringUtils.isNotBlank(ti.getPlatItemId()));
        boolean hasCloudSource = taskItems.stream().anyMatch(this::hasCloudOrderRef)
                || (isInbound && !sourceToOrderNo.isEmpty())
                || hasOutboundCloudLine;
        if (!hasCloudSource) {
            log.info("入/出库结果上报待办跳过:无云仓来源单据,taskId={}", task.getId());
            return null;
        }
        Set<Long> orderIdSet = taskItems.stream()
                .filter(Objects::nonNull)
                .map(TaskItem::getOrderId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Long, WkOrder> orderById = new HashMap<>();
        if (!orderIdSet.isEmpty()) {
            for (WkOrder o : asnOrderService.listByIds(orderIdSet)) {
                if (o != null && o.getId() != null) {
                    orderById.put(o.getId(), o);
                }
            }
        }
        Set<String> orderCodeSet = new HashSet<>();
        for (TaskItem ti : taskItems) {
            if (ti == null) {
                continue;
            }
            String on = isInbound && ti.getSource() != null
                    ? sourceToOrderNo.get(ti.getSource())
                    : (ti.getPlatOrderCode() != null ? ti.getPlatOrderCode() : ti.getPlatWorkCode());
            if (on == null && isInbound) {
                on = ti.getPlatOrderCode() != null ? ti.getPlatOrderCode() : ti.getPlatWorkCode();
            }
            if (on == null && !isInbound && ti.getOrderId() != null) {
                WkOrder o = orderById.get(ti.getOrderId());
                if (o != null) {
                    on = StringUtils.isNotBlank(o.getPoCode()) ? o.getPoCode() : o.getCode();
                }
            }
            if (StringUtils.isNotBlank(on)) {
                orderCodeSet.add(on);
            }
        }
        Map<String, WkOrder> orderByCode = new HashMap<>();
        if (!orderCodeSet.isEmpty()) {
            for (WkOrder o : asnOrderService.list(new LambdaQueryWrapper<WkOrder>().in(WkOrder::getCode, orderCodeSet))) {
                if (o != null && StringUtils.isNotBlank(o.getCode())) {
                    orderByCode.put(o.getCode(), o);
                }
            }
            for (WkOrder o : asnOrderService.list(new LambdaQueryWrapper<WkOrder>().in(WkOrder::getPoCode, orderCodeSet))) {
                if (o != null && StringUtils.isNotBlank(o.getPoCode())) {
                    orderByCode.putIfAbsent(o.getPoCode(), o);
                }
            }
        }
        return new CloudInOutReportContext(wareHouseId, locId, sourceToOrderNo, orderById, orderByCode);
    }
    private InOutResultReportParam buildInOutParamForItem(Task task, TaskItem item, boolean isInbound,
            BigDecimal outboundQtyResolved, CloudInOutReportContext ctx) {
        if (task == null || item == null || ctx == null) {
            return null;
        }
        boolean hasTaskItemCloudRef = hasCloudOrderRef(item);
        boolean hasInboundAsnFallbackRef = isInbound
                && item.getSource() != null
                && StringUtils.isNotBlank(ctx.sourceToOrderNo.get(item.getSource()));
        boolean hasOutboundCloudLineRef = !isInbound && item.getOrderId() != null && StringUtils.isNotBlank(item.getPlatItemId());
        if (!hasTaskItemCloudRef && !hasInboundAsnFallbackRef && !hasOutboundCloudLineRef) {
            return null;
        }
        WkOrder asnOrder = null;
        if (item.getOrderId() != null) {
            asnOrder = ctx.orderById.get(item.getOrderId());
        }
        String orderNo = isInbound ? ctx.sourceToOrderNo.get(item.getSource()) : (item.getPlatOrderCode() != null ? item.getPlatOrderCode() : item.getPlatWorkCode());
        if (orderNo == null && isInbound) {
            orderNo = item.getPlatOrderCode() != null ? item.getPlatOrderCode() : item.getPlatWorkCode();
        }
        if (orderNo == null && !isInbound && asnOrder != null) {
            orderNo = StringUtils.isNotBlank(asnOrder.getPoCode()) ? asnOrder.getPoCode() : asnOrder.getCode();
        }
        if (orderNo == null || item.getMatnrCode() == null) {
            return null;
        }
        if (!isInbound && outboundQtyResolved == null) {
            return null;
        }
        if (asnOrder == null) {
            asnOrder = ctx.orderByCode.get(orderNo);
        }
        String qtyStr;
        if (isInbound) {
            qtyStr = item.getAnfme() != null ? QuantityUtils.toPlainQtyString(QuantityUtils.toScaledBigDecimal(item.getAnfme())) : "0";
        } else {
            qtyStr = QuantityUtils.toPlainQtyString(outboundQtyResolved);
        }
        return new InOutResultReportParam()
                .setOrderNo(orderNo)
                .setPlanNo(item.getPlatWorkCode())
                .setWkType(item.getWkType())
                .setUnitNo(item.getUnit())
                .setLineId(item.getPlatItemId())
                .setWareHouseId(ctx.wareHouseId)
                .setDocWarehouseNo(asnOrder != null ? asnOrder.getDocTaskWarehouseNo() : null)
                .setOrgNo(asnOrder != null ? asnOrder.getDocOrgNo() : null)
                .setInWarehouseNo(isInbound && asnOrder != null ? asnOrder.getDocInWarehouseNo() : null)
                .setOutWarehouseNo(!isInbound && asnOrder != null ? asnOrder.getDocOutWarehouseNo() : null)
                .setLocId(ctx.locId)
                .setMatNr(item.getMatnrCode())
                .setQty(qtyStr)
                .setBatch(item.getBatch())
                .setInbound(isInbound)
                .setBarcode(task.getBarcode());
    }
    private static final class CloudInOutReportContext {
        final String wareHouseId;
        final String locId;
        final Map<Long, String> sourceToOrderNo;
        final Map<Long, WkOrder> orderById;
        final Map<String, WkOrder> orderByCode;
        private CloudInOutReportContext(String wareHouseId, String locId, Map<Long, String> sourceToOrderNo,
                Map<Long, WkOrder> orderById, Map<String, WkOrder> orderByCode) {
            this.wareHouseId = wareHouseId;
            this.locId = locId;
            this.sourceToOrderNo = sourceToOrderNo;
            this.orderById = orderById;
            this.orderByCode = orderByCode;
        }
    }
    private boolean hasCloudOrderRef(TaskItem item) {
        if (item == null) {
            return false;
        }
        return StringUtils.isNotBlank(item.getPlatOrderCode())
                || StringUtils.isNotBlank(item.getPlatWorkCode());
    }
    /** sys_config CLOUD_WMS_INOUT_REPORT_MODE:immediate / wait_order / manual / single */
    private String resolveCloudWmsInoutReportMode() {
        try {
            Config cfg = configService.getCachedOrLoad(GlobalConfigCode.CLOUD_WMS_INOUT_REPORT_MODE);
            if (cfg != null && StringUtils.isNotBlank(cfg.getVal())) {
                return cfg.getVal().trim().toLowerCase();
            }
        } catch (Exception ignored) {
        }
        return CloudWmsInoutReportMode.IMMEDIATE;
    }
}