From 000205578dc02b9d9ac0e2e5dee740142f4cff80 Mon Sep 17 00:00:00 2001
From: gongchunyi <deslre0381@gmail.com>
Date: 星期二, 21 四月 2026 10:36:30 +0800
Subject: [PATCH] fix: 销售发货单打印有多个产品时只展示一个产品名称

---
 src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java |  514 +++++++++++++++++++++++++++++++++++++++++++++++++++-----
 1 files changed, 465 insertions(+), 49 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 c270773..9b4d1a1 100644
--- a/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
+++ b/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -19,6 +19,9 @@
 import com.ruoyi.common.enums.FileNameType;
 import com.ruoyi.common.enums.SaleEnum;
 import com.ruoyi.common.enums.StockInQualifiedRecordTypeEnum;
+import com.ruoyi.common.enums.StockInUnQualifiedRecordTypeEnum;
+import com.ruoyi.common.enums.StockOutQualifiedRecordTypeEnum;
+import com.ruoyi.common.enums.StockOutUnQualifiedRecordTypeEnum;
 import com.ruoyi.common.exception.ServiceException;
 import com.ruoyi.common.exception.base.BaseException;
 import com.ruoyi.common.utils.DateUtils;
@@ -37,6 +40,7 @@
 import com.ruoyi.project.system.domain.SysUser;
 import com.ruoyi.project.system.mapper.SysDeptMapper;
 import com.ruoyi.project.system.mapper.SysUserMapper;
+import com.ruoyi.procurementrecord.utils.StockUtils;
 import com.ruoyi.purchase.dto.SimpleReturnOrderGroupDto;
 import com.ruoyi.purchase.mapper.PurchaseReturnOrderProductsMapper;
 import com.ruoyi.quality.mapper.QualityInspectMapper;
@@ -139,6 +143,7 @@
     private final StockOutRecordMapper stockOutRecordMapper;
     private final StockInRecordService stockInRecordService;
     private final StockOutRecordService stockOutRecordService;
+    private final StockUtils stockUtils;
 
     @Autowired
     private SysDeptMapper sysDeptMapper;
@@ -272,6 +277,7 @@
                     product.setActualTotalArea(pieceArea.multiply(quantity).setScale(2, RoundingMode.HALF_UP));
                 }
             }
+            product.fillRemainingQuantity();
         }
 
         // 3.鏌ヨ涓婁紶鏂囦欢
@@ -620,6 +626,7 @@
                 salesLedgerProduct.setNoInvoiceNum(quantity);
                 salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxExclusiveTotalPrice());
                 salesLedgerProduct.setPendingInvoiceTotal(taxInclusiveTotalPrice);
+                salesLedgerProduct.fillRemainingQuantity();
                 salesLedgerProductMapper.insert(salesLedgerProduct);
                 if (!processList.isEmpty()) {
                     salesLedgerProductProcessBindService.updateProductProcessBind(processList, salesLedgerProduct.getId());
@@ -999,7 +1006,16 @@
         if (!updateList.isEmpty()) {
             for (SalesLedgerProduct product : updateList) {
                 product.setType(type.getCode());
-                product.setProductStockStatus(0);
+                SalesLedgerProduct db = salesLedgerProductMapper.selectById(product.getId());
+                if (db != null) {
+                    BigDecimal stockedQty = product.getStockedQuantity() != null ? product.getStockedQuantity() : db.getStockedQuantity();
+                    BigDecimal orderQty = product.getQuantity() != null ? product.getQuantity() : db.getQuantity();
+                    product.setStockedQuantity(stockedQty);
+                    product.setProductStockStatus(calculateProductStockStatus(stockedQty, orderQty));
+                } else {
+                    product.setProductStockStatus(0);
+                }
+                product.fillRemainingQuantity();
                 salesLedgerProductMapper.updateById(product);
                 //  娓呯┖閿�鍞骇鍝佺粦瀹氱殑鍔犲伐
                 salesLedgerProductProcessBindService.updateProductProcessBind(product.getSalesProductProcessList(), product.getId());
@@ -1012,7 +1028,10 @@
                 salesLedgerProduct.setNoInvoiceNum(salesLedgerProduct.getQuantity());
                 salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxInclusiveTotalPrice());
                 salesLedgerProduct.setPendingInvoiceTotal(salesLedgerProduct.getTaxInclusiveTotalPrice());
-                salesLedgerProduct.setProductStockStatus(0);
+                BigDecimal stockedQty = salesLedgerProduct.getStockedQuantity();
+                BigDecimal orderQty = salesLedgerProduct.getQuantity();
+                salesLedgerProduct.setProductStockStatus(calculateProductStockStatus(stockedQty, orderQty));
+                salesLedgerProduct.fillRemainingQuantity();
                 salesLedgerProductMapper.insert(salesLedgerProduct);
                 //  缁戝畾浜у搧棰濆鍔犲伐
                 //  娓呯┖閿�鍞骇鍝佺粦瀹氱殑鍔犲伐
@@ -1021,6 +1040,41 @@
 //                salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
             }
         }
