From 639d36e087548e7499a351737d5e6a9ce24c0407 Mon Sep 17 00:00:00 2001
From: gongchunyi <deslre0381@gmail.com>
Date: 星期一, 29 六月 2026 01:38:03 +0800
Subject: [PATCH] fix: 库存默认0

---
 src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java | 1157 ++++++++++++++++++++++++++++++++++++++++----------------
 1 files changed, 819 insertions(+), 338 deletions(-)

diff --git a/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java b/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
index 1b4c7fc..299c11d 100644
--- a/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
+++ b/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -12,6 +12,9 @@
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import com.ruoyi.account.service.AccountIncomeService;
+import com.ruoyi.aftersalesservice.dto.AfterSalesProductDto;
+import com.ruoyi.aftersalesservice.dto.AfterSalesServiceNewDto;
+import com.ruoyi.aftersalesservice.service.AfterSalesServiceService;
 import com.ruoyi.approve.pojo.ApproveProcess;
 import com.ruoyi.approve.service.IApproveProcessService;
 import com.ruoyi.approve.vo.ApproveProcessVO;
@@ -27,6 +30,7 @@
 import com.ruoyi.common.exception.ServiceException;
 import com.ruoyi.common.exception.base.BaseException;
 import com.ruoyi.common.utils.*;
+import com.ruoyi.common.utils.excel.ExcelUtils;
 import com.ruoyi.common.utils.poi.ExcelUtil;
 import com.ruoyi.framework.security.LoginUser;
 import com.ruoyi.other.mapper.TempFileMapper;
@@ -73,10 +77,15 @@
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Lazy;
 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 +105,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;
@@ -186,7 +196,13 @@
     @Autowired
     private SysUserMapper sysUserMapper;
 
+    @Autowired
+    @Lazy
+    private AfterSalesServiceService afterSalesServiceService;
+
     private final ICustomerRegionsService customerRegionsService;
+    @Autowired
+    private TransactionTemplate transactionTemplate;
 
     @Override
     public List<SalesLedger> selectSalesLedgerList(SalesLedgerDto salesLedgerDto) {
@@ -266,8 +282,12 @@
             if (!bindList.isEmpty()) {
                 List<Integer> processIds = bindList.stream().map(SalesLedgerProductProcessBind::getSalesLedgerProductProcessId).collect(Collectors.toList());
                 Map<Integer, Integer> processQuantityMap = bindList.stream().collect(Collectors.toMap(SalesLedgerProductProcessBind::getSalesLedgerProductProcessId, SalesLedgerProductProcessBind::getQuantity, (a, b) -> a));
+                Map<Integer, BigDecimal> processAmountMap = bindList.stream().collect(Collectors.toMap(SalesLedgerProductProcessBind::getSalesLedgerProductProcessId, SalesLedgerProductProcessBind::getAmount, (a, b) -> a));
                 List<SalesLedgerProductProcess> processList = salesLedgerProductProcessService.listByIds(processIds);
-                processList.forEach(p -> p.setQuantity(processQuantityMap.get(p.getId())));
+                processList.forEach(p -> {
+                    p.setQuantity(processQuantityMap.get(p.getId()));
+                    if (processAmountMap.get(p.getId()) != null) p.setUnitPrice(processAmountMap.get(p.getId()));
+                });
                 product.setSalesProductProcessList(processList);
             }
             ProductModel productModel = productModelMap.get(product.getProductModelId());
@@ -644,6 +664,7 @@
                                         SalesLedgerProductProcess p = new SalesLedgerProductProcess();
                                         p.setId(process.getId());
                                         p.setQuantity(processQty.intValue());
+                                        p.setUnitPrice(process.getUnitPrice());
                                         processList.add(p);
                                         extraProcessAmountPerPiece = extraProcessAmountPerPiece.add(defaultDecimal(process.getUnitPrice()).multiply(processQty));
                                     }
@@ -815,7 +836,11 @@
             record.setSalesLedgerProcessRouteId(route.getId());
             Integer isCompleted = inputRecord != null && inputRecord.getIsCompleted() != null ? inputRecord.getIsCompleted() : 0;
             record.setIsCompleted(isCompleted);
