feat: 商品详情页功能完成

后端:
- ProductOverviewController POST /ec/product/overview
- ProductOverviewQueryDTO / ProductOverviewVO (productId + 7个统计字段)
- ProductOverviewServiceImpl

前端:
- ProductCard 添加统计入口,goToDetails 改用 path 导航
- /api/ecommerce/product-overview/ 接口定义
- views/ecommerce/product/details/ 商品详情页 + OverviewTab (7个ChartCard)

数据库:
- sys_menu id=43 parent_id 从 8 改为 6
This commit is contained in:
小蟑螂
2026-04-11 23:58:28 +08:00
parent bd9916fa99
commit 92a6175edb
18 changed files with 1059 additions and 157 deletions
@@ -65,13 +65,19 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
}
/**
* 从请求头中获取JWT Token
* 从请求头或query参数中获取JWT Token
*/
private String getTokenFromRequest(HttpServletRequest request) {
// 优先从 Authorization header 获取
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
// 回退:从 query 参数获取(EventSource 无法自定义 header)
String queryToken = request.getParameter("token");
if (StringUtils.hasText(queryToken)) {
return queryToken;
}
return null;
}
}
@@ -206,6 +206,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
private final Map<Long, ProductPO> productByIdCache = new HashMap<>();
private final Map<String, Long> statusIdByNameCache = new HashMap<>();
private final Set<String> existingPlatformOrderNos = new HashSet<>();
private final Map<String, Long> existingOrderIdByPlatformNo = new HashMap<>(); // platformOrderNo -> orderId
private final Set<String> existingRelationKeys = new HashSet<>();
private final List<PendingOrderInsert> pendingOrders = new ArrayList<>();
private final Map<String, PendingOrderInsert> pendingOrderByPlatformNo = new HashMap<>(); // 按平台订单号索引,用于快速查找和更新
@@ -296,7 +297,14 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
notifyTaskProgress(task.getCreateBy(), convertToVO(completedTask));
} catch (Exception e) {
updateTaskStatus(taskId, "failed", "处理失败: " + e.getMessage(), 0, 0, 0);
String errMsg = e.getMessage();
if (errMsg != null) {
byte[] errBytes = errMsg.getBytes(java.nio.charset.StandardCharsets.UTF_8);
if (errBytes.length > 59500) {
errMsg = new String(errBytes, 0, 59500, java.nio.charset.StandardCharsets.UTF_8) + "...[已截断]";
}
}
updateTaskStatus(taskId, "failed", "处理失败: " + errMsg, 0, 0, 0);
ImportTaskPO failedTask = importTaskService.getById(taskId);
notifyTaskProgress(task.getCreateBy(), convertToVO(failedTask));
}
@@ -329,8 +337,11 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
int totalCount = 0;
int successCount = 0;
int failCount = 0;
int insertCount = 0;
int updateCount = 0;
StringBuilder errorMessages = new StringBuilder();
ImportRuntimeContext context = null;
try {
// 获取文件信息
SysFileVO fileInfo = sysFileService.getFileById(task.getFileId());
@@ -383,7 +394,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 更新总行数
updateTaskStatus(task.getId(), "processing", null, totalCount, 0, 0);
ImportRuntimeContext context = new ImportRuntimeContext(companyId, task.getShopId(), task.getCreateBy());
context = new ImportRuntimeContext(companyId, task.getShopId(), task.getCreateBy());
preloadImportContext(context, records, fieldMapping, statusMapping);
for (int i = 0; i < records.size(); i++) {
@@ -395,12 +406,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
CreateOrderDTO orderDTO = parseOrderFromCSV(record, fieldMapping, statusMapping, task.getShopId(),
null, companyId, task.getCreateBy(), context);
queueShopProductRelation(orderDTO, context);
OrderPO orderPO = buildOrderPO(orderDTO, companyId, task.getCreateBy(), task.getId());
// 如果是更新操作,设置订单ID
if (orderDTO.getExistingOrderId() != null) {
orderPO.setId(orderDTO.getExistingOrderId());
}
OrderPO orderPO = buildOrderPO(orderDTO, companyId, task.getCreateBy(), task.getId(), context);
StringBuilder updateMsg = new StringBuilder();
if (orderDTO.getExistingOrderId() != null) {
@@ -409,12 +415,12 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 检查是否是同批次内重复(内存中的重复)
boolean isInMemoryDuplicate = validatePlatformOrderNo(
orderDTO.getPlatformOrderNo(), context, orderPO, rowNumber, orderDTO.getExistingOrderId(), updateMsg);
orderDTO.getPlatformOrderNo(), context, orderPO, rowNumber, orderPO.getId(), updateMsg);
if (!isInMemoryDuplicate) {
// 非重复:新增到pending队列
PendingOrderInsert pendingInsert = new PendingOrderInsert(
rowNumber, orderDTO.getPlatformOrderNo(), orderPO, orderDTO.getExistingOrderId(), updateMsg);
rowNumber, orderDTO.getPlatformOrderNo(), orderPO, orderPO.getId(), updateMsg);
context.pendingOrders.add(pendingInsert);
if (orderDTO.getPlatformOrderNo() != null && !orderDTO.getPlatformOrderNo().trim().isEmpty()) {
context.pendingOrderByPlatformNo.put(orderDTO.getPlatformOrderNo().trim(), pendingInsert);
@@ -428,6 +434,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
int[] result = flushPendingOrders(context, errorMessages);
successCount += result[0];
failCount += result[1];
insertCount += result[0];
updateCount += result[2];
}
} catch (Exception e) {
@@ -451,6 +459,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
int[] flushResult = flushPendingOrders(context, errorMessages);
successCount += flushResult[0];
failCount += flushResult[1];
insertCount += flushResult[0];
updateCount += flushResult[2];
}
} finally {
// 清理:从OSS下载的临时文件需要手动删除
@@ -461,7 +471,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 更新最终状态
String finalStatus = failCount == 0 ? "success" : (successCount > 0 ? "success" : "failed");
String message = failCount > 0 ? errorMessages.toString() : "导入完成";
String summaryMsg = String.format("导入完成,新增 %d 条,更新 %d 条", insertCount, updateCount);
String message = failCount > 0 ? summaryMsg + "\n" + errorMessages.toString() : summaryMsg;
updateTaskStatus(task.getId(), finalStatus, message, totalCount, successCount, failCount);
}
@@ -1409,11 +1420,13 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
LambdaQueryWrapper<OrderPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderPO::getCompanyId, context.companyId)
.in(OrderPO::getPlatformOrderNo, chunk)
.select(OrderPO::getPlatformOrderNo);
.select(OrderPO::getId, OrderPO::getPlatformOrderNo);
List<OrderPO> orders = orderMapper.selectList(wrapper);
for (OrderPO order : orders) {
if (order.getPlatformOrderNo() != null) {
context.existingPlatformOrderNos.add(order.getPlatformOrderNo().trim());
String normalized = order.getPlatformOrderNo().trim();
context.existingPlatformOrderNos.add(normalized);
context.existingOrderIdByPlatformNo.put(normalized, order.getId());
}
}
}
@@ -1482,12 +1495,18 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
String normalized = platformOrderNo.trim();
// 检查同一批次内是否已存在相同的平台订单号
// 优先使用 preload 中已知的最早 existingOrderId
Long existingId = newExistingOrderId;
if (existingId == null && context.existingOrderIdByPlatformNo.containsKey(normalized)) {
existingId = context.existingOrderIdByPlatformNo.get(normalized);
}
if (context.pendingPlatformOrderNos.contains(normalized)) {
// 同批次内重复:更新已存在的pending订单数据
PendingOrderInsert existing = context.pendingOrderByPlatformNo.get(normalized);
if (existing != null) {
// 更新已存在订单的数据和行号
existing.updateData(newOrderPO, newExistingOrderId, newUpdateMsg, newRowNumber);
// 更新已存在订单的数据和行号,同时保留/更新 existingOrderId
existing.updateData(newOrderPO, existingId, newUpdateMsg, newRowNumber);
}
return true;
}
@@ -1548,12 +1567,14 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
private int[] flushPendingOrders(ImportRuntimeContext context, StringBuilder errorMessages) {
if (context.pendingOrders.isEmpty()) {
return new int[] {0, 0};
return new int[] {0, 0, 0, 0};
}
int success = 0;
int fail = 0;
int insertSuccess = 0;
int insertFail = 0;
int updateSuccess = 0;
int updateFail = 0;
List<PendingOrderInsert> batch = new ArrayList<>(context.pendingOrders);
// 分离新增和更新
List<PendingOrderInsert> inserts = new ArrayList<>();
List<PendingOrderInsert> updates = new ArrayList<>();
@@ -1564,30 +1585,24 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
inserts.add(pending);
}
}
// 处理新增
if (!inserts.isEmpty()) {
int[] result = doBatchInsert(inserts, context, errorMessages);
success += result[0];
fail += result[1];
insertSuccess += result[0];
insertFail += result[1];
}
// 处理更新
for (PendingOrderInsert pending : updates) {
try {
orderMapper.updateById(pending.order);
success++;
updateSuccess++;
// 记录更新消息
if (pending.updateMessages != null && pending.updateMessages.length() > 0) {
// 更新消息用单独的格式,前面加 [更新] 标记
String updateInfo = pending.updateMessages.toString();
if (updateInfo.contains("已更新")) {
errorMessages.append(String.format("[更新] 第%d行:%s", pending.rowNumber, updateInfo))
.append(System.lineSeparator());
} else {
errorMessages.append(String.format("[更新] 第%d行:%s", pending.rowNumber, updateInfo))
.append(System.lineSeparator());
}
errorMessages.append(String.format("[更新] 第%d行:%s", pending.rowNumber, updateInfo))
.append(System.lineSeparator());
}
// 更新内存状态
if (pending.platformOrderNo != null && !pending.platformOrderNo.trim().isEmpty()) {
@@ -1596,14 +1611,14 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
context.existingPlatformOrderNos.add(normalized);
}
} catch (Exception e) {
fail++;
updateFail++;
errorMessages.append(String.format("[失败] 第%d行:更新失败 %s", pending.rowNumber, e.getMessage()))
.append(System.lineSeparator());
}
}
context.pendingOrders.clear();
return new int[] {success, fail};
return new int[] {insertSuccess, insertFail, updateSuccess, updateFail};
}
private int[] doBatchInsert(List<PendingOrderInsert> inserts, ImportRuntimeContext context, StringBuilder errorMessages) {
@@ -1647,7 +1662,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
return new int[] {success, fail};
}
private OrderPO buildOrderPO(CreateOrderDTO createOrderDTO, Long companyId, Long createBy, Long importTaskId) {
private OrderPO buildOrderPO(CreateOrderDTO createOrderDTO, Long companyId, Long createBy, Long importTaskId, ImportRuntimeContext context) {
OrderPO order = new OrderPO();
order.setCompanyId(companyId);
order.setShopId(createOrderDTO.getShopId());
@@ -1667,6 +1682,13 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
order.setCreateBy(createBy);
order.setImportTaskId(importTaskId);
order.setConfirm(createOrderDTO.getConfirm() != null ? createOrderDTO.getConfirm() : 1);
// 从 preload 的订单号→ID 映射中查找已有订单ID,用于走 UPDATE 而非 INSERT
if (context != null && createOrderDTO.getPlatformOrderNo() != null) {
String normalized = createOrderDTO.getPlatformOrderNo().trim();
if (context.existingOrderIdByPlatformNo.containsKey(normalized)) {
order.setId(context.existingOrderIdByPlatformNo.get(normalized));
}
}
return order;
}
@@ -1687,7 +1709,12 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
updateWrapper.eq(ImportTaskPO::getId, taskId);
updateWrapper.set(ImportTaskPO::getStatus, status);
if (message != null) {
updateWrapper.set(ImportTaskPO::getMessage, message);
// text 上限约 65535 字节,按字节长度截断(中文在UTF-8下占3字节)
byte[] msgBytes = message.getBytes(java.nio.charset.StandardCharsets.UTF_8);
String safeMsg = msgBytes.length > 60000
? new String(msgBytes, 0, 60000, java.nio.charset.StandardCharsets.UTF_8)
: message;
updateWrapper.set(ImportTaskPO::getMessage, safeMsg);
}
if (totalCount != null) {
updateWrapper.set(ImportTaskPO::getTotalCount, totalCount);
@@ -0,0 +1,39 @@
package top.xyquan.ecomdmbbackend.modules.ecom.product.overview.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.ecom.product.overview.model.dto.ProductOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.overview.model.vo.ProductOverviewVO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.overview.service.ProductOverviewService;
/**
* 商品概览控制器
*/
@Tag(name = "电商-商品概览", description = "商品统计概览接口")
@RestController
@RequestMapping("/ec/product")
public class ProductOverviewController {
private final ProductOverviewService productOverviewService;
public ProductOverviewController(ProductOverviewService productOverviewService) {
this.productOverviewService = productOverviewService;
}
@Operation(summary = "获取商品总览", description = "获取指定商品在日期范围内的销售额、订单数、客单价、成本、退款金额、推广费、费比等统计数据")
@PostMapping("/overview")
@RequirePermission(value = "ecom:product:read", description = "查询商品总览", allowSuper = true)
public ApiResponse<ProductOverviewVO> getProductOverview(
@Valid @RequestBody ProductOverviewQueryDTO queryDTO) {
ProductOverviewVO overview = productOverviewService.getProductOverview(queryDTO);
return ApiResponse.success(overview);
}
}
@@ -0,0 +1,36 @@
package top.xyquan.ecomdmbbackend.modules.ecom.product.overview.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.time.LocalDate;
/**
* 商品概览查询DTO
*/
@Data
@Schema(description = "商品概览查询DTO")
public class ProductOverviewQueryDTO {
/**
* 商品ID
*/
@Schema(description = "商品ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "商品ID不能为空")
private Long productId;
/**
* 开始日期
*/
@Schema(description = "开始日期", example = "2024-01-01", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "开始日期不能为空")
private LocalDate startDate;
/**
* 结束日期
*/
@Schema(description = "结束日期", example = "2024-01-31", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "结束日期不能为空")
private LocalDate endDate;
}
@@ -0,0 +1,110 @@
package top.xyquan.ecomdmbbackend.modules.ecom.product.overview.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
/**
* 商品总览VO
*/
@Data
@Schema(description = "商品总览VO")
public class ProductOverviewVO {
/**
* 商品ID
*/
@Schema(description = "商品ID")
private Long productId;
/**
* 商品名称
*/
@Schema(description = "商品名称")
private String productName;
/**
* 销售额统计
*/
@Schema(description = "销售额统计")
private DailyStatistics salesAmount;
/**
* 订单数统计
*/
@Schema(description = "订单数统计")
private DailyStatistics orderCount;
/**
* 客单价统计
*/
@Schema(description = "客单价统计")
private DailyStatistics averageOrderValue;
/**
* 成本统计
*/
@Schema(description = "成本统计")
private DailyStatistics costAmount;
/**
* 退款金额统计
*/
@Schema(description = "退款金额统计")
private DailyStatistics refundAmount;
/**
* 推广费统计
*/
@Schema(description = "推广费统计")
private DailyStatistics promotionFee;
/**
* 费比统计
*/
@Schema(description = "费比统计")
private DailyStatistics feeRatio;
/**
* 每日统计数据
*/
@Data
@Schema(description = "每日统计数据")
public static class DailyStatistics {
/**
* 时间范围的总值
*/
@Schema(description = "时间范围的总值")
private BigDecimal total;
/**
* 每日数据列表
*/
@Schema(description = "每日数据列表")
private List<DailyData> dailyDataList;
}
/**
* 每日数据项
*/
@Data
@Schema(description = "每日数据项")
public static class DailyData {
/**
* 日期
*/
@JsonFormat(pattern = "yyyy-MM-dd")
@Schema(description = "日期", example = "2024-01-01")
private LocalDate date;
/**
* 对应的值
*/
@Schema(description = "对应的值")
private BigDecimal value;
}
}
@@ -0,0 +1,18 @@
package top.xyquan.ecomdmbbackend.modules.ecom.product.overview.service;
import top.xyquan.ecomdmbbackend.modules.ecom.product.overview.model.dto.ProductOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.overview.model.vo.ProductOverviewVO;
/**
* 商品概览服务接口
*/
public interface ProductOverviewService {
/**
* 获取商品总览统计数据
*
* @param queryDTO 查询参数(商品ID + 日期范围)
* @return 商品总览数据
*/
ProductOverviewVO getProductOverview(ProductOverviewQueryDTO queryDTO);
}
@@ -0,0 +1,421 @@
package top.xyquan.ecomdmbbackend.modules.ecom.product.overview.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.mapper.OrderStatusMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.overview.model.dto.ProductOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.overview.model.vo.ProductOverviewVO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.overview.service.ProductOverviewService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 商品概览服务实现类
*/
@Service
public class ProductOverviewServiceImpl implements ProductOverviewService {
private final CurrentUserContext currentUserContext;
private final OrderMapper orderMapper;
private final PromotionFeeMapper promotionFeeMapper;
private final OrderStatusMapper orderStatusMapper;
private final ProductService productService;
public ProductOverviewServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper,
PromotionFeeMapper promotionFeeMapper,
OrderStatusMapper orderStatusMapper,
ProductService productService) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
this.orderStatusMapper = orderStatusMapper;
this.productService = productService;
}
@Override
public ProductOverviewVO getProductOverview(ProductOverviewQueryDTO queryDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证商品是否存在
ProductPO product = productService.getById(queryDTO.getProductId());
if (product == null || !product.getCompanyId().equals(companyId)) {
throw new BusinessException("商品不存在");
}
// 验证日期范围
if (queryDTO.getStartDate().isAfter(queryDTO.getEndDate())) {
throw new BusinessException("开始日期不能晚于结束日期");
}
// 查询时间范围
LocalDateTime startDateTime = queryDTO.getStartDate().atStartOfDay();
LocalDateTime endDateTime = queryDTO.getEndDate().atTime(23, 59, 59);
// 查询订单数据(按商品过滤)
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getProductId, queryDTO.getProductId())
.ge(OrderPO::getOrderTime, startDateTime)
.le(OrderPO::getOrderTime, endDateTime);
List<OrderPO> orders = orderMapper.selectList(orderWrapper);
// 查询推广费数据(店铺粒度的推广费,需要通过订单关联的shopId过滤)
// 先收集该商品对应订单的店铺ID列表
List<Long> shopIds = orders.stream()
.map(OrderPO::getShopId)
.filter(shopId -> shopId != null)
.distinct()
.collect(Collectors.toList());
List<PromotionFeePO> promotionFees = new ArrayList<>();
if (!shopIds.isEmpty()) {
LambdaQueryWrapper<PromotionFeePO> promotionWrapper = new LambdaQueryWrapper<>();
promotionWrapper.eq(PromotionFeePO::getCompanyId, companyId)
.in(PromotionFeePO::getShopId, shopIds)
.ge(PromotionFeePO::getFeeDate, queryDTO.getStartDate())
.le(PromotionFeePO::getFeeDate, queryDTO.getEndDate());
promotionFees = promotionFeeMapper.selectList(promotionWrapper);
}
// 获取退款状态ID
Long refundStatusId = getRefundStatusId();
// 按日期分组订单数据
Map<LocalDate, List<OrderPO>> ordersByDate = orders.stream()
.collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate()));
// 按日期分组推广费数据
Map<LocalDate, List<PromotionFeePO>> promotionFeesByDate = promotionFees.stream()
.collect(Collectors.groupingBy(PromotionFeePO::getFeeDate));
// 生成日期范围内的所有日期列表
List<LocalDate> dateList = new ArrayList<>();
LocalDate currentDate = queryDTO.getStartDate();
while (!currentDate.isAfter(queryDTO.getEndDate())) {
dateList.add(currentDate);
currentDate = currentDate.plusDays(1);
}
// 构建返回对象
ProductOverviewVO overviewVO = new ProductOverviewVO();
overviewVO.setProductId(product.getId());
overviewVO.setProductName(product.getName());
// 计算销售额统计
ProductOverviewVO.DailyStatistics salesAmountStats = calculateSalesAmountStatistics(
ordersByDate, dateList, orders);
overviewVO.setSalesAmount(salesAmountStats);
// 计算订单数统计
ProductOverviewVO.DailyStatistics orderCountStats = calculateOrderCountStatistics(
ordersByDate, dateList, orders);
overviewVO.setOrderCount(orderCountStats);
// 计算客单价统计
ProductOverviewVO.DailyStatistics averageOrderValueStats = calculateAverageOrderValueStatistics(
salesAmountStats, orderCountStats);
overviewVO.setAverageOrderValue(averageOrderValueStats);
// 计算成本统计
ProductOverviewVO.DailyStatistics costAmountStats = calculateCostAmountStatistics(
ordersByDate, dateList, orders);
overviewVO.setCostAmount(costAmountStats);
// 计算退款金额统计
ProductOverviewVO.DailyStatistics refundAmountStats = calculateRefundAmountStatistics(
ordersByDate, dateList, orders, refundStatusId);
overviewVO.setRefundAmount(refundAmountStats);
// 计算推广费统计(按商品关联的店铺分摊,这里简化处理:按店铺粒度的推广费均摊到各商品)
ProductOverviewVO.DailyStatistics promotionFeeStats = calculatePromotionFeeStatistics(
promotionFeesByDate, dateList, promotionFees, shopIds.size());
overviewVO.setPromotionFee(promotionFeeStats);
// 计算费比统计
ProductOverviewVO.DailyStatistics feeRatioStats = calculateFeeRatioStatistics(
salesAmountStats, promotionFeeStats);
overviewVO.setFeeRatio(feeRatioStats);
return overviewVO;
}
/**
* 计算销售额统计
*/
private ProductOverviewVO.DailyStatistics calculateSalesAmountStatistics(
Map<LocalDate, List<OrderPO>> ordersByDate, List<LocalDate> dateList, List<OrderPO> allOrders) {
ProductOverviewVO.DailyStatistics stats = new ProductOverviewVO.DailyStatistics();
BigDecimal total = allOrders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
stats.setTotal(total);
List<ProductOverviewVO.DailyData> dailyDataList = dateList.stream()
.map(date -> {
ProductOverviewVO.DailyData dailyData = new ProductOverviewVO.DailyData();
dailyData.setDate(date);
List<OrderPO> dayOrders = ordersByDate.getOrDefault(date, List.of());
BigDecimal dayAmount = dayOrders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
dailyData.setValue(dayAmount);
return dailyData;
})
.sorted(Comparator.comparing(ProductOverviewVO.DailyData::getDate))
.collect(Collectors.toList());
stats.setDailyDataList(dailyDataList);
return stats;
}
/**
* 计算订单数统计
*/
private ProductOverviewVO.DailyStatistics calculateOrderCountStatistics(
Map<LocalDate, List<OrderPO>> ordersByDate, List<LocalDate> dateList, List<OrderPO> allOrders) {
ProductOverviewVO.DailyStatistics stats = new ProductOverviewVO.DailyStatistics();
// 按平台订单号去重统计总订单数
long totalCount = allOrders.stream()
.map(OrderPO::getPlatformOrderNo)
.filter(no -> no != null && !no.isEmpty())
.distinct()
.count();
if (totalCount == 0) {
totalCount = allOrders.size();
}
stats.setTotal(BigDecimal.valueOf(totalCount));
List<ProductOverviewVO.DailyData> dailyDataList = dateList.stream()
.map(date -> {
ProductOverviewVO.DailyData dailyData = new ProductOverviewVO.DailyData();
dailyData.setDate(date);
List<OrderPO> dayOrders = ordersByDate.getOrDefault(date, List.of());
long dayCount = dayOrders.stream()
.map(OrderPO::getPlatformOrderNo)
.filter(no -> no != null && !no.isEmpty())
.distinct()
.count();
if (dayCount == 0) {
dayCount = dayOrders.size();
}
dailyData.setValue(BigDecimal.valueOf(dayCount));
return dailyData;
})
.sorted(Comparator.comparing(ProductOverviewVO.DailyData::getDate))
.collect(Collectors.toList());
stats.setDailyDataList(dailyDataList);
return stats;
}
/**
* 计算客单价统计
*/
private ProductOverviewVO.DailyStatistics calculateAverageOrderValueStatistics(
ProductOverviewVO.DailyStatistics salesAmountStats, ProductOverviewVO.DailyStatistics orderCountStats) {
ProductOverviewVO.DailyStatistics stats = new ProductOverviewVO.DailyStatistics();
BigDecimal totalSales = salesAmountStats.getTotal();
BigDecimal totalOrders = orderCountStats.getTotal();
BigDecimal total = totalOrders.compareTo(BigDecimal.ZERO) > 0
? totalSales.divide(totalOrders, 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
stats.setTotal(total);
List<ProductOverviewVO.DailyData> dailyDataList = new ArrayList<>();
for (int i = 0; i < salesAmountStats.getDailyDataList().size(); i++) {
ProductOverviewVO.DailyData salesData = salesAmountStats.getDailyDataList().get(i);
ProductOverviewVO.DailyData orderData = orderCountStats.getDailyDataList().get(i);
ProductOverviewVO.DailyData dailyData = new ProductOverviewVO.DailyData();
dailyData.setDate(salesData.getDate());
BigDecimal dayValue = orderData.getValue().compareTo(BigDecimal.ZERO) > 0
? salesData.getValue().divide(orderData.getValue(), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
dailyData.setValue(dayValue);
dailyDataList.add(dailyData);
}
stats.setDailyDataList(dailyDataList);
return stats;
}
/**
* 计算成本统计
*/
private ProductOverviewVO.DailyStatistics calculateCostAmountStatistics(
Map<LocalDate, List<OrderPO>> ordersByDate, List<LocalDate> dateList, List<OrderPO> allOrders) {
ProductOverviewVO.DailyStatistics stats = new ProductOverviewVO.DailyStatistics();
BigDecimal total = allOrders.stream()
.map(order -> {
BigDecimal productCost = order.getProductCost() != null ? order.getProductCost() : BigDecimal.ZERO;
BigDecimal shippingCost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO;
BigDecimal otherCost = order.getOtherCost() != null ? order.getOtherCost() : BigDecimal.ZERO;
Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1;
return productCost.add(shippingCost).add(otherCost).multiply(new BigDecimal(quantity));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
stats.setTotal(total);
List<ProductOverviewVO.DailyData> dailyDataList = dateList.stream()
.map(date -> {
ProductOverviewVO.DailyData dailyData = new ProductOverviewVO.DailyData();
dailyData.setDate(date);
List<OrderPO> dayOrders = ordersByDate.getOrDefault(date, List.of());
BigDecimal dayCost = dayOrders.stream()
.map(order -> {
BigDecimal productCost = order.getProductCost() != null ? order.getProductCost() : BigDecimal.ZERO;
BigDecimal shippingCost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO;
BigDecimal otherCost = order.getOtherCost() != null ? order.getOtherCost() : BigDecimal.ZERO;
Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1;
return productCost.add(shippingCost).add(otherCost).multiply(new BigDecimal(quantity));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
dailyData.setValue(dayCost);
return dailyData;
})
.sorted(Comparator.comparing(ProductOverviewVO.DailyData::getDate))
.collect(Collectors.toList());
stats.setDailyDataList(dailyDataList);
return stats;
}
/**
* 计算退款金额统计
*/
private ProductOverviewVO.DailyStatistics calculateRefundAmountStatistics(
Map<LocalDate, List<OrderPO>> ordersByDate, List<LocalDate> dateList,
List<OrderPO> allOrders, Long refundStatusId) {
ProductOverviewVO.DailyStatistics stats = new ProductOverviewVO.DailyStatistics();
BigDecimal total = allOrders.stream()
.filter(order -> refundStatusId != null && refundStatusId.equals(order.getStatusId()))
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
stats.setTotal(total);
List<ProductOverviewVO.DailyData> dailyDataList = dateList.stream()
.map(date -> {
ProductOverviewVO.DailyData dailyData = new ProductOverviewVO.DailyData();
dailyData.setDate(date);
List<OrderPO> dayOrders = ordersByDate.getOrDefault(date, List.of());
BigDecimal dayRefund = dayOrders.stream()
.filter(order -> refundStatusId != null && refundStatusId.equals(order.getStatusId()))
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
dailyData.setValue(dayRefund);
return dailyData;
})
.sorted(Comparator.comparing(ProductOverviewVO.DailyData::getDate))
.collect(Collectors.toList());
stats.setDailyDataList(dailyDataList);
return stats;
}
/**
* 计算推广费统计(推广费按商品关联的店铺均摊)
*/
private ProductOverviewVO.DailyStatistics calculatePromotionFeeStatistics(
Map<LocalDate, List<PromotionFeePO>> promotionFeesByDate, List<LocalDate> dateList,
List<PromotionFeePO> allFees, int shopCount) {
ProductOverviewVO.DailyStatistics stats = new ProductOverviewVO.DailyStatistics();
BigDecimal totalPerProduct = allFees.stream()
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
// 如果有多个店铺,按店铺数量均分(简化处理:假设各商品等比)
if (shopCount > 1) {
totalPerProduct = totalPerProduct.divide(new BigDecimal(shopCount), 2, RoundingMode.HALF_UP);
}
stats.setTotal(totalPerProduct);
List<ProductOverviewVO.DailyData> dailyDataList = dateList.stream()
.map(date -> {
ProductOverviewVO.DailyData dailyData = new ProductOverviewVO.DailyData();
dailyData.setDate(date);
List<PromotionFeePO> dayFees = promotionFeesByDate.getOrDefault(date, List.of());
BigDecimal dayFee = dayFees.stream()
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
if (shopCount > 1) {
dayFee = dayFee.divide(new BigDecimal(shopCount), 2, RoundingMode.HALF_UP);
}
dailyData.setValue(dayFee);
return dailyData;
})
.sorted(Comparator.comparing(ProductOverviewVO.DailyData::getDate))
.collect(Collectors.toList());
stats.setDailyDataList(dailyDataList);
return stats;
}
/**
* 计算费比统计
*/
private ProductOverviewVO.DailyStatistics calculateFeeRatioStatistics(
ProductOverviewVO.DailyStatistics salesAmountStats, ProductOverviewVO.DailyStatistics promotionFeeStats) {
ProductOverviewVO.DailyStatistics stats = new ProductOverviewVO.DailyStatistics();
BigDecimal totalSales = salesAmountStats.getTotal();
BigDecimal totalFee = promotionFeeStats.getTotal();
BigDecimal total = totalSales.compareTo(BigDecimal.ZERO) > 0
? totalFee.divide(totalSales, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
stats.setTotal(total);
List<ProductOverviewVO.DailyData> dailyDataList = new ArrayList<>();
for (int i = 0; i < salesAmountStats.getDailyDataList().size(); i++) {
ProductOverviewVO.DailyData salesData = salesAmountStats.getDailyDataList().get(i);
ProductOverviewVO.DailyData feeData = promotionFeeStats.getDailyDataList().get(i);
ProductOverviewVO.DailyData dailyData = new ProductOverviewVO.DailyData();
dailyData.setDate(salesData.getDate());
BigDecimal dayRatio = salesData.getValue().compareTo(BigDecimal.ZERO) > 0
? feeData.getValue().divide(salesData.getValue(), 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
dailyData.setValue(dayRatio);
dailyDataList.add(dailyData);
}
stats.setDailyDataList(dailyDataList);
return stats;
}
/**
* 获取退款状态ID(根据 is_refund 字段查找)
*/
private Long getRefundStatusId() {
Long companyId = currentUserContext.getCurrentCompanyId();
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getIsRefund, 1)
.select(OrderStatusPO::getId)
.last("LIMIT 1");
OrderStatusPO refundStatus = orderStatusMapper.selectOne(wrapper);
return refundStatus != null ? refundStatus.getId() : null;
}
}