gongchunyi
12 小时以前 d8e43527be8f994f721a52e1881ff6209e2e30ae
src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -5,18 +5,16 @@
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.account.service.AccountIncomeService;
import com.ruoyi.approve.service.IApproveProcessService;
import com.ruoyi.approve.vo.ApproveProcessVO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.account.service.AccountIncomeService;
import com.ruoyi.approve.pojo.ApproveProcess;
import com.ruoyi.common.enums.ApproveTypeEnum;
import com.ruoyi.approve.service.IApproveProcessService;
import com.ruoyi.approve.vo.ApproveProcessVO;
import com.ruoyi.basic.mapper.CustomerMapper;
import com.ruoyi.basic.mapper.ProductMapper;
import com.ruoyi.basic.mapper.ProductModelMapper;
@@ -25,32 +23,22 @@
import com.ruoyi.basic.pojo.Product;
import com.ruoyi.basic.pojo.ProductModel;
import com.ruoyi.basic.service.ICustomerRegionsService;
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.enums.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.EnumUtil;
import com.ruoyi.common.utils.OrderUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.other.mapper.TempFileMapper;
import com.ruoyi.other.pojo.TempFile;
import com.ruoyi.procurementrecord.utils.StockUtils;
import com.ruoyi.production.mapper.*;
import com.ruoyi.production.pojo.ProcessRoute;
import com.ruoyi.production.pojo.ProcessRouteItem;
import com.ruoyi.production.service.ProductionProductMainService;
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;
@@ -65,11 +53,13 @@
import com.ruoyi.sales.mapper.*;
import com.ruoyi.sales.pojo.*;
import com.ruoyi.sales.service.ISalesLedgerProcessRouteService;
import com.ruoyi.sales.service.ISalesLedgerProcessRouteRecordService;
import com.ruoyi.sales.service.ISalesLedgerProductProcessBindService;
import com.ruoyi.sales.service.ISalesLedgerProductProcessService;
import com.ruoyi.sales.service.ISalesLedgerService;
import com.ruoyi.stock.dto.StockInventoryDto;
import com.ruoyi.stock.mapper.StockInRecordMapper;
import com.ruoyi.stock.mapper.StockInventoryMapper;
import com.ruoyi.stock.mapper.StockOutRecordMapper;
import com.ruoyi.stock.pojo.StockInRecord;
import com.ruoyi.stock.pojo.StockOutRecord;
@@ -85,25 +75,32 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.YearMonth;
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;
@@ -161,13 +158,17 @@
    private final ISalesLedgerProductProcessBindService salesLedgerProductProcessBindService;
    private final ISalesLedgerProcessRouteService salesLedgerProcessRouteService;
    private final ISalesLedgerProcessRouteRecordService salesLedgerProcessRouteRecordService;
    private final StockInventoryService stockInventoryService;
    private final StockInRecordMapper stockInRecordMapper;
    private final StockOutRecordMapper stockOutRecordMapper;
    private final StockInventoryMapper stockInventoryMapper;
    private final StockInRecordService stockInRecordService;
    private final StockOutRecordService stockOutRecordService;
    private final StockUtils stockUtils;
    private final ShipmentApprovalMapper shipmentApprovalMapper;
    @Autowired
    private IApproveProcessService approveProcessService;
