From dc864ea57c4ae4eac0fedfc32af0873c7386dd36 Mon Sep 17 00:00:00 2001 From: ah-max150 Date: Sat, 5 Sep 2026 22:29:27 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=B7=A5=E4=BD=9C=E5=8F=B0=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0SKU=E6=B1=87=E6=80=BB=E8=A1=A8=E5=B9=B6=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E8=B7=B3=E8=BD=ACSKU=E6=A6=82=E8=A7=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../V20260908__bi_sku_overview_permission.sql | 8 + .../V20260908b__sku_overview_menu.sql | 4 + .../query/BiOrderStatQueryService.java | 83 ++++ .../BiOrderStatDailyRepository.java | 29 +- .../overview/model/agg/OverviewAggRows.java | 22 + .../overview/model/vo/CompanyOverviewVO.java | 2 + .../service/CompanyOverviewService.java | 22 +- .../impl/CompanyOverviewServiceImpl.java | 118 ++++- .../controller/BiSkuOverviewController.java | 32 ++ .../model/dto/SkuOverviewQueryDTO.java | 29 ++ .../skuoverview/model/vo/SkuOverviewVO.java | 65 +++ .../service/BiSkuOverviewService.java | 12 + .../impl/BiSkuOverviewServiceImpl.java | 304 ++++++++++++ .../service/impl/BiWorkbenchServiceImpl.java | 12 +- .../src/main/resources/sql/init/sys_seed.sql | 12 + .../src/api/bi/overview/types/types.vo.ts | 4 +- .../web-antd/src/api/ec/sku/overview/apis.ts | 11 + .../web-antd/src/api/ec/sku/overview/index.ts | 2 + .../src/api/ec/sku/overview/types/index.ts | 2 + .../api/ec/sku/overview/types/types.dto.ts | 10 + .../src/api/ec/sku/overview/types/types.vo.ts | 70 +++ .../web-antd/src/views/bi/workbench/index.vue | 15 + .../components/CategorySummaryTable.vue | 18 +- .../finance/components/OverviewTables.vue | 28 +- .../constants/overview-table-columns.ts | 6 +- .../views/bi/workbench/tabs/finance/index.vue | 4 + .../overview/components/SkuSummaryTable.vue | 24 +- .../src/views/ec/product/overview/index.vue | 9 + .../sku/overview/components/SkuHeroBanner.vue | 207 +++++++++ .../sku/overview/components/TimeRangeBar.vue | 302 ++++++++++++ .../views/ec/sku/overview/constants/sku-ui.ts | 16 + .../src/views/ec/sku/overview/index.vue | 436 ++++++++++++++++++ 32 files changed, 1896 insertions(+), 22 deletions(-) create mode 100644 ecom-dmb-backend/sql/migration/V20260908__bi_sku_overview_permission.sql create mode 100644 ecom-dmb-backend/sql/migration/V20260908b__sku_overview_menu.sql create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/controller/BiSkuOverviewController.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/model/dto/SkuOverviewQueryDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/model/vo/SkuOverviewVO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/service/BiSkuOverviewService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/service/impl/BiSkuOverviewServiceImpl.java create mode 100644 ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/apis.ts create mode 100644 ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/index.ts create mode 100644 ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/index.ts create mode 100644 ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/types.dto.ts create mode 100644 ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/types.vo.ts create mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/components/SkuHeroBanner.vue create mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/components/TimeRangeBar.vue create mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/constants/sku-ui.ts create mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/index.vue diff --git a/ecom-dmb-backend/sql/migration/V20260908__bi_sku_overview_permission.sql b/ecom-dmb-backend/sql/migration/V20260908__bi_sku_overview_permission.sql new file mode 100644 index 00000000..31b8be99 --- /dev/null +++ b/ecom-dmb-backend/sql/migration/V20260908__bi_sku_overview_permission.sql @@ -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'); diff --git a/ecom-dmb-backend/sql/migration/V20260908b__sku_overview_menu.sql b/ecom-dmb-backend/sql/migration/V20260908b__sku_overview_menu.sql new file mode 100644 index 00000000..308ff161 --- /dev/null +++ b/ecom-dmb-backend/sql/migration/V20260908b__sku_overview_menu.sql @@ -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'); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/orderstat/query/BiOrderStatQueryService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/orderstat/query/BiOrderStatQueryService.java index 23bdaeaf..4e0e65c7 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/orderstat/query/BiOrderStatQueryService.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/orderstat/query/BiOrderStatQueryService.java @@ -55,6 +55,13 @@ public class BiOrderStatQueryService { return repository.listSkuDocs(companyId, productId, shopIds, start, end); } + /** 按 SKU 主键拉区间日文档(SKU 概览)。 */ + public List listSkuDocsBySkuId(Long companyId, Long productSkuId, + List shopIds, + LocalDate start, LocalDate end) { + return repository.listSkuDocsBySkuId(companyId, productSkuId, shopIds, start, end); + } + /** 商品日文档按日历日合并(单商品趋势)。 */ public List toDailyRowsFromProductDocs( List productDocs) { @@ -72,6 +79,22 @@ public class BiOrderStatQueryService { return new ArrayList<>(byDay.values()); } + /** SKU 日文档按日历日合并(单 SKU 趋势)。 */ + public List toDailyRowsFromSkuDocs(List skuDocs) { + Map 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 sumSkuDocsBySku(List skuDocs) { Map merged = new HashMap<>(); @@ -122,6 +145,56 @@ public class BiOrderStatQueryService { return new ArrayList<>(merged.values()); } + /** + * SKU 日文档按 (shopId, productSkuId) 合并区间,供工作台 SKU 汇总表。 + * 行上净销售三件套 = 成交 − 退款。 + */ + public List toShopSkuRows(List docs) { + Map 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)); } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/orderstat/repository/BiOrderStatDailyRepository.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/orderstat/repository/BiOrderStatDailyRepository.java index 5aaeda83..40cbaef1 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/orderstat/repository/BiOrderStatDailyRepository.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/orderstat/repository/BiOrderStatDailyRepository.java @@ -73,17 +73,40 @@ public class BiOrderStatDailyRepository { } /** - * 区间内 SKU 日文档。{@code productId} 必填; + * 区间内 SKU 日文档。 + * {@code productId} 为空时不按商品过滤(公司/店铺级 SKU 汇总); * {@code shopIds} 为空时不按店过滤。 */ public List listSkuDocs(Long companyId, Long productId, List 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 listSkuDocsBySkuId(Long companyId, Long productSkuId, + List 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); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/agg/OverviewAggRows.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/agg/OverviewAggRows.java index 132b0fb1..f71d0804 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/agg/OverviewAggRows.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/agg/OverviewAggRows.java @@ -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; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/vo/CompanyOverviewVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/vo/CompanyOverviewVO.java index b59b74a6..f7916b35 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/vo/CompanyOverviewVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/vo/CompanyOverviewVO.java @@ -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; } /** diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/CompanyOverviewService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/CompanyOverviewService.java index 271abb37..6e0c51cf 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/CompanyOverviewService.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/CompanyOverviewService.java @@ -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 shops, + List orderRows, + List promotionRows, + List 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 promotionRows, List brushRows, LocalDate startDate, - LocalDate endDate); + LocalDate endDate, + List skuRows); } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/CompanyOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/CompanyOverviewServiceImpl.java index 30488e17..820ad346 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/CompanyOverviewServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/CompanyOverviewServiceImpl.java @@ -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 promotionRows, List brushRows, LocalDate startDate, - LocalDate endDate) { + LocalDate endDate, + List 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 shops, @@ -353,7 +362,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { List promotionRows, List brushRows, LocalDate startDate, - LocalDate endDate) { + LocalDate endDate, + List skuRows) { Map byShop = new HashMap<>(); Map 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 skuRows, + CompanyOverviewVO.CategoryOverview productTable, + Map brushByShop) { + if (skuRows == null || skuRows.isEmpty()) { + CompanyOverviewVO.CategoryOverview empty = new CompanyOverviewVO.CategoryOverview(); + empty.setCategories(List.of()); + empty.setTotal(computeCategoryTotal(List.of())); + return empty; + } + + Map 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 bySku = new HashMap<>(); + Map skuProductId = new HashMap<>(); + Map> 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 salesByProductFromSku = new HashMap<>(); + for (Map.Entry e : bySku.entrySet()) { + Long pid = skuProductId.getOrDefault(e.getKey(), 0L); + if (pid != null && pid > 0) { + salesByProductFromSku.merge(pid, e.getValue().sales, BigDecimal::add); + } + } + + Map skuNames = loadSkuNameMap(bySku.keySet()); + List list = new ArrayList<>(); + for (Map.Entry 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 shops, Map byShop, Map promoByShop, Map brushByShop, Map> targetsByShop) { @@ -736,6 +820,15 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { .stream().collect(Collectors.toMap(ProductPO::getId, ProductPO::getName, (a, b) -> a)); } + private Map loadSkuNameMap(java.util.Set skuKeys) { + List ids = skuKeys.stream().filter(id -> id != null && id > 0).distinct().toList(); + if (ids.isEmpty()) { + return Map.of(); + } + return productSkuMapper.selectList(new LambdaQueryWrapper().in(ProductSkuPO::getId, ids)) + .stream().collect(Collectors.toMap(ProductSkuPO::getId, ProductSkuPO::getName, (a, b) -> a)); + } + private Map> loadTargetsByShop(Long companyId, LocalDate start, LocalDate end) { List 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); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/controller/BiSkuOverviewController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/controller/BiSkuOverviewController.java new file mode 100644 index 00000000..1acf261d --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/controller/BiSkuOverviewController.java @@ -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 overview(@Valid @RequestBody SkuOverviewQueryDTO queryDTO) { + return ApiResponse.success("获取SKU概览成功", biSkuOverviewService.getSkuOverview(queryDTO)); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/model/dto/SkuOverviewQueryDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/model/dto/SkuOverviewQueryDTO.java new file mode 100644 index 00000000..d8871ef4 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/model/dto/SkuOverviewQueryDTO.java @@ -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"); +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/model/vo/SkuOverviewVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/model/vo/SkuOverviewVO.java new file mode 100644 index 00000000..8d4a6bd6 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/model/vo/SkuOverviewVO.java @@ -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 kpis; + + /** 成交/净销售/利润日趋势 */ + private List 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 dailyDataList; + } + + @Data + public static class TrendDataItem { + @JsonFormat(pattern = "yyyy-MM-dd") + private LocalDate date; + private BigDecimal value; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/service/BiSkuOverviewService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/service/BiSkuOverviewService.java new file mode 100644 index 00000000..bb54410c --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/service/BiSkuOverviewService.java @@ -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); +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/service/impl/BiSkuOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/service/impl/BiSkuOverviewServiceImpl.java new file mode 100644 index 00000000..07bb2deb --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/skuoverview/service/impl/BiSkuOverviewServiceImpl.java @@ -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 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 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 shopIdFilter, Long filterShopId, + LocalDate start, LocalDate end, BigDecimal taxRate) { + List thisSkuDocs = + orderStatQueryService.listSkuDocsBySkuId(companyId, skuId, shopIdFilter, start, end); + + List dailyRows = + orderStatQueryService.toDailyRowsFromSkuDocs(thisSkuDocs); + + List 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 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 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 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 allProductDocs = + orderStatQueryService.listProductDocs(companyId, shopIds, start, end); + BiWorkbenchFeeLoader.FeeBundle fees = feeLoader.load(companyId, shopIds, start, end); + List 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 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 dealTrend) { + SkuOverviewVO.TrendData sales = new SkuOverviewVO.TrendData(); + SkuOverviewVO.TrendData orders = new SkuOverviewVO.TrendData(); + List salesItems = new ArrayList<>(); + List 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 shopIds, + BiFinanceKpiAssembler.Totals totals, + List dailyRows) { + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/impl/BiWorkbenchServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/impl/BiWorkbenchServiceImpl.java index 7667e543..a6c5cfdd 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/impl/BiWorkbenchServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/impl/BiWorkbenchServiceImpl.java @@ -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 orderRows, + List skuRows, List dailyRows, List promotionRows, List brushRows, diff --git a/ecom-dmb-backend/src/main/resources/sql/init/sys_seed.sql b/ecom-dmb-backend/src/main/resources/sql/init/sys_seed.sql index be3b0d5f..d10eb9c2 100644 --- a/ecom-dmb-backend/src/main/resources/sql/init/sys_seed.sql +++ b/ecom-dmb-backend/src/main/resources/sql/init/sys_seed.sql @@ -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` = '商品类目'); diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/bi/overview/types/types.vo.ts b/ecom-dmb-frontend/apps/web-antd/src/api/bi/overview/types/types.vo.ts index 8131aad2..28eac729 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/bi/overview/types/types.vo.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/bi/overview/types/types.vo.ts @@ -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; } /** 店铺汇总行 */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/apis.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/apis.ts new file mode 100644 index 00000000..1606d01d --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/apis.ts @@ -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( + '/bi/sku/overview', + params, + ); +} diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/index.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/index.ts new file mode 100644 index 00000000..daf76d51 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/index.ts @@ -0,0 +1,2 @@ +export * from './apis'; +export * from './types'; diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/index.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/index.ts new file mode 100644 index 00000000..88cc38f4 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/index.ts @@ -0,0 +1,2 @@ +export type { SkuOverviewDTO } from './types.dto'; +export type { SkuOverviewVO } from './types.vo'; diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/types.dto.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/types.dto.ts new file mode 100644 index 00000000..0fea018d --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/types.dto.ts @@ -0,0 +1,10 @@ +export namespace SkuOverviewDTO { + /** SKU 概览查询参数 */ + export interface Query { + skuId: number; + shopId?: number; + startDate: string; + endDate: string; + taxRate?: number; + } +} diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/types.vo.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/types.vo.ts new file mode 100644 index 00000000..b34b6e3e --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ec/sku/overview/types/types.vo.ts @@ -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; + } +} diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/index.vue b/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/index.vue index 148f1ebb..67094846 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/index.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/index.vue @@ -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 | null>( null, ); @@ -1045,6 +1059,7 @@ onUnmounted(() => { @navigate-shop="handleShopNavigate" @navigate-platform="handlePlatformNavigate" @navigate-category="handleCategoryNavigate" + @navigate-sku="handleSkuNavigate" /> diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/components/CategorySummaryTable.vue b/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/components/CategorySummaryTable.vue index a3bc6cbc..0dc21f65 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/components/CategorySummaryTable.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/components/CategorySummaryTable.vue @@ -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(), { @@ -56,6 +59,7 @@ const props = withDefaults(defineProps(), { 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 }} + + {{ cat.categoryName }} + + (), { 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([]); @@ -45,6 +47,8 @@ const categoryExportMode = ref(false); const selectedExportCategoryIds = ref([]); const productExportMode = ref(false); const selectedExportProductIds = ref([]); +const skuExportMode = ref(false); +const selectedExportSkuIds = ref([]); 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 汇总导出即将支持,请先使用页面查看或商品维度导出'); +} + diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/constants/overview-table-columns.ts b/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/constants/overview-table-columns.ts index da47500c..e8528e6d 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/constants/overview-table-columns.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/constants/overview-table-columns.ts @@ -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( /** 某张表可用的列(品类/商品无目标列) */ 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]; diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/index.vue b/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/index.vue index 51f1fac9..cb6743ca 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/index.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/index.vue @@ -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)" /> diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/components/SkuSummaryTable.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/components/SkuSummaryTable.vue index 29d3cbb4..d1026a2e 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/components/SkuSummaryTable.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/components/SkuSummaryTable.vue @@ -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(), { 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" > + {{ item.skuName }} + + + {{ item.skuName }} diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/index.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/index.vue index 2ecf2631..af82bd30 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/index.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/index.vue @@ -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" />
+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'); +} + + + diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/components/TimeRangeBar.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/components/TimeRangeBar.vue new file mode 100644 index 00000000..4ef7cb01 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/components/TimeRangeBar.vue @@ -0,0 +1,302 @@ + + + + + diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/constants/sku-ui.ts b/ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/constants/sku-ui.ts new file mode 100644 index 00000000..386a9bd3 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/constants/sku-ui.ts @@ -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'; diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/index.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/index.vue new file mode 100644 index 00000000..02e3c9c3 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/sku/overview/index.vue @@ -0,0 +1,436 @@ + + + + +