refactor(ecom-dmb): 导出服务重构,ExportServiceImpl拆分为独立服务类,抽取ExportFilenameUtils统一文件名构建

This commit is contained in:
小蟑螂
2026-04-28 14:02:29 +08:00
parent 455f10beed
commit 57fe400dee
21 changed files with 979 additions and 831 deletions
@@ -35,6 +35,7 @@ public class WebConfig implements WebMvcConfigurer {
.allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Content-Disposition")
.allowCredentials(true)
.maxAge(3600);
}
@@ -10,11 +10,10 @@ import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.PlatformExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ExportService;
import jakarta.servlet.http.HttpServletResponse;
import java.time.format.DateTimeFormatter;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.util.ExportFilenameUtils;
/**
* 概览导出控制器
@@ -24,8 +23,6 @@ import java.time.format.DateTimeFormatter;
@RequestMapping("/ec")
public class ExportController {
private static final DateTimeFormatter FILE_NAME_FMT = DateTimeFormatter.ofPattern("yyyyMMdd");
private final ExportService exportService;
public ExportController(ExportService exportService) {
@@ -37,42 +34,16 @@ public class ExportController {
@RequirePermission(value = "data:export", description = "导出公司概览", allowSuper = true)
public void exportCompanyOverview(@Valid @RequestBody CompanyExportDTO dto, HttpServletResponse response) {
byte[] data = exportService.exportCompanyOverview(dto);
String dateRange = dto.getDateRange().get(0).format(FILE_NAME_FMT) + "-" +
dto.getDateRange().get(dto.getDateRange().size() - 1).format(FILE_NAME_FMT);
String filename = "公司概览_" + dateRange + ".xlsx";
String filename = ExportFilenameUtils.buildXlsxName("公司概览", dto.getDateRange());
writeExcel(response, filename, data);
}
@Operation(summary = "导出店铺概览Excel", description = "导出单店铺概览数据为Excel文件")
@PostMapping("/shop/export-overview")
@RequirePermission(value = "data:export", description = "导出店铺概览", allowSuper = true)
public void exportShopOverview(@Valid @RequestBody ShopExportDTO dto, HttpServletResponse response) {
byte[] data = exportService.exportShopOverview(dto);
String dateRange = dto.getDateRange().get(0).format(FILE_NAME_FMT) + "-" +
dto.getDateRange().get(dto.getDateRange().size() - 1).format(FILE_NAME_FMT);
String filename = "店铺概览_" + dateRange + ".xlsx";
writeExcel(response, filename, data);
}
@Operation(summary = "导出门店品类对比Excel", description = "导出门店品类多维度数据对比为Excel文件")
@PostMapping("/shop/export-category")
@RequirePermission(value = "data:export", description = "导出门店品类对比", allowSuper = true)
public void exportShopCategoryOverview(
@RequestBody CategoryExportDTO dto,
HttpServletResponse response) {
byte[] data = exportService.exportCategoryOverview(dto);
String filename = "门店品类对比_" + System.currentTimeMillis() + ".xlsx";
writeExcel(response, filename, data);
}
@Operation(summary = "导出品类概览Excel", description = "导出多品类对比数据为Excel文件,支持指定品类或导出全部")
@Operation(summary = "导出品类概览Excel", description = "导出多品类汇总数据为Excel文件,支持指定品类或导出全部")
@PostMapping("/category-overview/export")
@RequirePermission(value = "data:export", description = "导出品类概览", allowSuper = true)
public void exportCategoryOverview(@Valid @RequestBody CategoryExportDTO dto, HttpServletResponse response) {
byte[] data = exportService.exportCategoryOverview(dto);
String dateRange = dto.getDateRange().get(0).format(FILE_NAME_FMT) + "-" +
dto.getDateRange().get(dto.getDateRange().size() - 1).format(FILE_NAME_FMT);
String filename = "品类概览_" + dateRange + ".xlsx";
String filename = ExportFilenameUtils.buildXlsxName("品类概览", dto.getDateRange());
writeExcel(response, filename, data);
}
@@ -81,9 +52,7 @@ public class ExportController {
@RequirePermission(value = "data:export", description = "导出平台维度汇总", allowSuper = true)
public void exportPlatformOverview(@Valid @RequestBody PlatformExportDTO dto, HttpServletResponse response) {
byte[] data = exportService.exportPlatformOverview(dto);
String dateRange = dto.getDateRange().get(0).format(FILE_NAME_FMT) + "-" +
dto.getDateRange().get(dto.getDateRange().size() - 1).format(FILE_NAME_FMT);
String filename = "平台维度汇总_" + dateRange + ".xlsx";
String filename = ExportFilenameUtils.buildXlsxName("平台维度汇总", dto.getDateRange());
writeExcel(response, filename, data);
}
@@ -68,15 +68,15 @@ public class CompanyOverviewVO {
private List<ShopEfficiencyQuadrant> shopEfficiencyQuadrants;
/**
* 多店铺数据横向对比(包含合计行和店铺列表)
* 多店铺数据横向汇总(包含合计行和店铺列表)
*/
@Schema(description = "多店铺数据横向对比")
@Schema(description = "多店铺数据横向汇总")
private ShopOverview shopComparisons;
/**
* 多品类数据横向对比(包含合计行和品类列表)
* 多品类数据横向汇总(包含合计行和品类列表)
*/
@Schema(description = "多品类数据横向对比")
@Schema(description = "多品类数据横向汇总")
private CategoryOverview categoryComparisons;
/**
@@ -101,7 +101,7 @@ public class CompanyOverviewVO {
@Schema(description = "合计行")
private ShopComparison total;
@Schema(description = "各店铺对比列表")
@Schema(description = "各店铺汇总列表")
private List<ShopComparison> shops;
}
@@ -114,7 +114,7 @@ public class CompanyOverviewVO {
@Schema(description = "合计行")
private CategoryComparison total;
@Schema(description = "各品类对比列表")
@Schema(description = "各品类汇总列表")
private List<CategoryComparison> categories;
}
@@ -202,10 +202,10 @@ public class CompanyOverviewVO {
}
/**
* 店铺对比数据
* 店铺汇总数据
*/
@Data
@Schema(description = "店铺对比数据")
@Schema(description = "店铺汇总数据")
public static class ShopComparison {
@Schema(description = "店铺ID", example = "1")
private Long shopId;
@@ -272,10 +272,10 @@ public class CompanyOverviewVO {
}
/**
* 品类对比数据
* 品类汇总数据
*/
@Data
@Schema(description = "品类对比数据")
@Schema(description = "品类汇总数据")
public static class CategoryComparison {
@Schema(description = "品类ID(未分配为null)", example = "1")
private Long categoryId;
@@ -136,15 +136,15 @@ public class ShopOverviewStatisticsVO {
private TrendData orderCountTrend;
/**
* 多商品数据横向对比(含合计行)
* 多商品数据横向汇总(含合计行)
*/
@Schema(description = "多商品数据横向对比")
@Schema(description = "多商品数据横向汇总")
private ProductOverview productOverview;
/**
* 品类多维度数据对比(含合计行)
* 品类多维度数据汇总(含合计行)
*/
@Schema(description = "品类多维度数据对比")
@Schema(description = "品类多维度数据汇总")
private CategoryOverview categoryOverview;
/**
@@ -155,7 +155,7 @@ public class ShopOverviewStatisticsVO {
public static class ProductOverview {
@Schema(description = "合计行")
private ProductComparison total;
@Schema(description = "各商品对比列表")
@Schema(description = "各商品汇总列表")
private List<ProductComparison> products;
}
@@ -167,15 +167,15 @@ public class ShopOverviewStatisticsVO {
public static class CategoryOverview {
@Schema(description = "合计行")
private CategoryComparison total;
@Schema(description = "各品类对比列表")
@Schema(description = "各品类汇总列表")
private List<CategoryComparison> categories;
}
/**
* 商品对比数据
* 商品汇总数据
*/
@Data
@Schema(description = "商品对比数据")
@Schema(description = "商品汇总数据")
public static class ProductComparison {
@Schema(description = "商品ID", example = "1")
private Long productId;
@@ -230,10 +230,10 @@ public class ShopOverviewStatisticsVO {
}
/**
* 品类对比数据
* 品类汇总数据
*/
@Data
@Schema(description = "品类对比数据")
@Schema(description = "品类汇总数据")
public static class CategoryComparison {
@Schema(description = "品类ID", example = "1")
private Long categoryId;
@@ -0,0 +1,11 @@
package top.xyquan.ecomdmbbackend.modules.ecom.overview.service;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO;
/**
* 按品类维度导出 Excel(店铺「门店品类汇总」与全店「品类概览」共用实现)
*/
public interface CategoryExportExcelService {
byte[] exportCategoryOverview(CategoryExportDTO dto);
}
@@ -3,8 +3,6 @@ package top.xyquan.ecomdmbbackend.modules.ecom.overview.service;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.PlatformExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopExportDTO;
/**
* 概览导出服务接口
*/
@@ -18,14 +16,6 @@ public interface ExportService {
*/
byte[] exportCompanyOverview(CompanyExportDTO dto);
/**
* 导出店铺概览Excel
*
* @param dto 导出参数
* @return Excel文件字节数组
*/
byte[] exportShopOverview(ShopExportDTO dto);
/**
* 导出品类概览Excel
*
@@ -0,0 +1,356 @@
package top.xyquan.ecomdmbbackend.modules.ecom.overview.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CategoryExportExcelService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class CategoryExportExcelServiceImpl implements CategoryExportExcelService {
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final CurrentUserContext currentUserContext;
private final OrderMapper orderMapper;
private final PromotionFeeMapper promotionFeeMapper;
private final BrushOrderMapper brushOrderMapper;
private final ProductService productService;
private final CategoryService categoryService;
private final ExportStatusRangeHelper exportStatusRangeHelper;
public CategoryExportExcelServiceImpl(
CurrentUserContext currentUserContext,
OrderMapper orderMapper,
PromotionFeeMapper promotionFeeMapper,
BrushOrderMapper brushOrderMapper,
ProductService productService,
CategoryService categoryService,
ExportStatusRangeHelper exportStatusRangeHelper) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
this.brushOrderMapper = brushOrderMapper;
this.productService = productService;
this.categoryService = categoryService;
this.exportStatusRangeHelper = exportStatusRangeHelper;
}
@Override
public byte[] exportCategoryOverview(CategoryExportDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange());
LocalDate startDate = dateRange[0];
LocalDate endDate = dateRange[1];
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
List<Long> autoStatusIds = exportStatusRangeHelper.getAutoStatusIds(companyId);
List<Long> refundStatusIds = exportStatusRangeHelper.getRefundStatusIds(companyId);
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.ge(OrderPO::getOrderTime, startDateTime)
.le(OrderPO::getOrderTime, endDateTime);
if (!autoStatusIds.isEmpty()) {
orderWrapper.in(OrderPO::getStatusId, autoStatusIds);
} else {
orderWrapper.isNull(OrderPO::getId);
}
List<OrderPO> orders = orderMapper.selectList(orderWrapper);
LambdaQueryWrapper<PromotionFeePO> promoWrapper = new LambdaQueryWrapper<>();
promoWrapper.eq(PromotionFeePO::getCompanyId, companyId)
.ge(PromotionFeePO::getFeeDate, startDate)
.le(PromotionFeePO::getFeeDate, endDate);
List<PromotionFeePO> promotionFees = promotionFeeMapper.selectList(promoWrapper);
LambdaQueryWrapper<BrushOrderPO> brushWrapper = new LambdaQueryWrapper<>();
brushWrapper.eq(BrushOrderPO::getCompanyId, companyId)
.ge(BrushOrderPO::getBrushTime, startDate.atStartOfDay())
.le(BrushOrderPO::getBrushTime, endDate.atTime(23, 59, 59));
List<BrushOrderPO> brushOrders = brushOrderMapper.selectList(brushWrapper);
List<Long> productIds = orders.stream()
.map(OrderPO::getProductId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
Map<Long, Long> productCategoryMap = new HashMap<>();
if (!productIds.isEmpty()) {
LambdaQueryWrapper<ProductPO> productWrapper = new LambdaQueryWrapper<>();
productWrapper.in(ProductPO::getId, productIds).select(ProductPO::getId, ProductPO::getCategoryId);
List<ProductPO> products = productService.list(productWrapper);
for (ProductPO product : products) {
productCategoryMap.put(product.getId(), product.getCategoryId());
}
}
Map<Long, List<OrderPO>> ordersByCategory = orders.stream()
.collect(Collectors.groupingBy(order -> {
Long categoryId = productCategoryMap.get(order.getProductId());
return categoryId != null ? categoryId : -1L;
}));
Map<Long, BigDecimal> shopTotalPromoFeeMap = promotionFees.stream()
.collect(Collectors.groupingBy(PromotionFeePO::getShopId,
Collectors.reducing(BigDecimal.ZERO,
f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO,
BigDecimal::add)));
Map<Long, BigDecimal> shopTotalBrushFeeMap = brushOrders.stream()
.collect(Collectors.groupingBy(BrushOrderPO::getShopId,
Collectors.reducing(BigDecimal.ZERO,
b -> b.getBrushAmount() != null ? b.getBrushAmount() : BigDecimal.ZERO,
BigDecimal::add)));
LambdaQueryWrapper<CategoryPO> categoryWrapper = new LambdaQueryWrapper<>();
categoryWrapper.eq(CategoryPO::getCompanyId, companyId);
List<CategoryPO> allCategories = categoryService.list(categoryWrapper);
Map<Long, String> categoryNameMap = allCategories.stream()
.collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName));
List<CompanyOverviewVO.CategoryComparison> categoryDataList = new ArrayList<>();
for (Map.Entry<Long, List<OrderPO>> entry : ordersByCategory.entrySet()) {
Long categoryId = entry.getKey();
List<OrderPO> categoryOrders = entry.getValue();
BigDecimal salesAmount = categoryOrders.stream()
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
int orderCount = categoryOrders.size();
BigDecimal refundAmount = categoryOrders.stream()
.filter(o -> !refundStatusIds.isEmpty() && refundStatusIds.contains(o.getStatusId()))
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal productCost = categoryOrders.stream()
.map(o -> {
BigDecimal c = o.getProductCost() != null ? o.getProductCost() : BigDecimal.ZERO;
int qty = o.getQuantity() != null ? o.getQuantity() : 1;
return c.multiply(new BigDecimal(qty));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal shippingCost = categoryOrders.stream()
.map(o -> {
BigDecimal c = o.getShippingCost() != null ? o.getShippingCost() : BigDecimal.ZERO;
int qty = o.getQuantity() != null ? o.getQuantity() : 1;
return c.multiply(new BigDecimal(qty));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal otherCost = categoryOrders.stream()
.map(o -> o.getOtherCost() != null ? o.getOtherCost() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Map<Long, BigDecimal> categorySalesByShop = categoryOrders.stream()
.collect(Collectors.groupingBy(OrderPO::getShopId,
Collectors.reducing(BigDecimal.ZERO,
o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO,
BigDecimal::add)));
BigDecimal categoryTotalSales = categorySalesByShop.values().stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalPromotionFee = BigDecimal.ZERO;
BigDecimal totalBrushFee = BigDecimal.ZERO;
if (categoryTotalSales.compareTo(BigDecimal.ZERO) > 0) {
for (Map.Entry<Long, BigDecimal> shopEntry : categorySalesByShop.entrySet()) {
Long shopId = shopEntry.getKey();
BigDecimal ratio = shopEntry.getValue().divide(categoryTotalSales, 6, RoundingMode.HALF_UP);
totalPromotionFee = totalPromotionFee.add(
shopTotalPromoFeeMap.getOrDefault(shopId, BigDecimal.ZERO).multiply(ratio));
totalBrushFee = totalBrushFee.add(
shopTotalBrushFeeMap.getOrDefault(shopId, BigDecimal.ZERO).multiply(ratio));
}
}
BigDecimal totalCost = productCost.add(shippingCost).add(otherCost);
BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount);
BigDecimal salesTaxAmount = salesAmount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP);
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount);
BigDecimal roi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0
? salesAmount.subtract(refundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal feeRatio = salesAmount.compareTo(BigDecimal.ZERO) > 0
? totalPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal avgOrderValue = orderCount > 0
? salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
String categoryName = categoryId == -1L
? "未分配品类"
: categoryNameMap.getOrDefault(categoryId, "Unknown");
CompanyOverviewVO.CategoryComparison data = new CompanyOverviewVO.CategoryComparison();
data.setCategoryId(categoryId == -1L ? null : categoryId);
data.setCategoryName(categoryName);
data.setSalesAmount(salesAmount);
data.setOrderCount(orderCount);
data.setAverageOrderValue(avgOrderValue);
data.setProductCost(productCost);
data.setShippingCost(shippingCost);
data.setOtherCost(otherCost);
data.setRefundAmount(refundAmount);
data.setTotalPromotionFee(totalPromotionFee);
data.setBrushFee(totalBrushFee);
data.setFeeRatio(feeRatio);
data.setTotalProfitBeforeTax(profitBeforeTax);
data.setSalesTaxAmount(salesTaxAmount);
data.setProfitAfterTax(profitAfterTax);
data.setRoi(roi);
categoryDataList.add(data);
}
if (dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty()) {
Set<Long> allowedIds = new HashSet<>(dto.getCategoryIds());
categoryDataList = categoryDataList.stream()
.filter(c -> c.getCategoryId() != null && allowedIds.contains(c.getCategoryId()))
.collect(Collectors.toList());
}
categoryDataList.sort(Comparator.comparing(CompanyOverviewVO.CategoryComparison::getSalesAmount).reversed());
String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT);
try (Workbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("品类明细");
createCategoryDetailSheet(sheet, dateRangeLabel, categoryDataList, taxRate);
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out);
return out.toByteArray();
}
} catch (Exception e) {
throw new BusinessException("导出品类Excel失败: " + e.getMessage());
}
}
private void createCategoryDetailSheet(Sheet sheet, String dateRangeLabel,
List<CompanyOverviewVO.CategoryComparison> dataList,
BigDecimal taxRate) {
CellStyle titleStyle = createTitleStyle(sheet.getWorkbook());
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("品类明细 | " + dateRangeLabel);
titleCell.setCellStyle(titleStyle);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 13));
String taxLabel = taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP).toPlainString() + "%税额";
String[] headers = {
"品类名称", "销售额", "单量", "客单价",
"商品成本", "运费", "其他成本", "退款金额", "推广费", "刷单费用",
"费比", "税前盈亏", taxLabel, "税后盈亏", "ROI"
};
Row headerRow = sheet.createRow(1);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
int rowIdx = 2;
for (CompanyOverviewVO.CategoryComparison data : dataList) {
Row row = sheet.createRow(rowIdx++);
setCell(row, 0, data.getCategoryName(), dataStyle);
setCell(row, 1, objToDouble(data.getSalesAmount()), dataStyle);
setCell(row, 2, objToDouble(data.getOrderCount()), dataStyle);
setCell(row, 3, objToDouble(data.getAverageOrderValue()), dataStyle);
setCell(row, 4, objToDouble(data.getProductCost()), dataStyle);
setCell(row, 5, objToDouble(data.getShippingCost()), dataStyle);
setCell(row, 6, objToDouble(data.getOtherCost()), dataStyle);
setCell(row, 7, objToDouble(data.getRefundAmount()), dataStyle);
setCell(row, 8, objToDouble(data.getTotalPromotionFee()), dataStyle);
setCell(row, 9, objToDouble(data.getBrushFee()), dataStyle);
setCell(row, 10, objToDouble(data.getFeeRatio()), dataStyle);
setCell(row, 11, objToDouble(data.getTotalProfitBeforeTax()), dataStyle);
setCell(row, 12, objToDouble(data.getSalesTaxAmount()), dataStyle);
setCell(row, 13, objToDouble(data.getProfitAfterTax()), dataStyle);
setCell(row, 14, objToDouble(data.getRoi()), dataStyle);
}
for (int i = 0; i < headers.length; i++) {
sheet.setColumnWidth(i, 3200);
}
}
private double objToDouble(Object val) {
if (val == null) return 0.0;
if (val instanceof BigDecimal) return ((BigDecimal) val).setScale(2, RoundingMode.HALF_UP).doubleValue();
if (val instanceof Integer) return ((Integer) val).doubleValue();
return 0.0;
}
private CellStyle createTitleStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
font.setFontHeightInPoints((short) 14);
style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER);
return style;
}
private CellStyle createHeaderStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
return style;
}
private CellStyle createDataStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
DataFormat format = workbook.createDataFormat();
style.setDataFormat(format.getFormat("#,##0.00"));
return style;
}
private void setCell(Row row, int col, String value, CellStyle style) {
Cell cell = row.createCell(col);
cell.setCellValue(value != null ? value : "");
cell.setCellStyle(style);
}
private void setCell(Row row, int col, double value, CellStyle style) {
Cell cell = row.createCell(col);
cell.setCellValue(value);
cell.setCellStyle(style);
}
}
@@ -214,12 +214,12 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
shops, orders, promotionFees, brushOrders, refundStatusIds);
overviewVO.setShopEfficiencyQuadrants(shopEfficiencyQuadrants);
// 9. 多店铺数据横向对比
// 9. 多店铺数据横向汇总
CompanyOverviewVO.ShopOverview shopOverview = calculateShopComparisons(
shops, orders, promotionFees, brushOrders, refundStatusIds, companyId, startDate, endDate);
overviewVO.setShopComparisons(shopOverview);
// 10. 多品类数据横向对比
// 10. 多品类数据横向汇总
CompanyOverviewVO.CategoryOverview categoryOverview = calculateCategoryComparisons(
orders, promotionFees, brushOrders, refundStatusIds, companyId, startDate, endDate);
overviewVO.setCategoryComparisons(categoryOverview);
@@ -455,7 +455,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
}
/**
* 计算多店铺数据横向对比
* 计算多店铺数据横向汇总
*/
private CompanyOverviewVO.ShopOverview calculateShopComparisons(
List<ShopPO> shops, List<OrderPO> orders, List<PromotionFeePO> promotionFees,
@@ -628,7 +628,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
}
/**
* 计算店铺对比的合计行
* 计算店铺汇总的合计行
*/
private CompanyOverviewVO.ShopComparison computeShopTotal(List<CompanyOverviewVO.ShopComparison> shops) {
BigDecimal totalSales = BigDecimal.ZERO;
@@ -983,7 +983,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
}
/**
* 计算品类对比的合计行
* 计算品类汇总的合计行
*/
private CompanyOverviewVO.CategoryComparison computeCategoryTotal(List<CompanyOverviewVO.CategoryComparison> categories) {
BigDecimal totalSales = BigDecimal.ZERO;
@@ -10,28 +10,19 @@ import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.ShopOverviewStatisticsVO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ShopOverviewStatisticsService;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.PlatformExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CategoryExportExcelService;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ExportService;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.mapper.ShopMonthlyTargetMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.model.po.ShopMonthlyTargetPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
@@ -59,11 +50,9 @@ public class ExportServiceImpl implements ExportService {
private final BrushOrderMapper brushOrderMapper;
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
private final ShopService shopService;
private final ProductService productService;
private final OrderStatusService orderStatusService;
private final ShopOverviewStatisticsService shopOverviewStatisticsService;
private final CategoryService categoryService;
private final PlatformMapper platformMapper;
private final ExportStatusRangeHelper exportStatusRangeHelper;
private final CategoryExportExcelService categoryExportExcelService;
public ExportServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper,
@@ -71,28 +60,24 @@ public class ExportServiceImpl implements ExportService {
BrushOrderMapper brushOrderMapper,
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
ShopService shopService,
ProductService productService,
OrderStatusService orderStatusService,
ShopOverviewStatisticsService shopOverviewStatisticsService,
CategoryService categoryService,
PlatformMapper platformMapper) {
PlatformMapper platformMapper,
ExportStatusRangeHelper exportStatusRangeHelper,
CategoryExportExcelService categoryExportExcelService) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
this.brushOrderMapper = brushOrderMapper;
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
this.shopService = shopService;
this.productService = productService;
this.orderStatusService = orderStatusService;
this.shopOverviewStatisticsService = shopOverviewStatisticsService;
this.categoryService = categoryService;
this.platformMapper = platformMapper;
this.exportStatusRangeHelper = exportStatusRangeHelper;
this.categoryExportExcelService = categoryExportExcelService;
}
@Override
public byte[] exportCompanyOverview(CompanyExportDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
LocalDate[] dateRange = parseDateRange(dto.getDateRange());
LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange());
List<ShopPO> shops = shopService.list(
new LambdaQueryWrapper<ShopPO>().eq(ShopPO::getCompanyId, companyId)
@@ -103,8 +88,8 @@ public class ExportServiceImpl implements ExportService {
.collect(Collectors.toList());
}
List<Long> autoStatusIds = getAutoStatusIds(companyId);
List<Long> refundStatusIds = getRefundStatusIds(companyId);
List<Long> autoStatusIds = exportStatusRangeHelper.getAutoStatusIds(companyId);
List<Long> refundStatusIds = exportStatusRangeHelper.getRefundStatusIds(companyId);
List<Map<String, Object>> shopDataList = new ArrayList<>();
BigDecimal totalSales = BigDecimal.ZERO;
@@ -180,297 +165,9 @@ public class ExportServiceImpl implements ExportService {
}
}
@Override
public byte[] exportShopOverview(ShopExportDTO dto) {
// 调用已有的概览统计服务,获取完整数据(与店铺概览页完全一致)
ShopOverviewQueryDTO queryDTO = new ShopOverviewQueryDTO();
queryDTO.setShopId(dto.getShopId());
queryDTO.setDateRange(dto.getDateRange());
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
queryDTO.setTaxRate(taxRate);
ShopOverviewStatisticsVO vo = shopOverviewStatisticsService.getShopOverviewStatistics(queryDTO);
String dateRangeLabel = dto.getDateRange().get(0).format(DATE_FMT)
+ " 至 " + dto.getDateRange().get(dto.getDateRange().size() - 1).format(DATE_FMT);
String exportType = dto.getExportType() == null ? "all" : dto.getExportType();
try (Workbook workbook = new XSSFWorkbook()) {
if ("summary".equals(exportType) || "all".equals(exportType)) {
Sheet summarySheet = workbook.createSheet("汇总");
createShopSummarySheetFromVO(summarySheet, vo, dateRangeLabel);
}
if (("product".equals(exportType) || "all".equals(exportType))
&& vo.getProductOverview() != null && vo.getProductOverview().getProducts() != null && !vo.getProductOverview().getProducts().isEmpty()) {
Sheet productSheet = workbook.createSheet("商品明细");
createProductDetailSheetFromVO(productSheet, dateRangeLabel, vo.getProductOverview().getProducts(), taxRate);
}
if (("trend".equals(exportType) || "all".equals(exportType))
&& vo.getSalesAmountTrend() != null
&& vo.getSalesAmountTrend().getDailyDataList() != null
&& !vo.getSalesAmountTrend().getDailyDataList().isEmpty()) {
Sheet trendSheet = workbook.createSheet("销售趋势");
createTrendSheetFromVO(trendSheet, dateRangeLabel, vo);
}
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out);
return out.toByteArray();
}
} catch (Exception e) {
throw new BusinessException("导出Excel失败: " + e.getMessage());
}
}
@Override
public byte[] exportCategoryOverview(CategoryExportDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
LocalDate[] dateRange = parseDateRange(dto.getDateRange());
LocalDate startDate = dateRange[0];
LocalDate endDate = dateRange[1];
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
List<Long> autoStatusIds = getAutoStatusIds(companyId);
List<Long> refundStatusIds = getRefundStatusIds(companyId);
// 查询订单
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.ge(OrderPO::getOrderTime, startDateTime)
.le(OrderPO::getOrderTime, endDateTime);
if (!autoStatusIds.isEmpty()) {
orderWrapper.in(OrderPO::getStatusId, autoStatusIds);
} else {
orderWrapper.isNull(OrderPO::getId);
}
List<OrderPO> orders = orderMapper.selectList(orderWrapper);
// 查询推广费
LambdaQueryWrapper<PromotionFeePO> promoWrapper = new LambdaQueryWrapper<>();
promoWrapper.eq(PromotionFeePO::getCompanyId, companyId)
.ge(PromotionFeePO::getFeeDate, startDate)
.le(PromotionFeePO::getFeeDate, endDate);
List<PromotionFeePO> promotionFees = promotionFeeMapper.selectList(promoWrapper);
// 查询刷单费
LambdaQueryWrapper<BrushOrderPO> brushWrapper = new LambdaQueryWrapper<>();
brushWrapper.eq(BrushOrderPO::getCompanyId, companyId)
.ge(BrushOrderPO::getBrushTime, startDate.atStartOfDay())
.le(BrushOrderPO::getBrushTime, endDate.atTime(23, 59, 59));
List<BrushOrderPO> brushOrders = brushOrderMapper.selectList(brushWrapper);
// 构建 productId -> categoryId map
List<Long> productIds = orders.stream()
.map(OrderPO::getProductId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
Map<Long, Long> productCategoryMap = new HashMap<>();
if (!productIds.isEmpty()) {
LambdaQueryWrapper<ProductPO> productWrapper = new LambdaQueryWrapper<>();
productWrapper.in(ProductPO::getId, productIds).select(ProductPO::getId, ProductPO::getCategoryId);
List<ProductPO> products = productService.list(productWrapper);
for (ProductPO product : products) {
productCategoryMap.put(product.getId(), product.getCategoryId());
}
}
// 按品类分组
Map<Long, List<OrderPO>> ordersByCategory = orders.stream()
.collect(Collectors.groupingBy(order -> {
Long categoryId = productCategoryMap.get(order.getProductId());
return categoryId != null ? categoryId : -1L;
}));
// 推广费/刷单费按店铺分组
Map<Long, BigDecimal> shopTotalPromoFeeMap = promotionFees.stream()
.collect(Collectors.groupingBy(PromotionFeePO::getShopId,
Collectors.reducing(BigDecimal.ZERO,
f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO,
BigDecimal::add)));
Map<Long, BigDecimal> shopTotalBrushFeeMap = brushOrders.stream()
.collect(Collectors.groupingBy(BrushOrderPO::getShopId,
Collectors.reducing(BigDecimal.ZERO,
b -> b.getBrushAmount() != null ? b.getBrushAmount() : BigDecimal.ZERO,
BigDecimal::add)));
// 品类名称映射
LambdaQueryWrapper<CategoryPO> categoryWrapper = new LambdaQueryWrapper<>();
categoryWrapper.eq(CategoryPO::getCompanyId, companyId);
List<CategoryPO> allCategories = categoryService.list(categoryWrapper);
Map<Long, String> categoryNameMap = allCategories.stream()
.collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName));
// 计算各品类数据
List<CompanyOverviewVO.CategoryComparison> categoryDataList = new ArrayList<>();
for (Map.Entry<Long, List<OrderPO>> entry : ordersByCategory.entrySet()) {
Long categoryId = entry.getKey();
List<OrderPO> categoryOrders = entry.getValue();
BigDecimal salesAmount = categoryOrders.stream()
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
int orderCount = categoryOrders.size();
BigDecimal refundAmount = categoryOrders.stream()
.filter(o -> !refundStatusIds.isEmpty() && refundStatusIds.contains(o.getStatusId()))
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal productCost = categoryOrders.stream()
.map(o -> {
BigDecimal c = o.getProductCost() != null ? o.getProductCost() : BigDecimal.ZERO;
int qty = o.getQuantity() != null ? o.getQuantity() : 1;
return c.multiply(new BigDecimal(qty));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal shippingCost = categoryOrders.stream()
.map(o -> {
BigDecimal c = o.getShippingCost() != null ? o.getShippingCost() : BigDecimal.ZERO;
int qty = o.getQuantity() != null ? o.getQuantity() : 1;
return c.multiply(new BigDecimal(qty));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal otherCost = categoryOrders.stream()
.map(o -> o.getOtherCost() != null ? o.getOtherCost() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
// 按店铺销售额分摊推广费/刷单费
Map<Long, BigDecimal> categorySalesByShop = categoryOrders.stream()
.collect(Collectors.groupingBy(OrderPO::getShopId,
Collectors.reducing(BigDecimal.ZERO,
o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO,
BigDecimal::add)));
BigDecimal categoryTotalSales = categorySalesByShop.values().stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalPromotionFee = BigDecimal.ZERO;
BigDecimal totalBrushFee = BigDecimal.ZERO;
if (categoryTotalSales.compareTo(BigDecimal.ZERO) > 0) {
for (Map.Entry<Long, BigDecimal> shopEntry : categorySalesByShop.entrySet()) {
Long shopId = shopEntry.getKey();
BigDecimal ratio = shopEntry.getValue().divide(categoryTotalSales, 6, RoundingMode.HALF_UP);
totalPromotionFee = totalPromotionFee.add(
shopTotalPromoFeeMap.getOrDefault(shopId, BigDecimal.ZERO).multiply(ratio));
totalBrushFee = totalBrushFee.add(
shopTotalBrushFeeMap.getOrDefault(shopId, BigDecimal.ZERO).multiply(ratio));
}
}
BigDecimal totalCost = productCost.add(shippingCost).add(otherCost);
BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount);
BigDecimal salesTaxAmount = salesAmount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP);
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount);
BigDecimal roi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0
? salesAmount.subtract(refundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal feeRatio = salesAmount.compareTo(BigDecimal.ZERO) > 0
? totalPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal avgOrderValue = orderCount > 0
? salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
String categoryName = categoryId == -1L
? "未分配品类"
: categoryNameMap.getOrDefault(categoryId, "Unknown");
CompanyOverviewVO.CategoryComparison data = new CompanyOverviewVO.CategoryComparison();
data.setCategoryId(categoryId == -1L ? null : categoryId);
data.setCategoryName(categoryName);
data.setSalesAmount(salesAmount);
data.setOrderCount(orderCount);
data.setAverageOrderValue(avgOrderValue);
data.setProductCost(productCost);
data.setShippingCost(shippingCost);
data.setOtherCost(otherCost);
data.setRefundAmount(refundAmount);
data.setTotalPromotionFee(totalPromotionFee);
data.setBrushFee(totalBrushFee);
data.setFeeRatio(feeRatio);
data.setTotalProfitBeforeTax(profitBeforeTax);
data.setSalesTaxAmount(salesTaxAmount);
data.setProfitAfterTax(profitAfterTax);
data.setRoi(roi);
categoryDataList.add(data);
}
// 按品类ID过滤
if (dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty()) {
Set<Long> allowedIds = new HashSet<>(dto.getCategoryIds());
categoryDataList = categoryDataList.stream()
.filter(c -> c.getCategoryId() != null && allowedIds.contains(c.getCategoryId()))
.collect(Collectors.toList());
}
categoryDataList.sort(Comparator.comparing(CompanyOverviewVO.CategoryComparison::getSalesAmount).reversed());
String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT);
try (Workbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("品类明细");
createCategoryDetailSheet(sheet, dateRangeLabel, categoryDataList, taxRate);
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out);
return out.toByteArray();
}
} catch (Exception e) {
throw new BusinessException("导出品类Excel失败: " + e.getMessage());
}
}
private void createCategoryDetailSheet(Sheet sheet, String dateRangeLabel,
List<CompanyOverviewVO.CategoryComparison> dataList,
BigDecimal taxRate) {
CellStyle titleStyle = createTitleStyle(sheet.getWorkbook());
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("品类明细 | " + dateRangeLabel);
titleCell.setCellStyle(titleStyle);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 13));
String taxLabel = taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP).toPlainString() + "%税额";
String[] headers = {
"品类名称", "销售额", "单量", "客单价",
"商品成本", "运费", "其他成本", "退款金额", "推广费", "刷单费用",
"费比", "税前盈亏", taxLabel, "税后盈亏", "ROI"
};
Row headerRow = sheet.createRow(1);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
int rowIdx = 2;
for (CompanyOverviewVO.CategoryComparison data : dataList) {
Row row = sheet.createRow(rowIdx++);
setCell(row, 0, data.getCategoryName(), dataStyle);
setCell(row, 1, objToDouble(data.getSalesAmount()), dataStyle);
setCell(row, 2, objToDouble(data.getOrderCount()), dataStyle);
setCell(row, 3, objToDouble(data.getAverageOrderValue()), dataStyle);
setCell(row, 4, objToDouble(data.getProductCost()), dataStyle);
setCell(row, 5, objToDouble(data.getShippingCost()), dataStyle);
setCell(row, 6, objToDouble(data.getOtherCost()), dataStyle);
setCell(row, 7, objToDouble(data.getRefundAmount()), dataStyle);
setCell(row, 8, objToDouble(data.getTotalPromotionFee()), dataStyle);
setCell(row, 9, objToDouble(data.getBrushFee()), dataStyle);
setCell(row, 10, objToDouble(data.getFeeRatio()), dataStyle);
setCell(row, 11, objToDouble(data.getTotalProfitBeforeTax()), dataStyle);
setCell(row, 12, objToDouble(data.getSalesTaxAmount()), dataStyle);
setCell(row, 13, objToDouble(data.getProfitAfterTax()), dataStyle);
setCell(row, 14, objToDouble(data.getRoi()), dataStyle);
}
for (int i = 0; i < headers.length; i++) {
sheet.setColumnWidth(i, 3200);
}
return categoryExportExcelService.exportCategoryOverview(dto);
}
// ==================== Sheet 构建方法 ====================
@@ -602,171 +299,6 @@ public class ExportServiceImpl implements ExportService {
return 0.0;
}
private BigDecimal nvl(BigDecimal val, BigDecimal defaultVal) {
return val != null ? val : defaultVal;
}
private Integer nvl(Integer val, Integer defaultVal) {
return val != null ? val : defaultVal;
}
private Integer nvl(Integer val, int defaultVal) {
return val != null ? val : defaultVal;
}
private void createShopSummarySheet(Sheet sheet, String shopName, String dateRangeLabel, Map<String, Object> data) {
CellStyle titleStyle = createTitleStyle(sheet.getWorkbook());
CellStyle labelStyle = createLabelStyle(sheet.getWorkbook());
CellStyle valueStyle = createValueStyle(sheet.getWorkbook());
String[] labels = {"店铺名称", "销售额", "单量", "客单价", "推广费", "刷单费", "费比",
"退款金额", "成本运费", "税前盈亏", "税额", "税后盈亏", "ROI",
"目标销售额", "销售额达成率", "目标单量", "单量达成率"};
Object[] values = {
shopName,
nvl((BigDecimal) data.get("salesAmount"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP),
nvl((Integer) data.get("orderCount"), 0),
nvl((BigDecimal) data.get("avgOrderValue"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP),
nvl((BigDecimal) data.get("totalPromotionFee"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP),
nvl((BigDecimal) data.get("brushFee"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP),
nvl((BigDecimal) data.get("feeRatio"), BigDecimal.ZERO).setScale(4, RoundingMode.HALF_UP),
nvl((BigDecimal) data.get("refundAmount"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP),
nvl((BigDecimal) data.get("shippingCost"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP),
nvl((BigDecimal) data.get("totalProfitBeforeTax"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP),
nvl((BigDecimal) data.get("salesTaxAmount"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP),
nvl((BigDecimal) data.get("profitAfterTax"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP),
nvl((BigDecimal) data.get("roi"), BigDecimal.ZERO).setScale(4, RoundingMode.HALF_UP),
nvl((BigDecimal) data.get("targetAmount"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP),
nvl((BigDecimal) data.get("salesAmountAchievementRate"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP),
nvl((Integer) data.get("targetOrderCount"), 0),
nvl((BigDecimal) data.get("orderCountAchievementRate"), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP)
};
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue(shopName + " - 概览汇总 | " + dateRangeLabel);
titleCell.setCellStyle(titleStyle);
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(0, 0, 0, 1));
for (int i = 0; i < labels.length; i++) {
Row row = sheet.createRow(i + 1);
Cell labelCell = row.createCell(0);
labelCell.setCellValue(labels[i]);
labelCell.setCellStyle(labelStyle);
Cell valueCell = row.createCell(1);
Object val = values[i];
if (val instanceof BigDecimal) {
valueCell.setCellValue(((BigDecimal) val).doubleValue());
} else {
valueCell.setCellValue(val.toString());
}
valueCell.setCellStyle(valueStyle);
}
sheet.setColumnWidth(0, 4000);
sheet.setColumnWidth(1, 4000);
}
private void createProductDetailSheet(Sheet sheet, String dateRangeLabel,
Map<Long, List<OrderPO>> ordersByProduct,
PromotionFeeMapper promotionFeeMapper,
BrushOrderMapper brushOrderMapper,
Long companyId, Long shopId,
LocalDate startDate, LocalDate endDate,
List<Long> refundStatusIds) {
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("商品明细 | " + dateRangeLabel);
titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook()));
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(0, 0, 0, 13));
String[] headers = {"商品名称", "商品编码", "销售额", "单量", "客单价", "推广费", "刷单费",
"费比", "退款金额", "成本运费", "税前盈亏", "税额", "税后盈亏", "ROI"};
Row headerRow = sheet.createRow(1);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
int rowIdx = 2;
for (Map.Entry<Long, List<OrderPO>> entry : ordersByProduct.entrySet()) {
Long productId = entry.getKey();
List<OrderPO> productOrders = entry.getValue();
ProductPO product = productService.getById(productId);
if (product == null) continue;
BigDecimal salesAmount = productOrders.stream()
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal refundAmount = productOrders.stream()
.filter(o -> !refundStatusIds.isEmpty() && refundStatusIds.contains(o.getStatusId()))
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal shippingCost = productOrders.stream()
.map(o -> {
BigDecimal c = o.getShippingCost() != null ? o.getShippingCost() : BigDecimal.ZERO;
Integer qty = o.getQuantity() != null ? o.getQuantity() : 1;
return c.multiply(new BigDecimal(qty));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal productCost = productOrders.stream()
.map(o -> {
BigDecimal c = o.getProductCost() != null ? o.getProductCost() : BigDecimal.ZERO;
Integer qty = o.getQuantity() != null ? o.getQuantity() : 1;
return c.multiply(new BigDecimal(qty));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
int orderCount = productOrders.size();
BigDecimal avgOrderValue = orderCount > 0
? salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal totalCost = productCost.add(shippingCost);
BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount);
BigDecimal tax = profitBeforeTax.multiply(DEFAULT_TAX_RATE).setScale(2, RoundingMode.HALF_UP);
BigDecimal profitAfterTax = profitBeforeTax.subtract(tax);
// 按商品分摊推广费和刷单费(按销售额占比)
BigDecimal promotionFee = BigDecimal.ZERO;
BigDecimal brushFee = BigDecimal.ZERO;
BigDecimal roi = promotionFee.compareTo(BigDecimal.ZERO) > 0
? salesAmount.subtract(refundAmount).divide(promotionFee, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal feeRatio = salesAmount.compareTo(BigDecimal.ZERO) > 0
? promotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
Row row = sheet.createRow(rowIdx++);
setCell(row, 0, product.getName(), dataStyle);
setCell(row, 1, product.getProductCode(), dataStyle);
setCell(row, 2, salesAmount.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 3, (double) orderCount, dataStyle);
setCell(row, 4, avgOrderValue.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 5, promotionFee.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 6, brushFee.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 7, feeRatio.setScale(4, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 8, refundAmount.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 9, shippingCost.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 10, profitBeforeTax.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 11, tax.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 12, profitAfterTax.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 13, roi.setScale(4, RoundingMode.HALF_UP).doubleValue(), dataStyle);
}
for (int i = 0; i < headers.length; i++) {
sheet.setColumnWidth(i, 3200);
}
}
private void createTrendSheet(Sheet sheet, String dateRangeLabel,
Map<LocalDate, List<OrderPO>> ordersByDate,
LocalDate startDate, LocalDate endDate) {
@@ -816,228 +348,6 @@ public class ExportServiceImpl implements ExportService {
sheet.setColumnWidth(3, 3200);
}
// ==================== Sheet 构建方法(复用 VO 数据) ====================
/**
* 店铺汇总 Sheet - 从 VO 构建,横向排布(字段为列)
*/
private void createShopSummarySheetFromVO(Sheet sheet, ShopOverviewStatisticsVO vo, String dateRangeLabel) {
CellStyle titleStyle = createTitleStyle(sheet.getWorkbook());
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
// 字段定义(列顺序):字段名 -> VO字段key -> 是否BigDecimal
List<SummaryField> fields = Arrays.asList(
new SummaryField("销售额", "totalSalesAmount", true),
new SummaryField("单量", "totalOrderCount", false),
new SummaryField("客单价", "avgOrderValue", true),
new SummaryField("推广费", "totalPromotionFee", true),
new SummaryField("费比", "averageFeeRatio", true),
new SummaryField("退款金额", "refundAmount", true),
new SummaryField("税前盈亏", "profitBeforeTax", true),
new SummaryField("税额", "totalTaxAmount", true),
new SummaryField("税后盈亏", "totalNetProfitAfterTax", true),
new SummaryField("ROI", "totalROI", true),
new SummaryField("目标销售额", "totalTargetAmount", true),
new SummaryField("目标单量", "totalTargetOrderCount", false),
new SummaryField("销售额达成率(%)", "salesAmountAchievementRate", true),
new SummaryField("单量达成率(%)", "orderCountAchievementRate", true)
);
int colCount = fields.size() + 1; // 店铺名称列 + 每个字段一列
// 标题行
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue((vo.getShopName() != null ? vo.getShopName() : "") + " - 概览汇总 | " + dateRangeLabel);
titleCell.setCellStyle(titleStyle);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, colCount - 1));
// 表头:店铺名称列 + 字段列
Row headerRow = sheet.createRow(1);
Cell h0 = headerRow.createCell(0);
h0.setCellValue("指标名称");
h0.setCellStyle(headerStyle);
for (int c = 0; c < fields.size(); c++) {
Cell hCell = headerRow.createCell(c + 1);
hCell.setCellValue(fields.get(c).label);
hCell.setCellStyle(headerStyle);
}
// 数据行:店铺名称 + 各字段值
Row dataRow = sheet.createRow(2);
Cell shopNameCell = dataRow.createCell(0);
shopNameCell.setCellValue(vo.getShopName() != null ? vo.getShopName() : "");
shopNameCell.setCellStyle(dataStyle);
for (int c = 0; c < fields.size(); c++) {
SummaryField f = fields.get(c);
Cell cell = dataRow.createCell(c + 1);
cell.setCellStyle(dataStyle);
Object val = getVOFieldValue(vo, f.key);
if (val != null) {
if (val instanceof BigDecimal) {
int scale = ("averageFeeRatio".equals(f.key) || "totalROI".equals(f.key)) ? 4 : 2;
cell.setCellValue(((BigDecimal) val).setScale(scale, RoundingMode.HALF_UP).doubleValue());
} else if (val instanceof Integer) {
cell.setCellValue(((Integer) val).doubleValue());
}
}
}
sheet.setColumnWidth(0, 4000);
for (int c = 0; c < fields.size(); c++) {
sheet.setColumnWidth(c + 1, 3200);
}
}
private static class SummaryField {
String label;
String key;
boolean isDecimal;
SummaryField(String label, String key, boolean isDecimal) {
this.label = label; this.key = key; this.isDecimal = isDecimal;
}
}
private Object getVOFieldValue(ShopOverviewStatisticsVO vo, String key) {
switch (key) {
case "totalSalesAmount": return vo.getTotalSalesAmount();
case "totalOrderCount": return vo.getTotalOrderCount();
case "avgOrderValue": return vo.getAverageOrderValue();
case "totalPromotionFee": return vo.getTotalPromotionFee();
case "averageFeeRatio": return vo.getAverageFeeRatio();
case "refundAmount": return vo.getRefundAmount();
case "profitBeforeTax": return vo.getTotalProfitBeforeTax();
case "totalTaxAmount": return vo.getTotalTaxAmount();
case "totalNetProfitAfterTax": return vo.getTotalNetProfitAfterTax();
case "totalROI": return vo.getTotalROI();
case "totalTargetAmount": return vo.getTotalTargetAmount();
case "totalTargetOrderCount": return vo.getTotalTargetOrderCount();
case "salesAmountAchievementRate": return vo.getSalesAmountAchievementRate();
case "orderCountAchievementRate": return vo.getOrderCountAchievementRate();
default: return null;
}
}
/**
* 商品明细 Sheet - 从 VO.ProductComparison 构建
* 列顺序与页面「核心商品多维度损益对比表」完全一致
*/
private void createProductDetailSheetFromVO(Sheet sheet, String dateRangeLabel,
List<ShopOverviewStatisticsVO.ProductComparison> products,
BigDecimal taxRate) {
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("核心商品多维度损益对比表 | " + dateRangeLabel);
titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook()));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 12));
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
// 表头与页面顺序完全一致(分三组:规模/成本/损益)
String taxLabel = (taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP)).toPlainString() + "%税额";
String[] headers = {
"商品详情", "销售额", "单量", "客单价",
"商品成本", "运费", "其他成本", "退款金额", "推广费", "刷单费用",
"费比(%)", "单品ROI", "税前盈亏", taxLabel, "税后净利"
};
Row headerRow = sheet.createRow(1);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
int rowIdx = 2;
for (ShopOverviewStatisticsVO.ProductComparison p : products) {
Row row = sheet.createRow(rowIdx++);
// 商品详情
setCell(row, 0, p.getProductName() + (p.getProductCode() != null ? "\n编码: " + p.getProductCode() : ""), dataStyle);
setCell(row, 1, nvl(p.getSalesAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 2, (double) nvl(p.getOrderCount(), 0), dataStyle);
setCell(row, 3, nvl(p.getAverageOrderValue(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 4, nvl(p.getProductCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 5, nvl(p.getShippingCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 6, nvl(p.getOtherCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 7, nvl(p.getRefundAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 8, nvl(p.getTotalPromotionFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 9, nvl(p.getBrushFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 10, nvl(p.getFeeRatio(), BigDecimal.ZERO).setScale(4, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 11, nvl(p.getRoi(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 12, nvl(p.getTotalProfitBeforeTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 13, nvl(p.getSalesTaxAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 14, nvl(p.getProfitAfterTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
}
sheet.setColumnWidth(0, 5000);
for (int i = 1; i < headers.length; i++) {
sheet.setColumnWidth(i, 3200);
}
}
/**
* 销售趋势 Sheet - 从 VO.TrendData 构建
*/
private void createTrendSheetFromVO(Sheet sheet, String dateRangeLabel, ShopOverviewStatisticsVO vo) {
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("销售趋势 | " + dateRangeLabel);
titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook()));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
String[] headers = {"日期", "销售额", "单量"};
Row headerRow = sheet.createRow(1);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
List<ShopOverviewStatisticsVO.TrendDataItem> dailySales = vo.getSalesAmountTrend().getDailyDataList();
List<ShopOverviewStatisticsVO.TrendDataItem> dailyOrders = vo.getOrderCountTrend() != null
? vo.getOrderCountTrend().getDailyDataList() : null;
// 合并两个趋势数据
Map<LocalDate, BigDecimal> salesMap = dailySales.stream()
.collect(Collectors.toMap(ShopOverviewStatisticsVO.TrendDataItem::getDate,
ShopOverviewStatisticsVO.TrendDataItem::getValue, (a, b) -> a));
Map<LocalDate, BigDecimal> ordersMap = dailyOrders != null
? dailyOrders.stream().collect(Collectors.toMap(
ShopOverviewStatisticsVO.TrendDataItem::getDate,
ShopOverviewStatisticsVO.TrendDataItem::getValue, (a, b) -> a))
: Collections.emptyMap();
// 按日期排序输出
LocalDate startDate = vo.getSalesAmountTrend().getDailyDataList().stream()
.map(ShopOverviewStatisticsVO.TrendDataItem::getDate).min(LocalDate::compareTo).orElse(null);
LocalDate endDate = vo.getSalesAmountTrend().getDailyDataList().stream()
.map(ShopOverviewStatisticsVO.TrendDataItem::getDate).max(LocalDate::compareTo).orElse(null);
int rowIdx = 2;
if (startDate != null && endDate != null) {
LocalDate current = startDate;
while (!current.isAfter(endDate)) {
Row row = sheet.createRow(rowIdx++);
BigDecimal sales = salesMap.getOrDefault(current, BigDecimal.ZERO);
BigDecimal orders = ordersMap.getOrDefault(current, BigDecimal.ZERO);
setCell(row, 0, current.format(DATE_FMT), dataStyle);
setCell(row, 1, nvl(sales, BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 2, nvl(orders, BigDecimal.ZERO).setScale(0, RoundingMode.HALF_UP).doubleValue(), dataStyle);
current = current.plusDays(1);
}
}
sheet.setColumnWidth(0, 3200);
sheet.setColumnWidth(1, 3200);
sheet.setColumnWidth(2, 3200);
}
// ==================== 数据构建方法 ====================
private Map<String, Object> buildShopData(ShopPO shop, LocalDate startDate, LocalDate endDate,
@@ -1179,36 +489,6 @@ public class ExportServiceImpl implements ExportService {
return data;
}
private LocalDate[] parseDateRange(List<LocalDate> dateRange) {
if (dateRange.size() == 1) {
return new LocalDate[]{dateRange.get(0), dateRange.get(0)};
}
LocalDate start = dateRange.get(0);
LocalDate end = dateRange.get(1);
if (start.isAfter(end)) {
throw new BusinessException("开始日期不能晚于结束日期");
}
return new LocalDate[]{start, end};
}
private List<Long> getAutoStatusIds(Long companyId) {
List<OrderStatusPO> statusList = orderStatusService.list(
new LambdaQueryWrapper<OrderStatusPO>()
.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getAutoStatistics, 1)
.select(OrderStatusPO::getId));
return statusList.stream().map(OrderStatusPO::getId).collect(Collectors.toList());
}
private List<Long> getRefundStatusIds(Long companyId) {
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getIsRefund, 1)
.select(OrderStatusPO::getId);
List<OrderStatusPO> statusList = orderStatusService.list(wrapper);
return statusList.stream().map(OrderStatusPO::getId).collect(Collectors.toList());
}
// ==================== Excel 样式工具 ====================
private CellStyle createTitleStyle(Workbook workbook) {
@@ -1289,15 +569,15 @@ public class ExportServiceImpl implements ExportService {
@Override
public byte[] exportPlatformOverview(PlatformExportDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
LocalDate[] dateRange = parseDateRange(dto.getDateRange());
LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange());
LocalDate startDate = dateRange[0];
LocalDate endDate = dateRange[1];
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
List<Long> autoStatusIds = getAutoStatusIds(companyId);
List<Long> refundStatusIds = getRefundStatusIds(companyId);
List<Long> autoStatusIds = exportStatusRangeHelper.getAutoStatusIds(companyId);
List<Long> refundStatusIds = exportStatusRangeHelper.getRefundStatusIds(companyId);
// 查询所有店铺并按平台分组
List<ShopPO> allShops = shopService.list(
@@ -0,0 +1,54 @@
package top.xyquan.ecomdmbbackend.modules.ecom.overview.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
/**
* 导出共用的日期区间与订单状态 ID 解析
*/
@Component
public class ExportStatusRangeHelper {
private final OrderStatusService orderStatusService;
public ExportStatusRangeHelper(OrderStatusService orderStatusService) {
this.orderStatusService = orderStatusService;
}
public LocalDate[] parseDateRange(List<LocalDate> dateRange) {
if (dateRange.size() == 1) {
return new LocalDate[]{dateRange.get(0), dateRange.get(0)};
}
LocalDate start = dateRange.get(0);
LocalDate end = dateRange.get(1);
if (start.isAfter(end)) {
throw new BusinessException("开始日期不能晚于结束日期");
}
return new LocalDate[]{start, end};
}
public List<Long> getAutoStatusIds(Long companyId) {
List<OrderStatusPO> statusList = orderStatusService.list(
new LambdaQueryWrapper<OrderStatusPO>()
.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getAutoStatistics, 1)
.select(OrderStatusPO::getId));
return statusList.stream().map(OrderStatusPO::getId).collect(Collectors.toList());
}
public List<Long> getRefundStatusIds(Long companyId) {
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getIsRefund, 1)
.select(OrderStatusPO::getId);
List<OrderStatusPO> statusList = orderStatusService.list(wrapper);
return statusList.stream().map(OrderStatusPO::getId).collect(Collectors.toList());
}
}
@@ -240,12 +240,12 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
overviewVO.setSalesAmountTrend(salesAmountTrend);
overviewVO.setOrderCountTrend(orderCountTrend);
// 10. 多商品数据横向对比
// 10. 多商品数据横向汇总
ShopOverviewStatisticsVO.ProductOverview productOverview = calculateProductComparisons(
orders, promotionFees, brushOrders, refundStatusIds);
overviewVO.setProductOverview(productOverview);
// 11. 品类多维度数据对比
// 11. 品类多维度数据汇总
ShopOverviewStatisticsVO.CategoryOverview categoryOverview = calculateCategoryComparisons(
orders, promotionFees, brushOrders, refundStatusIds);
overviewVO.setCategoryOverview(categoryOverview);
@@ -364,7 +364,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
}
/**
* 计算多商品数据横向对比
* 计算多商品数据横向汇总
*/
private ShopOverviewStatisticsVO.ProductOverview calculateProductComparisons(
List<OrderPO> orders, List<PromotionFeePO> promotionFees,
@@ -504,7 +504,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
}
/**
* 计算商品对比的合计行
* 计算商品汇总的合计行
*/
private ShopOverviewStatisticsVO.ProductComparison computeProductTotal(List<ShopOverviewStatisticsVO.ProductComparison> products) {
BigDecimal totalSales = BigDecimal.ZERO;
@@ -685,7 +685,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
}
/**
* 计算品类多维度数据对比
* 计算品类多维度数据汇总
*/
private ShopOverviewStatisticsVO.CategoryOverview calculateCategoryComparisons(
List<OrderPO> orders, List<PromotionFeePO> promotionFees,
@@ -832,7 +832,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
}
/**
* 计算店铺视角品类对比的合计行
* 计算店铺视角品类汇总的合计行
*/
private ShopOverviewStatisticsVO.CategoryComparison computeCategoryTotalForShop(List<ShopOverviewStatisticsVO.CategoryComparison> categories) {
BigDecimal totalSales = BigDecimal.ZERO;
@@ -0,0 +1,21 @@
package top.xyquan.ecomdmbbackend.modules.ecom.overview.util;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* 汇总类 Excel 导出文件名:前缀_开始日期-结束日期.xlsx(日期为 yyyyMMdd)
*/
public final class ExportFilenameUtils {
private static final DateTimeFormatter SEGMENT_FMT = DateTimeFormatter.ofPattern("yyyyMMdd");
private ExportFilenameUtils() {}
public static String buildXlsxName(String namePrefix, List<LocalDate> dateRange) {
LocalDate start = dateRange.get(0);
LocalDate end = dateRange.get(dateRange.size() - 1);
return namePrefix + "_" + start.format(SEGMENT_FMT) + "-" + end.format(SEGMENT_FMT) + ".xlsx";
}
}
@@ -108,7 +108,7 @@ public class ShopController {
return ApiResponse.success("获取店铺商品列表成功", result);
}
@Operation(summary = "获取店铺概览统计数据", description = "获取指定店铺的概览统计数据,包括销售额、单量、推广费、利润、ROI等,以及多商品数据横向对比")
@Operation(summary = "获取店铺概览统计数据", description = "获取指定店铺的概览统计数据,包括销售额、单量、推广费、利润、ROI等,以及多商品数据横向汇总")
@PostMapping("/overview-statistics")
@RequirePermission(value = "ecom:shop:read", description = "查询店铺概览统计", allowSuper = true)
public ApiResponse<ShopOverviewStatisticsVO> getShopOverviewStatistics(@Valid @RequestBody ShopOverviewQueryDTO queryDTO) {
@@ -0,0 +1,62 @@
package top.xyquan.ecomdmbbackend.modules.ecom.shop.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.util.ExportFilenameUtils;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopExportService;
/**
* 店铺侧 Excel 导出(路径仍为 /ec/shop/*,与前端约定一致)
*/
@Tag(name = "电商-店铺导出", description = "店铺概览与门店品类导出")
@RestController
@RequestMapping("/ec/shop")
public class ShopExportController {
private final ShopExportService shopExportService;
public ShopExportController(ShopExportService shopExportService) {
this.shopExportService = shopExportService;
}
@Operation(summary = "导出店铺概览Excel", description = "导出单店铺概览数据为Excel文件")
@PostMapping("/export-overview")
@RequirePermission(value = "data:export", description = "导出店铺概览", allowSuper = true)
public void exportShopOverview(@Valid @RequestBody ShopExportDTO dto, HttpServletResponse response) {
byte[] data = shopExportService.exportShopOverview(dto);
String filename = ExportFilenameUtils.buildXlsxName("店铺概览", dto.getDateRange());
writeExcel(response, filename, data);
}
@Operation(summary = "导出门店品类汇总Excel", description = "导出门店品类多维度数据汇总为Excel文件")
@PostMapping("/export-category")
@RequirePermission(value = "data:export", description = "导出门店品类汇总", allowSuper = true)
public void exportShopCategoryOverview(@Valid @RequestBody CategoryExportDTO dto, HttpServletResponse response) {
byte[] data = shopExportService.exportShopCategoryOverview(dto);
String filename = ExportFilenameUtils.buildXlsxName("门店品类汇总", dto.getDateRange());
writeExcel(response, filename, data);
}
private void writeExcel(HttpServletResponse response, String filename, byte[] data) {
try {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"");
response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.getOutputStream().write(data);
response.getOutputStream().flush();
} catch (Exception e) {
throw new RuntimeException("写入Excel文件失败: " + e.getMessage());
}
}
}
@@ -0,0 +1,15 @@
package top.xyquan.ecomdmbbackend.modules.ecom.shop.service;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopExportDTO;
/**
* 店铺侧 Excel 导出(单店概览、门店品类汇总)
*/
public interface ShopExportService {
byte[] exportShopOverview(ShopExportDTO dto);
/** 与品类概览导出逻辑一致,供店铺概览页「门店品类汇总」使用 */
byte[] exportShopCategoryOverview(CategoryExportDTO dto);
}
@@ -0,0 +1,354 @@
package top.xyquan.ecomdmbbackend.modules.ecom.shop.service.impl;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.ShopOverviewStatisticsVO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ShopOverviewStatisticsService;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CategoryExportExcelService;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopExportService;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class ShopExportServiceImpl implements ShopExportService {
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final ShopOverviewStatisticsService shopOverviewStatisticsService;
private final CategoryExportExcelService categoryExportExcelService;
public ShopExportServiceImpl(
ShopOverviewStatisticsService shopOverviewStatisticsService,
CategoryExportExcelService categoryExportExcelService) {
this.shopOverviewStatisticsService = shopOverviewStatisticsService;
this.categoryExportExcelService = categoryExportExcelService;
}
@Override
public byte[] exportShopOverview(ShopExportDTO dto) {
ShopOverviewQueryDTO queryDTO = new ShopOverviewQueryDTO();
queryDTO.setShopId(dto.getShopId());
queryDTO.setDateRange(dto.getDateRange());
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
queryDTO.setTaxRate(taxRate);
ShopOverviewStatisticsVO vo = shopOverviewStatisticsService.getShopOverviewStatistics(queryDTO);
String dateRangeLabel = dto.getDateRange().get(0).format(DATE_FMT)
+ " 至 " + dto.getDateRange().get(dto.getDateRange().size() - 1).format(DATE_FMT);
String exportType = dto.getExportType() == null ? "all" : dto.getExportType();
try (Workbook workbook = new XSSFWorkbook()) {
if ("summary".equals(exportType) || "all".equals(exportType)) {
Sheet summarySheet = workbook.createSheet("汇总");
createShopSummarySheetFromVO(summarySheet, vo, dateRangeLabel);
}
if (("product".equals(exportType) || "all".equals(exportType))
&& vo.getProductOverview() != null && vo.getProductOverview().getProducts() != null
&& !vo.getProductOverview().getProducts().isEmpty()) {
Sheet productSheet = workbook.createSheet("商品明细");
createProductDetailSheetFromVO(productSheet, dateRangeLabel, vo.getProductOverview().getProducts(), taxRate);
}
if (("trend".equals(exportType) || "all".equals(exportType))
&& vo.getSalesAmountTrend() != null
&& vo.getSalesAmountTrend().getDailyDataList() != null
&& !vo.getSalesAmountTrend().getDailyDataList().isEmpty()) {
Sheet trendSheet = workbook.createSheet("销售趋势");
createTrendSheetFromVO(trendSheet, dateRangeLabel, vo);
}
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out);
return out.toByteArray();
}
} catch (Exception e) {
throw new BusinessException("导出Excel失败: " + e.getMessage());
}
}
@Override
public byte[] exportShopCategoryOverview(CategoryExportDTO dto) {
return categoryExportExcelService.exportCategoryOverview(dto);
}
private void createShopSummarySheetFromVO(Sheet sheet, ShopOverviewStatisticsVO vo, String dateRangeLabel) {
CellStyle titleStyle = createTitleStyle(sheet.getWorkbook());
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
List<SummaryField> fields = Arrays.asList(
new SummaryField("销售额", "totalSalesAmount", true),
new SummaryField("单量", "totalOrderCount", false),
new SummaryField("客单价", "avgOrderValue", true),
new SummaryField("推广费", "totalPromotionFee", true),
new SummaryField("费比", "averageFeeRatio", true),
new SummaryField("退款金额", "refundAmount", true),
new SummaryField("税前盈亏", "profitBeforeTax", true),
new SummaryField("税额", "totalTaxAmount", true),
new SummaryField("税后盈亏", "totalNetProfitAfterTax", true),
new SummaryField("ROI", "totalROI", true),
new SummaryField("目标销售额", "totalTargetAmount", true),
new SummaryField("目标单量", "totalTargetOrderCount", false),
new SummaryField("销售额达成率(%)", "salesAmountAchievementRate", true),
new SummaryField("单量达成率(%)", "orderCountAchievementRate", true)
);
int colCount = fields.size() + 1;
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue((vo.getShopName() != null ? vo.getShopName() : "") + " - 概览汇总 | " + dateRangeLabel);
titleCell.setCellStyle(titleStyle);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, colCount - 1));
Row headerRow = sheet.createRow(1);
Cell h0 = headerRow.createCell(0);
h0.setCellValue("指标名称");
h0.setCellStyle(headerStyle);
for (int c = 0; c < fields.size(); c++) {
Cell hCell = headerRow.createCell(c + 1);
hCell.setCellValue(fields.get(c).label);
hCell.setCellStyle(headerStyle);
}
Row dataRow = sheet.createRow(2);
Cell shopNameCell = dataRow.createCell(0);
shopNameCell.setCellValue(vo.getShopName() != null ? vo.getShopName() : "");
shopNameCell.setCellStyle(dataStyle);
for (int c = 0; c < fields.size(); c++) {
SummaryField f = fields.get(c);
Cell cell = dataRow.createCell(c + 1);
cell.setCellStyle(dataStyle);
Object val = getVOFieldValue(vo, f.key);
if (val != null) {
if (val instanceof BigDecimal) {
int scale = ("averageFeeRatio".equals(f.key) || "totalROI".equals(f.key)) ? 4 : 2;
cell.setCellValue(((BigDecimal) val).setScale(scale, RoundingMode.HALF_UP).doubleValue());
} else if (val instanceof Integer) {
cell.setCellValue(((Integer) val).doubleValue());
}
}
}
sheet.setColumnWidth(0, 4000);
for (int c = 0; c < fields.size(); c++) {
sheet.setColumnWidth(c + 1, 3200);
}
}
private static class SummaryField {
final String label;
final String key;
@SuppressWarnings("unused")
final boolean isDecimal;
SummaryField(String label, String key, boolean isDecimal) {
this.label = label;
this.key = key;
this.isDecimal = isDecimal;
}
}
private Object getVOFieldValue(ShopOverviewStatisticsVO vo, String key) {
return switch (key) {
case "totalSalesAmount" -> vo.getTotalSalesAmount();
case "totalOrderCount" -> vo.getTotalOrderCount();
case "avgOrderValue" -> vo.getAverageOrderValue();
case "totalPromotionFee" -> vo.getTotalPromotionFee();
case "averageFeeRatio" -> vo.getAverageFeeRatio();
case "refundAmount" -> vo.getRefundAmount();
case "profitBeforeTax" -> vo.getTotalProfitBeforeTax();
case "totalTaxAmount" -> vo.getTotalTaxAmount();
case "totalNetProfitAfterTax" -> vo.getTotalNetProfitAfterTax();
case "totalROI" -> vo.getTotalROI();
case "totalTargetAmount" -> vo.getTotalTargetAmount();
case "totalTargetOrderCount" -> vo.getTotalTargetOrderCount();
case "salesAmountAchievementRate" -> vo.getSalesAmountAchievementRate();
case "orderCountAchievementRate" -> vo.getOrderCountAchievementRate();
default -> null;
};
}
private void createProductDetailSheetFromVO(Sheet sheet, String dateRangeLabel,
List<ShopOverviewStatisticsVO.ProductComparison> products,
BigDecimal taxRate) {
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("核心商品多维度损益汇总表 | " + dateRangeLabel);
titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook()));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 12));
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
String taxLabel = (taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP)).toPlainString() + "%税额";
String[] headers = {
"商品详情", "销售额", "单量", "客单价",
"商品成本", "运费", "其他成本", "退款金额", "推广费", "刷单费用",
"费比(%)", "单品ROI", "税前盈亏", taxLabel, "税后净利"
};
Row headerRow = sheet.createRow(1);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
int rowIdx = 2;
for (ShopOverviewStatisticsVO.ProductComparison p : products) {
Row row = sheet.createRow(rowIdx++);
setCell(row, 0, p.getProductName() + (p.getProductCode() != null ? "\n编码: " + p.getProductCode() : ""), dataStyle);
setCell(row, 1, nvl(p.getSalesAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 2, (double) nvl(p.getOrderCount(), 0), dataStyle);
setCell(row, 3, nvl(p.getAverageOrderValue(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 4, nvl(p.getProductCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 5, nvl(p.getShippingCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 6, nvl(p.getOtherCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 7, nvl(p.getRefundAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 8, nvl(p.getTotalPromotionFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 9, nvl(p.getBrushFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 10, nvl(p.getFeeRatio(), BigDecimal.ZERO).setScale(4, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 11, nvl(p.getRoi(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 12, nvl(p.getTotalProfitBeforeTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 13, nvl(p.getSalesTaxAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 14, nvl(p.getProfitAfterTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
}
sheet.setColumnWidth(0, 5000);
for (int i = 1; i < headers.length; i++) {
sheet.setColumnWidth(i, 3200);
}
}
private void createTrendSheetFromVO(Sheet sheet, String dateRangeLabel, ShopOverviewStatisticsVO vo) {
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("销售趋势 | " + dateRangeLabel);
titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook()));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
String[] headers = {"日期", "销售额", "单量"};
Row headerRow = sheet.createRow(1);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
List<ShopOverviewStatisticsVO.TrendDataItem> dailySales = vo.getSalesAmountTrend().getDailyDataList();
List<ShopOverviewStatisticsVO.TrendDataItem> dailyOrders = vo.getOrderCountTrend() != null
? vo.getOrderCountTrend().getDailyDataList() : null;
Map<LocalDate, BigDecimal> salesMap = dailySales.stream()
.collect(Collectors.toMap(ShopOverviewStatisticsVO.TrendDataItem::getDate,
ShopOverviewStatisticsVO.TrendDataItem::getValue, (a, b) -> a));
Map<LocalDate, BigDecimal> ordersMap = dailyOrders != null
? dailyOrders.stream().collect(Collectors.toMap(
ShopOverviewStatisticsVO.TrendDataItem::getDate,
ShopOverviewStatisticsVO.TrendDataItem::getValue, (a, b) -> a))
: Collections.emptyMap();
LocalDate startDate = vo.getSalesAmountTrend().getDailyDataList().stream()
.map(ShopOverviewStatisticsVO.TrendDataItem::getDate).min(LocalDate::compareTo).orElse(null);
LocalDate endDate = vo.getSalesAmountTrend().getDailyDataList().stream()
.map(ShopOverviewStatisticsVO.TrendDataItem::getDate).max(LocalDate::compareTo).orElse(null);
int rowIdx = 2;
if (startDate != null && endDate != null) {
LocalDate current = startDate;
while (!current.isAfter(endDate)) {
Row row = sheet.createRow(rowIdx++);
BigDecimal sales = salesMap.getOrDefault(current, BigDecimal.ZERO);
BigDecimal orders = ordersMap.getOrDefault(current, BigDecimal.ZERO);
setCell(row, 0, current.format(DATE_FMT), dataStyle);
setCell(row, 1, nvl(sales, BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 2, nvl(orders, BigDecimal.ZERO).setScale(0, RoundingMode.HALF_UP).doubleValue(), dataStyle);
current = current.plusDays(1);
}
}
sheet.setColumnWidth(0, 3200);
sheet.setColumnWidth(1, 3200);
sheet.setColumnWidth(2, 3200);
}
private static BigDecimal nvl(BigDecimal val, BigDecimal defaultVal) {
return val != null ? val : defaultVal;
}
private static int nvl(Integer val, int defaultVal) {
return val != null ? val : defaultVal;
}
private CellStyle createTitleStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
font.setFontHeightInPoints((short) 14);
style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER);
return style;
}
private CellStyle createHeaderStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
return style;
}
private CellStyle createDataStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
DataFormat format = workbook.createDataFormat();
style.setDataFormat(format.getFormat("#,##0.00"));
return style;
}
private void setCell(Row row, int col, String value, CellStyle style) {
Cell cell = row.createCell(col);
cell.setCellValue(value != null ? value : "");
cell.setCellStyle(style);
}
private void setCell(Row row, int col, double value, CellStyle style) {
Cell cell = row.createCell(col);
cell.setCellValue(value);
cell.setCellStyle(style);
}
}
@@ -149,13 +149,13 @@ export namespace ShopVO {
salesAmountTrend?: TrendData;
/** 单量趋势分析 */
orderCountTrend?: TrendData;
/** 多商品数据横向对比(含合计行) */
/** 多商品数据横向汇总(含合计行) */
productOverview?: ProductOverview;
/** 品类多维度数据对比(含合计行) */
/** 品类多维度数据汇总(含合计行) */
categoryOverview?: CategoryOverview;
}
/** 商品对比数据 */
/** 商品汇总数据 */
export interface ProductComparison {
/** 商品ID */
productId: number;
@@ -193,7 +193,7 @@ export namespace ShopVO {
roi?: number;
}
/** 品类对比数据 */
/** 品类汇总数据 */
export interface CategoryComparison {
/** 品类ID */
categoryId: number;
@@ -249,7 +249,7 @@ export namespace ShopVO {
export interface ProductOverview {
/** 合计行 */
total: ProductComparison;
/** 各商品对比列表 */
/** 各商品汇总列表 */
products: ProductComparison[];
}
@@ -257,7 +257,7 @@ export namespace ShopVO {
export interface CategoryOverview {
/** 合计行 */
total: CategoryComparison;
/** 各品类对比列表 */
/** 各品类汇总列表 */
categories: CategoryComparison[];
}
}
@@ -23,9 +23,9 @@ export namespace CompanyOverviewVO {
shopSalesRatios?: ShopSalesRatio[];
/** 店铺效率象限(ROI vs 净利) */
shopEfficiencyQuadrants?: ShopEfficiencyQuadrant[];
/** 多店铺数据横向对比 */
/** 多店铺数据横向汇总 */
shopComparisons?: ShopOverview;
/** 多品类数据横向对比 */
/** 多品类数据横向汇总 */
categoryComparisons?: CategoryOverview;
/** 平台维度概览(包含合计行和平台列表) */
platformSummary?: PlatformOverview;
@@ -69,7 +69,7 @@ export namespace CompanyOverviewVO {
quadrant: number;
}
/** 店铺对比数据(16维度) */
/** 店铺汇总数据(16维度) */
export interface ShopComparison {
/** 店铺ID */
shopId: number;
@@ -115,7 +115,7 @@ export namespace CompanyOverviewVO {
roi?: number;
}
/** 品类对比数据 */
/** 品类汇总数据 */
export interface CategoryComparison {
/** 品类ID(未分配为null) */
categoryId?: number;
@@ -207,7 +207,7 @@ export namespace CompanyOverviewVO {
export interface ShopOverview {
/** 合计行 */
total: ShopComparison;
/** 各店铺对比列表 */
/** 各店铺汇总列表 */
shops: ShopComparison[];
}
@@ -215,7 +215,7 @@ export namespace CompanyOverviewVO {
export interface CategoryOverview {
/** 合计行 */
total: CategoryComparison;
/** 各品类对比列表 */
/** 各品类汇总列表 */
categories: CategoryComparison[];
}
}
@@ -14,6 +14,26 @@ function formatToken(token: null | string) {
return token ? `Bearer ${token}` : null;
}
/** 从 Content-Disposition 解析文件名(与后端 attachment; filename="..." 对齐) */
function parseFilenameFromContentDisposition(
contentDisposition: string | null,
): string | null {
if (!contentDisposition) return null;
const utf8Match = /filename\*=UTF-8''([^;\s]+)/i.exec(contentDisposition);
if (utf8Match?.[1]) {
try {
return decodeURIComponent(utf8Match[1].replace(/"/g, ''));
} catch {
return utf8Match[1].replace(/"/g, '');
}
}
const quoted = /filename="([^"]+)"/i.exec(contentDisposition);
if (quoted?.[1]) return quoted[1];
const plain = /filename=([^;\s]+)/i.exec(contentDisposition);
if (plain?.[1]) return plain[1].replace(/^"|"$/g, '');
return null;
}
export async function exportByPost(
url: string,
params: Record<string, unknown>,
@@ -55,11 +75,16 @@ export async function exportByPost(
return;
}
const headerName =
parseFilenameFromContentDisposition(
response.headers.get('Content-Disposition'),
) || filename;
// 触发浏览器下载
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = filename;
link.download = headerName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
@@ -69,7 +69,12 @@ const handleCategoryExport = async () => {
if (selectedExportCategoryIds.value.length > 0) {
Object.assign(params, { categoryIds: selectedExportCategoryIds.value });
}
await exportByPost('/ec/category-overview/export', params, '品类多维度经营明细.xlsx');
const [cStart, cEnd] = dateRange.value;
await exportByPost(
'/ec/category-overview/export',
params,
`品类概览_${cStart.format('YYYYMMDD')}-${cEnd.format('YYYYMMDD')}.xlsx`,
);
};
// 税率(公司/店铺概览共用持久化)
@@ -386,7 +391,7 @@ const handleExportCompanyOverview = async () => {
: undefined;
}
const filename = `公司概览_${startDate.format('YYYYMMDD')}_${endDate.format('YYYYMMDD')}.xlsx`;
const filename = `公司概览_${startDate.format('YYYYMMDD')}-${endDate.format('YYYYMMDD')}.xlsx`;
await exportByPost(
'/ec/store-overview/export',
{
@@ -427,7 +432,7 @@ const handlePlatformExport = async () => {
try {
exportLoading.value = true;
const [startDate, endDate] = dateRange.value;
const filename = `平台维度汇总_${startDate.format('YYYYMMDD')}_${endDate.format('YYYYMMDD')}.xlsx`;
const filename = `平台维度汇总_${startDate.format('YYYYMMDD')}-${endDate.format('YYYYMMDD')}.xlsx`;
await exportByPost(
'/ec/platform-overview/export',
{
@@ -232,7 +232,7 @@ const handleExportShopOverview = async () => {
exportLoading.value = true;
const shopName = overviewData.value?.shopName || `店铺${shopId.value}`;
const [startDate, endDate] = dateRange.value;
const filename = `${shopName}_概览_${startDate.format('YYYYMMDD')}_${endDate.format('YYYYMMDD')}.xlsx`;
const filename = `${shopName}_概览_${startDate.format('YYYYMMDD')}-${endDate.format('YYYYMMDD')}.xlsx`;
await exportByPost(
'/ec/shop/export-overview',
{
@@ -270,7 +270,12 @@ const handleCategoryExport = async () => {
if (selectedExportCategoryIds.value.length > 0) {
params.categoryIds = selectedExportCategoryIds.value;
}
await exportByPost('/ec/shop/export-category', params, '门店品类汇总.xlsx');
const [catStart, catEnd] = dateRange.value;
await exportByPost(
'/ec/shop/export-category',
params,
`门店品类汇总_${catStart.format('YYYYMMDD')}-${catEnd.format('YYYYMMDD')}.xlsx`,
);
} finally {
categoryExportLoading.value = false;
}