src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -1,7 +1,6 @@
package com.ruoyi.sales.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
@@ -9,34 +8,42 @@
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.pojo.AccountIncome;
import com.ruoyi.account.service.AccountIncomeService;
import com.ruoyi.basic.mapper.CustomerMapper;
import com.ruoyi.basic.mapper.ProductMapper;
import com.ruoyi.basic.mapper.ProductModelMapper;
import com.ruoyi.basic.pojo.Customer;
import com.ruoyi.basic.pojo.ProductModel;
import com.ruoyi.common.enums.FileNameType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.other.mapper.TempFileMapper;
import com.ruoyi.other.pojo.TempFile;
import com.ruoyi.production.dto.ProductStructureDto;
import com.ruoyi.production.mapper.*;
import com.ruoyi.production.pojo.*;
import com.ruoyi.production.service.ProductionProductMainService;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysDeptMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.quality.mapper.QualityInspectMapper;
import com.ruoyi.quality.pojo.QualityInspect;
import com.ruoyi.sales.dto.MonthlyAmountDto;
import com.ruoyi.sales.dto.SalesLedgerDto;
import com.ruoyi.sales.dto.*;
import com.ruoyi.sales.mapper.*;
import com.ruoyi.sales.pojo.*;
import com.ruoyi.sales.service.ISalesLedgerProductService;
import com.ruoyi.sales.service.ISalesLedgerService;
import com.ruoyi.stock.mapper.StockInventoryMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@@ -44,10 +51,15 @@
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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;
@@ -86,6 +98,12 @@
    private final ReceiptPaymentMapper receiptPaymentMapper;
    private final ShippingInfoServiceImpl shippingInfoServiceImpl;
    private final CommonFileServiceImpl commonFileService;
    private final ShippingInfoMapper shippingInfoMapper;
    private final InvoiceLedgerMapper invoiceLedgerMapper;
    private final SalesLedgerSchedulingMapper salesLedgerSchedulingMapper;
@@ -117,6 +135,11 @@
    private final QualityInspectMapper qualityInspectMapper;
    private final StockInventoryMapper stockInventoryMapper;
    private ISalesLedgerProductService salesLedgerProductService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
@@ -130,8 +153,14 @@
    private final RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ProductModelMapper productModelMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductStructureMapper productStructureMapper;
    @Autowired
    private ProductionProductMainService productionProductMainService;
    ;
    @Override
    public List<SalesLedger> selectSalesLedgerList(SalesLedgerDto salesLedgerDto) {
@@ -158,6 +187,17 @@
            product.setTempNoInvoiceNum(product.getNoInvoiceNum());
            product.setRegister(SecurityUtils.getLoginUser().getUser().getNickName());
            product.setRegisterDate(LocalDateTime.now());
            // 发货信息
            ShippingInfo shippingInfo = shippingInfoMapper.selectOne(new LambdaQueryWrapper<ShippingInfo>()
                    .eq(ShippingInfo::getSalesLedgerProductId, product.getId())
                    .orderByDesc(ShippingInfo::getCreateTime)
                    .last("limit 1"));
            if (shippingInfo != null) {
                product.setShippingStatus(shippingInfo.getStatus());
            }
            ProductModel productModel = productModelMapper.selectById(product.getProductModelId());
            product.setMaterialCode(productModel.getMaterialCode());
        }
        // 3.查询上传文件