+        refreshSalesLedgerStockStatus(salesLedgerId);
+    }
+
+    private int calculateProductStockStatus(BigDecimal stockedQty, BigDecimal orderQty) {
+        BigDecimal stocked = stockedQty == null ? BigDecimal.ZERO : stockedQty;
+        BigDecimal order = orderQty == null ? BigDecimal.ZERO : orderQty;
+        if (stocked.compareTo(BigDecimal.ZERO) <= 0) {
+            return 0;
+        }
+        if (order.compareTo(BigDecimal.ZERO) > 0 && stocked.compareTo(order) < 0) {
+            return 1;
+        }
+        return 2;
+    }
+
+    private void refreshSalesLedgerStockStatus(Long salesLedgerId) {
+        if (salesLedgerId == null) return;
+        SalesLedger ledger = baseMapper.selectById(salesLedgerId);
+        if (ledger == null) return;
+        List<SalesLedgerProduct> allProducts = salesLedgerProductMapper.selectList(
+                Wrappers.<SalesLedgerProduct>lambdaQuery()
+                        .eq(SalesLedgerProduct::getSalesLedgerId, salesLedgerId)
+                        .eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
+        if (CollectionUtils.isEmpty(allProducts)) {
+            ledger.setStockStatus(0);
+            baseMapper.updateById(ledger);
+            return;
+        }
+        boolean anyInbound = allProducts.stream().anyMatch(p -> {
+            BigDecimal sq = p.getStockedQuantity();
+            return sq != null && sq.compareTo(BigDecimal.ZERO) > 0;
+        });
+        boolean allFull = allProducts.stream().allMatch(p -> Objects.equals(p.getProductStockStatus(), 2));
+        ledger.setStockStatus(allFull ? 2 : (anyInbound ? 1 : 0));
+        baseMapper.updateById(ledger);
     }
 
     private SalesLedger convertToEntity(SalesLedgerDto dto) {
@@ -1183,13 +1237,19 @@
         List<SalesProcessCardDto.ProcessNodeDto> nodeDtos = new ArrayList<>();
 
         if (CollectionUtils.isEmpty(salesLedgerProcessRoutes)) {
-            // 鏃犺嚜瀹氫箟璺嚎锛屽彇榛樿璺嚎
-            ProcessRoute defaultRoute = processRouteMapper.selectOne(
+            // 鏃犺嚜瀹氫箟璺嚎锛氬厛鏌ヨ榛樿宸ヨ壓璺嚎锛涜嫢鏃犻粯璁わ紝鑾峰彇鍒涘缓鏃堕棿鏈�杩戠殑涓�鏉�
+            ProcessRoute fallbackRoute = processRouteMapper.selectOne(
                     new LambdaQueryWrapper<ProcessRoute>().eq(ProcessRoute::getIsDefault, 1).last("LIMIT 1"));
-            if (defaultRoute != null) {
+            if (fallbackRoute == null) {
+                fallbackRoute = processRouteMapper.selectOne(
+                        new LambdaQueryWrapper<ProcessRoute>()
+                                .orderByDesc(ProcessRoute::getCreateTime)
+                                .last("LIMIT 1"));
+            }
+            if (fallbackRoute != null) {
                 List<ProcessRouteItem> routeItems = processRouteItemMapper.selectList(
                         new LambdaQueryWrapper<ProcessRouteItem>()
-                                .eq(ProcessRouteItem::getRouteId, defaultRoute.getId())
+                                .eq(ProcessRouteItem::getRouteId, fallbackRoute.getId())
                                 .orderByAsc(ProcessRouteItem::getDragSort));
                 for (ProcessRouteItem i : routeItems) {
                     SalesProcessCardDto.ProcessNodeDto node = new SalesProcessCardDto.ProcessNodeDto();
@@ -1438,64 +1498,76 @@
 
         //  鏌ヨ鎵�鏈変骇鍝�
         List<SalesLedgerProduct> allProducts = salesLedgerProductMapper.selectList(
-                new LambdaQueryWrapper<SalesLedgerProduct>().in(SalesLedgerProduct::getSalesLedgerId, salesLedgerIds));
+                new LambdaQueryWrapper<SalesLedgerProduct>()
+                        .in(SalesLedgerProduct::getSalesLedgerId, salesLedgerIds)
+                        .eq(SalesLedgerProduct::getType, 1));
 
         if (CollectionUtils.isNotEmpty(allProducts)) {
             Map<Long, SalesLedger> ledgerMap = ledgers.stream()
                     .collect(Collectors.toMap(SalesLedger::getId, Function.identity()));
 
-            Map<Long, List<SalesLedgerProduct>> groupedData = new LinkedHashMap<>();
-            for (SalesLedgerProduct p : allProducts) {
-                groupedData.computeIfAbsent(p.getSalesLedgerId(), k -> new ArrayList<>()).add(p);
-            }
-
             List<SalesInvoicesDto.InvoiceOrderGroupDto> groups = new ArrayList<>();
             BigDecimal totalQty = BigDecimal.ZERO;
             BigDecimal totalArea = BigDecimal.ZERO;
 
-            for (Map.Entry<Long, List<SalesLedgerProduct>> ledgerEntry : groupedData.entrySet()) {
+            Map<Long, Map<String, List<SalesLedgerProduct>>> groupedData = new LinkedHashMap<>();
+            for (SalesLedgerProduct p : allProducts) {
+                Long ledgerId = p.getSalesLedgerId();
+                String productCategory = StringUtils.defaultString(p.getProductCategory(), "");
+                String specificationModel = StringUtils.defaultString(p.getSpecificationModel(), "");
+                String groupKey = productCategory + "||" + specificationModel;
+                groupedData.computeIfAbsent(ledgerId, k -> new LinkedHashMap<>())
+                        .computeIfAbsent(groupKey, k -> new ArrayList<>())
+                        .add(p);
+            }
+
+            for (Map.Entry<Long, Map<String, List<SalesLedgerProduct>>> ledgerEntry : groupedData.entrySet()) {
                 SalesLedger ledger = ledgerMap.get(ledgerEntry.getKey());
                 String orderNo = ledger != null ? ledger.getSalesContractNo() : "";
-                List<SalesLedgerProduct> products = ledgerEntry.getValue();
 
-                SalesInvoicesDto.InvoiceOrderGroupDto group = new SalesInvoicesDto.InvoiceOrderGroupDto();
-                group.setSalesContractNo(orderNo);
-                if (CollectionUtils.isNotEmpty(products)) {
-                    group.setProductName(products.get(0).getProductCategory());
-                }
+                for (Map.Entry<String, List<SalesLedgerProduct>> productEntry : ledgerEntry.getValue().entrySet()) {
+                    String key = productEntry.getKey();
+                    String[] parts = key.split("\\|\\|", -1);
+                    String productName = parts.length > 0 ? parts[0] : "";
+                    List<SalesLedgerProduct> products = productEntry.getValue();
 
-                List<SalesInvoicesDto.InvoiceItemDto> itemDtos = new ArrayList<>();
-                BigDecimal groupQty = BigDecimal.ZERO;
-                BigDecimal groupArea = BigDecimal.ZERO;
+                    SalesInvoicesDto.InvoiceOrderGroupDto group = new SalesInvoicesDto.InvoiceOrderGroupDto();
+                    group.setSalesContractNo(orderNo);
+                    group.setProductName(productName);
+                    List<SalesInvoicesDto.InvoiceItemDto> itemDtos = new ArrayList<>();
+                    BigDecimal groupQty = BigDecimal.ZERO;
+                    BigDecimal groupArea = BigDecimal.ZERO;
 
-                for (SalesLedgerProduct p : products) {
-                    SalesInvoicesDto.InvoiceItemDto item = new SalesInvoicesDto.InvoiceItemDto();
-                    item.setFloorCode(p.getFloorCode());
-                    item.setWidthHeight((p.getWidth() != null ? p.getWidth().stripTrailingZeros().toPlainString() : "0") +
-                            " * " + (p.getHeight() != null ? p.getHeight().stripTrailingZeros().toPlainString() : "0"));
-                    item.setQuantity(p.getQuantity());
+                    for (SalesLedgerProduct p : products) {
+                        SalesInvoicesDto.InvoiceItemDto item = new SalesInvoicesDto.InvoiceItemDto();
+                        item.setFloorCode(p.getFloorCode());
+                        item.setWidthHeight((p.getWidth() != null ? p.getWidth().stripTrailingZeros().toPlainString() : "0") +
+                                " * " + (p.getHeight() != null ? p.getHeight().stripTrailingZeros().toPlainString() : "0"));
+                        item.setSpecificationModel(p.getSpecificationModel());
+                        item.setQuantity(p.getQuantity());
 
-                    // 闈㈢Н
-                    BigDecimal area = p.getSettleTotalArea() != null ? p.getSettleTotalArea() : p.getActualTotalArea();
-                    if (area == null && p.getWidth() != null && p.getHeight() != null && p.getQuantity() != null) {
-                        area = p.getWidth().multiply(p.getHeight()).multiply(p.getQuantity()).divide(new BigDecimal(1000000), 2, RoundingMode.HALF_UP);
+                        // 闈㈢Н
+                        BigDecimal area = p.getSettleTotalArea() != null ? p.getSettleTotalArea() : p.getActualTotalArea();
+                        if (area == null && p.getWidth() != null && p.getHeight() != null && p.getQuantity() != null) {
+                            area = p.getWidth().multiply(p.getHeight()).multiply(p.getQuantity()).divide(new BigDecimal(1000000), 2, RoundingMode.HALF_UP);
+                        }
+                        item.setArea(area);
+                        item.setRemark(p.getRemark());
+                        item.setProcessRequirement(p.getProcessRequirement());
+
+                        itemDtos.add(item);
+                        groupQty = groupQty.add(p.getQuantity() != null ? p.getQuantity() : BigDecimal.ZERO);
+                        groupArea = groupArea.add(area != null ? area : BigDecimal.ZERO);
                     }
-                    item.setArea(area);
-                    item.setRemark(p.getRemark());
-                    item.setProcessRequirement(p.getProcessRequirement());
 
-                    itemDtos.add(item);
-                    groupQty = groupQty.add(p.getQuantity() != null ? p.getQuantity() : BigDecimal.ZERO);
-                    groupArea = groupArea.add(area != null ? area : BigDecimal.ZERO);
+                    group.setItems(itemDtos);
+                    group.setGroupTotalQuantity(groupQty);
+                    group.setGroupTotalArea(groupArea.setScale(2, RoundingMode.HALF_UP));
+                    groups.add(group);
+
+                    totalQty = totalQty.add(groupQty);
+                    totalArea = totalArea.add(groupArea);
                 }
-
-                group.setItems(itemDtos);
-                group.setGroupTotalQuantity(groupQty);
-                group.setGroupTotalArea(groupArea.setScale(2, RoundingMode.HALF_UP));
-                groups.add(group);
-
-                totalQty = totalQty.add(groupQty);
-                totalArea = totalArea.add(groupArea);
             }
             dto.setGroups(groups);
             dto.setTotalQuantity(totalQty);
@@ -1675,23 +1747,367 @@
             throw new ServiceException("鍏ュ簱澶辫触,鏈煡璇㈠埌璇ラ攢鍞鍗曠殑閿�鍞骇鍝�");
         }
         for (SalesLedgerProduct product : salesLedgerProducts) {
+            if (!Objects.equals(product.getSalesLedgerId(), ledger.getId())) {
+                throw new ServiceException("鍏ュ簱澶辫触,瀛樺湪涓嶅睘浜庡綋鍓嶉攢鍞鍗曠殑浜у搧");
+            }
             if (product.getProductModelId() == null) {
+                continue;
+            }
+            BigDecimal orderQty = product.getQuantity() == null ? BigDecimal.ZERO : product.getQuantity();
+            BigDecimal oldStocked = product.getStockedQuantity() == null ? BigDecimal.ZERO : product.getStockedQuantity();
+            BigDecimal inboundQty = orderQty.subtract(oldStocked);
+            if (inboundQty.compareTo(BigDecimal.ZERO) < 0) {
+                inboundQty = BigDecimal.ZERO;
+            }
+            if (inboundQty.compareTo(BigDecimal.ZERO) <= 0) {
                 continue;
             }
             StockInventoryDto stockInventoryDto = new StockInventoryDto();
             stockInventoryDto.setRecordId(product.getId());
             stockInventoryDto.setRecordType(StockInQualifiedRecordTypeEnum.SALE_STOCK_IN.getCode());
-            stockInventoryDto.setQualitity(product.getQuantity());
+            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;
+            }
+            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 -> Objects.equals(item.getProductStockStatus(), 1));
-        boolean allStocked = CollectionUtils.isNotEmpty(ledgerAllProducts) && ledgerAllProducts.stream().allMatch(item -> Objects.equals(item.getProductStockStatus(), 1));
+        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));
         baseMapper.updateById(ledger);
     }
+
+    @Override
+    public List<Customer> shippedCustomers() {
+        List<SalesLedger> ledgers = list(Wrappers.<SalesLedger>lambdaQuery()
+                .eq(SalesLedger::getDeliveryStatus, 5)
+                .isNotNull(SalesLedger::getCustomerId)
+                .select(SalesLedger::getCustomerId));
+        if (CollectionUtils.isEmpty(ledgers)) {
+            return Collections.emptyList();
+        }
+        Set<Long> customerIds = ledgers.stream()
+                .map(SalesLedger::getCustomerId)
+                .collect(Collectors.toCollection(LinkedHashSet::new));
+        return customerMapper.selectList(Wrappers.<Customer>lambdaQuery()
+                .in(Customer::getId, customerIds)
+                .orderByAsc(Customer::getCustomerName));
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void scanInbound(SalesScanInboundDto dto) {
+        if (dto == null || dto.getSalesLedgerId() == null) {
+            throw new ServiceException("閿�鍞鍗曞叆搴撳け璐�,鍏ュ簱鏁版嵁涓嶈兘涓虹┖");
+        }
+
+        SalesLedger salesLedger = baseMapper.selectById(dto.getSalesLedgerId());
+        if (salesLedger == null) {
+            throw new ServiceException("鍏ュ簱澶辫触,閿�鍞鍗曚笉瀛樺湪");
+        }
+        if (salesLedger.getStockStatus() == null) {
+            throw new ServiceException("鍏ュ簱澶辫触,閿�鍞鍗曠姸鎬佸紓甯�");
+        }
+        if (salesLedger.getStockStatus() == 2) {
+            throw new ServiceException("鍏ュ簱澶辫触,璇ラ攢鍞鍗曞凡鍏ㄩ儴鍏ュ簱");
+        }
+        if (salesLedger.getDeliveryStatus() == 5) {
+            throw new ServiceException("鍏ュ簱澶辫触,璇ラ攢鍞鍗曞凡鍙戣揣");
+        }
+        if (CollectionUtils.isEmpty(dto.getSalesLedgerProductList())) {
+            throw new ServiceException("閿�鍞鍗曞叆搴撳け璐�,鍏ュ簱浜у搧涓嶈兘涓虹┖");
+        }
+        //  鏈鍏ュ簱鏁伴噺鍙互澶т簬璁㈠崟鏁伴噺,浣嗕笉鑳戒负璐�
+        Map<Long, BigDecimal> inboundQtyByLineId = new LinkedHashMap<>();
+        for (SalesLedgerProduct inbound : dto.getSalesLedgerProductList()) {
+            if (inbound == null || inbound.getId() == null) {
+                throw new ServiceException("鍏ュ簱澶辫触,閿�鍞骇鍝佷俊鎭笉瀹屾暣");
+            }
+            BigDecimal inboundQty = inbound.getStockedQuantity();
+            if (inboundQty == null) {
+                throw new ServiceException("鍏ュ簱澶辫触,鍏ュ簱鏁伴噺涓嶈兘涓虹┖");
+            }
+            if (inboundQty.compareTo(BigDecimal.ZERO) < 0) {
+                throw new ServiceException("鍏ュ簱澶辫触,鍏ュ簱鏁伴噺涓嶈兘涓鸿礋鏁�");
+            }
+            inboundQtyByLineId.merge(inbound.getId(), inboundQty, BigDecimal::add);
+        }
+        Long ledgerId = salesLedger.getId();
+        for (Map.Entry<Long, BigDecimal> entry : inboundQtyByLineId.entrySet()) {
+            Long salesLedgerProductId = entry.getKey();
+            BigDecimal inboundThisLine = entry.getValue();
+            if (inboundThisLine.compareTo(BigDecimal.ZERO) == 0) {
+                continue;
+            }
+            SalesLedgerProduct dbProduct = salesLedgerProductMapper.selectById(salesLedgerProductId);
+            if (dbProduct == null) {
+                throw new ServiceException("鍏ュ簱澶辫触,閿�鍞骇鍝佷笉瀛樺湪");
+            }
+            if (!Objects.equals(dbProduct.getSalesLedgerId(), ledgerId)) {
+                throw new ServiceException("鍏ュ簱澶辫触,閿�鍞骇鍝佷笌璁㈠崟涓嶅尮閰�");
+            }
+            if (!Objects.equals(dbProduct.getType(), SaleEnum.SALE.getCode())) {
+                throw new ServiceException("鍏ュ簱澶辫触,浠呮敮鎸侀攢鍞鍗曚骇鍝佽");
+            }
+            if (dbProduct.getProductModelId() == null) {
+                throw new ServiceException("鍏ュ簱澶辫触,浜у搧瑙勬牸鏈淮鎶�,鏃犳硶鍏ュ簱");
+            }
+            BigDecimal oldStocked = dbProduct.getStockedQuantity() == null ? BigDecimal.ZERO : dbProduct.getStockedQuantity();
+            BigDecimal newStocked = oldStocked.add(inboundThisLine);
+
+            StockInventoryDto stockInventoryDto = new StockInventoryDto();
+            stockInventoryDto.setRecordId(dbProduct.getId());
+            stockInventoryDto.setRecordType(StockInQualifiedRecordTypeEnum.SALE_SCAN_STOCK_IN.getCode());
+            stockInventoryDto.setQualitity(inboundThisLine);
+            stockInventoryDto.setProductModelId(dbProduct.getProductModelId());
+            stockInventoryDto.setSalesLedgerId(ledgerId);
+            stockInventoryDto.setSalesLedgerProductId(dbProduct.getId());
+            stockInventoryService.addstockInventory(stockInventoryDto);
+
+            BigDecimal orderQty = dbProduct.getQuantity() == null ? BigDecimal.ZERO : dbProduct.getQuantity();
+            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;
+            }
+            dbProduct.setStockedQuantity(newStocked);
+            dbProduct.setProductStockStatus(lineStockStatus);
+            dbProduct.fillRemainingQuantity();
+            salesLedgerProductMapper.updateById(dbProduct);
+        }
+        List<SalesLedgerProduct> ledgerAllProducts = salesLedgerProductMapper.selectList(
+                Wrappers.<SalesLedgerProduct>lambdaQuery().eq(SalesLedgerProduct::getSalesLedgerId, ledgerId));
+        boolean anyInbound = ledgerAllProducts.stream().anyMatch(p -> {
+            BigDecimal sq = p.getStockedQuantity();
+            return sq != null && sq.compareTo(BigDecimal.ZERO) > 0;
+        });
+        boolean allLinesFull = ledgerAllProducts.stream().allMatch(p -> Objects.equals(p.getProductStockStatus(), 2));
+        salesLedger.setStockStatus(allLinesFull ? 2 : (anyInbound ? 1 : 0));
+        baseMapper.updateById(salesLedger);
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void scanInboundUnqualified(SalesScanInboundDto dto) {
+        if (dto == null || dto.getSalesLedgerId() == null) {
+            throw new ServiceException("閿�鍞鍗曚笉鍚堟牸鍏ュ簱澶辫触,鍏ュ簱鏁版嵁涓嶈兘涓虹┖");
+        }
+        SalesLedger salesLedger = baseMapper.selectById(dto.getSalesLedgerId());
+        if (salesLedger == null) {
+            throw new ServiceException("涓嶅悎鏍煎叆搴撳け璐�,閿�鍞鍗曚笉瀛樺湪");
+        }
+        if (salesLedger.getDeliveryStatus() != null && salesLedger.getDeliveryStatus() == 5) {
+            throw new ServiceException("涓嶅悎鏍煎叆搴撳け璐�,璇ラ攢鍞鍗曞凡鍙戣揣");
+        }
+        if (CollectionUtils.isEmpty(dto.getSalesLedgerProductList())) {
+            throw new ServiceException("閿�鍞鍗曚笉鍚堟牸鍏ュ簱澶辫触,鍏ュ簱浜у搧涓嶈兘涓虹┖");
+        }
+        Map<Long, BigDecimal> inboundQtyByLineId = new LinkedHashMap<>();
+        for (SalesLedgerProduct inbound : dto.getSalesLedgerProductList()) {
+            if (inbound == null || inbound.getId() == null) {
+                throw new ServiceException("涓嶅悎鏍煎叆搴撳け璐�,閿�鍞骇鍝佷俊鎭笉瀹屾暣");
+            }
+            BigDecimal inboundQty = inbound.getStockedQuantity();
+            if (inboundQty == null) {
+                throw new ServiceException("涓嶅悎鏍煎叆搴撳け璐�,鍏ュ簱鏁伴噺涓嶈兘涓虹┖");
+            }
+            if (inboundQty.compareTo(BigDecimal.ZERO) < 0) {
+                throw new ServiceException("涓嶅悎鏍煎叆搴撳け璐�,鍏ュ簱鏁伴噺涓嶈兘涓鸿礋鏁�");
+            }
+            inboundQtyByLineId.merge(inbound.getId(), inboundQty, BigDecimal::add);
+        }
+        Long ledgerId = salesLedger.getId();
+        for (Map.Entry<Long, BigDecimal> entry : inboundQtyByLineId.entrySet()) {
+            Long salesLedgerProductId = entry.getKey();
+            BigDecimal inboundThisLine = entry.getValue();
+            if (inboundThisLine.compareTo(BigDecimal.ZERO) == 0) {
+                continue;
+            }
+            SalesLedgerProduct dbProduct = salesLedgerProductMapper.selectById(salesLedgerProductId);
+            if (dbProduct == null) {
+                throw new ServiceException("涓嶅悎鏍煎叆搴撳け璐�,閿�鍞骇鍝佷笉瀛樺湪");
+            }
+            if (!Objects.equals(dbProduct.getSalesLedgerId(), ledgerId)) {
+                throw new ServiceException("涓嶅悎鏍煎叆搴撳け璐�,閿�鍞骇鍝佷笌璁㈠崟涓嶅尮閰�");
+            }
+            if (!Objects.equals(dbProduct.getType(), SaleEnum.SALE.getCode())) {
+                throw new ServiceException("涓嶅悎鏍煎叆搴撳け璐�,浠呮敮鎸侀攢鍞鍗曚骇鍝佽");
+            }
+            if (dbProduct.getProductModelId() == null) {
+                throw new ServiceException("涓嶅悎鏍煎叆搴撳け璐�,浜у搧瑙勬牸鏈淮鎶�,鏃犳硶鍏ュ簱");
+            }
+            stockUtils.addUnStock(ledgerId, dbProduct.getId(), dbProduct.getProductModelId(), inboundThisLine,
+                    StockInUnQualifiedRecordTypeEnum.SALES_SCAN_UNSTOCK_IN.getCode(), dbProduct.getId());
+
+            BigDecimal oldUnStocked = dbProduct.getUnqualifiedStockedQuantity() == null ? BigDecimal.ZERO : dbProduct.getUnqualifiedStockedQuantity();
+            dbProduct.setUnqualifiedStockedQuantity(oldUnStocked.add(inboundThisLine));
+            dbProduct.fillRemainingQuantity();
+            salesLedgerProductMapper.updateById(dbProduct);
+        }
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void scanOutbound(SalesScanInboundDto dto) {
+        if (dto == null || dto.getSalesLedgerId() == null) {
+            throw new ServiceException("閿�鍞鍗曞嚭搴撳け璐�,鍑哄簱鏁版嵁涓嶈兘涓虹┖");
+        }
+        SalesLedger salesLedger = baseMapper.selectById(dto.getSalesLedgerId());
+        if (salesLedger == null) {
+            throw new ServiceException("鍑哄簱澶辫触,閿�鍞鍗曚笉瀛樺湪");
+        }
+        if (salesLedger.getDeliveryStatus() != null && salesLedger.getDeliveryStatus() == 5) {
+            throw new ServiceException("鍑哄簱澶辫触,璇ラ攢鍞鍗曞凡鍙戣揣");
+        }
+        if (CollectionUtils.isEmpty(dto.getSalesLedgerProductList())) {
+            throw new ServiceException("閿�鍞鍗曞嚭搴撳け璐�,鍑哄簱浜у搧涓嶈兘涓虹┖");
+        }
+        int saleType = SaleEnum.SALE.getCode();
+        Map<Long, BigDecimal> outboundQtyByLineId = new LinkedHashMap<>();
+        for (SalesLedgerProduct line : dto.getSalesLedgerProductList()) {
+            if (line == null || line.getId() == null) {
+                throw new ServiceException("鍑哄簱澶辫触,閿�鍞骇鍝佷俊鎭笉瀹屾暣");
+            }
+            BigDecimal outboundQty = line.getStockedQuantity();
+            if (outboundQty == null) {
+                throw new ServiceException("鍑哄簱澶辫触,鍑哄簱鏁伴噺涓嶈兘涓虹┖");
+            }
+            if (outboundQty.compareTo(BigDecimal.ZERO) < 0) {
+                throw new ServiceException("鍑哄簱澶辫触,鍑哄簱鏁伴噺涓嶈兘涓鸿礋鏁�");
+            }
+            outboundQtyByLineId.merge(line.getId(), outboundQty, BigDecimal::add);
+        }
+        Long ledgerId = salesLedger.getId();
+        for (Map.Entry<Long, BigDecimal> entry : outboundQtyByLineId.entrySet()) {
+            Long salesLedgerProductId = entry.getKey();
+            BigDecimal outboundThisLine = entry.getValue();
+            if (outboundThisLine.compareTo(BigDecimal.ZERO) == 0) {
+                continue;
+            }
+            SalesLedgerProduct dbProduct = salesLedgerProductMapper.selectById(salesLedgerProductId);
+            if (dbProduct == null) {
+                throw new ServiceException("鍑哄簱澶辫触,閿�鍞骇鍝佷笉瀛樺湪");
+            }
+            if (!Objects.equals(dbProduct.getSalesLedgerId(), ledgerId) || !Objects.equals(dbProduct.getType(), saleType)) {
+                throw new ServiceException("鍑哄簱澶辫触,閿�鍞骇鍝佷笌璁㈠崟涓嶅尮閰�");
+            }
+            if (dbProduct.getProductModelId() == null) {
+                throw new ServiceException("鍑哄簱澶辫触,浜у搧瑙勬牸鏈淮鎶�,鏃犳硶鍑哄簱");
+            }
+            stockUtils.assertQualifiedAvailable(dbProduct.getProductModelId(), outboundThisLine);
+
+            StockInventoryDto stockInventoryDto = new StockInventoryDto();
+            stockInventoryDto.setRecordId(dbProduct.getId());
+            stockInventoryDto.setRecordType(StockOutQualifiedRecordTypeEnum.SALE_SCAN_STOCK_OUT.getCode());
+            stockInventoryDto.setQualitity(outboundThisLine);
+            stockInventoryDto.setProductModelId(dbProduct.getProductModelId());
+            stockInventoryDto.setSalesLedgerId(ledgerId);
+            stockInventoryDto.setSalesLedgerProductId(dbProduct.getId());
+            stockInventoryService.subtractStockInventory(stockInventoryDto);
+
+            BigDecimal oldShipped = dbProduct.getShippedQuantity() == null ? BigDecimal.ZERO : dbProduct.getShippedQuantity();
+            dbProduct.setShippedQuantity(oldShipped.add(outboundThisLine));
+            dbProduct.fillRemainingQuantity();
+            salesLedgerProductMapper.updateById(dbProduct);
+        }
+        List<SalesLedgerProduct> ledgerAllProducts = salesLedgerProductMapper.selectList(
+                Wrappers.<SalesLedgerProduct>lambdaQuery().eq(SalesLedgerProduct::getSalesLedgerId, ledgerId));
+        boolean anyInbound = ledgerAllProducts.stream().anyMatch(p -> {
+            BigDecimal sq = p.getStockedQuantity();
+            return sq != null && sq.compareTo(BigDecimal.ZERO) > 0;
+        });
+        boolean allLinesFull = ledgerAllProducts.stream().allMatch(p -> Objects.equals(p.getProductStockStatus(), 2));
+        salesLedger.setStockStatus(allLinesFull ? 2 : (anyInbound ? 1 : 0));
+        baseMapper.updateById(salesLedger);
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void scanOutboundUnqualified(SalesScanInboundDto dto) {
+        if (dto == null || dto.getSalesLedgerId() == null) {
+            throw new ServiceException("閿�鍞鍗曚笉鍚堟牸鍑哄簱澶辫触,鍑哄簱鏁版嵁涓嶈兘涓虹┖");
+        }
+        SalesLedger salesLedger = baseMapper.selectById(dto.getSalesLedgerId());
+        if (salesLedger == null) {
+            throw new ServiceException("涓嶅悎鏍煎嚭搴撳け璐�,閿�鍞鍗曚笉瀛樺湪");
+        }
+        if (salesLedger.getDeliveryStatus() != null && salesLedger.getDeliveryStatus() == 5) {
+            throw new ServiceException("涓嶅悎鏍煎嚭搴撳け璐�,璇ラ攢鍞鍗曞凡鍙戣揣");
+        }
+        if (CollectionUtils.isEmpty(dto.getSalesLedgerProductList())) {
+            throw new ServiceException("閿�鍞鍗曚笉鍚堟牸鍑哄簱澶辫触,鍑哄簱浜у搧涓嶈兘涓虹┖");
+        }
+        int saleType = SaleEnum.SALE.getCode();
+        Map<Long, BigDecimal> outboundQtyByLineId = new LinkedHashMap<>();
+        for (SalesLedgerProduct line : dto.getSalesLedgerProductList()) {
+            if (line == null || line.getId() == null) {
+                throw new ServiceException("涓嶅悎鏍煎嚭搴撳け璐�,閿�鍞骇鍝佷俊鎭笉瀹屾暣");
+            }
+            BigDecimal outboundQty = line.getStockedQuantity();
+            if (outboundQty == null) {
+                throw new ServiceException("涓嶅悎鏍煎嚭搴撳け璐�,鍑哄簱鏁伴噺涓嶈兘涓虹┖");
+            }
+            if (outboundQty.compareTo(BigDecimal.ZERO) < 0) {
+                throw new ServiceException("涓嶅悎鏍煎嚭搴撳け璐�,鍑哄簱鏁伴噺涓嶈兘涓鸿礋鏁�");
+            }
+            outboundQtyByLineId.merge(line.getId(), outboundQty, BigDecimal::add);
+        }
+        Long ledgerId = salesLedger.getId();
+        for (Map.Entry<Long, BigDecimal> entry : outboundQtyByLineId.entrySet()) {
+            Long salesLedgerProductId = entry.getKey();
+            BigDecimal outboundThisLine = entry.getValue();
+            if (outboundThisLine.compareTo(BigDecimal.ZERO) == 0) {
+                continue;
+            }
+            SalesLedgerProduct dbProduct = salesLedgerProductMapper.selectById(salesLedgerProductId);
+            if (dbProduct == null) {
+                throw new ServiceException("涓嶅悎鏍煎嚭搴撳け璐�,閿�鍞骇鍝佷笉瀛樺湪");
+            }
+            if (!Objects.equals(dbProduct.getSalesLedgerId(), ledgerId) || !Objects.equals(dbProduct.getType(), saleType)) {
+                throw new ServiceException("涓嶅悎鏍煎嚭搴撳け璐�,閿�鍞骇鍝佷笌璁㈠崟涓嶅尮閰�");
+            }
+            if (dbProduct.getProductModelId() == null) {
+                throw new ServiceException("涓嶅悎鏍煎嚭搴撳け璐�,浜у搧瑙勬牸鏈淮鎶�,鏃犳硶鍑哄簱");
+            }
+            BigDecimal unStocked = dbProduct.getUnqualifiedStockedQuantity() == null ? BigDecimal.ZERO : dbProduct.getUnqualifiedStockedQuantity();
+            BigDecimal unShipped = dbProduct.getUnqualifiedShippedQuantity() == null ? BigDecimal.ZERO : dbProduct.getUnqualifiedShippedQuantity();
+            BigDecimal canUnShip = unStocked.subtract(unShipped);
+            if (outboundThisLine.compareTo(canUnShip) > 0) {
+                throw new ServiceException("涓嶅悎鏍煎嚭搴撳け璐�,鍑哄簱鏁伴噺涓嶈兘澶т簬涓嶅悎鏍煎叆搴撴暟閲�");
+            }
+            stockUtils.assertUnqualifiedAvailable(dbProduct.getProductModelId(), outboundThisLine);
+            stockUtils.subtractUnStock(ledgerId, dbProduct.getId(), dbProduct.getProductModelId(), outboundThisLine,
+                    StockOutUnQualifiedRecordTypeEnum.SALE_SCAN_UNSTOCK_OUT.getCode(), dbProduct.getId());
+
+            dbProduct.setUnqualifiedShippedQuantity(unShipped.add(outboundThisLine));
+            dbProduct.fillRemainingQuantity();
+            salesLedgerProductMapper.updateById(dbProduct);
+        }
+    }
 }

--
Gitblit v1.9.3