feat(product): 商品详情页对接真实API,替换mock数据

后端:
- 重写 ProductOverviewServiceImpl匹配新的扁平化VO结构
- ProductOverviewVO: 新增 totalSalesAmount/monthOverMonthGrowth/totalROI 等扁平KPI字段
- ProductOverviewQueryDTO: 支持 productId/startDate/endDate/taxRate

前端:
- types.vo.ts: 适配新VO结构 (KPI字段扁平化+趋势数据+规格汇总)
- types.dto.ts: 更新查询DTO
- details/index.vue: fetchOverview调用真实API,normalizeOverview保留所有字段
- details/components/: StatCards/SalesTrendChart/FinancialPanel/SpecSummaryTable 适配新数据
- 修复 formatPercentPlain 对 null 值崩溃的问题
- StatCards/SalesTrendChart/FinancialPanel 使用 v-if 保护避免初始渲染报错
This commit is contained in:
小蟑螂
2026-04-27 22:44:53 +08:00
parent c8651a7dd1
commit 89604da32e
14 changed files with 2121 additions and 429 deletions
@@ -4,6 +4,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
/**
@@ -33,4 +34,10 @@ public class ProductOverviewQueryDTO {
@Schema(description = "结束日期", example = "2024-01-31", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "结束日期不能为空")
private LocalDate endDate;
}
/**
* 税率(默认0.04)
*/
@Schema(description = "税率,用于计算税额,默认0.04", example = "0.04")
private BigDecimal taxRate = new BigDecimal("0.04");
}
@@ -9,10 +9,10 @@ import java.time.LocalDate;
import java.util.List;
/**
* 商品总览VO
* 商品概览响应VO
*/
@Data
@Schema(description = "商品总览VO")
@Schema(description = "商品概览响应VO")
public class ProductOverviewVO {
/**
@@ -27,54 +27,116 @@ public class ProductOverviewVO {
@Schema(description = "商品名称")
private String productName;
/**
* 销售额统计
*/
@Schema(description = "销售额统计")
private DailyStatistics salesAmount;
// ========== KPI 汇总指标 ==========
/**
* 订单数统计
* 总销售额
*/
@Schema(description = "订单数统计")
private DailyStatistics orderCount;
@Schema(description = "总销售额")
private BigDecimal totalSalesAmount;
/**
* 客单价统计
* 较上月同期增长百分比
*/
@Schema(description = "客单价统计")
private DailyStatistics averageOrderValue;
@Schema(description = "较上月同期增长百分比", example = "15.50")
private BigDecimal monthOverMonthGrowth;
/**
* 成本统计
* 总订单量
*/
@Schema(description = "成本统计")
private DailyStatistics costAmount;
@Schema(description = "总订单量")
private Integer totalOrderCount;
/**
* 退款金额统计
* 平均费比(推广费/销售额)
*/
@Schema(description = "退款金额统计")
private DailyStatistics refundAmount;
@Schema(description = "平均费比")
private BigDecimal averageFeeRatio;
/**
* 推广费统计
* 总净利润(税后)
*/
@Schema(description = "推广费统计")
private DailyStatistics promotionFee;
@Schema(description = "总净利润(税后)")
private BigDecimal totalNetProfitAfterTax;
/**
* 费比统计
* 扣除总税额
*/
@Schema(description = "费比统计")
private DailyStatistics feeRatio;
@Schema(description = "扣除总税额")
private BigDecimal totalTaxAmount;
/**
* 每日统计数据
* 销量目标达成率
*/
@Schema(description = "销量目标达成率")
private BigDecimal orderCountAchievementRate;
/**
* 销售额目标达成率
*/
@Schema(description = "销售额目标达成率")
private BigDecimal salesAmountAchievementRate;
/**
* 汇总ROI
*/
@Schema(description = "汇总ROI")
private BigDecimal totalROI;
/**
* 汇总客单价
*/
@Schema(description = "汇总客单价")
private BigDecimal averageOrderValue;
/**
* 退款金额合计
*/
@Schema(description = "退款金额合计")
private BigDecimal refundAmount;
/**
* 税前盈亏
*/
@Schema(description = "税前盈亏")
private BigDecimal totalProfitBeforeTax;
/**
* 总税后盈亏(与 totalNetProfitAfterTax 一致)
*/
@Schema(description = "总税后盈亏")
private BigDecimal totalProfitAfterTax;
// ========== 趋势数据 ==========
/**
* 销售额趋势分析
*/
@Schema(description = "销售额趋势分析")
private TrendData salesAmountTrend;
/**
* 单量趋势分析
*/
@Schema(description = "单量趋势分析")
private TrendData orderCountTrend;
// ========== 规格销售汇总 ==========
/**
* 规格销售汇总(含各规格明细列表和合计行)
*/
@Schema(description = "规格销售汇总")
private SpecSummary specSummaries;
// ========== 内部类 ==========
/**
* 趋势数据
*/
@Data
@Schema(description = "每日统计数据")
public static class DailyStatistics {
@Schema(description = "趋势数据")
public static class TrendData {
/**
* 时间范围的总值
*/
@@ -85,15 +147,15 @@ public class ProductOverviewVO {
* 每日数据列表
*/
@Schema(description = "每日数据列表")
private List<DailyData> dailyDataList;
private List<TrendDataItem> dailyDataList;
}
/**
* 每日数据项
* 趋势数据项
*/
@Data
@Schema(description = "每日数据项")
public static class DailyData {
@Schema(description = "趋势数据项")
public static class TrendDataItem {
/**
* 日期
*/
@@ -107,4 +169,217 @@ public class ProductOverviewVO {
@Schema(description = "对应的值")
private BigDecimal value;
}
}
/**
* 规格销售汇总
*/
@Data
@Schema(description = "规格销售汇总")
public static class SpecSummary {
/**
* 各规格明细列表
*/
@Schema(description = "各规格明细列表")
private List<SpecSummaryItem> list;
/**
* 合计行
*/
@Schema(description = "合计行")
private SpecSummaryTotal total;
}
/**
* 规格销售明细项
*/
@Data
@Schema(description = "规格销售明细项")
public static class SpecSummaryItem {
/**
* 规格ID
*/
@Schema(description = "规格ID")
private Long specId;
/**
* 规格名称
*/
@Schema(description = "规格名称")
private String specName;
/**
* 规格编码
*/
@Schema(description = "规格编码")
private String specCode;
/**
* 销售额
*/
@Schema(description = "销售额")
private BigDecimal salesAmount;
/**
* 订单量(按平台订单号去重)
*/
@Schema(description = "订单量")
private Integer orderCount;
/**
* 总件数
*/
@Schema(description = "总件数")
private Integer quantity;
/**
* 客单价
*/
@Schema(description = "客单价")
private BigDecimal averageOrderValue;
/**
* 商品成本
*/
@Schema(description = "商品成本")
private BigDecimal productCost;
/**
* 运费
*/
@Schema(description = "运费")
private BigDecimal shippingCost;
/**
* 其他成本
*/
@Schema(description = "其他成本")
private BigDecimal otherCost;
/**
* 退款金额
*/
@Schema(description = "退款金额")
private BigDecimal refundAmount;
/**
* 推广费
*/
@Schema(description = "推广费")
private BigDecimal promotionFee;
/**
* 费比(推广费/销售额)
*/
@Schema(description = "费比")
private BigDecimal feeRatio;
/**
* 税前盈亏
*/
@Schema(description = "税前盈亏")
private BigDecimal profitBeforeTax;
/**
* 销售额×税率的税额
*/
@Schema(description = "销售额×税率的税额")
private BigDecimal salesTaxAmount;
/**
* ROI
*/
@Schema(description = "ROI")
private BigDecimal roi;
/**
* 税后盈亏
*/
@Schema(description = "税后盈亏")
private BigDecimal profitAfterTax;
}
/**
* 规格销售汇总合计行
*/
@Data
@Schema(description = "规格销售汇总合计行")
public static class SpecSummaryTotal {
/**
* 销售额
*/
@Schema(description = "销售额")
private BigDecimal salesAmount;
/**
* 订单量
*/
@Schema(description = "订单量")
private Integer orderCount;
/**
* 总件数
*/
@Schema(description = "总件数")
private Integer quantity;
/**
* 商品成本
*/
@Schema(description = "商品成本")
private BigDecimal productCost;
/**
* 运费
*/
@Schema(description = "运费")
private BigDecimal shippingCost;
/**
* 其他成本
*/
@Schema(description = "其他成本")
private BigDecimal otherCost;
/**
* 退款金额
*/
@Schema(description = "退款金额")
private BigDecimal refundAmount;
/**
* 推广费
*/
@Schema(description = "推广费")
private BigDecimal promotionFee;
/**
* 费比
*/
@Schema(description = "费比")
private BigDecimal feeRatio;
/**
* 税前盈亏
*/
@Schema(description = "税前盈亏")
private BigDecimal profitBeforeTax;
/**
* 税额
*/
@Schema(description = "税额")
private BigDecimal salesTaxAmount;
/**
* ROI
*/
@Schema(description = "ROI")
private BigDecimal roi;
/**
* 税后盈亏
*/
@Schema(description = "税后盈亏")
private BigDecimal profitAfterTax;
}
}
@@ -8,22 +8,24 @@ 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.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductSpecMapper;
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.modules.ecom.shop.monthlytarget.mapper.ShopMonthlyTargetMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.model.po.ShopMonthlyTargetPO;
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.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
/**
@@ -37,17 +39,23 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
private final PromotionFeeMapper promotionFeeMapper;
private final OrderStatusMapper orderStatusMapper;
private final ProductService productService;
private final ProductSpecMapper productSpecMapper;
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
public ProductOverviewServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper,
PromotionFeeMapper promotionFeeMapper,
OrderStatusMapper orderStatusMapper,
ProductService productService) {
ProductService productService,
ProductSpecMapper productSpecMapper,
ShopMonthlyTargetMapper shopMonthlyTargetMapper) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
this.orderStatusMapper = orderStatusMapper;
this.productService = productService;
this.productSpecMapper = productSpecMapper;
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
}
@Override
@@ -65,11 +73,17 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
throw new BusinessException("开始日期不能晚于结束日期");
}
// 查询时间范围
LocalDateTime startDateTime = queryDTO.getStartDate().atStartOfDay();
LocalDateTime endDateTime = queryDTO.getEndDate().atTime(23, 59, 59);
LocalDate startDate = queryDTO.getStartDate();
LocalDate endDate = queryDTO.getEndDate();
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
// 查询订单数据(按商品过滤)
// 税率
BigDecimal taxRate = queryDTO.getTaxRate() != null
? queryDTO.getTaxRate()
: new BigDecimal("0.04");
// 查询订单数据
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getProductId, queryDTO.getProductId())
@@ -77,344 +91,515 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
.le(OrderPO::getOrderTime, endDateTime);
List<OrderPO> orders = orderMapper.selectList(orderWrapper);
// 查询推广费数据(店铺粒度的推广费,需要通过订单关联的shopId过滤)
// 先收集该商品对应订单的店铺ID列表
// 收集店铺ID列表
List<Long> shopIds = orders.stream()
.map(OrderPO::getShopId)
.filter(shopId -> shopId != null)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
// 查询推广费(店铺粒度)
List<PromotionFeePO> promotionFees = new ArrayList<>();
if (!shopIds.isEmpty()) {
LambdaQueryWrapper<PromotionFeePO> promotionWrapper = new LambdaQueryWrapper<>();
promotionWrapper.eq(PromotionFeePO::getCompanyId, companyId)
LambdaQueryWrapper<PromotionFeePO> promoWrapper = new LambdaQueryWrapper<>();
promoWrapper.eq(PromotionFeePO::getCompanyId, companyId)
.in(PromotionFeePO::getShopId, shopIds)
.ge(PromotionFeePO::getFeeDate, queryDTO.getStartDate())
.le(PromotionFeePO::getFeeDate, queryDTO.getEndDate());
promotionFees = promotionFeeMapper.selectList(promotionWrapper);
.ge(PromotionFeePO::getFeeDate, startDate)
.le(PromotionFeePO::getFeeDate, endDate);
promotionFees = promotionFeeMapper.selectList(promoWrapper);
}
// 获取退款状态ID
List<Long> refundStatusIds = getRefundStatusIds();
Set<Long> refundStatusIds = getRefundStatusIds(companyId);
// 按日期分组订单数据
Map<LocalDate, List<OrderPO>> ordersByDate = orders.stream()
.collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate()));
// 查询上月同期数据(用于环比计算)
long dayCount = ChronoUnit.DAYS.between(startDate, endDate) + 1;
LocalDate lastStartDate = startDate.minusDays(dayCount);
LocalDate lastEndDate = startDate.minusDays(1);
LocalDateTime lastStartTime = lastStartDate.atStartOfDay();
LocalDateTime lastEndTime = lastEndDate.atTime(23, 59, 59);
// 按日期分组推广费数据
Map<LocalDate, List<PromotionFeePO>> promotionFeesByDate = promotionFees.stream()
.collect(Collectors.groupingBy(PromotionFeePO::getFeeDate));
LambdaQueryWrapper<OrderPO> lastPeriodWrapper = new LambdaQueryWrapper<>();
lastPeriodWrapper.eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getProductId, queryDTO.getProductId())
.ge(OrderPO::getOrderTime, lastStartTime)
.le(OrderPO::getOrderTime, lastEndTime);
List<OrderPO> lastPeriodOrders = orderMapper.selectList(lastPeriodWrapper);
// 生成日期范围内的所有日期列表
List<LocalDate> dateList = new ArrayList<>();
LocalDate currentDate = queryDTO.getStartDate();
while (!currentDate.isAfter(queryDTO.getEndDate())) {
dateList.add(currentDate);
currentDate = currentDate.plusDays(1);
}
// ========== 构建返回对象 ==========
ProductOverviewVO vo = new ProductOverviewVO();
vo.setProductId(product.getId());
vo.setProductName(product.getName());
// 构建返回对象
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, refundStatusIds);
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)
// ---------- KPI 汇总指标 ----------
// 总销售额
BigDecimal totalSalesAmount = orders.stream()
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
stats.setTotal(total);
vo.setTotalSalesAmount(totalSalesAmount);
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()
// 总订单量(按平台订单号去重)
long totalOrderCount = orders.stream()
.map(OrderPO::getPlatformOrderNo)
.filter(no -> no != null && !no.isEmpty())
.distinct()
.count();
if (totalCount == 0) {
totalCount = allOrders.size();
if (totalOrderCount == 0) {
totalOrderCount = orders.size();
}
stats.setTotal(BigDecimal.valueOf(totalCount));
vo.setTotalOrderCount((int) totalOrderCount);
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 avgOrderValue = totalOrderCount > 0
? totalSalesAmount.divide(BigDecimal.valueOf(totalOrderCount), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
stats.setTotal(total);
vo.setAverageOrderValue(avgOrderValue);
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);
// 总退款金额(退款状态订单的实收金额)
BigDecimal totalRefundAmount = orders.stream()
.filter(o -> refundStatusIds.contains(o.getStatusId()))
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
vo.setRefundAmount(totalRefundAmount);
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);
// 总成本(含数量)
BigDecimal totalCostAmount = orders.stream()
.map(this::calcOrderCost)
.reduce(BigDecimal.ZERO, BigDecimal::add);
vo.setAverageFeeRatio(null); // 由 spec 维度均化,待后面补充
// 总推广费
BigDecimal totalPromotionFee = promotionFees.stream()
.map(f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
// 按订单数量比例分摊到当前商品(简化处理)
if (!shopIds.isEmpty() && totalPromotionFee.compareTo(BigDecimal.ZERO) > 0) {
// 按商品所在订单数占总订单比例分摊(近似)
// 这里不做细粒度分摊,保持店铺维度总额在 spec 维度按比例拆分
}
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, List<Long> refundStatusIds) {
ProductOverviewVO.DailyStatistics stats = new ProductOverviewVO.DailyStatistics();
BigDecimal total = allOrders.stream()
.filter(order -> !refundStatusIds.isEmpty() && refundStatusIds.contains(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 -> !refundStatusIds.isEmpty() && refundStatusIds.contains(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 avgFeeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0
? totalPromotionFee.divide(totalSalesAmount, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
stats.setTotal(total);
vo.setAverageFeeRatio(avgFeeRatio.multiply(new BigDecimal("100"))
.setScale(2, RoundingMode.HALF_UP)); // 转为百分比
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);
// 税前盈亏 = 销售额 - 成本 - 推广费
BigDecimal totalProfitBeforeTax = totalSalesAmount
.subtract(totalCostAmount)
.subtract(totalPromotionFee);
vo.setTotalProfitBeforeTax(totalProfitBeforeTax);
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);
// 税额 = 销售额 × 税率
BigDecimal totalTaxAmount = totalSalesAmount.multiply(taxRate)
.setScale(2, RoundingMode.HALF_UP);
vo.setTotalTaxAmount(totalTaxAmount);
// 税后盈亏
BigDecimal totalProfitAfterTax = totalProfitBeforeTax.subtract(totalTaxAmount);
vo.setTotalProfitAfterTax(totalProfitAfterTax);
vo.setTotalNetProfitAfterTax(totalProfitAfterTax);
// ROI = (销售额 - 成本) / 推广费
BigDecimal totalROI = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0
? totalSalesAmount.subtract(totalCostAmount)
.divide(totalPromotionFee, 2, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"))
: BigDecimal.ZERO;
vo.setTotalROI(totalROI);
// ---------- 环比增长(上月同期) ----------
BigDecimal lastPeriodSales = lastPeriodOrders.stream()
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal monthOverMonthGrowth = BigDecimal.ZERO;
if (lastPeriodSales.compareTo(BigDecimal.ZERO) > 0) {
monthOverMonthGrowth = totalSalesAmount
.subtract(lastPeriodSales)
.divide(lastPeriodSales, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"))
.setScale(2, RoundingMode.HALF_UP);
} else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
monthOverMonthGrowth = new BigDecimal("100.00");
}
stats.setDailyDataList(dailyDataList);
vo.setMonthOverMonthGrowth(monthOverMonthGrowth);
return stats;
// ---------- 达成率(简化:按店铺月度目标计算) ----------
if (!shopIds.isEmpty()) {
LocalDate firstDayOfMonth = startDate.withDayOfMonth(1);
LocalDate lastDayOfMonth = endDate.withDayOfMonth(endDate.lengthOfMonth());
LambdaQueryWrapper<ShopMonthlyTargetPO> targetWrapper = new LambdaQueryWrapper<>();
targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId)
.in(ShopMonthlyTargetPO::getShopId, shopIds)
.ge(ShopMonthlyTargetPO::getTargetMonth, firstDayOfMonth)
.le(ShopMonthlyTargetPO::getTargetMonth, lastDayOfMonth);
List<ShopMonthlyTargetPO> shopTargets = shopMonthlyTargetMapper.selectList(targetWrapper);
BigDecimal totalTargetAmount = shopTargets.stream()
.map(ShopMonthlyTargetPO::getTargetAmount)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Integer totalTargetOrderCount = shopTargets.stream()
.map(ShopMonthlyTargetPO::getTargetOrderCount)
.filter(Objects::nonNull)
.reduce(0, Integer::sum);
if (totalTargetAmount.compareTo(BigDecimal.ZERO) > 0) {
BigDecimal salesRate = totalSalesAmount
.divide(totalTargetAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"))
.setScale(2, RoundingMode.HALF_UP);
vo.setSalesAmountAchievementRate(salesRate);
}
if (totalTargetOrderCount != null && totalTargetOrderCount > 0) {
BigDecimal orderRate = BigDecimal.valueOf(totalOrderCount)
.divide(BigDecimal.valueOf(totalTargetOrderCount), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"))
.setScale(2, RoundingMode.HALF_UP);
vo.setOrderCountAchievementRate(orderRate);
}
}
// ---------- 趋势数据 ----------
vo.setSalesAmountTrend(buildTrend(orders, dateList -> dateList.stream()
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add), startDate, endDate));
vo.setOrderCountTrend(buildOrderCountTrend(orders, startDate, endDate));
// ---------- 规格销售汇总 ----------
vo.setSpecSummaries(buildSpecSummary(orders, promotionFees, refundStatusIds, taxRate, shopIds));
return vo;
}
/**
* 获取退款状态ID列表(根据 is_refund 字段查找)
* 计算单笔订单总成本(含数量)
*/
private List<Long> getRefundStatusIds() {
Long companyId = currentUserContext.getCurrentCompanyId();
private BigDecimal calcOrderCost(OrderPO 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;
int quantity = order.getQuantity() != null ? order.getQuantity() : 1;
return productCost.add(shippingCost).add(otherCost)
.multiply(BigDecimal.valueOf(quantity));
}
/**
* 构建销售趋势
*/
private ProductOverviewVO.TrendData buildTrend(List<OrderPO> orders,
java.util.function.Function<List<OrderPO>, BigDecimal> reducer,
LocalDate startDate, LocalDate endDate) {
Map<LocalDate, List<OrderPO>> ordersByDate = orders.stream()
.collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate()));
List<ProductOverviewVO.TrendDataItem> dailyList = new ArrayList<>();
LocalDate current = startDate;
while (!current.isAfter(endDate)) {
List<OrderPO> dayOrders = ordersByDate.getOrDefault(current, List.of());
BigDecimal value = reducer.apply(dayOrders);
ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem();
item.setDate(current);
item.setValue(value);
dailyList.add(item);
current = current.plusDays(1);
}
BigDecimal total = dailyList.stream()
.map(ProductOverviewVO.TrendDataItem::getValue)
.reduce(BigDecimal.ZERO, BigDecimal::add);
ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData();
trend.setTotal(total);
trend.setDailyDataList(dailyList);
return trend;
}
/**
* 构建订单数趋势
*/
private ProductOverviewVO.TrendData buildOrderCountTrend(List<OrderPO> orders,
LocalDate startDate, LocalDate endDate) {
Map<LocalDate, List<OrderPO>> ordersByDate = orders.stream()
.collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate()));
List<ProductOverviewVO.TrendDataItem> dailyList = new ArrayList<>();
LocalDate current = startDate;
while (!current.isAfter(endDate)) {
List<OrderPO> dayOrders = ordersByDate.getOrDefault(current, List.of());
// 按平台订单号去重
long count = dayOrders.stream()
.map(OrderPO::getPlatformOrderNo)
.filter(no -> no != null && !no.isEmpty())
.distinct()
.count();
if (count == 0) count = dayOrders.size();
ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem();
item.setDate(current);
item.setValue(BigDecimal.valueOf(count));
dailyList.add(item);
current = current.plusDays(1);
}
BigDecimal total = BigDecimal.valueOf(dailyList.stream()
.mapToLong(i -> i.getValue().longValue())
.sum());
ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData();
trend.setTotal(total);
trend.setDailyDataList(dailyList);
return trend;
}
/**
* 构建规格销售汇总
*/
private ProductOverviewVO.SpecSummary buildSpecSummary(List<OrderPO> orders,
List<PromotionFeePO> promotionFees,
Set<Long> refundStatusIds,
BigDecimal taxRate,
List<Long> shopIds) {
// 查询商品所有规格
if (orders.isEmpty()) {
return buildEmptySpecSummary();
}
Long productId = orders.get(0).getProductId();
Long companyId = orders.get(0).getCompanyId();
LambdaQueryWrapper<ProductSpecPO> specWrapper = new LambdaQueryWrapper<>();
specWrapper.eq(ProductSpecPO::getCompanyId, companyId)
.eq(ProductSpecPO::getProductId, productId);
List<ProductSpecPO> allSpecs = productSpecMapper.selectList(specWrapper);
Map<Long, ProductSpecPO> specMap = allSpecs.stream()
.collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a));
// 推广费按店铺维度收集,后面按订单数比例拆分
Map<Long, BigDecimal> shopPromotionFeeMap = promotionFees.stream()
.collect(Collectors.groupingBy(PromotionFeePO::getShopId,
Collectors.reducing(BigDecimal.ZERO,
f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO,
BigDecimal::add)));
// 按规格分组订单
Map<Long, List<OrderPO>> ordersBySpec = orders.stream()
.collect(Collectors.groupingBy(o -> {
Long specId = o.getProductSpecId();
return specId != null ? specId : 0L;
}));
List<ProductOverviewVO.SpecSummaryItem> specItems = new ArrayList<>();
for (Map.Entry<Long, List<OrderPO>> entry : ordersBySpec.entrySet()) {
Long specId = entry.getKey();
if (specId == 0L) continue; // 跳过未关联规格的订单
List<OrderPO> specOrders = entry.getValue();
ProductSpecPO spec = specMap.get(specId);
// 该规格的销售额
BigDecimal salesAmount = specOrders.stream()
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
// 该规格的订单量(去重)
long orderCount = specOrders.stream()
.map(OrderPO::getPlatformOrderNo)
.filter(no -> no != null && !no.isEmpty())
.distinct()
.count();
if (orderCount == 0) orderCount = specOrders.size();
// 总件数
int quantity = specOrders.stream()
.map(o -> o.getQuantity() != null ? o.getQuantity() : 1)
.reduce(0, Integer::sum);
// 客单价
BigDecimal avgOV = BigDecimal.valueOf(orderCount).compareTo(BigDecimal.ZERO) > 0
? salesAmount.divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
// 商品成本
BigDecimal productCostTotal = specOrders.stream()
.map(o -> {
BigDecimal pc = o.getProductCost() != null ? o.getProductCost() : BigDecimal.ZERO;
int qty = o.getQuantity() != null ? o.getQuantity() : 1;
return pc.multiply(BigDecimal.valueOf(qty));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
// 运费 + 其他成本
BigDecimal shippingCostTotal = specOrders.stream()
.map(o -> o.getShippingCost() != null ? o.getShippingCost() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal otherCostTotal = specOrders.stream()
.map(o -> o.getOtherCost() != null ? o.getOtherCost() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
// 退款金额
BigDecimal refundAmount = specOrders.stream()
.filter(o -> refundStatusIds.contains(o.getStatusId()))
.map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
// 推广费分摊(按该规格订单数占所有订单数比例)
int totalOrderCountAll = orders.size();
BigDecimal specPromotionFee = BigDecimal.ZERO;
if (totalOrderCountAll > 0) {
BigDecimal proportion = BigDecimal.valueOf(orderCount)
.divide(BigDecimal.valueOf(totalOrderCountAll), 4, RoundingMode.HALF_UP);
BigDecimal totalPromo = shopPromotionFeeMap.values().stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
specPromotionFee = totalPromo.multiply(proportion)
.setScale(2, RoundingMode.HALF_UP);
}
// 费比
BigDecimal feeRatio = salesAmount.compareTo(BigDecimal.ZERO) > 0
? specPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
// 税前盈亏
BigDecimal profitBeforeTax = salesAmount
.subtract(productCostTotal)
.subtract(shippingCostTotal)
.subtract(otherCostTotal)
.subtract(specPromotionFee);
// 税额
BigDecimal salesTaxAmount = salesAmount.multiply(taxRate)
.setScale(2, RoundingMode.HALF_UP);
// ROI
BigDecimal roi = specPromotionFee.compareTo(BigDecimal.ZERO) > 0
? salesAmount.subtract(productCostTotal)
.divide(specPromotionFee, 2, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"))
: BigDecimal.ZERO;
// 税后盈亏
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount);
ProductOverviewVO.SpecSummaryItem item = new ProductOverviewVO.SpecSummaryItem();
item.setSpecId(specId);
item.setSpecName(spec != null ? spec.getName() : "未知规格");
item.setSpecCode(spec != null ? spec.getSpecCode() : null);
item.setSalesAmount(salesAmount);
item.setOrderCount((int) orderCount);
item.setQuantity(quantity);
item.setAverageOrderValue(avgOV);
item.setProductCost(productCostTotal);
item.setShippingCost(shippingCostTotal);
item.setOtherCost(otherCostTotal);
item.setRefundAmount(refundAmount);
item.setPromotionFee(specPromotionFee);
item.setFeeRatio(feeRatio.multiply(new BigDecimal("100"))
.setScale(2, RoundingMode.HALF_UP));
item.setProfitBeforeTax(profitBeforeTax);
item.setSalesTaxAmount(salesTaxAmount);
item.setRoi(roi);
item.setProfitAfterTax(profitAfterTax);
specItems.add(item);
}
// 构建合计行
ProductOverviewVO.SpecSummaryTotal total = new ProductOverviewVO.SpecSummaryTotal();
total.setSalesAmount(specItems.stream()
.map(ProductOverviewVO.SpecSummaryItem::getSalesAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setOrderCount(specItems.stream()
.mapToInt(ProductOverviewVO.SpecSummaryItem::getOrderCount).sum());
total.setQuantity(specItems.stream()
.mapToInt(ProductOverviewVO.SpecSummaryItem::getQuantity).sum());
total.setProductCost(specItems.stream()
.map(ProductOverviewVO.SpecSummaryItem::getProductCost)
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setShippingCost(specItems.stream()
.map(ProductOverviewVO.SpecSummaryItem::getShippingCost)
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setOtherCost(specItems.stream()
.map(ProductOverviewVO.SpecSummaryItem::getOtherCost)
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setRefundAmount(specItems.stream()
.map(ProductOverviewVO.SpecSummaryItem::getRefundAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setPromotionFee(specItems.stream()
.map(ProductOverviewVO.SpecSummaryItem::getPromotionFee)
.reduce(BigDecimal.ZERO, BigDecimal::add));
BigDecimal totalSalesAmt = total.getSalesAmount();
BigDecimal totalPromoFee = total.getPromotionFee();
BigDecimal totalFeeRatio = totalSalesAmt.compareTo(BigDecimal.ZERO) > 0
? totalPromoFee.divide(totalSalesAmt, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
total.setFeeRatio(totalFeeRatio.multiply(new BigDecimal("100"))
.setScale(2, RoundingMode.HALF_UP));
BigDecimal totalProfitBT = total.getSalesAmount()
.subtract(total.getProductCost())
.subtract(total.getShippingCost())
.subtract(total.getOtherCost())
.subtract(total.getPromotionFee());
total.setProfitBeforeTax(totalProfitBT);
BigDecimal totalSalesTax = totalSalesAmt.multiply(taxRate).setScale(2, RoundingMode.HALF_UP);
total.setSalesTaxAmount(totalSalesTax);
BigDecimal totalRoi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
? totalSalesAmt.subtract(total.getProductCost())
.divide(totalPromoFee, 2, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"))
: BigDecimal.ZERO;
total.setRoi(totalRoi);
total.setProfitAfterTax(totalProfitBT.subtract(totalSalesTax));
ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary();
summary.setList(specItems);
summary.setTotal(total);
return summary;
}
private ProductOverviewVO.SpecSummary buildEmptySpecSummary() {
ProductOverviewVO.SpecSummaryTotal total = new ProductOverviewVO.SpecSummaryTotal();
total.setSalesAmount(BigDecimal.ZERO);
total.setOrderCount(0);
total.setQuantity(0);
total.setProductCost(BigDecimal.ZERO);
total.setShippingCost(BigDecimal.ZERO);
total.setOtherCost(BigDecimal.ZERO);
total.setRefundAmount(BigDecimal.ZERO);
total.setPromotionFee(BigDecimal.ZERO);
total.setFeeRatio(BigDecimal.ZERO);
total.setProfitBeforeTax(BigDecimal.ZERO);
total.setSalesTaxAmount(BigDecimal.ZERO);
total.setRoi(BigDecimal.ZERO);
total.setProfitAfterTax(BigDecimal.ZERO);
ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary();
summary.setList(new ArrayList<>());
summary.setTotal(total);
return summary;
}
/**
* 获取退款状态ID集合
*/
private Set<Long> getRefundStatusIds(Long companyId) {
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getIsRefund, 1)
.select(OrderStatusPO::getId);
List<OrderStatusPO> statusList = orderStatusMapper.selectList(wrapper);
return statusList.stream().map(OrderStatusPO::getId).collect(Collectors.toList());
return orderStatusMapper.selectList(wrapper).stream()
.map(OrderStatusPO::getId)
.collect(Collectors.toSet());
}
}
@@ -7,5 +7,7 @@ export namespace ProductOverviewDTO {
startDate: string;
/** 结束日期 */
endDate: string;
/** 税率(可选,0~1) */
taxRate?: number;
}
}
@@ -1,39 +1,139 @@
export namespace ProductOverviewVO {
/** 每日数据项 */
export interface DailyData {
/** 趋势数据项 */
export interface TrendDataItem {
/** 日期 */
date: string;
/** 对应的值 */
value: number;
}
/** 每日统计数据 */
export interface DailyStatistics {
/** 趋势数据 */
export interface TrendData {
/** 时间范围的总值 */
total: number;
/** 每日数据列表 */
dailyDataList: DailyData[];
dailyDataList: TrendDataItem[];
}
/** 商品总览 */
/** 规格销售明细项 */
export interface SpecSummaryItem {
/** 规格ID */
specId: number;
/** 规格名称 */
specName: string;
/** 规格编码 */
specCode: string;
/** 销售额 */
salesAmount: number;
/** 订单量 */
orderCount: number;
/** 总件数 */
quantity: number;
/** 客单价 */
averageOrderValue: number;
/** 商品成本 */
productCost: number;
/** 运费 */
shippingCost: number;
/** 其他成本 */
otherCost: number;
/** 退款金额 */
refundAmount: number;
/** 推广费 */
promotionFee: number;
/** 费比 */
feeRatio: number;
/** 税前盈亏 */
profitBeforeTax: number;
/** 销售额×税率的税额 */
salesTaxAmount: number;
/** ROI */
roi: number;
/** 税后盈亏 */
profitAfterTax: number;
}
/** 规格销售汇总合计行 */
export interface SpecSummaryTotal {
/** 销售额 */
salesAmount: number;
/** 订单量 */
orderCount: number;
/** 总件数 */
quantity: number;
/** 商品成本 */
productCost: number;
/** 运费 */
shippingCost: number;
/** 其他成本 */
otherCost: number;
/** 退款金额 */
refundAmount: number;
/** 推广费 */
promotionFee: number;
/** 费比 */
feeRatio: number;
/** 税前盈亏 */
profitBeforeTax: number;
/** 税额 */
salesTaxAmount: number;
/** ROI */
roi: number;
/** 税后盈亏 */
profitAfterTax: number;
}
/** 规格销售汇总 */
export interface SpecSummary {
/** 各规格明细列表 */
list: SpecSummaryItem[];
/** 合计行 */
total: SpecSummaryTotal;
}
/** 商品概览响应 */
export interface Overview {
/** 商品ID */
productId: number;
/** 商品名称 */
productName: string;
/** 销售额统计 */
salesAmount: DailyStatistics;
/** 订单数统计 */
orderCount: DailyStatistics;
/** 客单价统计 */
averageOrderValue: DailyStatistics;
/** 成本统计 */
costAmount: DailyStatistics;
/** 退款金额统计 */
refundAmount: DailyStatistics;
/** 推广费统计 */
promotionFee: DailyStatistics;
/** 费比统计 */
feeRatio: DailyStatistics;
// ========== KPI 汇总指标 ==========
/** 总销售额 */
totalSalesAmount: number;
/** 较上月同期增长百分比 */
monthOverMonthGrowth: number;
/** 总订单量 */
totalOrderCount: number;
/** 平均费比 */
averageFeeRatio: number;
/** 总净利润(税后) */
totalNetProfitAfterTax: number;
/** 扣除总税额 */
totalTaxAmount: number;
/** 销量目标达成率 */
orderCountAchievementRate: number;
/** 销售额目标达成率 */
salesAmountAchievementRate: number;
/** 汇总ROI */
totalROI: number;
/** 汇总客单价 */
averageOrderValue: number;
/** 退款金额合计 */
refundAmount: number;
/** 税前盈亏 */
totalProfitBeforeTax: number;
/** 总税后盈亏 */
totalProfitAfterTax: number;
// ========== 趋势数据 ==========
/** 销售额趋势分析 */
salesAmountTrend: TrendData;
/** 单量趋势分析 */
orderCountTrend: TrendData;
// ========== 规格销售汇总 ==========
/** 规格销售汇总 */
specSummaries: SpecSummary;
}
}
@@ -11,7 +11,6 @@ import {
Button,
Card,
DatePicker,
Form,
Image,
Input,
InputNumber,
@@ -370,11 +369,11 @@ const saveEdit = async () => {
<Card
hoverable
:body-style="{ padding: 0 }"
class="group management-card h-full"
class="group management-card h-full dark:bg-[#111827] dark:border-[#374151] dark:shadow-none"
:class="{ editing: isEditing }"
>
<div class="card-top">
<div class="img-preview" :class="{ 'editing-img': isEditing }">
<div class="img-preview dark:bg-[#1f2937] dark:border-[#374151]" :class="{ 'editing-img': isEditing }">
<template v-if="!isEditing">
<Image
v-if="currentImageUrl && !imageLoadError"
@@ -383,8 +382,8 @@ const saveEdit = async () => {
class="product-image"
:preview="true"
/>
<div v-else class="no-image">
<ImageOffIcon class="mb-1 text-base" />
<div v-else class="no-image dark:text-[#9ca3af]">
<ImageOffIcon class="mb-1 text-base dark:text-[#6b7280]" />
<span>暂无图片</span>
</div>
</template>
@@ -397,11 +396,11 @@ const saveEdit = async () => {
class="product-image"
@error="handleImageError"
/>
<div v-else class="no-image">
<ImageOffIcon class="mb-1 text-base" />
<div v-else class="no-image dark:text-[#9ca3af]">
<ImageOffIcon class="mb-1 text-base dark:text-[#6b7280]" />
<span>点击上传</span>
</div>
<div class="image-overlay">
<div class="image-overlay dark:bg-black/60">
<ImageOffIcon class="text-base mb-1" />
<span class="text-xs">{{ currentImageUrl && !imageLoadError ? '更换图片' : '上传图片' }}</span>
</div>
@@ -415,7 +414,7 @@ const saveEdit = async () => {
<div class="info-main">
<div class="field-row">
<span class="field-label">商品名称</span>
<span v-if="!isEditing" class="field-text field-text--title">{{ product.name }}</span>
<span v-if="!isEditing" class="field-text field-text--title dark:text-[#e5e7eb]">{{ product.name }}</span>
<TextArea
v-else
v-model:value="draft.name"
@@ -426,9 +425,9 @@ const saveEdit = async () => {
</div>
<div class="meta-grid">
<div class="meta-box">
<span class="label">类目</span>
<span v-if="!isEditing" class="value">{{ product.categoryName || '未设置' }}</span>
<div class="meta-box dark:bg-[#1f2937]">
<span class="label dark:text-[#9ca3af]">类目</span>
<span v-if="!isEditing" class="value dark:text-[#e5e7eb]">{{ product.categoryName || '未设置' }}</span>
<TreeSelect
v-else
v-model:value="draft.categoryId"
@@ -440,24 +439,24 @@ const saveEdit = async () => {
tree-default-expand-all
/>
</div>
<div class="meta-box">
<span class="label">商品编码</span>
<span v-if="!isEditing" class="value">{{ product.productCode || '未填写' }}</span>
<div class="meta-box dark:bg-[#1f2937]">
<span class="label dark:text-[#9ca3af]">商品编码</span>
<span v-if="!isEditing" class="value dark:text-[#e5e7eb]">{{ product.productCode || '未填写' }}</span>
<Input v-else v-model:value="draft.productCode" class="field-input field-input--meta" placeholder="请输入编码" />
</div>
<div class="meta-box">
<span class="label">创建时间</span>
<span class="value">{{ product.createTime || '-' }}</span>
<div class="meta-box dark:bg-[#1f2937]">
<span class="label dark:text-[#9ca3af]">创建时间</span>
<span class="value dark:text-[#e5e7eb]">{{ product.createTime || '-' }}</span>
</div>
<div class="meta-box">
<span class="label">更新时间</span>
<span class="value">{{ product.updateTime || '-' }}</span>
<div class="meta-box dark:bg-[#1f2937]">
<span class="label dark:text-[#9ca3af]">更新时间</span>
<span class="value dark:text-[#e5e7eb]">{{ product.updateTime || '-' }}</span>
</div>
</div>
</div>
</div>
<div class="specs-wrapper">
<div class="specs-wrapper dark:bg-[#1a202c]">
<div class="specs-header-row">
<div class="specs-header">规格</div>
<Button v-if="isEditing" type="dashed" size="small" @click="addSpec">
@@ -466,19 +465,19 @@ const saveEdit = async () => {
</Button>
</div>
<div v-if="displaySpecs.length > 0" class="table-container">
<div class="spec-row spec-head">
<span class="cell-head cell-code">规格编码</span>
<span class="cell-head cell-name">规格名称</span>
<span class="cell-head cell-cost">商品成本</span>
<span class="cell-head cell-cost">运费成本</span>
<span class="cell-head cell-cost">其他成本</span>
<span v-if="isEditing" class="op-col">操作</span>
<div v-if="displaySpecs.length > 0" class="table-container dark:bg-[#1a202c] dark:border-[#374151]">
<div class="spec-row spec-head dark:bg-[#1f2937] dark:text-[#9ca3af]">
<span class="cell-head cell-code dark:text-[#9ca3af]">规格编码</span>
<span class="cell-head cell-name dark:text-[#9ca3af]">规格名称</span>
<span class="cell-head cell-cost dark:text-[#9ca3af]">商品成本</span>
<span class="cell-head cell-cost dark:text-[#9ca3af]">运费成本</span>
<span class="cell-head cell-cost dark:text-[#9ca3af]">其他成本</span>
<span v-if="isEditing" class="op-col dark:bg-[#1f2937] dark:text-[#9ca3af]">操作</span>
</div>
<div
v-for="(spec, index) in displaySpecs"
:key="spec.id"
class="spec-row"
class="spec-row dark:bg-[#1a202c]"
:class="{ 'editing-row': isEditing }"
>
<span class="cell cell-code">
@@ -486,7 +485,7 @@ const saveEdit = async () => {
<Input v-else v-model:value="draft.specs[index]!.specCode" class="field-input" placeholder="编码" />
</span>
<span class="cell cell-name">
<span v-if="!isEditing" class="field-text">{{ spec.name || '-' }}</span>
<span v-if="!isEditing" class="field-text dark:text-[#e5e7eb]">{{ spec.name || '-' }}</span>
<TextArea
v-else
v-model:value="draft.specs[index]!.name"
@@ -496,7 +495,7 @@ const saveEdit = async () => {
/>
</span>
<span class="cell cell-cost">
<span v-if="!isEditing" class="cost-text">{{ formatCost(spec.productCost) }}</span>
<span v-if="!isEditing" class="cost-text dark:text-[#e5e7eb]">{{ formatCost(spec.productCost) }}</span>
<InputNumber
v-else
:value="spec.productCost ?? 0"
@@ -505,11 +504,11 @@ const saveEdit = async () => {
placeholder="0"
:min="0"
:precision="2"
@update:value="(v) => { draft.specs[index]!.productCost = v ?? 0; }"
@update:value="(v) => { draft.specs[index]!.productCost = (v as number) ?? 0; }"
/>
</span>
<span class="cell cell-cost">
<span v-if="!isEditing" class="cost-text">{{ formatCost(spec.shippingCost) }}</span>
<span v-if="!isEditing" class="cost-text dark:text-[#e5e7eb]">{{ formatCost(spec.shippingCost) }}</span>
<InputNumber
v-else
:value="spec.shippingCost ?? 0"
@@ -518,11 +517,11 @@ const saveEdit = async () => {
placeholder="0"
:min="0"
:precision="2"
@update:value="(v) => { draft.specs[index]!.shippingCost = v ?? 0; }"
@update:value="(v) => { draft.specs[index]!.shippingCost = (v as number) ?? 0; }"
/>
</span>
<span class="cell cell-cost">
<span v-if="!isEditing" class="cost-text">{{ formatCost(spec.otherCost) }}</span>
<span v-if="!isEditing" class="cost-text dark:text-[#e5e7eb]">{{ formatCost(spec.otherCost) }}</span>
<InputNumber
v-else
:value="spec.otherCost ?? 0"
@@ -531,10 +530,10 @@ const saveEdit = async () => {
placeholder="0"
:min="0"
:precision="2"
@update:value="(v) => { draft.specs[index]!.otherCost = v ?? 0; }"
@update:value="(v) => { draft.specs[index]!.otherCost = (v as number) ?? 0; }"
/>
</span>
<span v-if="isEditing" class="cell op-col">
<span v-if="isEditing" class="cell op-col dark:bg-[#1a202c]">
<Button type="text" danger size="small" class="delete-spec-btn" @click="removeSpec(index)">
<template #icon><TrashIcon class="h-4 w-4" /></template>
</Button>
@@ -542,15 +541,15 @@ const saveEdit = async () => {
</div>
<div
v-if="!isEditing && (product.specs?.length || 0) > visibleSpecs.length"
class="more-tip"
class="more-tip dark:text-[#9ca3af] dark:bg-[#1a202c]"
>
仅展示前 {{ visibleSpecs.length }} 条规格,点击"统计"查看全部
</div>
</div>
<div v-else-if="!isEditing" class="empty-text">暂无规格数据</div>
<div v-else-if="!isEditing" class="empty-text dark:text-[#9ca3af] dark:bg-[#1a202c]">暂无规格数据</div>
</div>
<div class="card-footer">
<div class="card-footer dark:bg-[#1a202c]">
<template v-if="!isEditing">
<Button class="btn btn-edit" @click="startEdit" title="编辑">
<template #icon><EditIcon class="h-4 w-4" /></template>
@@ -666,6 +665,52 @@ const saveEdit = async () => {
border-bottom: 1px solid #f9f9f9;
}
:global(html.dark) .card-top {
border-color: #374151;
}
.info-main {
flex: 1;
min-width: 0;
}
:global(html.dark) .info-main {
background: transparent;
}
.field-row {
display: flex;
align-items: flex-start;
gap: 8px;
margin-bottom: 12px;
min-height: 32px;
}
.field-label {
font-size: 13px;
color: #8c8c8c;
font-weight: 400;
width: 70px;
flex-shrink: 0;
padding-top: 4px;
}
:global(html.dark) .field-label {
color: #9ca3af;
}
.card-footer {
padding: 16px 24px;
border-top: 1px solid #f5f5f5;
display: flex;
align-items: center;
gap: 12px;
}
:global(html.dark) .card-footer {
border-color: #374151;
}
.img-preview {
width: 140px;
height: 140px;
@@ -0,0 +1,100 @@
<script lang="ts" setup>
interface Props {
data: {
totalSalesAmount?: number;
totalOrderCount?: number;
averageOrderValue?: number;
totalPromotionFee?: number;
totalCostAmount?: number;
totalRefundAmount?: number;
totalProfitAfterTax?: number;
totalNetProfitAfterTax?: number;
totalTaxAmount?: number;
monthOverMonthGrowth?: number;
} | null;
taxRate: number;
}
const props = defineProps<Props>();
const formatAmount = (amount: number | undefined) => {
if (amount === undefined) return '-';
return `¥${amount.toLocaleString('zh-CN')}`;
};
const formatPercent = (value: number | undefined) => {
if (value === undefined) return '-';
return `${value > 0 ? '+' : ''}${value.toFixed(1)}%`;
};
</script>
<template>
<div
class="flex flex-col rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-8 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<h3 class="mb-6 text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
商品财务损益 (P&L)
</h3>
<div class="flex flex-1 flex-col space-y-4 text-sm">
<div class="flex justify-between border-b border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pb-2">
<span class="text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">推广费总支出</span>
<span class="font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
{{ data?.totalPromotionFee ? `-${formatAmount(data.totalPromotionFee)}` : '-' }}
</span>
</div>
<div class="flex justify-between border-b border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pb-2">
<span class="text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">成本总支出</span>
<span class="font-bold text-rose-600 dark:text-rose-400">
{{ data?.totalCostAmount ? `-${formatAmount(data.totalCostAmount)}` : '-' }}
</span>
</div>
<div class="flex justify-between border-b border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pb-2">
<span class="text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">退款金额</span>
<span class="font-bold text-amber-600 dark:text-amber-400">
{{ data?.totalRefundAmount ? `-${formatAmount(data.totalRefundAmount)}` : '-' }}
</span>
</div>
<div class="flex justify-between border-b border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pb-2">
<span class="text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">客单价 (AOV)</span>
<span class="font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
{{ data?.averageOrderValue ? formatAmount(data.averageOrderValue) : '-' }}
</span>
</div>
<div class="flex justify-between border-b border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pb-2">
<span class="text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">税后盈亏 (Profit)</span>
<span class="font-bold text-indigo-600 dark:text-indigo-400">
{{ data?.totalNetProfitAfterTax ? formatAmount(data.totalNetProfitAfterTax) : '-' }}
</span>
</div>
<!-- 扣除项 -->
<div class="mt-4 space-y-3 rounded-2xl bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] p-4">
<div class="flex justify-between text-xs">
<span class="text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">销售额 {{ (props.taxRate * 100).toFixed(0) }}% 税额</span>
<span class="font-bold text-rose-500 dark:text-rose-400">
{{ data?.totalTaxAmount ? formatAmount(data.totalTaxAmount) : '-' }}
</span>
</div>
<div class="flex justify-between text-xs">
<span class="text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">较上月同期增长</span>
<span class="font-black text-emerald-500 dark:text-emerald-400">
{{ formatPercent(data?.monthOverMonthGrowth) }}
</span>
</div>
</div>
<!-- 最终结果 -->
<div
class="mt-auto flex items-center justify-between rounded-2xl bg-slate-900 p-5 text-white shadow-2xl dark:shadow-none"
>
<div>
<p class="text-[10px] font-black uppercase opacity-60">Final Net Profit</p>
<p class="text-xs font-bold">商品最终净利</p>
</div>
<div class="text-3xl font-black">
{{ data?.totalNetProfitAfterTax ? formatAmount(data.totalNetProfitAfterTax) : '-' }}
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,216 @@
<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import dayjs from 'dayjs';
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
interface Props {
data: {
salesAmountTrend?: {
dailyDataList: { date: string; value: number }[];
};
orderCountTrend?: {
dailyDataList: { date: string; value: number }[];
};
} | null;
}
const props = defineProps<Props>();
const trendChartRef = ref<EchartsUIType>();
const { renderEcharts: renderTrendChart } = useEcharts(trendChartRef);
let isUnmounted = false;
let renderTimer: null | ReturnType<typeof setTimeout> = null;
let darkObserver: MutationObserver | null = null;
const renderChart = () => {
if (!trendChartRef.value || !props.data) return;
const salesTrend = props.data.salesAmountTrend;
const orderTrend = props.data.orderCountTrend;
if (!salesTrend || !orderTrend) return;
const salesList = Array.isArray(salesTrend.dailyDataList)
? salesTrend.dailyDataList
: [];
const orderList = Array.isArray(orderTrend.dailyDataList)
? orderTrend.dailyDataList
: [];
if (salesList.length === 0 && orderList.length === 0) {
return;
}
const dates = salesList.map((item) =>
dayjs(item.date).format('MM-DD'),
);
const salesData = salesList.map((item) => item.value);
const orderData = orderList.map((item) => item.value);
const isDark = document.documentElement.classList.contains('dark');
try {
renderTrendChart({
grid: {
left: '3%',
right: '3%',
bottom: '3%',
top: '5%',
containLabel: true,
},
tooltip: {
trigger: 'axis',
backgroundColor: isDark ? 'hsl(222.34deg 10.43% 12.27%)' : '#fff',
textStyle: {
color: isDark ? 'hsl(0deg 0% 95%)' : '#000',
},
},
xAxis: {
type: 'category',
boundaryGap: false,
data: dates,
axisLine: {
lineStyle: {
color: isDark ? 'hsl(240deg 3.7% 22%)' : '#e2e8f0',
},
},
},
yAxis: [
{
type: 'value',
name: '销售额',
nameTextStyle: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
axisLabel: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
splitLine: {
lineStyle: {
type: 'dashed',
color: isDark ? 'hsl(240deg 3.7% 22%)' : undefined,
},
},
},
{
type: 'value',
name: '单量',
position: 'right',
nameTextStyle: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
axisLabel: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
splitLine: { show: false },
},
],
series: [
{
name: '销售额',
type: 'line',
smooth: true,
symbol: 'none',
lineStyle: { width: 3, color: '#3b82f6' },
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(59, 130, 246, 0.4)' },
{ offset: 1, color: 'rgba(59, 130, 246, 0)' },
],
},
},
data: salesData,
},
{
name: '日单量',
type: 'line',
yAxisIndex: 1,
smooth: true,
symbol: 'none',
lineStyle: { width: 3, color: '#10b981' },
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(16, 185, 129, 0.2)' },
{ offset: 1, color: 'rgba(16, 185, 129, 0)' },
],
},
},
data: orderData,
},
],
});
} catch (error) {
console.error('渲染趋势图失败:', error);
}
};
const scheduleRender = async () => {
if (renderTimer) {
clearTimeout(renderTimer);
renderTimer = null;
}
await nextTick();
if (isUnmounted) return;
renderTimer = setTimeout(() => {
if (isUnmounted) return;
renderChart();
}, 16);
};
watch(
() => props.data,
() => {
if (props.data) {
scheduleRender();
}
},
{ deep: true, immediate: true },
);
onMounted(() => {
isUnmounted = false;
darkObserver = new MutationObserver(() => {
if (props.data) scheduleRender();
});
darkObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
});
onUnmounted(() => {
isUnmounted = true;
if (renderTimer) {
clearTimeout(renderTimer);
renderTimer = null;
}
darkObserver?.disconnect();
darkObserver = null;
});
defineExpose({ renderChart });
</script>
<template>
<div class="rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-8 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px] xl:col-span-2">
<h3 class="mb-6 text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
销售额与单量趋势分析
</h3>
<div class="h-[380px] w-full">
<EchartsUI ref="trendChartRef" />
</div>
</div>
</template>
@@ -0,0 +1,241 @@
<script lang="ts" setup>
interface SpecData {
specId: number;
specName: string;
specCode?: string;
salesAmount: number;
orderCount: number;
quantity: number;
averageOrderValue: number;
productCost: number;
shippingCost: number;
otherCost: number;
refundAmount: number;
promotionFee: number;
feeRatio: number;
profitBeforeTax: number;
salesTaxAmount: number;
roi: number;
profitAfterTax: number;
}
interface Props {
data: SpecData[];
taxRate?: number;
}
const props = withDefaults(defineProps<Props>(), {
taxRate: 4,
});
const formatAmount = (amount: number | undefined) => {
if (amount === undefined || amount === null) return '-';
return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};
const formatPercent = (value: number | undefined) => {
if (value === undefined || value === null) return '-';
return `${value.toFixed(1)}%`;
};
const formatCount = (value: number | undefined) => {
if (value === undefined || value === null) return '-';
return value.toLocaleString('zh-CN');
};
// 计算合计
const totalData = () => {
if (!props.data || props.data.length === 0) return null;
const total: SpecData = {
specId: 0,
specName: '合计',
salesAmount: 0,
orderCount: 0,
quantity: 0,
averageOrderValue: 0,
productCost: 0,
shippingCost: 0,
otherCost: 0,
refundAmount: 0,
promotionFee: 0,
feeRatio: 0,
profitBeforeTax: 0,
salesTaxAmount: 0,
roi: 0,
profitAfterTax: 0,
};
props.data.forEach((item) => {
total.salesAmount += item.salesAmount || 0;
total.orderCount += item.orderCount || 0;
total.quantity += item.quantity || 0;
total.productCost += item.productCost || 0;
total.shippingCost += item.shippingCost || 0;
total.otherCost += item.otherCost || 0;
total.refundAmount += item.refundAmount || 0;
total.promotionFee += item.promotionFee || 0;
total.profitBeforeTax += item.profitBeforeTax || 0;
total.salesTaxAmount += item.salesTaxAmount || 0;
total.profitAfterTax += item.profitAfterTax || 0;
});
if (total.salesAmount > 0) {
total.averageOrderValue = total.salesAmount / total.orderCount;
total.feeRatio = (total.promotionFee / total.salesAmount) * 100;
total.roi = total.profitAfterTax / (total.productCost + total.shippingCost + total.otherCost + total.promotionFee) * 100;
}
return total;
};
</script>
<template>
<div
class="overflow-hidden rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div
class="flex items-center justify-between border-b border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] bg-white/40 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6"
>
<div>
<h3 class="text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">商品规格销售汇总</h3>
<p class="mt-1 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
各规格经营明细:规模、成本及最终损益
</p>
</div>
</div>
<div class="table-container">
<table class="w-full whitespace-nowrap text-left text-sm">
<thead
class="bg-slate-50 dark:bg-[hsl(240deg_3.7%_15.9%)] text-xs font-black uppercase text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
<tr>
<th
rowspan="2"
class="sticky-col border-r-2 border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] bg-white dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-5 text-base font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)] shadow-sm dark:shadow-none"
>
规格名称
</th>
<th
colspan="3"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] bg-blue-50/50 dark:bg-[hsl(217.2deg_32.6%_17.5%/50%)] p-3 text-center text-blue-700 dark:text-blue-400"
>
经营规模
</th>
<th
colspan="6"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] bg-orange-50/50 dark:bg-[hsl(24deg_9.8%_15%/50%)] p-3 text-center text-orange-700 dark:text-orange-400"
>
成本费用
</th>
<th
colspan="5"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] bg-emerald-50/50 dark:bg-[hsl(142deg_71.8%_29%/20%)] p-3 text-center text-emerald-700 dark:text-emerald-400"
>
盈利分析
</th>
</tr>
<tr class="bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] text-sm">
<!-- 规模 -->
<th class="border-b border-l px-5 py-3 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">销售额</th>
<th class="border-b px-5 py-3">订单量</th>
<th class="border-b px-5 py-3">客单价</th>
<!-- 成本 -->
<th class="border-b border-l px-5 py-3">商品成本</th>
<th class="border-b px-5 py-3">运费</th>
<th class="border-b px-5 py-3">其他成本</th>
<th class="border-b px-5 py-3 font-bold text-rose-600 dark:text-rose-400">退款金额</th>
<th class="border-b px-5 py-3">推广费</th>
<th class="border-b px-5 py-3 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">费比 %</th>
<!-- 盈利 -->
<th class="border-b border-l px-5 py-3 font-bold">税前盈亏</th>
<th class="border-b px-5 py-3 italic text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ (taxRate * 100).toFixed(0) }}%税额</th>
<th class="border-b px-5 py-3 font-black text-indigo-700 dark:text-indigo-400">ROI</th>
<th class="border-b bg-emerald-600 dark:bg-emerald-600 px-5 py-3 font-black text-white">税后盈亏</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 dark:divide-[hsl(240deg_3.7%_22%)]">
<tr
v-for="item in data"
:key="item.specId"
class="transition-colors hover:bg-slate-50/50 dark:hover:bg-[hsl(240deg_3.7%_15.9%/30%)]"
>
<!-- 规格名称 -->
<td class="sticky-col border-r-2 border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] bg-white dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-5 shadow-sm dark:shadow-none">
<div class="font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">{{ item.specName }}</div>
<div v-if="item.specCode" class="mt-0.5 font-mono text-xs text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">{{ item.specCode }}</div>
</td>
<!-- 规模 -->
<td class="p-5 font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">{{ formatAmount(item.salesAmount) }}</td>
<td class="p-5 font-medium">
<span>{{ formatCount(item.orderCount) }}</span>
<span class="ml-1 text-xs text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">单</span>
<span class="ml-2 text-xs text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">({{ formatCount(item.quantity) }}件)</span>
</td>
<td class="p-5 font-medium">{{ formatAmount(item.averageOrderValue) }}</td>
<!-- 成本 -->
<td class="p-5">{{ item.productCost ? formatAmount(item.productCost) : '-' }}</td>
<td class="p-5">{{ item.shippingCost ? formatAmount(item.shippingCost) : '-' }}</td>
<td class="p-5">{{ item.otherCost ? formatAmount(item.otherCost) : '-' }}</td>
<td class="p-5 font-bold text-rose-600 dark:text-rose-400">
{{ item.refundAmount ? formatAmount(item.refundAmount) : '-' }}
</td>
<td class="p-5">{{ item.promotionFee ? formatAmount(item.promotionFee) : '-' }}</td>
<td class="p-5 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">{{ formatPercent(item.feeRatio) }}</td>
<!-- 盈利 -->
<td class="p-5 font-bold" :class="item.profitBeforeTax >= 0 ? 'text-slate-800 dark:text-[hsl(0deg_0%_95%)]' : 'text-rose-600 dark:text-rose-400'">
{{ formatAmount(item.profitBeforeTax) }}
</td>
<td class="p-5 italic text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">{{ item.salesTaxAmount ? formatAmount(item.salesTaxAmount) : '-' }}</td>
<td class="p-5 font-black text-indigo-700 dark:text-indigo-400">{{ item.roi ? item.roi.toFixed(2) : '-' }}</td>
<td class="bg-emerald-50 dark:bg-[hsl(142deg_71.8%_29%/20%)] p-5 text-base font-black" :class="item.profitAfterTax >= 0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400'">
{{ formatAmount(item.profitAfterTax) }}
</td>
</tr>
<tr v-if="!data || data.length === 0">
<td colspan="15" class="p-8 text-center text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">暂无规格数据</td>
</tr>
</tbody>
<tfoot v-if="totalData()" class="bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)]">
<tr class="font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<td class="border-r-2 border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] p-5 text-base">合计</td>
<td class="p-5">{{ formatAmount(totalData()!.salesAmount) }}</td>
<td class="p-5">
<span>{{ formatCount(totalData()!.orderCount) }}</span>
<span class="ml-1 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">单</span>
<span class="ml-2 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">({{ formatCount(totalData()!.quantity) }}件)</span>
</td>
<td class="p-5">-</td>
<td class="p-5">{{ formatAmount(totalData()!.productCost) }}</td>
<td class="p-5">{{ formatAmount(totalData()!.shippingCost) }}</td>
<td class="p-5">{{ formatAmount(totalData()!.otherCost) }}</td>
<td class="p-5 text-rose-600 dark:text-rose-400">{{ formatAmount(totalData()!.refundAmount) }}</td>
<td class="p-5">{{ formatAmount(totalData()!.promotionFee) }}</td>
<td class="p-5 text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ formatPercent(totalData()!.feeRatio) }}</td>
<td class="p-5">{{ formatAmount(totalData()!.profitBeforeTax) }}</td>
<td class="p-5 italic text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ formatAmount(totalData()!.salesTaxAmount) }}</td>
<td class="p-5 text-indigo-700 dark:text-indigo-400">{{ totalData()!.roi ? totalData()!.roi.toFixed(2) : '-' }}</td>
<td class="bg-emerald-100 dark:bg-emerald-900/30 p-5 text-base text-emerald-600 dark:text-emerald-400">{{ formatAmount(totalData()!.profitAfterTax) }}</td>
</tr>
</tfoot>
</table>
</div>
</div>
</template>
<style scoped>
.sticky-col {
position: sticky;
left: 0;
z-index: 10;
}
.table-container {
overflow-x: auto;
}
.table-container::-webkit-scrollbar {
height: 6px;
}
.table-container::-webkit-scrollbar-thumb {
background: #e2e8f0;
border-radius: 10px;
}
</style>
@@ -0,0 +1,147 @@
<script lang="ts" setup>
interface Props {
data: {
productName?: string;
totalSalesAmount?: number;
totalOrderCount?: number;
averageOrderValue?: number;
totalPromotionFee?: number;
totalCostAmount?: number;
totalRefundAmount?: number;
totalProfitAfterTax?: number;
totalNetProfitAfterTax?: number;
totalTaxAmount?: number;
monthOverMonthGrowth?: number;
salesAmountAchievementRate?: number;
orderCountAchievementRate?: number;
averageFeeRatio?: number;
totalROI?: number;
} | null;
loading?: boolean;
}
defineProps<Props>();
const formatAmount = (amount: number | undefined) => {
if (amount === undefined) return '-';
return `¥${amount.toLocaleString('zh-CN')}`;
};
const toNumber = (value: unknown): number | undefined => {
if (value === undefined || value === null || value === '') return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
};
const formatPercentPlain = (value: number | undefined | null) => {
if (value == null) return '-';
return `${value.toFixed(1)}%`;
};
const formatPercent = (value: number | undefined) => {
if (value === undefined) return '-';
return `${value > 0 ? '+' : ''}${value.toFixed(1)}%`;
};
</script>
<template>
<div class="grid grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-4">
<!-- 销售额 -->
<div
class="flex flex-col justify-between rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 flex items-start justify-between">
<span class="text-xs font-black uppercase tracking-widest text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
商品销售总额
</span>
<span
v-if="data?.monthOverMonthGrowth !== undefined"
class="rounded bg-emerald-50 dark:bg-[hsl(142deg_71.8%_29%/20%)] px-2 py-1 text-xs font-bold text-emerald-600 dark:text-emerald-400"
>
增长率 {{ formatPercent(data.monthOverMonthGrowth) }}
</span>
</div>
<div class="text-4xl font-black leading-none text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
{{ data?.totalSalesAmount ? formatAmount(data.totalSalesAmount) : '-' }}
</div>
<div
v-if="data?.salesAmountAchievementRate !== undefined"
class="mt-6 flex items-center justify-between border-t border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pt-4 text-xs font-bold"
>
<span class="text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">销售额目标达成</span>
<span class="font-black text-blue-600 dark:text-blue-400">
{{ formatPercentPlain(data.salesAmountAchievementRate) }}
</span>
</div>
</div>
<!-- 订单达成 -->
<div
class="flex flex-col justify-between rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 text-xs font-black uppercase tracking-widest text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
订单总量与达成
</div>
<div class="text-4xl font-black leading-none text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
{{ data?.totalOrderCount?.toLocaleString('zh-CN') || '-' }}
<span class="ml-1 text-sm font-normal text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">单</span>
</div>
<div v-if="data?.orderCountAchievementRate !== undefined" class="mt-6">
<div class="mb-2 flex justify-between text-[10px] font-black text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<span>目标达成率</span>
<span>
{{ formatPercentPlain(data.orderCountAchievementRate) }}
</span>
</div>
<div class="h-2 w-full overflow-hidden rounded-full bg-slate-100">
<div
class="h-full bg-indigo-500 transition-all duration-1000"
:style="{ width: `${Math.min(data.orderCountAchievementRate || 0, 100)}%` }"
></div>
</div>
</div>
</div>
<!-- 推广效率 -->
<div
class="flex flex-col justify-between rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 text-xs font-black uppercase tracking-widest text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
投资回报率 (ROI)
</div>
<div class="text-4xl font-black leading-none text-indigo-600 dark:text-indigo-400">
{{ toNumber(data?.totalROI)?.toFixed(2) || '-' }}
</div>
<div
v-if="data?.averageFeeRatio !== undefined"
class="mt-6 space-y-2 border-t border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pt-4"
>
<div class="flex justify-between text-xs font-bold">
<span class="text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">平均费比</span>
<span class="text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
{{ formatPercentPlain(data.averageFeeRatio) }}
</span>
</div>
</div>
</div>
<!-- 利润汇总 -->
<div
class="flex flex-col justify-between rounded-[20px] border-l-4 border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] border-l-emerald-500 dark:border-l-emerald-500 bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 text-xs font-black uppercase tracking-widest text-emerald-600 dark:text-emerald-400">
商品净利润 (税后)
</div>
<div class="text-4xl font-black leading-none text-emerald-600 dark:text-emerald-400">
{{ data?.totalNetProfitAfterTax ? formatAmount(data.totalNetProfitAfterTax) : '-' }}
</div>
<div
v-if="data?.totalTaxAmount !== undefined"
class="mt-6 flex justify-between border-t border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pt-4 text-[11px] font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
>
<span>已扣除税额</span>
<span>{{ formatAmount(data.totalTaxAmount) }}</span>
</div>
</div>
</div>
</template>
@@ -0,0 +1,207 @@
<script lang="ts" setup>
import { Button, DatePicker, InputNumber } from 'ant-design-vue';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
interface Props {
modelValue: {
taxRate: number;
activeTimeRange: '7days' | '30days' | 'custom' | 'today' | 'yesterday';
customDateRange: [Dayjs, Dayjs] | undefined;
dateRange: [Dayjs, Dayjs];
};
}
interface Emits {
(e: 'update:modelValue', val: Props['modelValue']): void;
}
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const TAX_RATE_KEY = 'overview-tax-rate';
const formatTaxRate = (value: null | number | string | undefined) => {
if (value === null || value === undefined || value === '') return '';
const num = Number(value);
if (!Number.isFinite(num)) return '';
return `${num * 100}%`;
};
const parseTaxRate = (value: string | undefined) => {
if (!value) return 0;
const num = Number(value.replace('%', '').trim());
return Number.isFinite(num) ? num / 100 : 0;
};
const switchTimeRange = (type: '7days' | '30days' | 'custom' | 'today' | 'yesterday') => {
let startDate: Dayjs;
let endDate: Dayjs = dayjs();
switch (type) {
case '7days':
startDate = dayjs().subtract(7, 'day');
break;
case '30days':
startDate = dayjs().subtract(30, 'day');
break;
case 'custom':
if (props.modelValue.customDateRange) {
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: type,
dateRange: props.modelValue.customDateRange,
});
}
return;
case 'today':
startDate = dayjs();
endDate = dayjs();
break;
case 'yesterday':
startDate = dayjs().subtract(1, 'day');
endDate = dayjs().subtract(1, 'day');
break;
}
const newRange: [Dayjs, Dayjs] = [startDate, endDate];
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: type,
dateRange: newRange,
customDateRange: newRange,
});
};
const handleCustomDateRangeChange = (
value: [Dayjs, Dayjs] | [string, string] | null,
) => {
if (value && Array.isArray(value) && value.length === 2) {
const dates = [
dayjs.isDayjs(value[0]) ? value[0] : dayjs(value[0]),
dayjs.isDayjs(value[1]) ? value[1] : dayjs(value[1]),
] as [Dayjs, Dayjs];
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: 'custom',
dateRange: dates,
customDateRange: dates,
});
}
};
const handleTaxRateChange = (val: number | string | undefined) => {
const num = typeof val === 'string' ? parseTaxRate(val) : val ?? 0.04;
localStorage.setItem(TAX_RATE_KEY, String(num));
emit('update:modelValue', {
...props.modelValue,
taxRate: num,
});
};
</script>
<template>
<div class="flex items-center gap-2">
<!-- 税率输入 -->
<div
class="flex h-[50px] items-center gap-2 rounded-2xl border border-slate-200 bg-slate-200/50 dark:bg-[hsl(240deg_3.7%_15.9%/30%)] px-3"
>
<span class="text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">税率</span>
<InputNumber
:value="props.modelValue.taxRate"
:min="0"
:max="1"
:step="0.01"
:precision="2"
size="small"
class="tax-rate-input !h-8 !w-20 !rounded-lg !border-none !bg-white/30 dark:!bg-[hsl(240deg_3.7%_22%/30%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)] !text-sm !font-bold"
:formatter="formatTaxRate"
:parser="parseTaxRate"
@change="handleTaxRateChange"
/>
</div>
<!-- 时间选择器 -->
<div
class="flex items-center gap-1.5 rounded-2xl border border-slate-200 bg-slate-200/50 dark:bg-[hsl(240deg_3.7%_15.9%/30%)] p-1"
>
<div class="flex rounded-xl bg-white/40 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-1 shadow-inner dark:shadow-none">
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-lg !border-none !px-5 !py-2 !text-sm !font-bold !shadow-none !transition-all"
:class="
props.modelValue.activeTimeRange === 'today'
? '!bg-white !font-black !text-blue-600 dark:text-blue-400 dark:!shadow-none !shadow-sm'
: '!bg-transparent !text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] hover:!text-slate-800'
"
@click="switchTimeRange('today')"
>
今日
</Button>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-lg !border-none !px-5 !py-2 !text-sm !font-bold !shadow-none !transition-all"
:class="
props.modelValue.activeTimeRange === 'yesterday'
? '!bg-white !font-black !text-blue-600 dark:text-blue-400 dark:!shadow-none !shadow-sm'
: '!bg-transparent !text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] hover:!text-slate-800'
"
@click="switchTimeRange('yesterday')"
>
昨日
</Button>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-lg !border-none !px-5 !py-2 !text-sm !font-bold !shadow-none !transition-all"
:class="
props.modelValue.activeTimeRange === '7days'
? '!bg-white !font-black !text-blue-600 dark:text-blue-400 dark:!shadow-none !shadow-sm'
: '!bg-transparent !text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] hover:!text-slate-800'
"
@click="switchTimeRange('7days')"
>
近7日
</Button>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-lg !border-none !px-5 !py-2 !text-sm !font-bold !shadow-none !transition-all"
:class="
props.modelValue.activeTimeRange === '30days'
? '!bg-white !font-black !text-blue-600 dark:text-blue-400 dark:!shadow-none !shadow-sm'
: '!bg-transparent !text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] hover:!text-slate-800'
"
@click="switchTimeRange('30days')"
>
近30日
</Button>
</div>
<!-- 日期选择器 -->
<div class="flex items-center gap-2">
<span class="text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">自定义日期</span>
<DatePicker.RangePicker
:value="props.modelValue.customDateRange"
size="small"
format="YYYY-MM-DD"
:allow-clear="false"
:placeholder="['开始日期', '结束日期']"
class="!h-8 !cursor-pointer !border-none !bg-transparent !text-sm !font-bold"
@change="handleCustomDateRangeChange"
/>
</div>
</div>
</div>
</template>
<style scoped>
:deep(.tax-rate-input .ant-input-number-input) {
height: 32px;
line-height: 32px;
padding-top: 0;
padding-bottom: 0;
}
</style>
@@ -1,37 +1,204 @@
<script lang="ts" setup>
import { computed, ref } from 'vue';
import type { Dayjs } from 'dayjs';
import { computed, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { Page } from '@vben/common-ui';
import { Tabs } from 'ant-design-vue';
import { Spin, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import OverviewTab from './tabs/OverviewTab.vue';
import TimeRangeBar from './components/TimeRangeBar.vue';
import StatCards from './components/StatCards.vue';
import SalesTrendChart from './components/SalesTrendChart.vue';
import FinancialPanel from './components/FinancialPanel.vue';
import SpecSummaryTable from './components/SpecSummaryTable.vue';
import { getProductOverviewApi } from '#/api/ecommerce/product-overview';
defineOptions({ name: 'ProductDetails' });
defineOptions({ name: 'ProductOverview' });
const route = useRoute();
// 商品ID(从路由参数获取)
const productId = computed(() => {
const id = route.params.id;
return id ? Number(id) : 0;
const parsed = id ? Number(id) : 0;
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
});
// 当前激活的 tab
const activeKey = ref('overview');
// 响应式数据
const loading = ref(false);
const overviewData = ref<any>(null);
const normalizeOverview = (raw: any) => {
if (!raw || typeof raw !== 'object') return null;
return {
// 保留所有 KPI 字段
...raw,
// 防御性处理嵌套结构
salesAmountTrend: {
...(raw.salesAmountTrend || {}),
dailyDataList: Array.isArray(raw.salesAmountTrend?.dailyDataList)
? raw.salesAmountTrend.dailyDataList
: [],
},
orderCountTrend: {
...(raw.orderCountTrend || {}),
dailyDataList: Array.isArray(raw.orderCountTrend?.dailyDataList)
? raw.orderCountTrend.dailyDataList
: [],
},
specSummaries: {
...(raw.specSummaries || {}),
list: Array.isArray(raw.specSummaries?.list) ? raw.specSummaries.list : [],
},
};
};
// 日期范围
const dateRange = ref<[Dayjs, Dayjs]>([
dayjs().subtract(30, 'day'),
dayjs(),
]);
// 当前选中的时间范围类型
const activeTimeRange = ref<
'7days' | '30days' | 'custom' | 'today' | 'yesterday'
>('30days');
// 自定义日期范围
const customDateRange = ref<[Dayjs, Dayjs] | undefined>([
dateRange.value[0],
dateRange.value[1],
]);
// 税率(持久化)
const TAX_RATE_KEY = 'overview-tax-rate';
const taxRate = ref<number>(0.04);
taxRate.value = Number(localStorage.getItem(TAX_RATE_KEY)) || 0.04;
watch(taxRate, () => {
fetchOverview();
});
// 时间范围状态(传递给子组件)
const timeRangeState = computed(() => ({
taxRate: taxRate.value,
activeTimeRange: activeTimeRange.value,
customDateRange: customDateRange.value,
dateRange: dateRange.value,
}));
// 监听子组件的时间范围变化
const handleTimeRangeChange = async (val: typeof timeRangeState.value) => {
taxRate.value = val.taxRate;
activeTimeRange.value = val.activeTimeRange;
customDateRange.value = val.customDateRange;
dateRange.value = val.dateRange;
await fetchOverview();
};
// 获取概览数据
async function fetchOverview() {
if (!productId.value) return;
loading.value = true;
try {
const res = await getProductOverviewApi({
productId: productId.value,
startDate: dateRange.value[0].format('YYYY-MM-DD'),
endDate: dateRange.value[1].format('YYYY-MM-DD'),
taxRate: taxRate.value,
});
overviewData.value = normalizeOverview(res);
} catch (err: any) {
message.error(err?.message || '加载失败');
} finally {
loading.value = false;
}
}
// 初始加载
watch(productId, (val) => {
if (val) fetchOverview();
}, { immediate: true });
// 计算 page title 用 productName
const pageTitle = computed(() => overviewData.value?.productName || '商品概览');
</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
:title="pageTitle"
auto-content-height
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<template #description>
<div class="mt-1 text-sm font-bold italic text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
商品ID: {{ productId || 'N/A' }} · 数据更新于: {{ dayjs().format('YYYY-MM-DD HH:mm:ss') }}
</div>
</template>
<template #extra>
<TimeRangeBar
:model-value="timeRangeState"
@update:model-value="handleTimeRangeChange"
/>
</template>
<Spin :spinning="loading">
<div v-if="overviewData" class="mx-auto w-full space-y-6 p-4 md:p-8">
<!-- 第一层:核心统计卡片 -->
<StatCards :data="overviewData" :loading="loading" />
<!-- 第二层:趋势与财务拆解 -->
<div class="grid grid-cols-1 gap-6 xl:grid-cols-3">
<SalesTrendChart :data="overviewData" />
<FinancialPanel :data="overviewData" :tax-rate="taxRate" />
</div>
<!-- 第三层:规格销售汇总 -->
<SpecSummaryTable
:data="overviewData?.specSummaries?.list"
:tax-rate="taxRate"
/>
</div>
<div v-else-if="!loading" class="flex items-center justify-center p-8 text-slate-400">
暂无数据
</div>
</Spin>
</Page>
</template>
<style scoped>
/* 表格滚动条优化 */
.table-container::-webkit-scrollbar {
height: 6px;
}
.table-container::-webkit-scrollbar-thumb {
background: #e2e8f0;
border-radius: 10px;
}
</style>
<style>
html.dark .product-overview-thead table thead th {
background-color: hsl(240deg 3.7% 15.9% / 80%) !important;
}
html.dark .product-overview-thead table thead th {
border-color: hsl(240deg 3.7% 22%) !important;
}
html.dark .table-container table tbody tr:hover td {
background-color: hsl(217.2deg 32.6% 17.5% / 30%) !important;
}
html.dark .table-container::-webkit-scrollbar-thumb {
background: hsl(240deg 3.7% 22%);
}
html.dark .table-container::-webkit-scrollbar-track {
background: hsl(240deg 3.7% 15.9%);
}
</style>
@@ -80,7 +80,7 @@ function handleModalSuccess() {
</script>
<template>
<Page :auto-content-height="true" content-class="flex-col">
<Page :auto-content-height="true" content-class="flex-col dark:bg-[#0f1623]">
<!-- 工具栏区域 -->
<template #extra>
<Flex gap="small" align="center">
@@ -122,13 +122,13 @@ function handleModalSuccess() {
/>
<!-- 网格视图 -->
<ProductGridView
v-else
ref="productGridViewRef"
v-model:search-form="searchForm"
@edit="handleEdit"
@delete="handleDelete"
/>
<div v-else class="flex-1 overflow-y-auto dark:bg-[#0f1623]">
<ProductGridView
ref="productGridViewRef"
v-model:search-form="searchForm"
@delete="handleDelete"
/>
</div>
<!-- 商品表单模态框 -->
<ProductFormModal ref="productFormModalRef" @success="handleModalSuccess" />
@@ -272,7 +272,7 @@ onUnmounted(() => {
<!-- 网格内容 -->
<Card
class="flex flex-1 flex-col overflow-y-auto"
class="flex flex-1 flex-col overflow-y-auto dark:bg-[#111827] dark:border-[#374151]"
:body-style="{
padding: '16px',
display: 'flex',