From 5114abc98622a9444c507b7bb1c429c5293dac73 Mon Sep 17 00:00:00 2001 From: ah-max150 Date: Sat, 5 Sep 2026 11:08:30 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8C=89=E7=BB=8F=E8=90=A5=E6=A6=82?= =?UTF-8?q?=E8=A7=88=E9=A3=8E=E6=A0=BC=E9=87=8D=E5=81=9A=E5=95=86=E5=93=81?= =?UTF-8?q?=E6=A6=82=E8=A7=88=E5=B9=B6=E8=A1=A5=E9=BD=90=20KPI=20=E4=B8=8E?= =?UTF-8?q?=E8=B6=8B=E5=8A=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../model/vo/ProductOverviewVO.java | 270 ++------------ .../impl/BiProductOverviewServiceImpl.java | 331 +++++++++--------- .../support/BiFinanceKpiAssembler.java | 319 +++++++++++++++++ .../api/ec/product/overview/types/types.vo.ts | 140 +++----- .../components/FinanceCostPieChart.vue | 26 +- .../finance/components/FinanceTrendChart.vue | 17 +- .../overview/components/ProductHeroBanner.vue | 179 ++++++++++ .../components/ProductSkuRankStrip.vue | 95 +++++ .../overview/components/SalesTrendChart.vue | 227 ------------ .../components/SkuSalesTop10Panel.vue | 97 ----- .../overview/components/SkuSummaryTable.vue | 10 +- .../product/overview/components/StatCards.vue | 199 ----------- .../product/overview/constants/product-ui.ts | 16 + .../src/views/ec/product/overview/index.vue | 241 +++++++++---- 14 files changed, 1070 insertions(+), 1097 deletions(-) create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/support/BiFinanceKpiAssembler.java create mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/components/ProductHeroBanner.vue create mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/components/ProductSkuRankStrip.vue delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/components/SalesTrendChart.vue delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/components/SkuSalesTop10Panel.vue delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/components/StatCards.vue create mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/product/overview/constants/product-ui.ts diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/model/vo/ProductOverviewVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/model/vo/ProductOverviewVO.java index 862beda6..2fd15b7b 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/model/vo/ProductOverviewVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/model/vo/ProductOverviewVO.java @@ -2,351 +2,123 @@ package top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; +import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchCostSliceVO; +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; /** - * 商品概览响应VO + * 商品概览响应:经营 KPI/趋势与工作台经营概览同口径,并附 SKU 明细。 */ @Data public class ProductOverviewVO { - /** - * 商品ID - */ private Long productId; - /** - * 商品名称 - */ private String productName; - // ========== KPI 汇总指标 ========== + /** 与工作台经营概览同结构的 KPI 列表 */ + private List kpis; - /** - * 总销售额 - */ + /** 成交/净销售/利润日趋势(与工作台 dealTrend 同形) */ + private List dealTrend; + + /** 各 SKU 净销售额占比(饼图) */ + private List skuSalesShare; + + private String momCompareDateStart; + private String momCompareDateEnd; + private String yoyCompareDateStart; + private String yoyCompareDateEnd; + + /** 兼容 Agent/旧前端:扁平 KPI 摘要 */ private BigDecimal totalSalesAmount; - - /** - * 较上月同期增长百分比 - */ private BigDecimal monthOverMonthGrowth; - - /** - * 总订单量 - */ private Integer totalOrderCount; - - /** - * 平均费比(推广费/销售额) - */ private BigDecimal averageFeeRatio; - - /** - * 总净利润(税后) - */ private BigDecimal totalNetProfitAfterTax; - - /** - * 扣除总税额 - */ private BigDecimal totalTaxAmount; - - /** - * 销量目标达成率 - */ private BigDecimal orderCountAchievementRate; - - /** - * 销售额目标达成率 - */ private BigDecimal salesAmountAchievementRate; - - /** - * 汇总ROI - */ private BigDecimal totalROI; - // ========== 各规格销量 Top10 ========== - - /** - * 各规格销量 Top10(按单量降序,最多10条) - */ private List specSalesTop10; - // ========== 趋势数据 ========== - - /** - * 销售额趋势分析 - */ + /** @deprecated 使用 dealTrend;保留以免旧客户端空指针 */ private TrendData salesAmountTrend; - - /** - * 单量趋势分析 - */ + /** @deprecated 使用 dealTrend */ private TrendData orderCountTrend; - // ========== 规格销售汇总 ========== - - /** - * 规格销售汇总(含各规格明细列表和合计行) - */ private SpecSummary specSummaries; - // ========== 内部类 ========== - - /** - * 趋势数据 - */ @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; } - /** - * 规格销售汇总 - */ @Data public static class SpecSummary { - /** - * 各规格明细列表 - */ private List list; - - /** - * 合计行 - */ private SpecSummaryTotal total; } - /** - * 规格销售明细项 - */ @Data public static class SpecSummaryItem { - /** - * 规格ID - */ private Long skuId; - - /** - * 规格名称 - */ private String skuName; - - /** - * 规格编码 - */ private String skuCode; - - /** - * 销售额 - */ private BigDecimal salesAmount; - - /** - * 订单量(按平台订单号去重) - */ private Integer orderCount; - - /** - * 总件数 - */ private Integer quantity; - - /** - * 客单价 - */ private BigDecimal averageOrderValue; - - /** - * 商品成本 - */ private BigDecimal productCost; - - /** - * 运费 - */ private BigDecimal shippingCost; - - /** - * 其他成本 - */ private BigDecimal otherCost; - - /** - * 订单成本(商品成本+运费+其他成本,不含推广费、刷单费) - */ private BigDecimal orderCost; - - /** - * 退款金额 - */ private BigDecimal refundAmount; - - /** - * 推广费 - */ private BigDecimal promotionFee; - - /** - * 费比(推广费/销售额) - */ private BigDecimal feeRatio; - - /** - * 税前盈亏 - */ private BigDecimal profitBeforeTax; - - /** - * 销售额×税率的税额 - */ private BigDecimal salesTaxAmount; - - /** - * ROI - */ private BigDecimal roi; - - /** - * 税后盈亏 - */ private BigDecimal profitAfterTax; } - /** - * 规格销售汇总合计行 - */ @Data public static class SpecSummaryTotal { - /** - * 销售额 - */ private BigDecimal salesAmount; - - /** - * 订单量 - */ private Integer orderCount; - - /** - * 总件数 - */ private Integer quantity; - - /** - * 商品成本 - */ private BigDecimal productCost; - - /** - * 运费 - */ private BigDecimal shippingCost; - - /** - * 其他成本 - */ private BigDecimal otherCost; - - /** - * 订单成本(商品成本+运费+其他成本,不含推广费、刷单费) - */ private BigDecimal orderCost; - - /** - * 退款金额 - */ private BigDecimal refundAmount; - - /** - * 推广费 - */ private BigDecimal promotionFee; - - /** - * 费比 - */ private BigDecimal feeRatio; - - /** - * 税前盈亏 - */ private BigDecimal profitBeforeTax; - - /** - * 税额 - */ private BigDecimal salesTaxAmount; - - /** - * ROI - */ private BigDecimal roi; - - /** - * 税后盈亏 - */ private BigDecimal profitAfterTax; } - /** - * 规格销量排名项 - */ @Data public static class SpecSalesRankItem { - /** - * 规格ID - */ private Long skuId; - - /** - * 规格名称 - */ private String skuName; - - /** - * 规格编码 - */ private String skuCode; - - /** - * 订单量 - */ private Integer orderCount; - - /** - * 销售额 - */ private BigDecimal salesAmount; } -} \ No newline at end of file +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/service/impl/BiProductOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/service/impl/BiProductOverviewServiceImpl.java index 699a8e4b..2ca3a106 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/service/impl/BiProductOverviewServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/service/impl/BiProductOverviewServiceImpl.java @@ -6,17 +6,20 @@ 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.productoverview.service.BiProductOverviewService; -import top.xyquan.ecomdmbbackend.modules.bi.workbench.support.BiWorkbenchFeeLoader; 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.ec.product.sku.mapper.ProductSkuMapper; -import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO; -import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO; import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.dto.ProductOverviewQueryDTO; import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo.ProductOverviewVO; +import top.xyquan.ecomdmbbackend.modules.bi.productoverview.service.BiProductOverviewService; +import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchCostSliceVO; +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.monthlytarget.mapper.ShopMonthlyTargetMapper; import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.model.po.ShopMonthlyTargetPO; @@ -26,7 +29,6 @@ import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.LocalDate; -import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; @@ -38,8 +40,7 @@ import java.util.Set; import java.util.stream.Collectors; /** - * 商品概览:Mongo product/sku 日汇聚 + MySQL 推广/目标。 - * 推广分摊复用工作台四表(按店全量商品行作分母),不再扫订单明细。 + * 商品概览:Mongo product/sku 日汇聚 + 经营 KPI(与工作台同口径)。 */ @Service public class BiProductOverviewServiceImpl implements BiProductOverviewService { @@ -87,7 +88,6 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService { 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); @@ -96,10 +96,53 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService { } } - // 先拉本商品日文档,确定涉及店铺 List shopIdFilter = filterShopId != null ? List.of(filterShopId) : null; + PeriodBundle cur = loadPeriod(companyId, product.getId(), shopIdFilter, filterShopId, start, end, taxRate); + + LocalDate[] mom = BiFinanceKpiAssembler.lastMonthSameSpan(start, end); + LocalDate[] yoy = BiFinanceKpiAssembler.yoySameSpan(start, end); + PeriodBundle prev = loadPeriod(companyId, product.getId(), shopIdFilter, filterShopId, mom[0], mom[1], taxRate); + PeriodBundle yoyBundle = loadPeriod(companyId, product.getId(), 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); + + List skuDocs = + orderStatQueryService.listSkuDocs(companyId, product.getId(), shopIdFilter, start, end); + List skuMetrics = + orderStatQueryService.sumSkuDocsBySku(skuDocs); + ProductOverviewVO.SpecSummary specSummaries = + buildSpecSummary(skuMetrics, taxRate, curT.promotion()); + + ProductOverviewVO vo = new ProductOverviewVO(); + vo.setProductId(product.getId()); + vo.setProductName(product.getName()); + vo.setKpis(BiFinanceKpiAssembler.buildKpis(curT, prevT, yoyT, start, end, taxRate)); + vo.setDealTrend(dealTrend); + vo.setSkuSalesShare(buildSkuSalesShare(specSummaries, curT.totalSales())); + vo.setMomCompareDateStart(mom[0].toString()); + vo.setMomCompareDateEnd(mom[1].toString()); + vo.setYoyCompareDateStart(yoy[0].toString()); + vo.setYoyCompareDateEnd(yoy[1].toString()); + vo.setSpecSummaries(specSummaries); + vo.setSpecSalesTop10(buildSpecTop10(specSummaries)); + fillLegacyFlatFields(vo, curT, prevT); + fillTargets(vo, companyId, cur.shopIds(), start, end, curT.totalSales(), curT.orderCount()); + fillLegacyTrends(vo, dealTrend); + return vo; + } + + /** + * 加载单区间:店铺范围 + 商品分摊后的经营 Totals + 日趋势行。 + */ + private PeriodBundle loadPeriod(Long companyId, Long productId, List shopIdFilter, Long filterShopId, + LocalDate start, LocalDate end, BigDecimal taxRate) { List thisProductDocs = - orderStatQueryService.listProductDocs(companyId, shopIdFilter, product.getId(), start, end); + orderStatQueryService.listProductDocs(companyId, shopIdFilter, productId, start, end); List shopIds; if (filterShopId != null) { @@ -121,83 +164,74 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService { s -> s.getPlatformCode() != null ? s.getPlatformCode() : "", (a, b) -> a)); - // 店内全量商品行:推广分摊分母(替代 allShopOrdersForPromo) - List allProductDocs = shopIds.isEmpty() - ? List.of() - : orderStatQueryService.listProductDocs(companyId, shopIds, start, end); - BiWorkbenchFeeLoader.FeeBundle fees = shopIds.isEmpty() - ? new BiWorkbenchFeeLoader.FeeBundle(List.of(), List.of()) - : feeLoader.load(companyId, shopIds, start, end); + List dailyRows = + orderStatQueryService.toDailyRowsFromProductDocs(thisProductDocs); + if (shops.isEmpty()) { + return new PeriodBundle(List.of(), BiFinanceKpiAssembler.Totals.empty(), dailyRows); + } + + 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 = shops.isEmpty() - ? emptyTables() - : companyOverviewService.buildWorkbenchSummaryTablesFromAgg( + CompanyOverviewVO.WorkbenchTableBundle tables = + companyOverviewService.buildWorkbenchSummaryTablesFromAgg( taxRate, companyId, shops, orderRows, fees.promotionRows(), fees.brushRows(), start, end); - - CompanyOverviewVO.CategorySummary productRow = findProductRow(tables.getProductTable(), product.getId()); - - BigDecimal sales = productRow != null ? nz(productRow.getSalesAmount()) : sumSales(thisProductDocs); - int orderCount = productRow != null && productRow.getSalesOrderCount() != null - ? productRow.getSalesOrderCount() - : sumOrders(thisProductDocs); - BigDecimal promo = productRow != null ? nz(productRow.getTotalPromotionFee()) : BigDecimal.ZERO; - BigDecimal orderCost = productRow != null ? nz(productRow.getOrderCost()) - : sumCost(thisProductDocs); - BigDecimal tax = salesTaxOnNet(sales, taxRate); - BigDecimal net = sales.subtract(orderCost).subtract(promo).subtract(tax); - - ProductOverviewVO vo = new ProductOverviewVO(); - vo.setProductId(product.getId()); - vo.setProductName(product.getName()); - vo.setTotalSalesAmount(sales.setScale(2, RoundingMode.HALF_UP)); - vo.setTotalOrderCount(orderCount); - vo.setAverageFeeRatio(sales.compareTo(BigDecimal.ZERO) > 0 - ? promo.divide(sales, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP) - : BigDecimal.ZERO); - vo.setTotalTaxAmount(tax); - vo.setTotalNetProfitAfterTax(net.setScale(2, RoundingMode.HALF_UP)); - vo.setTotalROI(roi(sales, promo)); - vo.setMonthOverMonthGrowth(calcPrevPeriodGrowth(companyId, product.getId(), shopIdFilter, - start, end, sales)); - - fillTargets(vo, companyId, shopIds, start, end, sales, orderCount); - - Map daily = - orderStatQueryService.toDailyRowsFromProductDocs(thisProductDocs).stream() - .filter(d -> d.getStatDate() != null) - .collect(Collectors.toMap(OverviewAggRows.DailyRow::getStatDate, d -> d, (a, b) -> a)); - vo.setSalesAmountTrend(buildTrend(start, end, daily, true)); - vo.setOrderCountTrend(buildTrend(start, end, daily, false)); - - List skuDocs = - orderStatQueryService.listSkuDocs(companyId, product.getId(), shopIdFilter, start, end); - List skuMetrics = - orderStatQueryService.sumSkuDocsBySku(skuDocs); - vo.setSpecSummaries(buildSpecSummary(skuMetrics, taxRate, promo)); - vo.setSpecSalesTop10(buildSpecTop10(vo.getSpecSummaries())); - - return vo; + CompanyOverviewVO.CategorySummary productRow = findProductRow(tables.getProductTable(), productId); + BiFinanceKpiAssembler.Totals totals = productRow != null + ? BiFinanceKpiAssembler.fromCategorySummary(productRow, taxRate) + : BiFinanceKpiAssembler.Totals.empty(); + return new PeriodBundle(shopIds, totals, dailyRows); } - private BigDecimal calcPrevPeriodGrowth(Long companyId, Long productId, List shopIds, - LocalDate start, LocalDate end, BigDecimal curSales) { - long dayCount = ChronoUnit.DAYS.between(start, end) + 1; - LocalDate prevStart = start.minusDays(dayCount); - LocalDate prevEnd = start.minusDays(1); - List prevDocs = - orderStatQueryService.listProductDocs(companyId, shopIds, productId, prevStart, prevEnd); - BigDecimal last = sumSales(prevDocs); - if (last.compareTo(BigDecimal.ZERO) > 0) { - return curSales.subtract(last) - .divide(last, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) - .setScale(2, RoundingMode.HALF_UP); + private void fillLegacyFlatFields(ProductOverviewVO vo, + BiFinanceKpiAssembler.Totals cur, + BiFinanceKpiAssembler.Totals prev) { + vo.setTotalSalesAmount(BiFinanceKpiAssembler.yuan2(cur.totalSales())); + vo.setTotalOrderCount(cur.orderCount()); + 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.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(ProductOverviewVO vo, List dealTrend) { + ProductOverviewVO.TrendData sales = new ProductOverviewVO.TrendData(); + ProductOverviewVO.TrendData orders = new ProductOverviewVO.TrendData(); + List salesItems = new ArrayList<>(); + List orderItems = new ArrayList<>(); + BigDecimal salesTotal = BigDecimal.ZERO; + BigDecimal orderTotal = BigDecimal.ZERO; + if (dealTrend != null) { + for (WorkbenchTrendPointVO p : dealTrend) { + ProductOverviewVO.TrendDataItem s = new ProductOverviewVO.TrendDataItem(); + s.setDate(LocalDate.parse(p.getDate())); + s.setValue(BiFinanceKpiAssembler.nz(p.getSalesYuan())); + salesItems.add(s); + salesTotal = salesTotal.add(s.getValue()); + + ProductOverviewVO.TrendDataItem o = new ProductOverviewVO.TrendDataItem(); + o.setDate(s.getDate()); + o.setValue(BigDecimal.valueOf(p.getSalesOrderCount() != null ? p.getSalesOrderCount() : 0)); + orderItems.add(o); + orderTotal = orderTotal.add(o.getValue()); + } } - return curSales.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100.00") : BigDecimal.ZERO; + sales.setDailyDataList(salesItems); + sales.setTotal(salesTotal); + orders.setDailyDataList(orderItems); + orders.setTotal(orderTotal); + vo.setSalesAmountTrend(sales); + vo.setOrderCountTrend(orders); } private void fillTargets(ProductOverviewVO vo, Long companyId, List shopIds, @@ -233,13 +267,39 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService { } } + private List buildSkuSalesShare(ProductOverviewVO.SpecSummary summary, + BigDecimal salesTotal) { + if (summary == null || summary.getList() == null || summary.getList().isEmpty()) { + return List.of(); + } + BigDecimal base = BiFinanceKpiAssembler.nz(salesTotal); + return summary.getList().stream() + .filter(i -> BiFinanceKpiAssembler.nz(i.getSalesAmount()).compareTo(BigDecimal.ZERO) > 0) + .sorted(Comparator.comparing(ProductOverviewVO.SpecSummaryItem::getSalesAmount, + Comparator.nullsFirst(BigDecimal::compareTo)).reversed()) + .limit(12) + .map(i -> { + BigDecimal amt = BiFinanceKpiAssembler.nz(i.getSalesAmount()); + BigDecimal pct = base.compareTo(BigDecimal.ZERO) > 0 + ? amt.multiply(new BigDecimal("100")).divide(base, 2, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + String name = i.getSkuName() != null ? i.getSkuName() : "SKU"; + return WorkbenchCostSliceVO.builder() + .name(name) + .value(BiFinanceKpiAssembler.yuan2(amt)) + .pct(pct) + .build(); + }) + .collect(Collectors.toList()); + } + private ProductOverviewVO.SpecSummary buildSpecSummary( List metrics, BigDecimal taxRate, BigDecimal totalPromo) { BigDecimal salesPool = metrics.stream() .map(BiOrderStatQueryService.SkuPeriodMetrics::salesAmount) - .map(BiProductOverviewServiceImpl::nz) + .map(BiFinanceKpiAssembler::nz) .reduce(BigDecimal.ZERO, BigDecimal::add); Set skuIds = metrics.stream() @@ -257,11 +317,12 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService { List list = new ArrayList<>(); for (BiOrderStatQueryService.SkuPeriodMetrics m : metrics) { - BigDecimal sales = nz(m.salesAmount()); + BigDecimal sales = BiFinanceKpiAssembler.nz(m.salesAmount()); BigDecimal sharePromo = salesPool.compareTo(BigDecimal.ZERO) > 0 - ? nz(totalPromo).multiply(sales).divide(salesPool, 4, RoundingMode.HALF_UP) + ? BiFinanceKpiAssembler.nz(totalPromo).multiply(sales) + .divide(salesPool, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; - BigDecimal refund = nz(m.refundAmount()); + BigDecimal refund = BiFinanceKpiAssembler.nz(m.refundAmount()); BigDecimal cost = m.orderCost(); BigDecimal tax = salesTaxOnNet(sales, taxRate); BigDecimal pbt = sales.subtract(cost).subtract(sharePromo); @@ -279,9 +340,9 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService { item.setAverageOrderValue(m.salesOrderCount() > 0 ? sales.divide(BigDecimal.valueOf(m.salesOrderCount()), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO); - item.setProductCost(nz(m.productCost()).setScale(2, RoundingMode.HALF_UP)); - item.setShippingCost(nz(m.freightCost()).setScale(2, RoundingMode.HALF_UP)); - item.setOtherCost(nz(m.otherCost()).setScale(2, RoundingMode.HALF_UP)); + item.setProductCost(BiFinanceKpiAssembler.nz(m.productCost()).setScale(2, RoundingMode.HALF_UP)); + item.setShippingCost(BiFinanceKpiAssembler.nz(m.freightCost()).setScale(2, RoundingMode.HALF_UP)); + item.setOtherCost(BiFinanceKpiAssembler.nz(m.otherCost()).setScale(2, RoundingMode.HALF_UP)); item.setOrderCost(cost.setScale(2, RoundingMode.HALF_UP)); item.setRefundAmount(refund.setScale(2, RoundingMode.HALF_UP)); item.setPromotionFee(sharePromo.setScale(2, RoundingMode.HALF_UP)); @@ -297,22 +358,32 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService { Comparator.nullsFirst(BigDecimal::compareTo)).reversed()); ProductOverviewVO.SpecSummaryTotal total = new ProductOverviewVO.SpecSummaryTotal(); - total.setSalesAmount(list.stream().map(i -> nz(i.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add)); + total.setSalesAmount(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getSalesAmount())) + .reduce(BigDecimal.ZERO, BigDecimal::add)); total.setOrderCount(list.stream().mapToInt(i -> i.getOrderCount() != null ? i.getOrderCount() : 0).sum()); total.setQuantity(list.stream().mapToInt(i -> i.getQuantity() != null ? i.getQuantity() : 0).sum()); - total.setProductCost(list.stream().map(i -> nz(i.getProductCost())).reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setShippingCost(list.stream().map(i -> nz(i.getShippingCost())).reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setOtherCost(list.stream().map(i -> nz(i.getOtherCost())).reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setOrderCost(list.stream().map(i -> nz(i.getOrderCost())).reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setRefundAmount(list.stream().map(i -> nz(i.getRefundAmount())).reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setPromotionFee(list.stream().map(i -> nz(i.getPromotionFee())).reduce(BigDecimal.ZERO, BigDecimal::add)); + total.setProductCost(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getProductCost())) + .reduce(BigDecimal.ZERO, BigDecimal::add)); + total.setShippingCost(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getShippingCost())) + .reduce(BigDecimal.ZERO, BigDecimal::add)); + total.setOtherCost(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getOtherCost())) + .reduce(BigDecimal.ZERO, BigDecimal::add)); + total.setOrderCost(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getOrderCost())) + .reduce(BigDecimal.ZERO, BigDecimal::add)); + total.setRefundAmount(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getRefundAmount())) + .reduce(BigDecimal.ZERO, BigDecimal::add)); + total.setPromotionFee(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getPromotionFee())) + .reduce(BigDecimal.ZERO, BigDecimal::add)); total.setFeeRatio(total.getSalesAmount().compareTo(BigDecimal.ZERO) > 0 ? total.getPromotionFee().divide(total.getSalesAmount(), 4, RoundingMode.HALF_UP) : BigDecimal.ZERO); - total.setProfitBeforeTax(list.stream().map(i -> nz(i.getProfitBeforeTax())).reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setSalesTaxAmount(list.stream().map(i -> nz(i.getSalesTaxAmount())).reduce(BigDecimal.ZERO, BigDecimal::add)); + total.setProfitBeforeTax(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getProfitBeforeTax())) + .reduce(BigDecimal.ZERO, BigDecimal::add)); + total.setSalesTaxAmount(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getSalesTaxAmount())) + .reduce(BigDecimal.ZERO, BigDecimal::add)); total.setRoi(roi(total.getSalesAmount(), total.getPromotionFee())); - total.setProfitAfterTax(list.stream().map(i -> nz(i.getProfitAfterTax())).reduce(BigDecimal.ZERO, BigDecimal::add)); + total.setProfitAfterTax(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getProfitAfterTax())) + .reduce(BigDecimal.ZERO, BigDecimal::add)); ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary(); summary.setList(list); @@ -343,29 +414,6 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService { .collect(Collectors.toList()); } - private static ProductOverviewVO.TrendData buildTrend( - LocalDate start, LocalDate end, - Map daily, - boolean sales) { - List items = new ArrayList<>(); - BigDecimal total = BigDecimal.ZERO; - for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) { - OverviewAggRows.DailyRow row = daily.get(d); - BigDecimal value = sales - ? (row != null ? nz(row.getSalesAmount()) : BigDecimal.ZERO) - : BigDecimal.valueOf(row != null && row.getOrderCount() != null ? row.getOrderCount() : 0L); - ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem(); - item.setDate(d); - item.setValue(value); - items.add(item); - total = total.add(value); - } - ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData(); - trend.setTotal(total); - trend.setDailyDataList(items); - return trend; - } - private static CompanyOverviewVO.CategorySummary findProductRow( CompanyOverviewVO.CategoryOverview table, Long productId) { if (table == null || table.getCategories() == null || productId == null) { @@ -377,53 +425,24 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService { .orElse(null); } - private static CompanyOverviewVO.WorkbenchTableBundle emptyTables() { - CompanyOverviewVO.WorkbenchTableBundle b = new CompanyOverviewVO.WorkbenchTableBundle(); - CompanyOverviewVO.CategoryOverview empty = new CompanyOverviewVO.CategoryOverview(); - empty.setCategories(List.of()); - b.setProductTable(empty); - b.setCategoryTable(empty); - return b; - } - - private static BigDecimal sumSales(List docs) { - return docs.stream() - .map(d -> nz(d.getDealAmount()).subtract(nz(d.getRefundAmount()))) - .reduce(BigDecimal.ZERO, BigDecimal::add); - } - - private static BigDecimal sumCost(List docs) { - return docs.stream() - .map(d -> nz(d.getProductCost()).add(nz(d.getFreightCost())).add(nz(d.getOtherCost()))) - .reduce(BigDecimal.ZERO, BigDecimal::add); - } - - private static int sumOrders(List docs) { - return docs.stream().mapToInt(d -> - nzInt(d.getDealOrderCount()) - nzInt(d.getRefundOrderCount())).sum(); - } - - /** 税额 = 净销售额 × 税率 */ private static BigDecimal salesTaxOnNet(BigDecimal sales, BigDecimal taxRate) { - BigDecimal base = nz(sales); + BigDecimal base = BiFinanceKpiAssembler.nz(sales); if (base.compareTo(BigDecimal.ZERO) < 0) { base = BigDecimal.ZERO; } - return base.multiply(taxRate != null ? taxRate : DEFAULT_TAX_RATE).setScale(2, RoundingMode.HALF_UP); - } - - private static int nzInt(Integer v) { - return v != null ? v : 0; + return base.multiply(taxRate != null ? taxRate : DEFAULT_TAX_RATE) + .setScale(2, RoundingMode.HALF_UP); } private static BigDecimal roi(BigDecimal netSales, BigDecimal promo) { if (promo == null || promo.compareTo(BigDecimal.ZERO) <= 0) { return BigDecimal.ZERO; } - return nz(netSales).divide(promo, 4, RoundingMode.HALF_UP); + return BiFinanceKpiAssembler.nz(netSales).divide(promo, 4, RoundingMode.HALF_UP); } - private static BigDecimal nz(BigDecimal v) { - return v != null ? v : BigDecimal.ZERO; + 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/support/BiFinanceKpiAssembler.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/support/BiFinanceKpiAssembler.java new file mode 100644 index 00000000..242314cc --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/support/BiFinanceKpiAssembler.java @@ -0,0 +1,319 @@ +package top.xyquan.ecomdmbbackend.modules.bi.workbench.support; + +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.workbench.model.vo.WorkbenchKpiItemVO; +import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchTrendPointVO; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 经营财务 KPI / 趋势组装:工作台与商品概览共用,保证口径一致。 + */ +public final class BiFinanceKpiAssembler { + + private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04"); + private static final DateTimeFormatter TREND_DATE_FMT = DateTimeFormatter.ISO_LOCAL_DATE; + + private BiFinanceKpiAssembler() { + } + + /** + * 单时间段财务 KPI 总量。 + */ + public record Totals(BigDecimal totalSales, + BigDecimal totalRefund, + BigDecimal totalCost, + BigDecimal productCost, + BigDecimal freightCost, + BigDecimal otherCost, + BigDecimal promotion, + BigDecimal brush, + BigDecimal tax, + BigDecimal grossOrder, + BigDecimal netProfit, + int orderCount, + int salesQuantitySum, + BigDecimal totalDealAmount, + int dealOrderCount, + int dealQuantitySum, + BigDecimal averageOrderValue, + BigDecimal dealAverageOrderValue, + BigDecimal salesPiecePrice, + BigDecimal dealPiecePrice) { + public static Totals empty() { + return buildTotals(BigDecimal.ZERO, BigDecimal.ZERO, + BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, + BigDecimal.ZERO, BigDecimal.ZERO, DEFAULT_TAX_RATE, + 0, 0, BigDecimal.ZERO, 0, 0); + } + } + + public static Totals buildTotals(BigDecimal sales, BigDecimal refund, + BigDecimal pc, BigDecimal fc, BigDecimal oc, + BigDecimal promotion, BigDecimal brush, BigDecimal taxRate, + int orderCount, int salesQuantitySum, + BigDecimal totalDealAmount, int dealOrderCount, int dealQuantitySum) { + BigDecimal s = nz(sales); + BigDecimal cost = nz(pc).add(nz(fc)).add(nz(oc)); + BigDecimal promo = nz(promotion); + BigDecimal brushFee = nz(brush); + BigDecimal deal = nz(totalDealAmount); + BigDecimal gross = s.subtract(cost); + BigDecimal pbt = gross.subtract(promo).subtract(brushFee); + BigDecimal tax = salesTaxOnSales(s, taxRate); + BigDecimal aov = orderCount > 0 + ? s.divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; + BigDecimal dealAov = dealOrderCount > 0 + ? deal.divide(BigDecimal.valueOf(dealOrderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; + BigDecimal salesPiecePrice = salesQuantitySum > 0 + ? s.divide(BigDecimal.valueOf(salesQuantitySum), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; + BigDecimal dealPiecePrice = dealQuantitySum > 0 + ? deal.divide(BigDecimal.valueOf(dealQuantitySum), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; + return new Totals(s, nz(refund), cost, nz(pc), nz(fc), nz(oc), promo, brushFee, tax, + gross, pbt.subtract(tax), + orderCount, salesQuantitySum, deal, dealOrderCount, dealQuantitySum, + aov, dealAov, salesPiecePrice, dealPiecePrice); + } + + /** 从经营汇总表商品/品类行构造 Totals(税按税率重算,与工作台一致)。 */ + public static Totals fromCategorySummary(CompanyOverviewVO.CategorySummary row, BigDecimal taxRate) { + if (row == null) { + return Totals.empty(); + } + return buildTotals( + nz(row.getSalesAmount()), + nz(row.getRefundAmount()), + nz(row.getProductCost()), + nz(row.getShippingCost()), + nz(row.getOtherCost()), + nz(row.getTotalPromotionFee()), + nz(row.getBrushFee()), + taxRate, + row.getSalesOrderCount() != null ? row.getSalesOrderCount() : 0, + row.getSalesQuantitySum() != null ? row.getSalesQuantitySum() : 0, + nz(row.getDealAmount()), + row.getDealOrderCount() != null ? row.getDealOrderCount() : 0, + row.getDealQuantitySum() != null ? row.getDealQuantitySum() : 0); + } + + public static List buildKpis(Totals cur, Totals prev, Totals yoy, + LocalDate start, LocalDate end, BigDecimal taxRate) { + int days = (int) (end.toEpochDay() - start.toEpochDay() + 1); + Totals c = cur != null ? cur : Totals.empty(); + Totals p = prev != null ? prev : Totals.empty(); + Totals y = yoy != null ? yoy : Totals.empty(); + + BigDecimal grossMarginPct = safePct(c.grossOrder(), c.totalSales()); + BigDecimal netMarginPct = safePct(c.netProfit(), c.totalSales()); + BigDecimal refundRate = safePct(c.totalRefund(), c.totalSales()); + BigDecimal costRate = safePct(c.totalCost(), c.totalSales()); + BigDecimal roi = c.promotion().compareTo(BigDecimal.ZERO) > 0 + ? c.totalSales().divide(c.promotion(), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; + BigDecimal yoyRoi = y.promotion().compareTo(BigDecimal.ZERO) > 0 + ? y.totalSales().divide(y.promotion(), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; + BigDecimal prevRoi = p.promotion().compareTo(BigDecimal.ZERO) > 0 + ? p.totalSales().divide(p.promotion(), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; + + BigDecimal avgDailySalesOrders = days > 0 + ? BigDecimal.valueOf(c.orderCount()).divide(BigDecimal.valueOf(days), 1, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + BigDecimal avgDailyDealOrders = days > 0 + ? BigDecimal.valueOf(c.dealOrderCount()).divide(BigDecimal.valueOf(days), 1, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + + List list = new ArrayList<>(); + list.add(kpi("成交金额", yuan2(c.totalDealAmount()), "元", c.totalDealAmount(), p.totalDealAmount(), y.totalDealAmount(), + "成交状态实收", c.totalDealAmount(), true)); + list.add(kpiCount("成交单量", c.dealOrderCount(), p.dealOrderCount(), y.dealOrderCount(), "单", + "日均 " + avgDailyDealOrders.stripTrailingZeros().toPlainString() + " 单")); + list.add(kpiCount("成交销量", c.dealQuantitySum(), p.dealQuantitySum(), y.dealQuantitySum(), "件", "成交状态件数")); + list.add(kpi("成交客单价", yuan2(c.dealAverageOrderValue()), "元", + c.dealAverageOrderValue(), p.dealAverageOrderValue(), y.dealAverageOrderValue(), + "成交金额/成交单量", c.dealAverageOrderValue(), false)); + + list.add(kpi("净销售额", yuan2(c.totalSales()), "元", c.totalSales(), p.totalSales(), y.totalSales(), + "成交−退款", c.totalSales(), true)); + list.add(kpiCount("净销售单量", c.orderCount(), p.orderCount(), y.orderCount(), "单", + "日均 " + avgDailySalesOrders.stripTrailingZeros().toPlainString() + " 单")); + list.add(kpiCount("净销量", c.salesQuantitySum(), p.salesQuantitySum(), y.salesQuantitySum(), "件", + "成交件数−退款件数")); + list.add(kpi("净销售客单价", yuan2(c.averageOrderValue()), "元", + c.averageOrderValue(), p.averageOrderValue(), y.averageOrderValue(), + "净销售额/净销售单量", c.averageOrderValue(), false)); + + list.add(kpi("退款额", yuan2(c.totalRefund()), "元", c.totalRefund(), p.totalRefund(), y.totalRefund(), + "计入退款状态", c.totalRefund(), true)); + list.add(kpi("退款率", refundRate.setScale(2, RoundingMode.HALF_UP), "%", + refundRate, safePct(p.totalRefund(), p.totalSales()), safePct(y.totalRefund(), y.totalSales()), + "退款/净销售额", null, null)); + + list.add(kpi("订单成本", yuan2(c.totalCost()), "元", c.totalCost(), p.totalCost(), y.totalCost(), + "成本率 " + costRate.stripTrailingZeros().toPlainString() + "%", c.totalCost(), true)); + list.add(kpi("商品成本", yuan2(c.productCost()), "元", c.productCost(), p.productCost(), y.productCost(), + null, c.productCost(), true)); + list.add(kpi("运费成本", yuan2(c.freightCost()), "元", c.freightCost(), p.freightCost(), y.freightCost(), + null, c.freightCost(), true)); + list.add(kpi("其他成本", yuan2(c.otherCost()), "元", c.otherCost(), p.otherCost(), y.otherCost(), + null, c.otherCost(), true)); + + list.add(kpi("毛利润", yuan2(c.grossOrder()), "元", c.grossOrder(), p.grossOrder(), y.grossOrder(), + "毛利率 " + grossMarginPct.stripTrailingZeros().toPlainString() + "%", c.grossOrder(), true)); + list.add(kpi("推广费", yuan2(c.promotion()), "元", c.promotion(), p.promotion(), y.promotion(), + null, c.promotion(), true)); + list.add(kpi("刷单费", yuan2(c.brush()), "元", c.brush(), p.brush(), y.brush(), + null, c.brush(), true)); + BigDecimal rate = taxRate != null ? taxRate : DEFAULT_TAX_RATE; + list.add(kpi("税额", yuan2(c.tax()), "元", c.tax(), p.tax(), y.tax(), + "税率 " + rate.multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString() + "%", + c.tax(), true)); + list.add(kpi("净利润", yuan2(c.netProfit()), "元", c.netProfit(), p.netProfit(), y.netProfit(), + "净利率 " + netMarginPct.stripTrailingZeros().toPlainString() + "%", + c.netProfit(), true)); + + list.add(kpi("广告ROI", roi.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros(), ":1", roi, prevRoi, yoyRoi, + "净销售额/推广费", null, null)); + return list; + } + + public static List buildTrendFromDaily( + List dailyRows, + LocalDate start, LocalDate end, Totals periodTotals) { + Map byDay = new HashMap<>(); + if (dailyRows != null) { + for (OverviewAggRows.DailyRow row : dailyRows) { + if (row.getStatDate() != null) { + byDay.put(row.getStatDate(), row); + } + } + } + Totals totals = periodTotals != null ? periodTotals : Totals.empty(); + BigDecimal salesTotal = totals.totalSales(); + List list = new ArrayList<>(); + for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) { + OverviewAggRows.DailyRow row = byDay.get(d); + BigDecimal sales = row != null ? nz(row.getSalesAmount()) : BigDecimal.ZERO; + BigDecimal deal = row != null ? nz(row.getDealAmount()) : BigDecimal.ZERO; + int salesOrders = row != null && row.getOrderCount() != null ? row.getOrderCount().intValue() : 0; + int dealOrders = row != null && row.getDealOrderCount() != null ? row.getDealOrderCount().intValue() : 0; + BigDecimal refund = row != null ? nz(row.getRefundAmount()) : BigDecimal.ZERO; + BigDecimal cost = row != null + ? nz(row.getProductCost()).add(nz(row.getFreightCost())).add(nz(row.getOtherCost())) + : BigDecimal.ZERO; + BigDecimal gross = sales.subtract(cost); + BigDecimal promoB = allocShare(sales, salesTotal, totals.promotion()); + BigDecimal brushB = allocShare(sales, salesTotal, totals.brush()); + BigDecimal taxB = salesTotal.compareTo(BigDecimal.ZERO) <= 0 + ? BigDecimal.ZERO + : allocShare(sales, salesTotal.max(BigDecimal.ONE), totals.tax()); + list.add(WorkbenchTrendPointVO.builder() + .date(d.format(TREND_DATE_FMT)) + .dealYuan(yuan2(deal)) + .dealOrderCount(dealOrders) + .salesYuan(yuan2(sales)) + .salesOrderCount(salesOrders) + .profitYuan(yuan2(gross)) + .netProfitYuan(yuan2(gross.subtract(promoB).subtract(brushB).subtract(taxB))) + .refundYuan(yuan2(refund)) + .build()); + } + return list; + } + + public static LocalDate[] lastMonthSameSpan(LocalDate start, LocalDate end) { + return new LocalDate[]{start.minusMonths(1), end.minusMonths(1)}; + } + + public static LocalDate[] yoySameSpan(LocalDate start, LocalDate end) { + return new LocalDate[]{start.minusYears(1), end.minusYears(1)}; + } + + public static BigDecimal allocShare(BigDecimal part, BigDecimal total, BigDecimal amount) { + if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) { + return BigDecimal.ZERO; + } + if (total == null || total.compareTo(BigDecimal.ZERO) <= 0) { + return BigDecimal.ZERO; + } + return amount.multiply(part).divide(total, 4, RoundingMode.HALF_UP); + } + + public static BigDecimal yuan2(BigDecimal yuan) { + if (yuan == null) { + return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP); + } + return yuan.setScale(2, RoundingMode.HALF_UP); + } + + public static BigDecimal safePct(BigDecimal num, BigDecimal den) { + if (den == null || den.compareTo(BigDecimal.ZERO) <= 0) { + return BigDecimal.ZERO; + } + if (num == null) { + return BigDecimal.ZERO; + } + return num.multiply(new BigDecimal("100")).divide(den, 2, RoundingMode.HALF_UP); + } + + public static BigDecimal pctChange(BigDecimal cur, BigDecimal prev) { + if (prev == null || prev.compareTo(BigDecimal.ZERO) == 0) { + if (cur != null && cur.compareTo(BigDecimal.ZERO) > 0) { + return new BigDecimal("100"); + } + return BigDecimal.ZERO; + } + return cur.subtract(prev).divide(prev, 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP); + } + + public static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } + + private static BigDecimal salesTaxOnSales(BigDecimal salesAmount, BigDecimal rate) { + BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO; + if (sales.compareTo(BigDecimal.ZERO) < 0) { + sales = BigDecimal.ZERO; + } + BigDecimal r = rate != null ? rate : DEFAULT_TAX_RATE; + return sales.multiply(r).setScale(2, RoundingMode.HALF_UP); + } + + private static WorkbenchKpiItemVO kpiCount(String label, int cur, int prev, int yoy, String unit, String sub) { + return kpi(label, BigDecimal.valueOf(cur), unit, + BigDecimal.valueOf(cur), BigDecimal.valueOf(prev), BigDecimal.valueOf(yoy), + sub, null, null); + } + + private static WorkbenchKpiItemVO kpi(String label, BigDecimal value, String unit, + BigDecimal curAmt, BigDecimal prevAmt, BigDecimal yoyAmt, String sub, + BigDecimal amountYuan, Boolean preferWanDisplay) { + BigDecimal change = pctChange(curAmt, prevAmt); + boolean up = curAmt.compareTo(prevAmt) >= 0; + BigDecimal yoyPct = pctChange(curAmt, yoyAmt); + boolean yoyUpFlag = curAmt.compareTo(yoyAmt) >= 0; + var b = WorkbenchKpiItemVO.builder() + .label(label) + .value(value) + .unit(unit) + .changePct(change) + .up(up) + .yoyChangePct(yoyPct) + .yoyUp(yoyUpFlag) + .sub(sub); + if (amountYuan != null) { + b.amountYuan(yuan2(amountYuan)); + } + if (preferWanDisplay != null) { + b.preferWanDisplay(preferWanDisplay); + } + return b.build(); + } +} diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/overview/types/types.vo.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/overview/types/types.vo.ts index 0017c7da..43044e58 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/overview/types/types.vo.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/overview/types/types.vo.ts @@ -1,155 +1,127 @@ export namespace ProductOverviewVO { - /** 趋势数据项 */ + /** 与工作台经营 KPI 同形 */ + 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; + } + + export interface PieSlice { + name: string; + value?: number; + pct?: number; + } + + /** @deprecated 旧趋势结构,优先用 dealTrend */ export interface TrendDataItem { - /** 日期 */ date: string; - /** 对应的值 */ value: number; } - /** 趋势数据 */ + /** @deprecated */ export interface TrendData { - /** 时间范围的总值 */ total: number; - /** 每日数据列表 */ dailyDataList: TrendDataItem[]; } - /** SKU 销量排名项 */ export interface SkuSalesRankItem { - /** SKU ID */ skuId?: number; - /** SKU 名称 */ skuName?: string; - /** SKU 编码 */ skuCode?: string; - /** 订单量 */ orderCount?: number; - /** 销售额 */ salesAmount?: number; } - /** SKU 销售明细项 */ export interface SkuSummaryItem { - /** SKU ID */ skuId: number; - /** SKU 名称 */ skuName: string; - /** SKU 编码 */ skuCode: string; - /** 销售额 */ salesAmount: number; - /** 订单量 */ orderCount: number; - /** 总件数 */ quantity: number; - /** 客单价 */ averageOrderValue: number; - /** 商品成本 */ productCost: number; - /** 运费 */ shippingCost: number; - /** 其他成本 */ otherCost: number; - /** 订单成本(商品成本+运费+其他成本,不含推广费、刷单费) */ orderCost?: number; - /** 退款金额 */ refundAmount: number; - /** 推广费 */ promotionFee: number; - /** 费比 */ feeRatio: number; - /** 税前盈亏 */ profitBeforeTax: number; - /** 销售额×税率的税额 */ salesTaxAmount: number; - /** ROI */ roi: number; - /** 税后盈亏 */ profitAfterTax: number; } - /** SKU 销售汇总合计行 */ export interface SkuSummaryTotal { - /** 销售额 */ salesAmount: number; - /** 订单量 */ orderCount: number; - /** 总件数 */ quantity: number; - /** 客单价(前端汇总或后端可选返回) */ averageOrderValue?: number; - /** 商品成本 */ productCost: number; - /** 运费 */ shippingCost: number; - /** 其他成本 */ otherCost: number; - /** 订单成本(商品成本+运费+其他成本,不含推广费、刷单费) */ orderCost?: number; - /** 退款金额 */ refundAmount: number; - /** 推广费 */ promotionFee: number; - /** 费比 */ feeRatio: number; - /** 税前盈亏 */ profitBeforeTax: number; - /** 税额 */ salesTaxAmount: number; - /** ROI */ roi: number; - /** 税后盈亏 */ profitAfterTax: number; } - /** SKU 销售汇总 */ export interface SkuSummary { - /** 各 SKU 明细列表 */ list: SkuSummaryItem[]; - /** 合计行 */ total: SkuSummaryTotal; } - /** 商品概览响应 */ export interface Overview { - /** 商品 ID */ productId: number; - /** 商品名称 */ productName: string; - // ========== KPI 汇总指标 ========== - /** 总销售额 */ - totalSalesAmount: number; - /** 较上月同期增长百分比 */ - monthOverMonthGrowth: number; - /** 总订单量 */ - totalOrderCount: number; - /** 平均费比 */ - averageFeeRatio: number; - /** 总净利润(税后) */ - totalNetProfitAfterTax: number; - /** 扣除总税额 */ - totalTaxAmount: number; - /** 销量目标达成率 */ - orderCountAchievementRate: number; - /** 销售额目标达成率 */ - salesAmountAchievementRate: number; - /** 汇总 ROI */ - totalROI: number; + /** 经营 KPI(与工作台同口径) */ + kpis?: KpiItem[]; + dealTrend?: TrendPoint[]; + skuSalesShare?: PieSlice[]; + momCompareDateStart?: string | null; + momCompareDateEnd?: string | null; + yoyCompareDateStart?: string | null; + yoyCompareDateEnd?: string | null; - // ========== 各 SKU 销量 Top10 ========== - /** 各 SKU 销量 Top10(后端字段名仍为 specSalesTop10) */ - specSalesTop10: SkuSalesRankItem[]; + totalSalesAmount?: number; + monthOverMonthGrowth?: number; + totalOrderCount?: number; + averageFeeRatio?: number; + totalNetProfitAfterTax?: number; + totalTaxAmount?: number; + orderCountAchievementRate?: number; + salesAmountAchievementRate?: number; + totalROI?: number; - // ========== 趋势数据 ========== - /** 销售额趋势分析 */ - salesAmountTrend: TrendData; - /** 单量趋势分析 */ - orderCountTrend: TrendData; - - // ========== SKU 销售汇总 ========== - /** SKU 销售汇总(后端字段名仍为 specSummaries) */ - specSummaries: SkuSummary; + specSalesTop10?: SkuSalesRankItem[]; + /** @deprecated */ + salesAmountTrend?: TrendData; + /** @deprecated */ + orderCountTrend?: TrendData; + specSummaries?: SkuSummary; } } diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/components/FinanceCostPieChart.vue b/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/components/FinanceCostPieChart.vue index 3e45a913..3844beb3 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/components/FinanceCostPieChart.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/bi/workbench/tabs/finance/components/FinanceCostPieChart.vue @@ -11,9 +11,23 @@ import { FINANCE_PANEL_SHELL } from '../constants/finance-ui'; defineOptions({ name: 'WorkbenchFinancePlatformSalesPieChart' }); -const props = defineProps<{ - platformSalesShare: WorkbenchVO.PieSlice[]; -}>(); +const props = withDefaults( + defineProps<{ + platformSalesShare: WorkbenchVO.PieSlice[]; + /** 面板标题,商品概览可改为「各 SKU 净销售额分布」 */ + title?: string; + subtitle?: string; + /** 覆盖面板外壳(商品概览等可传入自身主题 class) */ + panelClass?: string; + }>(), + { + title: '各平台净销售额分布', + subtitle: '占当前筛选条件下净销售额合计的比例', + panelClass: undefined, + }, +); + +const shellClass = computed(() => props.panelClass || FINANCE_PANEL_SHELL); const PLATFORM_PIE_COLORS = [ '#3b82f6', @@ -164,17 +178,17 @@ defineExpose({ redraw });