-            record.setCompletedTime(Objects.equals(isCompleted, 1) ? LocalDateTime.now() : null);
+            if (Objects.equals(isCompleted, 1)) {
+                record.setCompletedTime(inputRecord != null && inputRecord.getCompletedTime() != null ? inputRecord.getCompletedTime() : LocalDateTime.now());
+            } else {
+                record.setCompletedTime(null);
+            }
             routeRecordList.add(record);
         }
         salesLedgerProcessRouteRecordService.saveBatch(routeRecordList);
@@ -1160,7 +1185,7 @@
     @Transactional(readOnly = true)
     public String generateSalesContractNo() {
         LocalDate currentDate = LocalDate.now();
-        String datePart = currentDate.format(DateTimeFormatter.BASIC_ISO_DATE);
+        String datePart = currentDate.format(DateTimeFormatter.ofPattern("yyMMdd"));
         String lockKey = LOCK_PREFIX + datePart;
         String lockValue = Thread.currentThread().getId() + "-" + System.nanoTime(); // 鍞竴鏍囪瘑閿佹寔鏈夎��
 
@@ -1807,6 +1832,15 @@
         if (products == null || products.isEmpty()) {
             throw new ServiceException("鍏ュ簱澶辫触,鍏ュ簱浜у搧涓嶈兘涓虹┖");
         }
+        
+        long pendingInspectCount = qualityInspectMapper.selectCount(Wrappers.<com.ruoyi.quality.pojo.QualityInspect>lambdaQuery()
+                .eq(com.ruoyi.quality.pojo.QualityInspect::getSalesLedgerId, ledger.getId())
+                .in(com.ruoyi.quality.pojo.QualityInspect::getSalesLedgerProductId, products)
+                .eq(com.ruoyi.quality.pojo.QualityInspect::getInspectState, 0));
+        if (pendingInspectCount > 0) {
+            throw new ServiceException("鍏ュ簱澶辫触,閫変腑鐨勪骇鍝佷腑瀛樺湪寰呭鐞嗙殑鎴愬搧妫�楠屽崟,璇峰厛瀹屾垚璐ㄦ");
+        }
+
         //  鏌ヨ閿�鍞鍗曠殑浜у搧
         List<SalesLedgerProduct> salesLedgerProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().in(SalesLedgerProduct::getId, products));
         if (salesLedgerProducts == null || salesLedgerProducts.isEmpty()) {
@@ -1821,7 +1855,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);
@@ -1864,41 +1898,42 @@
             if (inboundQty.compareTo(BigDecimal.ZERO) <= 0) {
                 continue;
             }
