yuan
2026-06-26 fbda2f16d63dcad15de13ab0997ef51257e5815b
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,6 +77,7 @@
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;
@@ -191,6 +196,10 @@
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    @Lazy
    private AfterSalesServiceService afterSalesServiceService;
    private final ICustomerRegionsService customerRegionsService;
    @Autowired
    private TransactionTemplate transactionTemplate;
@@ -273,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());
@@ -651,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));
                                    }
@@ -822,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);
@@ -1167,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(); // 唯一标识锁持有者
@@ -1814,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()) {
@@ -1871,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);
    }
@@ -2474,13 +2502,23 @@
                if (CollectionUtils.isEmpty(rowList)) {
                    return;
                }
                if (StringUtils.hasText(rowList.get(0).getCustomerName()) && rowList.get(0).getCustomerName().startsWith("补片")) {
                    return;
                }
                rowList.sort(Comparator.comparing(r -> buildCategoryProductName(r) + "||" + buildSpecificationModel(r)));
                SalesLedger ledger = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>().eq(SalesLedger::getSalesContractNo, orderNo).last("LIMIT 1"));
                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 + "]不存在,无法补录已发货数据");
                    return;
                }
                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;
                        }
                    }
                }
                if (skipInboundAndShipping) {
                    return;
                }
                List<SalesLedgerProduct> dbProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()).eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
@@ -2621,7 +2659,6 @@
                ledger.setStockStatus(allInbound ? 2 : (anyInbound ? 1 : 0));
                ledger.setDeliveryStatus(allShipped ? 5 : 1);
//            ledger.setReviewStatus(1);
                ledger.setOrderStatus(1);
                Long entryUserId = StringUtils.hasText(ledger.getEntryPerson()) ? Long.parseLong(ledger.getEntryPerson()) : 1L;
                Long entryDeptId = 1L;
@@ -2804,7 +2841,10 @@
                    ledger.setContractAmount(BigDecimal.ZERO);
                    salesLedgerMapper.insert(ledger);
                    bindImportProcessRoute(ledger.getId(), rowList, routeNameMap, finalRouteItemMap);
                    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;
@@ -2867,7 +2907,17 @@
                        // 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(),
@@ -2886,7 +2936,7 @@
                                    product.getId()
                            );
                            StockInRecord inRecord = stockInRecordMapper.selectOne(new LambdaQueryWrapper<StockInRecord>()
                            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) {
@@ -2899,14 +2949,14 @@
                                }
                                inRecord.setInboundBatches(batch);
                                if (row.getReportDate() != null) {
                                    LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
                                    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 LambdaQueryWrapper<StockOutRecord>()
                            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) {
@@ -2975,7 +3025,6 @@
                        }
                        ledger.setStockStatus(allInbound ? 2 : (anyInbound ? 1 : 0));
                        ledger.setDeliveryStatus(allShipped ? 5 : 1);
                        ledger.setOrderStatus(1);
                        Long entryUserId = StringUtils.hasText(ledger.getEntryPerson()) ? Long.parseLong(ledger.getEntryPerson()) : 1L;
                        Long entryDeptId = 1L;
@@ -3042,6 +3091,31 @@
                        } 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);
@@ -3079,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("导入失败,订单工艺流程不能为空");
@@ -3111,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) {
@@ -3452,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());
@@ -3514,7 +3631,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());
@@ -3919,43 +4036,10 @@
            // 5. 取消审批流程
            cancelApproveProcesses(id, originalLedger.getSalesContractNo());
            // 6. 重新生成:创建新台账副本
            // 6. 重新生成:此处不直接在后端入库,而是返回原单据ID给前端
            // 前端拿到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;
@@ -4157,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) {
@@ -4246,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));
@@ -4281,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);
                // 查询该台账的产品列表
@@ -4469,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());
@@ -4515,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());
@@ -4689,15 +4747,5 @@
        }
    }
    private String getOrderStatusText(Integer status) {
        if (status == null || status == 0) return "进行中";
        switch (status) {
            case 0:
                return "进行中";
            case 1:
                return "已完成";
            default:
                return "进行中";
        }
    }
}