refactor(概览): 汇总字段 totalCost 重命名为 orderCost,列名统一为订单成本

This commit is contained in:
小蟑螂
2026-06-01 00:29:35 +08:00
parent c3447eab86
commit e1d90ccba3
28 changed files with 1636 additions and 235 deletions
@@ -0,0 +1,175 @@
package top.xyquan.ecomdmbbackend.modules.ecom.order.mapper;
import lombok.Data;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/**
* 订单/费用 SQL 聚合(SQL 均在 {@code mapper/order/OrderStatAggMapper.xml})。
* <p>
* 行类型定义为内嵌类,避免单独拆多个 model 文件。
*/
@Mapper
public interface OrderStatAggMapper {
/** SQL-1:shop × product 粒度,四表 rollup 基础 */
List<ShopProductRow> aggregateByShopProduct(
@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("start") LocalDateTime start,
@Param("end") LocalDateTime end,
@Param("unionStatusIds") List<Long> unionStatusIds,
@Param("salesStatusIds") List<Long> salesStatusIds,
@Param("refundStatusIds") List<Long> refundStatusIds,
@Param("productCostStatusIds") List<Long> productCostStatusIds,
@Param("freightCostStatusIds") List<Long> freightCostStatusIds,
@Param("otherCostStatusIds") List<Long> otherCostStatusIds);
/** SQL-2:日趋势 */
List<DailyRow> aggregateDaily(
@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("start") LocalDateTime start,
@Param("end") LocalDateTime end,
@Param("unionStatusIds") List<Long> unionStatusIds,
@Param("salesStatusIds") List<Long> salesStatusIds,
@Param("refundStatusIds") List<Long> refundStatusIds,
@Param("productCostStatusIds") List<Long> productCostStatusIds,
@Param("freightCostStatusIds") List<Long> freightCostStatusIds,
@Param("otherCostStatusIds") List<Long> otherCostStatusIds);
/** SQL-3:三段时间 KPI(一次扫描) */
PeriodKpiRow aggregatePeriodKpi(
@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("scanStart") LocalDateTime scanStart,
@Param("scanEnd") LocalDateTime scanEnd,
@Param("curStart") LocalDateTime curStart,
@Param("curEnd") LocalDateTime curEnd,
@Param("prevStart") LocalDateTime prevStart,
@Param("prevEnd") LocalDateTime prevEnd,
@Param("yoyStart") LocalDateTime yoyStart,
@Param("yoyEnd") LocalDateTime yoyEnd,
@Param("unionStatusIds") List<Long> unionStatusIds,
@Param("salesStatusIds") List<Long> salesStatusIds,
@Param("refundStatusIds") List<Long> refundStatusIds,
@Param("productCostStatusIds") List<Long> productCostStatusIds,
@Param("freightCostStatusIds") List<Long> freightCostStatusIds,
@Param("otherCostStatusIds") List<Long> otherCostStatusIds);
/** 推广费三段时间 KPI */
FeeKpiRow aggregatePromotionPeriodKpi(
@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("scanStart") LocalDate scanStart,
@Param("scanEnd") LocalDate scanEnd,
@Param("curStart") LocalDate curStart,
@Param("curEnd") LocalDate curEnd,
@Param("prevStart") LocalDate prevStart,
@Param("prevEnd") LocalDate prevEnd,
@Param("yoyStart") LocalDate yoyStart,
@Param("yoyEnd") LocalDate yoyEnd);
/** 刷单费三段时间 KPI */
FeeKpiRow aggregateBrushPeriodKpi(
@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("scanStart") LocalDateTime scanStart,
@Param("scanEnd") LocalDateTime scanEnd,
@Param("curStart") LocalDateTime curStart,
@Param("curEnd") LocalDateTime curEnd,
@Param("prevStart") LocalDateTime prevStart,
@Param("prevEnd") LocalDateTime prevEnd,
@Param("yoyStart") LocalDateTime yoyStart,
@Param("yoyEnd") LocalDateTime yoyEnd);
/** SQL-4:推广费明细(四表分摊) */
List<PromotionRow> aggregatePromotionFees(
@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
/** SQL-5:刷单费按店铺 */
List<BrushRow> aggregateBrushFees(
@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("start") LocalDateTime start,
@Param("end") LocalDateTime end);
@Data
class ShopProductRow {
private Long shopId;
private Long platformId;
private Long productId;
private Long categoryId;
private BigDecimal salesAmount;
private Long orderCount;
private BigDecimal refundAmount;
private BigDecimal productCost;
private BigDecimal freightCost;
private BigDecimal otherCost;
private BigDecimal gmvAllStatus;
}
@Data
class DailyRow {
private LocalDate statDate;
private BigDecimal salesAmount;
private BigDecimal refundAmount;
private BigDecimal productCost;
private BigDecimal freightCost;
private BigDecimal otherCost;
}
@Data
class PeriodKpiRow {
private BigDecimal curSalesAmount;
private Long curOrderCount;
private BigDecimal curRefundAmount;
private BigDecimal curProductCost;
private BigDecimal curFreightCost;
private BigDecimal curOtherCost;
private BigDecimal curGmvAllStatus;
private BigDecimal prevSalesAmount;
private Long prevOrderCount;
private BigDecimal prevRefundAmount;
private BigDecimal prevProductCost;
private BigDecimal prevFreightCost;
private BigDecimal prevOtherCost;
private BigDecimal prevGmvAllStatus;
private BigDecimal yoySalesAmount;
private Long yoyOrderCount;
private BigDecimal yoyRefundAmount;
private BigDecimal yoyProductCost;
private BigDecimal yoyFreightCost;
private BigDecimal yoyOtherCost;
private BigDecimal yoyGmvAllStatus;
}
@Data
class FeeKpiRow {
private BigDecimal curAmount;
private BigDecimal prevAmount;
private BigDecimal yoyAmount;
}
@Data
class PromotionRow {
private Long shopId;
private Long productId;
private Long categoryId;
private BigDecimal feeAmount;
}
@Data
class BrushRow {
private Long shopId;
private BigDecimal brushAmount;
}
}
@@ -286,6 +286,9 @@ public class CompanyOverviewVO {
@Schema(description = "销售额", example = "50000.00")
private BigDecimal salesAmount;
@Schema(description = "GMV(全订单状态商家实收合计)", example = "52000.00")
private BigDecimal gmv;
@Schema(description = "单量", example = "500")
private Integer orderCount;
@@ -301,8 +304,8 @@ public class CompanyOverviewVO {
@Schema(description = "其他成本", example = "1000.00")
private BigDecimal otherCost;
@Schema(description = "总成本(商品成本+运费+其他成本)", example = "5000.00")
private BigDecimal totalCost;
@Schema(description = "订单成本(商品成本+运费+其他成本,不含推广费、刷单费)", example = "5000.00")
private BigDecimal orderCost;
@Schema(description = "退款金额", example = "1000.00")
private BigDecimal refundAmount;
@@ -316,13 +319,16 @@ public class CompanyOverviewVO {
@Schema(description = "费比", example = "0.10")
private BigDecimal feeRatio;
@Schema(description = "税前盈亏", example = "35000.00")
@Schema(description = "毛利(实际销售额 − 订单成本 − 退款,未扣推广/刷单/税)", example = "38000.00")
private BigDecimal grossProfit;
@Schema(description = "税前净利(毛利 − 推广费 − 刷单费)", example = "35000.00")
private BigDecimal totalProfitBeforeTax;
@Schema(description = "销售额4%税额", example = "2000.00")
private BigDecimal salesTaxAmount;
@Schema(description = "税后盈亏", example = "30000.00")
@Schema(description = "税后净利(税前净利 − 税额)", example = "30000.00")
private BigDecimal profitAfterTax;
@Schema(description = "ROI", example = "1.5")
@@ -344,27 +350,26 @@ public class CompanyOverviewVO {
@Schema(description = "销售额", example = "50000.00")
private BigDecimal salesAmount;
@Schema(description = "GMV(全订单状态商家实收合计)", example = "52000.00")
private BigDecimal gmv;
@Schema(description = "单量", example = "500")
private Integer orderCount;
@Schema(description = "客单价", example = "100.00")
private BigDecimal averageOrderValue;
@Schema(description = "商品成本", example = "3000.00")
private BigDecimal productCost;
@Schema(description = "运费", example = "1000.00")
private BigDecimal shippingCost;
@Schema(description = "其他成本", example = "1000.00")
private BigDecimal otherCost;
@Schema(description = "总成本(商品成本+运费+其他成本)", example = "5000.00")
private BigDecimal totalCost;
@Schema(description = "订单成本(商品成本+运费+其他成本,不含推广费、刷单费)", example = "5000.00")
private BigDecimal orderCost;
@Schema(description = "退款金额", example = "1000.00")
private BigDecimal refundAmount;
@@ -378,13 +383,16 @@ public class CompanyOverviewVO {
@Schema(description = "费比", example = "0.10")
private BigDecimal feeRatio;
@Schema(description = "税前盈亏", example = "35000.00")
@Schema(description = "毛利(实际销售额 − 订单成本 − 退款,未扣推广/刷单/税)", example = "38000.00")
private BigDecimal grossProfit;
@Schema(description = "税前净利(毛利 − 推广费 − 刷单费)", example = "35000.00")
private BigDecimal totalProfitBeforeTax;
@Schema(description = "销售额4%税额", example = "2000.00")
private BigDecimal salesTaxAmount;
@Schema(description = "税后盈亏", example = "30000.00")
@Schema(description = "税后净利(税前净利 − 税额)", example = "30000.00")
private BigDecimal profitAfterTax;
@Schema(description = "ROI", example = "1.5")
@@ -418,6 +426,9 @@ public class CompanyOverviewVO {
@Schema(description = "销售额", example = "283600.00")
private BigDecimal salesAmount;
@Schema(description = "GMV(全订单状态商家实收合计)", example = "290000.00")
private BigDecimal gmv;
@Schema(description = "单量", example = "4521")
private Integer orderCount;
@@ -433,8 +444,8 @@ public class CompanyOverviewVO {
@Schema(description = "其他成本", example = "3200.00")
private BigDecimal otherCost;
@Schema(description = "总成本(商品成本+运费+其他成本)", example = "167700.00")
private BigDecimal totalCost;
@Schema(description = "订单成本(商品成本+运费+其他成本,不含推广费、刷单费)", example = "167700.00")
private BigDecimal orderCost;
@Schema(description = "退款金额", example = "12600.00")
private BigDecimal refundAmount;
@@ -448,7 +459,10 @@ public class CompanyOverviewVO {
@Schema(description = "费比", example = "0.187")
private BigDecimal feeRatio;
@Schema(description = "税前盈亏", example = "98600.00")
@Schema(description = "毛利(实际销售额 − 订单成本 − 退款,未扣推广/刷单/税)", example = "102000.00")
private BigDecimal grossProfit;
@Schema(description = "税前净利(毛利 − 推广费 − 刷单费)", example = "98600.00")
private BigDecimal totalProfitBeforeTax;
@Schema(description = "销售额4%税额", example = "11344.00")
@@ -457,7 +471,7 @@ public class CompanyOverviewVO {
@Schema(description = "ROI", example = "2.34")
private BigDecimal roi;
@Schema(description = "税后盈亏", example = "87256.00")
@Schema(description = "税后净利(税前净利 − 税额)", example = "87256.00")
private BigDecimal profitAfterTax;
}
}
@@ -226,8 +226,8 @@ public class ShopOverviewStatisticsVO {
@Schema(description = "其他成本", example = "1000.00")
private BigDecimal otherCost;
@Schema(description = "总成本(商品成本+运费+其他成本)", example = "5000.00")
private BigDecimal totalCost;
@Schema(description = "订单成本(商品成本+运费+其他成本,不含推广费、刷单费)", example = "5000.00")
private BigDecimal orderCost;
@Schema(description = "退款金额", example = "1000.00")
private BigDecimal refundAmount;
@@ -284,8 +284,8 @@ public class ShopOverviewStatisticsVO {
@Schema(description = "其他成本", example = "1000.00")
private BigDecimal otherCost;
@Schema(description = "总成本(商品成本+运费+其他成本)", example = "5000.00")
private BigDecimal totalCost;
@Schema(description = "订单成本(商品成本+运费+其他成本,不含推广费、刷单费)", example = "5000.00")
private BigDecimal orderCost;
@Schema(description = "退款金额", example = "1000.00")
private BigDecimal refundAmount;
@@ -1,6 +1,7 @@
package top.xyquan.ecomdmbbackend.modules.ecom.overview.service;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyOverviewQueryDTO;
@@ -50,5 +51,18 @@ public interface CompanyOverviewService {
OrderStatusStatSets stat,
LocalDate startDate,
LocalDate endDate);
/**
* 基于 SQL 聚合行构建四表(与 {@link #buildWorkbenchSummaryTables} 口径一致,不拉订单明细)。
*/
CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg(
BigDecimal taxRate,
Long companyId,
List<ShopPO> shops,
List<OrderStatAggMapper.ShopProductRow> orderRows,
List<OrderStatAggMapper.PromotionRow> promotionRows,
List<OrderStatAggMapper.BrushRow> brushRows,
LocalDate startDate,
LocalDate endDate);
}
@@ -397,7 +397,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
s.setProductCost(c.getProductCost());
s.setShippingCost(c.getShippingCost());
s.setOtherCost(c.getOtherCost());
s.setTotalCost(c.getTotalCost());
s.setOrderCost(c.getOrderCost());
s.setRefundAmount(c.getRefundAmount());
s.setTotalPromotionFee(c.getTotalPromotionFee());
s.setBrushFee(c.getBrushFee());
@@ -456,7 +456,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
total.setProductCost(totalProductCost);
total.setShippingCost(totalShippingCost);
total.setOtherCost(totalOtherCost);
total.setTotalCost(totalCost);
total.setOrderCost(totalCost);
total.setRefundAmount(totalRefund);
total.setTotalPromotionFee(totalPromoFee);
total.setBrushFee(totalBrushFee);
@@ -489,7 +489,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
+ "%税额";
String[] headers = {
dimensionColumnHeader, "实际销售额", "单量", "客单价",
"商品成本", "运费", "其他成本", "总成本", "退款金额", "推广费", "刷单费用", "费比 %",
"商品成本", "运费", "其他成本", "订单成本", "退款金额", "推广费", "刷单费用", "费比 %",
"税前盈亏", taxHeader, "ROI", "税后盈亏"
};
@@ -531,7 +531,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
setCell(row, 4, bd2Money(d.getProductCost()), style);
setCell(row, 5, bd2Money(d.getShippingCost()), style);
setCell(row, 6, bd2Money(d.getOtherCost()), style);
setCell(row, 7, bd2Money(d.getTotalCost()), style);
setCell(row, 7, bd2Money(d.getOrderCost()), style);
setCell(row, 8, bd2Money(d.getRefundAmount()), style);
setCell(row, 9, bd2Money(d.getTotalPromotionFee()), style);
setCell(row, 10, bd2Money(d.getBrushFee()), style);
@@ -4,6 +4,7 @@ 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.brushorder.mapper.BrushOrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO;
@@ -35,6 +36,7 @@ import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -264,18 +266,19 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
overviewVO.setShopEfficiencyQuadrants(shopEfficiencyQuadrants);
// 9. 多店铺数据横向汇总
GmvDimensionMaps gmvMaps = loadGmvDimensionMaps(companyId, shops, startDate, endDate);
CompanyOverviewVO.ShopOverview shopOverview = calculateShopSummary(
shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate);
shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps);
overviewVO.setShopSummary(shopOverview);
// 10. 多品类数据横向汇总
CompanyOverviewVO.CategoryOverview categoryOverview = calculateCategorySummary(
orders, promotionFees, brushOrders, stat, companyId, startDate, endDate);
orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps);
overviewVO.setCategorySummary(categoryOverview);
// 11. 平台维度汇总
CompanyOverviewVO.PlatformOverview platformOverview = calculatePlatformSummary(
shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate);
shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps);
overviewVO.setPlatformSummary(platformOverview);
// 12. 汇总ROI和总税后盈亏
@@ -505,7 +508,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
*/
private CompanyOverviewVO.ShopOverview calculateShopSummary(
List<ShopPO> shops, List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, OrderStatusStatSets stat, Long companyId, LocalDate startDate, LocalDate endDate) {
List<BrushOrderPO> brushOrders, OrderStatusStatSets stat, Long companyId, LocalDate startDate,
LocalDate endDate, GmvDimensionMaps gmvMaps) {
List<CompanyOverviewVO.ShopSummary> summaries = new ArrayList<>();
// 按店铺分组数据
@@ -631,12 +635,15 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
summary.setTargetAmount(targetAmount);
summary.setSalesAmountAchievementRate(salesAmountAchievementRate);
summary.setSalesAmount(salesAmount);
summary.setGmv(gmvMaps.byShop().getOrDefault(shop.getId(), BigDecimal.ZERO));
summary.setGrossProfit(salesAmount.subtract(orderLineCost).subtract(refundAmount)
.setScale(2, RoundingMode.HALF_UP));
summary.setOrderCount(orderCount);
summary.setAverageOrderValue(averageOrderValue);
summary.setProductCost(productCost);
summary.setShippingCost(shippingCost);
summary.setOtherCost(otherCost);
summary.setTotalCost(productCost.add(shippingCost).add(otherCost));
summary.setOrderCost(productCost.add(shippingCost).add(otherCost));
summary.setRefundAmount(refundAmount);
summary.setTotalPromotionFee(totalPromotionFee);
summary.setBrushFee(brushFee);
@@ -675,9 +682,13 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
BigDecimal totalRefund = BigDecimal.ZERO;
BigDecimal totalPromoFee = BigDecimal.ZERO;
BigDecimal totalBrushFee = BigDecimal.ZERO;
BigDecimal totalGmv = BigDecimal.ZERO;
BigDecimal totalGrossProfit = BigDecimal.ZERO;
for (CompanyOverviewVO.ShopSummary s : shops) {
totalSales = totalSales.add(s.getSalesAmount() != null ? s.getSalesAmount() : BigDecimal.ZERO);
totalGmv = totalGmv.add(s.getGmv() != null ? s.getGmv() : BigDecimal.ZERO);
totalGrossProfit = totalGrossProfit.add(s.getGrossProfit() != null ? s.getGrossProfit() : BigDecimal.ZERO);
totalOrders += s.getOrderCount() != null ? s.getOrderCount() : 0;
totalTargetAmount = totalTargetAmount.add(s.getTargetAmount() != null ? s.getTargetAmount() : BigDecimal.ZERO);
totalTargetOrders += s.getTargetOrderCount() != null ? s.getTargetOrderCount() : 0;
@@ -715,6 +726,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
total.setShopId(0L);
total.setShopName("合计");
total.setSalesAmount(totalSales);
total.setGmv(totalGmv);
total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP));
total.setOrderCount(totalOrders);
total.setAverageOrderValue(avgOrderValue);
total.setTargetAmount(totalTargetAmount);
@@ -724,7 +737,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
total.setProductCost(totalProductCost);
total.setShippingCost(totalShippingCost);
total.setOtherCost(totalOtherCost);
total.setTotalCost(totalCost);
total.setOrderCost(totalCost);
total.setRefundAmount(totalRefund);
total.setTotalPromotionFee(totalPromoFee);
total.setBrushFee(totalBrushFee);
@@ -810,7 +823,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
private CompanyOverviewVO.CategoryOverview calculateCategorySummary(
List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, OrderStatusStatSets stat, Long companyId,
LocalDate startDate, LocalDate endDate) {
LocalDate startDate, LocalDate endDate, GmvDimensionMaps gmvMaps) {
// Query all categories to build categoryId -> categoryName map
LambdaQueryWrapper<CategoryPO> categoryWrapper = new LambdaQueryWrapper<>();
@@ -974,12 +987,15 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
summary.setCategoryId(categoryId == -1L ? null : categoryId);
summary.setCategoryName(categoryName);
summary.setSalesAmount(salesAmount);
summary.setGmv(gmvMaps.byCategoryKey().getOrDefault(categoryId, BigDecimal.ZERO));
summary.setGrossProfit(salesAmount.subtract(totalCost).subtract(refundAmount)
.setScale(2, RoundingMode.HALF_UP));
summary.setOrderCount(orderCount);
summary.setAverageOrderValue(averageOrderValue);
summary.setProductCost(productCost);
summary.setShippingCost(shippingCost);
summary.setOtherCost(otherCost);
summary.setTotalCost(totalCost);
summary.setOrderCost(totalCost);
summary.setRefundAmount(refundAmount);
summary.setTotalPromotionFee(totalPromotionFee);
summary.setBrushFee(totalBrushFee);
@@ -1015,9 +1031,13 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
BigDecimal totalRefund = BigDecimal.ZERO;
BigDecimal totalPromoFee = BigDecimal.ZERO;
BigDecimal totalBrushFee = BigDecimal.ZERO;
BigDecimal totalGmv = BigDecimal.ZERO;
BigDecimal totalGrossProfit = BigDecimal.ZERO;
for (CompanyOverviewVO.CategorySummary c : categories) {
totalSales = totalSales.add(c.getSalesAmount() != null ? c.getSalesAmount() : BigDecimal.ZERO);
totalGmv = totalGmv.add(c.getGmv() != null ? c.getGmv() : BigDecimal.ZERO);
totalGrossProfit = totalGrossProfit.add(c.getGrossProfit() != null ? c.getGrossProfit() : BigDecimal.ZERO);
totalOrders += c.getOrderCount() != null ? c.getOrderCount() : 0;
totalProductCost = totalProductCost.add(c.getProductCost() != null ? c.getProductCost() : BigDecimal.ZERO);
totalShippingCost = totalShippingCost.add(c.getShippingCost() != null ? c.getShippingCost() : BigDecimal.ZERO);
@@ -1046,12 +1066,14 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
total.setCategoryId(0L);
total.setCategoryName("合计");
total.setSalesAmount(totalSales);
total.setGmv(totalGmv);
total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP));
total.setOrderCount(totalOrders);
total.setAverageOrderValue(avgOrderValue);
total.setProductCost(totalProductCost);
total.setShippingCost(totalShippingCost);
total.setOtherCost(totalOtherCost);
total.setTotalCost(totalCost);
total.setOrderCost(totalCost);
total.setRefundAmount(totalRefund);
total.setTotalPromotionFee(totalPromoFee);
total.setBrushFee(totalBrushFee);
@@ -1069,7 +1091,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
private CompanyOverviewVO.PlatformOverview calculatePlatformSummary(
List<ShopPO> shops, List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, OrderStatusStatSets stat, Long companyId,
LocalDate startDate, LocalDate endDate) {
LocalDate startDate, LocalDate endDate, GmvDimensionMaps gmvMaps) {
List<CompanyOverviewVO.PlatformSummary> platformSummaries = new ArrayList<>();
@@ -1134,6 +1156,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
BigDecimal totalBrushFee = BigDecimal.ZERO;
BigDecimal totalTargetAmount = BigDecimal.ZERO;
int totalTargetOrderCount = 0;
BigDecimal totalGmv = BigDecimal.ZERO;
for (ShopPO shop : platformShops) {
List<OrderPO> shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>());
@@ -1186,6 +1209,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
.reduce(BigDecimal.ZERO, BigDecimal::add);
totalBrushFee = totalBrushFee.add(shopBrush);
totalGmv = totalGmv.add(gmvMaps.byShop().getOrDefault(shop.getId(), BigDecimal.ZERO));
// 目标金额和目标单量
BigDecimal shopTargetAmount = shopTargets.stream()
.map(target -> target.getTargetAmount() != null ? target.getTargetAmount() : BigDecimal.ZERO)
@@ -1246,12 +1271,15 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
platformSummary.setTargetAmount(totalTargetAmount);
platformSummary.setSalesAmountAchievementRate(salesAmountAchievementRate);
platformSummary.setSalesAmount(totalSalesAmount);
platformSummary.setGmv(totalGmv);
platformSummary.setGrossProfit(totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount)
.setScale(2, RoundingMode.HALF_UP));
platformSummary.setOrderCount(totalOrderCount);
platformSummary.setAverageOrderValue(averageOrderValue);
platformSummary.setProductCost(totalProductCost);
platformSummary.setShippingCost(totalShippingCost);
platformSummary.setOtherCost(totalOtherCost);
platformSummary.setTotalCost(totalCost);
platformSummary.setOrderCost(totalCost);
platformSummary.setRefundAmount(totalRefundAmount);
platformSummary.setTotalPromotionFee(totalPromotionFee);
platformSummary.setBrushFee(totalBrushFee);
@@ -1268,7 +1296,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
if (!shopsWithoutPlatform.isEmpty()) {
CompanyOverviewVO.PlatformSummary otherSummary = calculateOtherPlatformSummary(
shopsWithoutPlatform, ordersByShop, promotionFeesByShop, brushOrdersByShop,
targetsByShop, stat, taxRate);
targetsByShop, stat, taxRate, gmvMaps);
if (otherSummary.getOrderCount() > 0) {
platformSummaries.add(otherSummary);
}
@@ -1301,9 +1329,13 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
BigDecimal totalRefundAmount = BigDecimal.ZERO;
BigDecimal totalPromotionFee = BigDecimal.ZERO;
BigDecimal totalBrushFee = BigDecimal.ZERO;
BigDecimal totalGmv = BigDecimal.ZERO;
BigDecimal totalGrossProfit = BigDecimal.ZERO;
for (CompanyOverviewVO.PlatformSummary p : platforms) {
totalSalesAmount = totalSalesAmount.add(p.getSalesAmount() != null ? p.getSalesAmount() : BigDecimal.ZERO);
totalGmv = totalGmv.add(p.getGmv() != null ? p.getGmv() : BigDecimal.ZERO);
totalGrossProfit = totalGrossProfit.add(p.getGrossProfit() != null ? p.getGrossProfit() : BigDecimal.ZERO);
totalOrderCount += p.getOrderCount() != null ? p.getOrderCount() : 0;
totalTargetAmount = totalTargetAmount.add(p.getTargetAmount() != null ? p.getTargetAmount() : BigDecimal.ZERO);
totalTargetOrderCount += p.getTargetOrderCount() != null ? p.getTargetOrderCount() : 0;
@@ -1341,6 +1373,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
total.setPlatformId(0L);
total.setPlatformName("合计");
total.setSalesAmount(totalSalesAmount);
total.setGmv(totalGmv);
total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP));
total.setOrderCount(totalOrderCount);
total.setAverageOrderValue(avgOrderValue);
total.setTargetAmount(totalTargetAmount);
@@ -1350,7 +1384,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
total.setProductCost(totalProductCost);
total.setShippingCost(totalShippingCost);
total.setOtherCost(totalOtherCost);
total.setTotalCost(totalCost);
total.setOrderCost(totalCost);
total.setRefundAmount(totalRefundAmount);
total.setTotalPromotionFee(totalPromotionFee);
total.setBrushFee(totalBrushFee);
@@ -1372,7 +1406,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
Map<Long, List<BrushOrderPO>> brushOrdersByShop,
Map<Long, List<ShopMonthlyTargetPO>> targetsByShop,
OrderStatusStatSets stat,
BigDecimal taxRate) {
BigDecimal taxRate,
GmvDimensionMaps gmvMaps) {
BigDecimal totalSalesAmount = BigDecimal.ZERO;
int totalOrderCount = 0;
@@ -1384,6 +1419,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
BigDecimal totalBrushFee = BigDecimal.ZERO;
BigDecimal totalTargetAmount = BigDecimal.ZERO;
int totalTargetOrderCount = 0;
BigDecimal totalGmv = BigDecimal.ZERO;
for (ShopPO shop : shops) {
List<OrderPO> shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>());
@@ -1436,6 +1472,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
.mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0)
.sum();
totalTargetOrderCount += shopTargetOrderCount;
totalGmv = totalGmv.add(gmvMaps.byShop().getOrDefault(shop.getId(), BigDecimal.ZERO));
}
BigDecimal averageOrderValue = totalOrderCount > 0
@@ -1468,12 +1505,15 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
summary.setTargetAmount(totalTargetAmount);
summary.setSalesAmountAchievementRate(salesAchievementRate);
summary.setSalesAmount(totalSalesAmount);
summary.setGmv(totalGmv);
summary.setGrossProfit(totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount)
.setScale(2, RoundingMode.HALF_UP));
summary.setOrderCount(totalOrderCount);
summary.setAverageOrderValue(averageOrderValue);
summary.setProductCost(totalProductCost);
summary.setShippingCost(totalShippingCost);
summary.setOtherCost(totalOtherCost);
summary.setTotalCost(totalCost);
summary.setOrderCost(totalCost);
summary.setRefundAmount(totalRefundAmount);
summary.setTotalPromotionFee(totalPromotionFee);
summary.setBrushFee(totalBrushFee);
@@ -1571,11 +1611,12 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
BigDecimal saved = this.taxRate;
try {
this.taxRate = taxRate != null ? taxRate : DEFAULT_TAX_RATE;
GmvDimensionMaps gmvMaps = loadGmvDimensionMaps(companyId, shops, startDate, endDate);
CompanyOverviewVO.WorkbenchTableBundle bundle = new CompanyOverviewVO.WorkbenchTableBundle();
bundle.setShopTable(calculateShopSummary(shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate));
bundle.setPlatformTable(calculatePlatformSummary(shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate));
bundle.setCategoryTable(calculateCategorySummary(orders, promotionFees, brushOrders, stat, companyId, startDate, endDate));
bundle.setProductTable(calculateProductSummaryAsCategory(orders, promotionFees, brushOrders, stat, companyId, startDate, endDate));
bundle.setShopTable(calculateShopSummary(shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps));
bundle.setPlatformTable(calculatePlatformSummary(shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps));
bundle.setCategoryTable(calculateCategorySummary(orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps));
bundle.setProductTable(calculateProductSummaryAsCategory(orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps));
return bundle;
} finally {
this.taxRate = saved;
@@ -1590,7 +1631,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
private CompanyOverviewVO.CategoryOverview calculateProductSummaryAsCategory(
List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, OrderStatusStatSets stat, Long companyId,
LocalDate startDate, LocalDate endDate) {
LocalDate startDate, LocalDate endDate, GmvDimensionMaps gmvMaps) {
Map<Long, Long> specIdToProductId = orderSpecIdToProductIdMap(orders);
List<Long> productIds = specIdToProductId.values().stream().filter(Objects::nonNull).distinct()
@@ -1750,12 +1791,15 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
summary.setCategoryId(productId == -1L ? null : productId);
summary.setCategoryName(productName);
summary.setSalesAmount(salesAmount);
summary.setGmv(gmvMaps.byProductKey().getOrDefault(productId, BigDecimal.ZERO));
summary.setGrossProfit(salesAmount.subtract(totalCost).subtract(refundAmount)
.setScale(2, RoundingMode.HALF_UP));
summary.setOrderCount(orderCount);
summary.setAverageOrderValue(averageOrderValue);
summary.setProductCost(productCost);
summary.setShippingCost(shippingCost);
summary.setOtherCost(otherCost);
summary.setTotalCost(totalCost);
summary.setOrderCost(totalCost);
summary.setRefundAmount(refundAmount);
summary.setTotalPromotionFee(totalPromotionFee);
summary.setBrushFee(totalBrushFee);
@@ -1774,5 +1818,548 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
overview.setCategories(summaries);
return overview;
}
@Override
public CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg(
BigDecimal taxRate,
Long companyId,
List<ShopPO> shops,
List<OrderStatAggMapper.ShopProductRow> orderRows,
List<OrderStatAggMapper.PromotionRow> promotionRows,
List<OrderStatAggMapper.BrushRow> brushRows,
LocalDate startDate,
LocalDate endDate) {
synchronized (this) {
BigDecimal saved = this.taxRate;
try {
this.taxRate = taxRate != null ? taxRate : DEFAULT_TAX_RATE;
return buildWorkbenchTablesFromAggInternal(companyId, shops, orderRows, promotionRows, brushRows, startDate, endDate);
} finally {
this.taxRate = saved;
}
}
}
/** SQL 聚合行 → 四表(推广/刷单分摊规则与明细版一致) */
private CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchTablesFromAggInternal(
Long companyId,
List<ShopPO> shops,
List<OrderStatAggMapper.ShopProductRow> orderRows,
List<OrderStatAggMapper.PromotionRow> promotionRows,
List<OrderStatAggMapper.BrushRow> brushRows,
LocalDate startDate,
LocalDate endDate) {
Map<Long, AggMetrics> byShop = new HashMap<>();
Map<Long, AggMetrics> byCategory = new HashMap<>();
Map<Long, AggMetrics> byProduct = new HashMap<>();
Map<Long, Map<Long, BigDecimal>> categorySalesByShop = new HashMap<>();
Map<Long, Map<Long, BigDecimal>> productSalesByShop = new HashMap<>();
Map<Long, Long> productCategoryMap = new HashMap<>();
for (OrderStatAggMapper.ShopProductRow row : orderRows) {
long shopId = row.getShopId() != null ? row.getShopId() : 0L;
long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L;
long categoryKey = productId <= 0 ? -1L
: (row.getCategoryId() == null || row.getCategoryId() == 0 ? 0L : row.getCategoryId());
if (productId > 0) {
productCategoryMap.put(productId, categoryKey <= 0 ? null : categoryKey);
}
mergeAgg(byShop, shopId, row);
mergeAgg(byCategory, categoryKey, row);
mergeAgg(byProduct, productId, row);
BigDecimal sales = nz(row.getSalesAmount());
categorySalesByShop.computeIfAbsent(categoryKey, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add);
productSalesByShop.computeIfAbsent(productId, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add);
}
Map<Long, BigDecimal> promoByShop = new HashMap<>();
Map<Long, BigDecimal> directPromoByProduct = new HashMap<>();
Map<Long, BigDecimal> directPromoByCategory = new HashMap<>();
BigDecimal ratioPool = BigDecimal.ZERO;
for (OrderStatAggMapper.PromotionRow fee : promotionRows) {
BigDecimal amt = nz(fee.getFeeAmount());
promoByShop.merge(fee.getShopId(), amt, BigDecimal::add);
if (fee.getProductId() != null) {
directPromoByProduct.merge(fee.getProductId(), amt, BigDecimal::add);
} else if (fee.getCategoryId() != null) {
directPromoByCategory.merge(fee.getCategoryId(), amt, BigDecimal::add);
} else {
ratioPool = ratioPool.add(amt);
}
}
Map<Long, BigDecimal> brushByShop = new HashMap<>();
for (OrderStatAggMapper.BrushRow b : brushRows) {
brushByShop.merge(b.getShopId(), nz(b.getBrushAmount()), BigDecimal::add);
}
BigDecimal totalSalesPool = orderRows.stream().map(r -> nz(r.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
Map<Long, String> platformNames = loadPlatformNameMap(companyId);
Map<Long, List<ShopMonthlyTargetPO>> targetsByShop = loadTargetsByShop(companyId, startDate, endDate);
CompanyOverviewVO.WorkbenchTableBundle bundle = new CompanyOverviewVO.WorkbenchTableBundle();
bundle.setShopTable(buildShopOverviewFromAgg(shops, byShop, promoByShop, brushByShop, targetsByShop, platformNames));
bundle.setPlatformTable(buildPlatformOverviewFromAgg(shops, byShop, promoByShop, brushByShop, targetsByShop, platformNames));
bundle.setCategoryTable(buildCategoryOverviewFromAgg(byCategory, categorySalesByShop, brushByShop,
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId));
bundle.setProductTable(buildProductOverviewFromAgg(byProduct, productSalesByShop, brushByShop,
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId));
return bundle;
}
private CompanyOverviewVO.ShopOverview buildShopOverviewFromAgg(
List<ShopPO> shops, Map<Long, AggMetrics> byShop, Map<Long, BigDecimal> promoByShop,
Map<Long, BigDecimal> brushByShop, Map<Long, List<ShopMonthlyTargetPO>> targetsByShop,
Map<Long, String> platformNames) {
List<CompanyOverviewVO.ShopSummary> list = new ArrayList<>();
for (ShopPO shop : shops) {
AggMetrics m = byShop.getOrDefault(shop.getId(), AggMetrics.EMPTY);
list.add(toShopSummaryFromAgg(shop, m, promoByShop.getOrDefault(shop.getId(), BigDecimal.ZERO),
brushByShop.getOrDefault(shop.getId(), BigDecimal.ZERO),
targetsByShop.getOrDefault(shop.getId(), List.of()), platformNames));
}
list.sort(Comparator.comparing(CompanyOverviewVO.ShopSummary::getSalesAmount,
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
CompanyOverviewVO.ShopOverview o = new CompanyOverviewVO.ShopOverview();
o.setShops(list);
o.setTotal(computeShopTotal(list));
return o;
}
private CompanyOverviewVO.PlatformOverview buildPlatformOverviewFromAgg(
List<ShopPO> shops, Map<Long, AggMetrics> byShop, Map<Long, BigDecimal> promoByShop,
Map<Long, BigDecimal> brushByShop, Map<Long, List<ShopMonthlyTargetPO>> targetsByShop,
Map<Long, String> platformNames) {
Map<Long, List<ShopPO>> byPlatform = shops.stream().filter(s -> s.getPlatformId() != null)
.collect(Collectors.groupingBy(ShopPO::getPlatformId));
List<CompanyOverviewVO.PlatformSummary> list = new ArrayList<>();
for (Map.Entry<Long, List<ShopPO>> e : byPlatform.entrySet()) {
list.add(rollupPlatformFromAgg(e.getKey(), platformNames.getOrDefault(e.getKey(), "未知平台"),
e.getValue(), byShop, promoByShop, brushByShop, targetsByShop));
}
list.sort(Comparator.comparing(CompanyOverviewVO.PlatformSummary::getSalesAmount,
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
CompanyOverviewVO.PlatformOverview o = new CompanyOverviewVO.PlatformOverview();
o.setPlatforms(list);
o.setTotal(computePlatformTotal(list));
return o;
}
private CompanyOverviewVO.CategoryOverview buildCategoryOverviewFromAgg(
Map<Long, AggMetrics> byCategory, Map<Long, Map<Long, BigDecimal>> categorySalesByShop,
Map<Long, BigDecimal> brushByShop, Map<Long, BigDecimal> directPromoByProduct,
Map<Long, BigDecimal> directPromoByCategory, BigDecimal ratioPool, BigDecimal totalSalesPool,
Map<Long, Long> productCategoryMap, Long companyId) {
Map<Long, String> categoryNames = loadCategoryNameMap(companyId);
Map<Long, BigDecimal> salesByCategory = byCategory.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().sales));
List<CompanyOverviewVO.CategorySummary> list = new ArrayList<>();
for (Map.Entry<Long, AggMetrics> e : byCategory.entrySet()) {
Long key = e.getKey();
AggMetrics m = e.getValue();
BigDecimal promo = resolveCategoryPromo(key, m.sales, salesByCategory, productCategoryMap,
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool);
BigDecimal brush = allocBrushShare(categorySalesByShop.get(key), brushByShop);
list.add(toCategorySummaryFromAgg(key, categoryAggName(key, categoryNames), m, promo, brush));
}
list.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount,
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
CompanyOverviewVO.CategoryOverview o = new CompanyOverviewVO.CategoryOverview();
o.setCategories(list);
o.setTotal(computeCategoryTotal(list));
return o;
}
private CompanyOverviewVO.CategoryOverview buildProductOverviewFromAgg(
Map<Long, AggMetrics> byProduct, Map<Long, Map<Long, BigDecimal>> productSalesByShop,
Map<Long, BigDecimal> brushByShop, Map<Long, BigDecimal> directPromoByProduct,
Map<Long, BigDecimal> directPromoByCategory, BigDecimal ratioPool, BigDecimal totalSalesPool,
Map<Long, Long> productCategoryMap, Long companyId) {
Map<Long, BigDecimal> salesByCategory = new HashMap<>();
for (Map.Entry<Long, AggMetrics> e : byProduct.entrySet()) {
if (e.getKey() > 0) {
Long cid = productCategoryMap.get(e.getKey());
if (cid != null && cid > 0) {
salesByCategory.merge(cid, e.getValue().sales, BigDecimal::add);
}
}
}
Map<Long, String> productNames = loadProductNameMap(byProduct.keySet());
List<CompanyOverviewVO.CategorySummary> list = new ArrayList<>();
for (Map.Entry<Long, AggMetrics> e : byProduct.entrySet()) {
Long pid = e.getKey();
AggMetrics m = e.getValue();
BigDecimal promo = resolveProductPromo(pid, m.sales, productCategoryMap, salesByCategory,
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool);
BigDecimal brush = allocBrushShare(productSalesByShop.get(pid), brushByShop);
String name = pid <= 0 ? "未匹配商品" : productNames.getOrDefault(pid, "商品" + pid);
list.add(toCategorySummaryFromAgg(pid, name, m, promo, brush));
}
list.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount,
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
CompanyOverviewVO.CategoryOverview o = new CompanyOverviewVO.CategoryOverview();
o.setCategories(list);
o.setTotal(computeCategoryTotal(list));
return o;
}
private CompanyOverviewVO.PlatformSummary rollupPlatformFromAgg(
Long platformId, String platformName, List<ShopPO> platformShops,
Map<Long, AggMetrics> byShop, Map<Long, BigDecimal> promoByShop, Map<Long, BigDecimal> brushByShop,
Map<Long, List<ShopMonthlyTargetPO>> targetsByShop) {
AggMetrics merged = AggMetrics.EMPTY;
BigDecimal promo = BigDecimal.ZERO;
BigDecimal brush = BigDecimal.ZERO;
BigDecimal targetAmt = BigDecimal.ZERO;
int targetOrders = 0;
for (ShopPO shop : platformShops) {
merged = merged.merge(byShop.getOrDefault(shop.getId(), AggMetrics.EMPTY));
promo = promo.add(promoByShop.getOrDefault(shop.getId(), BigDecimal.ZERO));
brush = brush.add(brushByShop.getOrDefault(shop.getId(), BigDecimal.ZERO));
for (ShopMonthlyTargetPO t : targetsByShop.getOrDefault(shop.getId(), List.of())) {
targetAmt = targetAmt.add(nz(t.getTargetAmount()));
targetOrders += t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0;
}
}
return toPlatformSummaryFromAgg(platformId, platformName, merged, promo, brush, targetAmt, targetOrders);
}
private CompanyOverviewVO.ShopSummary toShopSummaryFromAgg(
ShopPO shop, AggMetrics m, BigDecimal promo, BigDecimal brush,
List<ShopMonthlyTargetPO> targets, Map<Long, String> platformNames) {
BigDecimal targetAmt = targets.stream().map(t -> nz(t.getTargetAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
int targetOrders = targets.stream().mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0).sum();
CompanyOverviewVO.ShopSummary s = new CompanyOverviewVO.ShopSummary();
s.setShopId(shop.getId());
s.setShopName(shop.getName());
s.setPlatform(shop.getPlatformId() != null ? platformNames.get(shop.getPlatformId()) : null);
fillSummaryMetrics(s, m, promo, brush, targetAmt, targetOrders);
return s;
}
private CompanyOverviewVO.PlatformSummary toPlatformSummaryFromAgg(
Long platformId, String name, AggMetrics m, BigDecimal promo, BigDecimal brush,
BigDecimal targetAmt, int targetOrders) {
CompanyOverviewVO.PlatformSummary s = new CompanyOverviewVO.PlatformSummary();
s.setPlatformId(platformId > 0 ? platformId : null);
s.setPlatformName(name);
fillPlatformLikeMetrics(s, m, promo, brush, targetAmt, targetOrders);
return s;
}
private CompanyOverviewVO.CategorySummary toCategorySummaryFromAgg(
Long key, String name, AggMetrics m, BigDecimal promo, BigDecimal brush) {
CompanyOverviewVO.CategorySummary s = new CompanyOverviewVO.CategorySummary();
s.setCategoryId(key != null && key > 0 ? key : null);
s.setCategoryName(name);
fillCategoryLikeMetrics(s, m, promo, brush);
return s;
}
private void fillSummaryMetrics(CompanyOverviewVO.ShopSummary s, AggMetrics m, BigDecimal promo,
BigDecimal brush, BigDecimal targetAmt, int targetOrders) {
s.setSalesAmount(m.sales);
s.setGmv(m.gmv);
s.setOrderCount(m.orderCount);
s.setAverageOrderValue(aov(m.sales, m.orderCount));
s.setProductCost(m.productCost);
s.setShippingCost(m.freightCost);
s.setOtherCost(m.otherCost);
s.setOrderCost(m.orderCost());
s.setRefundAmount(m.refund);
s.setTotalPromotionFee(promo);
s.setBrushFee(brush);
s.setFeeRatio(safeDivide(promo, m.sales));
s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP));
BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush);
s.setTotalProfitBeforeTax(pbt);
s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund));
s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP));
s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo));
s.setTargetAmount(targetAmt);
s.setTargetOrderCount(targetOrders);
s.setSalesAmountAchievementRate(achievementRate(m.sales, targetAmt));
s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.orderCount), BigDecimal.valueOf(targetOrders)));
}
/** 品类/商品/平台汇总行:填充 GMV、毛利与净利字段 */
private void fillCategoryLikeMetrics(CompanyOverviewVO.CategorySummary s, AggMetrics m,
BigDecimal promo, BigDecimal brush) {
s.setSalesAmount(m.sales);
s.setGmv(m.gmv);
s.setOrderCount(m.orderCount);
s.setAverageOrderValue(aov(m.sales, m.orderCount));
s.setProductCost(m.productCost);
s.setShippingCost(m.freightCost);
s.setOtherCost(m.otherCost);
s.setOrderCost(m.orderCost());
s.setRefundAmount(m.refund);
s.setTotalPromotionFee(promo);
s.setBrushFee(brush);
s.setFeeRatio(safeDivide(promo, m.sales));
s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP));
BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush);
s.setTotalProfitBeforeTax(pbt);
s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund));
s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP));
s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo));
}
private void fillPlatformLikeMetrics(CompanyOverviewVO.PlatformSummary s, AggMetrics m,
BigDecimal promo, BigDecimal brush,
BigDecimal targetAmt, int targetOrders) {
s.setSalesAmount(m.sales);
s.setGmv(m.gmv);
s.setOrderCount(m.orderCount);
s.setAverageOrderValue(aov(m.sales, m.orderCount));
s.setProductCost(m.productCost);
s.setShippingCost(m.freightCost);
s.setOtherCost(m.otherCost);
s.setOrderCost(m.orderCost());
s.setRefundAmount(m.refund);
s.setTotalPromotionFee(promo);
s.setBrushFee(brush);
s.setFeeRatio(safeDivide(promo.add(brush), m.sales));
s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP));
BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush);
s.setTotalProfitBeforeTax(pbt);
s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund));
s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP));
s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo));
s.setTargetAmount(targetAmt);
s.setTargetOrderCount(targetOrders);
s.setSalesAmountAchievementRate(achievementRate(m.sales, targetAmt));
s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.orderCount), BigDecimal.valueOf(targetOrders)));
}
private static void mergeAgg(Map<Long, AggMetrics> map, long key, OrderStatAggMapper.ShopProductRow row) {
map.merge(key, AggMetrics.from(row), AggMetrics::merge);
}
private static BigDecimal resolveCategoryPromo(Long categoryKey, BigDecimal sales,
Map<Long, BigDecimal> salesByCategory, Map<Long, Long> productCategoryMap,
Map<Long, BigDecimal> directByProduct, Map<Long, BigDecimal> directByCategory,
BigDecimal ratioPool, BigDecimal totalPool) {
BigDecimal direct = BigDecimal.ZERO;
for (Map.Entry<Long, Long> e : productCategoryMap.entrySet()) {
if (matchesCategory(categoryKey, e.getValue())) {
direct = direct.add(directByProduct.getOrDefault(e.getKey(), BigDecimal.ZERO));
}
}
if (categoryKey != null && categoryKey > 0) {
direct = direct.add(directByCategory.getOrDefault(categoryKey, BigDecimal.ZERO));
}
return addPoolShare(direct, sales, ratioPool, totalPool);
}
private static BigDecimal resolveProductPromo(Long productId, BigDecimal sales,
Map<Long, Long> productCategoryMap, Map<Long, BigDecimal> salesByCategory,
Map<Long, BigDecimal> directByProduct, Map<Long, BigDecimal> directByCategory,
BigDecimal ratioPool, BigDecimal totalPool) {
if (productId == null || productId <= 0) {
return addPoolShare(BigDecimal.ZERO, sales, ratioPool, totalPool);
}
BigDecimal direct = directByProduct.getOrDefault(productId, BigDecimal.ZERO);
Long cid = productCategoryMap.get(productId);
if (cid != null && cid > 0) {
BigDecimal catSales = salesByCategory.getOrDefault(cid, BigDecimal.ZERO);
if (catSales.compareTo(BigDecimal.ZERO) > 0) {
direct = direct.add(directByCategory.getOrDefault(cid, BigDecimal.ZERO)
.multiply(sales).divide(catSales, 4, RoundingMode.HALF_UP));
}
}
return addPoolShare(direct, sales, ratioPool, totalPool);
}
private static boolean matchesCategory(Long categoryKey, Long productCat) {
if (categoryKey == -1L) {
return productCat == null;
}
return Objects.equals(categoryKey, productCat);
}
private static BigDecimal addPoolShare(BigDecimal base, BigDecimal sales, BigDecimal pool, BigDecimal total) {
if (pool.compareTo(BigDecimal.ZERO) > 0 && total.compareTo(BigDecimal.ZERO) > 0) {
return base.add(pool.multiply(sales).divide(total, 4, RoundingMode.HALF_UP));
}
return base;
}
private static BigDecimal allocBrushShare(Map<Long, BigDecimal> salesByShop, Map<Long, BigDecimal> brushByShop) {
if (salesByShop == null || salesByShop.isEmpty()) {
return BigDecimal.ZERO;
}
BigDecimal total = salesByShop.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
if (total.compareTo(BigDecimal.ZERO) <= 0) {
return BigDecimal.ZERO;
}
BigDecimal brush = BigDecimal.ZERO;
for (Map.Entry<Long, BigDecimal> e : salesByShop.entrySet()) {
brush = brush.add(brushByShop.getOrDefault(e.getKey(), BigDecimal.ZERO)
.multiply(e.getValue()).divide(total, 6, RoundingMode.HALF_UP));
}
return brush;
}
private Map<Long, String> loadPlatformNameMap(Long companyId) {
return platformMapper.selectList(new LambdaQueryWrapper<PlatformPO>().eq(PlatformPO::getCompanyId, companyId))
.stream().collect(Collectors.toMap(PlatformPO::getId, PlatformPO::getPlatformName, (a, b) -> a));
}
private Map<Long, String> loadCategoryNameMap(Long companyId) {
return categoryService.list(new LambdaQueryWrapper<CategoryPO>().eq(CategoryPO::getCompanyId, companyId))
.stream().collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName, (a, b) -> a));
}
private Map<Long, String> loadProductNameMap(java.util.Set<Long> productKeys) {
List<Long> ids = productKeys.stream().filter(id -> id != null && id > 0).distinct().toList();
if (ids.isEmpty()) {
return Map.of();
}
return productMapper.selectList(new LambdaQueryWrapper<ProductPO>().in(ProductPO::getId, ids))
.stream().collect(Collectors.toMap(ProductPO::getId, ProductPO::getName, (a, b) -> a));
}
private Map<Long, List<ShopMonthlyTargetPO>> loadTargetsByShop(Long companyId, LocalDate start, LocalDate end) {
List<LocalDate> months = new ArrayList<>();
LocalDate cur = start.withDayOfMonth(1);
LocalDate endMonth = end.withDayOfMonth(1);
while (!cur.isAfter(endMonth)) {
months.add(cur);
cur = cur.plusMonths(1);
}
if (months.isEmpty()) {
return Map.of();
}
LambdaQueryWrapper<ShopMonthlyTargetPO> w = new LambdaQueryWrapper<>();
w.eq(ShopMonthlyTargetPO::getCompanyId, companyId).in(ShopMonthlyTargetPO::getTargetMonth, months);
return shopMonthlyTargetMapper.selectList(w).stream()
.collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId));
}
private static String categoryAggName(Long key, Map<Long, String> names) {
if (key == null || key == -1L) {
return "其他品类";
}
if (key == 0L) {
return "未分类";
}
return names.getOrDefault(key, "类目" + key);
}
private static BigDecimal aov(BigDecimal sales, int count) {
return count > 0 ? sales.divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
}
private static BigDecimal safeDivide(BigDecimal a, BigDecimal b) {
return b.compareTo(BigDecimal.ZERO) > 0 ? a.divide(b, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
}
private static BigDecimal achievementRate(BigDecimal actual, BigDecimal target) {
if (target.compareTo(BigDecimal.ZERO) > 0) {
return actual.divide(target, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
}
return actual.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
}
private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
}
/** 全状态 GMV 按店铺/品类/商品维度预聚合(明细汇总路径用) */
private record GmvDimensionMaps(
Map<Long, BigDecimal> byShop,
Map<Long, BigDecimal> byCategoryKey,
Map<Long, BigDecimal> byProductKey) {
}
private GmvDimensionMaps loadGmvDimensionMaps(Long companyId, List<ShopPO> shops,
LocalDate startDate, LocalDate endDate) {
List<Long> shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).distinct().toList();
if (shopIds.isEmpty()) {
return new GmvDimensionMaps(Map.of(), Map.of(), Map.of());
}
LambdaQueryWrapper<OrderPO> w = new LambdaQueryWrapper<>();
w.eq(OrderPO::getCompanyId, companyId)
.in(OrderPO::getShopId, shopIds)
.ge(OrderPO::getOrderTime, startDate.atStartOfDay())
.le(OrderPO::getOrderTime, endDate.atTime(23, 59, 59));
List<OrderPO> allOrders = orderMapper.selectList(w);
Map<Long, Long> specToProduct = orderSpecIdToProductIdMap(allOrders);
Map<Long, Long> productCategoryMap = new HashMap<>();
List<Long> productIds = specToProduct.values().stream().filter(Objects::nonNull).distinct().toList();
if (!productIds.isEmpty()) {
productMapper.selectList(new LambdaQueryWrapper<ProductPO>().in(ProductPO::getId, productIds))
.forEach(p -> productCategoryMap.put(p.getId(), p.getCategoryId()));
}
Map<Long, BigDecimal> byShop = new HashMap<>();
Map<Long, BigDecimal> byCategoryKey = new HashMap<>();
Map<Long, BigDecimal> byProductKey = new HashMap<>();
for (OrderPO o : allOrders) {
BigDecimal amt = nz(o.getReceivedAmount());
if (o.getShopId() != null) {
byShop.merge(o.getShopId(), amt, BigDecimal::add);
}
long productId = o.getProductSpecId() != null
? specToProduct.getOrDefault(o.getProductSpecId(), -1L) : -1L;
byProductKey.merge(productId, amt, BigDecimal::add);
long categoryKey;
if (productId <= 0) {
categoryKey = -1L;
} else {
Long cid = productCategoryMap.get(productId);
categoryKey = cid == null || cid == 0 ? 0L : cid;
}
byCategoryKey.merge(categoryKey, amt, BigDecimal::add);
}
return new GmvDimensionMaps(byShop, byCategoryKey, byProductKey);
}
/** SQL 聚合指标桶 */
private static final class AggMetrics {
static final AggMetrics EMPTY = new AggMetrics();
BigDecimal sales = BigDecimal.ZERO;
/** 全订单状态 GMV(商家实收合计) */
BigDecimal gmv = BigDecimal.ZERO;
int orderCount;
BigDecimal refund = BigDecimal.ZERO;
BigDecimal productCost = BigDecimal.ZERO;
BigDecimal freightCost = BigDecimal.ZERO;
BigDecimal otherCost = BigDecimal.ZERO;
/** 订单成本合计(商品+运费+其他,不含推广/刷单) */
BigDecimal orderCost() {
return productCost.add(freightCost).add(otherCost);
}
/** 订单维度毛利:未扣推广/刷单/税 */
BigDecimal grossProfit() {
return sales.subtract(orderCost()).subtract(refund);
}
static AggMetrics from(OrderStatAggMapper.ShopProductRow row) {
AggMetrics a = new AggMetrics();
a.sales = nz(row.getSalesAmount());
a.gmv = nz(row.getGmvAllStatus());
a.orderCount = row.getOrderCount() != null ? row.getOrderCount().intValue() : 0;
a.refund = nz(row.getRefundAmount());
a.productCost = nz(row.getProductCost());
a.freightCost = nz(row.getFreightCost());
a.otherCost = nz(row.getOtherCost());
return a;
}
AggMetrics merge(AggMetrics o) {
AggMetrics a = new AggMetrics();
a.sales = sales.add(o.sales);
a.gmv = gmv.add(o.gmv);
a.orderCount = orderCount + o.orderCount;
a.refund = refund.add(o.refund);
a.productCost = productCost.add(o.productCost);
a.freightCost = freightCost.add(o.freightCost);
a.otherCost = otherCost.add(o.otherCost);
return a;
}
}
}
@@ -175,9 +175,9 @@ public class ExportServiceImpl implements ExportService {
String taxLabel = (taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP)).toPlainString() + "%税额";
String[] headers = {
firstColumnHeader, "目标单量", "单量达成率(%)", "目标额", "销售达成率(%)",
"实际销售额", "单量", "客单价",
"商品成本", "运费", "其他成本", "总成本", "退款金额", "推广费", "刷单费用", "费比",
"税前盈亏", taxLabel, "ROI", "税后盈亏"
"实际销售额", "GMV", "单量", "客单价",
"商品成本", "运费", "其他成本", "订单成本", "退款金额", "推广费", "刷单费用", "费比",
"毛利", "税前净利", taxLabel, "ROI", "税后净利"
};
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1));
CellStyle headerStyle = createHeaderStyle(wb);
@@ -214,17 +214,19 @@ public class ExportServiceImpl implements ExportService {
setCell(row, 3, objToDouble(data.get("targetAmount")), style);
setCell(row, 4, objToPct(data.get("salesAchievementRate")), style);
setCell(row, 5, objToDouble(data.get("salesAmount")), style);
setCell(row, 6, objToDouble(data.get("orderCount")), style);
setCell(row, 7, objToDouble(data.get("avgOrderValue")), style);
setCell(row, 8, objToDouble(data.get("productCost")), style);
setCell(row, 9, objToDouble(data.get("shippingCost")), style);
setCell(row, 10, objToDouble(data.get("otherCost")), style);
setCell(row, 11, objToDouble(data.get("totalCost")), style);
setCell(row, 12, objToDouble(data.get("refundAmount")), style);
setCell(row, 13, objToDouble(data.get("totalPromotionFee")), style);
setCell(row, 14, objToDouble(data.get("brushFee")), style);
setCell(row, 15, objToDouble(data.get("feeRatio")), style);
setCell(row, 16, objToDouble(data.get("totalProfitBeforeTax")), style);
setCell(row, 6, objToDouble(data.get("gmv")), style);
setCell(row, 7, objToDouble(data.get("orderCount")), style);
setCell(row, 8, objToDouble(data.get("avgOrderValue")), style);
setCell(row, 9, objToDouble(data.get("productCost")), style);
setCell(row, 10, objToDouble(data.get("shippingCost")), style);
setCell(row, 11, objToDouble(data.get("otherCost")), style);
setCell(row, 12, objToDouble(data.get("orderCost")), style);
setCell(row, 13, objToDouble(data.get("refundAmount")), style);
setCell(row, 14, objToDouble(data.get("totalPromotionFee")), style);
setCell(row, 15, objToDouble(data.get("brushFee")), style);
setCell(row, 16, objToDouble(data.get("feeRatio")), style);
setCell(row, 17, objToDouble(data.get("grossProfit")), style);
setCell(row, 18, objToDouble(data.get("totalProfitBeforeTax")), style);
BigDecimal salesTax = salesTaxOnNetForExport(
mapToBigDecimal(data.get("salesAmount")),
mapToBigDecimal(data.get("refundAmount")),
@@ -232,9 +234,9 @@ public class ExportServiceImpl implements ExportService {
BigDecimal profitAfterTax = mapToBigDecimal(data.get("totalProfitBeforeTax"))
.subtract(salesTax)
.setScale(2, RoundingMode.HALF_UP);
setCell(row, 17, salesTax.doubleValue(), style);
setCell(row, 18, objToDouble(data.get("roi")), style);
setCell(row, 19, profitAfterTax.doubleValue(), style);
setCell(row, 19, salesTax.doubleValue(), style);
setCell(row, 20, objToDouble(data.get("roi")), style);
setCell(row, 21, profitAfterTax.doubleValue(), style);
}
private static BigDecimal mapToBigDecimal(Object val) {
@@ -261,16 +263,18 @@ public class ExportServiceImpl implements ExportService {
data.put("targetAmount", s.getTargetAmount());
data.put("salesAchievementRate", s.getSalesAmountAchievementRate());
data.put("salesAmount", s.getSalesAmount());
data.put("gmv", s.getGmv());
data.put("orderCount", s.getOrderCount());
data.put("avgOrderValue", s.getAverageOrderValue());
data.put("productCost", s.getProductCost());
data.put("shippingCost", s.getShippingCost());
data.put("otherCost", s.getOtherCost());
data.put("totalCost", s.getTotalCost());
data.put("orderCost", s.getOrderCost());
data.put("refundAmount", s.getRefundAmount());
data.put("totalPromotionFee", s.getTotalPromotionFee());
data.put("brushFee", s.getBrushFee());
data.put("feeRatio", s.getFeeRatio());
data.put("grossProfit", s.getGrossProfit());
data.put("totalProfitBeforeTax", s.getTotalProfitBeforeTax());
data.put("salesTaxAmount", s.getSalesTaxAmount());
data.put("roi", s.getRoi());
@@ -351,7 +355,7 @@ public class ExportServiceImpl implements ExportService {
total.setProductCost(totalProductCost);
total.setShippingCost(totalShippingCost);
total.setOtherCost(totalOtherCost);
total.setTotalCost(totalCost);
total.setOrderCost(totalCost);
total.setRefundAmount(totalRefund);
total.setTotalPromotionFee(totalPromoFee);
total.setBrushFee(totalBrushFee);
@@ -371,16 +375,18 @@ public class ExportServiceImpl implements ExportService {
data.put("targetAmount", s.getTargetAmount());
data.put("salesAchievementRate", s.getSalesAmountAchievementRate());
data.put("salesAmount", s.getSalesAmount());
data.put("gmv", s.getGmv());
data.put("orderCount", s.getOrderCount());
data.put("avgOrderValue", s.getAverageOrderValue());
data.put("productCost", s.getProductCost());
data.put("shippingCost", s.getShippingCost());
data.put("otherCost", s.getOtherCost());
data.put("totalCost", s.getTotalCost());
data.put("orderCost", s.getOrderCost());
data.put("refundAmount", s.getRefundAmount());
data.put("totalPromotionFee", s.getTotalPromotionFee());
data.put("brushFee", s.getBrushFee());
data.put("feeRatio", s.getFeeRatio());
data.put("grossProfit", s.getGrossProfit());
data.put("totalProfitBeforeTax", s.getTotalProfitBeforeTax());
data.put("salesTaxAmount", s.getSalesTaxAmount());
data.put("roi", s.getRoi());
@@ -449,7 +455,7 @@ public class ExportServiceImpl implements ExportService {
total.setProductCost(totalProductCost);
total.setShippingCost(totalShippingCost);
total.setOtherCost(totalOtherCost);
total.setTotalCost(totalCost);
total.setOrderCost(totalCost);
total.setRefundAmount(totalRefund);
total.setTotalPromotionFee(totalPromoFee);
total.setBrushFee(totalBrushFee);
@@ -602,7 +602,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
summary.setProductCost(productCost);
summary.setShippingCost(shippingCost);
summary.setOtherCost(otherCost);
summary.setTotalCost(productCost.add(shippingCost).add(otherCost));
summary.setOrderCost(productCost.add(shippingCost).add(otherCost));
summary.setRefundAmount(refundAmount);
summary.setTotalPromotionFee(productPromotionFee);
summary.setBrushFee(brushFee);
@@ -675,7 +675,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
total.setProductCost(totalProductCost);
total.setShippingCost(totalShippingCost);
total.setOtherCost(totalOtherCost);
total.setTotalCost(totalCost);
total.setOrderCost(totalCost);
total.setRefundAmount(totalRefund);
total.setTotalPromotionFee(totalPromoFee);
total.setBrushFee(totalBrushFee);
@@ -688,7 +688,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
}
/**
* 计算商品总成本(订单成本)
* 计算商品订单成本(订单维度商品+运费+其他)
*/
private BigDecimal calculateProductTotalCost(List<OrderPO> orders, OrderStatusStatSets stat) {
return orders.stream()
@@ -930,7 +930,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
summary.setProductCost(productCost);
summary.setShippingCost(shippingCost);
summary.setOtherCost(otherCost);
summary.setTotalCost(totalCost);
summary.setOrderCost(totalCost);
summary.setRefundAmount(refundAmount);
summary.setTotalPromotionFee(catPromotionFee);
summary.setBrushFee(catBrushFee);
@@ -1002,7 +1002,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
total.setProductCost(totalProductCost);
total.setShippingCost(totalShippingCost);
total.setOtherCost(totalOtherCost);
total.setTotalCost(totalCost);
total.setOrderCost(totalCost);
total.setRefundAmount(totalRefund);
total.setTotalPromotionFee(totalPromoFee);
total.setBrushFee(totalBrushFee);
@@ -240,10 +240,10 @@ public class ProductOverviewVO {
private BigDecimal otherCost;
/**
* 总成本(商品成本+运费+其他成本)
* 订单成本(商品成本+运费+其他成本,不含推广费、刷单费)
*/
@Schema(description = "总成本(商品成本+运费+其他成本)")
private BigDecimal totalCost;
@Schema(description = "订单成本(商品成本+运费+其他成本,不含推广费、刷单费)")
private BigDecimal orderCost;
/**
* 退款金额
@@ -331,10 +331,10 @@ public class ProductOverviewVO {
private BigDecimal otherCost;
/**
* 总成本(商品成本+运费+其他成本)
* 订单成本(商品成本+运费+其他成本,不含推广费、刷单费)
*/
@Schema(description = "总成本(商品成本+运费+其他成本)")
private BigDecimal totalCost;
@Schema(description = "订单成本(商品成本+运费+其他成本,不含推广费、刷单费)")
private BigDecimal orderCost;
/**
* 退款金额
@@ -213,7 +213,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
.map(stat::receivedForRefund)
.reduce(BigDecimal.ZERO, BigDecimal::add);
// 总成本(商品/运费/其他成本按各维度开关,含数量)
// 订单成本(商品/运费/其他成本按各维度开关,含数量)
BigDecimal totalCostAmount = orders.stream()
.map(stat::totalCostForStats)
.reduce(BigDecimal.ZERO, BigDecimal::add);
@@ -622,7 +622,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
? specPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
// 税前盈亏(与店铺商品对比:销售额 - 总成本 - 退款金额 - 推广费)
// 税前净利(与店铺商品对比:销售额 - 订单成本 - 退款金额 - 推广费)
BigDecimal profitBeforeTax = salesAmount
.subtract(totalCostStat)
.subtract(refundAmount)
@@ -650,7 +650,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
item.setProductCost(productCostTotal);
item.setShippingCost(shippingCostTotal);
item.setOtherCost(otherCostTotal);
item.setTotalCost(totalCostStat);
item.setOrderCost(totalCostStat);
item.setRefundAmount(refundAmount);
item.setPromotionFee(specPromotionFee);
item.setFeeRatio(feeRatio.multiply(new BigDecimal("100"))
@@ -681,8 +681,8 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
total.setOtherCost(specItems.stream()
.map(ProductOverviewVO.SpecSummaryItem::getOtherCost)
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setTotalCost(specItems.stream()
.map(ProductOverviewVO.SpecSummaryItem::getTotalCost)
total.setOrderCost(specItems.stream()
.map(ProductOverviewVO.SpecSummaryItem::getOrderCost)
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setRefundAmount(specItems.stream()
.map(ProductOverviewVO.SpecSummaryItem::getRefundAmount)
@@ -700,7 +700,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
.setScale(2, RoundingMode.HALF_UP));
BigDecimal totalProfitBT = total.getSalesAmount()
.subtract(total.getTotalCost())
.subtract(total.getOrderCost())
.subtract(total.getRefundAmount())
.subtract(total.getPromotionFee());
total.setProfitBeforeTax(totalProfitBT);
@@ -733,7 +733,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
total.setProductCost(BigDecimal.ZERO);
total.setShippingCost(BigDecimal.ZERO);
total.setOtherCost(BigDecimal.ZERO);
total.setTotalCost(BigDecimal.ZERO);
total.setOrderCost(BigDecimal.ZERO);
total.setRefundAmount(BigDecimal.ZERO);
total.setPromotionFee(BigDecimal.ZERO);
total.setFeeRatio(BigDecimal.ZERO);
@@ -126,7 +126,7 @@ public class ShopExportServiceImpl implements ShopExportService {
String taxLabel = (taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP)).toPlainString() + "%税额";
String[] headers = {
"商品", "销售额", "单量", "客单价",
"商品成本", "运费", "其他成本", "总成本", "退款金额", "推广费", "刷单费用",
"商品成本", "运费", "其他成本", "订单成本", "退款金额", "推广费", "刷单费用",
"费比 %", "单品 ROI", "税前盈亏", taxLabel, "税后净利"
};
@@ -177,7 +177,7 @@ public class ShopExportServiceImpl implements ShopExportService {
setCell(row, 4, nvl(p.getProductCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 5, nvl(p.getShippingCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 6, nvl(p.getOtherCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 7, nvl(p.getTotalCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 7, nvl(p.getOrderCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 8, nvl(p.getRefundAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 9, nvl(p.getTotalPromotionFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 10, nvl(p.getBrushFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
@@ -8,6 +8,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
@@ -46,10 +47,12 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
@@ -84,6 +87,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
private final ProductMapper productMapper;
private final CategoryService categoryService;
private final PlatformMapper platformMapper;
private final OrderStatAggMapper orderStatAggMapper;
private final CompanyOverviewService companyOverviewService;
public WorkbenchServiceImpl(CurrentUserContext currentUserContext,
@@ -96,6 +100,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
ProductMapper productMapper,
CategoryService categoryService,
PlatformMapper platformMapper,
OrderStatAggMapper orderStatAggMapper,
CompanyOverviewService companyOverviewService) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
@@ -107,51 +112,42 @@ public class WorkbenchServiceImpl implements WorkbenchService {
this.productMapper = productMapper;
this.categoryService = categoryService;
this.platformMapper = platformMapper;
this.orderStatAggMapper = orderStatAggMapper;
this.companyOverviewService = companyOverviewService;
}
/** 经营概览 Tab:KPI/趋势/饼图 + 底部四表(含环比/同比,不加载多维排行) */
/** 经营概览 Tab:SQL 聚合 KPI/趋势/饼图 + 底部四表 */
@Override
public WorkbenchFinanceSliceVO financeSlice(WorkbenchQueryDTO queryDTO) {
ShopContext ctx = resolveShopContext(queryDTO);
if (ctx.shops().isEmpty()) {
if (ctx.shops().isEmpty() || ctx.stat().isUnionEmpty()) {
return emptyFinanceSlice();
}
ComparePeriodBundle compare = loadComparePeriods(ctx);
CurrentPeriodBundle current = loadCurrentPeriod(ctx);
DimensionAggMaps aggs = aggregateDimensions(current.orders(), ctx.shops(), ctx.shopById(), ctx.stat());
SqlAggBundle agg = loadSqlAgg(ctx);
ComparePeriodBundle compare = loadCompareFromSql(ctx);
Totals cur = totalsFromOrderRows(agg.orderRows(), agg.promoTotal(), agg.brushTotal(), ctx.taxRate());
WorkbenchFinancePanelVO finance = buildFinancePanel(
ctx, current, compare, aggs.platformAgg(), aggs.platformNames());
WorkbenchFinancePanelVO finance = buildFinancePanelFromSql(ctx, cur, compare, agg);
CompanyOverviewVO.WorkbenchTableBundle summaryTables = companyOverviewService.buildWorkbenchSummaryTables(
ctx.taxRate(),
ctx.companyId(),
ctx.shops(),
current.orders(),
current.promotionFees(),
current.brushOrders(),
ctx.stat(),
ctx.range().startDate(),
ctx.range().endDate());
CompanyOverviewVO.WorkbenchTableBundle summaryTables = companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
ctx.taxRate(), ctx.companyId(), ctx.shops(),
agg.orderRows(), agg.promotionRows(), agg.brushRows(),
ctx.range().startDate(), ctx.range().endDate());
return WorkbenchFinanceSliceVO.builder()
.finance(finance)
.summaryTables(summaryTables)
.build();
return WorkbenchFinanceSliceVO.builder().finance(finance).summaryTables(summaryTables).build();
}
/** 多维分析 Tab:仅当前区间四维损益 */
/** 多维分析 Tab:SQL 聚合 + 内存 rollup */
@Override
public WorkbenchMultiAnalysisPanelVO multiAnalysis(WorkbenchQueryDTO queryDTO) {
ShopContext ctx = resolveShopContext(queryDTO);
if (ctx.shops().isEmpty()) {
if (ctx.shops().isEmpty() || ctx.stat().isUnionEmpty()) {
return emptyMultiPanel();
}
CurrentPeriodBundle current = loadCurrentPeriod(ctx);
DimensionAggMaps aggs = aggregateDimensions(current.orders(), ctx.shops(), ctx.shopById(), ctx.stat());
return buildMultiPanel(aggs, current.totals());
SqlAggBundle agg = loadSqlAgg(ctx);
Totals cur = totalsFromOrderRows(agg.orderRows(), agg.promoTotal(), agg.brushTotal(), ctx.taxRate());
return buildMultiPanel(aggregateDimensionsFromSql(agg.orderRows(), ctx), cur);
}
/** 销售额排行 Tab:与多维同源,按销售额降序 */
@@ -169,34 +165,23 @@ public class WorkbenchServiceImpl implements WorkbenchService {
Long companyId = currentUserContext.getCurrentCompanyId();
DateRange range = parseDateRange(queryDTO);
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
List<Long> unionStatusIds = stat.getUnionStatusIds();
if (stat.isUnionEmpty()) {
return WorkbenchPeriodCompareSliceVO.builder()
.startDate(range.startDate()).endDate(range.endDate())
.total(new CompanyOverviewVO.ShopSummary()).build();
}
List<ShopPO> shops = loadFilteredShops(companyId, queryDTO.getPlatformId(), queryDTO.getShopId());
List<Long> shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList();
List<OrderPO> orders = loadOrders(companyId, shopIds, range.startDateTime(), range.endDateTime(), unionStatusIds);
List<PromotionFeePO> promotionFees = loadPromotionFees(companyId, shopIds, range.startDate(), range.endDate());
List<BrushOrderPO> brushOrders = loadBrushOrders(companyId, shopIds, range.startDateTime(), range.endDateTime());
CompanyOverviewVO.WorkbenchTableBundle bundle = companyOverviewService.buildWorkbenchSummaryTables(
taxRate,
companyId,
shops,
orders,
promotionFees,
brushOrders,
stat,
range.startDate(),
range.endDate());
ShopContext ctx = new ShopContext(taxRate, companyId, range, stat, shops,
shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList(),
shops.stream().collect(Collectors.toMap(ShopPO::getId, s -> s, (a, b) -> a)));
SqlAggBundle agg = loadSqlAgg(ctx);
CompanyOverviewVO.WorkbenchTableBundle bundle = companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
taxRate, companyId, shops, agg.orderRows(), agg.promotionRows(), agg.brushRows(),
range.startDate(), range.endDate());
CompanyOverviewVO.ShopSummary total = bundle.getShopTable() != null && bundle.getShopTable().getTotal() != null
? bundle.getShopTable().getTotal()
: new CompanyOverviewVO.ShopSummary();
? bundle.getShopTable().getTotal() : new CompanyOverviewVO.ShopSummary();
return WorkbenchPeriodCompareSliceVO.builder()
.startDate(range.startDate())
.endDate(range.endDate())
.total(total)
.build();
.startDate(range.startDate()).endDate(range.endDate()).total(total).build();
}
private WorkbenchFinanceSliceVO emptyFinanceSlice() {
@@ -239,7 +224,284 @@ public class WorkbenchServiceImpl implements WorkbenchService {
return new ShopContext(taxRate, companyId, range, stat, shops, shopIds, shopById);
}
/** 当前区间:计入销售额订单、推广/刷单、汇总 Totals */
/** 当前区间 SQL-1/2/4/5 */
private SqlAggBundle loadSqlAgg(ShopContext ctx) {
OrderStatusStatSets stat = ctx.stat();
List<OrderStatAggMapper.ShopProductRow> orderRows = orderStatAggMapper.aggregateByShopProduct(
ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime(),
stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()),
statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds()));
List<OrderStatAggMapper.DailyRow> dailyRows = orderStatAggMapper.aggregateDaily(
ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime(),
stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()),
statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds()));
List<OrderStatAggMapper.PromotionRow> promotionRows = orderStatAggMapper.aggregatePromotionFees(
ctx.companyId(), ctx.shopIds(), ctx.range().startDate(), ctx.range().endDate());
List<OrderStatAggMapper.BrushRow> brushRows = orderStatAggMapper.aggregateBrushFees(
ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime());
return new SqlAggBundle(orderRows, dailyRows, promotionRows, brushRows);
}
/** SQL-3 + 推广/刷单三段时间 KPI */
private ComparePeriodBundle loadCompareFromSql(ShopContext ctx) {
OrderStatusStatSets stat = ctx.stat();
DateRange lastRange = lastMonthSameSpan(ctx.range());
DateRange yoyRange = new DateRange(ctx.range().startDate().minusYears(1), ctx.range().endDate().minusYears(1));
LocalDateTime scanStart = minTime(lastRange.startDateTime(), yoyRange.startDateTime(), ctx.range().startDateTime());
LocalDateTime scanEnd = maxTime(lastRange.endDateTime(), yoyRange.endDateTime(), ctx.range().endDateTime());
OrderStatAggMapper.PeriodKpiRow orderKpi = orderStatAggMapper.aggregatePeriodKpi(
ctx.companyId(), ctx.shopIds(), scanStart, scanEnd,
ctx.range().startDateTime(), ctx.range().endDateTime(),
lastRange.startDateTime(), lastRange.endDateTime(),
yoyRange.startDateTime(), yoyRange.endDateTime(),
stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()),
statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds()));
if (orderKpi == null) {
orderKpi = new OrderStatAggMapper.PeriodKpiRow();
}
LocalDate feeScanStart = minDate(lastRange.startDate(), yoyRange.startDate(), ctx.range().startDate());
LocalDate feeScanEnd = maxDate(lastRange.endDate(), yoyRange.endDate(), ctx.range().endDate());
OrderStatAggMapper.FeeKpiRow promoKpi = orderStatAggMapper.aggregatePromotionPeriodKpi(
ctx.companyId(), ctx.shopIds(), feeScanStart, feeScanEnd,
ctx.range().startDate(), ctx.range().endDate(),
lastRange.startDate(), lastRange.endDate(),
yoyRange.startDate(), yoyRange.endDate());
if (promoKpi == null) {
promoKpi = new OrderStatAggMapper.FeeKpiRow();
}
OrderStatAggMapper.FeeKpiRow brushKpi = orderStatAggMapper.aggregateBrushPeriodKpi(
ctx.companyId(), ctx.shopIds(), scanStart, scanEnd,
ctx.range().startDateTime(), ctx.range().endDateTime(),
lastRange.startDateTime(), lastRange.endDateTime(),
yoyRange.startDateTime(), yoyRange.endDateTime());
if (brushKpi == null) {
brushKpi = new OrderStatAggMapper.FeeKpiRow();
}
return new ComparePeriodBundle(lastRange, yoyRange,
totalsFromPeriodKpi(orderKpi, promoKpi, brushKpi, PeriodSlice.PREV, ctx.taxRate()),
totalsFromPeriodKpi(orderKpi, promoKpi, brushKpi, PeriodSlice.YOY, ctx.taxRate()),
nz(orderKpi.getCurGmvAllStatus()), nz(orderKpi.getPrevGmvAllStatus()), nz(orderKpi.getYoyGmvAllStatus()));
}
private WorkbenchFinancePanelVO buildFinancePanelFromSql(ShopContext ctx, Totals cur,
ComparePeriodBundle compare, SqlAggBundle agg) {
Map<String, Agg> platformAgg = new HashMap<>();
for (OrderStatAggMapper.ShopProductRow row : agg.orderRows()) {
long pk = row.getPlatformId() != null ? row.getPlatformId() : 0L;
platformAgg.computeIfAbsent(String.valueOf(pk), k -> new Agg()).addFromAggRow(row);
}
return WorkbenchFinancePanelVO.builder()
.kpis(buildKpis(cur, compare.prev(), compare.yoy(), ctx.range(), ctx.taxRate(),
compare.totalGmvCur(), compare.totalGmvPrev(), compare.totalGmvYoy()))
.gmvTrend(buildTrendFromDaily(agg.dailyRows(), ctx.range(), cur))
.platformSalesShare(buildPlatformSalesSlices(platformAgg, loadPlatformNames(ctx.shops()), cur.totalSales()))
.momCompareDateStart(compare.lastRange().startDate().toString())
.momCompareDateEnd(compare.lastRange().endDate().toString())
.yoyCompareDateStart(compare.yoyRange().startDate().toString())
.yoyCompareDateEnd(compare.yoyRange().endDate().toString())
.build();
}
private DimensionAggMaps aggregateDimensionsFromSql(List<OrderStatAggMapper.ShopProductRow> rows, ShopContext ctx) {
Map<String, Agg> platformAgg = new HashMap<>();
Map<String, Agg> shopAgg = new HashMap<>();
Map<String, Agg> categoryAgg = new HashMap<>();
Map<String, Agg> productAgg = new HashMap<>();
Set<Long> productIds = new HashSet<>();
Set<Long> categoryIds = new HashSet<>();
for (OrderStatAggMapper.ShopProductRow row : rows) {
long platformKey = row.getPlatformId() != null ? row.getPlatformId() : 0L;
long shopKey = row.getShopId() != null ? row.getShopId() : 0L;
long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L;
long categoryKey = productId <= 0 ? -1L
: (row.getCategoryId() == null || row.getCategoryId() == 0 ? 0L : row.getCategoryId());
platformAgg.computeIfAbsent(String.valueOf(platformKey), k -> new Agg()).addFromAggRow(row);
shopAgg.computeIfAbsent(String.valueOf(shopKey), k -> new Agg()).addFromAggRow(row);
categoryAgg.computeIfAbsent(String.valueOf(categoryKey), k -> new Agg()).addFromAggRow(row);
productAgg.computeIfAbsent(String.valueOf(productId), k -> new Agg()).addFromAggRow(row);
if (productId > 0) {
productIds.add(productId);
}
if (categoryKey > 0) {
categoryIds.add(categoryKey);
}
}
Map<Long, ProductPO> productById = loadProducts(productIds);
Map<Long, String> categoryNames = loadCategoryNamesByIds(categoryIds);
return new DimensionAggMaps(platformAgg, shopAgg, categoryAgg, productAgg,
loadPlatformNames(ctx.shops()), categoryNames, productById, ctx.shopById());
}
private Totals totalsFromOrderRows(List<OrderStatAggMapper.ShopProductRow> rows,
BigDecimal promotion, BigDecimal brush, BigDecimal taxRate) {
BigDecimal sales = BigDecimal.ZERO, refund = BigDecimal.ZERO;
BigDecimal pc = BigDecimal.ZERO, fc = BigDecimal.ZERO, oc = BigDecimal.ZERO;
int orderCount = 0;
for (OrderStatAggMapper.ShopProductRow row : rows) {
sales = sales.add(nz(row.getSalesAmount()));
refund = refund.add(nz(row.getRefundAmount()));
pc = pc.add(nz(row.getProductCost()));
fc = fc.add(nz(row.getFreightCost()));
oc = oc.add(nz(row.getOtherCost()));
orderCount += row.getOrderCount() != null ? row.getOrderCount().intValue() : 0;
}
return buildTotals(sales, refund, pc, fc, oc, promotion, brush, taxRate, orderCount);
}
private Totals totalsFromPeriodKpi(OrderStatAggMapper.PeriodKpiRow o, OrderStatAggMapper.FeeKpiRow promo,
OrderStatAggMapper.FeeKpiRow brush, PeriodSlice slice, BigDecimal taxRate) {
return switch (slice) {
case CUR -> buildTotals(nz(o.getCurSalesAmount()), nz(o.getCurRefundAmount()),
nz(o.getCurProductCost()), nz(o.getCurFreightCost()), nz(o.getCurOtherCost()),
nz(promo.getCurAmount()), nz(brush.getCurAmount()), taxRate,
o.getCurOrderCount() != null ? o.getCurOrderCount().intValue() : 0);
case PREV -> buildTotals(nz(o.getPrevSalesAmount()), nz(o.getPrevRefundAmount()),
nz(o.getPrevProductCost()), nz(o.getPrevFreightCost()), nz(o.getPrevOtherCost()),
nz(promo.getPrevAmount()), nz(brush.getPrevAmount()), taxRate,
o.getPrevOrderCount() != null ? o.getPrevOrderCount().intValue() : 0);
case YOY -> buildTotals(nz(o.getYoySalesAmount()), nz(o.getYoyRefundAmount()),
nz(o.getYoyProductCost()), nz(o.getYoyFreightCost()), nz(o.getYoyOtherCost()),
nz(promo.getYoyAmount()), nz(brush.getYoyAmount()), taxRate,
o.getYoyOrderCount() != null ? o.getYoyOrderCount().intValue() : 0);
};
}
private Totals buildTotals(BigDecimal sales, BigDecimal refund, BigDecimal pc, BigDecimal fc, BigDecimal oc,
BigDecimal promotion, BigDecimal brush, BigDecimal taxRate, int orderCount) {
BigDecimal cost = pc.add(fc).add(oc);
BigDecimal gross = sales.subtract(cost).subtract(refund);
BigDecimal pbt = gross.subtract(promotion).subtract(brush);
BigDecimal tax = salesTaxOnNetSales(sales, refund, taxRate);
BigDecimal aov = orderCount > 0 ? sales.divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
return new Totals(sales, refund, cost, pc, fc, oc, promotion, brush, tax, gross, pbt.subtract(tax), orderCount, aov);
}
private List<WorkbenchTrendPointVO> buildTrendFromDaily(List<OrderStatAggMapper.DailyRow> dailyRows,
DateRange range, Totals periodTotals) {
Map<LocalDate, OrderStatAggMapper.DailyRow> byDay = new HashMap<>();
for (OrderStatAggMapper.DailyRow row : dailyRows) {
if (row.getStatDate() != null) {
byDay.put(row.getStatDate(), row);
}
}
BigDecimal salesTotal = periodTotals.totalSales();
BigDecimal netSum = BigDecimal.ZERO;
for (LocalDate d = range.startDate(); !d.isAfter(range.endDate()); d = d.plusDays(1)) {
netSum = netSum.add(dayNetSales(byDay.get(d)));
}
List<WorkbenchTrendPointVO> list = new ArrayList<>();
for (LocalDate d = range.startDate(); !d.isAfter(range.endDate()); d = d.plusDays(1)) {
OrderStatAggMapper.DailyRow row = byDay.get(d);
BigDecimal sales = row != null ? nz(row.getSalesAmount()) : BigDecimal.ZERO;
BigDecimal refund = row != null ? nz(row.getRefundAmount()) : BigDecimal.ZERO;
BigDecimal cost = row != null
? nz(row.getProductCost()).add(nz(row.getFreightCost())).add(nz(row.getOtherCost())) : BigDecimal.ZERO;
BigDecimal gross = sales.subtract(cost).subtract(refund);
BigDecimal promoB = allocShare(sales, salesTotal, periodTotals.promotion());
BigDecimal brushB = allocShare(sales, salesTotal, periodTotals.brush());
BigDecimal taxB = allocShare(dayNetSales(row), netSum.max(BigDecimal.ONE), periodTotals.tax());
if (netSum.compareTo(BigDecimal.ZERO) <= 0) {
taxB = BigDecimal.ZERO;
}
list.add(WorkbenchTrendPointVO.builder()
.date(d.format(TREND_DATE_FMT))
.salesYuan(yuan2(sales))
.profitYuan(yuan2(gross))
.netProfitYuan(yuan2(gross.subtract(promoB).subtract(brushB).subtract(taxB)))
.refundYuan(yuan2(refund))
.build());
}
return list;
}
private Map<Long, String> loadCategoryNamesByIds(Set<Long> categoryIds) {
if (categoryIds.isEmpty()) {
return Collections.emptyMap();
}
return categoryService.list(new LambdaQueryWrapper<CategoryPO>().in(CategoryPO::getId, categoryIds))
.stream().collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName, (a, b) -> a));
}
private static List<Long> statusList(java.util.Set<Long> ids) {
if (ids == null || ids.isEmpty()) {
return List.of(-1L);
}
List<Long> list = new ArrayList<>(ids);
Collections.sort(list);
return list;
}
private static BigDecimal dayNetSales(OrderStatAggMapper.DailyRow row) {
if (row == null) {
return BigDecimal.ZERO;
}
return nz(row.getSalesAmount()).subtract(nz(row.getRefundAmount())).max(BigDecimal.ZERO);
}
private static LocalDate minDate(LocalDate... dates) {
LocalDate min = dates[0];
for (LocalDate d : dates) {
if (d.isBefore(min)) {
min = d;
}
}
return min;
}
private static LocalDate maxDate(LocalDate... dates) {
LocalDate max = dates[0];
for (LocalDate d : dates) {
if (d.isAfter(max)) {
max = d;
}
}
return max;
}
private static LocalDateTime minTime(LocalDateTime... times) {
LocalDateTime min = times[0];
for (LocalDateTime t : times) {
if (t.isBefore(min)) {
min = t;
}
}
return min;
}
private static LocalDateTime maxTime(LocalDateTime... times) {
LocalDateTime max = times[0];
for (LocalDateTime t : times) {
if (t.isAfter(max)) {
max = t;
}
}
return max;
}
private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
}
private enum PeriodSlice { CUR, PREV, YOY }
private record SqlAggBundle(List<OrderStatAggMapper.ShopProductRow> orderRows,
List<OrderStatAggMapper.DailyRow> dailyRows,
List<OrderStatAggMapper.PromotionRow> promotionRows,
List<OrderStatAggMapper.BrushRow> brushRows) {
BigDecimal promoTotal() {
return promotionRows.stream().map(r -> nz(r.getFeeAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
}
BigDecimal brushTotal() {
return brushRows.stream().map(r -> nz(r.getBrushAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
/** 当前区间:计入销售额订单、推广/刷单、汇总 Totals(导出等仍用) */
private CurrentPeriodBundle loadCurrentPeriod(ShopContext ctx) {
List<Long> unionStatusIds = ctx.stat().getUnionStatusIds();
List<OrderPO> orders = loadOrders(ctx.companyId(), ctx.shopIds(),
@@ -252,9 +514,11 @@ public class WorkbenchServiceImpl implements WorkbenchService {
return new CurrentPeriodBundle(orders, promotionFees, brushOrders, totals);
}
/** 环比/同比:用于 KPI 对比与总 GMV */
/** 环比/同比:用于 KPI 对比与总 GMV(导出等仍用) */
private ComparePeriodBundle loadComparePeriods(ShopContext ctx) {
List<Long> unionStatusIds = ctx.stat().getUnionStatusIds();
List<OrderPO> curOrdersAllStatuses = loadOrdersAllStatuses(ctx.companyId(), ctx.shopIds(),
ctx.range().startDateTime(), ctx.range().endDateTime());
DateRange lastRange = lastMonthSameSpan(ctx.range());
List<OrderPO> lastOrders = loadOrders(ctx.companyId(), ctx.shopIds(),
lastRange.startDateTime(), lastRange.endDateTime(), unionStatusIds);
@@ -278,6 +542,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
Totals yoy = aggregateTotals(yoyOrders, ctx.stat(), yoyPromo, yoyBrush, ctx.taxRate());
return new ComparePeriodBundle(lastRange, yoyRange, prev, yoy,
sumAllReceivedAmount(curOrdersAllStatuses),
sumAllReceivedAmount(lastOrdersAllStatuses),
sumAllReceivedAmount(yoyOrdersAllStatuses));
}
@@ -339,6 +604,9 @@ public class WorkbenchServiceImpl implements WorkbenchService {
if ("0".equals(k)) {
return "未分类";
}
if ("-1".equals(k)) {
return "其他品类";
}
return aggs.categoryNames().getOrDefault(Long.parseLong(k), "类目" + k);
}, salesAllocBase, cur.promotion(), cur.brush(), cur.tax()))
.product(buildDimRows(aggs.productAgg(), k -> {
@@ -964,6 +1232,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
DateRange yoyRange,
Totals prev,
Totals yoy,
BigDecimal totalGmvCur,
BigDecimal totalGmvPrev,
BigDecimal totalGmvYoy) {
}
@@ -1035,6 +1304,14 @@ public class WorkbenchServiceImpl implements WorkbenchService {
}
}
/** 累加 SQL 聚合行 */
void addFromAggRow(OrderStatAggMapper.ShopProductRow row) {
sales = sales.add(nz(row.getSalesAmount()));
refund = refund.add(nz(row.getRefundAmount()));
cost = cost.add(nz(row.getProductCost())).add(nz(row.getFreightCost())).add(nz(row.getOtherCost()));
orders += row.getOrderCount() != null ? row.getOrderCount().intValue() : 0;
}
/** 桶内净销售额 max(0, 销售−退款),与 {@link Totals#netSalesBase()} 含义一致,用于税额分摊 */
BigDecimal netSalesBase() {
BigDecimal b = sales.subtract(refund);
@@ -0,0 +1,238 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper">
<!-- 公司/店铺/时间(不含状态过滤,供 GMV 等全状态指标) -->
<sql id="orderBaseFilter">
o.company_id = #{companyId}
<choose>
<when test="shopIds != null and shopIds.size() > 0">
AND o.shop_id IN
<foreach collection="shopIds" item="id" open="(" separator="," close=")">#{id}</foreach>
</when>
<otherwise>AND 1 = 0</otherwise>
</choose>
AND o.order_time &gt;= #{start}
AND o.order_time &lt;= #{end}
</sql>
<!-- 订单过滤 + 状态口径 CASE 表达式(与 OrderStatusStatSets 一致) -->
<sql id="orderFilter">
<include refid="orderBaseFilter"/>
<choose>
<when test="unionStatusIds != null and unionStatusIds.size() > 0">
AND o.status_id IN
<foreach collection="unionStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
</when>
<otherwise>AND 1 = 0</otherwise>
</choose>
</sql>
<sql id="qty">IFNULL(NULLIF(o.quantity, 0), 1)</sql>
<sql id="sumSales">
SUM(CASE WHEN o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.received_amount ELSE 0 END)
</sql>
<sql id="sumOrderCount">
SUM(CASE WHEN o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN 1 ELSE 0 END)
</sql>
<sql id="sumRefund">
SUM(CASE WHEN o.status_id IN
<foreach collection="refundStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.received_amount ELSE 0 END)
</sql>
<sql id="sumProductCost">
SUM(CASE WHEN o.status_id IN
<foreach collection="productCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.product_cost * <include refid="qty"/> ELSE 0 END)
</sql>
<sql id="sumFreightCost">
SUM(CASE WHEN o.status_id IN
<foreach collection="freightCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.shipping_cost * <include refid="qty"/> ELSE 0 END)
</sql>
<sql id="sumOtherCost">
SUM(CASE WHEN o.status_id IN
<foreach collection="otherCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.other_cost * <include refid="qty"/> ELSE 0 END)
</sql>
<select id="aggregateByShopProduct"
resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper$ShopProductRow">
SELECT o.shop_id AS shopId, s.platform_id AS platformId,
IFNULL(ps.product_id, -1) AS productId, IFNULL(p.category_id, 0) AS categoryId,
<include refid="sumSales"/> AS salesAmount,
<include refid="sumOrderCount"/> AS orderCount,
<include refid="sumRefund"/> AS refundAmount,
<include refid="sumProductCost"/> AS productCost,
<include refid="sumFreightCost"/> AS freightCost,
<include refid="sumOtherCost"/> AS otherCost,
SUM(o.received_amount) AS gmvAllStatus
FROM ec_order o
INNER JOIN ec_shop s ON s.id = o.shop_id
LEFT JOIN ec_product_spec ps ON ps.id = o.product_spec_id
LEFT JOIN ec_product p ON p.id = ps.product_id
WHERE <include refid="orderBaseFilter"/>
GROUP BY o.shop_id, s.platform_id, ps.product_id, p.category_id
</select>
<select id="aggregateDaily"
resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper$DailyRow">
SELECT DATE(o.order_time) AS statDate,
<include refid="sumSales"/> AS salesAmount,
<include refid="sumRefund"/> AS refundAmount,
<include refid="sumProductCost"/> AS productCost,
<include refid="sumFreightCost"/> AS freightCost,
<include refid="sumOtherCost"/> AS otherCost
FROM ec_order o
WHERE <include refid="orderFilter"/>
GROUP BY DATE(o.order_time)
ORDER BY statDate
</select>
<select id="aggregatePeriodKpi"
resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper$PeriodKpiRow">
SELECT
SUM(CASE WHEN o.order_time BETWEEN #{curStart} AND #{curEnd} AND o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.received_amount ELSE 0 END) AS curSalesAmount,
SUM(CASE WHEN o.order_time BETWEEN #{curStart} AND #{curEnd} AND o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN 1 ELSE 0 END) AS curOrderCount,
SUM(CASE WHEN o.order_time BETWEEN #{curStart} AND #{curEnd} AND o.status_id IN
<foreach collection="refundStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.received_amount ELSE 0 END) AS curRefundAmount,
SUM(CASE WHEN o.order_time BETWEEN #{curStart} AND #{curEnd} AND o.status_id IN
<foreach collection="productCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.product_cost * <include refid="qty"/> ELSE 0 END) AS curProductCost,
SUM(CASE WHEN o.order_time BETWEEN #{curStart} AND #{curEnd} AND o.status_id IN
<foreach collection="freightCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.shipping_cost * <include refid="qty"/> ELSE 0 END) AS curFreightCost,
SUM(CASE WHEN o.order_time BETWEEN #{curStart} AND #{curEnd} AND o.status_id IN
<foreach collection="otherCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.other_cost * <include refid="qty"/> ELSE 0 END) AS curOtherCost,
SUM(CASE WHEN o.order_time BETWEEN #{curStart} AND #{curEnd} THEN o.received_amount ELSE 0 END) AS curGmvAllStatus,
SUM(CASE WHEN o.order_time BETWEEN #{prevStart} AND #{prevEnd} AND o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.received_amount ELSE 0 END) AS prevSalesAmount,
SUM(CASE WHEN o.order_time BETWEEN #{prevStart} AND #{prevEnd} AND o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN 1 ELSE 0 END) AS prevOrderCount,
SUM(CASE WHEN o.order_time BETWEEN #{prevStart} AND #{prevEnd} AND o.status_id IN
<foreach collection="refundStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.received_amount ELSE 0 END) AS prevRefundAmount,
SUM(CASE WHEN o.order_time BETWEEN #{prevStart} AND #{prevEnd} AND o.status_id IN
<foreach collection="productCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.product_cost * <include refid="qty"/> ELSE 0 END) AS prevProductCost,
SUM(CASE WHEN o.order_time BETWEEN #{prevStart} AND #{prevEnd} AND o.status_id IN
<foreach collection="freightCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.shipping_cost * <include refid="qty"/> ELSE 0 END) AS prevFreightCost,
SUM(CASE WHEN o.order_time BETWEEN #{prevStart} AND #{prevEnd} AND o.status_id IN
<foreach collection="otherCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.other_cost * <include refid="qty"/> ELSE 0 END) AS prevOtherCost,
SUM(CASE WHEN o.order_time BETWEEN #{prevStart} AND #{prevEnd} THEN o.received_amount ELSE 0 END) AS prevGmvAllStatus,
SUM(CASE WHEN o.order_time BETWEEN #{yoyStart} AND #{yoyEnd} AND o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.received_amount ELSE 0 END) AS yoySalesAmount,
SUM(CASE WHEN o.order_time BETWEEN #{yoyStart} AND #{yoyEnd} AND o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN 1 ELSE 0 END) AS yoyOrderCount,
SUM(CASE WHEN o.order_time BETWEEN #{yoyStart} AND #{yoyEnd} AND o.status_id IN
<foreach collection="refundStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.received_amount ELSE 0 END) AS yoyRefundAmount,
SUM(CASE WHEN o.order_time BETWEEN #{yoyStart} AND #{yoyEnd} AND o.status_id IN
<foreach collection="productCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.product_cost * <include refid="qty"/> ELSE 0 END) AS yoyProductCost,
SUM(CASE WHEN o.order_time BETWEEN #{yoyStart} AND #{yoyEnd} AND o.status_id IN
<foreach collection="freightCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.shipping_cost * <include refid="qty"/> ELSE 0 END) AS yoyFreightCost,
SUM(CASE WHEN o.order_time BETWEEN #{yoyStart} AND #{yoyEnd} AND o.status_id IN
<foreach collection="otherCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.other_cost * <include refid="qty"/> ELSE 0 END) AS yoyOtherCost,
SUM(CASE WHEN o.order_time BETWEEN #{yoyStart} AND #{yoyEnd} THEN o.received_amount ELSE 0 END) AS yoyGmvAllStatus
FROM ec_order o
WHERE o.company_id = #{companyId}
<choose>
<when test="shopIds != null and shopIds.size() > 0">
AND o.shop_id IN <foreach collection="shopIds" item="id" open="(" separator="," close=")">#{id}</foreach>
</when>
<otherwise>AND 1 = 0</otherwise>
</choose>
AND o.order_time BETWEEN #{scanStart} AND #{scanEnd}
<choose>
<when test="unionStatusIds != null and unionStatusIds.size() > 0">
AND o.status_id IN <foreach collection="unionStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
</when>
<otherwise>AND 1 = 0</otherwise>
</choose>
</select>
<select id="aggregatePromotionPeriodKpi"
resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper$FeeKpiRow">
SELECT
SUM(CASE WHEN f.fee_date BETWEEN #{curStart} AND #{curEnd} THEN IFNULL(f.fee_amount,0) ELSE 0 END) AS curAmount,
SUM(CASE WHEN f.fee_date BETWEEN #{prevStart} AND #{prevEnd} THEN IFNULL(f.fee_amount,0) ELSE 0 END) AS prevAmount,
SUM(CASE WHEN f.fee_date BETWEEN #{yoyStart} AND #{yoyEnd} THEN IFNULL(f.fee_amount,0) ELSE 0 END) AS yoyAmount
FROM ec_promotion_fee f
WHERE f.company_id = #{companyId}
<choose>
<when test="shopIds != null and shopIds.size() > 0">
AND f.shop_id IN <foreach collection="shopIds" item="id" open="(" separator="," close=")">#{id}</foreach>
</when>
<otherwise>AND 1 = 0</otherwise>
</choose>
AND f.fee_date BETWEEN #{scanStart} AND #{scanEnd}
</select>
<select id="aggregateBrushPeriodKpi"
resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper$FeeKpiRow">
SELECT
SUM(CASE WHEN b.brush_time BETWEEN #{curStart} AND #{curEnd} THEN IFNULL(b.brush_amount,0) ELSE 0 END) AS curAmount,
SUM(CASE WHEN b.brush_time BETWEEN #{prevStart} AND #{prevEnd} THEN IFNULL(b.brush_amount,0) ELSE 0 END) AS prevAmount,
SUM(CASE WHEN b.brush_time BETWEEN #{yoyStart} AND #{yoyEnd} THEN IFNULL(b.brush_amount,0) ELSE 0 END) AS yoyAmount
FROM ec_brush_order b
WHERE b.company_id = #{companyId}
<choose>
<when test="shopIds != null and shopIds.size() > 0">
AND b.shop_id IN <foreach collection="shopIds" item="id" open="(" separator="," close=")">#{id}</foreach>
</when>
<otherwise>AND 1 = 0</otherwise>
</choose>
AND b.brush_time BETWEEN #{scanStart} AND #{scanEnd}
</select>
<select id="aggregatePromotionFees"
resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper$PromotionRow">
SELECT f.shop_id AS shopId, f.product_id AS productId, f.category_id AS categoryId,
SUM(IFNULL(f.fee_amount, 0)) AS feeAmount
FROM ec_promotion_fee f
WHERE f.company_id = #{companyId}
<choose>
<when test="shopIds != null and shopIds.size() > 0">
AND f.shop_id IN <foreach collection="shopIds" item="id" open="(" separator="," close=")">#{id}</foreach>
</when>
<otherwise>AND 1 = 0</otherwise>
</choose>
AND f.fee_date BETWEEN #{startDate} AND #{endDate}
GROUP BY f.shop_id, f.product_id, f.category_id
</select>
<select id="aggregateBrushFees"
resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper$BrushRow">
SELECT b.shop_id AS shopId, SUM(IFNULL(b.brush_amount, 0)) AS brushAmount
FROM ec_brush_order b
WHERE b.company_id = #{companyId}
<choose>
<when test="shopIds != null and shopIds.size() > 0">
AND b.shop_id IN <foreach collection="shopIds" item="id" open="(" separator="," close=")">#{id}</foreach>
</when>
<otherwise>AND 1 = 0</otherwise>
</choose>
AND b.brush_time BETWEEN #{start} AND #{end}
GROUP BY b.shop_id
</select>
</mapper>
@@ -51,8 +51,8 @@ export namespace ProductOverviewVO {
shippingCost: number;
/** 其他成本 */
otherCost: number;
/** 总成本(商品成本+运费+其他成本) */
totalCost?: number;
/** 订单成本(商品成本+运费+其他成本,不含推广费、刷单费) */
orderCost?: number;
/** 退款金额 */
refundAmount: number;
/** 推广费 */
@@ -85,8 +85,8 @@ export namespace ProductOverviewVO {
shippingCost: number;
/** 其他成本 */
otherCost: number;
/** 总成本(商品成本+运费+其他成本) */
totalCost?: number;
/** 订单成本(商品成本+运费+其他成本,不含推广费、刷单费) */
orderCost?: number;
/** 退款金额 */
refundAmount: number;
/** 推广费 */
@@ -132,8 +132,8 @@ export namespace ShopVO {
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 总成本(商品成本+运费+其他成本) */
totalCost?: number;
/** 订单成本(商品成本+运费+其他成本,不含推广费、刷单费) */
orderCost?: number;
/** 退款金额 */
refundAmount?: number;
/** 推广费 */
@@ -170,8 +170,8 @@ export namespace ShopVO {
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 总成本(商品成本+运费+其他成本) */
totalCost?: number;
/** 订单成本(商品成本+运费+其他成本,不含推广费、刷单费) */
orderCost?: number;
/** 退款金额 */
refundAmount?: number;
/** 推广费 */
@@ -107,6 +107,8 @@ export namespace CompanyOverviewVO {
salesAmountAchievementRate?: number;
/** 销售额 */
salesAmount: number;
/** GMV(全订单状态商家实收合计) */
gmv?: number;
/** 单量 */
orderCount?: number;
/** 客单价 */
@@ -117,8 +119,8 @@ export namespace CompanyOverviewVO {
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 总成本(商品成本+运费+其他成本) */
totalCost?: number;
/** 订单成本(商品成本+运费+其他成本,不含推广费、刷单费) */
orderCost?: number;
/** 退款金额 */
refundAmount?: number;
/** 推广费 */
@@ -127,11 +129,13 @@ export namespace CompanyOverviewVO {
brushFee?: number;
/** 费比 */
feeRatio?: number;
/** 税前盈亏 */
/** 毛利 */
grossProfit?: number;
/** 税前净利 */
totalProfitBeforeTax?: number;
/** 销售额4%税额 */
salesTaxAmount?: number;
/** 税后盈亏 */
/** 税后净利 */
profitAfterTax?: number;
/** ROI */
roi?: number;
@@ -145,6 +149,8 @@ export namespace CompanyOverviewVO {
categoryName: string;
/** 销售额 */
salesAmount: number;
/** GMV(全订单状态商家实收合计) */
gmv?: number;
/** 单量 */
orderCount?: number;
/** 客单价 */
@@ -155,8 +161,8 @@ export namespace CompanyOverviewVO {
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 总成本(商品成本+运费+其他成本) */
totalCost?: number;
/** 订单成本(商品成本+运费+其他成本,不含推广费、刷单费) */
orderCost?: number;
/** 退款金额 */
refundAmount?: number;
/** 推广费 */
@@ -165,11 +171,13 @@ export namespace CompanyOverviewVO {
brushFee?: number;
/** 费比 */
feeRatio?: number;
/** 税前盈亏 */
/** 毛利 */
grossProfit?: number;
/** 税前净利 */
totalProfitBeforeTax?: number;
/** 销售额4%税额 */
salesTaxAmount?: number;
/** 税后盈亏 */
/** 税后净利 */
profitAfterTax?: number;
/** ROI */
roi?: number;
@@ -191,6 +199,8 @@ export namespace CompanyOverviewVO {
salesAmountAchievementRate?: number;
/** 销售额 */
salesAmount: number;
/** GMV(全订单状态商家实收合计) */
gmv?: number;
/** 单量 */
orderCount?: number;
/** 客单价 */
@@ -201,8 +211,8 @@ export namespace CompanyOverviewVO {
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 总成本(商品成本+运费+其他成本) */
totalCost?: number;
/** 订单成本(商品成本+运费+其他成本,不含推广费、刷单费) */
orderCost?: number;
/** 退款金额 */
refundAmount?: number;
/** 推广费 */
@@ -211,13 +221,15 @@ export namespace CompanyOverviewVO {
brushFee?: number;
/** 费比 */
feeRatio?: number;
/** 税前盈亏 */
/** 毛利 */
grossProfit?: number;
/** 税前净利 */
totalProfitBeforeTax?: number;
/** 销售额4%税额 */
salesTaxAmount?: number;
/** ROI */
roi?: number;
/** 税后盈亏 */
/** 税后净利 */
profitAfterTax?: number;
}
@@ -11,6 +11,10 @@ export const overviewTableHints = {
salesAmountAchievementRate: '实际销售额 ÷ 目标额 × 100%。',
salesAmount:
'统计口径下,计入销售额的订单实收金额合计(与后端订单状态统计一致)。',
gmv:
'GMV = 所选时间范围内全部订单状态的商家实收金额合计(不按订单状态过滤)。',
grossProfit:
'毛利 = 实际销售额 − 订单成本 − 退款金额(未扣推广费、刷单费与税额)。',
/** 与 salesAmount 同口径,表头文案为「销售额」时使用 */
salesAmountShort:
'统计口径下,计入销售额的订单实收金额合计(与后端订单状态统计一致)。',
@@ -21,7 +25,8 @@ export const overviewTableHints = {
productCost: '订单维度「商品成本」字段汇总。',
shippingCost: '订单维度「运费成本」字段汇总。',
otherCost: '订单维度「其他成本」字段汇总。',
totalCost: '总成本 = 商品成本 + 运费 + 其他成本。',
orderCost:
'订单成本 = 商品成本 + 运费 + 其他成本(订单维度汇总,不含推广费、刷单费)。',
refundAmount: '统计口径下,计入退款的实收金额合计。',
totalPromotionFee: '该维度下推广费金额合计(来自推广费单据)。',
promotionFeeSpec:
@@ -38,12 +43,12 @@ export const overviewTableHints = {
feeRatioSpec:
'费比(%)= 推广费 ÷ 销售额;接口字段已为百分数数值(0–100),与店铺商品表费比展示方式不同。',
totalProfitBeforeTax:
'税前盈亏 = 实际销售额 − 总成本 − 退款金额 − 推广费 − 刷单费用。',
'税前净利 = 毛利 − 推广费 − 刷单费用。',
profitBeforeTaxSpec:
'税前盈亏 = 销售额 − 总成本 − 退款金额 − 推广费(规格维度不含刷单费)。',
'税前净利 = 销售额 − 订单成本 − 退款金额 − 推广费(规格维度不含刷单费)。',
roi: 'ROI =(实际销售额 − 退款金额)÷ 推广费;推广费为 0 时后端记为 0。',
profitAfterTax: '税后盈亏 = 税前盈亏 − 税额。',
profitAfterTaxNet: '税后净利 = 税前盈亏 − 税额(与「税后盈亏」同口径,表头名称不同)。',
profitAfterTax: '税后净利 = 税前净利 − 税额。',
profitAfterTaxNet: '税后净利 = 税前净利 − 税额(与「税后盈亏」同口径,表头名称不同)。',
} as const;
/** @deprecated 使用 overviewTableHints */
@@ -181,7 +181,7 @@ const cellRoi = (v: number | null | undefined) =>
<OverviewColumnHint :title="storeOverviewHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="storeOverviewHints.totalCost">总成本</OverviewColumnHint>
<OverviewColumnHint :title="storeOverviewHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-rose-600 dark:text-rose-400">
<OverviewColumnHint :title="storeOverviewHints.refundAmount">退款金额</OverviewColumnHint>
@@ -256,7 +256,7 @@ const cellRoi = (v: number | null | undefined) =>
<td class="p-6">{{ cellMoney(cat.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(cat.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">
{{ cellMoney(cat.totalCost) }}
{{ cellMoney(cat.orderCost) }}
</td>
<td class="p-6 font-bold text-rose-600 dark:text-rose-400">
{{ cellMoney(cat.refundAmount) }}
@@ -301,7 +301,7 @@ const cellRoi = (v: number | null | undefined) =>
<td class="p-6">{{ cellMoney(categorySummary?.total?.productCost) }}</td>
<td class="p-6">{{ cellMoney(categorySummary?.total?.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(categorySummary?.total?.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(categorySummary?.total?.totalCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(categorySummary?.total?.orderCost) }}</td>
<td class="p-6 text-rose-600 dark:text-rose-400">{{ cellMoney(categorySummary?.total?.refundAmount) }}</td>
<td class="p-6">{{ cellMoney(categorySummary?.total?.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoney(categorySummary?.total?.brushFee) }}</td>
@@ -75,7 +75,7 @@ const platformData = computed(() => {
productCost: p.productCost ?? 0,
shippingCost: p.shippingCost ?? 0,
otherCost: p.otherCost ?? 0,
totalCost: p.totalCost ?? 0,
orderCost: p.orderCost ?? 0,
refundAmount: p.refundAmount ?? 0,
totalPromotionFee: p.totalPromotionFee ?? 0,
brushFee: p.brushFee ?? 0,
@@ -265,7 +265,7 @@ const sortedData = computed(() => {
<OverviewColumnHint :title="storeOverviewHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="storeOverviewHints.totalCost">总成本</OverviewColumnHint>
<OverviewColumnHint :title="storeOverviewHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold text-rose-600 dark:text-rose-400">
<OverviewColumnHint :title="storeOverviewHints.refundAmount">退款金额</OverviewColumnHint>
@@ -346,7 +346,7 @@ const sortedData = computed(() => {
<td class="p-6">{{ formatAmount(p.productCost) }}</td>
<td class="p-6">{{ formatAmount(p.shippingCost) }}</td>
<td class="p-6">{{ formatAmount(p.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ formatAmount(p.totalCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ formatAmount(p.orderCost) }}</td>
<td class="p-6 font-bold text-rose-600 dark:text-rose-400">{{ formatAmount(p.refundAmount) }}</td>
<td class="p-6">{{ formatAmount(p.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ formatAmount(p.brushFee) }}</td>
@@ -388,7 +388,7 @@ const sortedData = computed(() => {
<td class="p-6">{{ cellMoney(totalData.productCost) }}</td>
<td class="p-6">{{ cellMoney(totalData.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(totalData.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(totalData.totalCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(totalData.orderCost) }}</td>
<td class="p-6 text-rose-600 dark:text-rose-400">{{ cellMoney(totalData.refundAmount) }}</td>
<td class="p-6">{{ cellMoney(totalData.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoney(totalData.brushFee) }}</td>
@@ -220,7 +220,7 @@ const cellRoi = (v: number | null | undefined) =>
<OverviewColumnHint :title="storeOverviewHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="storeOverviewHints.totalCost">总成本</OverviewColumnHint>
<OverviewColumnHint :title="storeOverviewHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-rose-600 dark:text-rose-400">
<OverviewColumnHint :title="storeOverviewHints.refundAmount">退款金额</OverviewColumnHint>
@@ -334,7 +334,7 @@ const cellRoi = (v: number | null | undefined) =>
{{ cellMoney(shop.otherCost) }}
</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">
{{ cellMoney(shop.totalCost) }}
{{ cellMoney(shop.orderCost) }}
</td>
<td class="p-6 font-bold text-rose-600 dark:text-rose-400">
{{ cellMoney(shop.refundAmount) }}
@@ -403,7 +403,7 @@ const cellRoi = (v: number | null | undefined) =>
<td class="p-6">{{ cellMoney(shopSummary?.total?.productCost) }}</td>
<td class="p-6">{{ cellMoney(shopSummary?.total?.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(shopSummary?.total?.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(shopSummary?.total?.totalCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(shopSummary?.total?.orderCost) }}</td>
<td class="p-6 text-rose-600 dark:text-rose-400">{{ cellMoney(shopSummary?.total?.refundAmount) }}</td>
<td class="p-6">{{ cellMoney(shopSummary?.total?.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoney(shopSummary?.total?.brushFee) }}</td>
@@ -109,6 +109,14 @@ function buildCompareMetrics(
valueA: z(a, (r) => r.salesAmount),
valueB: z(b, (r) => r.salesAmount),
},
{
key: 'gmv',
label: 'GMV',
hint: overviewTableHints.gmv,
format: 'money',
valueA: z(a, (r) => r.gmv),
valueB: z(b, (r) => r.gmv),
},
{
key: 'orderCount',
label: '单量',
@@ -150,12 +158,12 @@ function buildCompareMetrics(
valueB: z(b, (r) => r.otherCost),
},
{
key: 'totalCost',
label: '总成本',
hint: overviewTableHints.totalCost,
key: 'orderCost',
label: '订单成本',
hint: overviewTableHints.orderCost,
format: 'money',
valueA: z(a, (r) => r.totalCost),
valueB: z(b, (r) => r.totalCost),
valueA: z(a, (r) => r.orderCost),
valueB: z(b, (r) => r.orderCost),
},
{
key: 'refundAmount',
@@ -189,9 +197,17 @@ function buildCompareMetrics(
valueA: feeRatioAsPercent(a),
valueB: feeRatioAsPercent(b),
},
{
key: 'grossProfit',
label: '毛利',
hint: overviewTableHints.grossProfit,
format: 'money',
valueA: z(a, (r) => r.grossProfit),
valueB: z(b, (r) => r.grossProfit),
},
{
key: 'totalProfitBeforeTax',
label: '税前盈亏',
label: '税前净利',
hint: overviewTableHints.totalProfitBeforeTax,
format: 'money',
valueA: z(a, (r) => r.totalProfitBeforeTax),
@@ -215,7 +231,7 @@ function buildCompareMetrics(
},
{
key: 'profitAfterTax',
label: '税后盈亏',
label: '税后净利',
hint: overviewTableHints.profitAfterTax,
format: 'money',
valueA: z(a, (r) => r.profitAfterTax),
@@ -148,7 +148,7 @@ const cellRoi = (v: number | null | undefined) =>
{{ props.firstColumnLabel }}
</th>
<th
colspan="3"
colspan="4"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] dark:border-[hsl(240deg_3.7%_22%)] bg-slate-100/50 dark:bg-[hsl(240deg_3.7%_22%/50%)] p-3 text-center"
>
经营规模维度
@@ -160,7 +160,7 @@ const cellRoi = (v: number | null | undefined) =>
成本费用维度
</th>
<th
colspan="5"
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%)] dark:border-[hsl(240deg_3.7%_22%)] bg-emerald-50/50 dark:bg-[hsl(142deg_71.8%_29%)] p-3 text-center text-emerald-700 dark:text-emerald-200"
>
盈利分析维度
@@ -172,6 +172,9 @@ const cellRoi = (v: number | null | undefined) =>
实际销售额
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-black text-amber-700 dark:text-amber-400">
<OverviewColumnHint :title="storeOverviewHints.gmv">GMV</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.orderCount">单量</OverviewColumnHint>
</th>
@@ -188,7 +191,7 @@ const cellRoi = (v: number | null | undefined) =>
<OverviewColumnHint :title="storeOverviewHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="storeOverviewHints.totalCost">总成本</OverviewColumnHint>
<OverviewColumnHint :title="storeOverviewHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-rose-600 dark:text-rose-400">
<OverviewColumnHint :title="storeOverviewHints.refundAmount">退款金额</OverviewColumnHint>
@@ -202,9 +205,12 @@ const cellRoi = (v: number | null | undefined) =>
<th class="border-b px-6 py-4 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<OverviewColumnHint :title="storeOverviewHints.feeRatioCategoryRow">费比%</OverviewColumnHint>
</th>
<th class="border-b border-l px-6 py-4 font-bold">
<th class="border-b border-l px-6 py-4 font-bold text-emerald-700 dark:text-emerald-400">
<OverviewColumnHint :title="storeOverviewHints.grossProfit">毛利</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold">
<OverviewColumnHint :title="storeOverviewHints.totalProfitBeforeTax">
税前盈亏
税前净利
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 italic text-rose-500 dark:text-rose-400">
@@ -217,7 +223,7 @@ const cellRoi = (v: number | null | undefined) =>
</th>
<th class="border-b bg-emerald-600 dark:bg-emerald-600 px-6 py-4 font-black text-white">
<OverviewColumnHint light :title="storeOverviewHints.profitAfterTax">
税后盈亏
税后净利
</OverviewColumnHint>
</th>
</tr>
@@ -266,6 +272,7 @@ const cellRoi = (v: number | null | undefined) =>
</span>
</td>
<td class="p-6 font-black">{{ formatAmount(cat.salesAmount) }}</td>
<td class="p-6 font-black text-amber-700 dark:text-amber-400">{{ formatAmount(cat.gmv) }}</td>
<td class="p-6 font-medium">{{ formatIntCell(cat.orderCount) }}</td>
<td class="p-6 font-medium">
{{ cellMoney(cat.averageOrderValue) }}
@@ -274,7 +281,7 @@ const cellRoi = (v: number | null | undefined) =>
<td class="p-6">{{ cellMoney(cat.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(cat.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">
{{ cellMoney(cat.totalCost) }}
{{ cellMoney(cat.orderCost) }}
</td>
<td class="p-6 font-bold text-rose-600 dark:text-rose-400">
{{ cellMoney(cat.refundAmount) }}
@@ -286,6 +293,9 @@ const cellRoi = (v: number | null | undefined) =>
<td class="p-6 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
{{ cat.feeRatio !== undefined ? formatFeeRatioPercent(cat.feeRatio) : '-' }}
</td>
<td class="p-6 font-bold text-emerald-700 dark:text-emerald-400">
{{ cellMoney(cat.grossProfit) }}
</td>
<td class="p-6 font-bold">
{{ cellMoney(cat.totalProfitBeforeTax) }}
</td>
@@ -300,7 +310,7 @@ const cellRoi = (v: number | null | undefined) =>
</td>
</tr>
<tr v-if="!categorySummary?.categories?.length">
<td :colspan="categoryExportMode ? 18 : 17" class="p-8 text-center text-gray-400">
<td :colspan="categoryExportMode ? 20 : 19" class="p-8 text-center text-gray-400">
暂无数据
</td>
</tr>
@@ -311,6 +321,7 @@ const cellRoi = (v: number | null | undefined) =>
<td class="sticky-col bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] p-6 text-base">合计</td>
<!-- 规模 -->
<td class="p-6">{{ cellMoney(categorySummary?.total?.salesAmount) }}</td>
<td class="p-6 text-amber-700 dark:text-amber-400">{{ cellMoney(categorySummary?.total?.gmv) }}</td>
<td class="p-6">{{ formatIntCell(categorySummary?.total?.orderCount) }}</td>
<td class="p-6">
{{ cellMoney(categorySummary?.total?.averageOrderValue) }}
@@ -319,12 +330,13 @@ const cellRoi = (v: number | null | undefined) =>
<td class="p-6">{{ cellMoney(categorySummary?.total?.productCost) }}</td>
<td class="p-6">{{ cellMoney(categorySummary?.total?.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(categorySummary?.total?.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(categorySummary?.total?.totalCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(categorySummary?.total?.orderCost) }}</td>
<td class="p-6 text-rose-600 dark:text-rose-400">{{ cellMoney(categorySummary?.total?.refundAmount) }}</td>
<td class="p-6">{{ cellMoney(categorySummary?.total?.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoney(categorySummary?.total?.brushFee) }}</td>
<td class="p-6 text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ categorySummary?.total?.feeRatio !== undefined ? formatFeeRatioPercent(categorySummary?.total?.feeRatio) : '-' }}</td>
<!-- 盈利 -->
<td class="p-6 text-emerald-700 dark:text-emerald-400">{{ cellMoney(categorySummary?.total?.grossProfit) }}</td>
<td class="p-6">{{ cellMoney(categorySummary?.total?.totalProfitBeforeTax) }}</td>
<td class="p-6 italic text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoney(categorySummary?.total?.salesTaxAmount) }}</td>
<td class="p-6 text-indigo-700 dark:text-indigo-400">{{ cellRoi(categorySummary?.total?.roi) }}</td>
@@ -70,16 +70,18 @@ const platformData = computed(() => {
targetAmount: p.targetAmount ?? 0,
salesAmountAchievementRate: p.salesAmountAchievementRate ?? 0,
salesAmount: p.salesAmount ?? 0,
gmv: p.gmv ?? 0,
orderCount: p.orderCount ?? 0,
averageOrderValue: p.averageOrderValue ?? 0,
productCost: p.productCost ?? 0,
shippingCost: p.shippingCost ?? 0,
otherCost: p.otherCost ?? 0,
totalCost: p.totalCost ?? 0,
orderCost: p.orderCost ?? 0,
refundAmount: p.refundAmount ?? 0,
totalPromotionFee: p.totalPromotionFee ?? 0,
brushFee: p.brushFee ?? 0,
feeRatio: p.feeRatio ?? 0,
grossProfit: p.grossProfit ?? 0,
totalProfitBeforeTax: p.totalProfitBeforeTax ?? 0,
salesTaxAmount: p.salesTaxAmount ?? 0,
roi: p.roi ?? 0,
@@ -202,7 +204,7 @@ const sortedData = computed(() => {
</th>
<!-- 规模 -->
<th
colspan="3"
colspan="4"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] p-3 text-center bg-slate-100/50 dark:bg-[hsl(240deg_3.7%_22%/50%)]"
>
经营规模维度
@@ -216,7 +218,7 @@ const sortedData = computed(() => {
</th>
<!-- 盈利 -->
<th
colspan="5"
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%)] p-3 text-center bg-emerald-50/50 dark:bg-[hsl(142deg_71.8%_29%)] text-emerald-700 dark:text-emerald-200"
>
盈利分析维度
@@ -248,6 +250,9 @@ const sortedData = computed(() => {
实际销售额
</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-amber-700 dark:text-amber-400">
<OverviewColumnHint :title="storeOverviewHints.gmv">GMV</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.orderCount">单量</OverviewColumnHint>
</th>
@@ -265,7 +270,7 @@ const sortedData = computed(() => {
<OverviewColumnHint :title="storeOverviewHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="storeOverviewHints.totalCost">总成本</OverviewColumnHint>
<OverviewColumnHint :title="storeOverviewHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold text-rose-600 dark:text-rose-400">
<OverviewColumnHint :title="storeOverviewHints.refundAmount">退款金额</OverviewColumnHint>
@@ -280,9 +285,12 @@ const sortedData = computed(() => {
<OverviewColumnHint :title="storeOverviewHints.feeRatioPlatform">费比%</OverviewColumnHint>
</th>
<!-- 盈利子列 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold text-emerald-700 dark:text-emerald-400">
<OverviewColumnHint :title="storeOverviewHints.grossProfit">毛利</OverviewColumnHint>
</th>
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold">
<OverviewColumnHint :title="storeOverviewHints.totalProfitBeforeTax">
税前盈亏
税前净利
</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 italic text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
@@ -295,7 +303,7 @@ const sortedData = computed(() => {
</th>
<th class="border-b bg-emerald-600 dark:bg-emerald-600 px-6 py-4 font-black text-white">
<OverviewColumnHint light :title="storeOverviewHints.profitAfterTax">
税后盈亏
税后净利
</OverviewColumnHint>
</th>
</tr>
@@ -340,18 +348,22 @@ const sortedData = computed(() => {
<td class="p-6 font-black text-blue-600 dark:text-blue-400">{{ formatPercentPlain(p.salesAmountAchievementRate) }}</td>
<!-- 规模 -->
<td class="p-6 font-black">{{ formatAmount(p.salesAmount) }}</td>
<td class="p-6 font-black text-amber-700 dark:text-amber-400">{{ formatAmount(p.gmv) }}</td>
<td class="p-6 font-medium">{{ p.orderCount.toLocaleString('zh-CN') }}</td>
<td class="p-6 font-medium">{{ formatAmount(p.averageOrderValue) }}</td>
<!-- 成本 -->
<td class="p-6">{{ formatAmount(p.productCost) }}</td>
<td class="p-6">{{ formatAmount(p.shippingCost) }}</td>
<td class="p-6">{{ formatAmount(p.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ formatAmount(p.totalCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ formatAmount(p.orderCost) }}</td>
<td class="p-6 font-bold text-rose-600 dark:text-rose-400">{{ formatAmount(p.refundAmount) }}</td>
<td class="p-6">{{ formatAmount(p.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ formatAmount(p.brushFee) }}</td>
<td class="p-6 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">{{ formatFeeRatioPercent(p.feeRatio) }}</td>
<!-- 盈利 -->
<td class="p-6 font-bold text-emerald-700 dark:text-emerald-400">
{{ formatAmount(p.grossProfit) }}
</td>
<td class="p-6 font-bold" :class="p.totalProfitBeforeTax >= 0 ? 'text-slate-800 dark:text-[hsl(0deg_0%_95%)]' : 'text-rose-600 dark:text-rose-400'">
{{ formatAmount(p.totalProfitBeforeTax) }}
</td>
@@ -380,6 +392,7 @@ const sortedData = computed(() => {
</td>
<!-- 规模 -->
<td class="p-6">{{ cellMoney(totalData.salesAmount) }}</td>
<td class="p-6 text-amber-700 dark:text-amber-400">{{ cellMoney(totalData.gmv) }}</td>
<td class="p-6">{{ formatIntCell(totalData.orderCount) }}</td>
<td class="p-6">
{{ cellMoney(totalData.averageOrderValue) }}
@@ -388,7 +401,7 @@ const sortedData = computed(() => {
<td class="p-6">{{ cellMoney(totalData.productCost) }}</td>
<td class="p-6">{{ cellMoney(totalData.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(totalData.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(totalData.totalCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(totalData.orderCost) }}</td>
<td class="p-6 text-rose-600 dark:text-rose-400">{{ cellMoney(totalData.refundAmount) }}</td>
<td class="p-6">{{ cellMoney(totalData.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoney(totalData.brushFee) }}</td>
@@ -396,6 +409,9 @@ const sortedData = computed(() => {
{{ totalData.feeRatio !== undefined ? formatFeeRatioPercent(totalData.feeRatio) : '-' }}
</td>
<!-- 盈利 -->
<td class="p-6 text-emerald-700 dark:text-emerald-400">
{{ cellMoney(totalData.grossProfit) }}
</td>
<td class="p-6">
{{ cellMoney(totalData.totalProfitBeforeTax) }}
</td>
@@ -415,7 +431,7 @@ const sortedData = computed(() => {
</tfoot>
<tfoot v-else class="bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)]">
<tr class="text-center text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<td :colspan="platformExportMode ? 22 : 21" class="p-6">暂无数据</td>
<td :colspan="platformExportMode ? 24 : 23" class="p-6">暂无数据</td>
</tr>
</tfoot>
</table>
@@ -159,7 +159,7 @@ const cellRoi = (v: number | null | undefined) =>
目标达成维度
</th>
<th
colspan="3"
colspan="4"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] dark:border-[hsl(240deg_3.7%_22%)] bg-slate-100/50 dark:bg-[hsl(240deg_3.7%_22%/50%)] p-3 text-center"
>
经营规模维度
@@ -171,7 +171,7 @@ const cellRoi = (v: number | null | undefined) =>
成本费用维度
</th>
<th
colspan="5"
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%)] dark:border-[hsl(240deg_3.7%_22%)] bg-emerald-50/50 dark:bg-[hsl(142deg_71.8%_29%)] p-3 text-center text-emerald-700 dark:text-emerald-200"
>
盈利分析维度
@@ -203,6 +203,9 @@ const cellRoi = (v: number | null | undefined) =>
实际销售额
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-black text-amber-700 dark:text-amber-400">
<OverviewColumnHint :title="storeOverviewHints.gmv">GMV</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.orderCount">单量</OverviewColumnHint>
</th>
@@ -220,7 +223,7 @@ const cellRoi = (v: number | null | undefined) =>
<OverviewColumnHint :title="storeOverviewHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="storeOverviewHints.totalCost">总成本</OverviewColumnHint>
<OverviewColumnHint :title="storeOverviewHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-rose-600 dark:text-rose-400">
<OverviewColumnHint :title="storeOverviewHints.refundAmount">退款金额</OverviewColumnHint>
@@ -235,9 +238,12 @@ const cellRoi = (v: number | null | undefined) =>
<OverviewColumnHint :title="storeOverviewHints.feeRatioShopRow">费比%</OverviewColumnHint>
</th>
<!-- 盈利 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold">
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold text-emerald-700 dark:text-emerald-400">
<OverviewColumnHint :title="storeOverviewHints.grossProfit">毛利</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold">
<OverviewColumnHint :title="storeOverviewHints.totalProfitBeforeTax">
税前盈亏
税前净利
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 italic text-rose-500 dark:text-rose-400">
@@ -250,7 +256,7 @@ const cellRoi = (v: number | null | undefined) =>
</th>
<th class="border-b bg-emerald-600 dark:bg-emerald-600 px-6 py-4 font-black text-white">
<OverviewColumnHint light :title="storeOverviewHints.profitAfterTax">
税后盈亏
税后净利
</OverviewColumnHint>
</th>
</tr>
@@ -317,6 +323,9 @@ const cellRoi = (v: number | null | undefined) =>
<td class="p-6 font-black">
{{ formatAmount(shop.salesAmount) }}
</td>
<td class="p-6 font-black text-amber-700 dark:text-amber-400">
{{ formatAmount(shop.gmv) }}
</td>
<td class="p-6 font-medium">
{{ formatIntCell(shop.orderCount) }}
</td>
@@ -334,7 +343,7 @@ const cellRoi = (v: number | null | undefined) =>
{{ cellMoney(shop.otherCost) }}
</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">
{{ cellMoney(shop.totalCost) }}
{{ cellMoney(shop.orderCost) }}
</td>
<td class="p-6 font-bold text-rose-600 dark:text-rose-400">
{{ cellMoney(shop.refundAmount) }}
@@ -353,6 +362,9 @@ const cellRoi = (v: number | null | undefined) =>
}}
</td>
<!-- 盈利 -->
<td class="p-6 font-bold text-emerald-700 dark:text-emerald-400">
{{ cellMoney(shop.grossProfit) }}
</td>
<td class="p-6 font-bold">
{{ cellMoney(shop.totalProfitBeforeTax) }}
</td>
@@ -367,7 +379,7 @@ const cellRoi = (v: number | null | undefined) =>
</td>
</tr>
<tr v-if="!shopSummary?.shops?.length">
<td :colspan="shopExportMode ? 22 : 21" class="p-8 text-center text-gray-400">
<td :colspan="shopExportMode ? 24 : 23" class="p-8 text-center text-gray-400">
暂无数据
</td>
</tr>
@@ -400,6 +412,7 @@ const cellRoi = (v: number | null | undefined) =>
</td>
<!-- 规模 -->
<td class="p-6">{{ cellMoney(shopSummary?.total?.salesAmount) }}</td>
<td class="p-6 text-amber-700 dark:text-amber-400">{{ cellMoney(shopSummary?.total?.gmv) }}</td>
<td class="p-6">{{ formatIntCell(shopSummary?.total?.orderCount) }}</td>
<td class="p-6">
{{ cellMoney(shopSummary?.total?.averageOrderValue) }}
@@ -408,12 +421,13 @@ const cellRoi = (v: number | null | undefined) =>
<td class="p-6">{{ cellMoney(shopSummary?.total?.productCost) }}</td>
<td class="p-6">{{ cellMoney(shopSummary?.total?.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(shopSummary?.total?.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(shopSummary?.total?.totalCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(shopSummary?.total?.orderCost) }}</td>
<td class="p-6 text-rose-600 dark:text-rose-400">{{ cellMoney(shopSummary?.total?.refundAmount) }}</td>
<td class="p-6">{{ cellMoney(shopSummary?.total?.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoney(shopSummary?.total?.brushFee) }}</td>
<td class="p-6 text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ shopSummary?.total?.feeRatio !== undefined ? formatFeeRatioPercent(shopSummary?.total?.feeRatio) : '-' }}</td>
<!-- 盈利 -->
<td class="p-6 text-emerald-700 dark:text-emerald-400">{{ cellMoney(shopSummary?.total?.grossProfit) }}</td>
<td class="p-6">{{ cellMoney(shopSummary?.total?.totalProfitBeforeTax) }}</td>
<td class="p-6 italic text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoney(shopSummary?.total?.salesTaxAmount) }}</td>
<td class="p-6 text-indigo-700 dark:text-indigo-400">{{ cellRoi(shopSummary?.total?.roi) }}</td>
@@ -446,7 +460,7 @@ thead {
z-index: 20;
}
/* 最后一列(税后盈亏)固定在右侧 */
/* 最后一列(税后净利)固定在右侧 */
thead tr:last-child th:last-child,
tbody td:last-child:not([colspan]),
tfoot td:last-child:not([colspan]) {
@@ -12,17 +12,19 @@ function dimRowToShopSummary(row: WorkbenchVO.DimRow): CompanyOverviewVO.ShopSum
const refundAmount = yuanField(row.refundYuan);
const grossYuan = yuanField(row.grossProfitYuan);
const profitAfterTax = yuanField(row.netProfitYuan);
const totalCost = Math.max(0, salesAmount - refundAmount - grossYuan);
const orderCost = Math.max(0, salesAmount - refundAmount - grossYuan);
const shopId = Number(row.key);
return {
shopId: Number.isFinite(shopId) ? shopId : 0,
shopName: row.name,
salesAmount,
gmv: 0,
refundAmount,
totalCost,
productCost: totalCost,
orderCost,
productCost: orderCost,
shippingCost: 0,
otherCost: 0,
grossProfit: grossYuan,
totalProfitBeforeTax: grossYuan,
profitAfterTax,
};
@@ -46,16 +48,19 @@ function aggregateShopTotal(
targetAmount: sum('targetAmount'),
salesAmountAchievementRate: sum('salesAmountAchievementRate'),
salesAmount,
gmv: sum('gmv'),
orderCount: sum('orderCount'),
averageOrderValue,
productCost: sum('productCost'),
shippingCost: sum('shippingCost'),
otherCost: sum('otherCost'),
totalCost: sum('totalCost'),
orderCost: sum('orderCost'),
refundAmount: sum('refundAmount'),
totalPromotionFee,
brushFee: sum('brushFee'),
feeRatio,
gmv: 0,
grossProfit: sum('grossProfit'),
totalProfitBeforeTax: sum('totalProfitBeforeTax'),
salesTaxAmount: sum('salesTaxAmount'),
roi: totalPromotionFee ? salesAmount / totalPromotionFee : 0,
@@ -77,7 +82,7 @@ function dimRowToCategorySummary(
const refundAmount = yuanField(row.refundYuan);
const grossYuan = yuanField(row.grossProfitYuan);
const profitAfterTax = yuanField(row.netProfitYuan);
const totalCost = Math.max(0, salesAmount - refundAmount - grossYuan);
const orderCost = Math.max(0, salesAmount - refundAmount - grossYuan);
const rawId = Number(row.key);
const categoryId =
row.key === '0' || !Number.isFinite(rawId) ? undefined : rawId;
@@ -85,11 +90,13 @@ function dimRowToCategorySummary(
categoryId,
categoryName: row.name,
salesAmount,
gmv: 0,
refundAmount,
totalCost,
productCost: totalCost,
orderCost,
productCost: orderCost,
shippingCost: 0,
otherCost: 0,
grossProfit: grossYuan,
totalProfitBeforeTax: grossYuan,
profitAfterTax,
};
@@ -108,16 +115,19 @@ function aggregateCategoryTotal(
return {
categoryName: '合计',
salesAmount,
gmv: sum('gmv'),
orderCount: sum('orderCount'),
averageOrderValue,
productCost: sum('productCost'),
shippingCost: sum('shippingCost'),
otherCost: sum('otherCost'),
totalCost: sum('totalCost'),
orderCost: sum('orderCost'),
refundAmount: sum('refundAmount'),
totalPromotionFee,
brushFee: sum('brushFee'),
feeRatio,
gmv: 0,
grossProfit: sum('grossProfit'),
totalProfitBeforeTax: sum('totalProfitBeforeTax'),
salesTaxAmount: sum('salesTaxAmount'),
roi: totalPromotionFee ? salesAmount / totalPromotionFee : 0,
@@ -139,17 +149,19 @@ function dimRowToPlatformSummary(
const refundAmount = yuanField(row.refundYuan);
const grossYuan = yuanField(row.grossProfitYuan);
const profitAfterTax = yuanField(row.netProfitYuan);
const totalCost = Math.max(0, salesAmount - refundAmount - grossYuan);
const orderCost = Math.max(0, salesAmount - refundAmount - grossYuan);
const platformId = Number(row.key);
return {
platformId: Number.isFinite(platformId) ? platformId : 0,
platformName: row.name,
salesAmount,
gmv: 0,
refundAmount,
totalCost,
productCost: totalCost,
orderCost,
productCost: orderCost,
shippingCost: 0,
otherCost: 0,
grossProfit: grossYuan,
totalProfitBeforeTax: grossYuan,
profitAfterTax,
};
@@ -173,16 +185,19 @@ function aggregatePlatformTotal(
targetAmount: sum('targetAmount'),
salesAmountAchievementRate: sum('salesAmountAchievementRate'),
salesAmount,
gmv: sum('gmv'),
orderCount: sum('orderCount'),
averageOrderValue,
productCost: sum('productCost'),
shippingCost: sum('shippingCost'),
otherCost: sum('otherCost'),
totalCost: sum('totalCost'),
orderCost: sum('orderCost'),
refundAmount: sum('refundAmount'),
totalPromotionFee,
brushFee: sum('brushFee'),
feeRatio,
gmv: 0,
grossProfit: sum('grossProfit'),
totalProfitBeforeTax: sum('totalProfitBeforeTax'),
salesTaxAmount: sum('salesTaxAmount'),
roi: totalPromotionFee ? salesAmount / totalPromotionFee : 0,
@@ -21,7 +21,7 @@ interface SpecData {
productCost: number;
shippingCost: number;
otherCost: number;
totalCost?: number;
orderCost?: number;
refundAmount: number;
promotionFee: number;
feeRatio: number;
@@ -33,7 +33,7 @@ interface SpecData {
interface Props {
data: SpecData[];
/** 后端合计行(含 totalCost),优先展示 */
/** 后端合计行(含 orderCost),优先展示 */
footerTotal?: ProductOverviewVO.SpecSummaryTotal | null;
taxRate?: number;
}
@@ -78,7 +78,7 @@ const computedFooter = computed(() => {
productCost: 0,
shippingCost: 0,
otherCost: 0,
totalCost: 0,
orderCost: 0,
refundAmount: 0,
promotionFee: 0,
feeRatio: 0,
@@ -95,9 +95,9 @@ const computedFooter = computed(() => {
total.shippingCost += item.shippingCost || 0;
total.otherCost += item.otherCost || 0;
const lineTotalCost =
item.totalCost ??
item.orderCost ??
(item.productCost || 0) + (item.shippingCost || 0) + (item.otherCost || 0);
total.totalCost = (total.totalCost || 0) + lineTotalCost;
total.orderCost = (total.orderCost || 0) + lineTotalCost;
total.refundAmount += item.refundAmount || 0;
total.promotionFee += item.promotionFee || 0;
total.profitBeforeTax += item.profitBeforeTax || 0;
@@ -107,7 +107,7 @@ const computedFooter = computed(() => {
if (total.salesAmount > 0) {
total.averageOrderValue = total.salesAmount / total.orderCount;
total.feeRatio = (total.promotionFee / total.salesAmount) * 100;
const costBase = total.totalCost ?? total.productCost + total.shippingCost + total.otherCost;
const costBase = total.orderCost ?? total.productCost + total.shippingCost + total.otherCost;
total.roi =
costBase + total.promotionFee > 0
? (total.profitAfterTax / (costBase + total.promotionFee)) * 100
@@ -191,7 +191,7 @@ const footerRow = computed(() => props.footerTotal ?? computedFooter.value);
<OverviewColumnHint :title="overviewTableHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="overviewTableHints.totalCost">总成本</OverviewColumnHint>
<OverviewColumnHint :title="overviewTableHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3 font-bold text-rose-600 dark:text-rose-400">
<OverviewColumnHint :title="overviewTableHints.refundAmount">退款金额</OverviewColumnHint>
@@ -244,7 +244,7 @@ const footerRow = computed(() => props.footerTotal ?? computedFooter.value);
<td class="p-5">{{ cellMoney(item.shippingCost) }}</td>
<td class="p-5">{{ cellMoney(item.otherCost) }}</td>
<td class="p-5 font-bold text-orange-800 dark:text-orange-300">
{{ cellMoney(item.totalCost) }}
{{ cellMoney(item.orderCost) }}
</td>
<td class="p-5 font-bold text-rose-600 dark:text-rose-400">
{{ cellMoney(item.refundAmount) }}
@@ -279,7 +279,7 @@ const footerRow = computed(() => props.footerTotal ?? computedFooter.value);
<td class="p-5">{{ formatAmount(footerRow.shippingCost) }}</td>
<td class="p-5">{{ formatAmount(footerRow.otherCost) }}</td>
<td class="p-5 font-bold text-orange-800 dark:text-orange-300">
{{ footerRow.totalCost != null ? formatAmount(footerRow.totalCost) : formatAmount((footerRow.productCost || 0) + (footerRow.shippingCost || 0) + (footerRow.otherCost || 0)) }}
{{ footerRow.orderCost != null ? formatAmount(footerRow.orderCost) : formatAmount((footerRow.productCost || 0) + (footerRow.shippingCost || 0) + (footerRow.otherCost || 0)) }}
</td>
<td class="p-5 text-rose-600 dark:text-rose-400">{{ formatAmount(footerRow.refundAmount) }}</td>
<td class="p-5">{{ formatAmount(footerRow.promotionFee) }}</td>
@@ -149,7 +149,7 @@ const cellMoneyApi = (v: number | null | undefined) =>
<OverviewColumnHint :title="overviewTableHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-orange-800 dark:text-orange-300 dark:bg-[hsl(24deg_9.8%_15%/50%)]">
<OverviewColumnHint :title="overviewTableHints.totalCost">总成本</OverviewColumnHint>
<OverviewColumnHint :title="overviewTableHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-rose-600 dark:bg-[hsl(24deg_9.8%_15%/50%)] dark:text-rose-400">
<OverviewColumnHint :title="overviewTableHints.refundAmount">退款金额</OverviewColumnHint>
@@ -212,7 +212,7 @@ const cellMoneyApi = (v: number | null | undefined) =>
<td class="border-l dark:border-l-[hsl(240deg_3.7%_22%)] p-6 text-slate-600 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoneyApi(cat.productCost) }}</td>
<td class="p-6 text-slate-600 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoneyApi(cat.shippingCost) }}</td>
<td class="p-6 text-slate-600 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoneyApi(cat.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoneyApi(cat.totalCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoneyApi(cat.orderCost) }}</td>
<td class="border-l dark:border-l-[hsl(240deg_3.7%_22%)] p-6 font-bold text-rose-600 dark:text-rose-400">{{ cellMoneyApi(cat.refundAmount) }}</td>
<td class="p-6 text-amber-600 dark:text-amber-400">{{ cellMoneyApi(cat.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoneyApi(cat.brushFee) }}</td>
@@ -247,7 +247,7 @@ const cellMoneyApi = (v: number | null | undefined) =>
<td class="p-6">{{ cellMoneyApi(props.data.categoryOverview.total.productCost) }}</td>
<td class="p-6">{{ cellMoneyApi(props.data.categoryOverview.total.shippingCost) }}</td>
<td class="p-6">{{ cellMoneyApi(props.data.categoryOverview.total.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoneyApi(props.data.categoryOverview.total.totalCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoneyApi(props.data.categoryOverview.total.orderCost) }}</td>
<td class="p-6 text-rose-600 dark:text-rose-400">{{ cellMoneyApi(props.data.categoryOverview.total.refundAmount) }}</td>
<td class="p-6">{{ cellMoneyApi(props.data.categoryOverview.total.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoneyApi(props.data.categoryOverview.total.brushFee) }}</td>
@@ -173,7 +173,7 @@ function goToProductOverview(productId: number) {
<OverviewColumnHint :title="overviewTableHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="overviewTableHints.totalCost">总成本</OverviewColumnHint>
<OverviewColumnHint :title="overviewTableHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 text-rose-600">
<OverviewColumnHint :title="overviewTableHints.refundAmount">退款金额</OverviewColumnHint>
@@ -235,7 +235,7 @@ function goToProductOverview(productId: number) {
<td class="px-6 py-4">{{ cellMoneyApi(product.shippingCost) }}</td>
<td class="px-6 py-4">{{ cellMoneyApi(product.otherCost) }}</td>
<td class="px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
{{ cellMoneyApi(product.totalCost) }}
{{ cellMoneyApi(product.orderCost) }}
</td>
<td class="px-6 py-4 font-bold text-rose-500 dark:text-rose-400">
{{ cellMoneyApi(product.refundAmount) }}
@@ -278,7 +278,7 @@ function goToProductOverview(productId: number) {
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.productCost) }}</td>
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.shippingCost) }}</td>
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.otherCost) }}</td>
<td class="sticky bottom-0 bg-slate-100 font-bold text-orange-800 dark:text-orange-300 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.totalCost) }}</td>
<td class="sticky bottom-0 bg-slate-100 font-bold text-orange-800 dark:text-orange-300 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.orderCost) }}</td>
<td class="sticky bottom-0 bg-slate-100 text-rose-500 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-rose-400 px-6 py-4">{{ cellMoneyApi(data.productOverview.total.refundAmount) }}</td>
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.totalPromotionFee) }}</td>
<td class="sticky bottom-0 bg-slate-100 text-amber-500 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-amber-400 px-6 py-4">{{ cellMoneyApi(data.productOverview.total.brushFee) }}</td>