mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 05:49:20 +08:00
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:
+7
-1
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+65
-38
@@ -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);
|
||||
|
||||
+39
@@ -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);
|
||||
}
|
||||
}
|
||||
+36
@@ -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;
|
||||
}
|
||||
+110
@@ -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;
|
||||
}
|
||||
}
|
||||
+18
@@ -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);
|
||||
}
|
||||
+421
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -38,13 +38,14 @@ export async function getImportTaskPageApi(
|
||||
}
|
||||
|
||||
/**
|
||||
* SSE连接管理器(使用fetch API支持自定义请求头)
|
||||
* SSE连接管理器(使用原生EventSource,支持自动重连)
|
||||
*/
|
||||
class SseConnection {
|
||||
private abortController: AbortController | null = null;
|
||||
private eventSource: EventSource | null = null;
|
||||
private accessStore: ReturnType<typeof useAccessStore>;
|
||||
private listeners: Map<string, Set<(event: MessageEvent) => void>> =
|
||||
new Map();
|
||||
// EventSource 原生状态常量
|
||||
private readyState: number = EventSource.CLOSED;
|
||||
|
||||
constructor() {
|
||||
@@ -52,20 +53,38 @@ class SseConnection {
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加事件监听器
|
||||
* 添加事件监听器(需在 connect 之前调用)
|
||||
*/
|
||||
addEventListener(eventType: string, handler: (event: MessageEvent) => void) {
|
||||
if (!this.listeners.has(eventType)) {
|
||||
this.listeners.set(eventType, new Set());
|
||||
}
|
||||
this.listeners.get(eventType)!.add(handler);
|
||||
// 如果 EventSource 已建立,额外绑定一次(防止在 connect 之后调用 listener 漏掉)
|
||||
if (this.eventSource) {
|
||||
this.eventSource.addEventListener(eventType, handler as EventListener);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 建立SSE连接(使用fetch API)
|
||||
* 移除事件监听器
|
||||
*/
|
||||
removeEventListener(eventType: string, handler: (event: MessageEvent) => void) {
|
||||
const handlers = this.listeners.get(eventType);
|
||||
if (handlers) {
|
||||
handlers.delete(handler);
|
||||
}
|
||||
if (this.eventSource) {
|
||||
this.eventSource.removeEventListener(eventType, handler as EventListener);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 建立SSE连接
|
||||
* EventSource 原生支持自动重连,无需手动实现
|
||||
*/
|
||||
connect(): void {
|
||||
if (this.abortController) {
|
||||
if (this.eventSource) {
|
||||
this.disconnect();
|
||||
}
|
||||
|
||||
@@ -75,79 +94,37 @@ class SseConnection {
|
||||
return;
|
||||
}
|
||||
|
||||
const url = `${apiURL}/ec/import-task/sse/connect`;
|
||||
this.abortController = new AbortController();
|
||||
const url = `${apiURL}/ec/import-task/sse/connect?token=${encodeURIComponent(token)}`;
|
||||
this.readyState = EventSource.CONNECTING;
|
||||
|
||||
fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: 'text/event-stream',
|
||||
},
|
||||
signal: this.abortController.signal,
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
throw new Error(`SSE连接失败: ${response.status}`);
|
||||
}
|
||||
const es = new EventSource(url);
|
||||
this.eventSource = es;
|
||||
|
||||
this.readyState = EventSource.OPEN;
|
||||
es.onopen = () => {
|
||||
this.readyState = EventSource.OPEN;
|
||||
};
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
es.onerror = (event) => {
|
||||
this.readyState = EventSource.CLOSED;
|
||||
this.dispatchEvent('error', new MessageEvent('error', { data: event }));
|
||||
// EventSource 会自动重连,无需手动处理
|
||||
};
|
||||
|
||||
if (!reader) {
|
||||
throw new Error('无法获取响应流');
|
||||
}
|
||||
|
||||
// 读取流数据
|
||||
const readStream = () => {
|
||||
reader
|
||||
.read()
|
||||
.then(({ done, value }) => {
|
||||
if (done) {
|
||||
this.readyState = EventSource.CLOSED;
|
||||
return;
|
||||
}
|
||||
|
||||
const chunk = decoder.decode(value, { stream: true });
|
||||
this.parseSSE(chunk);
|
||||
readStream();
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.name !== 'AbortError') {
|
||||
console.error('读取SSE流失败:', error);
|
||||
this.readyState = EventSource.CLOSED;
|
||||
this.dispatchEvent(
|
||||
'error',
|
||||
new MessageEvent('error', { data: error }),
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
readStream();
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.name !== 'AbortError') {
|
||||
console.error('建立SSE连接失败:', error);
|
||||
this.readyState = EventSource.CLOSED;
|
||||
this.dispatchEvent(
|
||||
'error',
|
||||
new MessageEvent('error', { data: error }),
|
||||
);
|
||||
}
|
||||
// 将所有自定义事件类型的 listener 注册到 EventSource 上
|
||||
this.listeners.forEach((handlers, eventType) => {
|
||||
handlers.forEach((handler) => {
|
||||
es.addEventListener(eventType, handler as EventListener);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开连接
|
||||
* 断开连接(手动断开后不会自动重连)
|
||||
*/
|
||||
disconnect() {
|
||||
if (this.abortController) {
|
||||
this.abortController.abort();
|
||||
this.abortController = null;
|
||||
if (this.eventSource) {
|
||||
this.eventSource.close();
|
||||
this.eventSource = null;
|
||||
this.readyState = EventSource.CLOSED;
|
||||
}
|
||||
}
|
||||
@@ -159,22 +136,6 @@ class SseConnection {
|
||||
return this.readyState;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除事件监听器
|
||||
*/
|
||||
removeEventListener(
|
||||
eventType: string,
|
||||
handler: (event: MessageEvent) => void,
|
||||
) {
|
||||
const handlers = this.listeners.get(eventType);
|
||||
if (handlers) {
|
||||
handlers.delete(handler);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分发事件
|
||||
*/
|
||||
private dispatchEvent(eventType: string, event: MessageEvent) {
|
||||
const handlers = this.listeners.get(eventType);
|
||||
if (handlers) {
|
||||
@@ -187,34 +148,6 @@ class SseConnection {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析SSE数据
|
||||
*/
|
||||
private parseSSE(chunk: string) {
|
||||
const lines = chunk.split('\n');
|
||||
let eventType = 'message';
|
||||
let data = '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('event:')) {
|
||||
eventType = line.slice(6).trim();
|
||||
} else if (line.startsWith('data:')) {
|
||||
data += `${line.slice(5).trim()}\n`;
|
||||
} else if (
|
||||
line === '' && // 空行表示一个完整的消息
|
||||
data
|
||||
) {
|
||||
const event = new MessageEvent(eventType, {
|
||||
data: data.trim(),
|
||||
});
|
||||
this.dispatchEvent(eventType, event);
|
||||
this.dispatchEvent('message', event);
|
||||
data = '';
|
||||
eventType = 'message';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { ProductOverviewDTO, ProductOverviewVO } from './types';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
/**
|
||||
* 商品概览管理API
|
||||
*/
|
||||
|
||||
/**
|
||||
* 获取商品总览统计数据
|
||||
*/
|
||||
export async function getProductOverviewApi(params: ProductOverviewDTO.Query) {
|
||||
return requestClient.post<ProductOverviewVO.Overview>(
|
||||
'/ec/product/overview',
|
||||
params,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './apis';
|
||||
export * from './types';
|
||||
@@ -0,0 +1,2 @@
|
||||
export type { ProductOverviewDTO } from './types.dto';
|
||||
export type { ProductOverviewVO } from './types.vo';
|
||||
@@ -0,0 +1,11 @@
|
||||
export namespace ProductOverviewDTO {
|
||||
/** 商品概览查询参数 */
|
||||
export interface Query {
|
||||
/** 商品ID */
|
||||
productId: number;
|
||||
/** 开始日期 */
|
||||
startDate: string;
|
||||
/** 结束日期 */
|
||||
endDate: string;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
export namespace ProductOverviewVO {
|
||||
/** 每日数据项 */
|
||||
export interface DailyData {
|
||||
/** 日期 */
|
||||
date: string;
|
||||
/** 对应的值 */
|
||||
value: number;
|
||||
}
|
||||
|
||||
/** 每日统计数据 */
|
||||
export interface DailyStatistics {
|
||||
/** 时间范围的总值 */
|
||||
total: number;
|
||||
/** 每日数据列表 */
|
||||
dailyDataList: DailyData[];
|
||||
}
|
||||
|
||||
/** 商品总览 */
|
||||
export interface Overview {
|
||||
/** 商品ID */
|
||||
productId: number;
|
||||
/** 商品名称 */
|
||||
productName: string;
|
||||
/** 销售额统计 */
|
||||
salesAmount: DailyStatistics;
|
||||
/** 订单数统计 */
|
||||
orderCount: DailyStatistics;
|
||||
/** 客单价统计 */
|
||||
averageOrderValue: DailyStatistics;
|
||||
/** 成本统计 */
|
||||
costAmount: DailyStatistics;
|
||||
/** 退款金额统计 */
|
||||
refundAmount: DailyStatistics;
|
||||
/** 推广费统计 */
|
||||
promotionFee: DailyStatistics;
|
||||
/** 费比统计 */
|
||||
feeRatio: DailyStatistics;
|
||||
}
|
||||
}
|
||||
@@ -141,8 +141,7 @@ watch(
|
||||
:avatar
|
||||
:menus
|
||||
:text="userStore.userInfo?.realName"
|
||||
description="ann.vben@gmail.com"
|
||||
tag-text="Pro"
|
||||
:description="userStore.userInfo?.phone || '-'"
|
||||
@logout="handleLogout"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -37,9 +37,7 @@ async function generateAccess(options: GenerateMenuAndRoutesOptions) {
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
// 可以指定没有权限跳转403页面
|
||||
forbiddenComponent,
|
||||
// 如果 route.meta.menuVisibleWithForbidden = true
|
||||
layoutMap,
|
||||
pageMap,
|
||||
});
|
||||
|
||||
+25
-3
@@ -1,15 +1,20 @@
|
||||
<script lang="ts" setup>
|
||||
import type { ProductVO } from '#/api/ecommerce/product/types';
|
||||
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { Button, Card, Image, Popconfirm, Popover, Tag } from 'ant-design-vue';
|
||||
|
||||
defineProps<Props>();
|
||||
const emit = defineEmits<Emits>();
|
||||
const router = useRouter();
|
||||
|
||||
// 创建图标组件
|
||||
const EditIcon = createIconifyIcon('lucide:edit');
|
||||
const TrashIcon = createIconifyIcon('lucide:trash-2');
|
||||
const ChartIcon = createIconifyIcon('lucide:bar-chart-2');
|
||||
|
||||
interface Props {
|
||||
product: ProductVO.Info;
|
||||
@@ -27,6 +32,10 @@ const handleEdit = (product: ProductVO.Info) => {
|
||||
const handleDelete = (product: ProductVO.Info) => {
|
||||
emit('delete', product);
|
||||
};
|
||||
|
||||
const goToDetails = (product: ProductVO.Info) => {
|
||||
router.push(`/ecom/product/details/${product.id}`);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -35,9 +44,10 @@ const handleDelete = (product: ProductVO.Info) => {
|
||||
:body-style="{ padding: 0 }"
|
||||
class="group h-full border border-gray-200 transition-all duration-300 ease-out hover:-translate-y-1 hover:border-blue-500 hover:shadow-lg dark:border-gray-700"
|
||||
>
|
||||
<!-- 图片区域 -->
|
||||
<!-- 图片区域(点击进入详情) -->
|
||||
<div
|
||||
class="relative aspect-square cursor-pointer overflow-hidden rounded-t-lg bg-gray-100 dark:bg-neutral-800"
|
||||
@click="goToDetails(product)"
|
||||
>
|
||||
<Image
|
||||
v-if="product.mainImage"
|
||||
@@ -59,10 +69,11 @@ const handleDelete = (product: ProductVO.Info) => {
|
||||
|
||||
<!-- 信息区域 -->
|
||||
<div class="p-3">
|
||||
<!-- 商品名称 -->
|
||||
<!-- 商品名称(点击进入详情) -->
|
||||
<div
|
||||
class="mb-2 line-clamp-2 text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
class="mb-2 line-clamp-2 cursor-pointer text-sm font-medium text-gray-900 hover:text-blue-500 dark:text-gray-100"
|
||||
:title="product.name"
|
||||
@click="goToDetails(product)"
|
||||
>
|
||||
{{ product.name }}
|
||||
</div>
|
||||
@@ -142,6 +153,17 @@ const handleDelete = (product: ProductVO.Info) => {
|
||||
<span class="hidden sm:inline">删除</span>
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
title="查看统计"
|
||||
@click="goToDetails(product)"
|
||||
>
|
||||
<template #icon>
|
||||
<ChartIcon class="h-4 w-4" />
|
||||
</template>
|
||||
<span class="hidden sm:inline">统计</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import { Tabs } from 'ant-design-vue';
|
||||
|
||||
import OverviewTab from './tabs/OverviewTab.vue';
|
||||
|
||||
defineOptions({ name: 'ProductDetails' });
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
// 商品ID(从路由参数获取)
|
||||
const productId = computed(() => {
|
||||
const id = route.params.id;
|
||||
return id ? Number(id) : 0;
|
||||
});
|
||||
|
||||
// 当前激活的 tab
|
||||
const activeKey = ref('overview');
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page auto-content-height content-class="flex flex-col">
|
||||
<Tabs
|
||||
v-model:active-key="activeKey"
|
||||
class="flex min-h-0 flex-1 flex-col"
|
||||
:tab-bar-style="{ marginBottom: '16px' }"
|
||||
>
|
||||
<Tabs.TabPane key="overview" tab="总览">
|
||||
<OverviewTab :product-id="productId" />
|
||||
</Tabs.TabPane>
|
||||
</Tabs>
|
||||
</Page>
|
||||
</template>
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
<script lang="ts" setup>
|
||||
import type { ProductOverviewVO } from '#/api/ecommerce/product-overview/types';
|
||||
|
||||
import { onMounted, ref, watch } from 'vue';
|
||||
|
||||
import { Card, Col, DatePicker, message, Row, Space, Typography } from 'ant-design-vue';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
import { getProductOverviewApi } from '#/api/ecommerce/product-overview';
|
||||
|
||||
import ChartCard from '../../../shop/details/components/ChartCard.vue';
|
||||
|
||||
defineOptions({ name: 'ProductOverviewTab' });
|
||||
|
||||
const props = defineProps<Props>();
|
||||
|
||||
interface Props {
|
||||
productId: number;
|
||||
}
|
||||
|
||||
// 响应式数据
|
||||
const loading = ref(false);
|
||||
const overviewData = ref<null | ProductOverviewVO.Overview>(null);
|
||||
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
|
||||
dayjs().subtract(30, 'day'),
|
||||
dayjs(),
|
||||
]);
|
||||
|
||||
// 格式化金额
|
||||
function formatCurrency(value: number): string {
|
||||
return `¥${value.toLocaleString('zh-CN', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})}`;
|
||||
}
|
||||
|
||||
// 格式化百分比
|
||||
function formatPercent(value: number): string {
|
||||
return `${(value * 100).toFixed(2)}%`;
|
||||
}
|
||||
|
||||
// 获取商品总览数据
|
||||
async function fetchProductOverview() {
|
||||
if (!props.productId || !dateRange.value) return;
|
||||
try {
|
||||
loading.value = true;
|
||||
const data = await getProductOverviewApi({
|
||||
productId: props.productId,
|
||||
startDate: dateRange.value[0].format('YYYY-MM-DD'),
|
||||
endDate: dateRange.value[1].format('YYYY-MM-DD'),
|
||||
});
|
||||
overviewData.value = data;
|
||||
} catch (error) {
|
||||
console.error('获取商品总览失败:', error);
|
||||
message.error('获取商品总览失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 处理日期范围变化
|
||||
function handleDateRangeChange() {
|
||||
fetchProductOverview();
|
||||
}
|
||||
|
||||
// 监听 productId 变化
|
||||
watch(
|
||||
() => props.productId,
|
||||
(newProductId) => {
|
||||
if (newProductId) {
|
||||
fetchProductOverview();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// 初始化数据
|
||||
onMounted(() => {
|
||||
if (props.productId) {
|
||||
fetchProductOverview();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full flex-col">
|
||||
<!-- 日期选择器 -->
|
||||
<Card :loading="loading" class="mb-4 flex-shrink-0">
|
||||
<Space>
|
||||
<span>选择日期范围:</span>
|
||||
<DatePicker.RangePicker
|
||||
v-model:value="dateRange"
|
||||
format="YYYY-MM-DD"
|
||||
@change="handleDateRangeChange"
|
||||
/>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
<!-- 商品名称标题 -->
|
||||
<Card v-if="overviewData" :loading="loading" class="mb-4 flex-shrink-0">
|
||||
<Typography.Title :level="4" style="margin: 0">
|
||||
{{ overviewData.productName }}
|
||||
</Typography.Title>
|
||||
</Card>
|
||||
|
||||
<!-- 图表展示 -->
|
||||
<div v-if="overviewData" class="min-h-0 flex-1 overflow-auto">
|
||||
<Row :gutter="[16, 16]">
|
||||
<!-- 销售额 -->
|
||||
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
|
||||
<ChartCard
|
||||
:data="overviewData.salesAmount"
|
||||
:formatter="formatCurrency"
|
||||
title="销售额"
|
||||
/>
|
||||
</Col>
|
||||
|
||||
<!-- 订单数 -->
|
||||
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
|
||||
<ChartCard
|
||||
:data="overviewData.orderCount"
|
||||
:formatter="(v) => v.toLocaleString()"
|
||||
chart-type="bar"
|
||||
color="#019680"
|
||||
title="订单数"
|
||||
/>
|
||||
</Col>
|
||||
|
||||
<!-- 客单价 -->
|
||||
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
|
||||
<ChartCard
|
||||
:data="overviewData.averageOrderValue"
|
||||
:formatter="formatCurrency"
|
||||
color="#ff9800"
|
||||
title="客单价"
|
||||
/>
|
||||
</Col>
|
||||
|
||||
<!-- 成本 -->
|
||||
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
|
||||
<ChartCard
|
||||
:data="overviewData.costAmount"
|
||||
:formatter="formatCurrency"
|
||||
color="#f56c6c"
|
||||
title="成本"
|
||||
/>
|
||||
</Col>
|
||||
|
||||
<!-- 退款金额 -->
|
||||
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
|
||||
<ChartCard
|
||||
:data="overviewData.refundAmount"
|
||||
:formatter="formatCurrency"
|
||||
color="#e6a23c"
|
||||
title="退款金额"
|
||||
/>
|
||||
</Col>
|
||||
|
||||
<!-- 推广费 -->
|
||||
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
|
||||
<ChartCard
|
||||
:data="overviewData.promotionFee"
|
||||
:formatter="formatCurrency"
|
||||
color="#909399"
|
||||
title="推广费"
|
||||
/>
|
||||
</Col>
|
||||
|
||||
<!-- 费比 -->
|
||||
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
|
||||
<ChartCard
|
||||
:data="overviewData.feeRatio"
|
||||
:formatter="formatPercent"
|
||||
color="#67c23a"
|
||||
title="费比"
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div v-else class="flex flex-1 items-center justify-center">
|
||||
<span class="text-gray-400">暂无数据</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
Reference in New Issue
Block a user