@@ -175,6 +215,275 @@
            resultDto.setSalesLedgerFiles(salesLedgerFiles);
        }
        return resultDto;
    }
    @Override
    public void exportShippingNote(HttpServletResponse response, List<Long> ids) {
        try {
            List<SalesLedger> ledgerList = salesLedgerMapper.selectBatchIds(ids);
            String fileName = "送货单.xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            XSSFWorkbook workbook = new XSSFWorkbook();
            for (SalesLedger ledger : ledgerList) {
                XSSFSheet sheet = workbook.createSheet(ledger.getSalesContractNo());
                // 设置页边距(单位:英寸,1英寸=2.54厘米)
                sheet.getPrintSetup().setLandscape(false); // 纵向打印
                sheet.setMargin(Sheet.TopMargin, 0.54 / 2.54);     // 上页边距:0.54厘米
                sheet.setMargin(Sheet.BottomMargin, 0.54 / 2.54);  // 下页边距:0.54厘米
                sheet.setMargin(Sheet.LeftMargin, 0.41 / 2.54);   // 左页边距:0.41厘米
                sheet.setMargin(Sheet.RightMargin, 0.41 / 2.54);  // 右页边距:0.41厘米
                sheet.setMargin(Sheet.HeaderMargin, 0.77 / 2.54); // 页眉:0.77厘米
                sheet.setMargin(Sheet.FooterMargin, 0.27 / 2.54); // 页脚:0.27厘米
                sheet.setColumnWidth(0, 1310);
                sheet.setColumnWidth(1, 4000);
                sheet.setColumnWidth(2, 8980);
                sheet.setColumnWidth(3, 1820);
                sheet.setColumnWidth(4, 2880);
                sheet.setColumnWidth(5, 5090);
                sheet.setColumnWidth(6, 1410);
                CellStyle companyTitle = createBaseStyle(workbook, "宋体", (short) 20, true, true);
                CellStyle billTitle = createBaseStyle(workbook, "宋体", (short) 18, false, true);
                CellStyle headerStyle = createBorderStyle(workbook, "宋体", (short) 12, true, true);
                CellStyle dataCenterStyle = createBorderStyle(workbook, "宋体", (short) 11, false, true);
                // 样式1:带虚线 + 居中
                CellStyle dashStyle = createDashBottomStyle(workbook);
                dashStyle.setAlignment(HorizontalAlignment.CENTER);
                dashStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                // 样式2:无边框 + 居中(给仓库用)
                CellStyle centerNoBorder = createNoBorderStyle(workbook);
                centerNoBorder.setAlignment(HorizontalAlignment.CENTER);
                centerNoBorder.setVerticalAlignment(VerticalAlignment.CENTER);
                // 标题
                Row row0 = sheet.createRow(0);
                row0.createCell(0).setCellValue("湖南鹏创电子有限公司");
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
                fillMergeRange(sheet, 0, 0, 0, 6, companyTitle);
                Row row1 = sheet.createRow(1);
                row1.createCell(0).setCellValue("送   货   单");
                sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 6));
                fillMergeRange(sheet, 1, 1, 0, 6, billTitle);
                Customer customer = customerMapper.selectById(ledger.getCustomerId());
                Row row2 = sheet.createRow(2);
                row2.setHeightInPoints(13);
                row2.createCell(0).setCellValue("客户名称:" + ledger.getCustomerName());
                row2.createCell(4).setCellValue("单据编号:" + ledger.getSalesContractNo());
                Row row3 = sheet.createRow(3);
                row3.setHeightInPoints(13);
                row3.createCell(0).setCellValue("送货地址:" + customer.getCompanyAddress());
                row3.createCell(4).setCellValue("送货日期:" + formatDate(LocalDate.now()));
                // 空行
                Row row4 = sheet.createRow(4);
                row4.setHeightInPoints(13);
                row4.createCell(4).setCellValue("联系电话:" + customer.getCompanyPhone());
                Row row5 = sheet.createRow(5);
                row5.createCell(0).setCellValue("联系方式:" + customer.getContactPerson() + " " + customer.getContactPhone());
                Row row6 = sheet.createRow(6);
                row6.createCell(0).setCellValue("送货单位:湖南鹏创电子有限公司");
                Row row7 = sheet.createRow(7);
                row7.createCell(0).setCellValue("地址:湖南省耒阳市创新创业园A1栋");
                Row row8 = sheet.createRow(8);
                row8.setHeightInPoints((short) 3); // 行高3磅
                Row row9 = sheet.createRow(9);
                row9.createCell(0).setCellValue("货物详细信息:");
                int tableStart = 10;
                Row headerRow = sheet.createRow(tableStart);
                headerRow.setHeightInPoints((short) 18);
                String[] headers = {"序号", "物料编号", "品名/规格", "单位", "数量", "订单号", "共四联"};
                for (int i = 0; i < headers.length; i++) {
                    Cell hc = headerRow.createCell(i);
                    hc.setCellValue(headers[i]);
                    if (i == 6) {
                        hc.setCellStyle(dashStyle);
                    } else {
                        hc.setCellStyle(headerStyle);
                    }
                }
                // 查询产品
                SalesLedgerProduct cond = new SalesLedgerProduct();
                cond.setSalesLedgerId(ledger.getId());
                List<SalesLedgerProduct> productList = salesLedgerProductServiceImpl.selectSalesLedgerProductList(cond);
                BigDecimal totalQuantity = BigDecimal.ZERO;
                for (SalesLedgerProduct p : productList) {
                    if (p.getQuantity() != null) totalQuantity = totalQuantity.add(p.getQuantity());
                }
                int currentRow = tableStart + 1;
                String[] fourNames = {"存根", "回单", "客户", "仓库"};
                // 1. 所有产品
                for (int i = 0; i < productList.size(); i++) {
                    SalesLedgerProduct p = productList.get(i);
                    Row dataRow = sheet.createRow(currentRow++);
                    dataRow.setHeightInPoints((short) 18);
                    String materialCode = "";
                    if (p.getProductModelId() != null) {
                        ProductModel m = productModelMapper.selectById(p.getProductModelId());
                        if (m != null) materialCode = m.getMaterialCode();
                    }
                    dataRow.createCell(0).setCellValue(i + 1);
                    dataRow.createCell(1).setCellValue(materialCode);
                    dataRow.createCell(2).setCellValue(p.getProductCategory() + "/" + p.getSpecificationModel());
                    dataRow.createCell(3).setCellValue(p.getUnit());
                    dataRow.createCell(4).setCellValue(p.getQuantity() == null ? 0 : p.getQuantity().doubleValue());
                    dataRow.createCell(5).setCellValue(ledger.getSalesContractNo());
                    for (int c = 0; c <= 5; c++) dataRow.getCell(c).setCellStyle(dataCenterStyle);
                    Cell fourCell = dataRow.createCell(6);
                    if (i < fourNames.length) {
                        fourCell.setCellValue(fourNames[i]);
                        if (i <= 2) {
                            fourCell.setCellStyle(dashStyle);
                        } else {
                            fourCell.setCellStyle(centerNoBorder);
                        }
                    } else {
                        fourCell.setCellStyle(centerNoBorder);
                    }
                }
                // 2. 不足6行补空
                int minRow = 6;
                int needEmpty = Math.max(0, minRow - productList.size());
                for (int i = 0; i < needEmpty; i++) {
                    int seq = productList.size() + i;
                    Row dataRow = sheet.createRow(currentRow++);
                    dataRow.setHeightInPoints((short) 18);
                    for (int c = 0; c <= 5; c++) dataRow.createCell(c).setCellStyle(dataCenterStyle);
                    Cell fourCell = dataRow.createCell(6);
                    if (seq < fourNames.length) {
                        fourCell.setCellValue(fourNames[seq]);
                        if (seq <= 2) {
                            fourCell.setCellStyle(dashStyle);
                        } else {
                            fourCell.setCellStyle(centerNoBorder);
                        }
                    } else {
                        fourCell.setCellStyle(centerNoBorder);
                    }
                }
                // 合计
                Row totalRow = sheet.createRow(currentRow);
                totalRow.setHeightInPoints((short) 18);
                // 合计放在第二列,不合并单元格
                totalRow.createCell(1).setCellValue("合计");
                totalRow.createCell(4).setCellValue(totalQuantity.doubleValue());
                // 设置样式
                for (int c = 0; c <= 5; c++) {
                    Cell cell = totalRow.getCell(c) != null ? totalRow.getCell(c) : totalRow.createCell(c);
                    cell.setCellStyle(dataCenterStyle);
                }
                totalRow.createCell(6).setCellStyle(centerNoBorder);
                currentRow++;
                Row emptyRow1 = sheet.createRow(currentRow);
                emptyRow1.setHeightInPoints((short) 9); // 行高9磅
                currentRow++;
                Row remarkRow = sheet.createRow(currentRow);
                remarkRow.createCell(0).setCellValue("备注:贵司在收货后请即刻核实数量及品质,若有异议,请在3日内提出,否则视为收妥。");
                sheet.addMergedRegion(new CellRangeAddress(currentRow, currentRow, 0, 6));
                currentRow++;
                Row emptyRow2 = sheet.createRow(currentRow);
                emptyRow2.setHeightInPoints((short) 9); // 行高9磅
                currentRow++;
                Row sign1 = sheet.createRow(currentRow);
                sign1.createCell(0).setCellValue("送货单位(签章):");
                sign1.createCell(4).setCellValue("收货单位:");
                currentRow++;
                Row sign2 = sheet.createRow(currentRow);
                sign2.createCell(0).setCellValue("送货人:");
                sign2.createCell(4).setCellValue("收货人:");
            }
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            log.error("批量导出送货单异常", e);
            throw new RuntimeException("导出失败");
        }
    }
    // 工具类
    private CellStyle createBaseStyle(Workbook workbook, String fontName, short fontSize, boolean bold, boolean center) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName(fontName);
        font.setFontHeightInPoints(fontSize);
        font.setBold(bold);
        style.setFont(font);
        if (center) {
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
        }
        return style;
    }
    private CellStyle createBorderStyle(Workbook workbook, String fontName, short fontSize, boolean bold, boolean center) {
        CellStyle style = createBaseStyle(workbook, fontName, fontSize, bold, center);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }
    private CellStyle createNoBorderStyle(Workbook workbook) {
        return createBaseStyle(workbook, "宋体", (short) 11, false, false);
    }
    private CellStyle createDashBottomStyle(Workbook workbook) {
        CellStyle style = createNoBorderStyle(workbook);
        style.setBorderBottom(BorderStyle.DASHED);
        return style;
    }
    private void fillMergeRange(Sheet sheet, int startR, int endR, int startC, int endC, CellStyle style) {
        for (int r = startR; r <= endR; r++) {
            Row row = sheet.getRow(r) == null ? sheet.createRow(r) : sheet.getRow(r);
            for (int c = startC; c <= endC; c++) {
                Cell cell = row.getCell(c) == null ? row.createCell(c) : row.getCell(c);
                cell.setCellStyle(style);
            }
        }
    }
    public static String formatDate(LocalDate date) {
        if (date == null) {
            return null;
        }
        return date.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
    }
    @Override