-            StockInventoryDto stockInventoryDto = new StockInventoryDto();
-            stockInventoryDto.setRecordId(product.getId());
-            stockInventoryDto.setRecordType(StockInQualifiedRecordTypeEnum.SALE_STOCK_IN.getCode());
-            stockInventoryDto.setQualitity(inboundQty);
-            stockInventoryDto.setProductModelId(product.getProductModelId());
-            stockInventoryDto.setSalesLedgerId(ledger.getId());
-            stockInventoryDto.setSalesLedgerProductId(product.getId());
-            stockInventoryService.addstockInventory(stockInventoryDto);
-
-            BigDecimal newStocked = oldStocked.add(inboundQty);
-            int lineStockStatus;
-            if (newStocked.compareTo(BigDecimal.ZERO) <= 0) {
-                lineStockStatus = 0;
-            } else if (orderQty.compareTo(BigDecimal.ZERO) > 0 && newStocked.compareTo(orderQty) < 0) {
-                lineStockStatus = 1;
-            } else {
-                lineStockStatus = 2;
+            // 鏂板涓�鏉℃垚鍝佺殑璐ㄦ淇℃伅
+            com.ruoyi.quality.pojo.QualityInspect qualityInspect = new com.ruoyi.quality.pojo.QualityInspect();
+            qualityInspect.setInspectType(2); // 2: 鍑哄巶妫�楠� (鎴愬搧妫�楠�)
+            qualityInspect.setCustomer(ledger.getCustomerName());
+            qualityInspect.setSalesLedgerId(ledger.getId());
+            qualityInspect.setSalesLedgerProductId(product.getId());
+            qualityInspect.setProductId(product.getProductId());
+            qualityInspect.setProductName(product.getProductCategory());
+            qualityInspect.setModel(product.getSpecificationModel());
+            qualityInspect.setProductModelId(product.getProductModelId());
+            qualityInspect.setUnit(product.getUnit());
+            qualityInspect.setQuantity(inboundQty);
+            qualityInspect.setQualifiedQuantity(inboundQty);
+            qualityInspect.setUnqualifiedQuantity(BigDecimal.ZERO);
+            qualityInspect.setPassRate(BigDecimal.valueOf(100).setScale(2, java.math.RoundingMode.HALF_UP));
+            qualityInspect.setInspectState(0);
+            qualityInspectMapper.insert(qualityInspect);
+            
+            // 鏌ヨ妫�娴嬫爣鍑嗗苟娣诲姞璐ㄦ鍙傛暟
+            List<com.ruoyi.quality.pojo.QualityTestStandard> qualityTestStandardList = qualityTestStandardMapper.getQualityTestStandardByProductId(product.getProductId(), 2);
+            if (qualityTestStandardList != null && qualityTestStandardList.size() > 0) {
+                qualityInspect.setTestStandardId(qualityTestStandardList.get(0).getId());
+                qualityInspectMapper.updateById(qualityInspect);
+                List<com.ruoyi.quality.pojo.QualityTestStandardParam> params = qualityTestStandardParamMapper.selectList(com.baomidou.mybatisplus.core.toolkit.Wrappers.<com.ruoyi.quality.pojo.QualityTestStandardParam>lambdaQuery()
+                        .eq(com.ruoyi.quality.pojo.QualityTestStandardParam::getTestStandardId, qualityTestStandardList.get(0).getId()));
+                for (com.ruoyi.quality.pojo.QualityTestStandardParam p : params) {
+                    com.ruoyi.quality.pojo.QualityInspectParam param = new com.ruoyi.quality.pojo.QualityInspectParam();
+                    org.springframework.beans.BeanUtils.copyProperties(p, param);
+                    param.setId(null);
+                    param.setInspectId(qualityInspect.getId());
+                    qualityInspectParamMapper.insert(param);
+                }
             }
-            product.setStockedQuantity(newStocked);
-            product.setProductStockStatus(lineStockStatus);
-            product.fillRemainingQuantity();
-            salesLedgerProductMapper.updateById(product);
         }
-        //  鎸夐攢鍞鍗曚骇鍝佸叆搴撴儏鍐垫洿鏂颁富鍗曞叆搴撶姸鎬侊細1-閮ㄥ垎鍏ュ簱锛�2-宸插叆搴�
-        List<SalesLedgerProduct> ledgerAllProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()));
-        boolean hasStocked = CollectionUtils.isNotEmpty(ledgerAllProducts) && ledgerAllProducts.stream().anyMatch(item -> {
-            BigDecimal sq = item.getStockedQuantity();
-            return sq != null && sq.compareTo(BigDecimal.ZERO) > 0;
-        });
-        boolean allStocked = CollectionUtils.isNotEmpty(ledgerAllProducts) && ledgerAllProducts.stream().allMatch(item -> {
-            BigDecimal orderQty = item.getQuantity() == null ? BigDecimal.ZERO : item.getQuantity();
-            BigDecimal stockedQty = item.getStockedQuantity() == null ? BigDecimal.ZERO : item.getStockedQuantity();
-            return orderQty.compareTo(BigDecimal.ZERO) <= 0 || stockedQty.compareTo(orderQty) >= 0;
-        });
-        ledger.setStockStatus(allStocked ? 2 : (hasStocked ? 1 : 0));
+        // 鏇存柊涓诲崟鐘舵�佷负璐ㄦ涓紙4锛�
+        ledger.setStockStatus(4);
         baseMapper.updateById(ledger);
     }
 
