feat(ecom-dmb): 新增平台维度汇总功能

后端:
- CompanyOverviewVO 新增 platformSummary 平台维度汇总数据
- CompanyOverviewServiceImpl 新增 calculatePlatformSummary() 方法,按平台聚合数据
- PlatformExportDTO 导出参数 DTO
- ExportService/ExportServiceImpl 新增 exportPlatformOverview 导出方法
- ExportController 新增 POST /ec/platform-overview/export 接口

前端:
- PlatformSummaryCard 组件显示各平台多维度经营明细对比
- 支持指定平台导出和导出全部两种模式
- 组件优先使用动态数据,无数据时降级到 mock 数据
- types.vo.ts 新增 PlatformSummary 类型定义
- index.vue 集成平台导出功能
This commit is contained in:
小蟑螂
2026-04-23 11:58:59 +08:00
parent 1dac4de215
commit cfc0078aba
9 changed files with 1132 additions and 3 deletions
@@ -9,6 +9,7 @@ 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.PlatformExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ExportService;
@@ -75,6 +76,17 @@ public class ExportController {
writeExcel(response, filename, data);
}
@Operation(summary = "导出平台维度汇总Excel", description = "导出平台维度汇总数据为Excel文件,支持指定平台或导出全部")
@PostMapping("/platform-overview/export")
@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";
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 io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
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 PlatformExportDTO {
@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> platformIds;
@Schema(description = "税率,默认 0.04", example = "0.04")
private BigDecimal taxRate = new BigDecimal("0.04");
}
@@ -79,6 +79,12 @@ public class CompanyOverviewVO {
@Schema(description = "多品类数据横向对比")
private List<CategoryComparison> categoryComparisons;
/**
* 平台维度汇总
*/
@Schema(description = "平台维度汇总")
private List<PlatformSummary> platformSummary;
/**
* 汇总ROI
*/
@@ -287,5 +293,72 @@ public class CompanyOverviewVO {
@Schema(description = "ROI", example = "1.5")
private BigDecimal roi;
}
/**
* 平台维度汇总
*/
@Data
@Schema(description = "平台维度汇总")
public static class PlatformSummary {
@Schema(description = "平台ID", example = "1")
private Long platformId;
@Schema(description = "平台名称", example = "淘宝")
private String platformName;
@Schema(description = "目标单量", example = "5000")
private Integer targetOrderCount;
@Schema(description = "单量达成率", example = "90.4")
private BigDecimal orderCountAchievementRate;
@Schema(description = "目标销售额", example = "320000.00")
private BigDecimal targetAmount;
@Schema(description = "销售额达成率", example = "88.6")
private BigDecimal salesAmountAchievementRate;
@Schema(description = "销售额", example = "283600.00")
private BigDecimal salesAmount;
@Schema(description = "单量", example = "4521")
private Integer orderCount;
@Schema(description = "客单价", example = "62.70")
private BigDecimal averageOrderValue;
@Schema(description = "商品成本", example = "156000.00")
private BigDecimal productCost;
@Schema(description = "运费", example = "8500.00")
private BigDecimal shippingCost;
@Schema(description = "其他成本", example = "3200.00")
private BigDecimal otherCost;
@Schema(description = "退款金额", example = "12600.00")
private BigDecimal refundAmount;
@Schema(description = "推广费", example = "9800.00")
private BigDecimal totalPromotionFee;
@Schema(description = "刷单费用", example = "4200.00")
private BigDecimal brushFee;
@Schema(description = "费比", example = "0.187")
private BigDecimal feeRatio;
@Schema(description = "税前盈亏", example = "98600.00")
private BigDecimal totalProfitBeforeTax;
@Schema(description = "销售额4%税额", example = "11344.00")
private BigDecimal salesTaxAmount;
@Schema(description = "ROI", example = "2.34")
private BigDecimal roi;
@Schema(description = "税后盈亏", example = "87256.00")
private BigDecimal profitAfterTax;
}
}
@@ -2,6 +2,7 @@ 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;
/**
@@ -32,4 +33,12 @@ public interface ExportService {
* @return Excel文件字节数组
*/
byte[] exportCategoryOverview(CategoryExportDTO dto);
/**
* 导出平台维度汇总Excel
*
* @param dto 导出参数
* @return Excel文件字节数组
*/
byte[] exportPlatformOverview(PlatformExportDTO dto);
}
@@ -224,7 +224,12 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
orders, promotionFees, brushOrders, refundStatusId, companyId, startDate, endDate);
overviewVO.setCategoryComparisons(categoryComparisons);
// 11. 汇总ROI和总税后盈亏
// 11. 平台维度汇总
List<CompanyOverviewVO.PlatformSummary> platformSummary = calculatePlatformSummary(
shops, orders, promotionFees, brushOrders, refundStatusId, companyId, startDate, endDate);
overviewVO.setPlatformSummary(platformSummary);
// 12. 汇总ROI和总税后盈亏
BigDecimal totalROI = calculateTotalROI(orders, promotionFees, brushOrders, refundStatusId);
overviewVO.setTotalROI(totalROI);
overviewVO.setTotalProfitAfterTax(totalNetProfitAfterTax);
@@ -897,5 +902,211 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
.map(OrderStatusPO::getId)
.collect(Collectors.toList());
}
/**
* 计算平台维度汇总
*/
private List<CompanyOverviewVO.PlatformSummary> calculatePlatformSummary(
List<ShopPO> shops, List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, Long refundStatusId, Long companyId,
LocalDate startDate, LocalDate endDate) {
List<CompanyOverviewVO.PlatformSummary> platformSummaries = new ArrayList<>();
// 获取所有平台
List<PlatformPO> allPlatforms = platformMapper.selectList(null);
Map<Long, PlatformPO> platformMap = allPlatforms.stream()
.collect(Collectors.toMap(PlatformPO::getId, p -> p));
// 按平台分组店铺
Map<Long, List<ShopPO>> shopsByPlatform = shops.stream()
.filter(shop -> shop.getPlatformId() != null)
.collect(Collectors.groupingBy(ShopPO::getPlatformId));
// 生成目标月份列表
List<LocalDate> targetMonths = new ArrayList<>();
LocalDate currentMonth = startDate.withDayOfMonth(1);
LocalDate endMonth = endDate.withDayOfMonth(1);
while (!currentMonth.isAfter(endMonth)) {
targetMonths.add(currentMonth);
currentMonth = currentMonth.plusMonths(1);
}
// 查询所有店铺的目标数据
LambdaQueryWrapper<ShopMonthlyTargetPO> targetWrapper = new LambdaQueryWrapper<>();
targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId)
.in(ShopMonthlyTargetPO::getTargetMonth, targetMonths);
List<ShopMonthlyTargetPO> allTargets = shopMonthlyTargetMapper.selectList(targetWrapper);
Map<Long, List<ShopMonthlyTargetPO>> targetsByShop = allTargets.stream()
.collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId));
// 按店铺分组订单和费用
Map<Long, List<OrderPO>> ordersByShop = orders.stream()
.collect(Collectors.groupingBy(OrderPO::getShopId));
Map<Long, List<PromotionFeePO>> promotionFeesByShop = promotionFees.stream()
.collect(Collectors.groupingBy(PromotionFeePO::getShopId));
Map<Long, List<BrushOrderPO>> brushOrdersByShop = brushOrders.stream()
.collect(Collectors.groupingBy(BrushOrderPO::getShopId));
// 计算每个平台的数据
for (Map.Entry<Long, List<ShopPO>> entry : shopsByPlatform.entrySet()) {
Long platformId = entry.getKey();
List<ShopPO> platformShops = entry.getValue();
PlatformPO platform = platformMap.get(platformId);
if (platform == null) continue;
// 汇总该平台下所有店铺的数据
BigDecimal totalSalesAmount = BigDecimal.ZERO;
int totalOrderCount = 0;
BigDecimal totalRefundAmount = BigDecimal.ZERO;
BigDecimal totalProductCost = BigDecimal.ZERO;
BigDecimal totalShippingCost = BigDecimal.ZERO;
BigDecimal totalOtherCost = BigDecimal.ZERO;
BigDecimal totalPromotionFee = BigDecimal.ZERO;
BigDecimal totalBrushFee = BigDecimal.ZERO;
BigDecimal totalTargetAmount = BigDecimal.ZERO;
int totalTargetOrderCount = 0;
for (ShopPO shop : platformShops) {
List<OrderPO> shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<PromotionFeePO> shopPromotionFees = promotionFeesByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<BrushOrderPO> shopBrushOrders = brushOrdersByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<ShopMonthlyTargetPO> shopTargets = targetsByShop.getOrDefault(shop.getId(), new ArrayList<>());
// 销售额
BigDecimal shopSales = shopOrders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalSalesAmount = totalSalesAmount.add(shopSales);
// 订单数
totalOrderCount += shopOrders.size();
// 退款金额
BigDecimal shopRefund = shopOrders.stream()
.filter(order -> refundStatusId != null && refundStatusId.equals(order.getStatusId()))
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalRefundAmount = totalRefundAmount.add(shopRefund);
// 商品成本
BigDecimal shopProductCost = shopOrders.stream()
.map(order -> {
BigDecimal cost = order.getProductCost() != null ? order.getProductCost() : BigDecimal.ZERO;
Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1;
return cost.multiply(new BigDecimal(quantity));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalProductCost = totalProductCost.add(shopProductCost);
// 运费成本
BigDecimal shopShippingCost = shopOrders.stream()
.map(order -> {
BigDecimal cost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO;
Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1;
return cost.multiply(new BigDecimal(quantity));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalShippingCost = totalShippingCost.add(shopShippingCost);
// 其他成本
BigDecimal shopOtherCost = shopOrders.stream()
.map(order -> order.getOtherCost() != null ? order.getOtherCost() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalOtherCost = totalOtherCost.add(shopOtherCost);
// 推广费
BigDecimal shopPromoFee = shopPromotionFees.stream()
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalPromotionFee = totalPromotionFee.add(shopPromoFee);
// 刷单费
BigDecimal shopBrush = shopBrushOrders.stream()
.map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalBrushFee = totalBrushFee.add(shopBrush);
// 目标金额和目标单量
BigDecimal shopTargetAmount = shopTargets.stream()
.map(target -> target.getTargetAmount() != null ? target.getTargetAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalTargetAmount = totalTargetAmount.add(shopTargetAmount);
int shopTargetOrderCount = shopTargets.stream()
.mapToInt(target -> target.getTargetOrderCount() != null ? target.getTargetOrderCount() : 0)
.sum();
totalTargetOrderCount += shopTargetOrderCount;
}
// 计算派生指标
BigDecimal averageOrderValue = BigDecimal.ZERO;
if (totalOrderCount > 0) {
averageOrderValue = totalSalesAmount.divide(new BigDecimal(totalOrderCount), 2, RoundingMode.HALF_UP);
}
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
BigDecimal profitBeforeTax = totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount);
BigDecimal salesTaxAmount = totalSalesAmount.multiply(taxRate);
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount);
BigDecimal roi = BigDecimal.ZERO;
if (totalPromotionFee.compareTo(BigDecimal.ZERO) > 0) {
roi = totalSalesAmount.subtract(totalRefundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP);
}
BigDecimal feeRatio = BigDecimal.ZERO;
if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
feeRatio = totalPromotionFee.add(totalBrushFee).divide(totalSalesAmount, 4, RoundingMode.HALF_UP);
}
// 计算达成率
BigDecimal salesAmountAchievementRate = BigDecimal.ZERO;
if (totalTargetAmount.compareTo(BigDecimal.ZERO) > 0) {
salesAmountAchievementRate = totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"));
} else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
salesAmountAchievementRate = new BigDecimal("100");
}
BigDecimal orderCountAchievementRate = BigDecimal.ZERO;
if (totalTargetOrderCount > 0) {
orderCountAchievementRate = new BigDecimal(totalOrderCount)
.divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"));
} else if (totalOrderCount > 0) {
orderCountAchievementRate = new BigDecimal("100");
}
CompanyOverviewVO.PlatformSummary platformSummary = new CompanyOverviewVO.PlatformSummary();
platformSummary.setPlatformId(platformId);
platformSummary.setPlatformName(platform.getPlatformName());
platformSummary.setTargetOrderCount(totalTargetOrderCount);
platformSummary.setOrderCountAchievementRate(orderCountAchievementRate);
platformSummary.setTargetAmount(totalTargetAmount);
platformSummary.setSalesAmountAchievementRate(salesAmountAchievementRate);
platformSummary.setSalesAmount(totalSalesAmount);
platformSummary.setOrderCount(totalOrderCount);
platformSummary.setAverageOrderValue(averageOrderValue);
platformSummary.setProductCost(totalProductCost);
platformSummary.setShippingCost(totalShippingCost);
platformSummary.setOtherCost(totalOtherCost);
platformSummary.setRefundAmount(totalRefundAmount);
platformSummary.setTotalPromotionFee(totalPromotionFee);
platformSummary.setBrushFee(totalBrushFee);
platformSummary.setFeeRatio(feeRatio);
platformSummary.setTotalProfitBeforeTax(profitBeforeTax);
platformSummary.setSalesTaxAmount(salesTaxAmount);
platformSummary.setRoi(roi);
platformSummary.setProfitAfterTax(profitAfterTax);
platformSummaries.add(platformSummary);
}
// 按销售额降序排序
platformSummaries.sort(Comparator.comparing(CompanyOverviewVO.PlatformSummary::getSalesAmount).reversed());
return platformSummaries;
}
}
@@ -16,6 +16,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.ShopOverviewStat
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.ExportService;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
@@ -1278,4 +1279,295 @@ public class ExportServiceImpl implements ExportService {
cell.setCellValue(value);
cell.setCellStyle(style);
}
private void setCell(Row row, int col, int value, CellStyle style) {
Cell cell = row.createCell(col);
cell.setCellValue(value);
cell.setCellStyle(style);
}
@Override
public byte[] exportPlatformOverview(PlatformExportDTO 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);
// 查询所有店铺并按平台分组
List<ShopPO> allShops = shopService.list(
new LambdaQueryWrapper<ShopPO>().eq(ShopPO::getCompanyId, companyId)
);
Map<Long, List<ShopPO>> shopsByPlatform = allShops.stream()
.filter(shop -> shop.getPlatformId() != null)
.collect(Collectors.groupingBy(ShopPO::getPlatformId));
// 按平台过滤
if (dto.getPlatformIds() != null && !dto.getPlatformIds().isEmpty()) {
Set<Long> allowedPlatformIds = new HashSet<>(dto.getPlatformIds());
shopsByPlatform = shopsByPlatform.entrySet().stream()
.filter(e -> allowedPlatformIds.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
// 获取所有平台信息
List<PlatformPO> allPlatforms = platformMapper.selectList(null);
Map<Long, PlatformPO> platformMap = allPlatforms.stream()
.collect(Collectors.toMap(PlatformPO::getId, p -> p));
// 生成目标月份列表
List<LocalDate> targetMonths = new ArrayList<>();
LocalDate currentMonth = startDate.withDayOfMonth(1);
LocalDate endMonth = endDate.withDayOfMonth(1);
while (!currentMonth.isAfter(endMonth)) {
targetMonths.add(currentMonth);
currentMonth = currentMonth.plusMonths(1);
}
// 查询所有目标数据
LambdaQueryWrapper<ShopMonthlyTargetPO> targetWrapper = new LambdaQueryWrapper<>();
targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId)
.in(ShopMonthlyTargetPO::getTargetMonth, targetMonths);
List<ShopMonthlyTargetPO> allTargets = shopMonthlyTargetMapper.selectList(targetWrapper);
Map<Long, List<ShopMonthlyTargetPO>> targetsByShop = allTargets.stream()
.collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId));
// 查询所有订单
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> allOrders = orderMapper.selectList(orderWrapper);
Map<Long, List<OrderPO>> ordersByShop = allOrders.stream()
.collect(Collectors.groupingBy(OrderPO::getShopId));
// 查询推广费
LambdaQueryWrapper<PromotionFeePO> promoWrapper = new LambdaQueryWrapper<>();
promoWrapper.eq(PromotionFeePO::getCompanyId, companyId)
.ge(PromotionFeePO::getFeeDate, startDate)
.le(PromotionFeePO::getFeeDate, endDate);
List<PromotionFeePO> allPromotionFees = promotionFeeMapper.selectList(promoWrapper);
Map<Long, List<PromotionFeePO>> promotionFeesByShop = allPromotionFees.stream()
.collect(Collectors.groupingBy(PromotionFeePO::getShopId));
// 查询刷单费
LambdaQueryWrapper<BrushOrderPO> brushWrapper = new LambdaQueryWrapper<>();
brushWrapper.eq(BrushOrderPO::getCompanyId, companyId)
.ge(BrushOrderPO::getBrushTime, startDateTime)
.le(BrushOrderPO::getBrushTime, endDateTime);
List<BrushOrderPO> allBrushOrders = brushOrderMapper.selectList(brushWrapper);
Map<Long, List<BrushOrderPO>> brushOrdersByShop = allBrushOrders.stream()
.collect(Collectors.groupingBy(BrushOrderPO::getShopId));
// 按平台聚合数据
List<Map<String, Object>> platformDataList = new ArrayList<>();
for (Map.Entry<Long, List<ShopPO>> entry : shopsByPlatform.entrySet()) {
Long platformId = entry.getKey();
List<ShopPO> platformShops = entry.getValue();
PlatformPO platform = platformMap.get(platformId);
if (platform == null) continue;
BigDecimal totalSalesAmount = BigDecimal.ZERO;
int totalOrderCount = 0;
BigDecimal totalRefundAmount = BigDecimal.ZERO;
BigDecimal totalProductCost = BigDecimal.ZERO;
BigDecimal totalShippingCost = BigDecimal.ZERO;
BigDecimal totalOtherCost = BigDecimal.ZERO;
BigDecimal totalPromotionFee = BigDecimal.ZERO;
BigDecimal totalBrushFee = BigDecimal.ZERO;
BigDecimal totalTargetAmount = BigDecimal.ZERO;
int totalTargetOrderCount = 0;
for (ShopPO shop : platformShops) {
List<OrderPO> shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<PromotionFeePO> shopPromoFees = promotionFeesByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<BrushOrderPO> shopBrushOrders = brushOrdersByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<ShopMonthlyTargetPO> shopTargets = targetsByShop.getOrDefault(shop.getId(), new ArrayList<>());
BigDecimal shopSales = shopOrders.stream()
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalSalesAmount = totalSalesAmount.add(shopSales);
totalOrderCount += shopOrders.size();
BigDecimal shopRefund = shopOrders.stream()
.filter(o -> refundStatusId != null && refundStatusId.equals(o.getStatusId()))
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalRefundAmount = totalRefundAmount.add(shopRefund);
BigDecimal shopProductCost = shopOrders.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);
totalProductCost = totalProductCost.add(shopProductCost);
BigDecimal shopShippingCost = shopOrders.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);
totalShippingCost = totalShippingCost.add(shopShippingCost);
BigDecimal shopOtherCost = shopOrders.stream()
.map(o -> o.getOtherCost() != null ? o.getOtherCost() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalOtherCost = totalOtherCost.add(shopOtherCost);
BigDecimal shopPromoFee = shopPromoFees.stream()
.map(f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalPromotionFee = totalPromotionFee.add(shopPromoFee);
BigDecimal shopBrush = shopBrushOrders.stream()
.map(b -> b.getBrushAmount() != null ? b.getBrushAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalBrushFee = totalBrushFee.add(shopBrush);
BigDecimal shopTargetAmount = shopTargets.stream()
.map(t -> t.getTargetAmount() != null ? t.getTargetAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalTargetAmount = totalTargetAmount.add(shopTargetAmount);
int shopTargetOrderCount = shopTargets.stream()
.mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0)
.sum();
totalTargetOrderCount += shopTargetOrderCount;
}
BigDecimal avgOrderValue = totalOrderCount > 0
? totalSalesAmount.divide(new BigDecimal(totalOrderCount), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
BigDecimal profitBeforeTax = totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount);
BigDecimal salesTaxAmount = totalSalesAmount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP);
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount);
BigDecimal roi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0
? totalSalesAmount.subtract(totalRefundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal feeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0
? totalPromotionFee.add(totalBrushFee).divide(totalSalesAmount, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0
? totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"))
: BigDecimal.ZERO;
BigDecimal orderAchievementRate = totalTargetOrderCount > 0
? new BigDecimal(totalOrderCount)
.divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"))
: BigDecimal.ZERO;
Map<String, Object> data = new HashMap<>();
data.put("platformId", platformId);
data.put("platformName", platform.getPlatformName());
data.put("targetOrderCount", totalTargetOrderCount);
data.put("orderCountAchievementRate", orderAchievementRate);
data.put("targetAmount", totalTargetAmount);
data.put("salesAmountAchievementRate", salesAchievementRate);
data.put("salesAmount", totalSalesAmount);
data.put("orderCount", totalOrderCount);
data.put("avgOrderValue", avgOrderValue);
data.put("productCost", totalProductCost);
data.put("shippingCost", totalShippingCost);
data.put("otherCost", totalOtherCost);
data.put("refundAmount", totalRefundAmount);
data.put("totalPromotionFee", totalPromotionFee);
data.put("brushFee", totalBrushFee);
data.put("feeRatio", feeRatio);
data.put("totalProfitBeforeTax", profitBeforeTax);
data.put("salesTaxAmount", salesTaxAmount);
data.put("roi", roi);
data.put("profitAfterTax", profitAfterTax);
platformDataList.add(data);
}
platformDataList.sort((a, b) ->
((BigDecimal) b.get("salesAmount")).compareTo((BigDecimal) a.get("salesAmount")));
String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT);
try (Workbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("平台明细");
createPlatformDetailSheet(sheet, dateRangeLabel, platformDataList, taxRate);
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out);
return out.toByteArray();
}
} catch (Exception e) {
throw new BusinessException("导出平台Excel失败: " + e.getMessage());
}
}
private void createPlatformDetailSheet(Sheet sheet, String dateRangeLabel,
List<Map<String, Object>> platformDataList,
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, 17));
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 (Map<String, Object> data : platformDataList) {
Row row = sheet.createRow(rowIdx++);
setCell(row, 0, (String) data.get("platformName"), dataStyle);
setCell(row, 1, objToDouble(data.get("targetOrderCount")), dataStyle);
setCell(row, 2, objToPct(data.get("orderCountAchievementRate")), dataStyle);
setCell(row, 3, objToDouble(data.get("targetAmount")), dataStyle);
setCell(row, 4, objToPct(data.get("salesAmountAchievementRate")), dataStyle);
setCell(row, 5, objToDouble(data.get("salesAmount")), dataStyle);
setCell(row, 6, objToDouble(data.get("orderCount")), dataStyle);
setCell(row, 7, objToDouble(data.get("avgOrderValue")), dataStyle);
setCell(row, 8, objToDouble(data.get("productCost")), dataStyle);
setCell(row, 9, objToDouble(data.get("shippingCost")), dataStyle);
setCell(row, 10, objToDouble(data.get("otherCost")), dataStyle);
setCell(row, 11, objToDouble(data.get("refundAmount")), dataStyle);
setCell(row, 12, objToDouble(data.get("totalPromotionFee")), dataStyle);
setCell(row, 13, objToDouble(data.get("brushFee")), dataStyle);
setCell(row, 14, objToPct(data.get("feeRatio")), dataStyle);
setCell(row, 15, objToDouble(data.get("totalProfitBeforeTax")), dataStyle);
setCell(row, 16, objToDouble(data.get("salesTaxAmount")), dataStyle);
setCell(row, 17, objToDouble(data.get("roi")), dataStyle);
setCell(row, 18, objToDouble(data.get("profitAfterTax")), dataStyle);
}
for (int i = 0; i < headers.length; i++) {
sheet.setColumnWidth(i, 3200);
}
}
}