@@ -191,6 +192,8 @@
    private SysUserMapper sysUserMapper;
    private final ICustomerRegionsService customerRegionsService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Override
    public List<SalesLedger> selectSalesLedgerList(SalesLedgerDto salesLedgerDto) {
@@ -341,7 +344,9 @@
    public List getTopFiveList() {
        // 查询原始数据
        LambdaQueryWrapper<SalesLedger> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(SalesLedger::getCustomerId, SalesLedger::getCustomerName, SalesLedger::getContractAmount).orderByDesc(SalesLedger::getContractAmount);
        queryWrapper.select(SalesLedger::getCustomerId, SalesLedger::getCustomerName, SalesLedger::getContractAmount)
                .orderByDesc(SalesLedger::getContractAmount)
                .ne(SalesLedger::getReviewStatus, 2); // 排除反审核数据
        List<SalesLedger> records = salesLedgerMapper.selectList(queryWrapper);
        // 按客户ID分组并聚合金额
@@ -400,6 +405,7 @@
    @Override
    public IPage<SalesLedger> selectSalesLedgerListPage(Page page, SalesLedgerDto salesLedgerDto) {
        // 添加 reviewStatus 的筛选条件
        IPage<SalesLedger> iPage = salesLedgerMapper.selectSalesLedgerListPage(page, salesLedgerDto);
        if (CollectionUtils.isEmpty(iPage.getRecords())) {
@@ -484,6 +490,14 @@
            salesLedger.setIsFh(isFh);
            salesLedger.setIsEdit(!isFh);
            // 根据 reviewStatus 控制反审相关字段的显示
            if (salesLedger.getReviewStatus() != null && salesLedger.getReviewStatus() != 2) {
                // 当 reviewStatus 不为 2 时,隐藏反审时间、反审人和反审人ID
                salesLedger.setCounterReviewTime(null);
                salesLedger.setCounterReviewPerson(null);
                salesLedger.setCounterReviewPersonId(null);
            }
        }
        if (salesLedgerDto.getStatus() != null && salesLedgerDto.getStatus()) {
@@ -749,21 +763,22 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saleProcessBind(SalesLedgerProcessRoute salesLedgerProcessRoute) {
        if (salesLedgerProcessRoute == null) {
    public void saleProcessBind(SalesLedgerProcessRouteDto salesLedgerProcessRouteDto) {
        if (salesLedgerProcessRouteDto == null) {
            throw new ServiceException("绑定失败,数据不能为空");
        }
        SalesLedger salesLedger = baseMapper.selectById(salesLedgerProcessRoute.getSalesLedgerId());
        SalesLedger salesLedger = baseMapper.selectById(salesLedgerProcessRouteDto.getSalesLedgerId());
        if (salesLedger == null) {
            throw new ServiceException("绑定失败,销售订单不存在");
        }
        ProcessRoute processRoute = processRouteMapper.selectById(salesLedgerProcessRoute.getProcessRouteId());
        ProcessRoute processRoute = processRouteMapper.selectById(salesLedgerProcessRouteDto.getProcessRouteId());
        if (processRoute == null) {
            throw new ServiceException("绑定失败,工艺路线不存在");
        }
        //  清除已绑定的数据
        salesLedgerProcessRouteService.remove(new LambdaQueryWrapper<SalesLedgerProcessRoute>().eq(SalesLedgerProcessRoute::getSalesLedgerId, salesLedger.getId()));
        salesLedgerProcessRouteRecordService.remove(new LambdaQueryWrapper<SalesLedgerProcessRouteRecord>().eq(SalesLedgerProcessRouteRecord::getSalesLedgerId, salesLedger.getId()));
        //  将数据迁移到sales_ledger_process_route
        List<ProcessRouteItem> routeItems = processRouteItemMapper.selectList(new LambdaQueryWrapper<ProcessRouteItem>().eq(ProcessRouteItem::getRouteId, processRoute.getId()));
@@ -778,6 +793,39 @@
            salesLedgerProcessRouteList.add(ledgerProcessRoute);
        }
        salesLedgerProcessRouteService.saveBatch(salesLedgerProcessRouteList);
        List<SalesLedgerProcessRoute> savedRoutes = salesLedgerProcessRouteService.list(new LambdaQueryWrapper<SalesLedgerProcessRoute>()
                .eq(SalesLedgerProcessRoute::getSalesLedgerId, salesLedger.getId())
                .eq(SalesLedgerProcessRoute::getProcessRouteId, processRoute.getId()));
        Map<Long, SalesLedgerProcessRoute> routeMap = savedRoutes.stream()
                .filter(item -> item.getProcessRouteItemId() != null)
                .collect(Collectors.toMap(SalesLedgerProcessRoute::getProcessRouteItemId, item -> item, (a, b) -> a));
        Map<Long, SalesLedgerProcessRouteRecord> inputRecordMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(salesLedgerProcessRouteDto.getRecordList())) {
            for (SalesLedgerProcessRouteRecord record : salesLedgerProcessRouteDto.getRecordList()) {
                if (record != null && record.getProcessRouteItemId() != null) {
                    inputRecordMap.put(record.getProcessRouteItemId(), record);
                }
            }
        }
        List<SalesLedgerProcessRouteRecord> routeRecordList = new ArrayList<>();
        for (ProcessRouteItem routeItem : routeItems) {
            SalesLedgerProcessRoute route = routeMap.get(routeItem.getId());
            if (route == null || route.getId() == null) {
                continue;
            }
            SalesLedgerProcessRouteRecord inputRecord = inputRecordMap.get(routeItem.getId());
            SalesLedgerProcessRouteRecord record = new SalesLedgerProcessRouteRecord();
            record.setSalesLedgerId(salesLedger.getId());
            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);
            routeRecordList.add(record);
        }
        salesLedgerProcessRouteRecordService.saveBatch(routeRecordList);
    }
    /**
@@ -808,6 +856,13 @@
        List<Long> idList = Arrays.stream(ids).filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(idList)) {
            return 0;
        }
        // 校验:已审核的订单不能删除
        List<SalesLedger> ledgers = salesLedgerMapper.selectBatchIds(idList);
        for (SalesLedger ledger : ledgers) {
            if (ledger.getReviewStatus() != null && ledger.getReviewStatus() == 1) {
                throw new ServiceException("已审核的订单不能删除:" + ledger.getSalesContractNo());
            }
        }
        // 删除销售管理数据
        LambdaQueryWrapper<SalesLedgerProduct> queryWrapper = new LambdaQueryWrapper<>();
@@ -902,6 +957,27 @@
            } else {
                if (salesLedger.getDeliveryStatus() == 5) {
                    throw new ServiceException("订单已发货,禁止编辑");
                }
                // 查询数据库中的原始记录用于校验
                SalesLedger existingLedger = salesLedgerMapper.selectById(salesLedger.getId());
                if (salesLedger.getReviewStatus() != null && salesLedger.getReviewStatus() == 1) {
                    // 审核操作:校验审核人不能是录入人(仅对未审核→已审核的转换)
                    if (existingLedger != null && existingLedger.getReviewStatus() != null && existingLedger.getReviewStatus() == 0) {
                        Long currentUserId = SecurityUtils.getUserId();
                        String entryPerson = existingLedger.getEntryPerson();
                        if (entryPerson != null && entryPerson.equals(String.valueOf(currentUserId))) {
                            throw new ServiceException("不能审核本人录入的订单");
                        }
                    }
                    salesLedger.setReviewStatus(salesLedgerDto.getReviewStatus());
                } else if (salesLedger.getReviewStatus() != null && salesLedger.getReviewStatus() == 2) {
                    handleCounterReview(salesLedger);
                } else {
                    // 未审核状态的编辑操作:校验已审核的订单不能编辑
                    if (existingLedger != null && existingLedger.getReviewStatus() != null && existingLedger.getReviewStatus() == 1) {
                        throw new ServiceException("已审核的订单不能编辑");
                    }
                    salesLedger.setReviewStatus(0);
                }
                salesLedgerMapper.updateById(salesLedger);
            }
@@ -1091,7 +1167,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(); // 唯一标识锁持有者
@@ -1142,6 +1218,11 @@
    public SalesLedgerProcessRouteDto salesProcess(Long salesLedgerId) {
        SalesLedgerProcessRouteDto dto = new SalesLedgerProcessRouteDto();
        List<SalesLedgerProcessRoute> list = baseMapper.selectSalesProcess(salesLedgerId);
        List<SalesLedgerProcessRouteRecord> recordList = salesLedgerProcessRouteRecordService.list(
                new LambdaQueryWrapper<SalesLedgerProcessRouteRecord>()
                        .eq(SalesLedgerProcessRouteRecord::getSalesLedgerId, salesLedgerId)
                        .orderByAsc(SalesLedgerProcessRouteRecord::getId)
        );
        if (CollectionUtils.isNotEmpty(list)) {
            Long processRouteId = list.get(0).getProcessRouteId();
            ProcessRoute processRoute = processRouteMapper.selectById(processRouteId);
@@ -1168,6 +1249,17 @@
            }
        }
        dto.setList(list);
        if (CollectionUtils.isNotEmpty(list) && CollectionUtils.isNotEmpty(recordList)) {
            Map<Long, Long> routeItemIdMap = list.stream()
                    .filter(item -> item.getId() != null && item.getProcessRouteItemId() != null)
                    .collect(Collectors.toMap(SalesLedgerProcessRoute::getId, SalesLedgerProcessRoute::getProcessRouteItemId, (a, b) -> a));
            recordList.forEach(record -> {
                if (record != null && record.getSalesLedgerProcessRouteId() != null) {
                    record.setProcessRouteItemId(routeItemIdMap.get(record.getSalesLedgerProcessRouteId()));
                }
            });
        }
        dto.setRecordList(recordList);
        return dto;
    }
@@ -1736,7 +1828,7 @@
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(ApproveTypeEnum.STOCK_IN.getCode());
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveDeptId(208L);
        approveProcessVO.setApproveReason("入库审批:" + ledger.getSalesContractNo());
        approveProcessVO.setApproveRemark("salesStock:" + ledger.getId() + ":" + productIds);
        approveProcessVO.setApproveUserIds(approveUserIds);
@@ -1903,7 +1995,7 @@
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(ApproveTypeEnum.STOCK_IN.getCode());
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveDeptId(208L);
        approveProcessVO.setApproveReason(reason);
        approveProcessVO.setApproveRemark(remark);
        approveProcessVO.setApproveUserIds(approveUserIds);
@@ -2058,7 +2150,7 @@
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(ApproveTypeEnum.STOCK_IN.getCode());
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveDeptId(208L);
        approveProcessVO.setApproveReason(reason);
        approveProcessVO.setApproveRemark(remark);
        approveProcessVO.setApproveUserIds(approveUserIds);
@@ -2351,7 +2443,6 @@
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shippingImport(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("导入失败,导入文件数据不能为空");
@@ -2369,105 +2460,246 @@
        }
        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) {
                throw new ServiceException("导入失败,订单编号[" + orderNo + "]不存在,无法补录已发货数据");
            }
            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<>();
//        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        List<String> errorMessages = Collections.synchronizedList(new ArrayList<>());
        groupedByOrderNo.forEach((orderNo, rowList) -> {
//            SecurityContext originalContext = SecurityContextHolder.getContext();
//            SecurityContext ctx = SecurityContextHolder.createEmptyContext();
//            ctx.setAuthentication(authentication);
//            SecurityContextHolder.setContext(ctx);
            try {
                if (!StringUtils.hasText(orderNo)) {
                    throw new ServiceException("导入失败,存在订单编号为空的数据");
                }
                if (CollectionUtils.isEmpty(rowList)) {
                    return;
                }
                if (StringUtils.hasText(rowList.get(0).getCustomerName()) && rowList.get(0).getCustomerName().startsWith("补片")) {
                    return;
                }
                rowList.sort(Comparator.comparing(r -> buildCategoryProductName(r) + "||" + buildSpecificationModel(r)));
                SalesLedger ledger = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>().eq(SalesLedger::getSalesContractNo, orderNo).last("LIMIT 1"));
                if (ledger == null) {
//                throw new ServiceException("导入失败,订单编号[" + orderNo + "]不存在,无法补录已发货数据");
                    return;
                }
                List<SalesLedgerProduct> dbProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()).eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
                if (CollectionUtils.isEmpty(dbProducts)) {
                    throw new ServiceException("导入失败,订单编号[" + orderNo + "]没有销售产品,无法补录发货");
                }
                dbProducts.sort(Comparator.comparing(SalesLedgerProduct::getProductModelId, Comparator.nullsLast(Comparator.naturalOrder())));
                Map<String, List<SalesLedgerProduct>> productByCategory = dbProducts.stream().collect(Collectors.groupingBy(p -> StringUtils.hasText(p.getProductCategory()) ? p.getProductCategory().trim() : ""));
                Set<String> importedRowKeys = new HashSet<>();
            for (SalesShippingImportDto row : rowList) {
                BigDecimal shipQty = defaultDecimal(row.getQuantity());
                if (shipQty.compareTo(BigDecimal.ZERO) <= 0) {
                    throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在数量小于等于0的数据");
                }
                String rowKey = buildShippingRowKey(ledger.getId(), row);
                if (!importedRowKeys.add(rowKey)) {
                    throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在重复发货明细行");
                }
                Map<SalesLedgerProduct, BigDecimal> allocations = allocateShippingProductLines(orderNo, row, productByCategory, dbProducts);
                for (Map.Entry<SalesLedgerProduct, BigDecimal> alloc : allocations.entrySet()) {
                    SalesLedgerProduct dbProduct = alloc.getKey();
                    BigDecimal allocQty = alloc.getValue();
                    if (dbProduct.getProductModelId() == null) {
                        throw new ServiceException("导入失败,订单编号[" + orderNo + "]产品规格未维护,无法补录出库");
                for (SalesShippingImportDto row : rowList) {
                    BigDecimal shipQty = defaultDecimal(row.getQuantity());
                    if (shipQty.compareTo(BigDecimal.ZERO) <= 0) {
                        throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在数量小于等于0的数据");
                    }
                    // 历史已发货补录:直接写入入库+出库记录
                    stockUtils.addStock(
                            ledger.getId(),
                            dbProduct.getId(),
                            dbProduct.getProductModelId(),
                            allocQty,
                            StockInQualifiedRecordTypeEnum.SALE_STOCK_IN.getCode(),
                            dbProduct.getId()
                    );
                    stockUtils.substractStock(
                            ledger.getId(),
                            dbProduct.getId(),
                            dbProduct.getProductModelId(),
                            allocQty,
                            StockOutQualifiedRecordTypeEnum.SALE_SHIP_STOCK_OUT.getCode(),
                            dbProduct.getId()
                    );
                    BigDecimal oldShipped = defaultDecimal(dbProduct.getShippedQuantity());
                    BigDecimal newShipped = oldShipped.add(allocQty);
                    dbProduct.setStockedQuantity(defaultDecimal(dbProduct.getQuantity()));
                    dbProduct.setShippedQuantity(newShipped);
                    dbProduct.setApproveStatus(3);
                    updateProductStockStatus(dbProduct);
                    dbProduct.fillRemainingQuantity();
                    updateProductShipStatus(dbProduct);
                    salesLedgerProductMapper.updateById(dbProduct);
                    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) {
                        throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在重复发货记录,请勿重复导入");
                    String rowKey = buildShippingRowKey(ledger.getId(), row);
                    if (!importedRowKeys.add(rowKey)) {
                        throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在重复发货明细行");
                    }
                    shippingInfoMapper.insert(shippingInfo);
                    createShippingQualityInspect(ledger, dbProduct, row, allocQty);
                }
            }
                    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()
                        );
            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);
            salesLedgerMapper.updateById(ledger);
        }
                        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()));
                        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
                    }
                }
                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);
                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
@@ -2488,10 +2720,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();
@@ -2500,7 +2732,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();
@@ -2509,120 +2741,317 @@
            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));
        List<String> extraProcessNames = Arrays.asList("打孔", "挖缺", "安全角", "磨边", "精磨边", "运费", "加急费");
        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.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);
            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);
                    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 + "]已存在");
                    }
                List<SalesLedgerProductProcess> bindProcessList = buildImportProcessBinds(row, processMap);
                if (CollectionUtils.isNotEmpty(bindProcessList)) {
                    salesLedgerProductProcessBindService.updateProductProcessBind(bindProcessList, product.getId());
                    SalesLedger ledger = new SalesLedger();
                    SysUser creatorUser = resolveImportUser(first.getCreator(), userByNickNameMap, userByUserNameMap, "制单员", orderNo);
                    ledger.setSalesContractNo(orderNo);
                    ledger.setCustomerContractNo(first.getContractNo());
                    ledger.setProjectName(first.getProjectName());
                    ledger.setSalesman(first.getSalesman());
                    Customer customer = getOrCreateImportCustomer(first.getCustomerName(), customerNameMap, hebiRegion.getId());
                    ledger.setCustomerName(customer.getCustomerName());
                    ledger.setRemarks(first.getRemark());
                    ledger.setEntryPerson(String.valueOf(creatorUser.getUserId()));
                    ledger.setEntryDate(first.getReportDate());
                    if (first.getReportDate() != null) {
                        ledger.setExecutionDate(DateUtils.toLocalDate(first.getReportDate()));
                    }
                    ledger.setDeliveryDate(first.getDeliveryDeadline() == null ? (first.getReportDate() == null ? LocalDate.now().plusDays(7) : DateUtils.toLocalDate(first.getReportDate()).plusDays(7)) : DateUtils.toLocalDate(first.getDeliveryDeadline()));
                    ledger.setDeliveryStatus(1);
                    ledger.setStockStatus(0);
                    ledger.setReviewStatus(0);
                    ledger.setCustomerId(customer.getId());
                    ledger.setCustomerContractNo(StringUtils.hasText(ledger.getCustomerContractNo()) ? ledger.getCustomerContractNo() : customer.getTaxpayerIdentificationNumber());
                    ledger.setContractAmount(BigDecimal.ZERO);
                    salesLedgerMapper.insert(ledger);
                    bindImportProcessRoute(ledger.getId(), rowList, routeNameMap, finalRouteItemMap);
                    int reviewCount = 0;
                    BigDecimal contractAmount = BigDecimal.ZERO;
                    for (SalesNotShippingImportDto row : rowList) {
                        SalesLedgerProduct product = new SalesLedgerProduct();
                        product.setSalesLedgerId(ledger.getId());
                        product.setType(SaleEnum.SALE.getCode());
                        String specificationModel = buildSpecificationModel(row);
                        Product importProduct = resolveOrCreateImportProduct(row, productNameMap, finalFinishedGoodsParent, orderNo);
                        ProductModel importProductModel = resolveOrCreateImportProductModel(importProduct, specificationModel, row.getGlassThickness(), productModelKeyMap);
                        product.setProductCategory(row.getProductSubCategory());
                        product.setSpecificationModel(specificationModel);
                        product.setProductId(importProduct.getId());
                        product.setProductModelId(importProductModel.getId());
                        product.setFloorCode(row.getFloorNo());
                        product.setWidth(defaultDecimal(row.getWidth()));
                        product.setHeight(defaultDecimal(row.getHeight()));
                        product.setQuantity(defaultDecimal(row.getQuantity()));
                        product.setActualPieceArea(defaultDecimal(row.getActualSingleArea()));
                        product.setActualTotalArea(defaultDecimal(row.getActualTotalArea()));
                        product.setSettlePieceArea(defaultDecimal(row.getSettlementSingleArea()));
                        product.setSettleTotalArea(defaultDecimal(row.getSettlementTotalArea()));
                        product.setTaxInclusiveUnitPrice(defaultDecimal(row.getUnitPrice()));
                        product.setPerimeter(defaultDecimal(row.getPerimeter()));
                        product.setHeavyBox(defaultDecimal(row.getHeavyBox()));
                        product.setProcessRequirement(row.getProcessRequirement());
                        product.setRemark(StringUtils.hasText(row.getAuditRemark()) ? row.getAuditRemark() : row.getRemark());
                        product.setApproveStatus(0);
                        product.setProductStockStatus(0);
                        product.setRegister(creatorUser.getNickName());
                        product.setRegisterDate(row.getReportDate() == null ? LocalDateTime.now() : LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault()));
                        BigDecimal qty = defaultDecimal(product.getQuantity());
                        if (qty.compareTo(BigDecimal.ZERO) <= 0) {
                            throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在数量小于等于0的数据");
                        }
                        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);
                        if (customer.getCustomerName() != null && customer.getCustomerName().startsWith("补片")) {
                            Long inspectId = createNotShippingQualityInspect(ledger, product, row, qty);
                            stockUtils.addStock(
                                    ledger.getId(),
                                    product.getId(),
                                    product.getProductModelId(),
                                    qty,
                                    StockInQualifiedRecordTypeEnum.SALE_QC_OK_IN.getCode(),
                                    inspectId != null ? inspectId : product.getId()
                            );
                            stockUtils.substractStock(
                                    ledger.getId(),
                                    product.getId(),
                                    product.getProductModelId(),
                                    qty,
                                    StockOutQualifiedRecordTypeEnum.SALE_SHIP_STOCK_OUT.getCode(),
                                    product.getId()
                            );
                            StockInRecord inRecord = stockInRecordMapper.selectOne(new LambdaQueryWrapper<StockInRecord>()
                                    .eq(StockInRecord::getSalesLedgerProductId, product.getId())
                                    .orderByDesc(StockInRecord::getId).last("LIMIT 1"));
                            if (inRecord != null) {
                                String batch = "RK";
                                if (row.getReportDate() != null) {
                                    String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(row.getReportDate());
                                    batch += dateStr + "-" + row.getReportDate().getTime();
                                } else {
                                    batch += System.currentTimeMillis() + "-" + inRecord.getId();
                                }
                                inRecord.setInboundBatches(batch);
                                if (row.getReportDate() != null) {
                                    LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
                                    inRecord.setCreateTime(reportDateTime);
                                    inRecord.setUpdateTime(reportDateTime);
                                }
                                stockInRecordMapper.updateById(inRecord);
                            }
                            StockOutRecord outRecord = stockOutRecordMapper.selectOne(new LambdaQueryWrapper<StockOutRecord>()
                                    .eq(StockOutRecord::getSalesLedgerProductId, product.getId())
                                    .orderByDesc(StockOutRecord::getId).last("LIMIT 1"));
                            if (outRecord != null) {
                                String batch = "CK";
                                if (row.getReportDate() != null) {
                                    String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(row.getReportDate());
                                    batch += dateStr + "-" + row.getReportDate().getTime();
                                } else {
                                    batch += System.currentTimeMillis() + "-" + outRecord.getId();
                                }
                                outRecord.setOutboundBatches(batch);
                                if (row.getReportDate() != null) {
                                    LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
                                    outRecord.setCreateTime(reportDateTime);
                                    outRecord.setUpdateTime(reportDateTime);
                                }
                                stockOutRecordMapper.updateById(outRecord);
                            }
                            product.setStockedQuantity(qty);
                            product.setShippedQuantity(qty);
                            product.setApproveStatus(3);
                            updateProductStockStatus(product);
                            product.fillRemainingQuantity();
                            updateProductShipStatus(product);
                            salesLedgerProductMapper.updateById(product);
                            ShippingInfo shippingInfo = new ShippingInfo();
                            shippingInfo.setSalesLedgerId(ledger.getId());
                            shippingInfo.setSalesLedgerProductId(product.getId());
                            shippingInfo.setStatus("已发货");
                            if (row.getReportDate() != null) {
                                String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(row.getReportDate());
                                shippingInfo.setShippingNo("CK" + dateStr + "-" + row.getReportDate().getTime());
                            } else {
                                shippingInfo.setShippingNo("CK" + System.currentTimeMillis());
                            }
                            shippingInfo.setType("货车");
                            shippingInfo.setShippingCarNumber("无");
                            shippingInfo.setShippingDate(row.getReportDate());
                            shippingInfoMapper.insert(shippingInfo);
                            // createNotShippingQualityInspect moved up
                        }
                    }
                    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);
                        }
                    }
                    salesLedgerMapper.updateById(ledger);
                } catch (Exception e) {
                    log.error("订单 {} 未发货记录导入失败", orderNo, e);
//                    errorMessages.add("订单 [" + orderNo + "] 导入失败: " + e.getMessage());
                }
                salesLedgerProductServiceImpl.addProductionData(product);
                contractAmount = contractAmount.add(lineAmount);
            }
            ledger.setContractAmount(contractAmount);
            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) {
@@ -2631,6 +3060,9 @@
        mergeProcessQuantity(processQuantityMap, "挖缺", toProcessQuantity(row.getNotching()));
        mergeProcessQuantity(processQuantityMap, "安全角", toProcessQuantity(row.getSafetyCorner()));
        mergeProcessQuantity(processQuantityMap, "磨边", toProcessQuantity(row.getGrindingIrregular()));
        mergeProcessQuantity(processQuantityMap, "精磨边", toProcessQuantity(row.getFineGrinding()));
        mergeProcessQuantity(processQuantityMap, "运费", toProcessQuantity(row.getFreightFee()));
        mergeProcessQuantity(processQuantityMap, "加急费", toProcessQuantity(row.getUrgentFee()));
        List<SalesLedgerProductProcess> result = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : processQuantityMap.entrySet()) {
@@ -2684,6 +3116,11 @@
        if (CollectionUtils.isEmpty(processNames)) {
            throw new ServiceException("导入失败,工艺路线[" + flowKey + "]解析失败");
        }
        synchronized (("ROUTE_" + flowKey).intern()) {
            ProcessRoute exists = routeNameMap.get(flowKey);
            if (exists != null && exists.getId() != null) {
                return exists;
            }
        ProcessRoute route = new ProcessRoute();
        route.setProductModelId(0L);
        route.setProcessRouteName(flowKey);
@@ -2706,6 +3143,7 @@
        routeNameMap.put(flowKey, route);
        routeItemMap.put(route.getId(), routeItems);
        return route;
        }
    }
    private void mergeProcessQuantity(Map<String, Integer> processQuantityMap, String processName, Integer quantity) {
@@ -2782,12 +3220,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) {
@@ -2809,12 +3253,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) {
@@ -2826,16 +3276,36 @@
        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());
        created.setThickness(thickness);
        created.setUnit("mm");
        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();
        }
@@ -2947,16 +3417,21 @@
        String shippingNo = StringUtils.hasText(row.getShippingNo()) ? row.getShippingNo().trim() : "";
        String dateStr = row.getReportDate() == null ? "" : String.valueOf(row.getReportDate().getTime());
        String subCategory = StringUtils.hasText(row.getProductSubCategory()) ? row.getProductSubCategory().trim() : "";
        return ledgerId + "|" + subCategory + "|" + shippingNo + "|" + dateStr + "|" + defaultDecimal(row.getQuantity());
        Long sequence = row.getSequence();
        if (sequence == null) {
            throw new ServiceException("新增失败,导入出库单编号为空");
        }
        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);
@@ -2965,6 +3440,9 @@
        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);
@@ -2980,12 +3458,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();
@@ -2998,6 +3483,69 @@
            return param;
        }).collect(Collectors.toList());
        inspectParams.forEach(qualityInspectParamMapper::insert);
        return qualityInspect.getId();
    }
    private Long createNotShippingQualityInspect(SalesLedger ledger, SalesLedgerProduct dbProduct, SalesNotShippingImportDto row, BigDecimal inspectQty) {
        if (ledger == null || dbProduct == null || inspectQty == null || inspectQty.compareTo(BigDecimal.ZERO) <= 0) {
            return null;
        }
        Date checkDate = row.getReportDate() != null ? row.getReportDate() : new Date();
        QualityInspect qualityInspect = new QualityInspect();
        qualityInspect.setInspectType(2);
        qualityInspect.setPurchaseLedgerId(dbProduct.getId());
        qualityInspect.setCheckTime(checkDate);
        qualityInspect.setCustomer(StringUtils.hasText(ledger.getCustomerName()) ? ledger.getCustomerName() : row.getCustomerName());
        qualityInspect.setCheckName(StringUtils.hasText(row.getCreator()) ? row.getCreator().trim() : null);
        qualityInspect.setProductId(dbProduct.getProductId());
        qualityInspect.setProductName(dbProduct.getProductCategory());
        qualityInspect.setModel(dbProduct.getSpecificationModel());
        qualityInspect.setUnit(resolveInspectUnit(dbProduct));
        qualityInspect.setQuantity(inspectQty);
        qualityInspect.setQualifiedQuantity(inspectQty);
        qualityInspect.setUnqualifiedQuantity(BigDecimal.ZERO);
        qualityInspect.setPassRate(BigDecimal.valueOf(100));
        qualityInspect.setCheckResult("合格");
        qualityInspect.setInspectState(1);
        qualityInspect.setApprovalStatus(1);
        qualityInspect.setProductModelId(dbProduct.getProductModelId());
        QualityTestStandard selectedStandard = null;
        if (dbProduct.getProductId() != null) {
            List<QualityTestStandard> standards = qualityTestStandardMapper.getQualityTestStandardByProductId(dbProduct.getProductId(), 2, null);
            if (CollectionUtils.isNotEmpty(standards)) {
                selectedStandard = standards.get(0);
                qualityInspect.setTestStandardId(selectedStandard.getId());
            }
        }
        qualityInspectMapper.insert(qualityInspect);
        if (row.getReportDate() != null) {
            LocalDateTime reportDateTime = LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault());
            qualityInspect.setCreateTime(reportDateTime);
            qualityInspect.setUpdateTime(reportDateTime);
            qualityInspectMapper.updateById(qualityInspect);
        }
        if (selectedStandard == null || selectedStandard.getId() == null) {
            return qualityInspect.getId();
        }
        List<QualityTestStandardParam> standardParams = qualityTestStandardParamMapper.selectList(Wrappers.<QualityTestStandardParam>lambdaQuery().eq(QualityTestStandardParam::getTestStandardId, selectedStandard.getId()));
        if (CollectionUtils.isEmpty(standardParams)) {
            return qualityInspect.getId();
        }
        List<QualityInspectParam> inspectParams = standardParams.stream().map(item -> {
            QualityInspectParam param = new QualityInspectParam();
            param.setInspectId(qualityInspect.getId());
            param.setParameterItem(item.getParameterItem());
            param.setUnit(item.getUnit());
            param.setStandardValue(item.getStandardValue());
            param.setControlValue(item.getControlValue());
            param.setTestValue("无瑕疵");
            return param;
        }).collect(Collectors.toList());
        inspectParams.forEach(qualityInspectParamMapper::insert);
        return qualityInspect.getId();
    }
    private String resolveInspectUnit(SalesLedgerProduct dbProduct) {
@@ -3134,7 +3682,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());
@@ -3315,4 +3863,802 @@
        }
        baseMapper.updateById(salesLedger);
    }
    /**
     * 处理销售台账反审逻辑
     * 1. 设置反审相关信息(时间、人员)
     * 2. 复制原销售台账及产品数据,生成新的台账
     * 3. 对原台账的库存数据进行反向操作
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Long> counterReview(CounterReviewDto dto) {
        if (dto == null || CollectionUtils.isEmpty(dto.getIds())) {
            throw new ServiceException("请选择要反审核的订单");
        }
        if (dto.getCounterReviewType() == null || (dto.getCounterReviewType() != 1 && dto.getCounterReviewType() != 2)) {
            throw new ServiceException("请选择反审核类型:作废或重新生成");
        }
        if (dto.getCounterReviewDesc() == null || dto.getCounterReviewDesc().trim().isEmpty()) {
            throw new ServiceException("请输入反审核描述");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<Long> newLedgerIds = new ArrayList<>();
        for (Long id : dto.getIds()) {
            SalesLedger originalLedger = salesLedgerMapper.selectById(id);
            if (originalLedger == null) {
                throw new ServiceException("订单不存在,无法反审核");
            }
            if (originalLedger.getReviewStatus() == null || originalLedger.getReviewStatus() != 1) {
                throw new ServiceException("订单" + originalLedger.getSalesContractNo() + "不是已审核状态,无法反审核");
            }
            // 1. 标记原订单为已反审
            originalLedger.setReviewStatus(2);
            originalLedger.setCounterReviewTime(LocalDateTime.now());
            originalLedger.setCounterReviewPerson(loginUser.getUser().getNickName());
            originalLedger.setCounterReviewPersonId(loginUser.getUserId());
            originalLedger.setCounterReviewType(dto.getCounterReviewType());
            originalLedger.setCounterReviewDesc(dto.getCounterReviewDesc());
            salesLedgerMapper.updateById(originalLedger);
            // 2. 作废库存:入库扣减、出库增加、删除记录
            processOriginalOrderStock(id);
            // 3. 清除质检记录
            clearQualityInspectRecords(id);
            // 4. 清除发货信息和发货审批记录
            clearShippingAndApprovalRecords(id);
            // 5. 取消审批流程
            cancelApproveProcesses(id, originalLedger.getSalesContractNo());
            // 6. 重新生成:创建新台账副本
            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());
            }
        }
        return newLedgerIds;
    }
    /**
     * 旧版反审处理(兼容 addOrUpdateSalesLedger 中 reviewStatus=2 的调用)
     */
    private void handleCounterReview(SalesLedger salesLedger) {
        // 1. 设置反审相关信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        salesLedger.setCounterReviewTime(LocalDateTime.now());
        salesLedger.setCounterReviewPerson(loginUser.getUser().getNickName());
        salesLedger.setCounterReviewPersonId(loginUser.getUserId());
        salesLedger.setReviewStatus(2);
        Long originalSalesLedgerId = salesLedger.getId();
        // 2. 查询原销售台账数据
        SalesLedger originalLedger = salesLedgerMapper.selectById(originalSalesLedgerId);
        if (originalLedger == null) {
            throw new ServiceException("原订单不存在,无法反审");
        }
        // 3. 创建新的销售台账,复制原台账数据
        SalesLedger newLedger = new SalesLedger();
        BeanUtils.copyProperties(originalLedger, newLedger);
        newLedger.setId(null); // 清空ID,准备插入新记录
        newLedger.setSalesContractNo(generateSalesContractNo()); // 生成新合同号
        newLedger.setDeliveryStatus(1); // 设置为未发货状态
        newLedger.setStockStatus(0); // 设置为未入库状态
        newLedger.setReviewStatus(0); // 设置为未审核状态
        newLedger.setCounterReviewTime(null); // 清空反审时间
        newLedger.setCounterReviewPerson(null); // 清空反审人
        newLedger.setCounterReviewPersonId(null); // 清空反审人ID
        // 4. 插入新的销售台账
        salesLedgerMapper.insert(newLedger);
        // 5. 查询并复制原台账的所有产品数据
        List<SalesLedgerProduct> originalProducts = salesLedgerProductMapper.selectList(
                Wrappers.<SalesLedgerProduct>lambdaQuery()
                        .eq(SalesLedgerProduct::getSalesLedgerId, originalSalesLedgerId)
        );
        for (SalesLedgerProduct originalProduct : originalProducts) {
            // 5.1 创建新产品记录,复制原产品数据
            SalesLedgerProduct newProduct = new SalesLedgerProduct();
            BeanUtils.copyProperties(originalProduct, newProduct);
            newProduct.setId(null); // 清空ID,准备插入新记录
            newProduct.setSalesLedgerId(newLedger.getId()); // 关联到新的台账ID
            newProduct.setStockedQuantity(BigDecimal.ZERO); // 已入库数量重置为0
            newProduct.setShippedQuantity(BigDecimal.ZERO); // 已出库数量重置为0
            newProduct.setUnqualifiedStockedQuantity(BigDecimal.ZERO); // 不合格入库数量重置为0
            newProduct.setUnqualifiedShippedQuantity(BigDecimal.ZERO); // 不合格出库数量重置为0
            newProduct.setReturnQuality(BigDecimal.ZERO); // 退货数量重置为0
            newProduct.setAvailableQuality(newProduct.getQuantity().subtract(newProduct.getReturnQuality())); // 重新计算可用数量
            newProduct.setProductStockStatus(0); // 产品库存状态重置为0
            newProduct.fillRemainingQuantity(); // 重新计算剩余数量
            // 5.2 插入新产品记录
            salesLedgerProductMapper.insert(newProduct);
        }
        // 6. 处理原订单的库存数据(生成反审出入库记录)
        processOriginalOrderStock(originalSalesLedgerId);
        // 7. 清除原订单的质检记录
        clearQualityInspectRecords(originalSalesLedgerId);
        // 8. 清除原订单的发货信息和发货审批记录
        clearShippingAndApprovalRecords(originalSalesLedgerId);
        // 9. 取消原订单相关的审批流程
        cancelApproveProcesses(originalSalesLedgerId, originalLedger.getSalesContractNo());
    }
    /**
     * 清除原订单的质检记录
     */
    private void clearQualityInspectRecords(Long originalSalesLedgerId) {
        // 删除与原订单关联的质检记录
        qualityInspectMapper.delete(
                Wrappers.<QualityInspect>lambdaQuery()
                        .eq(QualityInspect::getPurchaseLedgerId, originalSalesLedgerId)
        );
    }
    /**
     * 清除原订单的发货信息和发货审批记录
     */
    private void clearShippingAndApprovalRecords(Long originalSalesLedgerId) {
        // 1. 查询原订单的所有发货信息
        List<ShippingInfo> shippingInfos = shippingInfoMapper.selectList(
                Wrappers.<ShippingInfo>lambdaQuery()
                        .eq(ShippingInfo::getSalesLedgerId, originalSalesLedgerId)
        );
        // 2. 删除发货审批记录
        if (!CollectionUtils.isEmpty(shippingInfos)) {
            List<Long> shippingInfoIds = shippingInfos.stream()
                    .map(ShippingInfo::getId)
                    .collect(Collectors.toList());
            shipmentApprovalMapper.delete(
                    Wrappers.<ShipmentApproval>lambdaQuery()
                            .eq(ShipmentApproval::getSalesLedgerId, originalSalesLedgerId)
                            .or()
                            .in(ShipmentApproval::getShippingInfoId, shippingInfoIds)
            );
            // 3. 删除发货信息记录
            shippingInfoMapper.delete(
                    Wrappers.<ShippingInfo>lambdaQuery()
                            .eq(ShippingInfo::getSalesLedgerId, originalSalesLedgerId)
            );
        }
    }
    /**
     * 取消原订单相关的审批流程
     */
    private void cancelApproveProcesses(Long originalSalesLedgerId, String originalSalesContractNo) {
        // 取消入库审批流程
        List<ApproveProcess> stockInApproveProcesses = approveProcessService.list(
                new LambdaQueryWrapper<ApproveProcess>()
                        .eq(ApproveProcess::getApproveType, ApproveTypeEnum.STOCK_IN.getCode())
                        .like(ApproveProcess::getApproveRemark, "salesStock:" + originalSalesLedgerId + ":")
                        .eq(ApproveProcess::getApproveDelete, 0)
        );
        for (ApproveProcess process : stockInApproveProcesses) {
            process.setApproveStatus(3); // 设置为审批失败状态
            process.setApproveDelete(1); // 标记为已删除
            approveProcessService.updateById(process);
        }
        // 取消发货审批流程
        List<ApproveProcess> deliveryApproveProcesses = approveProcessService.list(
                new LambdaQueryWrapper<ApproveProcess>()
                        .eq(ApproveProcess::getApproveType, 7) // 发货审批类型
                        .like(ApproveProcess::getApproveReason, "发货审批:" + originalSalesContractNo)
                        .eq(ApproveProcess::getApproveDelete, 0)
        );
        for (ApproveProcess process : deliveryApproveProcesses) {
            process.setApproveStatus(3); // 设置为审批失败状态
            process.setApproveDelete(1); // 标记为已删除
            approveProcessService.updateById(process);
        }
    }
    /**
     * 处理原订单的库存数据
     * 1. 删除原订单的所有入库记录,并扣减库存
     * 2. 删除原订单的所有出库记录,并增加库存
     */
    private void processOriginalOrderStock(Long originalSalesLedgerId) {
        // 1. 查询原订单的所有入库记录
        List<StockInRecord> stockInRecords = stockInRecordMapper.selectList(
                Wrappers.<StockInRecord>lambdaQuery()
                        .eq(StockInRecord::getSalesLedgerId, originalSalesLedgerId)
        );
        // 2. 删除入库记录并扣减库存
        for (StockInRecord stockInRecord : stockInRecords) {
            // 从库存表中扣减相应数量
            StockInventoryDto stockInventoryDto = new StockInventoryDto();
            stockInventoryDto.setProductModelId(stockInRecord.getProductModelId());
            stockInventoryDto.setQualitity(stockInRecord.getStockInNum());
            stockInventoryMapper.updateSubtractStockInventory(stockInventoryDto);
        }
        // 3. 删除所有入库记录
        stockInRecordMapper.delete(
                Wrappers.<StockInRecord>lambdaQuery()
                        .eq(StockInRecord::getSalesLedgerId, originalSalesLedgerId)
        );
        // 4. 查询原订单的所有出库记录
        List<StockOutRecord> stockOutRecords = stockOutRecordMapper.selectList(
                Wrappers.<StockOutRecord>lambdaQuery()
                        .eq(StockOutRecord::getSalesLedgerId, originalSalesLedgerId)
        );
        // 5. 删除出库记录并增加库存
        for (StockOutRecord stockOutRecord : stockOutRecords) {
            // 向库存表中增加相应数量
            StockInventoryDto stockInventoryDto = new StockInventoryDto();
            stockInventoryDto.setProductModelId(stockOutRecord.getProductModelId());
            stockInventoryDto.setQualitity(stockOutRecord.getStockOutNum());
            stockInventoryMapper.updateAddStockInventory(stockInventoryDto);
        }
        // 6. 删除所有出库记录
        stockOutRecordMapper.delete(
                Wrappers.<StockOutRecord>lambdaQuery()
                        .eq(StockOutRecord::getSalesLedgerId, originalSalesLedgerId)
        );
    }
    @Override
    public void incrementPrintCount(Long id, String printType) {
        if (id == null) {
            throw new ServiceException("销售台账ID不能为空");
        }
        if (printType == null || (!"label".equals(printType) && !"document".equals(printType))) {
            throw new ServiceException("打印类型必须为 label 或 document");
        }
        SalesLedger ledger = salesLedgerMapper.selectById(id);
        if (ledger == null) {
            throw new ServiceException("销售台账不存在");
        }
        if ("label".equals(printType)) {
            int currentCount = ledger.getLabelPrintCount() == null ? 0 : ledger.getLabelPrintCount();
            salesLedgerMapper.update(null,
                    Wrappers.<SalesLedger>lambdaUpdate()
                            .eq(SalesLedger::getId, id)
                            .set(SalesLedger::getLabelPrintCount, currentCount + 1)
            );
        } else {
            int currentCount = ledger.getDocumentPrintCount() == null ? 0 : ledger.getDocumentPrintCount();
            salesLedgerMapper.update(null,
                    Wrappers.<SalesLedger>lambdaUpdate()
                            .eq(SalesLedger::getId, id)
                            .set(SalesLedger::getDocumentPrintCount, currentCount + 1)
            );
        }
    }
    @Override
    public void exportWithProducts(HttpServletResponse response, SalesLedgerDto salesLedgerDto) {
        try {
            // 1. 查询销售台账列表(导出使用升序排序)
            Page<SalesLedger> page = new Page<>(-1, -1);
            // 使用 Wrappers 构建升序查询
            LambdaQueryWrapper<SalesLedger> queryWrapper = Wrappers.<SalesLedger>lambdaQuery()
                    .orderByAsc(SalesLedger::getEntryDate)
                    .orderByAsc(SalesLedger::getId);
            // 添加查询条件
            if (salesLedgerDto.getCustomerName() != null && !salesLedgerDto.getCustomerName().isEmpty()) {
                queryWrapper.like(SalesLedger::getCustomerName, salesLedgerDto.getCustomerName());
            }
            if (salesLedgerDto.getSalesContractNo() != null && !salesLedgerDto.getSalesContractNo().isEmpty()) {
                queryWrapper.like(SalesLedger::getSalesContractNo, salesLedgerDto.getSalesContractNo());
            }
            if (salesLedgerDto.getProjectName() != null && !salesLedgerDto.getProjectName().isEmpty()) {
                queryWrapper.like(SalesLedger::getProjectName, salesLedgerDto.getProjectName());
            }
            if (salesLedgerDto.getEntryDateStart() != null && !salesLedgerDto.getEntryDateStart().isEmpty()) {
                queryWrapper.ge(SalesLedger::getEntryDate, salesLedgerDto.getEntryDateStart());
            }
            if (salesLedgerDto.getEntryDateEnd() != null && !salesLedgerDto.getEntryDateEnd().isEmpty()) {
                queryWrapper.le(SalesLedger::getEntryDate, salesLedgerDto.getEntryDateEnd());
            }
            if (salesLedgerDto.getDeliveryStatus() != null) {
                queryWrapper.eq(SalesLedger::getDeliveryStatus, salesLedgerDto.getDeliveryStatus());
            }
            if (salesLedgerDto.getStockStatus() != null) {
                queryWrapper.eq(SalesLedger::getStockStatus, salesLedgerDto.getStockStatus());
            }
            if (salesLedgerDto.getReviewStatus() != null) {
                queryWrapper.eq(SalesLedger::getReviewStatus, salesLedgerDto.getReviewStatus());
            }
            if (salesLedgerDto.getReviewStatusList() != null && !salesLedgerDto.getReviewStatusList().isEmpty()) {
                queryWrapper.and(w -> w.in(SalesLedger::getReviewStatus, salesLedgerDto.getReviewStatusList())
                        .or().isNull(SalesLedger::getReviewStatus));
            }
            IPage<SalesLedger> ledgerPage = salesLedgerMapper.selectPage(page, queryWrapper);
            List<SalesLedger> ledgerList = ledgerPage.getRecords();
            // 2. 收集数据
            List<SalesLedgerExportDto> ledgerExportList = new ArrayList<>();
            List<SalesLedgerProductExportDto> productExportList = new ArrayList<>();
            for (SalesLedger ledger : ledgerList) {
                // 转换台账数据
                SalesLedgerExportDto ledgerDto = new SalesLedgerExportDto();
                ledgerDto.setSalesContractNo(ledger.getSalesContractNo());
                ledgerDto.setCustomerContractNo(ledger.getCustomerContractNo());
                ledgerDto.setProjectName(ledger.getProjectName());
                ledgerDto.setCustomerName(ledger.getCustomerName());
                ledgerDto.setSalesman(ledger.getSalesman());
                ledgerDto.setEntryPersonName(ledger.getEntryPersonName());
                ledgerDto.setEntryDate(ledger.getEntryDate());
                ledgerDto.setExecutionDate(ledger.getExecutionDate() != null ?
                        java.sql.Date.valueOf(ledger.getExecutionDate()) : null);
                ledgerDto.setDeliveryDate(ledger.getDeliveryDate() != null ?
                        java.sql.Date.valueOf(ledger.getDeliveryDate()) : null);
                ledgerDto.setContractAmount(ledger.getContractAmount());
                ledgerDto.setRemarks(ledger.getRemarks());
                ledgerDto.setCustomerRemarks(ledger.getCustomerRemarks());
                ledgerDto.setDeliveryStatusText(getDeliveryStatusText(ledger.getDeliveryStatus()));
                ledgerDto.setStockStatusText(getStockStatusText(ledger.getStockStatus()));
                ledgerDto.setReviewStatusText(getReviewStatusText(ledger.getReviewStatus()));
                ledgerExportList.add(ledgerDto);
                // 查询该台账的产品列表
                List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(
                        Wrappers.<SalesLedgerProduct>lambdaQuery()
                                .eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId())
                                .eq(SalesLedgerProduct::getType, 1)
                );
                for (SalesLedgerProduct product : products) {
                    SalesLedgerProductExportDto productDto = new SalesLedgerProductExportDto();
                    productDto.setSalesContractNo(ledger.getSalesContractNo());
                    productDto.setProductCategory(product.getProductCategory());
                    productDto.setSpecificationModel(product.getSpecificationModel());
                    productDto.setThickness(product.getThickness());
                    productDto.setFloorCode(product.getFloorCode());
                    productDto.setWidth(product.getWidth());
                    productDto.setHeight(product.getHeight());
                    productDto.setQuantity(product.getQuantity());
                    productDto.setSettlePieceArea(product.getSettlePieceArea());
                    productDto.setSettleTotalArea(product.getSettleTotalArea());
                    productDto.setTaxInclusiveUnitPrice(product.getTaxInclusiveUnitPrice());
                    productDto.setTaxRate(product.getTaxRate());
                    productDto.setTaxInclusiveTotalPrice(product.getTaxInclusiveTotalPrice());
                    productDto.setTaxExclusiveTotalPrice(product.getTaxExclusiveTotalPrice());
                    productDto.setInvoiceType(product.getInvoiceType());
                    productDto.setProcessRequirement(product.getProcessRequirement());
                    productDto.setRemark(product.getRemark());
                    productExportList.add(productDto);
                }
            }
            // 3. 使用ExcelUtil导出(内部会创建Workbook并写入响应)
            // 先创建临时文件,再合并两个sheet
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("销售台账.xlsx", "utf-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
            org.apache.poi.xssf.usermodel.XSSFWorkbook workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook();
            // Sheet1: 销售台账 - 手动填充
            fillSheetWithData(workbook, "销售台账", SalesLedgerExportDto.class, ledgerExportList);
            // Sheet2: 产品明细 - 手动填充
            fillSheetWithData(workbook, "产品明细", SalesLedgerProductExportDto.class, productExportList);
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            log.error("导出销售台账失败", e);
            throw new ServiceException("导出失败:" + e.getMessage());
        }
    }
    @Override
    public void exportProcessRoute(HttpServletResponse response, List<Long> salesLedgerIds, String completedTimeStart, String completedTimeEnd) {
        try {
            if (CollectionUtils.isEmpty(salesLedgerIds)) {
                throw new ServiceException("请选择要导出的销售台账");
            }
            LocalDateTime startTime = parseCompletedTime(completedTimeStart);
            LocalDateTime endTime = parseCompletedTime(completedTimeEnd);
            if (startTime == null && endTime == null) {
                startTime = LocalDate.now().atStartOfDay();
                endTime = LocalDateTime.now();
            } else {
                if (startTime == null) {
                    startTime = LocalDate.now().atStartOfDay();
                }
                if (endTime == null) {
                    endTime = LocalDateTime.now();
                }
            }
            LambdaQueryWrapper<SalesLedgerProcessRouteRecord> queryWrapper = Wrappers.<SalesLedgerProcessRouteRecord>lambdaQuery()
                    .eq(SalesLedgerProcessRouteRecord::getIsCompleted, 1)
                    .ge(SalesLedgerProcessRouteRecord::getCompletedTime, startTime)
                    .le(SalesLedgerProcessRouteRecord::getCompletedTime, endTime)
                    .orderByAsc(SalesLedgerProcessRouteRecord::getCompletedTime)
                    .orderByAsc(SalesLedgerProcessRouteRecord::getId);
            if (CollectionUtils.isNotEmpty(salesLedgerIds)) {
                queryWrapper.in(SalesLedgerProcessRouteRecord::getSalesLedgerId, salesLedgerIds);
            }
            List<SalesLedgerProcessRouteRecord> completedRoutes = salesLedgerProcessRouteRecordService.list(queryWrapper);
            Map<Long, SalesLedger> salesLedgerMap = Collections.emptyMap();
            Map<Long, SalesLedgerProcessRoute> routeMap = Collections.emptyMap();
            Map<Long, ProcessRouteItem> processRouteItemMap = Collections.emptyMap();
            Map<Long, List<SalesLedgerProduct>> productMap = Collections.emptyMap();
            if (CollectionUtils.isNotEmpty(completedRoutes)) {
                List<Long> routeSalesLedgerIds = completedRoutes.stream()
                        .map(SalesLedgerProcessRouteRecord::getSalesLedgerId)
                        .filter(Objects::nonNull)
                        .distinct()
                        .collect(Collectors.toList());
                List<Long> salesLedgerProcessRouteIds = completedRoutes.stream()
                        .map(SalesLedgerProcessRouteRecord::getSalesLedgerProcessRouteId)
                        .filter(Objects::nonNull)
                        .distinct()
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(routeSalesLedgerIds)) {
                    salesLedgerMap = salesLedgerMapper.selectBatchIds(routeSalesLedgerIds).stream()
                            .filter(Objects::nonNull)
                            .collect(Collectors.toMap(SalesLedger::getId, item -> item, (a, b) -> a));
                    List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>()
                            .in(SalesLedgerProduct::getSalesLedgerId, routeSalesLedgerIds)
                            .eq(SalesLedgerProduct::getType, 1)
                            .orderByAsc(SalesLedgerProduct::getSalesLedgerId)
                            .orderByAsc(SalesLedgerProduct::getId));
                    productMap = products.stream().collect(Collectors.groupingBy(
                            SalesLedgerProduct::getSalesLedgerId,
                            LinkedHashMap::new,
                            Collectors.toList()
                    ));
                }
                if (CollectionUtils.isNotEmpty(salesLedgerProcessRouteIds)) {
                    routeMap = salesLedgerProcessRouteService.listByIds(salesLedgerProcessRouteIds).stream()
                            .filter(Objects::nonNull)
                            .collect(Collectors.toMap(SalesLedgerProcessRoute::getId, item -> item, (a, b) -> a));
                    List<Long> processRouteItemIds = routeMap.values().stream()
                            .map(SalesLedgerProcessRoute::getProcessRouteItemId)
                            .filter(Objects::nonNull)
                            .distinct()
                            .collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(processRouteItemIds)) {
                        processRouteItemMap = processRouteItemMapper.selectBatchIds(processRouteItemIds).stream()
                                .filter(Objects::nonNull)
                                .collect(Collectors.toMap(ProcessRouteItem::getId, item -> item, (a, b) -> a));
                    }
                }
            }
            Map<Long, List<SalesLedgerProcessRouteRecord>> routeGroupMap = new LinkedHashMap<>();
            for (SalesLedgerProcessRouteRecord record : completedRoutes) {
                SalesLedgerProcessRoute route = routeMap.get(record.getSalesLedgerProcessRouteId());
                if (route == null || route.getProcessRouteItemId() == null) {
                    continue;
                }
                routeGroupMap.computeIfAbsent(route.getProcessRouteItemId(), k -> new ArrayList<>()).add(record);
            }
            final Map<Long, ProcessRouteItem> finalProcessRouteItemMap = processRouteItemMap;
            LinkedHashMap<String, List<List<Object>>> sheetMap = new LinkedHashMap<>();
            List<Long> orderedProcessRouteItemIds = routeGroupMap.keySet().stream()
                    .sorted((left, right) -> compareProcessRouteItem(left, right, finalProcessRouteItemMap))
                    .collect(Collectors.toList());
            for (Long processRouteItemId : orderedProcessRouteItemIds) {
                ProcessRouteItem processRouteItem = finalProcessRouteItemMap.get(processRouteItemId);
                String sheetName = buildUniqueSheetName(sheetMap, processRouteItem, processRouteItemId);
                List<List<Object>> sheetData = new ArrayList<>();
                sheetData.add(buildProcessRouteHeader());
                for (SalesLedgerProcessRouteRecord route : routeGroupMap.getOrDefault(processRouteItemId, Collections.emptyList())) {
                    SalesLedger salesLedger = salesLedgerMap.get(route.getSalesLedgerId());
                    if (salesLedger == null) {
                        continue;
                    }
                    List<SalesLedgerProduct> products = productMap.getOrDefault(salesLedger.getId(), Collections.emptyList());
                    if (CollectionUtils.isEmpty(products)) {
                        sheetData.add(buildProcessRouteRow(salesLedger, null, route));
                        continue;
                    }
                    for (SalesLedgerProduct product : products) {
                        sheetData.add(buildProcessRouteRow(salesLedger, product, route));
                    }
                }
                if (sheetData.size() == 1) {
                    sheetData.add(Arrays.asList("", "", "", "", "", "", "", "", ""));
                }
                sheetMap.put(sheetName, sheetData);
            }
            if (sheetMap.isEmpty()) {
                List<List<Object>> sheetData = new ArrayList<>();
                sheetData.add(buildProcessRouteHeader());
                sheetData.add(Arrays.asList("", "", "", "", "", "", ""));
                sheetMap.put("工艺路线", sheetData);
            }
            com.ruoyi.common.utils.excel.ExcelUtils.exportManySheet(response, "销售台账工艺路线导出", sheetMap);
        } catch (Exception e) {
            log.error("导出售后台账工艺路线失败", e);
            throw new ServiceException("导出售后台账工艺路线失败:" + e.getMessage());
        }
    }
    private LocalDateTime parseCompletedTime(String value) {
        if (!StringUtils.hasText(value)) {
            return null;
        }
        String text = value.trim();
        try {
            return LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } catch (Exception ex) {
            try {
                return LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            } catch (Exception ignored) {
                return LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay();
            }
        }
    }
    private int compareProcessRouteItem(Long left, Long right, Map<Long, ProcessRouteItem> processRouteItemMap) {
        ProcessRouteItem leftItem = processRouteItemMap.get(left);
        ProcessRouteItem rightItem = processRouteItemMap.get(right);
        int leftSort = leftItem != null && leftItem.getDragSort() != null ? leftItem.getDragSort() : Integer.MAX_VALUE;
        int rightSort = rightItem != null && rightItem.getDragSort() != null ? rightItem.getDragSort() : Integer.MAX_VALUE;
        if (leftSort != rightSort) {
            return Integer.compare(leftSort, rightSort);
        }
        String leftName = leftItem != null && StringUtils.hasText(leftItem.getProcessName()) ? leftItem.getProcessName() : "";
        String rightName = rightItem != null && StringUtils.hasText(rightItem.getProcessName()) ? rightItem.getProcessName() : "";
        int nameCompare = leftName.compareTo(rightName);
        if (nameCompare != 0) {
            return nameCompare;
        }
        return Long.compare(left, right);
    }
    private List<Object> buildProcessRouteHeader() {
        return Arrays.asList("日期", "订单编号", "客户名称", "规格", "数量", "面积", "是否是工程");
    }
    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(salesLedger.getSalesContractNo());
        row.add(salesLedger.getCustomerName());
        row.add(product == null ? "" : product.getSpecificationModel());
        row.add(product == null ? "" : product.getQuantity());
        row.add(product == null ? "" : resolveExportArea(product));
        row.add("");
        return row;
    }
    private BigDecimal resolveExportArea(SalesLedgerProduct product) {
        if (product == null) {
            return BigDecimal.ZERO;
        }
        if (product.getSettleTotalArea() != null) {
            return product.getSettleTotalArea();
        }
        if (product.getActualTotalArea() != null) {
            return product.getActualTotalArea();
        }
        BigDecimal qty = product.getQuantity() == null ? BigDecimal.ONE : product.getQuantity();
        if (product.getSettlePieceArea() != null) {
            return product.getSettlePieceArea().multiply(qty).setScale(2, RoundingMode.HALF_UP);
        }
        if (product.getActualPieceArea() != null) {
            return product.getActualPieceArea().multiply(qty).setScale(2, RoundingMode.HALF_UP);
        }
        if (product.getWidth() != null && product.getHeight() != null) {
            BigDecimal area = product.getWidth().multiply(product.getHeight())
                    .divide(new BigDecimal("1000000"), 2, RoundingMode.HALF_UP);
            return area.multiply(qty).setScale(2, RoundingMode.HALF_UP);
        }
        return BigDecimal.ZERO;
    }
    private String buildUniqueSheetName(Map<String, List<List<Object>>> sheetMap, ProcessRouteItem processRouteItem, Long processRouteItemId) {
        String baseName = processRouteItem != null && StringUtils.hasText(processRouteItem.getProcessName())
                ? processRouteItem.getProcessName()
                : "工序" + processRouteItemId;
        baseName = sanitizeSheetName(baseName);
        String sheetName = baseName;
        int suffix = 2;
        while (sheetMap.containsKey(sheetName)) {
            String suffixText = "_" + suffix++;
            int maxBaseLength = 31 - suffixText.length();
            String trimmedBase = baseName.length() > maxBaseLength ? baseName.substring(0, maxBaseLength) : baseName;
            sheetName = trimmedBase + suffixText;
        }
        return sheetName;
    }
    private String sanitizeSheetName(String sheetName) {
        if (!StringUtils.hasText(sheetName)) {
            return "工艺路线";
        }
        String sanitized = sheetName.replaceAll("[\\\\/?*\\[\\]:]", "_").trim();
        if (sanitized.isEmpty()) {
            sanitized = "工艺路线";
        }
        return sanitized.length() > 31 ? sanitized.substring(0, 31) : sanitized;
    }
    /**
     * 手动填充Sheet数据
     */
    private <T> void fillSheetWithData(org.apache.poi.xssf.usermodel.XSSFWorkbook workbook, String sheetName, Class<T> clazz, List<T> dataList) throws Exception {
        org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet(sheetName);
        // 获取字段上的@Excel注解
        java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
        List<java.lang.reflect.Field> excelFields = new ArrayList<>();
        for (java.lang.reflect.Field field : fields) {
            com.ruoyi.framework.aspectj.lang.annotation.Excel excel = field.getAnnotation(com.ruoyi.framework.aspectj.lang.annotation.Excel.class);
            if (excel != null) {
                excelFields.add(field);
            }
        }
        // 创建表头
        org.apache.poi.ss.usermodel.Row headerRow = sheet.createRow(0);
        org.apache.poi.ss.usermodel.CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(org.apache.poi.ss.usermodel.IndexedColors.GREY_50_PERCENT.getIndex());
        headerStyle.setFillPattern(org.apache.poi.ss.usermodel.FillPatternType.SOLID_FOREGROUND);
        headerStyle.setAlignment(org.apache.poi.ss.usermodel.HorizontalAlignment.CENTER);
        org.apache.poi.ss.usermodel.Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);
        for (int i = 0; i < excelFields.size(); i++) {
            java.lang.reflect.Field field = excelFields.get(i);
            field.setAccessible(true);
            com.ruoyi.framework.aspectj.lang.annotation.Excel excel = field.getAnnotation(com.ruoyi.framework.aspectj.lang.annotation.Excel.class);
            org.apache.poi.ss.usermodel.Cell cell = headerRow.createCell(i);
            cell.setCellValue(excel.name());
            cell.setCellStyle(headerStyle);
            sheet.setColumnWidth(i, 20 * 256);
        }
        // 创建数据行
        org.apache.poi.ss.usermodel.CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setAlignment(org.apache.poi.ss.usermodel.HorizontalAlignment.CENTER);
        for (int rowIndex = 0; rowIndex < dataList.size(); rowIndex++) {
            T data = dataList.get(rowIndex);
            org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowIndex + 1);
            for (int colIndex = 0; colIndex < excelFields.size(); colIndex++) {
                java.lang.reflect.Field field = excelFields.get(colIndex);
                field.setAccessible(true);
                Object value = field.get(data);
                org.apache.poi.ss.usermodel.Cell cell = row.createCell(colIndex);
                if (value == null) {
                    cell.setCellValue("");
                } else if (value instanceof Number) {
                    cell.setCellValue(((Number) value).doubleValue());
                } else if (value instanceof Date) {
                    cell.setCellValue(new java.text.SimpleDateFormat("yyyy-MM-dd").format((Date) value));
                } else {
                    cell.setCellValue(value.toString());
                }
                cell.setCellStyle(dataStyle);
            }
        }
    }
    private String getDeliveryStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 1:
                return "未发货";
            case 2:
                return "审批中";
            case 3:
                return "审批不通过";
            case 4:
                return "审批通过";
            case 5:
                return "已发货";
            case 6:
                return "部分发货";
            default:
                return "未知";
        }
    }
    private String getStockStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0:
                return "未入库";
            case 1:
                return "部分入库";
            case 2:
                return "已入库";
            case 3:
                return "审批中";
            default:
                return "未知";
        }
    }
    private String getReviewStatusText(Integer status) {
        if (status == null) return "待审核";
        switch (status) {
            case 0:
                return "待审核";
            case 1:
                return "已审核";
            case 2:
                return "已反审";
            default:
                return "待审核";
        }
    }
}