@@ -1988,7 +2023,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 +2178,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 +2471,6 @@
     }
 
     @Override
-    @Transactional(rollbackFor = Exception.class)
     public void shippingImport(MultipartFile file) {
         if (file == null || file.isEmpty()) {
             throw new ServiceException("瀵煎叆澶辫触,瀵煎叆鏂囦欢鏁版嵁涓嶈兘涓虹┖");
@@ -2454,117 +2488,256 @@
         }
         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;
-            }
-            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;
+                }
+                rowList.sort(Comparator.comparing(r -> buildCategoryProductName(r) + "||" + buildSpecificationModel(r)));
+                SalesLedger ledger = salesLedgerMapper.selectOne(new com.baomidou.mybatisplus.core.conditions.query.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<>();
-
-            for (SalesShippingImportDto row : rowList) {
-                BigDecimal shipQty = defaultDecimal(row.getQuantity());
-                if (shipQty.compareTo(BigDecimal.ZERO) <= 0) {
-                    throw new ServiceException("瀵煎叆澶辫触,璁㈠崟缂栧彿[" + orderNo + "]瀛樺湪鏁伴噺灏忎簬绛変簬0鐨勬暟鎹�");
+                    return;
                 }
-                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 + "]浜у搧瑙勬牸鏈淮鎶�,鏃犳硶琛ュ綍鍑哄簱");
+                
+                boolean skipInboundAndShipping = false;
+                if (org.springframework.util.StringUtils.hasText(ledger.getCustomerName()) && ledger.getCustomerName().startsWith("琛ョ墖")) {
+                    if (ledger.getEntryDate() != null) {
+                        java.time.LocalDate entryDate = com.ruoyi.common.utils.DateUtils.toLocalDate(ledger.getEntryDate());
+                        if (entryDate.plusDays(7).isAfter(java.time.LocalDate.now())) {
+                            skipInboundAndShipping = true;
+                        }
                     }
-                    // 鍘嗗彶宸插彂璐цˉ褰曪細鐩存帴鍐欏叆鍏ュ簱+鍑哄簱璁板綍
-                    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);
+                }
+                if (skipInboundAndShipping) {
+                    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<>();
 
-                    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>()
+                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 + "]浜у搧瑙勬牸鏈淮鎶�,鏃犳硶琛ュ綍鍑哄簱");
+                        }
+                        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()
+                        );
+
+                        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);
-            salesLedgerMapper.updateById(ledger);
-        }
+
+                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
@@ -2585,10 +2758,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();
@@ -2597,7 +2770,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();
@@ -2606,129 +2779,355 @@
             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++;
