feat(company-overview): 品类多维度经营明细对比导出功能

- 新增指定品类导出和导出全部两种模式
- 表头加全选复选框,每行加单选复选框
- CategoryComparisonTable 新增 categoryExportMode/selectedExportCategoryIds props
- index.vue 新增品类导出状态和 handleCategoryExport
- apis.ts 新增 exportCategoryOverviewApi
- 修复空状态 colspan
This commit is contained in:
小蟑螂
2026-04-21 17:48:07 +08:00
parent 046fe1ea3f
commit 80c0e6f4aa
7 changed files with 445 additions and 4 deletions
@@ -7,6 +7,7 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
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.ShopExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ExportService;
@@ -52,6 +53,17 @@ public class ExportController {
writeExcel(response, filename, data);
}
@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";
writeExcel(response, filename, data);
}
private void writeExcel(HttpServletResponse response, String filename, byte[] data) {
try {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
@@ -0,0 +1,31 @@
package top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
/**
* 品类概览导出DTO
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@Schema(description = "品类概览导出DTO")
public class CategoryExportDTO {
@Schema(description = "日期范围数组", example = "[\"2024-01-01\", \"2024-01-31\"]", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "日期范围不能为空")
@Size(min = 1, max = 2, message = "日期范围数组必须包含1-2个日期")
private List<LocalDate> dateRange;
@Schema(description = "品类ID列表,不传则导出全部品类", example = "[1, 2]")
private List<Long> categoryIds;
@Schema(description = "税率,默认 0.04", example = "0.04")
private BigDecimal taxRate = new BigDecimal("0.04");
}
@@ -1,5 +1,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.ShopExportDTO;
@@ -23,4 +24,12 @@ public interface ExportService {
* @return Excel文件字节数组
*/
byte[] exportShopOverview(ShopExportDTO dto);
/**
* 导出品类概览Excel
*
* @param dto 导出参数
* @return Excel文件字节数组
*/
byte[] exportCategoryOverview(CategoryExportDTO dto);
}
@@ -9,8 +9,10 @@ import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
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.ShopExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ExportService;
@@ -22,6 +24,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusSe
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;
@@ -55,6 +59,7 @@ public class ExportServiceImpl implements ExportService {
private final ProductService productService;
private final OrderStatusService orderStatusService;
private final ShopOverviewStatisticsService shopOverviewStatisticsService;
private final CategoryService categoryService;
public ExportServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper,
@@ -64,7 +69,8 @@ public class ExportServiceImpl implements ExportService {
ShopService shopService,
ProductService productService,
OrderStatusService orderStatusService,
ShopOverviewStatisticsService shopOverviewStatisticsService) {
ShopOverviewStatisticsService shopOverviewStatisticsService,
CategoryService categoryService) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
@@ -74,6 +80,7 @@ public class ExportServiceImpl implements ExportService {
this.productService = productService;
this.orderStatusService = orderStatusService;
this.shopOverviewStatisticsService = shopOverviewStatisticsService;
this.categoryService = categoryService;
}
@Override
@@ -212,6 +219,254 @@ public class ExportServiceImpl implements ExportService {
}
}
@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);
Long refundStatusId = getRefundStatusId(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 -> refundStatusId != null && refundStatusId.equals(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);
}
}
// ==================== Sheet 构建方法 ====================
private void createSummarySheet(Sheet sheet, String dateRangeLabel, BigDecimal totalSales, BigDecimal totalOrders,