gongchunyi
9 小时以前 a83092b3ba022605ee08b547d4fa45c1f677fbeb
feat: 新增销售-质检-合格入库
已修改2个文件
975 ■■■■■ 文件已修改
src/main/java/com/ruoyi/common/enums/StockInQualifiedRecordTypeEnum.java 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java 972 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ruoyi/common/enums/StockInQualifiedRecordTypeEnum.java
@@ -14,7 +14,8 @@
    SALE_SCAN_STOCK_IN("17", "销售订单扫码-合格入库"),
    PURCHASE_SCAN_STOCK_IN("18", "采购订单扫码-合格入库"),
    PURCHASE_SCAN_QUALITY_STOCK_IN("19", "扫码入库质检-合格入库"),
    SALE_COUNTER_REVIEW_STOCK_IN("21", "销售-反审入库");
    SALE_COUNTER_REVIEW_STOCK_IN("21", "销售-反审入库"),
    SALE_QC_OK_IN("22", "销售-质检-合格入库");
    private final String code;
src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -75,8 +75,12 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
@@ -96,6 +100,7 @@
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -187,6 +192,8 @@
    private SysUserMapper sysUserMapper;
    private final ICustomerRegionsService customerRegionsService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Override
    public List<SalesLedger> selectSalesLedgerList(SalesLedgerDto salesLedgerDto) {
@@ -1821,7 +1828,7 @@
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(ApproveTypeEnum.STOCK_IN.getCode());
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveDeptId(208L);
        approveProcessVO.setApproveReason("入库审批:" + ledger.getSalesContractNo());
        approveProcessVO.setApproveRemark("salesStock:" + ledger.getId() + ":" + productIds);
        approveProcessVO.setApproveUserIds(approveUserIds);
@@ -1988,7 +1995,7 @@
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(ApproveTypeEnum.STOCK_IN.getCode());
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveDeptId(208L);
        approveProcessVO.setApproveReason(reason);
        approveProcessVO.setApproveRemark(remark);
        approveProcessVO.setApproveUserIds(approveUserIds);
@@ -2143,7 +2150,7 @@
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(ApproveTypeEnum.STOCK_IN.getCode());
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveDeptId(208L);
        approveProcessVO.setApproveReason(reason);
        approveProcessVO.setApproveRemark(remark);
        approveProcessVO.setApproveUserIds(approveUserIds);
@@ -2436,7 +2443,6 @@
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shippingImport(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("导入失败,导入文件数据不能为空");
@@ -2454,121 +2460,247 @@
        }
        Map<String, List<SalesShippingImportDto>> groupedByOrderNo = list.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(SalesShippingImportDto::getOrderNo, LinkedHashMap::new, Collectors.toList()));
        for (Map.Entry<String, List<SalesShippingImportDto>> entry : groupedByOrderNo.entrySet()) {
            String orderNo = entry.getKey();
            if (!StringUtils.hasText(orderNo)) {
                throw new ServiceException("导入失败,存在订单编号为空的数据");
            }
            List<SalesShippingImportDto> rowList = entry.getValue();
            if (CollectionUtils.isEmpty(rowList)) {
                continue;
            }
            if (StringUtils.hasText(rowList.get(0).getCustomerName()) && rowList.get(0).getCustomerName().startsWith("补片")) {
                continue;
            }
            SalesLedger ledger = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>().eq(SalesLedger::getSalesContractNo, orderNo).last("LIMIT 1"));
            if (ledger == null) {
//        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        List<String> errorMessages = Collections.synchronizedList(new ArrayList<>());
        groupedByOrderNo.forEach((orderNo, rowList) -> {
//            SecurityContext originalContext = SecurityContextHolder.getContext();
//            SecurityContext ctx = SecurityContextHolder.createEmptyContext();
//            ctx.setAuthentication(authentication);
//            SecurityContextHolder.setContext(ctx);
            try {
                if (!StringUtils.hasText(orderNo)) {
                    throw new ServiceException("导入失败,存在订单编号为空的数据");
                }
                if (CollectionUtils.isEmpty(rowList)) {
                    return;
                }
                if (StringUtils.hasText(rowList.get(0).getCustomerName()) && rowList.get(0).getCustomerName().startsWith("补片")) {
                    return;
                }
                rowList.sort(Comparator.comparing(r -> buildCategoryProductName(r) + "||" + buildSpecificationModel(r)));
                SalesLedger ledger = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>().eq(SalesLedger::getSalesContractNo, orderNo).last("LIMIT 1"));
                if (ledger == null) {
//                throw new ServiceException("导入失败,订单编号[" + orderNo + "]不存在,无法补录已发货数据");
                continue;
            }
            List<SalesLedgerProduct> dbProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()).eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
            if (CollectionUtils.isEmpty(dbProducts)) {
                throw new ServiceException("导入失败,订单编号[" + orderNo + "]没有销售产品,无法补录发货");
            }
            Map<String, List<SalesLedgerProduct>> productByCategory = dbProducts.stream().collect(Collectors.groupingBy(p -> StringUtils.hasText(p.getProductCategory()) ? p.getProductCategory().trim() : ""));
            Set<String> importedRowKeys = new HashSet<>();
                    return;
                }
                List<SalesLedgerProduct> dbProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()).eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
                if (CollectionUtils.isEmpty(dbProducts)) {
                    throw new ServiceException("导入失败,订单编号[" + orderNo + "]没有销售产品,无法补录发货");
                }
                dbProducts.sort(Comparator.comparing(SalesLedgerProduct::getProductModelId, Comparator.nullsLast(Comparator.naturalOrder())));
                Map<String, List<SalesLedgerProduct>> productByCategory = dbProducts.stream().collect(Collectors.groupingBy(p -> StringUtils.hasText(p.getProductCategory()) ? p.getProductCategory().trim() : ""));
                Set<String> importedRowKeys = new HashSet<>();
            for (SalesShippingImportDto row : rowList) {
                BigDecimal shipQty = defaultDecimal(row.getQuantity());
                if (shipQty.compareTo(BigDecimal.ZERO) <= 0) {
                    throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在数量小于等于0的数据");
                }
                String rowKey = buildShippingRowKey(ledger.getId(), row);
                if (!importedRowKeys.add(rowKey)) {
                    throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在重复发货明细行");
                }
                Map<SalesLedgerProduct, BigDecimal> allocations = allocateShippingProductLines(orderNo, row, productByCategory, dbProducts);
                for (Map.Entry<SalesLedgerProduct, BigDecimal> alloc : allocations.entrySet()) {
                    SalesLedgerProduct dbProduct = alloc.getKey();
                    BigDecimal allocQty = alloc.getValue();
                    if (dbProduct.getProductModelId() == null) {
                        throw new ServiceException("导入失败,订单编号[" + orderNo + "]产品规格未维护,无法补录出库");
                for (SalesShippingImportDto row : rowList) {
                    BigDecimal shipQty = defaultDecimal(row.getQuantity());
                    if (shipQty.compareTo(BigDecimal.ZERO) <= 0) {
                        throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在数量小于等于0的数据");
                    }
                    // 历史已发货补录:直接写入入库+出库记录
                    stockUtils.addStock(
                            ledger.getId(),
                            dbProduct.getId(),
                            dbProduct.getProductModelId(),
                            allocQty,
                            StockInQualifiedRecordTypeEnum.SALE_STOCK_IN.getCode(),
                            dbProduct.getId()
                    );
                    stockUtils.substractStock(
                            ledger.getId(),
                            dbProduct.getId(),
                            dbProduct.getProductModelId(),
                            allocQty,
                            StockOutQualifiedRecordTypeEnum.SALE_SHIP_STOCK_OUT.getCode(),
                            dbProduct.getId()
                    );
                    BigDecimal oldShipped = defaultDecimal(dbProduct.getShippedQuantity());
                    BigDecimal newShipped = oldShipped.add(allocQty);
                    dbProduct.setStockedQuantity(defaultDecimal(dbProduct.getQuantity()));
                    dbProduct.setShippedQuantity(newShipped);
                    dbProduct.setApproveStatus(3);
                    updateProductStockStatus(dbProduct);
                    dbProduct.fillRemainingQuantity();
                    updateProductShipStatus(dbProduct);
                    salesLedgerProductMapper.updateById(dbProduct);
                    String rowKey = buildShippingRowKey(ledger.getId(), row);
                    if (!importedRowKeys.add(rowKey)) {
                        throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在重复发货明细行");
                    }
                    Map<SalesLedgerProduct, BigDecimal> allocations = allocateShippingProductLines(orderNo, row, productByCategory, dbProducts);
                    for (Map.Entry<SalesLedgerProduct, BigDecimal> alloc : allocations.entrySet()) {
                        SalesLedgerProduct dbProduct = alloc.getKey();
                        BigDecimal allocQty = alloc.getValue();
                        if (dbProduct.getProductModelId() == null) {
                            throw new ServiceException("导入失败,订单编号[" + orderNo + "]产品规格未维护,无法补录出库");
                        }
                        Long inspectId = createShippingQualityInspect(ledger, dbProduct, row, allocQty);
                        // 历史已发货补录:直接写入入库+出库记录
                        stockUtils.addStock(
                                ledger.getId(),
                                dbProduct.getId(),
                                dbProduct.getProductModelId(),
                                allocQty,
                                StockInQualifiedRecordTypeEnum.SALE_QC_OK_IN.getCode(),
                                inspectId != null ? inspectId : dbProduct.getId()
                        );
                        stockUtils.substractStock(
                                ledger.getId(),
                                dbProduct.getId(),
                                dbProduct.getProductModelId(),
                                allocQty,
                                StockOutQualifiedRecordTypeEnum.SALE_SHIP_STOCK_OUT.getCode(),
                                dbProduct.getId()
                        );
                    ShippingInfo shippingInfo = new ShippingInfo();
                    shippingInfo.setSalesLedgerId(ledger.getId());
                    shippingInfo.setSalesLedgerProductId(dbProduct.getId());
                    shippingInfo.setStatus("已发货");
                    shippingInfo.setShippingNo(row.getShippingNo());
                    shippingInfo.setType("货车");
                    shippingInfo.setShippingCarNumber("无");
                    shippingInfo.setShippingDate(row.getReportDate());
                    long existedShippingCount = shippingInfoMapper.selectCount(new LambdaQueryWrapper<ShippingInfo>()
                            .eq(ShippingInfo::getSalesLedgerId, ledger.getId())
                            .eq(ShippingInfo::getSalesLedgerProductId, dbProduct.getId())
                            .eq(StringUtils.hasText(row.getShippingNo()), ShippingInfo::getShippingNo, row.getShippingNo())
                            .eq(row.getReportDate() != null, ShippingInfo::getShippingDate, row.getReportDate()));
                    if (existedShippingCount > 0) {
//                        continue;
                        List<ShippingInfo> shippingInfos = shippingInfoMapper.selectList(new LambdaQueryWrapper<ShippingInfo>()
                        StockInRecord inRecord = stockInRecordMapper.selectOne(new LambdaQueryWrapper<StockInRecord>()
                                .eq(StockInRecord::getSalesLedgerProductId, dbProduct.getId())
                                .orderByDesc(StockInRecord::getId).last("LIMIT 1"));
                        if (inRecord != null) {
                            String batch = "RK";
                            if (row.getReportDate() != null) {
                                String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(row.getReportDate());
                                batch += dateStr + "-" + row.getReportDate().getTime();
                            } else {
                                batch += System.currentTimeMillis() + "-" + inRecord.getId();
                            }
                            inRecord.setInboundBatches(batch);
                            if (row.getReportDate() != null) {
                                LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
                                inRecord.setCreateTime(reportDateTime);
                                inRecord.setUpdateTime(reportDateTime);
                            }
                            stockInRecordMapper.updateById(inRecord);
                        }
                        StockOutRecord outRecord = stockOutRecordMapper.selectOne(new LambdaQueryWrapper<StockOutRecord>()
                                .eq(StockOutRecord::getSalesLedgerProductId, dbProduct.getId())
                                .orderByDesc(StockOutRecord::getId).last("LIMIT 1"));
                        if (outRecord != null) {
                            String batch = "CK";
                            if (row.getReportDate() != null) {
                                String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(row.getReportDate());
                                batch += dateStr + "-" + row.getReportDate().getTime();
                            } else {
                                batch += System.currentTimeMillis() + "-" + outRecord.getId();
                            }
                            outRecord.setOutboundBatches(batch);
                            if (row.getReportDate() != null) {
                                LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
                                outRecord.setCreateTime(reportDateTime);
                                outRecord.setUpdateTime(reportDateTime);
                            }
                            stockOutRecordMapper.updateById(outRecord);
                        }
                        BigDecimal oldShipped = defaultDecimal(dbProduct.getShippedQuantity());
                        BigDecimal newShipped = oldShipped.add(allocQty);
                        dbProduct.setStockedQuantity(defaultDecimal(dbProduct.getQuantity()));
                        dbProduct.setShippedQuantity(newShipped);
                        dbProduct.setApproveStatus(3);
                        updateProductStockStatus(dbProduct);
                        dbProduct.fillRemainingQuantity();
                        updateProductShipStatus(dbProduct);
                        salesLedgerProductMapper.updateById(dbProduct);
                        ShippingInfo shippingInfo = new ShippingInfo();
                        shippingInfo.setSalesLedgerId(ledger.getId());
                        shippingInfo.setSalesLedgerProductId(dbProduct.getId());
                        shippingInfo.setStatus("已发货");
                        shippingInfo.setShippingNo(row.getShippingNo());
                        shippingInfo.setType("货车");
                        shippingInfo.setShippingCarNumber("无");
                        shippingInfo.setShippingDate(row.getReportDate());
                        long existedShippingCount = shippingInfoMapper.selectCount(new LambdaQueryWrapper<ShippingInfo>()
                                .eq(ShippingInfo::getSalesLedgerId, ledger.getId())
                                .eq(ShippingInfo::getSalesLedgerProductId, dbProduct.getId())
                                .eq(StringUtils.hasText(row.getShippingNo()), ShippingInfo::getShippingNo, row.getShippingNo())
                                .eq(row.getReportDate() != null, ShippingInfo::getShippingDate, row.getReportDate()));
                        throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在重复发货记录,请勿重复导入");
                        if (existedShippingCount > 0) {
//                        continue;
                            List<ShippingInfo> shippingInfos = shippingInfoMapper.selectList(new LambdaQueryWrapper<ShippingInfo>()
                                    .eq(ShippingInfo::getSalesLedgerId, ledger.getId())
                                    .eq(ShippingInfo::getSalesLedgerProductId, dbProduct.getId())
                                    .eq(StringUtils.hasText(row.getShippingNo()), ShippingInfo::getShippingNo, row.getShippingNo())
                                    .eq(row.getReportDate() != null, ShippingInfo::getShippingDate, row.getReportDate()));
                            throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在重复发货记录,请勿重复导入");
                        }
                        shippingInfoMapper.insert(shippingInfo);
                        // createShippingQualityInspect moved up
                    }
                    shippingInfoMapper.insert(shippingInfo);
                    createShippingQualityInspect(ledger, dbProduct, row, allocQty);
                }
            }
            List<SalesLedgerProduct> latestProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()).eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
            boolean allShipped = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().allMatch(p -> {
                BigDecimal qty = defaultDecimal(p.getQuantity());
                BigDecimal shipped = defaultDecimal(p.getShippedQuantity());
                return shipped.compareTo(qty) >= 0;
            });
            boolean anyInbound = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().anyMatch(p -> defaultDecimal(p.getStockedQuantity()).compareTo(BigDecimal.ZERO) > 0);
            boolean allInbound = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().allMatch(p -> {
                BigDecimal qty = defaultDecimal(p.getQuantity());
                BigDecimal stocked = defaultDecimal(p.getStockedQuantity());
                return qty.compareTo(BigDecimal.ZERO) <= 0 || stocked.compareTo(qty) >= 0;
            });
            if (allShipped && rowList.get(0).getReportDate() != null) {
                ledger.setDeliveryDate(DateUtils.toLocalDate(rowList.get(0).getReportDate()));
            }
            ledger.setStockStatus(allInbound ? 2 : (anyInbound ? 1 : 0));
            ledger.setDeliveryStatus(allShipped ? 5 : 1);
                List<SalesLedgerProduct> latestProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()).eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
                boolean allShipped = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().allMatch(p -> {
                    BigDecimal qty = defaultDecimal(p.getQuantity());
                    BigDecimal shipped = defaultDecimal(p.getShippedQuantity());
                    return shipped.compareTo(qty) >= 0;
                });
                boolean anyInbound = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().anyMatch(p -> defaultDecimal(p.getStockedQuantity()).compareTo(BigDecimal.ZERO) > 0);
                boolean allInbound = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().allMatch(p -> {
                    BigDecimal qty = defaultDecimal(p.getQuantity());
                    BigDecimal stocked = defaultDecimal(p.getStockedQuantity());
                    return qty.compareTo(BigDecimal.ZERO) <= 0 || stocked.compareTo(qty) >= 0;
                });
                if (allShipped && rowList.get(0).getReportDate() != null) {
                    ledger.setDeliveryDate(DateUtils.toLocalDate(rowList.get(0).getReportDate()));
                }
                ledger.setStockStatus(allInbound ? 2 : (anyInbound ? 1 : 0));
                ledger.setDeliveryStatus(allShipped ? 5 : 1);
//            ledger.setReviewStatus(1);
            ledger.setOrderStatus(1);
            salesLedgerMapper.updateById(ledger);
        }
                ledger.setOrderStatus(1);
                Long entryUserId = StringUtils.hasText(ledger.getEntryPerson()) ? Long.parseLong(ledger.getEntryPerson()) : 1L;
                Long entryDeptId = 1L;
                if (StringUtils.hasText(ledger.getEntryPerson())) {
                    try {
                        SysUser entryUser = sysUserMapper.selectById(ledger.getEntryPerson());
                        if (entryUser != null && entryUser.getDeptId() != null) {
                            entryDeptId = entryUser.getDeptId();
                        }
                    } catch (Exception ignored) {
                    }
                }
                String reportDateStr = rowList.get(0).getReportDate() != null ? new java.text.SimpleDateFormat("yyyy-MM-dd").format(rowList.get(0).getReportDate()) : java.time.LocalDate.now().toString();
                try {
                    String productIds = latestProducts.stream().map(p -> String.valueOf(p.getId())).collect(Collectors.joining(","));
                    String inboundApproveUserIds = resolveApproveUserIds(null, ledger.getId(), INBOUND_BIZ_TYPE_WEB);
                    if (StringUtils.isEmpty(inboundApproveUserIds)) {
                        inboundApproveUserIds = "1";
                    }
                    ApproveProcessVO stockInVo = new ApproveProcessVO();
                    stockInVo.setApproveType(ApproveTypeEnum.STOCK_IN.getCode());
                    stockInVo.setApproveDeptId(208L);
                    stockInVo.setApproveReason("入库审批:" + ledger.getSalesContractNo());
                    stockInVo.setApproveRemark("salesStock:" + ledger.getId() + ":" + productIds);
                    stockInVo.setApproveUserIds(inboundApproveUserIds);
                    stockInVo.setApproveUser(entryUserId);
                    stockInVo.setApproveTime(reportDateStr);
                    approveProcessService.addApprove(stockInVo);
                    ApproveProcess savedStockIn = approveProcessService.getOne(new LambdaQueryWrapper<ApproveProcess>()
                            .eq(ApproveProcess::getApproveReason, stockInVo.getApproveReason())
                            .eq(ApproveProcess::getApproveType, stockInVo.getApproveType())
                            .orderByDesc(ApproveProcess::getId).last("LIMIT 1"));
                    if (savedStockIn != null) {
                        savedStockIn.setApproveStatus(2);
                        savedStockIn.setApproveOverTime(rowList.get(0).getReportDate());
                        approveProcessService.updateById(savedStockIn);
                    }
                } catch (Exception e) {
                    log.error("自动生成入库审批申请失败", e);
                    throw new ServiceException("生成入库申请审批失败:{}" + e.getMessage());
                }
                try {
                    ApproveProcessVO deliveryVo = new ApproveProcessVO();
                    deliveryVo.setApproveType(ApproveTypeEnum.DELIVERY.getCode());
                    deliveryVo.setApproveDeptId(208L);
                    deliveryVo.setApproveReason("发货审批:" + ledger.getSalesContractNo());
                    deliveryVo.setApproveUserIds("1");
                    deliveryVo.setApproveUser(entryUserId);
                    deliveryVo.setApproveTime(reportDateStr);
                    approveProcessService.addApprove(deliveryVo);
                    ApproveProcess savedDelivery = approveProcessService.getOne(new LambdaQueryWrapper<ApproveProcess>()
                            .eq(ApproveProcess::getApproveReason, deliveryVo.getApproveReason())
                            .eq(ApproveProcess::getApproveType, deliveryVo.getApproveType())
                            .orderByDesc(ApproveProcess::getId).last("LIMIT 1"));
                    if (savedDelivery != null) {
                        savedDelivery.setApproveStatus(2);
                        savedDelivery.setApproveOverTime(rowList.get(0).getReportDate());
                        approveProcessService.updateById(savedDelivery);
                    }
                } catch (Exception e) {
                    log.error("自动生成发货审批申请失败", e);
                    throw new ServiceException("生成发货申请审批失败:{}" + e.getMessage());
                }
                    salesLedgerMapper.updateById(ledger);
                } catch (Exception e) {
                    log.error("订单 {} 已发货记录导入失败", orderNo, e);
//                    errorMessages.add("订单 [" + orderNo + "] 导入失败: " + e.getMessage());
                }
