feat: 新增概览导出接口 - 公司概览导出 & 店铺概览导出

- 新增 CompanyExportDTO / ShopExportDTO 导出参数DTO
- 新增 ExportService + ExportServiceImpl,支持生成 Excel
  - 公司概览导出:汇总 sheet + 店铺明细 sheet
  - 店铺概览导出:汇总 sheet + 商品明细 sheet + 销售趋势 sheet
- 新增 ExportController,暴露 /ec/company-overview/export 和 /ec/shop/export-overview
- pom.xml 添加 apache poi-ooxml 5.2.5 依赖
This commit is contained in:
小蟑螂
2026-03-26 09:21:00 +08:00
parent a0fa113c40
commit bc8767c42a
8 changed files with 878 additions and 2 deletions
Vendored Regular → Executable
View File
+6
View File
@@ -132,6 +132,12 @@
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.18.4</version>
</dependency>
<!-- Apache POI Excel导出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
</dependency>
</dependencies>
<build>
@@ -0,0 +1,68 @@
package top.xyquan.ecomdmbbackend.modules.ecom.overview.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.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
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;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/**
* 概览导出控制器
*/
@Tag(name = "电商-概览导出", description = "概览数据导出接口")
@RestController
@RequestMapping("/ec")
public class ExportController {
private static final DateTimeFormatter FILE_NAME_FMT = DateTimeFormatter.ofPattern("yyyyMMdd");
private final ExportService exportService;
public ExportController(ExportService exportService) {
this.exportService = exportService;
}
@Operation(summary = "导出公司概览Excel", description = "导出全店铺概览数据为Excel文件")
@PostMapping("/company-overview/export")
@RequireRole(description = "导出公司概览", allowUser = 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";
writeExcel(response, filename, data);
}
@Operation(summary = "导出店铺概览Excel", description = "导出单店铺概览数据为Excel文件")
@PostMapping("/shop/export-overview")
@RequireRole(description = "导出店铺概览", allowUser = 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);
}
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,28 @@
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 lombok.Data;
import java.time.LocalDate;
import java.util.List;
/**
* 公司概览导出DTO
*/
@Data
@Schema(description = "公司概览导出DTO")
public class CompanyExportDTO {
@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> shopIds;
@Schema(description = "导出类型:summary-汇总 / detail-明细 / all-全部,默认 all", example = "all")
private String exportType = "all";
}
@@ -0,0 +1,30 @@
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.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.time.LocalDate;
import java.util.List;
/**
* 店铺概览导出DTO
*/
@Data
@Schema(description = "店铺概览导出DTO")
public class ShopExportDTO {
@Schema(description = "店铺ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "店铺ID不能为空")
private Long shopId;
@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 = "导出类型:summary-汇总 / product-商品明细 / trend-趋势 / all-全部,默认 all", example = "all")
private String exportType = "all";
}
@@ -0,0 +1,26 @@
package top.xyquan.ecomdmbbackend.modules.ecom.overview.service;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopExportDTO;
/**
* 概览导出服务接口
*/
public interface ExportService {
/**
* 导出公司概览Excel
*
* @param dto 导出参数
* @return Excel文件字节数组
*/
byte[] exportCompanyOverview(CompanyExportDTO dto);
/**
* 导出店铺概览Excel
*
* @param dto 导出参数
* @return Excel文件字节数组
*/
byte[] exportShopOverview(ShopExportDTO dto);
}
@@ -0,0 +1,718 @@
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.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.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.orderstatus.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.orderstatus.service.OrderStatusService;
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;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.shopmonthlytarget.mapper.ShopMonthlyTargetMapper;
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.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ecom.shopmonthlytarget.model.po.ShopMonthlyTargetPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
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 ExportServiceImpl implements ExportService {
private static final BigDecimal SALES_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 ShopMonthlyTargetMapper shopMonthlyTargetMapper;
private final ShopService shopService;
private final ProductService productService;
private final OrderStatusService orderStatusService;
public ExportServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper,
PromotionFeeMapper promotionFeeMapper,
BrushOrderMapper brushOrderMapper,
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
ShopService shopService,
ProductService productService,
OrderStatusService orderStatusService) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
this.brushOrderMapper = brushOrderMapper;
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
this.shopService = shopService;
this.productService = productService;
this.orderStatusService = orderStatusService;
}
@Override
public byte[] exportCompanyOverview(CompanyExportDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
LocalDate[] dateRange = parseDateRange(dto.getDateRange());
List<ShopPO> shops = shopService.list();
if (dto.getShopIds() != null && !dto.getShopIds().isEmpty()) {
shops = shops.stream()
.filter(s -> dto.getShopIds().contains(s.getId()))
.collect(Collectors.toList());
}
List<Long> autoStatusIds = getAutoStatusIds(companyId);
Long refundStatusId = getRefundStatusId(companyId);
List<Map<String, Object>> shopDataList = new ArrayList<>();
BigDecimal totalSales = BigDecimal.ZERO;
BigDecimal totalOrders = BigDecimal.ZERO;
BigDecimal totalPromotionFee = BigDecimal.ZERO;
BigDecimal totalBrushFee = BigDecimal.ZERO;
BigDecimal totalProfitBeforeTax = BigDecimal.ZERO;
for (ShopPO shop : shops) {
Map<String, Object> data = buildShopData(shop, dateRange[0], dateRange[1], autoStatusIds, refundStatusId, companyId);
shopDataList.add(data);
totalSales = totalSales.add((BigDecimal) data.get("salesAmount"));
totalOrders = totalOrders.add(new BigDecimal((Integer) data.get("orderCount")));
totalPromotionFee = totalPromotionFee.add((BigDecimal) data.get("promotionFee"));
totalBrushFee = totalBrushFee.add((BigDecimal) data.get("brushFee"));
totalProfitBeforeTax = totalProfitBeforeTax.add((BigDecimal) data.get("profitBeforeTax"));
}
// 计算汇总数据
BigDecimal totalTax = totalProfitBeforeTax.multiply(SALES_TAX_RATE).setScale(2, RoundingMode.HALF_UP);
BigDecimal totalProfitAfterTax = totalProfitBeforeTax.subtract(totalTax);
BigDecimal totalCost = totalPromotionFee.add(totalBrushFee);
BigDecimal totalRoi = totalCost.compareTo(BigDecimal.ZERO) > 0
? totalProfitBeforeTax.divide(totalCost, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal avgFeeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
? totalPromotionFee.divide(totalSales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
try (Workbook workbook = new XSSFWorkbook()) {
Sheet summarySheet = workbook.createSheet("汇总");
createSummarySheet(summarySheet, totalSales, totalOrders, totalPromotionFee,
totalBrushFee, avgFeeRatio, totalProfitBeforeTax, totalTax, totalProfitAfterTax, totalRoi);
String exportType = dto.getExportType() == null ? "all" : dto.getExportType();
if ("detail".equals(exportType) || "all".equals(exportType)) {
Sheet detailSheet = workbook.createSheet("店铺明细");
createCompanyDetailSheet(detailSheet, shopDataList);
}
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out);
return out.toByteArray();
}
} catch (Exception e) {
throw new BusinessException("导出Excel失败: " + e.getMessage());
}
}
@Override
public byte[] exportShopOverview(ShopExportDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
LocalDate[] dateRange = parseDateRange(dto.getDateRange());
List<Long> autoStatusIds = getAutoStatusIds(companyId);
Long refundStatusId = getRefundStatusId(companyId);
ShopPO shop = shopService.getById(dto.getShopId());
if (shop == null || !shop.getCompanyId().equals(companyId)) {
throw new BusinessException("店铺不存在");
}
List<Long> shopIds = Collections.singletonList(shop.getId());
Map<String, Object> shopData = buildShopData(shop, dateRange[0], dateRange[1], autoStatusIds, refundStatusId, companyId);
// 查询订单用于商品维度和趋势计算
LocalDateTime startDateTime = dateRange[0].atStartOfDay();
LocalDateTime endDateTime = dateRange[1].atTime(23, 59, 59);
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getShopId, shop.getId())
.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);
List<OrderPO> allOrdersWrapper = orderMapper.selectList(
new LambdaQueryWrapper<OrderPO>().eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getShopId, shop.getId())
.ge(OrderPO::getOrderTime, startDateTime)
.le(OrderPO::getOrderTime, endDateTime));
Long finalRefundStatusId = refundStatusId;
final List<OrderPO> finalOrders = orders;
Map<Long, List<OrderPO>> ordersByProduct = allOrdersWrapper.stream()
.collect(Collectors.groupingBy(OrderPO::getProductId));
// 趋势数据:按日期分组
Map<LocalDate, List<OrderPO>> ordersByDate = finalOrders.stream()
.collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate()));
String exportType = dto.getExportType() == null ? "all" : dto.getExportType();
try (Workbook workbook = new XSSFWorkbook()) {
if ("summary".equals(exportType) || "all".equals(exportType)) {
Sheet summarySheet = workbook.createSheet("汇总");
createShopSummarySheet(summarySheet, shop.getName(), shopData);
}
if (("product".equals(exportType) || "all".equals(exportType)) && !ordersByProduct.isEmpty()) {
Sheet productSheet = workbook.createSheet("商品明细");
createProductDetailSheet(productSheet, ordersByProduct, promotionFeeMapper, brushOrderMapper,
companyId, shop.getId(), dateRange[0], dateRange[1], refundStatusId);
}
if (("trend".equals(exportType) || "all".equals(exportType)) && !ordersByDate.isEmpty()) {
Sheet trendSheet = workbook.createSheet("销售趋势");
createTrendSheet(trendSheet, ordersByDate, dateRange[0], dateRange[1]);
}
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out);
return out.toByteArray();
}
} catch (Exception e) {
throw new BusinessException("导出Excel失败: " + e.getMessage());
}
}
// ==================== Sheet 构建方法 ====================
private void createSummarySheet(Sheet sheet, BigDecimal totalSales, BigDecimal totalOrders,
BigDecimal totalPromotionFee, BigDecimal totalBrushFee,
BigDecimal avgFeeRatio, BigDecimal profitBeforeTax,
BigDecimal tax, BigDecimal profitAfterTax, BigDecimal roi) {
CellStyle titleStyle = createTitleStyle(sheet.getWorkbook());
CellStyle labelStyle = createLabelStyle(sheet.getWorkbook());
CellStyle valueStyle = createValueStyle(sheet.getWorkbook());
String[] labels = {"全店总销售额", "全店总单量", "总推广费", "总刷单费", "平均费比",
"税前总盈亏", "总税额", "税后总盈亏", "汇总ROI"};
Object[] values = {
totalSales.setScale(2, RoundingMode.HALF_UP),
totalOrders.intValue(),
totalPromotionFee.setScale(2, RoundingMode.HALF_UP),
totalBrushFee.setScale(2, RoundingMode.HALF_UP),
avgFeeRatio.setScale(4, RoundingMode.HALF_UP),
profitBeforeTax.setScale(2, RoundingMode.HALF_UP),
tax.setScale(2, RoundingMode.HALF_UP),
profitAfterTax.setScale(2, RoundingMode.HALF_UP),
roi.setScale(4, RoundingMode.HALF_UP)
};
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("全店概览汇总");
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 createCompanyDetailSheet(Sheet sheet, List<Map<String, Object>> shopDataList) {
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
String[] headers = {"店铺名称", "平台", "销售额", "单量", "客单价", "推广费", "刷单费", "费比",
"退款金额", "成本运费", "税前盈亏", "税额", "税后盈亏", "ROI",
"目标销售额", "销售额达成率", "目标单量", "单量达成率"};
Row headerRow = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
int rowIdx = 1;
for (Map<String, Object> data : shopDataList) {
Row row = sheet.createRow(rowIdx++);
setCell(row, 0, (String) data.get("shopName"), dataStyle);
setCell(row, 1, (String) data.get("platform"), dataStyle);
setCell(row, 2, ((BigDecimal) data.get("salesAmount")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 3, ((Integer) data.get("orderCount")).doubleValue(), dataStyle);
setCell(row, 4, ((BigDecimal) data.get("avgOrderValue")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 5, ((BigDecimal) data.get("promotionFee")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 6, ((BigDecimal) data.get("brushFee")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 7, ((BigDecimal) data.get("feeRatio")).setScale(4, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 8, ((BigDecimal) data.get("refundAmount")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 9, ((BigDecimal) data.get("shippingCost")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 10, ((BigDecimal) data.get("profitBeforeTax")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 11, ((BigDecimal) data.get("tax")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 12, ((BigDecimal) data.get("profitAfterTax")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 13, ((BigDecimal) data.get("roi")).setScale(4, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 14, ((BigDecimal) data.get("targetAmount")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 15, ((BigDecimal) data.get("salesAchievementRate")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 16, ((Integer) data.get("targetOrderCount")).doubleValue(), dataStyle);
setCell(row, 17, ((BigDecimal) data.get("orderAchievementRate")).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
}
for (int i = 0; i < headers.length; i++) {
sheet.setColumnWidth(i, 3200);
}
}
private void createShopSummarySheet(Sheet sheet, String shopName, 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,
((BigDecimal) data.get("salesAmount")).setScale(2, RoundingMode.HALF_UP),
((Integer) data.get("orderCount")),
((BigDecimal) data.get("avgOrderValue")).setScale(2, RoundingMode.HALF_UP),
((BigDecimal) data.get("promotionFee")).setScale(2, RoundingMode.HALF_UP),
((BigDecimal) data.get("brushFee")).setScale(2, RoundingMode.HALF_UP),
((BigDecimal) data.get("feeRatio")).setScale(4, RoundingMode.HALF_UP),
((BigDecimal) data.get("refundAmount")).setScale(2, RoundingMode.HALF_UP),
((BigDecimal) data.get("shippingCost")).setScale(2, RoundingMode.HALF_UP),
((BigDecimal) data.get("profitBeforeTax")).setScale(2, RoundingMode.HALF_UP),
((BigDecimal) data.get("tax")).setScale(2, RoundingMode.HALF_UP),
((BigDecimal) data.get("profitAfterTax")).setScale(2, RoundingMode.HALF_UP),
((BigDecimal) data.get("roi")).setScale(4, RoundingMode.HALF_UP),
((BigDecimal) data.get("targetAmount")).setScale(2, RoundingMode.HALF_UP),
((BigDecimal) data.get("salesAchievementRate")).setScale(2, RoundingMode.HALF_UP),
((Integer) data.get("targetOrderCount")),
((BigDecimal) data.get("orderAchievementRate")).setScale(2, RoundingMode.HALF_UP)
};
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue(shopName + " - 概览汇总");
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, Map<Long, List<OrderPO>> ordersByProduct,
PromotionFeeMapper promotionFeeMapper,
BrushOrderMapper brushOrderMapper,
Long companyId, Long shopId,
LocalDate startDate, LocalDate endDate,
Long refundStatusId) {
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
String[] headers = {"商品名称", "商品编码", "销售额", "单量", "客单价", "推广费", "刷单费",
"费比", "退款金额", "成本运费", "税前盈亏", "税额", "税后盈亏", "ROI"};
Row headerRow = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
int rowIdx = 1;
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 -> refundStatusId != null && refundStatusId.equals(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(SALES_TAX_RATE).setScale(2, RoundingMode.HALF_UP);
BigDecimal profitAfterTax = profitBeforeTax.subtract(tax);
// 按商品分摊推广费和刷单费(按销售额占比)
BigDecimal promotionFee = BigDecimal.ZERO;
BigDecimal brushFee = BigDecimal.ZERO;
BigDecimal roi = totalCost.compareTo(BigDecimal.ZERO) > 0
? profitBeforeTax.divide(totalCost, 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, Map<LocalDate, List<OrderPO>> ordersByDate,
LocalDate startDate, LocalDate endDate) {
CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());
CellStyle dataStyle = createDataStyle(sheet.getWorkbook());
String[] headers = {"日期", "销售额", "单量", "客单价"};
Row headerRow = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
int rowIdx = 1;
LocalDate current = startDate;
while (!current.isAfter(endDate)) {
List<OrderPO> dayOrders = ordersByDate.getOrDefault(current, Collections.emptyList());
BigDecimal salesAmount = dayOrders.stream()
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
int orderCount = dayOrders.size();
BigDecimal avgOrderValue = orderCount > 0
? salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
Row row = sheet.createRow(rowIdx++);
setCell(row, 0, current.format(DATE_FMT), dataStyle);
setCell(row, 1, salesAmount.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
setCell(row, 2, (double) orderCount, dataStyle);
setCell(row, 3, avgOrderValue.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
current = current.plusDays(1);
}
sheet.setColumnWidth(0, 3200);
sheet.setColumnWidth(1, 3200);
sheet.setColumnWidth(2, 3200);
sheet.setColumnWidth(3, 3200);
}
// ==================== 数据构建方法 ====================
private Map<String, Object> buildShopData(ShopPO shop, LocalDate startDate, LocalDate endDate,
List<Long> autoStatusIds, Long refundStatusId, Long companyId) {
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getShopId, shop.getId())
.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)
.eq(PromotionFeePO::getShopId, shop.getId())
.ge(PromotionFeePO::getFeeDate, startDate)
.le(PromotionFeePO::getFeeDate, endDate);
List<PromotionFeePO> promotionFees = promotionFeeMapper.selectList(promoWrapper);
LambdaQueryWrapper<BrushOrderPO> brushWrapper = new LambdaQueryWrapper<>();
brushWrapper.eq(BrushOrderPO::getCompanyId, companyId)
.eq(BrushOrderPO::getShopId, shop.getId())
.ge(BrushOrderPO::getBrushTime, startDateTime)
.le(BrushOrderPO::getBrushTime, endDateTime);
List<BrushOrderPO> brushOrders = brushOrderMapper.selectList(brushWrapper);
// 目标数据
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)
.eq(ShopMonthlyTargetPO::getShopId, shop.getId())
.in(ShopMonthlyTargetPO::getTargetMonth, targetMonths);
List<ShopMonthlyTargetPO> targets = shopMonthlyTargetMapper.selectList(targetWrapper);
BigDecimal targetAmount = targets.stream()
.map(t -> t.getTargetAmount() != null ? t.getTargetAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Integer targetOrderCount = targets.stream()
.mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0)
.sum();
// 计算各项指标
BigDecimal salesAmount = orders.stream()
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
int orderCount = orders.size();
BigDecimal avgOrderValue = orderCount > 0
? salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal refundAmount = orders.stream()
.filter(o -> refundStatusId != null && refundStatusId.equals(o.getStatusId()))
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal shippingCost = orders.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 productCostTotal = orders.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);
BigDecimal promotionFee = promotionFees.stream()
.map(f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal brushFee = brushOrders.stream()
.map(b -> b.getBrushAmount() != null ? b.getBrushAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalCost = productCostTotal.add(shippingCost);
BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount);
BigDecimal tax = profitBeforeTax.multiply(SALES_TAX_RATE).setScale(2, RoundingMode.HALF_UP);
BigDecimal profitAfterTax = profitBeforeTax.subtract(tax);
BigDecimal feeRatio = salesAmount.compareTo(BigDecimal.ZERO) > 0
? promotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal roi = promotionFee.add(brushFee).compareTo(BigDecimal.ZERO) > 0
? profitBeforeTax.divide(promotionFee.add(brushFee), 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal salesAchievementRate = targetAmount.compareTo(BigDecimal.ZERO) > 0
? salesAmount.divide(targetAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100")) : BigDecimal.ZERO;
BigDecimal orderAchievementRate = targetOrderCount > 0
? new BigDecimal(orderCount).divide(new BigDecimal(targetOrderCount), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100")) : BigDecimal.ZERO;
Map<String, Object> data = new HashMap<>();
data.put("shopName", shop.getName());
data.put("platform", shop.getPlatform());
data.put("salesAmount", salesAmount);
data.put("orderCount", orderCount);
data.put("avgOrderValue", avgOrderValue);
data.put("promotionFee", promotionFee);
data.put("brushFee", brushFee);
data.put("feeRatio", feeRatio);
data.put("refundAmount", refundAmount);
data.put("shippingCost", shippingCost);
data.put("profitBeforeTax", profitBeforeTax);
data.put("tax", tax);
data.put("profitAfterTax", profitAfterTax);
data.put("roi", roi);
data.put("targetAmount", targetAmount);
data.put("targetOrderCount", targetOrderCount);
data.put("salesAchievementRate", salesAchievementRate);
data.put("orderAchievementRate", orderAchievementRate);
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 Long getRefundStatusId(Long companyId) {
OrderStatusPO status = orderStatusService.getOne(
new LambdaQueryWrapper<OrderStatusPO>()
.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getIsRefund, 1)
.last("LIMIT 1"));
return status != null ? status.getId() : null;
}
// ==================== Excel 样式工具 ====================
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 createLabelStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
return style;
}
private CellStyle createValueStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
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);
}
}
@@ -3,7 +3,7 @@ server:
spring:
datasource:
url: "jdbc:mysql://192.168.10.3:3306/ecom_dmb_dev?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true"
url: "jdbc:mysql://192.168.3.100:3306/ecom_dmb_dev?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true"
username: ecom_dmb_dev
password: ecom_dmb_dev
hikari:
@@ -29,7 +29,7 @@ spring:
# Redis配置
data:
redis:
host: 192.168.10.3
host: 192.168.3.100
port: 6379
password: redis_qinghua
database: 2