refactor: 导出服务重构,复用概览统计数据源并简化实现

- ExportService 全店导出复用 CompanyOverviewService 同源数据
- CategoryExportExcelService 全店品类导出新增独立入口
- 导出 Excel 均支持「汇总 + 销售趋势」多表结构
- 统一单元格样式:垂直居中对齐

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
小蟑螂
2026-05-08 12:14:49 +08:00
co-authored by Claude Opus 4.7
parent fc984be8b6
commit 04f6c413af
4 changed files with 708 additions and 961 deletions
@@ -1,6 +1,7 @@
package top.xyquan.ecomdmbbackend.modules.ecom.overview.service; 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.CategoryExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO;
/** /**
* 按品类维度导出 Excel(店铺「门店品类汇总」与全店「品类概览」共用实现) * 按品类维度导出 Excel(店铺「门店品类汇总」与全店「品类概览」共用实现)
@@ -8,4 +9,10 @@ import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportD
public interface CategoryExportExcelService { public interface CategoryExportExcelService {
byte[] exportCategoryOverview(CategoryExportDTO dto); byte[] exportCategoryOverview(CategoryExportDTO dto);
/**
* 全店按品类:与 {@link top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService#getCompanyOverview} 同源,
* 生成「品类汇总 + 销售趋势」两表。
*/
byte[] exportStoreCategoryFromOverview(CategoryExportDTO dto, CompanyOverviewVO overview);
} }
@@ -34,6 +34,7 @@ import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@@ -82,194 +83,53 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
@Override @Override
public byte[] exportCategoryOverview(CategoryExportDTO dto) { public byte[] exportCategoryOverview(CategoryExportDTO dto) {
if (dto.getShopId() != null) { if (dto.getShopId() == null) {
return exportShopCategoryViaOverview(dto); throw new BusinessException("全店按品类导出请使用 ExportService.exportCategoryOverview");
} }
Long companyId = currentUserContext.getCurrentCompanyId(); return exportShopCategoryViaOverview(dto);
}
@Override
public byte[] exportStoreCategoryFromOverview(CategoryExportDTO dto, CompanyOverviewVO overview) {
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange()); LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange());
LocalDate startDate = dateRange[0]; LocalDate startDate = dateRange[0];
LocalDate endDate = dateRange[1]; LocalDate endDate = dateRange[1];
LocalDateTime startDateTime = startDate.atStartOfDay(); String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT);
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
OrderStatusStatSets stat = exportStatusRangeHelper.resolveStat(companyId); CompanyOverviewVO.CategoryOverview co = overview.getCategorySummary();
List<Long> unionStatusIds = stat.getUnionStatusIds(); List<CompanyOverviewVO.CategorySummary> catRows = (co != null && co.getCategories() != null)
? new ArrayList<>(co.getCategories())
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>(); : new ArrayList<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.ge(OrderPO::getOrderTime, startDateTime)
.le(OrderPO::getOrderTime, endDateTime);
if (!unionStatusIds.isEmpty()) {
orderWrapper.in(OrderPO::getStatusId, unionStatusIds);
} 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> specIds = orders.stream()
.map(OrderPO::getProductSpecId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
Map<Long, Long> specIdToProductId = new HashMap<>();
if (!specIds.isEmpty()) {
List<ProductSpecPO> specs = productSpecMapper.selectList(new LambdaQueryWrapper<ProductSpecPO>()
.in(ProductSpecPO::getId, specIds)
.select(ProductSpecPO::getId, ProductSpecPO::getProductId));
for (ProductSpecPO s : specs) {
specIdToProductId.put(s.getId(), s.getProductId());
}
}
List<Long> productIds = specIdToProductId.values().stream().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 sid = order.getProductSpecId();
Long pid = sid != null ? specIdToProductId.get(sid) : null;
Long categoryId = pid != null ? productCategoryMap.get(pid) : null;
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.CategorySummary> 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(stat::receivedForSales)
.reduce(BigDecimal.ZERO, BigDecimal::add);
int orderCount = (int) categoryOrders.stream().filter(o -> stat.includesSales(o.getStatusId())).count();
BigDecimal refundAmount = categoryOrders.stream()
.map(stat::receivedForRefund)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal productCost = categoryOrders.stream()
.map(stat::productCostForStats)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal shippingCost = categoryOrders.stream()
.map(stat::freightCostForStats)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal otherCost = categoryOrders.stream()
.map(stat::otherCostForStats)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Map<Long, BigDecimal> categorySalesByShop = categoryOrders.stream()
.collect(Collectors.groupingBy(OrderPO::getShopId,
Collectors.reducing(BigDecimal.ZERO, stat::receivedForSales, 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)
.subtract(totalPromotionFee).subtract(totalBrushFee);
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.CategorySummary data = new CompanyOverviewVO.CategorySummary();
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.setTotalCost(totalCost);
data.setRefundAmount(refundAmount);
data.setTotalPromotionFee(totalPromotionFee);
data.setBrushFee(totalBrushFee);
data.setFeeRatio(feeRatio);
data.setTotalProfitBeforeTax(profitBeforeTax);
data.setSalesTaxAmount(salesTaxAmount);
data.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
data.setRoi(roi);
categoryDataList.add(data);
}
if (dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty()) { if (dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty()) {
Set<Long> allowedIds = new HashSet<>(dto.getCategoryIds()); Set<Long> allowed = new HashSet<>(dto.getCategoryIds());
categoryDataList = categoryDataList.stream() catRows = catRows.stream()
.filter(c -> allowedIds.contains(c.getCategoryId() != null ? c.getCategoryId() : 0L)) .filter(c -> allowed.contains(c.getCategoryId() != null ? c.getCategoryId() : 0L))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
categoryDataList.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount).reversed()); List<ShopOverviewStatisticsVO.CategorySummary> shopRows = catRows.stream()
String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT);
List<ShopOverviewStatisticsVO.CategorySummary> shopRows = categoryDataList.stream()
.map(this::toShopCategorySummary) .map(this::toShopCategorySummary)
.collect(Collectors.toList()); .collect(Collectors.toList());
ShopOverviewStatisticsVO.CategorySummary totalRow = aggregateCategoryTotals(shopRows, taxRate);
boolean categoryFiltered = dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty();
ShopOverviewStatisticsVO.CategorySummary totalRow = categoryFiltered
? aggregateCategoryTotals(shopRows, taxRate)
: (co != null && co.getTotal() != null
? toShopCategorySummary(co.getTotal())
: aggregateCategoryTotals(shopRows, taxRate));
try (Workbook workbook = new XSSFWorkbook()) { try (Workbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("品类汇总"); Sheet sheet = workbook.createSheet("汇总");
writeCategoryMultidimensionalSheet( writeCategoryMultidimensionalSheet(
sheet, "全店 - 品类多维度损益汇总", dateRangeLabel, shopRows, totalRow, taxRate); sheet, "全店 - 品类多维度损益汇总", dateRangeLabel, shopRows, totalRow, taxRate);
if (overview.getSalesAmountTrend() != null
&& overview.getSalesAmountTrend().getDailyDataList() != null
&& !overview.getSalesAmountTrend().getDailyDataList().isEmpty()) {
Sheet trendSheet = workbook.createSheet("销售趋势");
writeCompanyOverviewTrendSheet(trendSheet, "全店", dateRangeLabel, overview);
}
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out); workbook.write(out);
return out.toByteArray(); return out.toByteArray();
@@ -320,6 +180,12 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
try (Workbook workbook = new XSSFWorkbook()) { try (Workbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("品类汇总"); Sheet sheet = workbook.createSheet("品类汇总");
writeCategoryMultidimensionalSheet(sheet, shopTitle, dateRangeLabel, rows, totalRow, taxRate); writeCategoryMultidimensionalSheet(sheet, shopTitle, dateRangeLabel, rows, totalRow, taxRate);
if (vo.getSalesAmountTrend() != null
&& vo.getSalesAmountTrend().getDailyDataList() != null
&& !vo.getSalesAmountTrend().getDailyDataList().isEmpty()) {
Sheet trendSheet = workbook.createSheet("销量趋势");
writeShopSalesTrendSheet(trendSheet, shopTitle, dateRangeLabel, vo);
}
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out); workbook.write(out);
return out.toByteArray(); return out.toByteArray();
@@ -329,6 +195,140 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
} }
} }
/** 与店铺概览销量趋势同源({@link ShopOverviewStatisticsVO} 日销售额、日单量)。 */
private void writeShopSalesTrendSheet(
Sheet sheet, String shopContextTitle, String dateRangeLabel, ShopOverviewStatisticsVO vo) {
Workbook wb = sheet.getWorkbook();
CellStyle headerStyle = createHeaderStyle(wb);
CellStyle dataStyle = createDataStyle(wb);
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue(shopContextTitle + " - 销量趋势 | " + dateRangeLabel);
titleCell.setCellStyle(createTitleStyle(wb));
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 = dailySales.stream()
.map(ShopOverviewStatisticsVO.TrendDataItem::getDate)
.min(LocalDate::compareTo)
.orElse(null);
LocalDate endDate = dailySales.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, sales.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 2, orders.setScale(0, RoundingMode.HALF_UP).doubleValue(), dataStyle);
current = current.plusDays(1);
}
}
sheet.setColumnWidth(0, 3200);
sheet.setColumnWidth(1, 3200);
sheet.setColumnWidth(2, 3200);
}
/** 全店概览 {@link CompanyOverviewVO} 的日销售额、日单量趋势(与 /ec/store/overview 同源)。 */
private void writeCompanyOverviewTrendSheet(
Sheet sheet, String contextTitle, String dateRangeLabel, CompanyOverviewVO vo) {
Workbook wb = sheet.getWorkbook();
CellStyle headerStyle = createHeaderStyle(wb);
CellStyle dataStyle = createDataStyle(wb);
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue(contextTitle + " - 销售趋势 | " + dateRangeLabel);
titleCell.setCellStyle(createTitleStyle(wb));
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<CompanyOverviewVO.TrendDataItem> dailySales = vo.getSalesAmountTrend().getDailyDataList();
List<CompanyOverviewVO.TrendDataItem> dailyOrders = vo.getOrderCountTrend() != null
? vo.getOrderCountTrend().getDailyDataList()
: null;
Map<LocalDate, BigDecimal> salesMap = dailySales.stream()
.collect(Collectors.toMap(
CompanyOverviewVO.TrendDataItem::getDate,
CompanyOverviewVO.TrendDataItem::getValue,
(a, b) -> a));
Map<LocalDate, BigDecimal> ordersMap = dailyOrders != null
? dailyOrders.stream()
.collect(Collectors.toMap(
CompanyOverviewVO.TrendDataItem::getDate,
CompanyOverviewVO.TrendDataItem::getValue,
(a, b) -> a))
: Collections.emptyMap();
LocalDate startDate = dailySales.stream()
.map(CompanyOverviewVO.TrendDataItem::getDate)
.min(LocalDate::compareTo)
.orElse(null);
LocalDate endDate = dailySales.stream()
.map(CompanyOverviewVO.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, sales.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 2, orders.setScale(0, RoundingMode.HALF_UP).doubleValue(), dataStyle);
current = current.plusDays(1);
}
}
sheet.setColumnWidth(0, 3200);
sheet.setColumnWidth(1, 3200);
sheet.setColumnWidth(2, 3200);
}
private ShopOverviewStatisticsVO.CategorySummary toShopCategorySummary(CompanyOverviewVO.CategorySummary c) { private ShopOverviewStatisticsVO.CategorySummary toShopCategorySummary(CompanyOverviewVO.CategorySummary c) {
ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary(); ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary();
s.setCategoryId(c.getCategoryId() != null ? c.getCategoryId() : 0L); s.setCategoryId(c.getCategoryId() != null ? c.getCategoryId() : 0L);
@@ -511,6 +511,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
font.setFontHeightInPoints((short) 14); font.setFontHeightInPoints((short) 14);
style.setFont(font); style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER); style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style; return style;
} }
@@ -526,6 +527,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
style.setBorderLeft(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER); style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style; return style;
} }
@@ -535,6 +537,8 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
style.setBorderTop(BorderStyle.THIN); style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
DataFormat format = workbook.createDataFormat(); DataFormat format = workbook.createDataFormat();
style.setDataFormat(format.getFormat("#,##0.00")); style.setDataFormat(format.getFormat("#,##0.00"));
return style; return style;
@@ -18,7 +18,6 @@ import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -56,23 +55,28 @@ public class ShopExportServiceImpl implements ShopExportService {
String exportType = dto.getExportType() == null ? "all" : dto.getExportType(); String exportType = dto.getExportType() == null ? "all" : dto.getExportType();
try (Workbook workbook = new XSSFWorkbook()) { try (Workbook workbook = new XSSFWorkbook()) {
if ("summary".equals(exportType) || "all".equals(exportType)) { // 与店铺概览一致:仅「按商品汇总」+「销量趋势」,不再导出第一张「汇总」指标表
Sheet summarySheet = workbook.createSheet("汇总"); if (("product".equals(exportType) || "all".equals(exportType) || "summary".equals(exportType))
createShopSummarySheetFromVO(summarySheet, vo, dateRangeLabel); && vo.getProductOverview() != null) {
List<ShopOverviewStatisticsVO.ProductSummary> products = vo.getProductOverview().getProducts() != null
? vo.getProductOverview().getProducts()
: Collections.emptyList();
ShopOverviewStatisticsVO.ProductSummary totalRow = vo.getProductOverview().getTotal();
Sheet productSheet = workbook.createSheet("按商品汇总");
createProductDetailSheetFromVO(
productSheet,
vo.getShopName(),
dateRangeLabel,
products,
totalRow,
taxRate);
} }
if (("product".equals(exportType) || "all".equals(exportType)) if (("trend".equals(exportType) || "all".equals(exportType) || "summary".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() != null
&& vo.getSalesAmountTrend().getDailyDataList() != null && vo.getSalesAmountTrend().getDailyDataList() != null
&& !vo.getSalesAmountTrend().getDailyDataList().isEmpty()) { && !vo.getSalesAmountTrend().getDailyDataList().isEmpty()) {
Sheet trendSheet = workbook.createSheet("销售趋势"); Sheet trendSheet = workbook.createSheet("销量趋势");
createTrendSheetFromVO(trendSheet, dateRangeLabel, vo); createTrendSheetFromVO(trendSheet, dateRangeLabel, vo);
} }
@@ -90,122 +94,34 @@ public class ShopExportServiceImpl implements ShopExportService {
return categoryExportExcelService.exportCategoryOverview(dto); return categoryExportExcelService.exportCategoryOverview(dto);
} }
private void createShopSummarySheetFromVO(Sheet sheet, ShopOverviewStatisticsVO vo, String dateRangeLabel) { /**
CellStyle titleStyle = createTitleStyle(sheet.getWorkbook()); * 列顺序与概览页 {@code ProductComparisonTable.vue} 一致;费比 % 为「×100 后一位小数」与前端展示一致;合计行与 {@code productOverview.total} 同源。
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook()); */
CellStyle dataStyle = createDataStyle(sheet.getWorkbook()); private void createProductDetailSheetFromVO(
Sheet sheet,
List<SummaryField> fields = Arrays.asList( String shopName,
new SummaryField("销售额", "totalSalesAmount", true), String dateRangeLabel,
new SummaryField("单量", "totalOrderCount", false), List<ShopOverviewStatisticsVO.ProductSummary> products,
new SummaryField("客单价", "avgOrderValue", true), ShopOverviewStatisticsVO.ProductSummary totalRow,
new SummaryField("推广费", "totalPromotionFee", true), BigDecimal taxRate) {
new SummaryField("费比", "averageFeeRatio", true), Workbook wb = sheet.getWorkbook();
new SummaryField("退款金额", "refundAmount", true), CellStyle titleStyle = createTitleStyle(wb);
new SummaryField("税前盈亏", "profitBeforeTax", true), CellStyle headerStyle = createHeaderStyle(wb);
new SummaryField("税额", "totalTaxAmount", true), CellStyle dataStyle = createDataStyle(wb);
new SummaryField("税后盈亏", "totalNetProfitAfterTax", true), CellStyle totalStyle = createBoldDataStyle(wb);
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.ProductSummary> products,
BigDecimal taxRate) {
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("核心商品多维度损益汇总表 | " + dateRangeLabel);
titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook()));
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
String titlePrefix = (shopName != null && !shopName.isBlank() ? shopName : "店铺") + " - 按商品汇总";
String taxLabel = (taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP)).toPlainString() + "%税额"; String taxLabel = (taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP)).toPlainString() + "%税额";
String[] headers = { String[] headers = {
"商品详情", "销售额", "单量", "客单价", "商品", "销售额", "单量", "客单价",
"商品成本", "运费", "其他成本", "总成本", "退款金额", "推广费", "刷单费用", "商品成本", "运费", "其他成本", "总成本", "退款金额", "推广费", "刷单费用",
"费比(%)", "单品ROI", "税前盈亏", taxLabel, "税后净利" "费比 %", "单品 ROI", "税前盈亏", taxLabel, "税后净利"
}; };
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue(titlePrefix + " | " + dateRangeLabel);
titleCell.setCellStyle(titleStyle);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1)); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1));
Row headerRow = sheet.createRow(1); Row headerRow = sheet.createRow(1);
@@ -218,37 +134,57 @@ public class ShopExportServiceImpl implements ShopExportService {
int rowIdx = 2; int rowIdx = 2;
for (ShopOverviewStatisticsVO.ProductSummary p : products) { for (ShopOverviewStatisticsVO.ProductSummary p : products) {
Row row = sheet.createRow(rowIdx++); Row row = sheet.createRow(rowIdx++);
setCell(row, 0, p.getProductName() + (p.getProductCode() != null ? "\n编码: " + p.getProductCode() : ""), dataStyle); fillProductDataRow(row, p, dataStyle, false);
setCell(row, 1, nvl(p.getSalesAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); }
setCell(row, 2, (double) nvl(p.getOrderCount(), 0), dataStyle); if (totalRow != null) {
setCell(row, 3, nvl(p.getAverageOrderValue(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); fillProductDataRow(sheet.createRow(rowIdx), totalRow, totalStyle, true);
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.getTotalCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 8, nvl(p.getRefundAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 9, nvl(p.getTotalPromotionFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 10, nvl(p.getBrushFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 11, nvl(p.getFeeRatio(), BigDecimal.ZERO).setScale(4, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 12, nvl(p.getRoi(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 13, nvl(p.getTotalProfitBeforeTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 14, nvl(p.getSalesTaxAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 15, nvl(p.getProfitAfterTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
} }
sheet.setColumnWidth(0, 5000); sheet.setColumnWidth(0, 5200);
for (int i = 1; i < headers.length; i++) { for (int i = 1; i < headers.length; i++) {
sheet.setColumnWidth(i, 3200); sheet.setColumnWidth(i, 3400);
} }
} }
private void fillProductDataRow(
Row row,
ShopOverviewStatisticsVO.ProductSummary p,
CellStyle style,
boolean isTotalRow) {
String nameCol = isTotalRow
? "合计"
: (p.getProductName() != null ? p.getProductName() : "")
+ (p.getProductCode() != null && !p.getProductCode().isBlank()
? "\n编码: " + p.getProductCode()
: "");
setCell(row, 0, nameCol, style);
setCell(row, 1, nvl(p.getSalesAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 2, (double) nvl(p.getOrderCount(), 0), style);
setCell(row, 3, nvl(p.getAverageOrderValue(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 4, nvl(p.getProductCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 5, nvl(p.getShippingCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 6, nvl(p.getOtherCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 7, nvl(p.getTotalCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 8, nvl(p.getRefundAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 9, nvl(p.getTotalPromotionFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 10, nvl(p.getBrushFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
BigDecimal fr = p.getFeeRatio();
double feePct = fr == null ? 0.0
: fr.multiply(new BigDecimal("100")).setScale(1, RoundingMode.HALF_UP).doubleValue();
setCell(row, 11, feePct, style);
setCell(row, 12, nvl(p.getRoi(), BigDecimal.ZERO).setScale(4, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 13, nvl(p.getTotalProfitBeforeTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 14, nvl(p.getSalesTaxAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 15, nvl(p.getProfitAfterTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
}
private void createTrendSheetFromVO(Sheet sheet, String dateRangeLabel, ShopOverviewStatisticsVO vo) { private void createTrendSheetFromVO(Sheet sheet, String dateRangeLabel, ShopOverviewStatisticsVO vo) {
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook()); CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook()); CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
Row titleRow = sheet.createRow(0); Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0); Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("销售趋势 | " + dateRangeLabel); titleCell.setCellValue("销量趋势 | " + dateRangeLabel);
titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook())); titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook()));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
@@ -312,6 +248,7 @@ public class ShopExportServiceImpl implements ShopExportService {
font.setFontHeightInPoints((short) 14); font.setFontHeightInPoints((short) 14);
style.setFont(font); style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER); style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style; return style;
} }
@@ -327,6 +264,7 @@ public class ShopExportServiceImpl implements ShopExportService {
style.setBorderLeft(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER); style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style; return style;
} }
@@ -336,11 +274,21 @@ public class ShopExportServiceImpl implements ShopExportService {
style.setBorderTop(BorderStyle.THIN); style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
DataFormat format = workbook.createDataFormat(); DataFormat format = workbook.createDataFormat();
style.setDataFormat(format.getFormat("#,##0.00")); style.setDataFormat(format.getFormat("#,##0.00"));
return style; return style;
} }
private CellStyle createBoldDataStyle(Workbook workbook) {
CellStyle style = createDataStyle(workbook);
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
return style;
}
private void setCell(Row row, int col, String value, CellStyle style) { private void setCell(Row row, int col, String value, CellStyle style) {
Cell cell = row.createCell(col); Cell cell = row.createCell(col);
cell.setCellValue(value != null ? value : ""); cell.setCellValue(value != null ? value : "");