@@ -219,8 +528,8 @@
        // 查询原始数据
        LambdaQueryWrapper<SalesLedger> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(SalesLedger::getCustomerId,
                SalesLedger::getCustomerName,
                SalesLedger::getContractAmount)
                        SalesLedger::getCustomerName,
                        SalesLedger::getContractAmount)
                .orderByDesc(SalesLedger::getContractAmount);
        List<SalesLedger> records = salesLedgerMapper.selectList(queryWrapper);
@@ -228,7 +537,7 @@
        Map<Long, GroupedCustomer> groupedMap = new LinkedHashMap<>(); // 使用LinkedHashMap保持排序
        for (SalesLedger record : records) {
            groupedMap.computeIfAbsent(record.getCustomerId(),
                    k -> new GroupedCustomer(record.getCustomerId(), record.getCustomerName()))
                            k -> new GroupedCustomer(record.getCustomerId(), record.getCustomerName()))
                    .addAmount(record.getContractAmount());
        }
@@ -248,82 +557,183 @@
    @Override
    public List<MonthlyAmountDto> getAmountHalfYear(Integer type) {
        LocalDate now = LocalDate.now();
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 根据 type 确定查询的时间间隔(天数)和总查询天数
        int daysPerPeriod;
        int totalDays;
        switch (type) {
            case 1:
                daysPerPeriod = 5;   // 每5天查一次
                totalDays = 30;       // 6次 × 5天 = 30天
                break;
            case 2:
                daysPerPeriod = 15;    // 每15天查一次
                totalDays = 90;       // 6次 × 15天 = 90天
                break;
            case 3:
                daysPerPeriod = 30;   // 每30天查一次
                totalDays = 180;      // 6次 × 30天 = 180天
                break;
            default:
                throw new IllegalArgumentException("Invalid type value: " + type);
        }
        List<MonthlyAmountDto> result = new ArrayList<>();
        // 循环6次,每次查询一个时间段的数据
        for (int i = 0; i < 6; i++) {
            // 计算当前时间段的起始和结束时间
            LocalDateTime endTime = currentDateTime.minusDays(i * daysPerPeriod);
            LocalDateTime startTime = endTime.minusDays(daysPerPeriod);
        for (int i = 5; i >= 0; i--) {
            YearMonth yearMonth = YearMonth.from(now.minusMonths(i));
            LocalDateTime startTime = yearMonth.atDay(1).atStartOfDay();
            LocalDateTime endTime = yearMonth.atEndOfMonth().atTime(23, 59, 59);
            // 查询回款金额
            //  回款金额
            LambdaQueryWrapper<ReceiptPayment> receiptPaymentQuery = new LambdaQueryWrapper<>();
            receiptPaymentQuery
                    .ge(ReceiptPayment::getCreateTime, startTime)
                    .lt(ReceiptPayment::getCreateTime, endTime);
            List<ReceiptPayment> receiptPayments = receiptPaymentMapper.selectList(receiptPaymentQuery);
                    .le(ReceiptPayment::getCreateTime, endTime);
            // 查询开票金额
            LambdaQueryWrapper<InvoiceLedger> invoiceLedgerQuery = new LambdaQueryWrapper<>();
            invoiceLedgerQuery
                    .ge(InvoiceLedger::getCreateTime, startTime)
                    .lt(InvoiceLedger::getCreateTime, endTime);
            List<InvoiceLedger> invoiceLedgers = invoiceLedgerMapper.selectList(invoiceLedgerQuery);
            List<ReceiptPayment> receiptPayments =
                    receiptPaymentMapper.selectList(receiptPaymentQuery);
            // 计算回款总额
            BigDecimal receiptAmount = receiptPayments.stream()
                    .map(ReceiptPayment::getReceiptPaymentAmount)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            // 计算开票总额
            //  开票金额
            LambdaQueryWrapper<InvoiceLedger> invoiceLedgerQuery = new LambdaQueryWrapper<>();
            invoiceLedgerQuery
                    .ge(InvoiceLedger::getCreateTime, startTime)
                    .le(InvoiceLedger::getCreateTime, endTime);
            List<InvoiceLedger> invoiceLedgers =
                    invoiceLedgerMapper.selectList(invoiceLedgerQuery);
            BigDecimal invoiceAmount = invoiceLedgers.stream()
                    .map(InvoiceLedger::getInvoiceTotal)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            // 构造返回的 DTO
            MonthlyAmountDto dto = new MonthlyAmountDto();
            dto.setMonth(startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " ~ " +
                    endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            dto.setMonth(yearMonth.format(DateTimeFormatter.ofPattern("yyyy-MM")));
            dto.setReceiptAmount(receiptAmount);
            dto.setInvoiceAmount(invoiceAmount);
            result.add(dto);
        }
        // 反转列表,使时间顺序从早到晚
        Collections.reverse(result);
        return result;
    }
    @Override
    public IPage<SalesLedger> selectSalesLedgerListPage(Page page, SalesLedgerDto salesLedgerDto) {
    public IPage<SalesLedgerDto> selectSalesLedgerListPage(Page page, SalesLedgerDto salesLedgerDto) {
        return salesLedgerMapper.selectSalesLedgerListPage(page, salesLedgerDto);
    }
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importData(MultipartFile file) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        try {
            InputStream inputStream = file.getInputStream();
            ExcelUtil<SalesLedgerImportDto> salesLedgerImportDtoExcelUtil = new ExcelUtil<>(SalesLedgerImportDto.class);
            Map<String, List<SalesLedgerImportDto>> stringListMap = salesLedgerImportDtoExcelUtil.importExcelMultiSheet(Arrays.asList("销售台账数据", "销售产品数据"), inputStream, 0);
            if (CollectionUtils.isEmpty(stringListMap)) return AjaxResult.error("销售表格为空!");
            // 业务层合并
            List<SalesLedgerImportDto> salesLedgerImportDtoList = stringListMap.get("销售台账数据");
            if (CollectionUtils.isEmpty(salesLedgerImportDtoList)) return AjaxResult.error("销售台账数据为空!");
            List<SalesLedgerImportDto> salesLedgerProductImportDtoList = stringListMap.get("销售产品数据");
            if (CollectionUtils.isEmpty(salesLedgerProductImportDtoList)) return AjaxResult.error("销售产品数据为空!");
            // 客户数据
            List<Customer> customers = customerMapper.selectList(new LambdaQueryWrapper<Customer>().in(Customer::getCustomerName,
                    salesLedgerImportDtoList.stream().map(SalesLedgerImportDto::getCustomerName).collect(Collectors.toList())));
//            // 规格型号数据
//            List<ProductModel> productModels = productModelMapper.selectList(new LambdaQueryWrapper<ProductModel>().in(ProductModel::getModel,
//                    salesLedgerProductImportDtoList.stream().map(SalesLedgerImportDto::getSpecificationModel).collect(Collectors.toList())));
//            // 产品大类数据
//            List<Product> productList = productMapper.selectList(new LambdaQueryWrapper<Product>().in(Product::getProductName,
//                    salesLedgerProductImportDtoList.stream().map(SalesLedgerImportDto::getProductCategory).collect(Collectors.toList())));
            List<Map<String, Object>> list = productModelMapper.getProductAndModelList();
            // 录入人数据
            List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().in(SysUser::getNickName,
                    salesLedgerImportDtoList.stream().map(SalesLedgerImportDto::getEntryPerson).collect(Collectors.toList())));
            for (SalesLedgerImportDto salesLedgerImportDto : salesLedgerImportDtoList) {
                SalesLedger salesLedger1 = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>()
                        .eq(SalesLedger::getSalesContractNo, salesLedgerImportDto.getSalesContractNo())
                        .last("LIMIT 1"));
                if (salesLedger1 != null) {
                    continue;
                }
                SalesLedger salesLedger = new SalesLedger();
                BeanUtils.copyProperties(salesLedgerImportDto, salesLedger);
                salesLedger.setExecutionDate(DateUtils.toLocalDate(salesLedgerImportDto.getExecutionDate()));
                // 通过客户名称查询客户ID,客户合同号
                salesLedger.setCustomerId(customers.stream()
                        .filter(customer -> customer.getCustomerName().equals(salesLedger.getCustomerName()))
                        .findFirst()
                        .map(Customer::getId)
                        .orElse(null));
                salesLedger.setCustomerContractNo(customers.stream()
                        .filter(customer -> customer.getCustomerName().equals(salesLedger.getCustomerName()))
                        .findFirst()
                        .map(Customer::getTaxpayerIdentificationNumber)
                        .orElse(null));
                Long aLong = sysUsers.stream()
                        .filter(sysUser -> sysUser.getNickName().equals(salesLedger.getEntryPerson()))
                        .findFirst()
                        .map(SysUser::getUserId)
                        .orElse(null);
                if (aLong == null)
                    throw new RuntimeException("录入人:" + salesLedger.getEntryPerson() + ",无对应用户!");
                salesLedger.setEntryPerson(aLong.toString());
                // 销售产品数据绑定,通过销售单号获取对应销售产品数据
                List<SalesLedgerProductImportDto> salesLedgerProductImportDtos = salesLedgerProductImportDtoList.stream()
                        .filter(salesLedgerProductImportDto -> salesLedgerProductImportDto.getSalesContractNo().equals(salesLedger.getSalesContractNo()))
                        .collect(Collectors.toList());
                if (CollectionUtils.isEmpty(salesLedgerProductImportDtos))
                    throw new RuntimeException("销售单号:" + salesLedgerImportDto.getSalesContractNo() + ",无对应产品数据!");
                salesLedger.setContractAmount(salesLedgerProductImportDtos.stream()
                        .map(SalesLedgerProductImportDto::getTaxInclusiveTotalPrice)
                        .reduce(BigDecimal.ZERO, BigDecimal::add));
                salesLedgerMapper.insert(salesLedger);
                for (SalesLedgerProductImportDto salesLedgerProductImportDto : salesLedgerProductImportDtos) {
                    SalesLedgerProduct salesLedgerProduct = new SalesLedgerProduct();
                    BeanUtils.copyProperties(salesLedgerProductImportDto, salesLedgerProduct);
                    salesLedgerProduct.setSalesLedgerId(salesLedger.getId());
                    salesLedgerProduct.setType(1);
                    // 计算不含税总价
                    salesLedgerProduct.setTaxExclusiveTotalPrice(salesLedgerProduct.getTaxInclusiveTotalPrice().divide(new BigDecimal(1).add(salesLedgerProduct.getTaxRate().divide(new BigDecimal(100))), 2, RoundingMode.HALF_UP));
                    salesLedgerProduct.setNoInvoiceNum(salesLedgerProduct.getQuantity());
                    salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxExclusiveTotalPrice());
                    list.stream()
                            .filter(map -> map.get("productName").equals(salesLedgerProduct.getProductCategory()) && map.get("model").equals(salesLedgerProduct.getSpecificationModel()))
                            .findFirst()
                            .ifPresent(map -> {
                                salesLedgerProduct.setProductModelId(Long.parseLong(map.get("modelId").toString()));
                                salesLedgerProduct.setProductId(Long.parseLong(map.get("id").toString()));
                            });
//                    salesLedgerProduct.setProductId(productList.stream()
//                            .filter(product -> product.getProductName().equals(salesLedgerProduct.getProductCategory()))
//                            .findFirst()
//                            .map(Product::getId)
//                            .orElse(null));
//                    salesLedgerProduct.setProductModelId(productModels.stream()
//                            .filter(productModel -> productModel.getModel().equals(salesLedgerProduct.getSpecificationModel()))
//                            .findFirst()
//                            .map(ProductModel::getId)
//                            .orElse(null));
                    salesLedgerProduct.setRegister(loginUser.getNickName());
                    salesLedgerProduct.setRegisterDate(LocalDateTime.now());
                    salesLedgerProduct.setApproveStatus(0);
                    salesLedgerProduct.setPendingInvoiceTotal(salesLedgerProductImportDto.getTaxInclusiveTotalPrice());
                    salesLedgerProductMapper.insert(salesLedgerProduct);
                    // 添加生产数据
                    salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
                }
            }
            return AjaxResult.success("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success("导入失败");
    }
    @Override
    public List<LossProductModelDto> getSalesLedgerWithProductsLoss(Long salesLedgerId) {
        List<LossProductModelDto> lossProductModelDtos = salesLedgerProductMapper.selectProductBomStructure(salesLedgerId);
        return lossProductModelDtos;
    }
    // 内部类用于存储聚合结果
    private static class GroupedCustomer {
@@ -426,20 +836,23 @@
            wrapperTree.in(ReceiptPayment::getInvoiceLedgerId, invoiceLedgerIds);
            receiptPaymentMapper.delete(wrapperTree);
        }
        // 删除发货台账记录
        List<ShippingInfo> shippingInfos = shippingInfoMapper.selectList(new LambdaQueryWrapper<ShippingInfo>()
                .in(ShippingInfo::getSalesLedgerId, idList));
        if (CollectionUtils.isNotEmpty(shippingInfos)) {
            shippingInfoServiceImpl.delete(shippingInfos.stream().map(ShippingInfo::getId).collect(Collectors.toList()));
        }
        // 删除附件表
        commonFileService.deleteByBusinessIds(idList, FileNameType.SALE.getValue());
        // 删除生产管控数据
        // 删除生产订单数据
        LambdaQueryWrapper<SalesLedgerScheduling> in = new LambdaQueryWrapper<SalesLedgerScheduling>()
                .in(SalesLedgerScheduling::getSalesLedgerId, idList);
        salesLedgerSchedulingMapper.delete(in);
        // 删除生产派工数据
        LambdaQueryWrapper<SalesLedgerWork> workOrderWrapper = new LambdaQueryWrapper<>();
        workOrderWrapper.in(SalesLedgerWork::getSalesLedgerId, idList);
        salesLedgerWorkMapper.delete(workOrderWrapper);
        // 删除生产核算数据
        LambdaQueryWrapper<SalesLedgerProductionAccounting> reportWrapper = new LambdaQueryWrapper<>();
        reportWrapper.in(SalesLedgerProductionAccounting::getSalesLedgerId, idList);
        salesLedgerProductionAccountingMapper.delete(reportWrapper);
        //查询生产报工id
        ArrayList<Long> mainIdList = productionProductMainService.listMain(idList);
        if (CollectionUtils.isNotEmpty(mainIdList)) {
            mainIdList.stream().forEach(mainId -> {
                productionProductMainService.removeProductMain(mainId);
            });
        }
        // 2. 再删除主表数据
        return salesLedgerMapper.deleteBatchIds(idList);
    }