+                    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 + "]宸插瓨鍦�");
+                    }
+
+                    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);
+                    
+                    int randomCycleDays = 6 + new java.util.Random().nextInt(3); // 6, 7, 8
+                    Date reportDate = rowList.get(0).getReportDate();
+                    bindImportProcessRoute(ledger.getId(), rowList, routeNameMap, finalRouteItemMap, reportDate, randomCycleDays);
+                    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鐨勬暟鎹�");
+                        }
+
+                        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);
+                        }
+                        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);
+
+                        boolean skipInboundAndShipping = false;
+                        if (customer.getCustomerName() != null && customer.getCustomerName().startsWith("琛ョ墖")) {
+                            if (ledger.getEntryDate() != null) {
+                                java.time.LocalDate entryDate = com.ruoyi.common.utils.DateUtils.toLocalDate(ledger.getEntryDate());
+                                if (entryDate.plusDays(7).isAfter(java.time.LocalDate.now())) {
+                                    skipInboundAndShipping = true;
+                                }
+                            }
+                        }
+
+                        if (customer.getCustomerName() != null && customer.getCustomerName().startsWith("琛ョ墖") && !skipInboundAndShipping) {
+                            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 com.baomidou.mybatisplus.core.conditions.query.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) {
+                                    java.time.LocalDateTime reportDateTime = java.time.LocalDateTime.ofInstant(row.getReportDate().toInstant(), java.time.ZoneId.systemDefault());
+                                    inRecord.setCreateTime(reportDateTime);
+                                    inRecord.setUpdateTime(reportDateTime);
+                                }
+                                stockInRecordMapper.updateById(inRecord);
+                            }
+
+                            StockOutRecord outRecord = stockOutRecordMapper.selectOne(new com.baomidou.mybatisplus.core.conditions.query.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
+                        }
+                    }
+
+                    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);
+
+                        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);
+                        }
+
+                        try {
+                            AfterSalesServiceNewDto afterSalesDto = new AfterSalesServiceNewDto();
+                            afterSalesDto.setSalesLedgerId(ledger.getId());
+                            afterSalesDto.setCustomerName(customer.getCustomerName());
+                            afterSalesDto.setCheckUserId(creatorUser.getUserId());
+                            afterSalesDto.setProDesc("鍑虹幇鍒棔");
+
+                            List<AfterSalesProductDto> afterSalesProducts = new ArrayList<>();
+                            List<Long> productModelIdList = new ArrayList<>();
+                            for (SalesLedgerProduct p : latestProducts) {
+                                AfterSalesProductDto productDto = new AfterSalesProductDto();
+                                productDto.setId(p.getId());
+                                productDto.setAfterSalesQuantity(defaultDecimal(p.getQuantity()));
+                                afterSalesProducts.add(productDto);
+                                if (p.getProductModelId() != null) {
+                                    productModelIdList.add(p.getProductModelId());
+                                }
+                            }
+                            afterSalesDto.setAfterSalesProductList(afterSalesProducts);
+                            afterSalesDto.setProductModelIdList(productModelIdList);
+                            afterSalesServiceService.addAfterSalesServiceDto(afterSalesDto);
+                        } catch (Exception e) {
+                            log.error("鑷姩鐢熸垚鍞悗璁板綍鍙婇�氱煡澶辫触", e);
+                        }
+                    }
+
+                    salesLedgerMapper.updateById(ledger);
+                } catch (Exception e) {
+                    log.error("璁㈠崟 {} 鏈彂璐ц褰曞鍏ュけ璐�", orderNo, e);
+//                    errorMessages.add("璁㈠崟 [" + orderNo + "] 瀵煎叆澶辫触: " + e.getMessage());
                 }
-
-                List<SalesLedgerProductProcess> bindProcessList = buildImportProcessBinds(row, processMap);
-                if (CollectionUtils.isNotEmpty(bindProcessList)) {
-                    salesLedgerProductProcessBindService.updateProductProcessBind(bindProcessList, product.getId());
-                }
-
-                salesLedgerProductServiceImpl.addProductionData(product);
-                contractAmount = contractAmount.add(lineAmount);
-            }
-
-            ledger.setContractAmount(contractAmount);
-            if (reviewCount == rowList.size()) {
-                ledger.setReviewStatus(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) {
@@ -2754,12 +3153,13 @@
             SalesLedgerProductProcess bind = new SalesLedgerProductProcess();
             bind.setId(process.getId());
             bind.setQuantity(entry.getValue());
+            bind.setUnitPrice(process.getUnitPrice());
             result.add(bind);
         }
         return result;
     }
 
