feat: 工作台增加SKU汇总表并支持跳转SKU概览

This commit is contained in:
2026-09-05 22:29:27 +08:00
parent ebca4d093a
commit dc864ea57c
32 changed files with 1896 additions and 22 deletions
@@ -0,0 +1,8 @@
-- SKU 分析模块权限:bi:sku / bi:sku:overview
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3732, (SELECT id FROM `sys_permission` WHERE `code` = 'bi' LIMIT 1), 'bi:sku', 'SKU分析', 'module', 1, '', 32
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3732 OR `code` = 'bi:sku');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3733, (SELECT id FROM `sys_permission` WHERE `code` = 'bi:sku' LIMIT 1), 'bi:sku:overview', 'SKU概览', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3733 OR `code` = 'bi:sku:overview');
@@ -0,0 +1,4 @@
-- SKU 概览嵌入页菜单(hideInMenu,由商品概览/工作台跳转打开)
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 55, (SELECT id FROM `sys_menu` WHERE `id` = 6 OR `name` = '电商页面' LIMIT 1), 0, 'SKU概览', 'SkuOverview', 'SKU概览', '/ec/sku/overview/:id', '/ec/sku/overview/index', '', 'lucide:boxes', 'embedded', 0, 1, 1, 6
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 55 OR `name` = 'SKU概览' OR `route_name` = 'SkuOverview');
@@ -55,6 +55,13 @@ public class BiOrderStatQueryService {
return repository.listSkuDocs(companyId, productId, shopIds, start, end);
}
/** 按 SKU 主键拉区间日文档(SKU 概览)。 */
public List<BiOrderStatDailySkuDoc> listSkuDocsBySkuId(Long companyId, Long productSkuId,
List<Long> shopIds,
LocalDate start, LocalDate end) {
return repository.listSkuDocsBySkuId(companyId, productSkuId, shopIds, start, end);
}
/** 商品日文档按日历日合并(单商品趋势)。 */
public List<OverviewAggRows.DailyRow> toDailyRowsFromProductDocs(
List<BiOrderStatDailyProductDoc> productDocs) {
@@ -72,6 +79,22 @@ public class BiOrderStatQueryService {
return new ArrayList<>(byDay.values());
}
/** SKU 日文档按日历日合并(单 SKU 趋势)。 */
public List<OverviewAggRows.DailyRow> toDailyRowsFromSkuDocs(List<BiOrderStatDailySkuDoc> skuDocs) {
Map<LocalDate, OverviewAggRows.DailyRow> byDay = new HashMap<>();
for (BiOrderStatDailySkuDoc doc : skuDocs) {
if (doc == null || doc.getStatDate() == null) {
continue;
}
OverviewAggRows.DailyRow row = byDay.computeIfAbsent(doc.getStatDate(), d -> emptyDaily(d));
addDealRefundCost(row,
doc.getDealAmount(), doc.getDealOrderCount(),
doc.getRefundAmount(), doc.getRefundOrderCount(),
doc.getProductCost(), doc.getFreightCost(), doc.getOtherCost());
}
return new ArrayList<>(byDay.values());
}
/** SKU 日文档按 productSkuId 合并区间。 */
public List<SkuPeriodMetrics> sumSkuDocsBySku(List<BiOrderStatDailySkuDoc> skuDocs) {
Map<Long, SkuPeriodMetrics> merged = new HashMap<>();
@@ -122,6 +145,56 @@ public class BiOrderStatQueryService {
return new ArrayList<>(merged.values());
}
/**
* SKU 日文档按 (shopId, productSkuId) 合并区间,供工作台 SKU 汇总表。
* 行上净销售三件套 = 成交 − 退款。
*/
public List<OverviewAggRows.ShopSkuRow> toShopSkuRows(List<BiOrderStatDailySkuDoc> docs) {
Map<String, OverviewAggRows.ShopSkuRow> merged = new HashMap<>();
for (BiOrderStatDailySkuDoc doc : docs) {
if (doc == null || doc.getShopId() == null) {
continue;
}
long skuId = doc.getProductSkuId() != null ? doc.getProductSkuId() : 0L;
long productId = doc.getProductId() != null ? doc.getProductId() : 0L;
String key = doc.getShopId() + ":" + skuId;
OverviewAggRows.ShopSkuRow row = merged.computeIfAbsent(key, k -> {
OverviewAggRows.ShopSkuRow r = new OverviewAggRows.ShopSkuRow();
r.setShopId(doc.getShopId());
r.setProductId(productId);
r.setProductSkuId(skuId);
r.setSalesAmount(BigDecimal.ZERO);
r.setOrderCount(0L);
r.setSalesQuantitySum(0L);
r.setRefundAmount(BigDecimal.ZERO);
r.setRefundOrderCount(0L);
r.setRefundQuantitySum(0L);
r.setProductCost(BigDecimal.ZERO);
r.setFreightCost(BigDecimal.ZERO);
r.setOtherCost(BigDecimal.ZERO);
r.setDealAmount(BigDecimal.ZERO);
r.setDealOrderCount(0L);
r.setDealQuantitySum(0L);
return r;
});
// 同一 SKU 跨店合并时保留非 0 的 productId
if ((row.getProductId() == null || row.getProductId() <= 0) && productId > 0) {
row.setProductId(productId);
}
row.setDealAmount(nz(row.getDealAmount()).add(nz(doc.getDealAmount())));
row.setDealOrderCount(nzLong(row.getDealOrderCount()) + nzInt(doc.getDealOrderCount()));
row.setDealQuantitySum(nzLong(row.getDealQuantitySum()) + nzInt(doc.getDealQuantitySum()));
row.setRefundAmount(nz(row.getRefundAmount()).add(nz(doc.getRefundAmount())));
row.setRefundOrderCount(nzLong(row.getRefundOrderCount()) + nzInt(doc.getRefundOrderCount()));
row.setRefundQuantitySum(nzLong(row.getRefundQuantitySum()) + nzInt(doc.getRefundQuantitySum()));
row.setProductCost(nz(row.getProductCost()).add(nz(doc.getProductCost())));
row.setFreightCost(nz(row.getFreightCost()).add(nz(doc.getFreightCost())));
row.setOtherCost(nz(row.getOtherCost()).add(nz(doc.getOtherCost())));
fillNetSalesSku(row);
}
return new ArrayList<>(merged.values());
}
/**
* SKU 区间指标。{@code salesAmount}/{@code salesOrderCount}/{@code salesQuantitySum} 为净销售三件套(成交−退款)。
*/
@@ -335,6 +408,16 @@ public class BiOrderStatQueryService {
nzLong(row.getRefundQuantitySum())));
}
private static void fillNetSalesSku(OverviewAggRows.ShopSkuRow row) {
row.setSalesAmount(netAmount(row.getDealAmount(), row.getRefundAmount()));
row.setOrderCount(netCountLong(
nzLong(row.getDealOrderCount()),
nzLong(row.getRefundOrderCount())));
row.setSalesQuantitySum(netCountLong(
nzLong(row.getDealQuantitySum()),
nzLong(row.getRefundQuantitySum())));
}
private static BigDecimal netAmount(BigDecimal deal, BigDecimal refund) {
return nz(deal).subtract(nz(refund));
}
@@ -73,17 +73,40 @@ public class BiOrderStatDailyRepository {
}
/**
* 区间内 SKU 日文档。{@code productId} 必填;
* 区间内 SKU 日文档。
* {@code productId} 为空时不按商品过滤(公司/店铺级 SKU 汇总);
* {@code shopIds} 为空时不按店过滤。
*/
public List<BiOrderStatDailySkuDoc> listSkuDocs(Long companyId, Long productId,
List<Long> shopIds,
LocalDate start, LocalDate end) {
if (companyId == null || productId == null || start == null || end == null) {
if (companyId == null || start == null || end == null) {
return List.of();
}
Criteria c = Criteria.where("companyId").is(companyId)
.and("productId").is(productId)
.and("statDate").gte(start).lte(end);
if (productId != null) {
c = c.and("productId").is(productId);
}
if (shopIds != null && !shopIds.isEmpty()) {
c = c.and("shopId").in(shopIds);
}
return mongoTemplate.find(Query.query(c), BiOrderStatDailySkuDoc.class);
}
/**
* 按内部 SKU 主键拉区间日文档(SKU 概览)。
* {@code shopIds} 为空时不按店过滤。
*/
public List<BiOrderStatDailySkuDoc> listSkuDocsBySkuId(Long companyId, Long productSkuId,
List<Long> shopIds,
LocalDate start, LocalDate end) {
if (companyId == null || productSkuId == null || productSkuId <= 0
|| start == null || end == null) {
return List.of();
}
Criteria c = Criteria.where("companyId").is(companyId)
.and("productSkuId").is(productSkuId)
.and("statDate").gte(start).lte(end);
if (shopIds != null && !shopIds.isEmpty()) {
c = c.and("shopId").in(shopIds);
@@ -36,6 +36,28 @@ public final class OverviewAggRows {
private Long dealQuantitySum;
}
/**
* 店铺×SKU 区间行(工作台 SKU 汇总表);净销售三件套同 {@link ShopProductRow}。
*/
@Data
public static class ShopSkuRow {
private Long shopId;
private Long productId;
private Long productSkuId;
private BigDecimal salesAmount;
private Long orderCount;
private Long salesQuantitySum;
private BigDecimal refundAmount;
private Long refundOrderCount;
private Long refundQuantitySum;
private BigDecimal productCost;
private BigDecimal freightCost;
private BigDecimal otherCost;
private BigDecimal dealAmount;
private Long dealOrderCount;
private Long dealQuantitySum;
}
@Data
public static class DailyRow {
private LocalDate statDate;
@@ -117,6 +117,8 @@ public class CompanyOverviewVO {
private PlatformOverview platformTable;
private CategoryOverview categoryTable;
private CategoryOverview productTable;
/** SKU 汇总(复用 CategoryOverview;categoryId=skuId,categoryName=sku 名) */
private CategoryOverview skuTable;
}
/**
@@ -14,7 +14,24 @@ import java.util.List;
public interface CompanyOverviewService {
/**
* 基于 Mongo/SQL 聚合行构建工作台底部四表。
* 基于 Mongo/SQL 聚合行构建工作台底部汇总表(不含 SKU 表)。
*/
default CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg(
BigDecimal taxRate,
Long companyId,
List<ShopPO> shops,
List<OverviewAggRows.ShopProductRow> orderRows,
List<OverviewAggRows.PromotionRow> promotionRows,
List<OverviewAggRows.BrushRow> brushRows,
LocalDate startDate,
LocalDate endDate) {
return buildWorkbenchSummaryTablesFromAgg(
taxRate, companyId, shops, orderRows, promotionRows, brushRows,
startDate, endDate, List.of());
}
/**
* 基于商品行 + 可选 SKU 行构建工作台底部汇总表(含 skuTable)。
*/
CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg(
BigDecimal taxRate,
@@ -24,5 +41,6 @@ public interface CompanyOverviewService {
List<OverviewAggRows.PromotionRow> promotionRows,
List<OverviewAggRows.BrushRow> brushRows,
LocalDate startDate,
LocalDate endDate);
LocalDate endDate,
List<OverviewAggRows.ShopSkuRow> skuRows);
}
@@ -13,6 +13,8 @@ import top.xyquan.ecomdmbbackend.modules.ec.product.category.model.po.CategoryPO
import top.xyquan.ecomdmbbackend.modules.ec.product.category.service.CategoryService;
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
import java.math.BigDecimal;
import java.math.RoundingMode;
@@ -36,14 +38,17 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
private final ProductMapper productMapper;
private final ProductSkuMapper productSkuMapper;
private final CategoryService categoryService;
public CompanyOverviewServiceImpl(
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
ProductMapper productMapper,
ProductSkuMapper productSkuMapper,
CategoryService categoryService) {
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
this.productMapper = productMapper;
this.productSkuMapper = productSkuMapper;
this.categoryService = categoryService;
}
@@ -325,6 +330,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
return total;
}
@Override
public CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg(
BigDecimal taxRate,
Long companyId,
@@ -333,19 +339,22 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
List<OverviewAggRows.PromotionRow> promotionRows,
List<OverviewAggRows.BrushRow> brushRows,
LocalDate startDate,
LocalDate endDate) {
LocalDate endDate,
List<OverviewAggRows.ShopSkuRow> skuRows) {
synchronized (this) {
BigDecimal saved = this.taxRate;
try {
this.taxRate = taxRate != null ? taxRate : DEFAULT_TAX_RATE;
return buildWorkbenchTablesFromAggInternal(companyId, shops, orderRows, promotionRows, brushRows, startDate, endDate);
return buildWorkbenchTablesFromAggInternal(
companyId, shops, orderRows, promotionRows, brushRows,
startDate, endDate, skuRows != null ? skuRows : List.of());
} finally {
this.taxRate = saved;
}
}
}
/** SQL 聚合行 → 四表(推广/刷单分摊规则与明细版一致) */
/** 聚合行 → 五表(推广/刷单分摊规则与明细版一致) */
private CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchTablesFromAggInternal(
Long companyId,
List<ShopPO> shops,
@@ -353,7 +362,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
List<OverviewAggRows.PromotionRow> promotionRows,
List<OverviewAggRows.BrushRow> brushRows,
LocalDate startDate,
LocalDate endDate) {
LocalDate endDate,
List<OverviewAggRows.ShopSkuRow> skuRows) {
Map<Long, AggMetrics> byShop = new HashMap<>();
Map<Long, AggMetrics> byCategory = new HashMap<>();
@@ -408,9 +418,83 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId));
bundle.setProductTable(buildProductOverviewFromAgg(byProduct, productSalesByShop, brushByShop,
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId));
bundle.setSkuTable(buildSkuOverviewFromAgg(skuRows, bundle.getProductTable(), brushByShop));
return bundle;
}
/**
* SKU 汇总:订单指标来自 SKU 日汇聚;推广按父商品推广×SKU 净销占比分摊;刷单按店净销占比。
*/
private CompanyOverviewVO.CategoryOverview buildSkuOverviewFromAgg(
List<OverviewAggRows.ShopSkuRow> skuRows,
CompanyOverviewVO.CategoryOverview productTable,
Map<Long, BigDecimal> brushByShop) {
if (skuRows == null || skuRows.isEmpty()) {
CompanyOverviewVO.CategoryOverview empty = new CompanyOverviewVO.CategoryOverview();
empty.setCategories(List.of());
empty.setTotal(computeCategoryTotal(List.of()));
return empty;
}
Map<Long, BigDecimal> productPromoById = new HashMap<>();
if (productTable != null && productTable.getCategories() != null) {
for (CompanyOverviewVO.CategorySummary p : productTable.getCategories()) {
if (p.getCategoryId() == null || p.getCategoryId() <= 0) {
continue;
}
productPromoById.put(p.getCategoryId(), nz(p.getTotalPromotionFee()));
}
}
Map<Long, AggMetrics> bySku = new HashMap<>();
Map<Long, Long> skuProductId = new HashMap<>();
Map<Long, Map<Long, BigDecimal>> skuSalesByShop = new HashMap<>();
for (OverviewAggRows.ShopSkuRow row : skuRows) {
long skuId = row.getProductSkuId() != null ? row.getProductSkuId() : 0L;
long shopId = row.getShopId() != null ? row.getShopId() : 0L;
long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : 0L;
bySku.merge(skuId, AggMetrics.from(row), AggMetrics::merge);
if (productId > 0) {
skuProductId.putIfAbsent(skuId, productId);
} else if (!skuProductId.containsKey(skuId)) {
skuProductId.put(skuId, 0L);
}
BigDecimal sales = nz(row.getSalesAmount());
skuSalesByShop.computeIfAbsent(skuId, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add);
}
// 同商品下 SKU 净销合计,用于推广二次分摊
Map<Long, BigDecimal> salesByProductFromSku = new HashMap<>();
for (Map.Entry<Long, AggMetrics> e : bySku.entrySet()) {
Long pid = skuProductId.getOrDefault(e.getKey(), 0L);
if (pid != null && pid > 0) {
salesByProductFromSku.merge(pid, e.getValue().sales, BigDecimal::add);
}
}
Map<Long, String> skuNames = loadSkuNameMap(bySku.keySet());
List<CompanyOverviewVO.CategorySummary> list = new ArrayList<>();
for (Map.Entry<Long, AggMetrics> e : bySku.entrySet()) {
Long skuId = e.getKey();
AggMetrics m = e.getValue();
Long productId = skuProductId.getOrDefault(skuId, 0L);
BigDecimal productPromo = productPromoById.getOrDefault(productId, BigDecimal.ZERO);
BigDecimal productSkuSalesPool = salesByProductFromSku.getOrDefault(productId, BigDecimal.ZERO);
BigDecimal promo = productSkuSalesPool.compareTo(BigDecimal.ZERO) > 0
? productPromo.multiply(m.sales).divide(productSkuSalesPool, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal brush = allocBrushShare(skuSalesByShop.get(skuId), brushByShop);
String name = skuId <= 0 ? "未绑定规格" : skuNames.getOrDefault(skuId, "规格" + skuId);
list.add(toCategorySummaryFromAgg(skuId, 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.ShopOverview buildShopOverviewFromAgg(
List<ShopPO> shops, Map<Long, AggMetrics> byShop, Map<Long, BigDecimal> promoByShop,
Map<Long, BigDecimal> brushByShop, Map<Long, List<ShopMonthlyTargetPO>> targetsByShop) {
@@ -736,6 +820,15 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
.stream().collect(Collectors.toMap(ProductPO::getId, ProductPO::getName, (a, b) -> a));
}
private Map<Long, String> loadSkuNameMap(java.util.Set<Long> skuKeys) {
List<Long> ids = skuKeys.stream().filter(id -> id != null && id > 0).distinct().toList();
if (ids.isEmpty()) {
return Map.of();
}
return productSkuMapper.selectList(new LambdaQueryWrapper<ProductSkuPO>().in(ProductSkuPO::getId, ids))
.stream().collect(Collectors.toMap(ProductSkuPO::getId, ProductSkuPO::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);
@@ -825,6 +918,23 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
return a;
}
static AggMetrics from(OverviewAggRows.ShopSkuRow row) {
AggMetrics a = new AggMetrics();
a.sales = nz(row.getSalesAmount());
a.dealAmount = nz(row.getDealAmount());
a.salesOrderCount = row.getOrderCount() != null ? row.getOrderCount().intValue() : 0;
a.dealOrderCount = row.getDealOrderCount() != null ? row.getDealOrderCount().intValue() : 0;
a.dealQuantitySum = row.getDealQuantitySum() != null ? row.getDealQuantitySum().intValue() : 0;
a.salesQuantitySum = row.getSalesQuantitySum() != null ? row.getSalesQuantitySum().intValue() : 0;
a.refund = nz(row.getRefundAmount());
a.refundOrderCount = row.getRefundOrderCount() != null ? row.getRefundOrderCount().intValue() : 0;
a.refundQuantitySum = row.getRefundQuantitySum() != null ? row.getRefundQuantitySum().intValue() : 0;
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);
@@ -0,0 +1,32 @@
package top.xyquan.ecomdmbbackend.modules.bi.skuoverview.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.bi.skuoverview.model.dto.SkuOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.bi.skuoverview.model.vo.SkuOverviewVO;
import top.xyquan.ecomdmbbackend.modules.bi.skuoverview.service.BiSkuOverviewService;
/**
* SKU 概览 API:公司下指定 SKU 的经营汇总。
*/
@RestController
@RequestMapping("/api/bi/sku")
public class BiSkuOverviewController {
private final BiSkuOverviewService biSkuOverviewService;
public BiSkuOverviewController(BiSkuOverviewService biSkuOverviewService) {
this.biSkuOverviewService = biSkuOverviewService;
}
@PostMapping("/overview")
@RequirePermission(value = "bi:sku:overview", description = "查询SKU概览", allowSuper = true)
public ApiResponse<SkuOverviewVO> overview(@Valid @RequestBody SkuOverviewQueryDTO queryDTO) {
return ApiResponse.success("获取SKU概览成功", biSkuOverviewService.getSkuOverview(queryDTO));
}
}
@@ -0,0 +1,29 @@
package top.xyquan.ecomdmbbackend.modules.bi.skuoverview.model.dto;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
/**
* SKU 概览查询参数。
*/
@Data
public class SkuOverviewQueryDTO {
@NotNull(message = "SKU ID不能为空")
private Long skuId;
@NotNull(message = "开始日期不能为空")
private LocalDate startDate;
@NotNull(message = "结束日期不能为空")
private LocalDate endDate;
/** 店铺 ID(可选;传入时仅统计该店下该 SKU) */
private Long shopId;
/** 税率(默认 0.04) */
private BigDecimal taxRate = new BigDecimal("0.04");
}
@@ -0,0 +1,65 @@
package top.xyquan.ecomdmbbackend.modules.bi.skuoverview.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchKpiItemVO;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchTrendPointVO;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
/**
* SKU 概览响应:经营 KPI/趋势与工作台同口径(精简版,无规格表)。
*/
@Data
public class SkuOverviewVO {
private Long skuId;
private String skuName;
private String skuCode;
private Long productId;
private String productName;
/** 与工作台经营概览同结构的 KPI 列表 */
private List<WorkbenchKpiItemVO> kpis;
/** 成交/净销售/利润日趋势 */
private List<WorkbenchTrendPointVO> dealTrend;
private String momCompareDateStart;
private String momCompareDateEnd;
private String yoyCompareDateStart;
private String yoyCompareDateEnd;
/** 兼容扁平 KPI 摘要 */
private BigDecimal totalSalesAmount;
private BigDecimal monthOverMonthGrowth;
private Integer totalOrderCount;
private BigDecimal averageFeeRatio;
private BigDecimal totalNetProfitAfterTax;
private BigDecimal totalTaxAmount;
private BigDecimal totalROI;
private BigDecimal totalPromotionFee;
private BigDecimal refundAmount;
private BigDecimal averageOrderValue;
private BigDecimal totalProfitBeforeTax;
/** @deprecated 使用 dealTrend */
private TrendData salesAmountTrend;
/** @deprecated 使用 dealTrend */
private TrendData orderCountTrend;
@Data
public static class TrendData {
private BigDecimal total;
private List<TrendDataItem> dailyDataList;
}
@Data
public static class TrendDataItem {
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate date;
private BigDecimal value;
}
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.bi.skuoverview.service;
import top.xyquan.ecomdmbbackend.modules.bi.skuoverview.model.dto.SkuOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.bi.skuoverview.model.vo.SkuOverviewVO;
/**
* BI SKU 概览:订单读 Mongo SKU 日汇聚,推广/刷单从父商品行按销占比分摊。
*/
public interface BiSkuOverviewService {
SkuOverviewVO getSkuOverview(SkuOverviewQueryDTO queryDTO);
}
@@ -0,0 +1,304 @@
package top.xyquan.ecomdmbbackend.modules.bi.skuoverview.service.impl;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySkuDoc;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.query.BiOrderStatQueryService;
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CompanyOverviewService;
import top.xyquan.ecomdmbbackend.modules.bi.skuoverview.model.dto.SkuOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.bi.skuoverview.model.vo.SkuOverviewVO;
import top.xyquan.ecomdmbbackend.modules.bi.skuoverview.service.BiSkuOverviewService;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchTrendPointVO;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.support.BiFinanceKpiAssembler;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.support.BiWorkbenchFeeLoader;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* SKU 概览:Mongo SKU 日汇聚 + 父商品推广/刷单按净销占比分摊后的经营 KPI。
*/
@Service
public class BiSkuOverviewServiceImpl implements BiSkuOverviewService {
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
private final CurrentUserContext currentUserContext;
private final ProductSkuMapper productSkuMapper;
private final ProductService productService;
private final ShopService shopService;
private final BiOrderStatQueryService orderStatQueryService;
private final BiWorkbenchFeeLoader feeLoader;
private final CompanyOverviewService companyOverviewService;
public BiSkuOverviewServiceImpl(CurrentUserContext currentUserContext,
ProductSkuMapper productSkuMapper,
ProductService productService,
ShopService shopService,
BiOrderStatQueryService orderStatQueryService,
BiWorkbenchFeeLoader feeLoader,
CompanyOverviewService companyOverviewService) {
this.currentUserContext = currentUserContext;
this.productSkuMapper = productSkuMapper;
this.productService = productService;
this.shopService = shopService;
this.orderStatQueryService = orderStatQueryService;
this.feeLoader = feeLoader;
this.companyOverviewService = companyOverviewService;
}
@Override
public SkuOverviewVO getSkuOverview(SkuOverviewQueryDTO queryDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
ProductSkuPO sku = productSkuMapper.selectById(queryDTO.getSkuId());
if (sku == null || !Objects.equals(sku.getCompanyId(), companyId)) {
throw new BusinessException("SKU不存在");
}
if (queryDTO.getStartDate().isAfter(queryDTO.getEndDate())) {
throw new BusinessException("开始日期不能晚于结束日期");
}
ProductPO product = sku.getProductId() != null ? productService.getById(sku.getProductId()) : null;
if (product != null && !Objects.equals(product.getCompanyId(), companyId)) {
product = null;
}
BigDecimal taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE;
LocalDate start = queryDTO.getStartDate();
LocalDate end = queryDTO.getEndDate();
Long filterShopId = queryDTO.getShopId();
if (filterShopId != null) {
ShopPO shop = shopService.getById(filterShopId);
if (shop == null || !Objects.equals(shop.getCompanyId(), companyId)) {
throw new BusinessException("店铺不存在");
}
}
List<Long> shopIdFilter = filterShopId != null ? List.of(filterShopId) : null;
Long productId = sku.getProductId();
PeriodBundle cur = loadPeriod(companyId, sku.getId(), productId, shopIdFilter, filterShopId,
start, end, taxRate);
LocalDate[] mom = BiFinanceKpiAssembler.lastMonthSameSpan(start, end);
LocalDate[] yoy = BiFinanceKpiAssembler.yoySameSpan(start, end);
PeriodBundle prev = loadPeriod(companyId, sku.getId(), productId, shopIdFilter, filterShopId,
mom[0], mom[1], taxRate);
PeriodBundle yoyBundle = loadPeriod(companyId, sku.getId(), productId, shopIdFilter, filterShopId,
yoy[0], yoy[1], taxRate);
BiFinanceKpiAssembler.Totals curT = cur.totals();
BiFinanceKpiAssembler.Totals prevT = prev.totals();
BiFinanceKpiAssembler.Totals yoyT = yoyBundle.totals();
List<WorkbenchTrendPointVO> dealTrend = BiFinanceKpiAssembler.buildTrendFromDaily(
cur.dailyRows(), start, end, curT);
SkuOverviewVO vo = new SkuOverviewVO();
vo.setSkuId(sku.getId());
vo.setSkuName(sku.getName());
vo.setSkuCode(sku.getSkuCode());
vo.setProductId(productId);
vo.setProductName(product != null ? product.getName() : null);
vo.setKpis(BiFinanceKpiAssembler.buildKpis(curT, prevT, yoyT, start, end, taxRate));
vo.setDealTrend(dealTrend);
vo.setMomCompareDateStart(mom[0].toString());
vo.setMomCompareDateEnd(mom[1].toString());
vo.setYoyCompareDateStart(yoy[0].toString());
vo.setYoyCompareDateEnd(yoy[1].toString());
fillLegacyFlatFields(vo, curT, prevT);
fillLegacyTrends(vo, dealTrend);
return vo;
}
/**
* 加载单区间:本 SKU 日汇聚指标 + 父商品推广/刷单按同商品 SKU 净销占比分摊。
*/
private PeriodBundle loadPeriod(Long companyId, Long skuId, Long productId,
List<Long> shopIdFilter, Long filterShopId,
LocalDate start, LocalDate end, BigDecimal taxRate) {
List<BiOrderStatDailySkuDoc> thisSkuDocs =
orderStatQueryService.listSkuDocsBySkuId(companyId, skuId, shopIdFilter, start, end);
List<OverviewAggRows.DailyRow> dailyRows =
orderStatQueryService.toDailyRowsFromSkuDocs(thisSkuDocs);
List<Long> shopIds;
if (filterShopId != null) {
shopIds = List.of(filterShopId);
} else {
shopIds = thisSkuDocs.stream()
.map(BiOrderStatDailySkuDoc::getShopId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
}
BiOrderStatQueryService.SkuPeriodMetrics thisMetrics = findSkuMetrics(
orderStatQueryService.sumSkuDocsBySku(thisSkuDocs), skuId);
if (shopIds.isEmpty() || thisMetrics == null) {
return new PeriodBundle(shopIds, BiFinanceKpiAssembler.Totals.empty(), dailyRows);
}
List<ShopPO> shops = shopService.listByIds(shopIds).stream()
.filter(s -> s != null && Objects.equals(s.getCompanyId(), companyId))
.collect(Collectors.toList());
if (shops.isEmpty()) {
return new PeriodBundle(shopIds, BiFinanceKpiAssembler.Totals.empty(), dailyRows);
}
Map<Long, String> platformByShopId = shops.stream()
.collect(Collectors.toMap(ShopPO::getId,
s -> s.getPlatformCode() != null ? s.getPlatformCode() : "",
(a, b) -> a));
// 同商品全部 SKU 净销合计,用于分摊推广/刷单
BigDecimal salesPool = BigDecimal.ZERO;
if (productId != null) {
List<BiOrderStatDailySkuDoc> siblingDocs =
orderStatQueryService.listSkuDocs(companyId, productId, shopIds, start, end);
salesPool = orderStatQueryService.sumSkuDocsBySku(siblingDocs).stream()
.map(BiOrderStatQueryService.SkuPeriodMetrics::salesAmount)
.map(BiFinanceKpiAssembler::nz)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
List<BiOrderStatDailyProductDoc> allProductDocs =
orderStatQueryService.listProductDocs(companyId, shopIds, start, end);
BiWorkbenchFeeLoader.FeeBundle fees = feeLoader.load(companyId, shopIds, start, end);
List<OverviewAggRows.ShopProductRow> orderRows =
orderStatQueryService.toShopProductRows(allProductDocs, platformByShopId);
CompanyOverviewVO.WorkbenchTableBundle tables =
companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
taxRate, companyId, shops, orderRows,
fees.promotionRows(), fees.brushRows(), start, end);
CompanyOverviewVO.CategorySummary productRow =
productId != null ? findProductRow(tables.getProductTable(), productId) : null;
BigDecimal productPromo = productRow != null
? BiFinanceKpiAssembler.nz(productRow.getTotalPromotionFee()) : BigDecimal.ZERO;
BigDecimal productBrush = productRow != null
? BiFinanceKpiAssembler.nz(productRow.getBrushFee()) : BigDecimal.ZERO;
BigDecimal skuSales = BiFinanceKpiAssembler.nz(thisMetrics.salesAmount());
BigDecimal sharePromo = salesPool.compareTo(BigDecimal.ZERO) > 0
? productPromo.multiply(skuSales).divide(salesPool, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal shareBrush = salesPool.compareTo(BigDecimal.ZERO) > 0
? productBrush.multiply(skuSales).divide(salesPool, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BiFinanceKpiAssembler.Totals totals = BiFinanceKpiAssembler.buildTotals(
skuSales,
BiFinanceKpiAssembler.nz(thisMetrics.refundAmount()),
BiFinanceKpiAssembler.nz(thisMetrics.productCost()),
BiFinanceKpiAssembler.nz(thisMetrics.freightCost()),
BiFinanceKpiAssembler.nz(thisMetrics.otherCost()),
sharePromo,
shareBrush,
taxRate,
thisMetrics.salesOrderCount(),
thisMetrics.salesQuantitySum(),
BiFinanceKpiAssembler.nz(thisMetrics.dealAmount()),
thisMetrics.dealOrderCount(),
thisMetrics.dealQuantitySum());
return new PeriodBundle(shopIds, totals, dailyRows);
}
private static BiOrderStatQueryService.SkuPeriodMetrics findSkuMetrics(
List<BiOrderStatQueryService.SkuPeriodMetrics> list, Long skuId) {
if (list == null || skuId == null) {
return null;
}
return list.stream()
.filter(m -> m.productSkuId() == skuId)
.findFirst()
.orElse(null);
}
private static CompanyOverviewVO.CategorySummary findProductRow(
CompanyOverviewVO.CategoryOverview table, Long productId) {
if (table == null || table.getCategories() == null || productId == null) {
return null;
}
return table.getCategories().stream()
.filter(c -> Objects.equals(c.getCategoryId(), productId))
.findFirst()
.orElse(null);
}
private void fillLegacyFlatFields(SkuOverviewVO vo,
BiFinanceKpiAssembler.Totals cur,
BiFinanceKpiAssembler.Totals prev) {
vo.setTotalSalesAmount(BiFinanceKpiAssembler.yuan2(cur.totalSales()));
vo.setTotalOrderCount(cur.orderCount());
vo.setRefundAmount(BiFinanceKpiAssembler.yuan2(cur.totalRefund()));
vo.setAverageOrderValue(BiFinanceKpiAssembler.yuan2(cur.averageOrderValue()));
vo.setTotalPromotionFee(BiFinanceKpiAssembler.yuan2(cur.promotion()));
vo.setAverageFeeRatio(cur.totalSales().compareTo(BigDecimal.ZERO) > 0
? cur.promotion().divide(cur.totalSales(), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP)
: BigDecimal.ZERO);
vo.setTotalTaxAmount(BiFinanceKpiAssembler.yuan2(cur.tax()));
vo.setTotalProfitBeforeTax(BiFinanceKpiAssembler.yuan2(
cur.grossOrder().subtract(cur.promotion()).subtract(cur.brush())));
vo.setTotalNetProfitAfterTax(BiFinanceKpiAssembler.yuan2(cur.netProfit()));
vo.setTotalROI(cur.promotion().compareTo(BigDecimal.ZERO) > 0
? cur.totalSales().divide(cur.promotion(), 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO);
vo.setMonthOverMonthGrowth(BiFinanceKpiAssembler.pctChange(cur.totalSales(), prev.totalSales()));
}
private void fillLegacyTrends(SkuOverviewVO vo, List<WorkbenchTrendPointVO> dealTrend) {
SkuOverviewVO.TrendData sales = new SkuOverviewVO.TrendData();
SkuOverviewVO.TrendData orders = new SkuOverviewVO.TrendData();
List<SkuOverviewVO.TrendDataItem> salesItems = new ArrayList<>();
List<SkuOverviewVO.TrendDataItem> orderItems = new ArrayList<>();
BigDecimal salesTotal = BigDecimal.ZERO;
BigDecimal orderTotal = BigDecimal.ZERO;
if (dealTrend != null) {
for (WorkbenchTrendPointVO p : dealTrend) {
SkuOverviewVO.TrendDataItem s = new SkuOverviewVO.TrendDataItem();
s.setDate(LocalDate.parse(p.getDate()));
s.setValue(BiFinanceKpiAssembler.nz(p.getSalesYuan()));
salesItems.add(s);
salesTotal = salesTotal.add(s.getValue());
SkuOverviewVO.TrendDataItem o = new SkuOverviewVO.TrendDataItem();
o.setDate(s.getDate());
o.setValue(BigDecimal.valueOf(p.getSalesOrderCount() != null ? p.getSalesOrderCount() : 0));
orderItems.add(o);
orderTotal = orderTotal.add(o.getValue());
}
}
sales.setDailyDataList(salesItems);
sales.setTotal(salesTotal);
orders.setDailyDataList(orderItems);
orders.setTotal(orderTotal);
vo.setSalesAmountTrend(sales);
vo.setOrderCountTrend(orders);
}
private record PeriodBundle(List<Long> shopIds,
BiFinanceKpiAssembler.Totals totals,
List<OverviewAggRows.DailyRow> dailyRows) {
}
}
@@ -115,7 +115,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
CompanyOverviewVO.WorkbenchTableBundle summaryTables = companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
ctx.taxRate(), ctx.companyId(), ctx.shops(),
agg.orderRows(), agg.promotionRows(), agg.brushRows(),
ctx.range().startDate(), ctx.range().endDate());
ctx.range().startDate(), ctx.range().endDate(), agg.skuRows());
return WorkbenchFinanceSliceVO.builder().finance(finance).summaryTables(summaryTables).build();
}
@@ -159,7 +159,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
SqlAggBundle agg = loadSqlAgg(ctx);
CompanyOverviewVO.WorkbenchTableBundle bundle = companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
taxRate, companyId, shops, agg.orderRows(), agg.promotionRows(), agg.brushRows(),
range.startDate(), range.endDate());
range.startDate(), range.endDate(), agg.skuRows());
CompanyOverviewVO.ShopSummary total = bundle.getShopTable() != null && bundle.getShopTable().getTotal() != null
? bundle.getShopTable().getTotal() : new CompanyOverviewVO.ShopSummary();
return WorkbenchPeriodCompareSliceVO.builder()
@@ -181,13 +181,13 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
return companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
ctx.taxRate(), ctx.companyId(), ctx.shops(),
List.of(), List.of(), List.of(),
ctx.range().startDate(), ctx.range().endDate());
ctx.range().startDate(), ctx.range().endDate(), List.of());
}
SqlAggBundle agg = loadSqlAgg(ctx);
return companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
ctx.taxRate(), ctx.companyId(), ctx.shops(),
agg.orderRows(), agg.promotionRows(), agg.brushRows(),
ctx.range().startDate(), ctx.range().endDate());
ctx.range().startDate(), ctx.range().endDate(), agg.skuRows());
}
private WorkbenchFinanceSliceVO emptyFinanceSlice() {
@@ -239,10 +239,13 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
ctx.companyId(), ctx.shopIds(), ctx.range().startDate(), ctx.range().endDate());
var productDocs = orderStatQueryService.listProductDocs(
ctx.companyId(), ctx.shopIds(), ctx.range().startDate(), ctx.range().endDate());
var skuDocs = orderStatQueryService.listSkuDocs(
ctx.companyId(), null, ctx.shopIds(), ctx.range().startDate(), ctx.range().endDate());
BiWorkbenchFeeLoader.FeeBundle fees = feeLoader.load(
ctx.companyId(), ctx.shopIds(), ctx.range().startDate(), ctx.range().endDate());
return new SqlAggBundle(
orderStatQueryService.toShopProductRows(productDocs, platformByShop),
orderStatQueryService.toShopSkuRows(skuDocs),
orderStatQueryService.toDailyRows(shopDocs),
fees.promotionRows(),
fees.brushRows(),
@@ -421,6 +424,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
}
private record SqlAggBundle(List<OverviewAggRows.ShopProductRow> orderRows,
List<OverviewAggRows.ShopSkuRow> skuRows,
List<OverviewAggRows.DailyRow> dailyRows,
List<OverviewAggRows.PromotionRow> promotionRows,
List<OverviewAggRows.BrushRow> brushRows,
@@ -563,6 +563,14 @@ INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status
SELECT 3731, (SELECT id FROM `sys_permission` WHERE `code` = 'bi:product' LIMIT 1), 'bi:product:overview', '商品概览', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3731 OR `code` = 'bi:product:overview');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3732, (SELECT id FROM `sys_permission` WHERE `code` = 'bi' LIMIT 1), 'bi:sku', 'SKU分析', 'module', 1, '', 32
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3732 OR `code` = 'bi:sku');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3733, (SELECT id FROM `sys_permission` WHERE `code` = 'bi:sku' LIMIT 1), 'bi:sku:overview', 'SKU概览', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3733 OR `code` = 'bi:sku:overview');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3740, (SELECT id FROM `sys_permission` WHERE `code` = 'bi' LIMIT 1), 'bi:order-stat', '订单统计', 'module', 1, '', 40
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3740 OR `code` = 'bi:order-stat');
@@ -811,6 +819,10 @@ INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title
SELECT 54, (SELECT id FROM `sys_menu` WHERE `id` = 6 OR `name` = '电商页面' LIMIT 1), 0, '品类概览', 'CategoryOverview', '品类概览', '/ec/category/overview/:id', '/ec/category/overview/index', '', 'lucide:tags', 'embedded', 0, 1, 1, 5
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 54 OR `name` = '品类概览');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 55, (SELECT id FROM `sys_menu` WHERE `id` = 6 OR `name` = '电商页面' LIMIT 1), 0, 'SKU概览', 'SkuOverview', 'SKU概览', '/ec/sku/overview/:id', '/ec/sku/overview/index', '', 'lucide:boxes', 'embedded', 0, 1, 1, 6
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 55 OR `name` = 'SKU概览' OR `route_name` = 'SkuOverview');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 44, (SELECT id FROM `sys_menu` WHERE `id` = 14006 OR `name` = '经营商品' LIMIT 1), 0, '商品类目', 'CategoryConfig', '商品类目', '/ec/product/category', '/ec/product/category/index', '', 'gg:list', 'menu', 1, 1, 1, 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 44 OR `name` = '商品类目');
@@ -75,12 +75,14 @@ export namespace CompanyOverviewVO {
categories?: CategorySummary[];
}
/** 工作台底部四张汇总表 */
/** 工作台底部汇总表 */
export interface WorkbenchTableBundle {
shopTable?: ShopOverview;
platformTable?: PlatformOverview;
categoryTable?: CategoryOverview;
productTable?: CategoryOverview;
/** SKU 汇总;categoryId=skuId */
skuTable?: CategoryOverview;
}
/** 店铺汇总行 */
@@ -0,0 +1,11 @@
import type { SkuOverviewDTO, SkuOverviewVO } from './types';
import { requestClient } from '#/api/request';
/** 获取 SKU 概览统计数据 */
export async function getSkuOverviewApi(params: SkuOverviewDTO.Query) {
return requestClient.post<SkuOverviewVO.Overview>(
'/bi/sku/overview',
params,
);
}
@@ -0,0 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1,2 @@
export type { SkuOverviewDTO } from './types.dto';
export type { SkuOverviewVO } from './types.vo';
@@ -0,0 +1,10 @@
export namespace SkuOverviewDTO {
/** SKU 概览查询参数 */
export interface Query {
skuId: number;
shopId?: number;
startDate: string;
endDate: string;
taxRate?: number;
}
}
@@ -0,0 +1,70 @@
/** SKU 概览 VO(与后端 SkuOverviewVO 对齐) */
export namespace SkuOverviewVO {
export interface KpiItem {
label: string;
value: number;
unit: string;
changePct?: number;
up?: boolean;
yoyChangePct?: number | null;
yoyUp?: boolean | null;
sub?: string;
amountYuan?: number | null;
preferWanDisplay?: boolean | null;
}
export interface TrendPoint {
date: string;
dealYuan?: number;
dealOrderCount?: number;
salesYuan?: number;
salesOrderCount?: number;
profitYuan?: number;
netProfitYuan?: number;
refundYuan?: number;
}
/** @deprecated */
export interface TrendDataItem {
date: string;
value: number;
}
/** @deprecated */
export interface TrendData {
total: number;
dailyDataList: TrendDataItem[];
}
export interface Overview {
skuId: number;
skuName?: string;
skuCode?: string;
productId?: number;
productName?: string;
kpis?: KpiItem[];
dealTrend?: TrendPoint[];
momCompareDateStart?: string | null;
momCompareDateEnd?: string | null;
yoyCompareDateStart?: string | null;
yoyCompareDateEnd?: string | null;
totalSalesAmount?: number;
monthOverMonthGrowth?: number;
totalOrderCount?: number;
averageFeeRatio?: number;
totalNetProfitAfterTax?: number;
totalTaxAmount?: number;
totalROI?: number;
totalPromotionFee?: number;
refundAmount?: number;
averageOrderValue?: number;
totalProfitBeforeTax?: number;
/** @deprecated */
salesAmountTrend?: TrendData;
/** @deprecated */
orderCountTrend?: TrendData;
}
}
@@ -712,6 +712,20 @@ function handleCategoryNavigate(categoryId: number) {
});
}
function handleSkuNavigate(skuId: number) {
if (!skuId || skuId <= 0) return;
const shopId = parseSelectedShopId();
router.push({
path: `/ec/sku/overview/${skuId}`,
query: buildOverviewRouteQuery(
dateRange.value,
shopId != null && Number.isFinite(shopId) && shopId > 0
? { shopId }
: undefined,
),
});
}
const financeTabRef = ref<InstanceType<typeof WorkbenchFinanceTab> | null>(
null,
);
@@ -1045,6 +1059,7 @@ onUnmounted(() => {
@navigate-shop="handleShopNavigate"
@navigate-platform="handlePlatformNavigate"
@navigate-category="handleCategoryNavigate"
@navigate-sku="handleSkuNavigate"
/>
</Spin>
</Tabs.TabPane>
@@ -33,11 +33,13 @@ interface Props {
headingSubtitle?: string;
/** 首列维度名称,如「品类」「商品」 */
firstColumnLabel?: string;
/** 为 true 时首列名称可点击跳转商品概览(categoryId 即商品 ID) */
/** 为首列名称可点击跳转商品概览(categoryId 即商品 ID) */
productNavigate?: boolean;
/** 为 true 时首列名称可点击跳转品类概览 */
categoryNavigate?: boolean;
columnPrefsKey?: 'category' | 'product';
/** 为 true 时首列名称可点击跳转 SKU 概览(categoryId 即 skuId) */
skuNavigate?: boolean;
columnPrefsKey?: 'category' | 'product' | 'sku';
}
interface Emits {
@@ -46,6 +48,7 @@ interface Emits {
(e: 'export'): void;
(e: 'navigate-product', productId: number): void;
(e: 'navigate-category', categoryId: number): void;
(e: 'navigate-sku', skuId: number): void;
}
const props = withDefaults(defineProps<Props>(), {
@@ -56,6 +59,7 @@ const props = withDefaults(defineProps<Props>(), {
firstColumnLabel: '品类',
productNavigate: false,
categoryNavigate: false,
skuNavigate: false,
columnPrefsKey: 'category',
});
@@ -69,7 +73,7 @@ const {
applyVisible,
resetToDefault,
} = useOverviewTableColumnPrefs(
props.columnPrefsKey as 'category' | 'product',
props.columnPrefsKey as 'category' | 'product' | 'sku',
);
const emptyColspan = computed(
@@ -357,6 +361,14 @@ const cellRoi = (v: number | null | undefined) =>
{{ cat.categoryName }}
<JumpIcon class="text-xs" />
</span>
<span
v-else-if="skuNavigate && cat.categoryId != null"
class="inline-flex cursor-pointer items-center gap-1 rounded-full bg-blue-50 px-3 py-1 text-sm font-bold text-blue-600 transition-colors hover:text-blue-300 hover:underline dark:bg-blue-900/30 dark:text-blue-400"
@click="emit('navigate-sku', cat.categoryId!)"
>
{{ cat.categoryName }}
<JumpIcon class="text-xs" />
</span>
<span
v-else
class="inline-block rounded-full bg-blue-50 px-3 py-1 text-sm font-bold text-blue-600 dark:bg-blue-900/30 dark:text-blue-400"
@@ -23,6 +23,7 @@ const props = withDefaults(
platformSummary?: CompanyOverviewVO.PlatformOverview | null;
categorySummary?: CompanyOverviewVO.CategoryOverview | null;
productSummary?: CompanyOverviewVO.CategoryOverview | null;
skuSummary?: CompanyOverviewVO.CategoryOverview | null;
}>(),
{
taxRate: 0.04,
@@ -34,8 +35,9 @@ const emit = defineEmits<{
(e: 'navigate-shop', shopId: number): void;
(e: 'navigate-platform', platformCode: string): void;
(e: 'navigate-category', categoryId: number): void;
(e: 'navigate-sku', skuId: number): void;
}>();
const activeMode = ref<'category' | 'platform' | 'product' | 'shop'>('shop');
const activeMode = ref<'category' | 'platform' | 'product' | 'shop' | 'sku'>('shop');
const shopExportMode = ref(false);
const selectedExportShopIds = ref<number[]>([]);
@@ -45,6 +47,8 @@ const categoryExportMode = ref(false);
const selectedExportCategoryIds = ref<number[]>([]);
const productExportMode = ref(false);
const selectedExportProductIds = ref<number[]>([]);
const skuExportMode = ref(false);
const selectedExportSkuIds = ref<number[]>([]);
const exportLoading = ref(false);
@@ -53,6 +57,7 @@ const modeOptions = [
{ label: '平台汇总', value: 'platform' },
{ label: '品类汇总', value: 'category' },
{ label: '商品汇总', value: 'product' },
{ label: 'SKU汇总', value: 'sku' },
];
function dateSegmentForFilename(): string {
@@ -173,6 +178,10 @@ async function handleProductExport() {
}
}
function handleSkuExport() {
message.info('SKU 汇总导出即将支持,请先使用页面查看或商品维度导出');
}
</script>
<template>
@@ -244,6 +253,23 @@ async function handleProductExport() {
@export="handleProductExport"
@navigate-product="(id: number) => emit('navigate-product', id)"
/>
<CategorySummaryTable
v-if="activeMode === 'sku'"
column-prefs-key="sku"
heading-title="各 SKU 多维度经营明细汇总"
heading-subtitle="数据来自 Mongo SKU 日汇聚;推广按所属商品推广占比分摊;点击规格名可跳转 SKU 概览"
first-column-label="SKU"
:sku-navigate="true"
:category-summary="skuSummary ?? undefined"
:tax-rate="taxRate"
:category-export-mode="skuExportMode"
:selected-export-category-ids="selectedExportSkuIds"
@update:selected-export-category-ids="selectedExportSkuIds = $event"
@toggle-category-export-mode="skuExportMode = $event"
@export="handleSkuExport"
@navigate-sku="(id: number) => emit('navigate-sku', id)"
/>
</div>
</template>
@@ -1,6 +1,6 @@
/** 经营概览底部四表:可配置列目录(首列维度名固定不可隐藏) */
export type OverviewTableKey = 'shop' | 'platform' | 'category' | 'product';
export type OverviewTableKey = 'shop' | 'platform' | 'category' | 'product' | 'sku';
export type OverviewColGroupId = 'target' | 'scale' | 'cost' | 'profit';
@@ -99,7 +99,7 @@ const TARGET_IDS = new Set<OverviewColumnId>(
/** 某张表可用的列(品类/商品无目标列) */
export function columnsForTable(tableKey: OverviewTableKey): OverviewColumnDef[] {
if (tableKey === 'category' || tableKey === 'product') {
if (tableKey === 'category' || tableKey === 'product' || tableKey === 'sku') {
return OVERVIEW_COLUMNS.filter((c) => !TARGET_IDS.has(c.id));
}
return [...OVERVIEW_COLUMNS];
@@ -110,7 +110,7 @@ export function defaultVisibleIds(tableKey: OverviewTableKey): OverviewColumnId[
}
export function groupsForTable(tableKey: OverviewTableKey): OverviewColGroupDef[] {
if (tableKey === 'category' || tableKey === 'product') {
if (tableKey === 'category' || tableKey === 'product' || tableKey === 'sku') {
return OVERVIEW_COL_GROUPS.filter((g) => g.id !== 'target');
}
return [...OVERVIEW_COL_GROUPS];
@@ -29,6 +29,7 @@ const emit = defineEmits<{
(e: 'navigate-shop', shopId: number): void;
(e: 'navigate-platform', platformCode: string): void;
(e: 'navigate-category', categoryId: number): void;
(e: 'navigate-sku', skuId: number): void;
}>();
const props = defineProps<{
@@ -60,6 +61,7 @@ const productOverview = computed(
props.summaryTables?.productTable ??
buildCategoryOverviewFromDimRows(props.multiAnalysis.product),
);
const skuOverview = computed(() => props.summaryTables?.skuTable ?? null);
const IconSliders = createIconifyIcon('lucide:sliders-horizontal');
@@ -169,10 +171,12 @@ defineExpose({ redraw });
:platform-summary="platformOverview"
:category-summary="categoryOverview"
:product-summary="productOverview"
:sku-summary="skuOverview"
@navigate-product="(id: number) => emit('navigate-product', id)"
@navigate-shop="(id: number) => emit('navigate-shop', id)"
@navigate-platform="(code: string) => emit('navigate-platform', code)"
@navigate-category="(id: number) => emit('navigate-category', id)"
@navigate-sku="(id: number) => emit('navigate-sku', id)"
/>
</div>
</template>
@@ -3,6 +3,8 @@ import type { ProductOverviewVO } from '#/api/ec/product/overview';
import { computed } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import OverviewColumnHint from '#/components/overview/OverviewColumnHint.vue';
import {
overviewTableHints,
@@ -46,6 +48,17 @@ const props = withDefaults(defineProps<Props>(), {
footerTotal: null,
});
const emit = defineEmits<{
(e: 'navigate-sku', skuId: number): void;
}>();
const JumpIcon = createIconifyIcon('tdesign:jump');
function onNavigateSku(skuId: number | undefined) {
if (skuId == null || skuId <= 0) return;
emit('navigate-sku', skuId);
}
const formatAmount = (amount: number | undefined) => {
if (amount === undefined || amount === null) return '-';
return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
@@ -251,7 +264,16 @@ const footerRow = computed(() => props.footerTotal ?? computedFooter.value);
class="sticky-col border-r-2 border-slate-100 dark:border-r-[hsl(240deg_3.7%_22%)] bg-white dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 font-bold shadow-sm dark:shadow-none"
>
<span
class="inline-flex items-center rounded-full bg-blue-50 px-3 py-1 text-sm font-bold text-blue-600 dark:bg-blue-900/30 dark:text-blue-400"
v-if="item.skuId > 0"
class="inline-flex cursor-pointer items-center gap-1 rounded-full bg-blue-50 px-3 py-1 text-sm font-bold text-blue-600 transition-colors hover:text-blue-300 hover:underline dark:bg-blue-900/30 dark:text-blue-400"
@click="onNavigateSku(item.skuId)"
>
{{ item.skuName }}
<JumpIcon class="text-xs" />
</span>
<span
v-else
class="inline-flex items-center rounded-full bg-slate-50 px-3 py-1 text-sm font-bold text-slate-500 dark:bg-slate-800/50 dark:text-slate-400"
>
{{ item.skuName }}
</span>
@@ -388,6 +388,14 @@ function handleProductChange(nextProductId: number) {
});
}
function handleSkuNavigate(skuId: number) {
if (!skuId || skuId <= 0) return;
router.push({
path: `/ec/sku/overview/${skuId}`,
query: buildProductOverviewQuery(),
});
}
const timeRangeState = computed(() => ({
taxRate: taxRate.value,
activeTimeRange: activeTimeRange.value,
@@ -613,6 +621,7 @@ onUnmounted(() => {
:data="overviewData?.specSummaries?.list ?? []"
:footer-total="overviewData?.specSummaries?.total"
:tax-rate="taxRate"
@navigate-sku="handleSkuNavigate"
/>
</div>
<div
@@ -0,0 +1,207 @@
<script lang="ts" setup>
import type { SkuOverviewVO } from '#/api/ec/sku/overview';
import { computed } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import {
SKU_HERO_SHELL,
SKU_SPOT_CARD,
} from '../constants/sku-ui';
defineOptions({ name: 'SkuOverviewHero' });
const props = defineProps<{
data: SkuOverviewVO.Overview;
dateLabel?: string;
}>();
const emit = defineEmits<{
(e: 'navigate-product'): void;
}>();
const IconBarcode = createIconifyIcon('lucide:barcode');
const IconPackage = createIconifyIcon('lucide:package');
const IconWallet = createIconifyIcon('lucide:wallet');
const IconBag = createIconifyIcon('lucide:shopping-bag');
const IconNet = createIconifyIcon('lucide:badge-dollar-sign');
const IconRoi = createIconifyIcon('lucide:target');
function pickKpi(label: string) {
return props.data.kpis?.find((k) => k.label === label);
}
function formatYuan(v: number | undefined | null) {
if (v == null || !Number.isFinite(Number(v))) return '—';
return `¥${Number(v).toLocaleString('zh-CN', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}`;
}
function formatNum(v: number | undefined | null, digits = 0) {
if (v == null || !Number.isFinite(Number(v))) return '—';
return Number(v).toLocaleString('zh-CN', {
minimumFractionDigits: digits,
maximumFractionDigits: digits,
});
}
const spots = computed(() => {
const sales = pickKpi('净销售额');
const orders = pickKpi('净销售单量');
const profit = pickKpi('净利润');
const roi = pickKpi('广告ROI');
return [
{
key: 'sales',
label: '净销售额',
value:
sales?.amountYuan != null
? formatYuan(sales.amountYuan)
: formatYuan(props.data.totalSalesAmount),
delta: sales?.changePct,
icon: IconWallet,
},
{
key: 'orders',
label: '净销售单量',
value:
orders != null
? `${formatNum(orders.value)} 单`
: `${formatNum(props.data.totalOrderCount)} 单`,
delta: orders?.changePct,
icon: IconBag,
},
{
key: 'profit',
label: '净利润',
value:
profit?.amountYuan != null
? formatYuan(profit.amountYuan)
: formatYuan(props.data.totalNetProfitAfterTax),
delta: profit?.changePct,
icon: IconNet,
},
{
key: 'roi',
label: '广告 ROI',
value:
roi != null
? formatNum(Number(roi.value), 2)
: formatNum(props.data.totalROI, 2),
delta: roi?.changePct,
icon: IconRoi,
},
];
});
const canNavigateProduct = computed(
() =>
props.data.productId != null &&
Number.isFinite(props.data.productId) &&
props.data.productId > 0,
);
function deltaClass(pct: number | undefined | null) {
if (pct == null || !Number.isFinite(Number(pct))) return 'text-slate-400';
return Number(pct) >= 0
? 'text-emerald-600 dark:text-emerald-400'
: 'text-rose-500 dark:text-rose-400';
}
function formatDelta(pct: number | undefined | null) {
if (pct == null || !Number.isFinite(Number(pct))) return '';
const n = Number(pct);
return `环比 ${n > 0 ? '+' : ''}${n}%`;
}
function handleProductClick() {
if (!canNavigateProduct.value) return;
emit('navigate-product');
}
</script>
<template>
<section :class="SKU_HERO_SHELL">
<div
class="pointer-events-none absolute -right-8 -top-10 size-40 rounded-full bg-indigo-200/30 blur-2xl dark:bg-indigo-500/10"
/>
<div
class="pointer-events-none absolute -bottom-12 left-1/3 size-48 rounded-full bg-slate-200/25 blur-3xl dark:bg-slate-500/10"
/>
<div class="relative flex flex-wrap items-start justify-between gap-4">
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<span
class="grid size-9 shrink-0 place-items-center rounded-[12px] bg-indigo-600 text-white shadow-sm shadow-indigo-600/25 dark:bg-indigo-500"
>
<component :is="IconBarcode" class="size-4" />
</span>
<span
class="rounded-full bg-indigo-600/10 px-2 py-0.5 text-[11px] font-semibold text-indigo-700 dark:bg-indigo-400/10 dark:text-indigo-300"
>
规格诊断
</span>
</div>
<h2
class="mt-3 max-w-3xl text-xl font-bold tracking-tight text-slate-900 dark:text-[hsl(0deg_0%_96%)] sm:text-2xl"
:title="data.skuName"
>
{{ data.skuName || '未命名 SKU' }}
</h2>
<p
class="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
<span v-if="data.skuCode">编码 {{ data.skuCode }}</span>
<span v-if="canNavigateProduct" class="inline-flex items-center gap-1">
<component :is="IconPackage" class="size-3 shrink-0" />
所属商品
<button
type="button"
class="max-w-[16rem] truncate font-medium text-indigo-700 underline-offset-2 hover:text-indigo-900 hover:underline dark:text-indigo-300 dark:hover:text-indigo-200"
:title="data.productName"
@click="handleProductClick"
>
{{ data.productName || `商品 #${data.productId}` }}
</button>
</span>
<span v-else-if="data.productName">
所属商品 {{ data.productName }}
</span>
<span v-if="dateLabel">统计区间 {{ dateLabel }}</span>
</p>
</div>
</div>
<div class="relative mt-5 grid grid-cols-2 gap-2.5 lg:grid-cols-4">
<div v-for="spot in spots" :key="spot.key" :class="SKU_SPOT_CARD">
<div class="flex items-center justify-between gap-2">
<span
class="truncate text-xs font-medium text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
{{ spot.label }}
</span>
<component
:is="spot.icon"
class="size-3.5 shrink-0 text-indigo-600/80 dark:text-indigo-400/80"
/>
</div>
<div
class="mt-1.5 truncate text-lg font-bold tabular-nums tracking-tight text-slate-900 dark:text-[hsl(0deg_0%_95%)]"
>
{{ spot.value }}
</div>
<div
v-if="spot.delta != null"
class="mt-1 text-[11px] font-medium tabular-nums"
:class="deltaClass(spot.delta)"
>
{{ formatDelta(spot.delta) }}
</div>
</div>
</div>
</section>
</template>
@@ -0,0 +1,302 @@
<script lang="ts" setup>
import { computed, ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { DatePicker, InputNumber, Popover } from 'ant-design-vue';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { normalizeOverviewRangePickerChange } from '#/utils/overview-date-range';
import {
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState,
overviewToolbarPanelClass,
overviewToolbarShellClass,
} from '../../../styles/overview-toolbar-classes';
interface Props {
modelValue: {
taxRate: number;
activeTimeRange:
| '7days'
| '30days'
| 'thisMonth'
| 'custom'
| 'today'
| 'yesterday';
customDateRange: [Dayjs, Dayjs] | undefined;
dateRange: [Dayjs, Dayjs];
};
}
interface Emits {
(e: 'update:modelValue', val: Props['modelValue']): void;
}
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const openPopover = ref<string | null>(null);
function handlePopoverOpen(name: string, open: boolean) {
if (open) {
openPopover.value = name;
} else if (openPopover.value === name) {
openPopover.value = null;
}
}
const ReceiptIcon = createIconifyIcon('lucide:receipt');
const CalendarIcon = createIconifyIcon('lucide:calendar');
const timeRangeLabel = computed(() => {
const t = props.modelValue.activeTimeRange;
if (t === 'today') return '今日';
if (t === 'yesterday') return '昨日';
if (t === '7days') return '近7日';
if (t === '30days') return '近30日';
if (t === 'thisMonth') return '本月';
if (props.modelValue.customDateRange) {
return `${props.modelValue.customDateRange[0].format('M/D')}-${props.modelValue.customDateRange[1].format('M/D')}`;
}
return '日期';
});
const TAX_RATE_KEY = 'overview-tax-rate';
const formatTaxRate = (value: null | number | string | undefined) => {
if (value === null || value === undefined || value === '') return '';
const num = Number(value);
if (!Number.isFinite(num)) return '';
return `${Math.round(num * 100 * 1e10) / 1e10}%`;
};
const parseTaxRate = (value: string | undefined) => {
if (!value) return 0;
const num = Number(value.replace('%', '').trim());
return Number.isFinite(num) ? num / 100 : 0;
};
const switchTimeRange = (
type: '7days' | '30days' | 'thisMonth' | 'custom' | 'today' | 'yesterday',
) => {
let startDate: Dayjs;
let endDate: Dayjs = dayjs();
switch (type) {
case '7days':
startDate = dayjs().subtract(7, 'day');
break;
case '30days':
startDate = dayjs().subtract(30, 'day');
break;
case 'thisMonth':
startDate = dayjs().startOf('month');
endDate = dayjs();
break;
case 'custom':
if (props.modelValue.customDateRange) {
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: type,
dateRange: props.modelValue.customDateRange,
});
}
return;
case 'today':
startDate = dayjs();
endDate = dayjs();
break;
case 'yesterday':
startDate = dayjs().subtract(1, 'day');
endDate = dayjs().subtract(1, 'day');
break;
}
const newRange: [Dayjs, Dayjs] = [startDate, endDate];
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: type,
dateRange: newRange,
customDateRange: newRange,
});
};
const handleCustomDateRangeChange = (
value: [Dayjs, Dayjs] | [string, string] | null,
dateStrings?: [string, string],
) => {
const dates = normalizeOverviewRangePickerChange(value, dateStrings);
if (!dates) return;
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: 'custom',
dateRange: dates,
customDateRange: dates,
});
};
const handleTaxRateChange = (val: number | string | undefined) => {
const num = typeof val === 'string' ? parseTaxRate(val) : (val ?? 0.04);
localStorage.setItem(TAX_RATE_KEY, String(num));
emit('update:modelValue', {
...props.modelValue,
taxRate: num,
});
};
</script>
<template>
<div
class="overview-header-extra flex w-full max-w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center sm:gap-2"
>
<Popover
trigger="click"
:open="openPopover === 'taxRate'"
placement="bottom"
overlay-class-name="workbench-toolbar-popover"
@update:open="(val: boolean) => handlePopoverOpen('taxRate', val)"
>
<template #content>
<div class="flex items-center gap-2 whitespace-nowrap">
<span
class="shrink-0 text-xs font-bold text-slate-700 dark:text-slate-300"
>
税率
</span>
<InputNumber
:value="props.modelValue.taxRate"
:min="0"
:max="1"
:step="0.01"
:precision="2"
size="small"
class="tax-rate-input !h-8 !w-20 !rounded-lg !border-none !bg-transparent !text-center !text-sm !font-bold !text-slate-800 !shadow-none dark:!text-slate-100"
:formatter="formatTaxRate"
:parser="parseTaxRate"
@change="handleTaxRateChange"
/>
</div>
</template>
<div :class="[overviewToolbarShellClass, 'cursor-pointer']">
<div
:class="[overviewToolbarPanelClass, 'flex items-center gap-1 px-2 py-1']"
>
<ReceiptIcon class="h-4 w-4 shrink-0" />
<span
class="whitespace-nowrap text-xs font-bold text-slate-700 dark:text-slate-300"
>
税率{{ formatTaxRate(props.modelValue.taxRate) }}
</span>
</div>
</div>
</Popover>
<Popover
trigger="click"
:open="openPopover === 'timeRange'"
placement="bottom"
overlay-class-name="workbench-toolbar-popover"
@update:open="(val: boolean) => handlePopoverOpen('timeRange', val)"
>
<template #content>
<div class="flex flex-col gap-2 px-1 py-0.5">
<div class="flex items-center gap-1 overflow-x-auto whitespace-nowrap">
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(
props.modelValue.activeTimeRange === 'today',
),
]"
@click="switchTimeRange('today')"
>
今日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(
props.modelValue.activeTimeRange === 'yesterday',
),
]"
@click="switchTimeRange('yesterday')"
>
昨日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(
props.modelValue.activeTimeRange === '7days',
),
]"
@click="switchTimeRange('7days')"
>
近7日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(
props.modelValue.activeTimeRange === '30days',
),
]"
@click="switchTimeRange('30days')"
>
近30日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(
props.modelValue.activeTimeRange === 'thisMonth',
),
]"
@click="switchTimeRange('thisMonth')"
>
本月
</button>
</div>
<div class="flex items-center gap-2">
<span
class="whitespace-nowrap text-xs font-bold text-slate-700 dark:text-slate-300"
>
自定义日期
</span>
<DatePicker.RangePicker
:value="props.modelValue.customDateRange"
size="small"
format="YYYY-MM-DD"
:allow-clear="false"
:placeholder="['开始', '结束']"
class="overview-header-range-picker !h-8 !w-full !border-none !bg-transparent !text-sm !font-bold !text-slate-800 sm:!w-[220px] dark:!text-slate-200"
@change="handleCustomDateRangeChange"
/>
</div>
</div>
</template>
<div :class="[overviewToolbarShellClass, 'cursor-pointer']">
<div
:class="[overviewToolbarPanelClass, 'flex items-center gap-1 px-2 py-1']"
>
<CalendarIcon class="h-4 w-4 shrink-0" />
<span
class="whitespace-nowrap text-xs font-bold text-slate-700 dark:text-slate-300"
>
{{ timeRangeLabel }}
</span>
</div>
</div>
</Popover>
</div>
</template>
<style src="../../../styles/overview-toolbar.css"></style>
@@ -0,0 +1,16 @@
/** SKU 概览:靛蓝/slate-blue 强调,与商品青绿、品类玫红、店铺琥珀、平台紫区分 */
export const SKU_PAGE_BG =
'bg-[#f4f6fb] dark:bg-[hsl(222deg_22%_8%)]';
export const SKU_PANEL_SHELL =
'overflow-hidden rounded-[16px] border border-indigo-200/70 bg-white shadow-[0_1px_2px_rgba(67,56,202,0.04),0_10px_28px_rgba(67,56,202,0.05)] dark:border-indigo-900/40 dark:bg-[hsl(222deg_16%_11%)] dark:shadow-none';
export const SKU_HERO_SHELL =
'relative overflow-hidden rounded-[18px] border border-indigo-200/80 bg-gradient-to-br from-indigo-50 via-white to-slate-100/80 p-5 shadow-[0_1px_2px_rgba(67,56,202,0.05),0_12px_32px_rgba(67,56,202,0.07)] md:p-6 dark:border-indigo-900/45 dark:from-indigo-950/40 dark:via-[hsl(222deg_16%_11%)] dark:to-slate-950/30 dark:shadow-none';
export const SKU_SPOT_CARD =
'min-w-0 rounded-[14px] border border-indigo-100/90 bg-white/80 px-3.5 py-3 backdrop-blur-sm dark:border-indigo-900/35 dark:bg-[hsl(222deg_16%_12%/80%)]';
export const SKU_SECTION_LABEL =
'inline-flex items-center gap-1.5 rounded-full border border-indigo-200/80 bg-indigo-50/80 px-2.5 py-0.5 text-[11px] font-semibold tracking-wide text-indigo-800 dark:border-indigo-800/50 dark:bg-indigo-950/40 dark:text-indigo-300';
@@ -0,0 +1,436 @@
<script lang="ts" setup>
import type { SkuOverviewVO } from '#/api/ec/sku/overview';
import type { WorkbenchVO } from '#/api/bi/workbench/types';
import type { FinanceKpiCardId } from '#/views/bi/workbench/tabs/finance/constants/kpi-catalog';
import type { Dayjs } from 'dayjs';
import {
computed,
nextTick,
onActivated,
onMounted,
ref,
watch,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Spin } from 'ant-design-vue';
import dayjs from 'dayjs';
import { getSkuOverviewApi } from '#/api/ec/sku/overview';
import {
applyOverviewDateRangeFromUrl,
buildOverviewRouteQuery,
parseOverviewShopIdFromQuery,
syncOverviewDateRangeToUrl,
} from '#/utils/overview-date-range';
import { formatOverviewTabTitle } from '#/utils/overview-tab-title';
import FinanceKpiGrid from '#/views/bi/workbench/tabs/finance/components/FinanceKpiGrid.vue';
import FinanceKpiSettingsModal from '#/views/bi/workbench/tabs/finance/components/FinanceKpiSettingsModal.vue';
import FinanceTrendChart from '#/views/bi/workbench/tabs/finance/components/FinanceTrendChart.vue';
import { useFinanceKpiPreferences } from '#/views/bi/workbench/tabs/finance/composables/useFinanceKpiPreferences';
import TimeRangeBar from './components/TimeRangeBar.vue';
import SkuHeroBanner from './components/SkuHeroBanner.vue';
import {
SKU_PAGE_BG,
SKU_PANEL_SHELL,
SKU_SECTION_LABEL,
} from './constants/sku-ui';
defineOptions({ name: 'SkuOverview' });
const route = useRoute();
const router = useRouter();
const { setTabTitle } = useTabs();
const IconSliders = createIconifyIcon('lucide:sliders-horizontal');
/** 当前是否为 SKU 概览路由 */
const isSkuOverviewRoute = () =>
/\/ec\/sku\/overview\/[^/]+\/?$/.test(route.path);
const skuId = computed(() => {
if (!isSkuOverviewRoute()) return 0;
const id = Number(route.params.id);
return Number.isFinite(id) && id > 0 ? id : 0;
});
const contextShopId = computed(() => {
if (!isSkuOverviewRoute()) return undefined;
return parseOverviewShopIdFromQuery(
route.query as Record<string, unknown>,
);
});
/** 数据加载后用 SKU 名覆盖菜单默认标签 */
async function syncSkuTabTitle(name?: null | string) {
if (!isSkuOverviewRoute()) return;
await setTabTitle(
formatOverviewTabTitle(
'SKU',
name,
skuId.value ? `#${skuId.value}` : '概览',
),
);
}
const loading = ref(false);
const overviewData = ref<null | SkuOverviewVO.Overview>(null);
const financeKpis = computed<WorkbenchVO.KpiItem[]>(
() => (overviewData.value?.kpis as WorkbenchVO.KpiItem[] | undefined) ?? [],
);
const dealTrend = computed<WorkbenchVO.TrendPoint[]>(
() =>
(overviewData.value?.dealTrend as WorkbenchVO.TrendPoint[] | undefined) ??
[],
);
const periodDateLabel = computed(() => {
const [start, end] = dateRange.value;
return `${start.format('YYYY-MM-DD')} ~ ${end.format('YYYY-MM-DD')}`;
});
const {
visibleCardIds,
primaryByCardId,
colsPerRow,
applySettings,
setCardPrimary,
} = useFinanceKpiPreferences();
const kpiSettingsOpen = ref(false);
const visibleKpiCount = computed(() => visibleCardIds.value.length);
const trendChartRef = ref<InstanceType<typeof FinanceTrendChart> | null>(null);
async function redrawCharts() {
await nextTick();
await trendChartRef.value?.redraw();
}
function onKpiSettingsSave(payload: {
visibleCardIds: string[];
primaryByCardId: Record<string, string>;
colsPerRow: number;
}) {
if (payload.visibleCardIds.length === 0) {
message.warning('请至少选择一张 KPI 卡片');
return;
}
applySettings(payload);
message.success('KPI 显示已更新');
}
function onSetPrimary(payload: {
cardId: FinanceKpiCardId;
metricLabel: string;
}) {
setCardPrimary(payload.cardId, payload.metricLabel);
}
const dateRange = ref<[Dayjs, Dayjs]>([dayjs().startOf('month'), dayjs()]);
const activeTimeRange = ref<
'7days' | '30days' | 'thisMonth' | 'custom' | 'today' | 'yesterday'
>('thisMonth');
const customDateRange = ref<[Dayjs, Dayjs] | undefined>([
dateRange.value[0],
dateRange.value[1],
]);
const lastRequestKey = ref('');
const isRequesting = ref(false);
const TAX_RATE_KEY = 'overview-tax-rate';
const taxRate = ref<number>(0.04);
taxRate.value = Number(localStorage.getItem(TAX_RATE_KEY)) || 0.04;
watch(taxRate, () => {
void loadOverviewData();
});
const timeRangeState = computed(() => ({
taxRate: taxRate.value,
activeTimeRange: activeTimeRange.value,
customDateRange: customDateRange.value,
dateRange: dateRange.value,
}));
const handleTimeRangeChange = async (val: typeof timeRangeState.value) => {
taxRate.value = val.taxRate;
activeTimeRange.value = val.activeTimeRange;
customDateRange.value = val.customDateRange;
dateRange.value = val.dateRange;
lastRequestKey.value = '';
syncDateRangeToRouteQuery();
await refreshOverviewByCurrentParams();
};
const setTimeRangeTypeByDates = (startDate: Dayjs, endDate: Dayjs) => {
const today = dayjs();
const daysDiff = endDate.diff(startDate, 'day');
const isEndDateToday = endDate.isSame(today, 'day');
const isStartDate7DaysAgo = startDate.isSame(
dayjs().subtract(7, 'day'),
'day',
);
const isStartDate30DaysAgo = startDate.isSame(
dayjs().subtract(30, 'day'),
'day',
);
if (isEndDateToday && startDate.isSame(today.startOf('month'), 'day')) {
activeTimeRange.value = 'thisMonth';
customDateRange.value = [startDate, endDate];
return;
}
if (daysDiff === 0 && startDate.isSame(today, 'day')) {
activeTimeRange.value = 'today';
customDateRange.value = [startDate, endDate];
return;
}
if (daysDiff === 0 && startDate.isSame(dayjs().subtract(1, 'day'), 'day')) {
activeTimeRange.value = 'yesterday';
customDateRange.value = [startDate, endDate];
return;
}
if (isEndDateToday && isStartDate7DaysAgo) {
activeTimeRange.value = '7days';
customDateRange.value = [startDate, endDate];
return;
}
if (isEndDateToday && isStartDate30DaysAgo) {
activeTimeRange.value = '30days';
customDateRange.value = [startDate, endDate];
return;
}
activeTimeRange.value = 'custom';
customDateRange.value = [startDate, endDate];
};
const applyDateRangeFromRouteQuery = () =>
applyOverviewDateRangeFromUrl(dateRange, setTimeRangeTypeByDates);
const syncDateRangeToRouteQuery = () => {
syncOverviewDateRangeToUrl(dateRange.value);
};
function handleNavigateProduct() {
const productId = overviewData.value?.productId;
if (productId == null || productId <= 0) return;
router.push({
path: `/ec/product/overview/${productId}`,
query: buildOverviewRouteQuery(
dateRange.value,
contextShopId.value != null && contextShopId.value > 0
? { shopId: contextShopId.value }
: undefined,
),
});
}
const loadOverviewData = async () => {
if (!isSkuOverviewRoute() || !skuId.value) return;
if (isRequesting.value) return;
const requestSkuId = skuId.value;
isRequesting.value = true;
try {
loading.value = true;
const [startDate, endDate] = dateRange.value;
const res = await getSkuOverviewApi({
skuId: requestSkuId,
startDate: startDate.format('YYYY-MM-DD'),
endDate: endDate.format('YYYY-MM-DD'),
taxRate: taxRate.value,
...(contextShopId.value != null && contextShopId.value > 0
? { shopId: contextShopId.value }
: {}),
});
overviewData.value = res;
if (isSkuOverviewRoute() && skuId.value === requestSkuId) {
await syncSkuTabTitle(res?.skuName);
}
await redrawCharts();
} catch (err: any) {
overviewData.value = null;
message.error(err?.message || '加载SKU概览失败');
} finally {
loading.value = false;
isRequesting.value = false;
}
};
const refreshOverviewByCurrentParams = async (force = false) => {
if (!isSkuOverviewRoute()) return;
applyDateRangeFromRouteQuery();
if (!skuId.value) return;
const shopKey = contextShopId.value ?? '';
const requestKey = `${skuId.value}_${dateRange.value[0].format('YYYY-MM-DD')}_${dateRange.value[1].format('YYYY-MM-DD')}_${taxRate.value}_${shopKey}`;
if (!force && lastRequestKey.value === requestKey) {
return;
}
lastRequestKey.value = requestKey;
await loadOverviewData();
};
watch(
() => [
route.path,
route.params.id,
route.query.startDate,
route.query.endDate,
route.query.shopId,
],
async () => {
if (!isSkuOverviewRoute()) return;
await refreshOverviewByCurrentParams();
},
);
onMounted(async () => {
if (!isSkuOverviewRoute()) return;
await refreshOverviewByCurrentParams(true);
});
onActivated(async () => {
if (!isSkuOverviewRoute()) return;
await refreshOverviewByCurrentParams(true);
});
</script>
<template>
<Page
auto-content-height
:class="SKU_PAGE_BG"
content-padding-class="px-4 pb-4"
header-class="sku-overview-page-header"
>
<template #title>
<div
class="text-xl font-black tracking-tight text-indigo-950 dark:text-indigo-50 sm:text-2xl md:text-3xl"
>
SKU 概览
</div>
<p
class="mt-0.5 text-xs font-normal text-indigo-800/70 dark:text-indigo-300/70"
>
规格诊断 · 穿透商品
</p>
</template>
<template #extra>
<div class="w-full max-w-full sm:w-auto">
<TimeRangeBar
:model-value="timeRangeState"
@update:model-value="handleTimeRangeChange"
/>
</div>
</template>
<Spin :spinning="loading">
<div
v-if="overviewData"
class="sku-overview-body mx-auto w-full min-w-0 space-y-4 pt-4"
>
<SkuHeroBanner
:data="overviewData"
:date-label="periodDateLabel"
@navigate-product="handleNavigateProduct"
/>
<FinanceTrendChart
ref="trendChartRef"
:trend="dealTrend"
:panel-class="SKU_PANEL_SHELL"
/>
<div class="flex flex-wrap items-center justify-between gap-3 pt-1">
<div>
<span :class="SKU_SECTION_LABEL">指标明细</span>
<h2
class="mt-2 text-base font-semibold text-slate-800 dark:text-[hsl(0deg_0%_95%)]"
>
SKU 经营指标
</h2>
<p
class="mt-0.5 text-xs text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
>
口径与工作台一致,卡片布局可自定义
<span v-if="visibleKpiCount > 0">
· 已选 {{ visibleKpiCount }} 张 · 最多 {{ colsPerRow }} 列
</span>
</p>
</div>
<Button
type="default"
class="shrink-0 whitespace-nowrap !rounded-[10px] !border-indigo-200 !bg-white !text-indigo-900 shadow-[0_1px_2px_rgba(67,56,202,0.05)] hover:!border-indigo-400 hover:!text-indigo-800 dark:!border-indigo-800/50 dark:!bg-[hsl(222deg_16%_12%)] dark:!text-indigo-200 dark:hover:!border-indigo-500/50 dark:hover:!text-indigo-100"
@click="kpiSettingsOpen = true"
>
<template #icon>
<component :is="IconSliders" class="size-4 shrink-0" />
</template>
KPI 显示设置
</Button>
</div>
<FinanceKpiSettingsModal
v-model:open="kpiSettingsOpen"
:cols-per-row="colsPerRow"
:visible-card-ids="visibleCardIds"
:primary-by-card-id="primaryByCardId"
@save="onKpiSettingsSave"
/>
<FinanceKpiGrid
:kpis="financeKpis"
:cols-per-row="colsPerRow"
:tax-rate="taxRate"
:visible-card-ids="visibleCardIds"
:primary-by-card-id="primaryByCardId"
:mom-compare-date-start="overviewData.momCompareDateStart"
:mom-compare-date-end="overviewData.momCompareDateEnd"
:yoy-compare-date-start="overviewData.yoyCompareDateStart"
:yoy-compare-date-end="overviewData.yoyCompareDateEnd"
@set-primary="onSetPrimary"
/>
</div>
<div
v-else-if="!loading"
class="flex items-center justify-center p-8 text-slate-400"
>
暂无数据
</div>
</Spin>
</Page>
</template>
<style scoped>
:deep(.sku-overview-page-header) {
align-items: stretch;
flex-direction: column;
gap: 10px;
}
@media (min-width: 640px) {
:deep(.sku-overview-page-header) {
flex-direction: row;
align-items: center;
}
}
:deep(.sku-overview-page-header > div:first-child),
:deep(.sku-overview-page-header > div:last-child) {
width: 100%;
}
@media (min-width: 640px) {
:deep(.sku-overview-page-header > div:first-child),
:deep(.sku-overview-page-header > div:last-child) {
width: auto;
}
}
</style>