@@ -458,45 +871,19 @@
            SalesLedger salesLedger = convertToEntity(salesLedgerDto);
            salesLedger.setCustomerName(customer.getCustomerName());
            salesLedger.setTenantId(customer.getTenantId());
            AccountIncome accountIncome = new AccountIncome();
            accountIncome.setIncomeDate(salesLedger.getEntryDate());
            accountIncome.setIncomeType("0");
            accountIncome.setCustomerName(customer.getCustomerName());
            accountIncome.setIncomeMoney(salesLedger.getContractAmount());
            accountIncome.setIncomeMethod("0");
            accountIncome.setInputTime(new Date());
            accountIncome.setInputUser(salesLedger.getEntryPerson());
            // 3. 新增或更新主表
            if (salesLedger.getId() == null) {
                String contractNo = generateSalesContractNo();
                salesLedger.setSalesContractNo(contractNo);
                salesLedgerMapper.insert(salesLedger);
                accountIncome.setIncomeDescribed("销售合同:" + salesLedger.getSalesContractNo());
                accountIncome.setInvoiceNumber(salesLedger.getSalesContractNo());
                accountIncomeService.save(accountIncome);
            } else {
                salesLedgerMapper.updateById(salesLedger);
                SalesLedger salesLedgerDB = salesLedgerMapper.selectById(salesLedger.getId());
                List<AccountIncome> accountIncomeDBs = accountIncomeService.getByInvoiceNumberList(salesLedger.getSalesContractNo());
                if (!org.springframework.util.CollectionUtils.isEmpty(accountIncomeDBs)) {
                    accountIncomeDBs.forEach(accountIncomeDB -> {
                        accountIncomeDB.setCustomerName(salesLedgerDB.getCustomerName());
                        accountIncomeDB.setIncomeMoney(salesLedgerDB.getContractAmount());
                        accountIncomeDB.setIncomeDescribed("销售合同:" + salesLedgerDB.getSalesContractNo());
                        accountIncomeDB.setInvoiceNumber(salesLedgerDB.getSalesContractNo());
                        accountIncomeDB.setInputTime(new Date());
                        accountIncomeDB.setInputUser(salesLedgerDB.getEntryPerson());
                        accountIncomeService.updateById(accountIncomeDB);
                    });
                }
            }
            // 4. 处理子表数据
            List<SalesLedgerProduct> productList = salesLedgerDto.getProductData();
            if (productList != null && !productList.isEmpty()) {
                handleSalesLedgerProducts(salesLedger.getId(), productList, salesLedgerDto.getType());
                handleSalesLedgerProducts(salesLedger.getId(), productList, salesLedgerDto.getType(), Boolean.TRUE.equals(salesLedgerDto.getProduce()));
                updateMainContractAmount(
                        salesLedger.getId(),
                        productList,
@@ -594,7 +981,7 @@
    }
    private void handleSalesLedgerProducts(Long salesLedgerId, List<SalesLedgerProduct> products, Integer type) {
    private void handleSalesLedgerProducts(Long salesLedgerId, List<SalesLedgerProduct> products, Integer type, boolean isProduce) {
        // 按ID分组,区分新增和更新的记录
        Map<Boolean, List<SalesLedgerProduct>> partitionedProducts = products.stream()
                .peek(p -> p.setSalesLedgerId(salesLedgerId))
@@ -603,9 +990,26 @@
        List<SalesLedgerProduct> updateList = partitionedProducts.get(true);
        List<SalesLedgerProduct> insertList = partitionedProducts.get(false);
//        List<StockInventoryDto> stockInventoryDtos = stockInventoryMapper.selectProductList();
        // 执行更新操作
        if (!updateList.isEmpty()) {
            for (SalesLedgerProduct product : updateList) {
//                // 查询库存数量
//                SalesLedgerProduct oldProduct = salesLedgerProductMapper.selectById(product.getId());
//                BigDecimal quantityChange = product.getQuantity().subtract(oldProduct.getQuantity());
//
//                // 如果数量增加了,检查库存
//                if (quantityChange.compareTo(BigDecimal.ZERO) > 0) {
//                    for (StockInventoryDto stockInventoryDto : stockInventoryDtos) {
//                        if (stockInventoryDto.getProductId().equals(product.getId())) {
//                            if (quantityChange.compareTo(stockInventoryDto.getQualitity()) > 0) {
//                                throw new RuntimeException("库存不足");
//                            }
//                            break;
//                        }
//                    }
//                }
                product.setType(type);
                salesLedgerProductMapper.updateById(product);
            }
@@ -613,10 +1017,23 @@
        // 执行插入操作
        if (!insertList.isEmpty()) {
            for (SalesLedgerProduct salesLedgerProduct : insertList) {
//                for (StockInventoryDto stockInventoryDto : stockInventoryDtos) {
//                    if (stockInventoryDto.getProductId().equals(salesLedgerProduct.getId())) {
//                        if (salesLedgerProduct.getQuantity().compareTo(stockInventoryDto.getQualitity()) > 0) {
//                            throw new RuntimeException("库存不足");
//                        }
//                    }
//                }
                salesLedgerProduct.setType(type);
                salesLedgerProduct.setNoInvoiceNum(salesLedgerProduct.getQuantity());
                salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxInclusiveTotalPrice());
                salesLedgerProduct.setPendingInvoiceTotal(salesLedgerProduct.getTaxInclusiveTotalPrice());
                salesLedgerProductMapper.insert(salesLedgerProduct);
            }
        }
        if (isProduce) {
            for (SalesLedgerProduct salesLedgerProduct : products) {
                // 添加生产数据
                salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
            }
@@ -626,6 +1043,7 @@
    private SalesLedger convertToEntity(SalesLedgerDto dto) {
        SalesLedger entity = new SalesLedger();
        BeanUtils.copyProperties(dto, entity);
        entity.setProduce(dto.getProduce());
        return entity;
    }