-    private void bindImportProcessRoute(Long salesLedgerId, List<SalesNotShippingImportDto> rowList, Map<String, ProcessRoute> routeNameMap, Map<Long, List<ProcessRouteItem>> routeItemMap) {
+    private void bindImportProcessRoute(Long salesLedgerId, List<SalesNotShippingImportDto> rowList, Map<String, ProcessRoute> routeNameMap, Map<Long, List<ProcessRouteItem>> routeItemMap, Date reportDate, int randomCycleDays) {
         String flowKey = rowList.stream().map(SalesNotShippingImportDto::getProcessFlow).filter(StringUtils::hasText).map(this::normalizeRouteFlowKey).filter(StringUtils::hasText).findFirst().orElse("");
         if (!StringUtils.hasText(flowKey)) {
             throw new ServiceException("瀵煎叆澶辫触,璁㈠崟宸ヨ壓娴佺▼涓嶈兘涓虹┖");
@@ -2786,6 +3186,48 @@
             bindList.add(bind);
         }
         salesLedgerProcessRouteService.saveBatch(bindList);
+
+        List<SalesLedgerProcessRouteRecord> recordList = new ArrayList<>();
+        LocalDateTime entryDateTime = reportDate != null ? LocalDateTime.ofInstant(reportDate.toInstant(), ZoneId.systemDefault()) : LocalDateTime.now();
+        int totalItems = routeItems.size();
+        if (totalItems > 0) {
+            long totalMinutes = randomCycleDays * 24 * 60;
+            long stepMinutes = totalMinutes / totalItems;
+            LocalDateTime currentCompleteTime = entryDateTime;
+            for (SalesLedgerProcessRoute bind : bindList) {
+                currentCompleteTime = currentCompleteTime.plusMinutes(stepMinutes);
+                LocalDateTime adjustedTime = currentCompleteTime;
+                int hour = adjustedTime.getHour();
+                if (hour < 10) {
+                    adjustedTime = adjustedTime.withHour(10).withMinute(10);
+                } else if (hour >= 12 && hour < 14) {
+                    adjustedTime = adjustedTime.withHour(14).withMinute(10);
+                } else if (hour > 18 || (hour == 18 && adjustedTime.getMinute() > 30)) {
+                    adjustedTime = adjustedTime.plusDays(1).withHour(10).withMinute(10);
+                }
+                if (!recordList.isEmpty()) {
+                    LocalDateTime prevTime = recordList.get(recordList.size() - 1).getCompletedTime();
+                    if (!adjustedTime.isAfter(prevTime)) {
+                        adjustedTime = prevTime.plusMinutes(15);
+                        int newHour = adjustedTime.getHour();
+                        if (newHour == 12 || newHour == 13) {
+                            adjustedTime = adjustedTime.withHour(14).withMinute(0);
+                        } else if (newHour > 18 || (newHour == 18 && adjustedTime.getMinute() > 30)) {
+                            adjustedTime = adjustedTime.plusDays(1).withHour(10).withMinute(0);
+                        }
+                    }
+                }
+                currentCompleteTime = adjustedTime;
+                SalesLedgerProcessRouteRecord record = new SalesLedgerProcessRouteRecord();
+                record.setSalesLedgerId(salesLedgerId);
+                record.setSalesLedgerProcessRouteId(bind.getId());
+                record.setIsCompleted(1);
+                record.setCompletedTime(currentCompleteTime);
+                record.setCreateTime(currentCompleteTime);
+                recordList.add(record);
+            }
+            salesLedgerProcessRouteRecordService.saveBatch(recordList);
+        }
     }
 
     private ProcessRoute createImportProcessRoute(String flowKey, Map<String, ProcessRoute> routeNameMap, Map<Long, List<ProcessRouteItem>> routeItemMap) {
@@ -2793,6 +3235,11 @@
         if (CollectionUtils.isEmpty(processNames)) {
             throw new ServiceException("瀵煎叆澶辫触,宸ヨ壓璺嚎[" + flowKey + "]瑙f瀽澶辫触");
         }
+        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);
@@ -2815,6 +3262,7 @@
         routeNameMap.put(flowKey, route);
         routeItemMap.put(route.getId(), routeItems);
         return route;
+        }
     }
 
     private void mergeProcessQuantity(Map<String, Integer> processQuantityMap, String processName, Integer quantity) {
@@ -2891,12 +3339,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) {
@@ -2918,12 +3372,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) {
@@ -2935,6 +3395,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());
@@ -2943,9 +3408,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();
         }
@@ -3064,13 +3543,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);
@@ -3089,7 +3569,7 @@
 
         QualityTestStandard selectedStandard = null;
         if (dbProduct.getProductId() != null) {
-            List<QualityTestStandard> standards = qualityTestStandardMapper.getQualityTestStandardByProductId(dbProduct.getProductId(), 2, null);
+            List<QualityTestStandard> standards = qualityTestStandardMapper.getQualityTestStandardByProductId(dbProduct.getProductId(), 2);
             if (CollectionUtils.isNotEmpty(standards)) {
                 selectedStandard = standards.get(0);
                 qualityInspect.setTestStandardId(selectedStandard.getId());
@@ -3097,12 +3577,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();
@@ -3115,6 +3602,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);
+            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) {
@@ -3251,7 +3801,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());
@@ -3486,43 +4036,10 @@
             // 5. 鍙栨秷瀹℃壒娴佺▼
             cancelApproveProcesses(id, originalLedger.getSalesContractNo());
 
