huminmin
2026-04-23 7403a0bb5b6c69a830c326aa7bc4fa720d23477a
src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -1,5 +1,10 @@
package com.ruoyi.sales.service.impl;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
@@ -8,6 +13,9 @@
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.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.ruoyi.account.pojo.AccountIncome;
import com.ruoyi.account.service.AccountIncomeService;
import com.ruoyi.basic.mapper.CustomerMapper;
import com.ruoyi.basic.mapper.ProductMapper;
@@ -17,9 +25,11 @@
import com.ruoyi.common.enums.FileNameType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HackLoopTableRenderPolicy;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.device.execl.DeviceMaintenanceExeclDto;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.other.mapper.TempFileMapper;
@@ -34,6 +44,7 @@
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;
@@ -48,11 +59,13 @@
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -60,11 +73,14 @@
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * 销售台账Service业务层处理
@@ -129,6 +145,8 @@
    private final QualityInspectMapper qualityInspectMapper;
    private final StockInventoryMapper stockInventoryMapper;
    private ISalesLedgerProductService salesLedgerProductService;
    @Autowired
@@ -206,6 +224,222 @@
            resultDto.setSalesLedgerFiles(salesLedgerFiles);
        }
        return resultDto;
    }
    @Override
    public void exportShippingNote(HttpServletResponse response, List<Long> ids) {
        log.info("开始导出送货单,台账ID列表: {}", ids);
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            throw new BaseException("请选择要导出的销售台账");
        }
        List<SalesLedger> salesLedgerList = salesLedgerMapper.selectList(
                Wrappers.<SalesLedger>lambdaQuery()
                        .in(SalesLedger::getId, ids)
        );
        if (salesLedgerList.isEmpty()) {
            throw new BaseException("未找到对应销售台账数据");
        }
        // 根据销售台账数量决定导出方式
        if (salesLedgerList.size() == 1) {
            // 单个销售台账,直接导出xlsx文件
            exportSingleShippingNote(response, salesLedgerList.get(0));
        } else {
            // 多个销售台账,生成压缩包
            exportBatchShippingNote(response, salesLedgerList);
        }
    }
    /**
     * 导出单个送货单
     */
    private void exportSingleShippingNote(HttpServletResponse response, SalesLedger ledger) {
        try {
            // 设置响应头
            String fileName = String.format("送货单_%s.xlsx",
                    Optional.ofNullable(ledger.getSalesContractNo()).orElse(String.valueOf(ledger.getId())));
            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");
            // 查询明细
            SalesLedgerProduct cond = new SalesLedgerProduct();
            cond.setSalesLedgerId(ledger.getId());
            List<SalesLedgerProduct> productList = salesLedgerProductServiceImpl.selectSalesLedgerProductList(cond);
            // 自动序号+物料编码赋值
            for (int i = 0; i < productList.size(); i++) {
                SalesLedgerProduct product = productList.get(i);
                if (product != null) {
                    product.setSerialNumber(i + 1);
                    product.setOrderNo(ledger.getSalesContractNo());
                    Long productModelId = product.getProductModelId();
                    if (productModelId != null) {
                        ProductModel productModel = productModelMapper.selectById(productModelId);
                        if (productModel != null) {
                            product.setMaterialCode(productModel.getMaterialCode());
                        }
                    }
                }
            }
            // 关联客户信息
            Customer customer = customerMapper.selectById(ledger.getCustomerId());
            // 计算总合计
            BigDecimal totalQuantity = BigDecimal.ZERO;
            for (SalesLedgerProduct product : productList) {
                totalQuantity = totalQuantity.add(product.getQuantity() == null ? BigDecimal.ZERO : product.getQuantity());
            }
            // 组装顶部静态数据
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("customerName", ledger.getCustomerName());
            dataMap.put("companyAddress", customer.getCompanyAddress());
            dataMap.put("contactPerson", customer.getContactPerson());
            dataMap.put("contactPhone", customer.getContactPhone());
            dataMap.put("companyPhone", customer.getCompanyPhone());
            dataMap.put("salesContractNo", ledger.getSalesContractNo());
            dataMap.put("deliveryDate", formatDate(LocalDate.now()));
            dataMap.put("totalQuantity", totalQuantity);
            // 使用模板生成Excel
            InputStream templateIs = this.getClass().getResourceAsStream("/static/shipping-note.xlsx");
            if (templateIs == null) {
                throw new BaseException("模板文件不存在");
            }
            ExcelWriter writer = EasyExcel.write(response.getOutputStream()).withTemplate(templateIs).build();
            WriteSheet sheet = EasyExcel.writerSheet().build();
            // 先填充数据(包括合计)
            writer.fill(dataMap, sheet);
            // 再填充产品列表
            if (!productList.isEmpty()) {
                FillConfig fillConfig = FillConfig.builder()
                        .forceNewRow(Boolean.TRUE)
                        .build();
                writer.fill(productList, fillConfig, sheet);
            }
            writer.finish();
            templateIs.close();
        } catch (BaseException e) {
            log.error("导出失败:{}", e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            log.error("导出异常", e);
            throw new BaseException("导出失败:" + e.getMessage());
        }
    }
    /**
     * 批量导出送货单为压缩包
     */
    private void exportBatchShippingNote(HttpServletResponse response, List<SalesLedger> salesLedgerList) {
        // 设置响应头
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=送货单.zip");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            for (SalesLedger ledger : salesLedgerList) {
                log.info("处理合同号: {}", ledger.getSalesContractNo());
                // 查询明细
                SalesLedgerProduct cond = new SalesLedgerProduct();
                cond.setSalesLedgerId(ledger.getId());
                List<SalesLedgerProduct> productList = salesLedgerProductServiceImpl.selectSalesLedgerProductList(cond);
                // 自动序号+物料编码赋值
                for (int i = 0; i < productList.size(); i++) {
                    SalesLedgerProduct product = productList.get(i);
                    if (product != null) {
                        product.setSerialNumber(i + 1);
                        product.setOrderNo(ledger.getSalesContractNo());
                        Long productModelId = product.getProductModelId();
                        if (productModelId != null) {
                            ProductModel productModel = productModelMapper.selectById(productModelId);
                            if (productModel != null) {
                                product.setMaterialCode(productModel.getMaterialCode());
                            }
                        }
                    }
                }
                // 关联客户信息
                Customer customer = customerMapper.selectById(ledger.getCustomerId());
                // 计算总合计
                BigDecimal totalQuantity = BigDecimal.ZERO;
                for (SalesLedgerProduct product : productList) {
                    totalQuantity = totalQuantity.add(product.getQuantity() == null ? BigDecimal.ZERO : product.getQuantity());
                }
                // 组装顶部静态数据
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("customerName", ledger.getCustomerName());
                dataMap.put("companyAddress", customer.getCompanyAddress());
                dataMap.put("contactPerson", customer.getContactPerson());
                dataMap.put("contactPhone", customer.getContactPhone());
                dataMap.put("companyPhone", customer.getCompanyPhone());
                dataMap.put("salesContractNo", ledger.getSalesContractNo());
                dataMap.put("deliveryDate", formatDate(LocalDate.now()));
                dataMap.put("totalQuantity", totalQuantity);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                InputStream templateIs = this.getClass().getResourceAsStream("/static/shipping-note.xlsx");
                ExcelWriter writer = EasyExcel.write(bos).withTemplate(templateIs).build();
                WriteSheet sheet = EasyExcel.writerSheet().build();
                // 先填充数据(包括合计)
                writer.fill(dataMap, sheet);
                // 再填充产品列表
                if (!productList.isEmpty()) {
                    FillConfig fillConfig = FillConfig.builder()
                            .forceNewRow(Boolean.TRUE)
                            .build();
                    writer.fill(productList, fillConfig, sheet);
                }
                writer.finish();
                templateIs.close();
                // 打包ZIP
                String excelName = String.format("送货单_%s.xlsx",
                        Optional.ofNullable(ledger.getSalesContractNo()).orElse(String.valueOf(ledger.getId())));
                ZipEntry entry = new ZipEntry(excelName);
                zos.putNextEntry(entry);
                zos.write(bos.toByteArray());
                zos.closeEntry();
                bos.close();
            }
            zos.finish();
            log.info("批量导出完成,共{}份送货单", salesLedgerList.size());
        } catch (BaseException e) {
            log.error("导出失败:{}", e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            log.error("导出异常", e);
            throw new BaseException("导出失败:" + e.getMessage());
        }
    }
    public static String formatDate(LocalDate date) {
        if (date == null) {
            return null;
        }
        return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }
    @Override
@@ -868,4 +1102,4 @@
            throw new RuntimeException("动态更新主表金额失败", e);
        }
    }
}
}