//            SecurityContextHolder.setContext(originalContext);
        });
//        if (!errorMessages.isEmpty()) {
//            throw new ServiceException("部分数据导入失败:\n" + String.join("\n", errorMessages));
//        }
    }
    @Override
@@ -2589,10 +2721,10 @@
            throw new ServiceException("导入失败,文件数据为空");
        }
        List<SysUser> allUsers = sysUserMapper.selectList(null);
        Map<String, SysUser> userByNickNameMap = allUsers.stream().filter(Objects::nonNull).filter(u -> StringUtils.hasText(u.getNickName())).collect(Collectors.toMap(SysUser::getNickName, Function.identity(), (a, b) -> a));
        Map<String, SysUser> userByUserNameMap = allUsers.stream().filter(Objects::nonNull).filter(u -> StringUtils.hasText(u.getUserName())).collect(Collectors.toMap(SysUser::getUserName, Function.identity(), (a, b) -> a));
        Map<String, SysUser> userByNickNameMap = new ConcurrentHashMap<>(allUsers.stream().filter(Objects::nonNull).filter(u -> StringUtils.hasText(u.getNickName())).collect(Collectors.toMap(SysUser::getNickName, Function.identity(), (a, b) -> a)));
        Map<String, SysUser> userByUserNameMap = new ConcurrentHashMap<>(allUsers.stream().filter(Objects::nonNull).filter(u -> StringUtils.hasText(u.getUserName())).collect(Collectors.toMap(SysUser::getUserName, Function.identity(), (a, b) -> a)));
        Map<String, Customer> customerNameMap = customerMapper.selectList(null).stream().filter(Objects::nonNull).filter(c -> StringUtils.hasText(c.getCustomerName())).collect(Collectors.toMap(Customer::getCustomerName, Function.identity(), (a, b) -> a));
        Map<String, Customer> customerNameMap = new ConcurrentHashMap<>(customerMapper.selectList(null).stream().filter(Objects::nonNull).filter(c -> StringUtils.hasText(c.getCustomerName())).collect(Collectors.toMap(Customer::getCustomerName, Function.identity(), (a, b) -> a)));
        List<CustomerRegions> allRegions = customerRegionsService.list();
        CustomerRegions hebiRegion = allRegions.stream().filter(Objects::nonNull).filter(r -> "鹤壁".equals(r.getRegionsName())).findFirst().orElseGet(() -> {
            CustomerRegions region = new CustomerRegions();
@@ -2601,7 +2733,7 @@
            customerRegionsService.save(region);
            return region;
        });
        Map<String, Product> productNameMap = productMapper.selectList(null).stream().filter(Objects::nonNull).filter(p -> StringUtils.hasText(p.getProductName())).collect(Collectors.toMap(Product::getProductName, Function.identity(), (a, b) -> a));
        Map<String, Product> productNameMap = new ConcurrentHashMap<>(productMapper.selectList(null).stream().filter(Objects::nonNull).filter(p -> StringUtils.hasText(p.getProductName())).collect(Collectors.toMap(Product::getProductName, Function.identity(), (a, b) -> a)));
        Product finishedGoodsParent = productNameMap.get("成品");
        if (finishedGoodsParent == null || finishedGoodsParent.getId() == null) {
            finishedGoodsParent = new Product();
@@ -2610,232 +2742,318 @@
            productMapper.insert(finishedGoodsParent);
            productNameMap.put("成品", finishedGoodsParent);
        }
        Map<String, ProductModel> productModelKeyMap = productModelMapper.selectList(null).stream().filter(Objects::nonNull).filter(m -> m.getProductId() != null && StringUtils.hasText(m.getModel())).collect(Collectors.toMap(m -> buildProductModelKey(m.getProductId(), m.getModel()), Function.identity(), (a, b) -> a));
        Map<String, ProductModel> productModelKeyMap = new ConcurrentHashMap<>(productModelMapper.selectList(null).stream().filter(Objects::nonNull).filter(m -> m.getProductId() != null && StringUtils.hasText(m.getModel())).collect(Collectors.toMap(m -> buildProductModelKey(m.getProductId(), m.getModel()), Function.identity(), (a, b) -> a)));
        List<String> extraProcessNames = Arrays.asList("打孔", "挖缺", "安全角", "磨边", "精磨边", "运费", "加急费");
        Map<String, SalesLedgerProductProcess> processMap = salesLedgerProductProcessService.list(new LambdaQueryWrapper<SalesLedgerProductProcess>().in(SalesLedgerProductProcess::getProcessName, extraProcessNames)).stream().filter(Objects::nonNull).filter(p -> StringUtils.hasText(p.getProcessName())).collect(Collectors.toMap(SalesLedgerProductProcess::getProcessName, Function.identity(), (a, b) -> a));
        Map<String, SalesLedgerProductProcess> processMap = new ConcurrentHashMap<>(salesLedgerProductProcessService.list(new LambdaQueryWrapper<SalesLedgerProductProcess>().in(SalesLedgerProductProcess::getProcessName, extraProcessNames)).stream().filter(Objects::nonNull).filter(p -> StringUtils.hasText(p.getProcessName())).collect(Collectors.toMap(SalesLedgerProductProcess::getProcessName, Function.identity(), (a, b) -> a)));
        List<ProcessRoute> processRoutes = processRouteMapper.selectList(new LambdaQueryWrapper<ProcessRoute>().eq(ProcessRoute::getProductModelId, 0L));
        Map<String, ProcessRoute> routeNameMap = processRoutes.stream().filter(Objects::nonNull).filter(r -> StringUtils.hasText(r.getProcessRouteName())).collect(Collectors.toMap(r -> normalizeRouteFlowKey(r.getProcessRouteName()), Function.identity(), this::chooseBetterRoute));
        Map<Long, List<ProcessRouteItem>> routeItemMap = Collections.emptyMap();
        Map<String, ProcessRoute> routeNameMap = new ConcurrentHashMap<>(processRoutes.stream().filter(Objects::nonNull).filter(r -> StringUtils.hasText(r.getProcessRouteName())).collect(Collectors.toMap(r -> normalizeRouteFlowKey(r.getProcessRouteName()), Function.identity(), this::chooseBetterRoute)));
        Map<Long, List<ProcessRouteItem>> routeItemMap = new ConcurrentHashMap<>();
        List<Long> routeIds = processRoutes.stream().map(ProcessRoute::getId).filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(routeIds)) {
            routeItemMap = processRouteItemMapper.selectList(new LambdaQueryWrapper<ProcessRouteItem>().in(ProcessRouteItem::getRouteId, routeIds).orderByAsc(ProcessRouteItem::getDragSort).orderByAsc(ProcessRouteItem::getId)).stream().filter(Objects::nonNull).collect(Collectors.groupingBy(ProcessRouteItem::getRouteId));
            routeItemMap.putAll(processRouteItemMapper.selectList(new LambdaQueryWrapper<ProcessRouteItem>().in(ProcessRouteItem::getRouteId, routeIds).orderByAsc(ProcessRouteItem::getDragSort).orderByAsc(ProcessRouteItem::getId)).stream().filter(Objects::nonNull).collect(Collectors.groupingBy(ProcessRouteItem::getRouteId)));
        }
        final Map<Long, List<ProcessRouteItem>> finalRouteItemMap = routeItemMap;
        final Product finalFinishedGoodsParent = finishedGoodsParent;
        Map<String, List<SalesNotShippingImportDto>> groupedByOrderNo = list.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(SalesNotShippingImportDto::getOrderNo, LinkedHashMap::new, Collectors.toList()));
        for (Map.Entry<String, List<SalesNotShippingImportDto>> entry : groupedByOrderNo.entrySet()) {
            String orderNo = entry.getKey();
            if (!StringUtils.hasText(orderNo)) {
                throw new ServiceException("导入失败,存在订单编号为空的数据");
            }
            List<SalesNotShippingImportDto> rowList = entry.getValue();
            if (CollectionUtils.isEmpty(rowList)) {
                continue;
            }
            SalesNotShippingImportDto first = rowList.get(0);
            SalesLedger exists = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>().eq(SalesLedger::getSalesContractNo, orderNo).last("LIMIT 1"));
            if (exists != null) {
                throw new ServiceException("导入失败,订单编号[" + orderNo + "]已存在");
            }
            SalesLedger ledger = new SalesLedger();
            SysUser creatorUser = resolveImportUser(first.getCreator(), userByNickNameMap, userByUserNameMap, "制单员", orderNo);
            ledger.setSalesContractNo(orderNo);
            ledger.setCustomerContractNo(first.getContractNo());
            ledger.setProjectName(first.getProjectName());
            ledger.setSalesman(first.getSalesman());
            Customer customer = getOrCreateImportCustomer(first.getCustomerName(), customerNameMap, hebiRegion.getId());
            ledger.setCustomerName(customer.getCustomerName());
            ledger.setRemarks(first.getRemark());
            ledger.setEntryPerson(String.valueOf(creatorUser.getUserId()));
            ledger.setEntryDate(first.getReportDate());
            if (first.getReportDate() != null) {
                ledger.setExecutionDate(DateUtils.toLocalDate(first.getReportDate()));
            }
            ledger.setDeliveryDate(first.getDeliveryDeadline() == null ? (first.getReportDate() == null ? LocalDate.now().plusDays(7) : DateUtils.toLocalDate(first.getReportDate()).plusDays(7)) : DateUtils.toLocalDate(first.getDeliveryDeadline()));
            ledger.setDeliveryStatus(1);
            ledger.setStockStatus(0);
            ledger.setReviewStatus(0);
            ledger.setCustomerId(customer.getId());
            ledger.setCustomerContractNo(StringUtils.hasText(ledger.getCustomerContractNo()) ? ledger.getCustomerContractNo() : customer.getTaxpayerIdentificationNumber());
            ledger.setContractAmount(BigDecimal.ZERO);
            salesLedgerMapper.insert(ledger);
            bindImportProcessRoute(ledger.getId(), rowList, routeNameMap, routeItemMap);
            int reviewCount = 0;
            BigDecimal contractAmount = BigDecimal.ZERO;
            for (SalesNotShippingImportDto row : rowList) {
                SalesLedgerProduct product = new SalesLedgerProduct();
                product.setSalesLedgerId(ledger.getId());
                product.setType(SaleEnum.SALE.getCode());
                String specificationModel = buildSpecificationModel(row);
                Product importProduct = resolveOrCreateImportProduct(row, productNameMap, finishedGoodsParent, orderNo);
                ProductModel importProductModel = resolveOrCreateImportProductModel(importProduct, specificationModel, row.getGlassThickness(), productModelKeyMap);
                product.setProductCategory(row.getProductSubCategory());
                product.setSpecificationModel(specificationModel);
                product.setProductId(importProduct.getId());
                product.setProductModelId(importProductModel.getId());
                product.setFloorCode(row.getFloorNo());
                product.setWidth(defaultDecimal(row.getWidth()));
                product.setHeight(defaultDecimal(row.getHeight()));
                product.setQuantity(defaultDecimal(row.getQuantity()));
                product.setActualPieceArea(defaultDecimal(row.getActualSingleArea()));
                product.setActualTotalArea(defaultDecimal(row.getActualTotalArea()));
                product.setSettlePieceArea(defaultDecimal(row.getSettlementSingleArea()));
                product.setSettleTotalArea(defaultDecimal(row.getSettlementTotalArea()));
                product.setTaxInclusiveUnitPrice(defaultDecimal(row.getUnitPrice()));
                product.setPerimeter(defaultDecimal(row.getPerimeter()));
                product.setHeavyBox(defaultDecimal(row.getHeavyBox()));
                product.setProcessRequirement(row.getProcessRequirement());
                product.setRemark(StringUtils.hasText(row.getAuditRemark()) ? row.getAuditRemark() : row.getRemark());
                product.setApproveStatus(0);
                product.setProductStockStatus(0);
                product.setRegister(creatorUser.getNickName());
                product.setRegisterDate(row.getReportDate() == null ? LocalDateTime.now() : LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault()));
                BigDecimal qty = defaultDecimal(product.getQuantity());
                if (qty.compareTo(BigDecimal.ZERO) <= 0) {
                    throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在数量小于等于0的数据");
//        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        List<String> errorMessages = Collections.synchronizedList(new ArrayList<>());
        groupedByOrderNo.forEach((orderNo, rowList) -> {
//            SecurityContext originalContext = SecurityContextHolder.getContext();
//            SecurityContext ctx = SecurityContextHolder.createEmptyContext();
//            ctx.setAuthentication(authentication);
//            SecurityContextHolder.setContext(ctx);
            try {
                if (!StringUtils.hasText(orderNo)) {
                    throw new ServiceException("导入失败,存在订单编号为空的数据");
                }
                BigDecimal lineAmount = defaultDecimal(row.getGlassAmount()).add(defaultDecimal(row.getOtherProcessFee()));
                if (lineAmount.compareTo(BigDecimal.ZERO) <= 0 && product.getTaxInclusiveUnitPrice().compareTo(BigDecimal.ZERO) > 0 && product.getSettleTotalArea().compareTo(BigDecimal.ZERO) > 0) {
                    lineAmount = product.getTaxInclusiveUnitPrice().multiply(product.getSettleTotalArea()).setScale(2, RoundingMode.HALF_UP);
                if (CollectionUtils.isEmpty(rowList)) {
                    return;
                }
                product.setTaxRate(BigDecimal.ZERO);
                product.setTaxInclusiveTotalPrice(lineAmount);
                product.setTaxExclusiveTotalPrice(lineAmount);
                product.setNoInvoiceNum(qty);
                product.setNoInvoiceAmount(lineAmount);
                product.setPendingInvoiceTotal(lineAmount);
                product.fillRemainingQuantity();
                salesLedgerProductMapper.insert(product);
                if (StringUtils.isNotEmpty(row.getAuditor())) {
                    reviewCount++;
                }
                List<SalesLedgerProductProcess> bindProcessList = buildImportProcessBinds(row, processMap);
                if (CollectionUtils.isNotEmpty(bindProcessList)) {
                    salesLedgerProductProcessBindService.updateProductProcessBind(bindProcessList, product.getId());
                }
                salesLedgerProductServiceImpl.addProductionData(product);
                contractAmount = contractAmount.add(lineAmount);
                if (customer.getCustomerName() != null && customer.getCustomerName().startsWith("补片")) {
                    stockUtils.addStock(
                            ledger.getId(),
                            product.getId(),
                            product.getProductModelId(),
                            qty,
                            StockInQualifiedRecordTypeEnum.SALE_STOCK_IN.getCode(),
                            product.getId()
                    );
                    stockUtils.substractStock(
                            ledger.getId(),
                            product.getId(),
                            product.getProductModelId(),
                            qty,
                            StockOutQualifiedRecordTypeEnum.SALE_SHIP_STOCK_OUT.getCode(),
                            product.getId()
                    );
                    StockInRecord inRecord = stockInRecordMapper.selectOne(new LambdaQueryWrapper<StockInRecord>()
                            .eq(StockInRecord::getSalesLedgerProductId, product.getId())
                            .orderByDesc(StockInRecord::getId).last("LIMIT 1"));
                    if (inRecord != null) {
                        String batch = "RK";
                        if (row.getReportDate() != null) {
                            String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(row.getReportDate());
                            batch += dateStr + "-" + row.getReportDate().getTime();
                        } else {
                            batch += System.currentTimeMillis() + "-" + inRecord.getId();
                        }
                        inRecord.setInboundBatches(batch);
                        if (row.getReportDate() != null) {
                            LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
                            inRecord.setCreateTime(reportDateTime);
                            inRecord.setUpdateTime(reportDateTime);
                        }
                        stockInRecordMapper.updateById(inRecord);
                    rowList.sort(Comparator.comparing(r -> buildCategoryProductName(r) + "||" + buildSpecificationModel(r)));
                    SalesNotShippingImportDto first = rowList.get(0);
                    SalesLedger exists = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>().eq(SalesLedger::getSalesContractNo, orderNo).last("LIMIT 1"));
                    if (exists != null) {
                        throw new ServiceException("导入失败,订单编号[" + orderNo + "]已存在");
                    }
                    StockOutRecord outRecord = stockOutRecordMapper.selectOne(new LambdaQueryWrapper<StockOutRecord>()
                            .eq(StockOutRecord::getSalesLedgerProductId, product.getId())
                            .orderByDesc(StockOutRecord::getId).last("LIMIT 1"));
                    if (outRecord != null) {
                        String batch = "CK";
                        if (row.getReportDate() != null) {
                            String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(row.getReportDate());
                            batch += dateStr + "-" + row.getReportDate().getTime();
                        } else {
                            batch += System.currentTimeMillis() + "-" + outRecord.getId();
                    SalesLedger ledger = new SalesLedger();
                    SysUser creatorUser = resolveImportUser(first.getCreator(), userByNickNameMap, userByUserNameMap, "制单员", orderNo);
                    ledger.setSalesContractNo(orderNo);
                    ledger.setCustomerContractNo(first.getContractNo());
                    ledger.setProjectName(first.getProjectName());
                    ledger.setSalesman(first.getSalesman());
                    Customer customer = getOrCreateImportCustomer(first.getCustomerName(), customerNameMap, hebiRegion.getId());
                    ledger.setCustomerName(customer.getCustomerName());
                    ledger.setRemarks(first.getRemark());
                    ledger.setEntryPerson(String.valueOf(creatorUser.getUserId()));
                    ledger.setEntryDate(first.getReportDate());
                    if (first.getReportDate() != null) {
                        ledger.setExecutionDate(DateUtils.toLocalDate(first.getReportDate()));
                    }
                    ledger.setDeliveryDate(first.getDeliveryDeadline() == null ? (first.getReportDate() == null ? LocalDate.now().plusDays(7) : DateUtils.toLocalDate(first.getReportDate()).plusDays(7)) : DateUtils.toLocalDate(first.getDeliveryDeadline()));
                    ledger.setDeliveryStatus(1);
                    ledger.setStockStatus(0);
                    ledger.setReviewStatus(0);
                    ledger.setCustomerId(customer.getId());
                    ledger.setCustomerContractNo(StringUtils.hasText(ledger.getCustomerContractNo()) ? ledger.getCustomerContractNo() : customer.getTaxpayerIdentificationNumber());
                    ledger.setContractAmount(BigDecimal.ZERO);
                    salesLedgerMapper.insert(ledger);
                    bindImportProcessRoute(ledger.getId(), rowList, routeNameMap, finalRouteItemMap);
                    int reviewCount = 0;
                    BigDecimal contractAmount = BigDecimal.ZERO;
                    for (SalesNotShippingImportDto row : rowList) {
                        SalesLedgerProduct product = new SalesLedgerProduct();
                        product.setSalesLedgerId(ledger.getId());
                        product.setType(SaleEnum.SALE.getCode());
                        String specificationModel = buildSpecificationModel(row);
                        Product importProduct = resolveOrCreateImportProduct(row, productNameMap, finalFinishedGoodsParent, orderNo);
                        ProductModel importProductModel = resolveOrCreateImportProductModel(importProduct, specificationModel, row.getGlassThickness(), productModelKeyMap);
                        product.setProductCategory(row.getProductSubCategory());
                        product.setSpecificationModel(specificationModel);
                        product.setProductId(importProduct.getId());
                        product.setProductModelId(importProductModel.getId());
                        product.setFloorCode(row.getFloorNo());
                        product.setWidth(defaultDecimal(row.getWidth()));
                        product.setHeight(defaultDecimal(row.getHeight()));
                        product.setQuantity(defaultDecimal(row.getQuantity()));
                        product.setActualPieceArea(defaultDecimal(row.getActualSingleArea()));
                        product.setActualTotalArea(defaultDecimal(row.getActualTotalArea()));
                        product.setSettlePieceArea(defaultDecimal(row.getSettlementSingleArea()));
                        product.setSettleTotalArea(defaultDecimal(row.getSettlementTotalArea()));
                        product.setTaxInclusiveUnitPrice(defaultDecimal(row.getUnitPrice()));
                        product.setPerimeter(defaultDecimal(row.getPerimeter()));
                        product.setHeavyBox(defaultDecimal(row.getHeavyBox()));
                        product.setProcessRequirement(row.getProcessRequirement());
                        product.setRemark(StringUtils.hasText(row.getAuditRemark()) ? row.getAuditRemark() : row.getRemark());
                        product.setApproveStatus(0);
                        product.setProductStockStatus(0);
                        product.setRegister(creatorUser.getNickName());
                        product.setRegisterDate(row.getReportDate() == null ? LocalDateTime.now() : LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault()));
                        BigDecimal qty = defaultDecimal(product.getQuantity());
                        if (qty.compareTo(BigDecimal.ZERO) <= 0) {
                            throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在数量小于等于0的数据");
                        }
                        outRecord.setOutboundBatches(batch);
                        if (row.getReportDate() != null) {
                            LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
                            outRecord.setCreateTime(reportDateTime);
                            outRecord.setUpdateTime(reportDateTime);
                        BigDecimal lineAmount = defaultDecimal(row.getGlassAmount()).add(defaultDecimal(row.getOtherProcessFee()));
                        if (lineAmount.compareTo(BigDecimal.ZERO) <= 0 && product.getTaxInclusiveUnitPrice().compareTo(BigDecimal.ZERO) > 0 && product.getSettleTotalArea().compareTo(BigDecimal.ZERO) > 0) {
                            lineAmount = product.getTaxInclusiveUnitPrice().multiply(product.getSettleTotalArea()).setScale(2, RoundingMode.HALF_UP);
                        }
                        stockOutRecordMapper.updateById(outRecord);
                        product.setTaxRate(BigDecimal.ZERO);
                        product.setTaxInclusiveTotalPrice(lineAmount);
                        product.setTaxExclusiveTotalPrice(lineAmount);
                        product.setNoInvoiceNum(qty);
                        product.setNoInvoiceAmount(lineAmount);
                        product.setPendingInvoiceTotal(lineAmount);
                        product.fillRemainingQuantity();
                        salesLedgerProductMapper.insert(product);
                        if (StringUtils.isNotEmpty(row.getAuditor())) {
                            reviewCount++;
                        }
                        List<SalesLedgerProductProcess> bindProcessList = buildImportProcessBinds(row, processMap);
                        if (CollectionUtils.isNotEmpty(bindProcessList)) {
                            salesLedgerProductProcessBindService.updateProductProcessBind(bindProcessList, product.getId());
                        }
                        // 本项目无生产模块,无需向 ProductOrder 表中新增数据
                        // salesLedgerProductServiceImpl.addProductionData(product);
                        contractAmount = contractAmount.add(lineAmount);
                        if (customer.getCustomerName() != null && customer.getCustomerName().startsWith("补片")) {
                            Long inspectId = createNotShippingQualityInspect(ledger, product, row, qty);
                            stockUtils.addStock(
                                    ledger.getId(),
                                    product.getId(),
                                    product.getProductModelId(),
                                    qty,
                                    StockInQualifiedRecordTypeEnum.SALE_QC_OK_IN.getCode(),
                                    inspectId != null ? inspectId : product.getId()
                            );
                            stockUtils.substractStock(
                                    ledger.getId(),
                                    product.getId(),
                                    product.getProductModelId(),
                                    qty,
                                    StockOutQualifiedRecordTypeEnum.SALE_SHIP_STOCK_OUT.getCode(),
                                    product.getId()
                            );
                            StockInRecord inRecord = stockInRecordMapper.selectOne(new LambdaQueryWrapper<StockInRecord>()
                                    .eq(StockInRecord::getSalesLedgerProductId, product.getId())
                                    .orderByDesc(StockInRecord::getId).last("LIMIT 1"));
                            if (inRecord != null) {
                                String batch = "RK";
                                if (row.getReportDate() != null) {
                                    String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(row.getReportDate());
                                    batch += dateStr + "-" + row.getReportDate().getTime();
                                } else {
                                    batch += System.currentTimeMillis() + "-" + inRecord.getId();
                                }
                                inRecord.setInboundBatches(batch);
                                if (row.getReportDate() != null) {
                                    LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
                                    inRecord.setCreateTime(reportDateTime);
                                    inRecord.setUpdateTime(reportDateTime);
                                }
                                stockInRecordMapper.updateById(inRecord);
                            }
                            StockOutRecord outRecord = stockOutRecordMapper.selectOne(new LambdaQueryWrapper<StockOutRecord>()
                                    .eq(StockOutRecord::getSalesLedgerProductId, product.getId())
                                    .orderByDesc(StockOutRecord::getId).last("LIMIT 1"));
                            if (outRecord != null) {
                                String batch = "CK";
                                if (row.getReportDate() != null) {
                                    String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(row.getReportDate());
                                    batch += dateStr + "-" + row.getReportDate().getTime();
                                } else {
                                    batch += System.currentTimeMillis() + "-" + outRecord.getId();
                                }
                                outRecord.setOutboundBatches(batch);
                                if (row.getReportDate() != null) {
                                    LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
                                    outRecord.setCreateTime(reportDateTime);
                                    outRecord.setUpdateTime(reportDateTime);
                                }
                                stockOutRecordMapper.updateById(outRecord);
                            }
                            product.setStockedQuantity(qty);
                            product.setShippedQuantity(qty);
                            product.setApproveStatus(3);
                            updateProductStockStatus(product);
                            product.fillRemainingQuantity();
                            updateProductShipStatus(product);
                            salesLedgerProductMapper.updateById(product);
                            ShippingInfo shippingInfo = new ShippingInfo();
                            shippingInfo.setSalesLedgerId(ledger.getId());
                            shippingInfo.setSalesLedgerProductId(product.getId());
                            shippingInfo.setStatus("已发货");
                            if (row.getReportDate() != null) {
                                String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(row.getReportDate());
                                shippingInfo.setShippingNo("CK" + dateStr + "-" + row.getReportDate().getTime());
                            } else {
                                shippingInfo.setShippingNo("CK" + System.currentTimeMillis());
                            }
                            shippingInfo.setType("货车");
                            shippingInfo.setShippingCarNumber("无");
                            shippingInfo.setShippingDate(row.getReportDate());
                            shippingInfoMapper.insert(shippingInfo);
                            // createNotShippingQualityInspect moved up
                        }
                    }
                    product.setStockedQuantity(qty);
                    product.setShippedQuantity(qty);
                    product.setApproveStatus(3);
                    updateProductStockStatus(product);
                    product.fillRemainingQuantity();
                    updateProductShipStatus(product);
                    salesLedgerProductMapper.updateById(product);
                    ShippingInfo shippingInfo = new ShippingInfo();
                    shippingInfo.setSalesLedgerId(ledger.getId());
                    shippingInfo.setSalesLedgerProductId(product.getId());
                    shippingInfo.setStatus("已发货");
                    if (row.getReportDate() != null) {
                        String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(row.getReportDate());
                        shippingInfo.setShippingNo("CK" + dateStr + "-" + row.getReportDate().getTime());
                    } else {
                        shippingInfo.setShippingNo("CK" + System.currentTimeMillis());
                    ledger.setContractAmount(contractAmount);
                    if (reviewCount == rowList.size()) {
                        ledger.setReviewStatus(1);
                    }
                    shippingInfo.setType("货车");
                    shippingInfo.setShippingCarNumber("无");
                    shippingInfo.setShippingDate(row.getReportDate());
                    shippingInfoMapper.insert(shippingInfo);
                    if (customer.getCustomerName() != null && customer.getCustomerName().startsWith("补片")) {
                        List<SalesLedgerProduct> latestProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()).eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
                        boolean allShipped = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().allMatch(p -> {
                            BigDecimal pQty = defaultDecimal(p.getQuantity());
                            BigDecimal shipped = defaultDecimal(p.getShippedQuantity());
                            return shipped.compareTo(pQty) >= 0;
                        });
                        boolean anyInbound = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().anyMatch(p -> defaultDecimal(p.getStockedQuantity()).compareTo(BigDecimal.ZERO) > 0);
                        boolean allInbound = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().allMatch(p -> {
                            BigDecimal pQty = defaultDecimal(p.getQuantity());
                            BigDecimal stocked = defaultDecimal(p.getStockedQuantity());
                            return pQty.compareTo(BigDecimal.ZERO) <= 0 || stocked.compareTo(pQty) >= 0;
                        });
                        if (allShipped && rowList.get(0).getReportDate() != null) {
                            ledger.setDeliveryDate(DateUtils.toLocalDate(rowList.get(0).getReportDate()));
                        }
                        ledger.setStockStatus(allInbound ? 2 : (anyInbound ? 1 : 0));
                        ledger.setDeliveryStatus(allShipped ? 5 : 1);
                        ledger.setOrderStatus(1);
                        Long entryUserId = StringUtils.hasText(ledger.getEntryPerson()) ? Long.parseLong(ledger.getEntryPerson()) : 1L;
                        Long entryDeptId = 1L;
                        if (StringUtils.hasText(ledger.getEntryPerson())) {
                            try {
                                SysUser entryUser = sysUserMapper.selectById(ledger.getEntryPerson());
                                if (entryUser != null && entryUser.getDeptId() != null) {
                                    entryDeptId = entryUser.getDeptId();
                                }
                            } catch (Exception ignored) {
                            }
                        }
                        String reportDateStr = rowList.get(0).getReportDate() != null ? new java.text.SimpleDateFormat("yyyy-MM-dd").format(rowList.get(0).getReportDate()) : LocalDate.now().toString();
                        try {
                            String productIds = latestProducts.stream().map(p -> String.valueOf(p.getId())).collect(Collectors.joining(","));
                            String inboundApproveUserIds = resolveApproveUserIds(null, ledger.getId(), INBOUND_BIZ_TYPE_WEB);
                            if (StringUtils.isEmpty(inboundApproveUserIds)) {
                                inboundApproveUserIds = "1";
                            }
                            ApproveProcessVO stockInVo = new ApproveProcessVO();
                            stockInVo.setApproveType(ApproveTypeEnum.STOCK_IN.getCode());
                            stockInVo.setApproveDeptId(208L);
                            stockInVo.setApproveReason("入库审批:" + ledger.getSalesContractNo());
                            stockInVo.setApproveRemark("salesStock:" + ledger.getId() + ":" + productIds);
                            stockInVo.setApproveUserIds(inboundApproveUserIds);
                            stockInVo.setApproveUser(entryUserId);
                            stockInVo.setApproveTime(reportDateStr);
                            approveProcessService.addApprove(stockInVo);
                            ApproveProcess savedStockIn = approveProcessService.getOne(new LambdaQueryWrapper<ApproveProcess>()
                                    .eq(ApproveProcess::getApproveReason, stockInVo.getApproveReason())
                                    .eq(ApproveProcess::getApproveType, stockInVo.getApproveType())
                                    .orderByDesc(ApproveProcess::getId).last("LIMIT 1"));
                            if (savedStockIn != null) {
                                savedStockIn.setApproveStatus(2);
                                savedStockIn.setApproveOverTime(rowList.get(0).getReportDate());
                                approveProcessService.updateById(savedStockIn);
                            }
                        } catch (Exception e) {
                            log.error("自动生成入库审批申请失败", e);
                        }
                        try {
                            ApproveProcessVO deliveryVo = new ApproveProcessVO();
                            deliveryVo.setApproveType(ApproveTypeEnum.DELIVERY.getCode());
                            deliveryVo.setApproveDeptId(208L);
                            deliveryVo.setApproveReason("发货审批:" + ledger.getSalesContractNo());
                            deliveryVo.setApproveUserIds("1");
                            deliveryVo.setApproveUser(entryUserId);
                            deliveryVo.setApproveTime(reportDateStr);
                            approveProcessService.addApprove(deliveryVo);
                            ApproveProcess savedDelivery = approveProcessService.getOne(new LambdaQueryWrapper<ApproveProcess>()
                                    .eq(ApproveProcess::getApproveReason, deliveryVo.getApproveReason())
                                    .eq(ApproveProcess::getApproveType, deliveryVo.getApproveType())
                                    .orderByDesc(ApproveProcess::getId).last("LIMIT 1"));
                            if (savedDelivery != null) {
                                savedDelivery.setApproveStatus(2);
                                savedDelivery.setApproveOverTime(rowList.get(0).getReportDate());
                                approveProcessService.updateById(savedDelivery);
                            }
                        } catch (Exception e) {
                            log.error("自动生成发货审批申请失败", e);
                        }
                    }
                    salesLedgerMapper.updateById(ledger);
                } catch (Exception e) {
                    log.error("订单 {} 未发货记录导入失败", orderNo, e);
//                    errorMessages.add("订单 [" + orderNo + "] 导入失败: " + e.getMessage());
                }
            }
            ledger.setContractAmount(contractAmount);
            if (reviewCount == rowList.size()) {
                ledger.setReviewStatus(1);
            }
            if (customer.getCustomerName() != null && customer.getCustomerName().startsWith("补片")) {
                List<SalesLedgerProduct> latestProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()).eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
                boolean allShipped = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().allMatch(p -> {
                    BigDecimal pQty = defaultDecimal(p.getQuantity());
                    BigDecimal shipped = defaultDecimal(p.getShippedQuantity());
                    return shipped.compareTo(pQty) >= 0;
                });
                boolean anyInbound = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().anyMatch(p -> defaultDecimal(p.getStockedQuantity()).compareTo(BigDecimal.ZERO) > 0);
                boolean allInbound = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().allMatch(p -> {
                    BigDecimal pQty = defaultDecimal(p.getQuantity());
                    BigDecimal stocked = defaultDecimal(p.getStockedQuantity());
                    return pQty.compareTo(BigDecimal.ZERO) <= 0 || stocked.compareTo(pQty) >= 0;
                });
                if (allShipped && rowList.get(0).getReportDate() != null) {
                    ledger.setDeliveryDate(DateUtils.toLocalDate(rowList.get(0).getReportDate()));
                }
                ledger.setStockStatus(allInbound ? 2 : (anyInbound ? 1 : 0));
                ledger.setDeliveryStatus(allShipped ? 5 : 1);
                ledger.setOrderStatus(1);
            }
            salesLedgerMapper.updateById(ledger);
        }
//            SecurityContextHolder.setContext(originalContext);
        });
//        if (!errorMessages.isEmpty()) {
//            throw new ServiceException("部分数据导入失败:\n" + String.join("\n", errorMessages));
//        }
    }
    private List<SalesLedgerProductProcess> buildImportProcessBinds(SalesNotShippingImportDto row, Map<String, SalesLedgerProductProcess> processMap) {
@@ -2900,6 +3118,11 @@
        if (CollectionUtils.isEmpty(processNames)) {
            throw new ServiceException("导入失败,工艺路线[" + flowKey + "]解析失败");
        }
        synchronized (("ROUTE_" + flowKey).intern()) {
            ProcessRoute exists = routeNameMap.get(flowKey);
            if (exists != null && exists.getId() != null) {
                return exists;
            }
        ProcessRoute route = new ProcessRoute();
        route.setProductModelId(0L);
        route.setProcessRouteName(flowKey);
@@ -2922,6 +3145,7 @@
        routeNameMap.put(flowKey, route);
        routeItemMap.put(route.getId(), routeItems);
        return route;
        }
    }
    private void mergeProcessQuantity(Map<String, Integer> processQuantityMap, String processName, Integer quantity) {
@@ -2998,12 +3222,18 @@
        if (exists != null && exists.getId() != null) {
            return exists;
        }
        synchronized (("CUSTOMER_" + key).intern()) {
            exists = customerNameMap.get(key);
            if (exists != null && exists.getId() != null) {
                return exists;
            }
        Customer customer = new Customer();
        customer.setCustomerName(key);
        customer.setRegionsId(hebiRegionId);
        customerMapper.insert(customer);
        customerNameMap.put(key, customer);
        return customer;
        }
    }
    private Product resolveOrCreateImportProduct(SalesNotShippingImportDto row, Map<String, Product> productNameMap, Product finishedGoodsParent, String orderNo) {
@@ -3025,12 +3255,18 @@
        if (!StringUtils.hasText(newProductName)) {
            throw new ServiceException("导入失败,订单编号[" + orderNo + "]产品名称和产品分类均为空");
        }
        synchronized (("PRODUCT_" + newProductName).intern()) {
            Product product = productNameMap.get(newProductName);
            if (product != null && product.getId() != null) {
                return product;
            }
        Product created = new Product();
        created.setParentId(finishedGoodsParent == null ? null : finishedGoodsParent.getId());
        created.setProductName(newProductName);
        productMapper.insert(created);
        productNameMap.put(newProductName, created);
        return created;
        }
    }
    private ProductModel resolveOrCreateImportProductModel(Product product, String modelName, BigDecimal thickness, Map<String, ProductModel> productModelKeyMap) {
@@ -3042,6 +3278,11 @@
        if (exists != null && exists.getId() != null) {
            return exists;
        }
        synchronized (("MODEL_" + key).intern()) {
            exists = productModelKeyMap.get(key);
            if (exists != null && exists.getId() != null) {
                return exists;
            }
        ProductModel created = new ProductModel();
        created.setProductId(product.getId());
        created.setModel(modelName.trim());
@@ -3050,9 +3291,23 @@
        productModelMapper.insert(created);
        productModelKeyMap.put(key, created);
        return created;
        }
    }
    private String buildSpecificationModel(SalesNotShippingImportDto row) {
        if (StringUtils.hasText(row.getProductName())) {
            return row.getProductName().trim();
        }
        if (StringUtils.hasText(row.getProductSubCategory())) {
            return row.getProductSubCategory().trim();
        }
        if (StringUtils.hasText(row.getProductCategory())) {
            return row.getProductCategory().trim();
        }
        return "";
    }
    private String buildSpecificationModel(SalesShippingImportDto row) {
        if (StringUtils.hasText(row.getProductName())) {
            return row.getProductName().trim();
        }
@@ -3171,13 +3426,14 @@
        return ledgerId + "|" + subCategory + "|" + shippingNo + "|" + dateStr + "|" + defaultDecimal(row.getQuantity()) + "|" + sequence;
    }
    private void createShippingQualityInspect(SalesLedger ledger, SalesLedgerProduct dbProduct, SalesShippingImportDto row, BigDecimal inspectQty) {
    private Long createShippingQualityInspect(SalesLedger ledger, SalesLedgerProduct dbProduct, SalesShippingImportDto row, BigDecimal inspectQty) {
        if (ledger == null || dbProduct == null || inspectQty == null || inspectQty.compareTo(BigDecimal.ZERO) <= 0) {
            return;
            return null;
        }
        Date checkDate = row.getReportDate() != null ? row.getReportDate() : new Date();
        QualityInspect qualityInspect = new QualityInspect();
        qualityInspect.setInspectType(2);
        qualityInspect.setPurchaseLedgerId(dbProduct.getId());
        qualityInspect.setCheckTime(checkDate);
        qualityInspect.setCustomer(StringUtils.hasText(ledger.getCustomerName()) ? ledger.getCustomerName() : row.getCustomerName());
        qualityInspect.setCheckName(StringUtils.hasText(row.getCreator()) ? row.getCreator().trim() : null);
@@ -3204,12 +3460,19 @@
        }
        qualityInspectMapper.insert(qualityInspect);
        if (row.getReportDate() != null) {
            LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
            qualityInspect.setCreateTime(reportDateTime);
            qualityInspect.setUpdateTime(reportDateTime);
            qualityInspectMapper.updateById(qualityInspect);
        }
        if (selectedStandard == null || selectedStandard.getId() == null) {
            return;
            return qualityInspect.getId();
        }
        List<QualityTestStandardParam> standardParams = qualityTestStandardParamMapper.selectList(Wrappers.<QualityTestStandardParam>lambdaQuery().eq(QualityTestStandardParam::getTestStandardId, selectedStandard.getId()));
        if (CollectionUtils.isEmpty(standardParams)) {
            return;
            return qualityInspect.getId();
        }
        List<QualityInspectParam> inspectParams = standardParams.stream().map(item -> {
            QualityInspectParam param = new QualityInspectParam();
@@ -3222,6 +3485,69 @@
            return param;
        }).collect(Collectors.toList());
        inspectParams.forEach(qualityInspectParamMapper::insert);
        return qualityInspect.getId();
    }
    private Long createNotShippingQualityInspect(SalesLedger ledger, SalesLedgerProduct dbProduct, SalesNotShippingImportDto row, BigDecimal inspectQty) {
        if (ledger == null || dbProduct == null || inspectQty == null || inspectQty.compareTo(BigDecimal.ZERO) <= 0) {
            return null;
        }
        Date checkDate = row.getReportDate() != null ? row.getReportDate() : new Date();
        QualityInspect qualityInspect = new QualityInspect();
        qualityInspect.setInspectType(2);
        qualityInspect.setPurchaseLedgerId(dbProduct.getId());
        qualityInspect.setCheckTime(checkDate);
        qualityInspect.setCustomer(StringUtils.hasText(ledger.getCustomerName()) ? ledger.getCustomerName() : row.getCustomerName());
        qualityInspect.setCheckName(StringUtils.hasText(row.getCreator()) ? row.getCreator().trim() : null);
        qualityInspect.setProductId(dbProduct.getProductId());
        qualityInspect.setProductName(dbProduct.getProductCategory());
        qualityInspect.setModel(dbProduct.getSpecificationModel());
        qualityInspect.setUnit(resolveInspectUnit(dbProduct));
        qualityInspect.setQuantity(inspectQty);
        qualityInspect.setQualifiedQuantity(inspectQty);
        qualityInspect.setUnqualifiedQuantity(BigDecimal.ZERO);
        qualityInspect.setPassRate(BigDecimal.valueOf(100));
        qualityInspect.setCheckResult("合格");
        qualityInspect.setInspectState(1);
        qualityInspect.setApprovalStatus(1);
        qualityInspect.setProductModelId(dbProduct.getProductModelId());
        QualityTestStandard selectedStandard = null;
        if (dbProduct.getProductId() != null) {
            List<QualityTestStandard> standards = qualityTestStandardMapper.getQualityTestStandardByProductId(dbProduct.getProductId(), 2, null);
            if (CollectionUtils.isNotEmpty(standards)) {
                selectedStandard = standards.get(0);
                qualityInspect.setTestStandardId(selectedStandard.getId());
            }
        }
        qualityInspectMapper.insert(qualityInspect);
        if (row.getReportDate() != null) {
            LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
            qualityInspect.setCreateTime(reportDateTime);
            qualityInspect.setUpdateTime(reportDateTime);
            qualityInspectMapper.updateById(qualityInspect);
        }
        if (selectedStandard == null || selectedStandard.getId() == null) {
            return qualityInspect.getId();
        }
        List<QualityTestStandardParam> standardParams = qualityTestStandardParamMapper.selectList(Wrappers.<QualityTestStandardParam>lambdaQuery().eq(QualityTestStandardParam::getTestStandardId, selectedStandard.getId()));
        if (CollectionUtils.isEmpty(standardParams)) {
            return qualityInspect.getId();
        }
        List<QualityInspectParam> inspectParams = standardParams.stream().map(item -> {
            QualityInspectParam param = new QualityInspectParam();
            param.setInspectId(qualityInspect.getId());
            param.setParameterItem(item.getParameterItem());
            param.setUnit(item.getUnit());
            param.setStandardValue(item.getStandardValue());
            param.setControlValue(item.getControlValue());
            param.setTestValue("无瑕疵");
            return param;
        }).collect(Collectors.toList());
        inspectParams.forEach(qualityInspectParamMapper::insert);
        return qualityInspect.getId();
    }
    private String resolveInspectUnit(SalesLedgerProduct dbProduct) {
@@ -3358,7 +3684,7 @@
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(7);
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveDeptId(208L);
        approveProcessVO.setApproveReason("发货审批:" + salesLedger.getSalesContractNo());
        approveProcessVO.setApproveRemark(remarkJson);
        approveProcessVO.setApproveUserIds(dto.getApproveUserIds().trim());