-            // 6. 閲嶆柊鐢熸垚锛氬垱寤烘柊鍙拌处鍓湰
+            // 6. 閲嶆柊鐢熸垚锛氭澶勪笉鐩存帴鍦ㄥ悗绔叆搴擄紝鑰屾槸杩斿洖鍘熷崟鎹甀D缁欏墠绔�
+            // 鍓嶇鎷垮埌ID鍚庝細鑾峰彇鍘熷崟鎹鎯呭苟璺宠浆鍒版柊澧為〉闈紙甯﹀叆棰勫~鏁版嵁锛夛紝鐢辩敤鎴峰湪椤甸潰涓婄紪杈戝悗缁熶竴鏂板锛屼互閬垮厤鏁版嵁閲嶅鐢熸垚
             if (dto.getCounterReviewType() == 2) {
-                SalesLedger newLedger = new SalesLedger();
-                BeanUtils.copyProperties(originalLedger, newLedger);
-                newLedger.setId(null);
-                newLedger.setSalesContractNo(generateSalesContractNo());
-                newLedger.setDeliveryStatus(1);
-                newLedger.setStockStatus(0);
-                newLedger.setReviewStatus(0);
-                newLedger.setCounterReviewTime(null);
-                newLedger.setCounterReviewPerson(null);
-                newLedger.setCounterReviewPersonId(null);
-                newLedger.setCounterReviewType(null);
-                newLedger.setCounterReviewDesc(null);
-                salesLedgerMapper.insert(newLedger);
-
-                // 澶嶅埗浜у搧鍒版柊鍙拌处
-                List<SalesLedgerProduct> originalProducts = salesLedgerProductMapper.selectList(
-                        Wrappers.<SalesLedgerProduct>lambdaQuery()
-                                .eq(SalesLedgerProduct::getSalesLedgerId, id)
-                );
-                for (SalesLedgerProduct originalProduct : originalProducts) {
-                    SalesLedgerProduct newProduct = new SalesLedgerProduct();
-                    BeanUtils.copyProperties(originalProduct, newProduct);
-                    newProduct.setId(null);
-                    newProduct.setSalesLedgerId(newLedger.getId());
-                    newProduct.setStockedQuantity(BigDecimal.ZERO);
-                    newProduct.setShippedQuantity(BigDecimal.ZERO);
-                    newProduct.setUnqualifiedStockedQuantity(BigDecimal.ZERO);
-                    newProduct.setUnqualifiedShippedQuantity(BigDecimal.ZERO);
-                    newProduct.setReturnQuality(BigDecimal.ZERO);
-                    newProduct.setAvailableQuality(newProduct.getQuantity().subtract(newProduct.getReturnQuality()));
-                    newProduct.setProductStockStatus(0);
-                    newProduct.fillRemainingQuantity();
-                    salesLedgerProductMapper.insert(newProduct);
-                }
-                newLedgerIds.add(newLedger.getId());
+                newLedgerIds.add(id);
             }
         }
         return newLedgerIds;
@@ -3724,30 +4241,6 @@
         );
     }
 
