feat: 添加店铺概览统计功能及退款状态支持

This commit is contained in:
ah--desktop
2026-01-15 00:02:38 +08:00
parent 290223fdba
commit 0056f2bb11
21 changed files with 2052 additions and 6 deletions
@@ -16,10 +16,13 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shop.ShopFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shop.ShopProductPageFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shop.ShopStatisticsQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shop.UpdateShopDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.overview.ShopOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopOverviewVO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopOverviewStatisticsVO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopOverviewStatisticsService;
import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
import top.xyquan.ecomdmbbackend.utils.FileUploadUtils;
@@ -32,9 +35,11 @@ import top.xyquan.ecomdmbbackend.utils.FileUploadUtils;
public class ShopController {
private final ShopService shopService;
private final ShopOverviewStatisticsService shopOverviewStatisticsService;
public ShopController(ShopService shopService) {
public ShopController(ShopService shopService, ShopOverviewStatisticsService shopOverviewStatisticsService) {
this.shopService = shopService;
this.shopOverviewStatisticsService = shopOverviewStatisticsService;
}
@Operation(summary = "创建店铺", description = "创建新的店铺")
@@ -102,4 +107,12 @@ public class ShopController {
PageResultVO<ProductVO> result = shopService.getShopProductPage(pageQueryDTO);
return ApiResponse.success(result);
}
@Operation(summary = "获取店铺概览统计数据", description = "获取指定店铺的概览统计数据,包括销售额、单量、推广费、利润、ROI等,以及多商品数据横向对比")
@PostMapping("/overview-statistics")
@RequireRole(description = "查询店铺概览统计", allowUser = true)
public ApiResponse<ShopOverviewStatisticsVO> getShopOverviewStatistics(@Valid @RequestBody ShopOverviewQueryDTO queryDTO) {
ShopOverviewStatisticsVO overviewVO = shopOverviewStatisticsService.getShopOverviewStatistics(queryDTO);
return ApiResponse.success(overviewVO);
}
}
@@ -37,5 +37,11 @@ public class CreateOrderStatusDTO {
@Schema(description = "是否自动参与统计", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "是否自动参与统计不能为空")
private Integer autoStatistics;
/**
* 是否为退款状态 0否 1是
*/
@Schema(description = "是否为退款状态", example = "0")
private Integer isRefund;
}
@@ -37,5 +37,11 @@ public class UpdateOrderStatusDTO {
@Schema(description = "是否自动参与统计", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "是否自动参与统计不能为空")
private Integer autoStatistics;
/**
* 是否为退款状态 0否 1是
*/
@Schema(description = "是否为退款状态", example = "0")
private Integer isRefund;
}
@@ -0,0 +1,34 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.overview;
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 ShopOverviewQueryDTO {
/**
* 店铺ID
*/
@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;
}
@@ -50,6 +50,12 @@ public class OrderStatusPO {
@TableField("auto_statistics")
private Integer autoStatistics;
/**
* 是否为退款状态 0否 1是
*/
@TableField("is_refund")
private Integer isRefund;
/**
* 创建时间
*/
@@ -48,6 +48,12 @@ public class OrderStatusVO {
@Schema(description = "是否自动参与统计", example = "1")
private Integer autoStatistics;
/**
* 是否为退款状态 0否 1是
*/
@Schema(description = "是否为退款状态", example = "0")
private Integer isRefund;
/**
* 创建时间
*/
@@ -0,0 +1,205 @@
package top.xyquan.ecomdmbbackend.modules.ecom.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 ShopOverviewStatisticsVO {
/**
* 店铺总销售额
*/
@Schema(description = "店铺总销售额", example = "100000.00")
private BigDecimal totalSalesAmount;
/**
* 较上月同期增长百分比
*/
@Schema(description = "较上月同期增长百分比", example = "15.50")
private BigDecimal monthOverMonthGrowth;
/**
* 店铺总单量
*/
@Schema(description = "店铺总单量", example = "1000")
private Integer totalOrderCount;
/**
* 总推广费支出
*/
@Schema(description = "总推广费支出", example = "5000.00")
private BigDecimal totalPromotionFee;
/**
* 平均费比(推广费/销售额)
*/
@Schema(description = "平均费比", example = "0.05")
private BigDecimal averageFeeRatio;
/**
* 店铺总净利(税后)
*/
@Schema(description = "店铺总净利(税后)", example = "80000.00")
private BigDecimal totalNetProfitAfterTax;
/**
* 扣除总税额
*/
@Schema(description = "扣除总税额", example = "6000.00")
private BigDecimal totalTaxAmount;
/**
* 店铺总销量目标(目标订单数)
*/
@Schema(description = "店铺总销量目标(目标订单数)", example = "1200")
private Integer totalTargetOrderCount;
/**
* 店铺总销售额目标
*/
@Schema(description = "店铺总销售额目标", example = "120000.00")
private BigDecimal totalTargetAmount;
/**
* 销量目标达成率
*/
@Schema(description = "销量目标达成率", example = "83.33")
private BigDecimal orderCountAchievementRate;
/**
* 销售额目标达成率
*/
@Schema(description = "销售额目标达成率", example = "83.33")
private BigDecimal salesAmountAchievementRate;
/**
* 汇总ROI
*/
@Schema(description = "汇总ROI", example = "1.5")
private BigDecimal totalROI;
/**
* 总税后盈亏
*/
@Schema(description = "总税后盈亏", example = "80000.00")
private BigDecimal totalProfitAfterTax;
/**
* 销售额趋势分析
*/
@Schema(description = "销售额趋势分析")
private TrendData salesAmountTrend;
/**
* 单量趋势分析
*/
@Schema(description = "单量趋势分析")
private TrendData orderCountTrend;
/**
* 多商品数据横向对比
*/
@Schema(description = "多商品数据横向对比")
private List<ProductComparison> productComparisons;
/**
* 商品对比数据
*/
@Data
@Schema(description = "商品对比数据")
public static class ProductComparison {
@Schema(description = "商品ID", example = "1")
private Long productId;
@Schema(description = "商品名称", example = "iPhone 15 Pro")
private String productName;
@Schema(description = "商品编码", example = "IPHONE15PRO")
private String productCode;
@Schema(description = "销售额", example = "50000.00")
private BigDecimal salesAmount;
@Schema(description = "单量", example = "500")
private Integer orderCount;
@Schema(description = "客单价", example = "100.00")
private BigDecimal averageOrderValue;
@Schema(description = "成本运费", example = "5000.00")
private BigDecimal shippingCost;
@Schema(description = "退款金额", example = "1000.00")
private BigDecimal refundAmount;
@Schema(description = "推广费", example = "5000.00")
private BigDecimal totalPromotionFee;
@Schema(description = "刷单费用", example = "2000.00")
private BigDecimal brushFee;
@Schema(description = "费比", example = "0.10")
private BigDecimal feeRatio;
@Schema(description = "税前盈亏", example = "35000.00")
private BigDecimal totalProfitBeforeTax;
@Schema(description = "销售额4%税额", example = "2000.00")
private BigDecimal salesTaxAmount;
@Schema(description = "税后盈亏", example = "30000.00")
private BigDecimal profitAfterTax;
@Schema(description = "ROI", example = "1.5")
private BigDecimal roi;
}
/**
* 趋势数据
*/
@Data
@Schema(description = "趋势数据")
public static class TrendData {
/**
* 时间范围的总值
*/
@Schema(description = "时间范围的总值")
private BigDecimal total;
/**
* 每日数据列表
*/
@Schema(description = "每日数据列表")
private List<TrendDataItem> dailyDataList;
}
/**
* 趋势数据项
*/
@Data
@Schema(description = "趋势数据项")
public static class TrendDataItem {
/**
* 日期
*/
@JsonFormat(pattern = "yyyy-MM-dd")
@Schema(description = "日期", example = "2024-01-01")
private LocalDate date;
/**
* 对应的值
*/
@Schema(description = "对应的值")
private BigDecimal value;
}
}
@@ -0,0 +1,19 @@
package top.xyquan.ecomdmbbackend.modules.ecom.service;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.overview.ShopOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopOverviewStatisticsVO;
/**
* 单店铺概览统计服务接口
*/
public interface ShopOverviewStatisticsService {
/**
* 获取单店铺概览统计数据
*
* @param queryDTO 查询DTO
* @return 单店铺概览统计VO
*/
ShopOverviewStatisticsVO getShopOverviewStatistics(ShopOverviewQueryDTO queryDTO);
}
@@ -624,13 +624,13 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
}
/**
* 获取退款状态ID
* 获取退款状态ID(通过 is_refund 字段查询)
*/
private Long getRefundStatusId() {
Long companyId = currentUserContext.getCurrentCompanyId();
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getStatusName, "已退款")
.eq(OrderStatusPO::getIsRefund, 1)
.last("LIMIT 1");
OrderStatusPO status = orderStatusService.getOne(wrapper);
return status != null ? status.getId() : null;
@@ -61,6 +61,9 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
if (orderStatus.getAutoStatistics() == null) {
orderStatus.setAutoStatistics(1);
}
if (orderStatus.getIsRefund() == null) {
orderStatus.setIsRefund(0);
}
// 设置创建人ID
orderStatus.setCreateBy(currentUserContext.getCurrentUserId());
@@ -0,0 +1,527 @@
package top.xyquan.ecomdmbbackend.modules.ecom.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.mapper.BrushOrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.ShopMonthlyTargetMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.overview.ShopOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.BrushOrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ShopMonthlyTargetPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopOverviewStatisticsVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopOverviewStatisticsService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopService;
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 ShopOverviewStatisticsServiceImpl implements ShopOverviewStatisticsService {
private static final BigDecimal SALES_TAX_RATE = new BigDecimal("0.04"); // 销售额4%税额
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 ShopOverviewStatisticsServiceImpl(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 ShopOverviewStatisticsVO getShopOverviewStatistics(ShopOverviewQueryDTO queryDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
// 解析日期范围
LocalDate startDate;
LocalDate endDate;
if (queryDTO.getDateRange().size() == 1) {
startDate = queryDTO.getDateRange().get(0);
endDate = startDate;
} else {
startDate = queryDTO.getDateRange().get(0);
endDate = queryDTO.getDateRange().get(1);
if (startDate.isAfter(endDate)) {
throw new BusinessException("开始日期不能晚于结束日期");
}
}
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
// 验证店铺是否存在
ShopPO shop = shopService.getById(queryDTO.getShopId());
if (shop == null || !shop.getCompanyId().equals(companyId)) {
throw new BusinessException("店铺不存在");
}
// 查询订单数据(该店铺)
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getShopId, queryDTO.getShopId())
.ge(OrderPO::getOrderTime, startDateTime)
.le(OrderPO::getOrderTime, endDateTime);
List<OrderPO> orders = orderMapper.selectList(orderWrapper);
// 查询推广费数据(该店铺)
LambdaQueryWrapper<PromotionFeePO> promotionWrapper = new LambdaQueryWrapper<>();
promotionWrapper.eq(PromotionFeePO::getCompanyId, companyId)
.eq(PromotionFeePO::getShopId, queryDTO.getShopId())
.ge(PromotionFeePO::getFeeDate, startDate)
.le(PromotionFeePO::getFeeDate, endDate);
List<PromotionFeePO> promotionFees = promotionFeeMapper.selectList(promotionWrapper);
// 查询刷单费数据(该店铺)
LambdaQueryWrapper<BrushOrderPO> brushWrapper = new LambdaQueryWrapper<>();
brushWrapper.eq(BrushOrderPO::getCompanyId, companyId)
.eq(BrushOrderPO::getShopId, queryDTO.getShopId())
.ge(BrushOrderPO::getBrushTime, startDateTime)
.le(BrushOrderPO::getBrushTime, endDateTime);
List<BrushOrderPO> brushOrders = brushOrderMapper.selectList(brushWrapper);
// 获取退款状态ID
Long refundStatusId = getRefundStatusId();
// 计算上月同期数据(用于增长百分比)
LocalDate lastMonthStartDate = startDate.minusMonths(1);
LocalDate lastMonthEndDate = endDate.minusMonths(1);
LocalDateTime lastMonthStartDateTime = lastMonthStartDate.atStartOfDay();
LocalDateTime lastMonthEndDateTime = lastMonthEndDate.atTime(23, 59, 59);
LambdaQueryWrapper<OrderPO> lastMonthOrderWrapper = new LambdaQueryWrapper<>();
lastMonthOrderWrapper.eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getShopId, queryDTO.getShopId())
.ge(OrderPO::getOrderTime, lastMonthStartDateTime)
.le(OrderPO::getOrderTime, lastMonthEndDateTime);
List<OrderPO> lastMonthOrders = orderMapper.selectList(lastMonthOrderWrapper);
// 构建返回对象
ShopOverviewStatisticsVO overviewVO = new ShopOverviewStatisticsVO();
// 1. 计算店铺总销售额
BigDecimal totalSalesAmount = orders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
overviewVO.setTotalSalesAmount(totalSalesAmount);
// 2. 计算较上月同期增长百分比
BigDecimal lastMonthSalesAmount = lastMonthOrders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal monthOverMonthGrowth = BigDecimal.ZERO;
if (lastMonthSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
monthOverMonthGrowth = totalSalesAmount.subtract(lastMonthSalesAmount)
.divide(lastMonthSalesAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"));
} else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
monthOverMonthGrowth = new BigDecimal("100");
}
overviewVO.setMonthOverMonthGrowth(monthOverMonthGrowth);
// 3. 计算店铺总单量
int totalOrderCount = orders.size();
overviewVO.setTotalOrderCount(totalOrderCount);
// 4. 计算总推广费支出
BigDecimal totalPromotionFee = promotionFees.stream()
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
overviewVO.setTotalPromotionFee(totalPromotionFee);
// 5. 计算平均费比
BigDecimal averageFeeRatio = BigDecimal.ZERO;
if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
averageFeeRatio = totalPromotionFee.divide(totalSalesAmount, 4, RoundingMode.HALF_UP);
}
overviewVO.setAverageFeeRatio(averageFeeRatio);
// 6. 计算店铺总净利(税后)和总税额
BigDecimal totalProfitBeforeTax = calculateTotalProfit(orders);
BigDecimal totalSalesTaxAmount = totalSalesAmount.multiply(SALES_TAX_RATE);
BigDecimal totalNetProfitAfterTax = totalProfitBeforeTax.subtract(totalSalesTaxAmount);
overviewVO.setTotalNetProfitAfterTax(totalNetProfitAfterTax);
overviewVO.setTotalTaxAmount(totalSalesTaxAmount);
// 7. 计算目标维度的数据
calculateTargetData(overviewVO, companyId, queryDTO.getShopId(), startDate, endDate, totalSalesAmount, totalOrderCount);
// 8. 汇总ROI和总税后盈亏
BigDecimal totalROI = calculateTotalROI(orders, promotionFees, brushOrders);
overviewVO.setTotalROI(totalROI);
overviewVO.setTotalProfitAfterTax(totalNetProfitAfterTax);
// 9. 计算趋势分析数据
ShopOverviewStatisticsVO.TrendData salesAmountTrend = calculateSalesAmountTrend(orders, startDate, endDate);
ShopOverviewStatisticsVO.TrendData orderCountTrend = calculateOrderCountTrend(orders, startDate, endDate);
overviewVO.setSalesAmountTrend(salesAmountTrend);
overviewVO.setOrderCountTrend(orderCountTrend);
// 10. 多商品数据横向对比
List<ShopOverviewStatisticsVO.ProductComparison> productComparisons = calculateProductComparisons(
orders, promotionFees, brushOrders, refundStatusId);
overviewVO.setProductComparisons(productComparisons);
return overviewVO;
}
/**
* 计算总利润(税前)
*/
private BigDecimal calculateTotalProfit(List<OrderPO> orders) {
return orders.stream()
.map(order -> {
BigDecimal receivedAmount = order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO;
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;
BigDecimal totalCost = productCost.add(shippingCost).add(otherCost).multiply(new BigDecimal(quantity));
return receivedAmount.subtract(totalCost);
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
/**
* 计算目标维度的数据
*/
private void calculateTargetData(ShopOverviewStatisticsVO overviewVO, Long companyId, Long shopId,
LocalDate startDate, LocalDate endDate,
BigDecimal totalSalesAmount, Integer totalOrderCount) {
// 生成日期范围内所有月份的第一天列表
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, shopId)
.in(ShopMonthlyTargetPO::getTargetMonth, targetMonths);
List<ShopMonthlyTargetPO> targets = shopMonthlyTargetMapper.selectList(targetWrapper);
// 汇总目标数据
BigDecimal totalTargetAmount = targets.stream()
.map(target -> target.getTargetAmount() != null ? target.getTargetAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Integer totalTargetOrderCount = targets.stream()
.mapToInt(target -> target.getTargetOrderCount() != null ? target.getTargetOrderCount() : 0)
.sum();
overviewVO.setTotalTargetAmount(totalTargetAmount);
overviewVO.setTotalTargetOrderCount(totalTargetOrderCount);
// 计算达成率
BigDecimal salesAmountAchievementRate = BigDecimal.ZERO;
if (totalTargetAmount.compareTo(BigDecimal.ZERO) > 0) {
salesAmountAchievementRate = totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"));
} else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
salesAmountAchievementRate = new BigDecimal("100");
}
overviewVO.setSalesAmountAchievementRate(salesAmountAchievementRate);
BigDecimal orderCountAchievementRate = BigDecimal.ZERO;
if (totalTargetOrderCount > 0) {
orderCountAchievementRate = new BigDecimal(totalOrderCount)
.divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"));
} else if (totalOrderCount > 0) {
orderCountAchievementRate = new BigDecimal("100");
}
overviewVO.setOrderCountAchievementRate(orderCountAchievementRate);
}
/**
* 计算汇总ROI
*/
private BigDecimal calculateTotalROI(List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders) {
BigDecimal totalProfit = calculateTotalProfit(orders);
BigDecimal totalPromotionFee = promotionFees.stream()
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalBrushFee = brushOrders.stream()
.map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalCost = totalPromotionFee.add(totalBrushFee);
return calculateROI(totalProfit, totalCost);
}
/**
* 计算ROI
*/
private BigDecimal calculateROI(BigDecimal profit, BigDecimal totalCost) {
if (totalCost.compareTo(BigDecimal.ZERO) <= 0) {
return BigDecimal.ZERO;
}
return profit.divide(totalCost, 4, RoundingMode.HALF_UP);
}
/**
* 计算多商品数据横向对比
*/
private List<ShopOverviewStatisticsVO.ProductComparison> calculateProductComparisons(
List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, Long refundStatusId) {
List<ShopOverviewStatisticsVO.ProductComparison> comparisons = new ArrayList<>();
// 按商品分组订单数据
Map<Long, List<OrderPO>> ordersByProduct = orders.stream()
.collect(Collectors.groupingBy(OrderPO::getProductId));
// 按商品分组刷单费数据(如果有商品ID)
Map<Long, List<BrushOrderPO>> brushOrdersByProduct = brushOrders.stream()
.filter(brush -> brush.getProductId() != null)
.collect(Collectors.groupingBy(BrushOrderPO::getProductId));
// 推广费无法按商品分组(推广费只有店铺级别),所以每个商品使用相同的推广费比例
BigDecimal totalPromotionFee = promotionFees.stream()
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalSalesAmount = orders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
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(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
int orderCount = productOrders.size();
BigDecimal refundAmount = productOrders.stream()
.filter(order -> refundStatusId != null && refundStatusId.equals(order.getStatusId()))
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal brushFee = brushOrdersByProduct.getOrDefault(productId, new ArrayList<>()).stream()
.map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
// 推广费按销售额比例分配
BigDecimal productPromotionFee = BigDecimal.ZERO;
if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
BigDecimal ratio = salesAmount.divide(totalSalesAmount, 4, RoundingMode.HALF_UP);
productPromotionFee = totalPromotionFee.multiply(ratio);
}
// 计算成本运费(单独计算运费成本)
BigDecimal shippingCost = productOrders.stream()
.map(order -> {
BigDecimal cost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO;
Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1;
return cost.multiply(new BigDecimal(quantity));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalCost = calculateProductTotalCost(productOrders);
BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount);
// 销售额4%税额
BigDecimal salesTaxAmount = salesAmount.multiply(SALES_TAX_RATE);
// 税后盈亏(扣除销售额4%税额)
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount);
BigDecimal totalCostForROI = productPromotionFee.add(brushFee);
BigDecimal roi = calculateROI(profitBeforeTax, totalCostForROI);
BigDecimal feeRatio = BigDecimal.ZERO;
if (salesAmount.compareTo(BigDecimal.ZERO) > 0) {
feeRatio = productPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP);
}
BigDecimal averageOrderValue = BigDecimal.ZERO;
if (orderCount > 0) {
averageOrderValue = salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP);
}
ShopOverviewStatisticsVO.ProductComparison comparison = new ShopOverviewStatisticsVO.ProductComparison();
comparison.setProductId(productId);
comparison.setProductName(product.getName());
comparison.setProductCode(product.getProductCode());
comparison.setSalesAmount(salesAmount);
comparison.setOrderCount(orderCount);
comparison.setAverageOrderValue(averageOrderValue);
comparison.setShippingCost(shippingCost);
comparison.setRefundAmount(refundAmount);
comparison.setTotalPromotionFee(productPromotionFee);
comparison.setBrushFee(brushFee);
comparison.setFeeRatio(feeRatio);
comparison.setTotalProfitBeforeTax(profitBeforeTax);
comparison.setSalesTaxAmount(salesTaxAmount);
comparison.setProfitAfterTax(profitAfterTax);
comparison.setRoi(roi);
comparisons.add(comparison);
}
// 按销售额降序排序
comparisons.sort(Comparator.comparing(ShopOverviewStatisticsVO.ProductComparison::getSalesAmount).reversed());
return comparisons;
}
/**
* 计算商品总成本(订单成本)
*/
private BigDecimal calculateProductTotalCost(List<OrderPO> orders) {
return orders.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);
}
/**
* 计算销售额趋势分析
*/
private ShopOverviewStatisticsVO.TrendData calculateSalesAmountTrend(List<OrderPO> orders, LocalDate startDate, LocalDate endDate) {
ShopOverviewStatisticsVO.TrendData trendData = new ShopOverviewStatisticsVO.TrendData();
// 按日期分组订单数据
Map<LocalDate, List<OrderPO>> ordersByDate = orders.stream()
.collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate()));
// 计算总销售额
BigDecimal total = orders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
trendData.setTotal(total);
// 生成日期范围内的所有日期列表
List<LocalDate> dateList = new ArrayList<>();
LocalDate currentDate = startDate;
while (!currentDate.isAfter(endDate)) {
dateList.add(currentDate);
currentDate = currentDate.plusDays(1);
}
// 计算每日销售额
List<ShopOverviewStatisticsVO.TrendDataItem> dailyDataList = dateList.stream()
.map(date -> {
ShopOverviewStatisticsVO.TrendDataItem item = new ShopOverviewStatisticsVO.TrendDataItem();
item.setDate(date);
List<OrderPO> dayOrders = ordersByDate.getOrDefault(date, new ArrayList<>());
BigDecimal dayAmount = dayOrders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
item.setValue(dayAmount);
return item;
})
.sorted(Comparator.comparing(ShopOverviewStatisticsVO.TrendDataItem::getDate))
.collect(Collectors.toList());
trendData.setDailyDataList(dailyDataList);
return trendData;
}
/**
* 计算单量趋势分析
*/
private ShopOverviewStatisticsVO.TrendData calculateOrderCountTrend(List<OrderPO> orders, LocalDate startDate, LocalDate endDate) {
ShopOverviewStatisticsVO.TrendData trendData = new ShopOverviewStatisticsVO.TrendData();
// 按日期分组订单数据
Map<LocalDate, List<OrderPO>> ordersByDate = orders.stream()
.collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate()));
// 计算总单量
int totalCount = orders.size();
trendData.setTotal(new BigDecimal(totalCount));
// 生成日期范围内的所有日期列表
List<LocalDate> dateList = new ArrayList<>();
LocalDate currentDate = startDate;
while (!currentDate.isAfter(endDate)) {
dateList.add(currentDate);
currentDate = currentDate.plusDays(1);
}
// 计算每日单量
List<ShopOverviewStatisticsVO.TrendDataItem> dailyDataList = dateList.stream()
.map(date -> {
ShopOverviewStatisticsVO.TrendDataItem item = new ShopOverviewStatisticsVO.TrendDataItem();
item.setDate(date);
List<OrderPO> dayOrders = ordersByDate.getOrDefault(date, new ArrayList<>());
int dayCount = dayOrders.size();
item.setValue(new BigDecimal(dayCount));
return item;
})
.sorted(Comparator.comparing(ShopOverviewStatisticsVO.TrendDataItem::getDate))
.collect(Collectors.toList());
trendData.setDailyDataList(dailyDataList);
return trendData;
}
/**
* 获取退款状态ID(通过 is_refund 字段查询)
*/
private Long getRefundStatusId() {
Long companyId = currentUserContext.getCurrentCompanyId();
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getIsRefund, 1)
.last("LIMIT 1");
OrderStatusPO status = orderStatusService.getOne(wrapper);
return status != null ? status.getId() : null;
}
}
@@ -251,13 +251,14 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
}
/**
* 获取退款状态ID(根据状态名称"已退款"查找)
* 获取退款状态ID(根据 is_refund 字段查找)
*/
private Long getRefundStatusId() {
Long companyId = currentUserContext.getCurrentCompanyId();
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getStatusName, "已退款");
.eq(OrderStatusPO::getIsRefund, 1)
.last("LIMIT 1");
OrderStatusPO status = orderStatusService.getOne(wrapper);
return status != null ? status.getId() : null;
}
@@ -80,6 +80,7 @@ CREATE TABLE `ec_order_status` (
`description` VARCHAR(200) DEFAULT NULL COMMENT '状态描述',
`sort_order` INT NOT NULL DEFAULT 0 COMMENT '排序',
`auto_statistics` TINYINT NOT NULL DEFAULT 1 COMMENT '是否自动参与统计 0不参与 1参与',
`is_refund` TINYINT NOT NULL DEFAULT 0 COMMENT '是否为退款状态 0否 1是',
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` BIGINT UNSIGNED DEFAULT NULL COMMENT '创建人ID',
@@ -89,6 +90,7 @@ CREATE TABLE `ec_order_status` (
UNIQUE KEY `uk_company_status_name` (`company_id`, `status_name`),
KEY `idx_sort_order` (`sort_order`),
KEY `idx_auto_statistics` (`auto_statistics`),
KEY `idx_is_refund` (`is_refund`),
KEY `fk_ec_order_status_creator` (`create_by`),
KEY `fk_ec_order_status_updater` (`update_by`),
CONSTRAINT `fk_ec_order_status_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,