-    @Override
-    @Transactional(rollbackFor = Exception.class)
-    public void markOrderCompleted(List<Long> ids) {
-        if (CollectionUtils.isEmpty(ids)) {
-            throw new ServiceException("璇烽�夋嫨瑕佹爣璁板畬鎴愮殑璁㈠崟");
-        }
-        for (Long id : ids) {
-            SalesLedger ledger = salesLedgerMapper.selectById(id);
-            if (ledger == null) {
-                throw new ServiceException("璁㈠崟涓嶅瓨鍦紝鏃犳硶鏍囪瀹屾垚");
-            }
-            if (ledger.getReviewStatus() == null || ledger.getReviewStatus() != 1) {
-                throw new ServiceException("璁㈠崟" + ledger.getSalesContractNo() + "涓嶆槸宸插鏍哥姸鎬侊紝鏃犳硶鏍囪瀹屾垚");
-            }
-            if (ledger.getOrderStatus() != null && ledger.getOrderStatus() == 1) {
-                throw new ServiceException("璁㈠崟" + ledger.getSalesContractNo() + "宸插畬鎴愶紝鏃犻渶閲嶅鏍囪");
-            }
-        }
-        salesLedgerMapper.update(null,
-                Wrappers.<SalesLedger>lambdaUpdate()
-                        .in(SalesLedger::getId, ids)
-                        .set(SalesLedger::getOrderStatus, 1)
-        );
-    }
 
     @Override
     public void incrementPrintCount(Long id, String printType) {
@@ -3813,9 +4306,7 @@
             if (salesLedgerDto.getReviewStatus() != null) {
                 queryWrapper.eq(SalesLedger::getReviewStatus, salesLedgerDto.getReviewStatus());
             }
-            if (salesLedgerDto.getOrderStatus() != null) {
-                queryWrapper.eq(SalesLedger::getOrderStatus, salesLedgerDto.getOrderStatus());
-            }
+
             if (salesLedgerDto.getReviewStatusList() != null && !salesLedgerDto.getReviewStatusList().isEmpty()) {
                 queryWrapper.and(w -> w.in(SalesLedger::getReviewStatus, salesLedgerDto.getReviewStatusList())
                         .or().isNull(SalesLedger::getReviewStatus));
@@ -3848,7 +4339,7 @@
                 ledgerDto.setDeliveryStatusText(getDeliveryStatusText(ledger.getDeliveryStatus()));
                 ledgerDto.setStockStatusText(getStockStatusText(ledger.getStockStatus()));
                 ledgerDto.setReviewStatusText(getReviewStatusText(ledger.getReviewStatus()));
-                ledgerDto.setOrderStatusText(getOrderStatusText(ledger.getOrderStatus()));
+
                 ledgerExportList.add(ledgerDto);
 
                 // 鏌ヨ璇ュ彴璐︾殑浜у搧鍒楄〃
@@ -4036,7 +4527,7 @@
                 sheetMap.put("宸ヨ壓璺嚎", sheetData);
             }
 
-            com.ruoyi.common.utils.excel.ExcelUtils.exportManySheet(response, "閿�鍞彴璐﹀伐鑹鸿矾绾垮鍑�", sheetMap);
+            ExcelUtils.exportManySheet(response, "閿�鍞彴璐﹀伐鑹鸿矾绾垮鍑�", sheetMap);
         } catch (Exception e) {
             log.error("瀵煎嚭鍞悗鍙拌处宸ヨ壓璺嚎澶辫触", e);
             throw new ServiceException("瀵煎嚭鍞悗鍙拌处宸ヨ壓璺嚎澶辫触锛�" + e.getMessage());
@@ -4082,7 +4573,7 @@
 
     private List<Object> buildProcessRouteRow(SalesLedger salesLedger, SalesLedgerProduct product, SalesLedgerProcessRouteRecord route) {
         List<Object> row = new ArrayList<>();
-        row.add(salesLedger.getEntryDate() == null ? "" : DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, salesLedger.getEntryDate()));
+        row.add(route.getCompletedTime() == null ? "" : route.getCompletedTime().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd")));
         row.add(salesLedger.getSalesContractNo());
         row.add(salesLedger.getCustomerName());
         row.add(product == null ? "" : product.getSpecificationModel());
@@ -4256,15 +4747,5 @@
         }
     }
 
-    private String getOrderStatusText(Integer status) {
-        if (status == null || status == 0) return "杩涜涓�";
-        switch (status) {
-            case 0:
-                return "杩涜涓�";
-            case 1:
-                return "宸插畬鎴�";
-            default:
-                return "杩涜涓�";
-        }
-    }
 }
+

--
Gitblit v1.9.3