From 9af2efaf312ac7a3e9bce1cbbc42d9a21d31227c Mon Sep 17 00:00:00 2001 From: ah-max150 Date: Thu, 13 Aug 2026 09:31:07 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E5=AE=8C=E5=85=A8=E8=BF=81?= =?UTF-8?q?=E7=A7=BB=E5=BA=97=E9=93=BA=E6=A6=82=E8=A7=88=E5=92=8C=E5=95=86?= =?UTF-8?q?=E5=93=81=E6=A6=82=E8=A7=88=E5=88=B0bi=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ecom-dmb-backend/README.md | 12 +- .../query/BiOrderStatQueryService.java | 95 +- .../BiOrderStatDailyRepository.java | 44 +- .../overview/model/agg/OverviewAggRows.java | 4 +- .../overview/model/dto/CategoryExportDTO.java | 2 +- .../overview/model/dto/CompanyExportDTO.java | 2 +- .../overview/model/dto/PlatformExportDTO.java | 2 +- .../overview/model/vo/CompanyOverviewVO.java | 2 +- .../service/CategoryExportExcelService.java | 15 +- .../service/CompanyOverviewService.java | 28 + .../bi/overview/service/ExportService.java | 21 + .../impl/CategoryExportExcelServiceImpl.java | 143 +- .../impl/CompanyOverviewServiceImpl.java | 775 ++++++ .../service/impl/ExportServiceImpl.java | 188 +- .../service/impl/ExportStatusRangeHelper.java | 2 +- .../overview/util/ExportFilenameUtils.java | 2 +- .../BiProductOverviewController.java | 33 + .../model/dto/ProductOverviewQueryDTO.java | 2 +- .../model/vo/ProductOverviewVO.java | 2 +- .../service/BiProductOverviewService.java | 12 + .../impl/BiProductOverviewServiceImpl.java | 426 +++ .../controller/BiShopExportController.java} | 22 +- .../controller/BiShopOverviewController.java | 33 + .../model/dto/ShopExportDTO.java | 2 +- .../model/dto/ShopOverviewQueryDTO.java | 2 +- .../model/vo/ShopOverviewStatisticsVO.java | 2 +- .../service/BiShopExportService.java | 14 + .../service/BiShopOverviewService.java | 12 + .../impl/BiShopExportServiceImpl.java} | 28 +- .../impl/BiShopOverviewServiceImpl.java | 387 +++ .../BiWorkbenchExportController.java | 2 +- .../model/vo/WorkbenchFinanceSliceVO.java | 2 +- .../vo/WorkbenchPeriodCompareSliceVO.java | 2 +- .../workbench/service/BiWorkbenchService.java | 2 +- .../impl/BiWorkbenchExportServiceImpl.java | 12 +- .../service/impl/BiWorkbenchServiceImpl.java | 6 +- .../support/BiWorkbenchFeeLoader.java | 2 +- .../controller/CompanyOverviewController.java | 34 - .../overview/controller/ExportController.java | 70 - .../model/dto/CompanyOverviewQueryDTO.java | 35 - .../service/CompanyOverviewService.java | 68 - .../ec/overview/service/ExportService.java | 37 - .../ShopOverviewStatisticsService.java | 19 - .../impl/CompanyOverviewServiceImpl.java | 2333 ----------------- .../ShopOverviewStatisticsServiceImpl.java | 1072 -------- .../controller/ProductOverviewController.java | 39 - .../service/ProductOverviewService.java | 18 - .../impl/ProductOverviewServiceImpl.java | 834 ------ .../ec/shop/service/ShopExportService.java | 16 - .../src/main/resources/sql/init/sys_seed.sql | 4 - .../api/ecommerce/product-overview/apis.ts | 2 +- .../web-antd/src/api/ecommerce/shop/apis.ts | 29 +- .../src/api/ecommerce/store-overview/apis.ts | 43 - .../src/api/ecommerce/store-overview/index.ts | 4 +- .../ecommerce/store-overview/types/index.ts | 4 +- .../store-overview/types/types.dto.ts | 13 - .../store-overview/types/types.vo.ts | 2 +- .../src/locales/langs/en-US/page.json | 1 - .../src/locales/langs/zh-CN/page.json | 1 - .../src/router/routes/modules/dashboard.ts | 20 +- .../web-antd/src/utils/overview-date-range.ts | 2 +- .../web-antd/src/utils/overview-fee-ratio.ts | 2 +- .../components/CategoryComparisonTable.vue | 322 --- .../components/ComparisonSwitcher.vue | 159 -- .../store-overview/components/KpiCards.vue | 142 - .../components/PlatformSummaryCard.vue | 424 --- .../store-overview/components/ShopCharts.vue | 275 -- .../components/ShopComparisonTable.vue | 424 --- .../views/dashboard/store-overview/index.vue | 615 ----- .../src/views/dashboard/workbench/index.vue | 2 +- .../finance/components/OverviewTables.vue | 6 +- .../components/WorkbenchDimChartsCard.vue | 2 +- .../dashboard/workbench/tabs/multi/index.vue | 2 +- .../views/ecommerce/shop/overview/index.vue | 18 +- .../__snapshots__/config.test.ts.snap | 2 +- .../packages/@core/preferences/src/config.ts | 2 +- 76 files changed, 2020 insertions(+), 7419 deletions(-) rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec => bi}/overview/model/agg/OverviewAggRows.java (90%) rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec => bi}/overview/model/dto/CategoryExportDTO.java (95%) rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec => bi}/overview/model/dto/CompanyExportDTO.java (95%) rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec => bi}/overview/model/dto/PlatformExportDTO.java (94%) rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec => bi}/overview/model/vo/CompanyOverviewVO.java (99%) rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec => bi}/overview/service/CategoryExportExcelService.java (50%) create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/CompanyOverviewService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/ExportService.java rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec => bi}/overview/service/impl/CategoryExportExcelServiceImpl.java (75%) create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/CompanyOverviewServiceImpl.java rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec => bi}/overview/service/impl/ExportServiceImpl.java (75%) rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec => bi}/overview/service/impl/ExportStatusRangeHelper.java (96%) rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec => bi}/overview/util/ExportFilenameUtils.java (97%) create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/controller/BiProductOverviewController.java rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec/product/overview => bi/productoverview}/model/dto/ProductOverviewQueryDTO.java (94%) rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec/product/overview => bi/productoverview}/model/vo/ProductOverviewVO.java (99%) create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/service/BiProductOverviewService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/service/impl/BiProductOverviewServiceImpl.java rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec/shop/controller/ShopExportController.java => bi/shopoverview/controller/BiShopExportController.java} (80%) create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/controller/BiShopOverviewController.java rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec/overview => bi/shopoverview}/model/dto/ShopExportDTO.java (94%) rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec/overview => bi/shopoverview}/model/dto/ShopOverviewQueryDTO.java (95%) rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec/overview => bi/shopoverview}/model/vo/ShopOverviewStatisticsVO.java (99%) create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/BiShopExportService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/BiShopOverviewService.java rename ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/{ec/shop/service/impl/ShopExportServiceImpl.java => bi/shopoverview/service/impl/BiShopExportServiceImpl.java} (93%) create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/impl/BiShopOverviewServiceImpl.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/controller/CompanyOverviewController.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/controller/ExportController.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/CompanyOverviewQueryDTO.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/CompanyOverviewService.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/ExportService.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/ShopOverviewStatisticsService.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/CompanyOverviewServiceImpl.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/ShopOverviewStatisticsServiceImpl.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/controller/ProductOverviewController.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/service/ProductOverviewService.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/service/impl/ProductOverviewServiceImpl.java delete mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/shop/service/ShopExportService.java delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/apis.ts delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/types.dto.ts delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/CategoryComparisonTable.vue delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ComparisonSwitcher.vue delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/KpiCards.vue delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/PlatformSummaryCard.vue delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ShopCharts.vue delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ShopComparisonTable.vue delete mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/index.vue diff --git a/ecom-dmb-backend/README.md b/ecom-dmb-backend/README.md index d917f164..b21a4f45 100644 --- a/ecom-dmb-backend/README.md +++ b/ecom-dmb-backend/README.md @@ -75,13 +75,11 @@ ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/ | 模块 | 路径 | 说明 | |------|------|------| -| 全店概览统计 | POST /ec/store/overview | 全店铺汇总统计 | -| 全店概览-按店铺汇总导出 | POST /ec/store-overview/export/by-shop | Excel | -| 全店概览-按品类汇总导出 | POST /ec/store-overview/export/by-category | Excel | -| 全店概览-按平台汇总导出 | POST /ec/store-overview/export/by-platform | Excel | -| 店铺概览 | POST /ec/shop/overview-statistics | 单店铺统计 | -| 店铺按商品汇总导出 | POST /ec/shop/export/summary-by-product | Excel | -| 店铺按品类汇总导出 | POST /ec/shop/export/summary-by-category | Excel | +| 工作台 | /api/bi/workbench/* | 经营工作台 | +| 店铺概览 | POST /api/bi/shop/overview | 单店铺统计 | +| 店铺按商品汇总导出 | POST /api/bi/shop/export/summary-by-product | Excel | +| 店铺按品类汇总导出 | POST /api/bi/shop/export/summary-by-category | Excel | +| 商品概览 | POST /api/bi/product/overview | 单商品统计 | | 订单 | /ec/order/* | CRUD | | 推广费 | /ec/promotion-fee/* | CRUD | | 刷单 | /ec/brush-order/* | CRUD | 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 4815d7b7..6a2aa4b6 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 @@ -4,8 +4,9 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc; import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc; +import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySkuDoc; import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.agg.OverviewAggRows; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows; import java.math.BigDecimal; import java.time.LocalDate; @@ -33,6 +34,96 @@ public class BiOrderStatQueryService { return repository.listProductDocs(companyId, shopIds, start, end); } + public List listProductDocs(Long companyId, List shopIds, + Long productId, + LocalDate start, LocalDate end) { + return repository.listProductDocs(companyId, shopIds, productId, start, end); + } + + public List listSkuDocs(Long companyId, Long productId, + List shopIds, + LocalDate start, LocalDate end) { + return repository.listSkuDocs(companyId, productId, shopIds, start, end); + } + + /** 商品日文档按日历日合并(单商品趋势)。 */ + public List toDailyRowsFromProductDocs( + List productDocs) { + Map byDay = new HashMap<>(); + for (BiOrderStatDailyProductDoc doc : productDocs) { + if (doc == null || doc.getStatDate() == null) { + continue; + } + OverviewAggRows.DailyRow row = byDay.computeIfAbsent(doc.getStatDate(), d -> { + OverviewAggRows.DailyRow r = new OverviewAggRows.DailyRow(); + r.setStatDate(d); + r.setSalesAmount(BigDecimal.ZERO); + r.setRefundAmount(BigDecimal.ZERO); + r.setProductCost(BigDecimal.ZERO); + r.setFreightCost(BigDecimal.ZERO); + r.setOtherCost(BigDecimal.ZERO); + r.setOrderCount(0L); + return r; + }); + row.setSalesAmount(nz(row.getSalesAmount()).add(nz(doc.getSalesAmount()))); + row.setRefundAmount(nz(row.getRefundAmount()).add(nz(doc.getRefundAmount()))); + 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()))); + row.setOrderCount(nzLong(row.getOrderCount()) + nzInt(doc.getSalesOrderCount())); + } + return new ArrayList<>(byDay.values()); + } + + /** SKU 日文档按 productSkuId 合并区间。 */ + public List sumSkuDocsBySku(List skuDocs) { + Map merged = new HashMap<>(); + for (BiOrderStatDailySkuDoc doc : skuDocs) { + if (doc == null) { + continue; + } + long skuId = doc.getProductSkuId() != null ? doc.getProductSkuId() : 0L; + SkuPeriodMetrics cur = merged.get(skuId); + if (cur == null) { + merged.put(skuId, new SkuPeriodMetrics( + skuId, + nz(doc.getSalesAmount()), + nz(doc.getRefundAmount()), + nz(doc.getProductCost()), + nz(doc.getFreightCost()), + nz(doc.getOtherCost()), + nzInt(doc.getSalesOrderCount()), + nzInt(doc.getSalesQuantitySum()))); + } else { + merged.put(skuId, new SkuPeriodMetrics( + skuId, + cur.salesAmount().add(nz(doc.getSalesAmount())), + cur.refundAmount().add(nz(doc.getRefundAmount())), + cur.productCost().add(nz(doc.getProductCost())), + cur.freightCost().add(nz(doc.getFreightCost())), + cur.otherCost().add(nz(doc.getOtherCost())), + cur.salesOrderCount() + nzInt(doc.getSalesOrderCount()), + cur.salesQuantitySum() + nzInt(doc.getSalesQuantitySum()))); + } + } + return new ArrayList<>(merged.values()); + } + + public record SkuPeriodMetrics( + long productSkuId, + BigDecimal salesAmount, + BigDecimal refundAmount, + BigDecimal productCost, + BigDecimal freightCost, + BigDecimal otherCost, + int salesOrderCount, + int salesQuantitySum + ) { + public BigDecimal orderCost() { + return nz(productCost).add(nz(freightCost)).add(nz(otherCost)); + } + } + /** * 商品日文档按 (shopId, productId, categoryId) 合并区间后,转为工作台多维/四表所需行。 * platformCode 由店铺主数据补齐(商品日文档无平台字段)。 @@ -94,6 +185,7 @@ public class BiOrderStatQueryService { r.setProductCost(BigDecimal.ZERO); r.setFreightCost(BigDecimal.ZERO); r.setOtherCost(BigDecimal.ZERO); + r.setOrderCount(0L); return r; }); row.setSalesAmount(nz(row.getSalesAmount()).add(nz(doc.getSalesAmount()))); @@ -101,6 +193,7 @@ public class BiOrderStatQueryService { 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()))); + row.setOrderCount(nzLong(row.getOrderCount()) + nzInt(doc.getSalesOrderCount())); } return new ArrayList<>(byDay.values()); } 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 b04b8b7c..7b987cdf 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 @@ -48,13 +48,47 @@ public class BiOrderStatDailyRepository { /** 区间内商品日文档(闭区间)。shopIds 为空返回空列表。 */ public List listProductDocs(Long companyId, List shopIds, LocalDate start, LocalDate end) { - if (companyId == null || shopIds == null || shopIds.isEmpty() || start == null || end == null) { + return listProductDocs(companyId, shopIds, null, start, end); + } + + /** + * 区间内商品日文档。{@code productId} 非空时仅该商品; + * {@code shopIds} 为空时不按店过滤(商品概览未指定店铺时用)。 + */ + public List listProductDocs(Long companyId, List shopIds, + Long productId, + LocalDate start, LocalDate end) { + if (companyId == null || start == null || end == null) { return List.of(); } - Query q = Query.query(Criteria.where("companyId").is(companyId) - .and("shopId").in(shopIds) - .and("statDate").gte(start).lte(end)); - return mongoTemplate.find(q, BiOrderStatDailyProductDoc.class); + Criteria c = Criteria.where("companyId").is(companyId) + .and("statDate").gte(start).lte(end); + if (shopIds != null && !shopIds.isEmpty()) { + c = c.and("shopId").in(shopIds); + } + if (productId != null) { + c = c.and("productId").is(productId); + } + return mongoTemplate.find(Query.query(c), BiOrderStatDailyProductDoc.class); + } + + /** + * 区间内 SKU 日文档。{@code productId} 必填; + * {@code shopIds} 为空时不按店过滤。 + */ + public List listSkuDocs(Long companyId, Long productId, + List shopIds, + LocalDate start, LocalDate end) { + if (companyId == null || productId == 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 (shopIds != null && !shopIds.isEmpty()) { + c = c.and("shopId").in(shopIds); + } + return mongoTemplate.find(Query.query(c), BiOrderStatDailySkuDoc.class); } public void replaceShopDay(BiOrderStatDailyShopDoc shopDoc, diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/agg/OverviewAggRows.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/agg/OverviewAggRows.java similarity index 90% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/agg/OverviewAggRows.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/agg/OverviewAggRows.java index d7eaa1d7..d423b8dd 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/agg/OverviewAggRows.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/agg/OverviewAggRows.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.model.agg; +package top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg; import lombok.Data; @@ -39,6 +39,8 @@ public final class OverviewAggRows { private BigDecimal productCost; private BigDecimal freightCost; private BigDecimal otherCost; + /** 当日销售单量合计(店铺/商品日汇聚 salesOrderCount) */ + private Long orderCount; } @Data diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/CategoryExportDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/dto/CategoryExportDTO.java similarity index 95% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/CategoryExportDTO.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/dto/CategoryExportDTO.java index bbba768a..e63bbb98 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/CategoryExportDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/dto/CategoryExportDTO.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto; +package top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.swagger.v3.oas.annotations.media.Schema; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/CompanyExportDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/dto/CompanyExportDTO.java similarity index 95% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/CompanyExportDTO.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/dto/CompanyExportDTO.java index 5b41409e..5ebc39fd 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/CompanyExportDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/dto/CompanyExportDTO.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto; +package top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotEmpty; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/PlatformExportDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/dto/PlatformExportDTO.java similarity index 94% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/PlatformExportDTO.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/dto/PlatformExportDTO.java index e1bdd43e..ae3f0dfc 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/PlatformExportDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/dto/PlatformExportDTO.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto; +package top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotEmpty; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/vo/CompanyOverviewVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/vo/CompanyOverviewVO.java similarity index 99% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/vo/CompanyOverviewVO.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/vo/CompanyOverviewVO.java index bd1b6c90..752d2399 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/vo/CompanyOverviewVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/model/vo/CompanyOverviewVO.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo; +package top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.v3.oas.annotations.media.Schema; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/CategoryExportExcelService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/CategoryExportExcelService.java similarity index 50% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/CategoryExportExcelService.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/CategoryExportExcelService.java index 41ab4650..548ca875 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/CategoryExportExcelService.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/CategoryExportExcelService.java @@ -1,21 +1,16 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.service; +package top.xyquan.ecomdmbbackend.modules.bi.overview.service; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO; /** - * 按品类维度导出 Excel(店铺「门店品类汇总」与全店「品类概览」共用实现) + * 按品类维度导出 Excel(店铺品类汇总、工作台品类/商品维表)。 */ public interface CategoryExportExcelService { + /** 店铺维度:按店铺 ID 导出品类汇总。 */ byte[] exportCategoryOverview(CategoryExportDTO dto); - /** - * 全店按品类:与 {@link top.xyquan.ecomdmbbackend.modules.ec.overview.service.CompanyOverviewService#getCompanyOverview} 同源, - * 生成「品类汇总 + 销售趋势」两表。 - */ - byte[] exportStoreCategoryFromOverview(CategoryExportDTO dto, CompanyOverviewVO overview); - /** * 多维度经营明细:品类/商品维度表已由调用方按筛选口径汇总,仅写「汇总」Sheet(无趋势表)。 * 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 new file mode 100644 index 00000000..271abb37 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/CompanyOverviewService.java @@ -0,0 +1,28 @@ +package top.xyquan.ecomdmbbackend.modules.bi.overview.service; + +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.ec.shop.model.po.ShopPO; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.List; + +/** + * 工作台汇总表构建(原全店概览服务收口后仅保留聚合读路径)。 + */ +public interface CompanyOverviewService { + + /** + * 基于 Mongo/SQL 聚合行构建工作台底部四表。 + */ + CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg( + BigDecimal taxRate, + Long companyId, + List shops, + List orderRows, + List promotionRows, + List brushRows, + LocalDate startDate, + LocalDate endDate); +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/ExportService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/ExportService.java new file mode 100644 index 00000000..1b481888 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/ExportService.java @@ -0,0 +1,21 @@ +package top.xyquan.ecomdmbbackend.modules.bi.overview.service; + +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CompanyExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.PlatformExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO; + +/** + * 工作台等多维表导出(按已汇总好的表写入 Excel)。 + */ +public interface ExportService { + + /** + * 多维度经营明细:已按筛选口径汇总好的「按店铺」表写入 Excel(不含趋势表)。 + */ + byte[] exportShopOverviewFromTable(CompanyExportDTO dto, CompanyOverviewVO.ShopOverview shopOverview, String summaryTitle); + + /** + * 多维度经营明细:已按筛选口径汇总好的「按平台」表写入 Excel(不含趋势表)。 + */ + byte[] exportPlatformOverviewFromTable(PlatformExportDTO dto, CompanyOverviewVO.PlatformOverview platformOverview, String summaryTitle); +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/CategoryExportExcelServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/CategoryExportExcelServiceImpl.java similarity index 75% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/CategoryExportExcelServiceImpl.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/CategoryExportExcelServiceImpl.java index c017b066..33fb6020 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/CategoryExportExcelServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/CategoryExportExcelServiceImpl.java @@ -1,16 +1,16 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.service.impl; +package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopOverviewQueryDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.ShopOverviewStatisticsVO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CategoryExportExcelService; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.ShopOverviewStatisticsService; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopOverviewService; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CategoryExportExcelService; import java.io.ByteArrayOutputStream; import java.math.BigDecimal; @@ -43,73 +43,23 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic } private final ExportStatusRangeHelper exportStatusRangeHelper; - private final ShopOverviewStatisticsService shopOverviewStatisticsService; + private final BiShopOverviewService biShopOverviewService; public CategoryExportExcelServiceImpl( ExportStatusRangeHelper exportStatusRangeHelper, - ShopOverviewStatisticsService shopOverviewStatisticsService) { + BiShopOverviewService biShopOverviewService) { this.exportStatusRangeHelper = exportStatusRangeHelper; - this.shopOverviewStatisticsService = shopOverviewStatisticsService; + this.biShopOverviewService = biShopOverviewService; } @Override public byte[] exportCategoryOverview(CategoryExportDTO dto) { if (dto.getShopId() == null) { - throw new BusinessException("全店按品类导出请使用 ExportService.exportCategoryOverview"); + throw new BusinessException("按品类导出必须指定店铺"); } return exportShopCategoryViaOverview(dto); } - @Override - public byte[] exportStoreCategoryFromOverview(CategoryExportDTO dto, CompanyOverviewVO overview) { - BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE; - LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange()); - LocalDate startDate = dateRange[0]; - LocalDate endDate = dateRange[1]; - String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT); - - CompanyOverviewVO.CategoryOverview co = overview.getCategorySummary(); - List catRows = (co != null && co.getCategories() != null) - ? new ArrayList<>(co.getCategories()) - : new ArrayList<>(); - - if (dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty()) { - Set allowed = new HashSet<>(dto.getCategoryIds()); - catRows = catRows.stream() - .filter(c -> allowed.contains(c.getCategoryId() != null ? c.getCategoryId() : 0L)) - .collect(Collectors.toList()); - } - - List shopRows = catRows.stream() - .map(this::toShopCategorySummary) - .collect(Collectors.toList()); - - boolean categoryFiltered = dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty(); - ShopOverviewStatisticsVO.CategorySummary totalRow = categoryFiltered - ? aggregateCategoryTotals(shopRows, taxRate) - : (co != null && co.getTotal() != null - ? toShopCategorySummary(co.getTotal()) - : aggregateCategoryTotals(shopRows, taxRate)); - - try (Workbook workbook = new XSSFWorkbook()) { - Sheet sheet = workbook.createSheet("汇总"); - writeCategoryMultidimensionalSheet( - sheet, "全店 - 品类多维度损益汇总", dateRangeLabel, shopRows, totalRow, taxRate, "品类名称"); - if (overview.getSalesAmountTrend() != null - && overview.getSalesAmountTrend().getDailyDataList() != null - && !overview.getSalesAmountTrend().getDailyDataList().isEmpty()) { - Sheet trendSheet = workbook.createSheet("销售趋势"); - writeCompanyOverviewTrendSheet(trendSheet, "全店", dateRangeLabel, overview); - } - try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { - workbook.write(out); - return out.toByteArray(); - } - } catch (Exception e) { - throw new BusinessException("导出品类Excel失败: " + e.getMessage()); - } - } - @Override public byte[] exportCategoryDimensionsFromTable( CategoryExportDTO dto, @@ -158,7 +108,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic } /** - * 店铺侧导出:与 {@link ShopOverviewStatisticsService#getShopOverviewStatistics} 同源, + * 店铺侧导出:与 {@link BiShopOverviewService#getShopOverview} 同源, * 保证订单状态参与统计、推广费/刷单费分摊与前端「品类多维度损益汇总」一致。 */ private byte[] exportShopCategoryViaOverview(CategoryExportDTO dto) { @@ -173,7 +123,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic query.setDateRange(dto.getDateRange()); query.setTaxRate(taxRate); - ShopOverviewStatisticsVO vo = shopOverviewStatisticsService.getShopOverviewStatistics(query); + ShopOverviewStatisticsVO vo = biShopOverviewService.getShopOverview(query); ShopOverviewStatisticsVO.CategoryOverview co = vo.getCategoryOverview(); List rows = (co != null && co.getCategories() != null) @@ -280,73 +230,6 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic sheet.setColumnWidth(2, 3200); } - /** 全店概览 {@link CompanyOverviewVO} 的日销售额、日单量趋势(与 /ec/store/overview 同源)。 */ - private void writeCompanyOverviewTrendSheet( - Sheet sheet, String contextTitle, String dateRangeLabel, CompanyOverviewVO vo) { - Workbook wb = sheet.getWorkbook(); - CellStyle headerStyle = createHeaderStyle(wb); - CellStyle dataStyle = createDataStyle(wb); - - Row titleRow = sheet.createRow(0); - Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue(contextTitle + " - 销售趋势 | " + dateRangeLabel); - titleCell.setCellStyle(createTitleStyle(wb)); - sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); - - String[] headers = {"日期", "销售额", "单量"}; - Row headerRow = sheet.createRow(1); - for (int i = 0; i < headers.length; i++) { - Cell cell = headerRow.createCell(i); - cell.setCellValue(headers[i]); - cell.setCellStyle(headerStyle); - } - - List dailySales = vo.getSalesAmountTrend().getDailyDataList(); - List dailyOrders = vo.getOrderCountTrend() != null - ? vo.getOrderCountTrend().getDailyDataList() - : null; - - Map salesMap = dailySales.stream() - .collect(Collectors.toMap( - CompanyOverviewVO.TrendDataItem::getDate, - CompanyOverviewVO.TrendDataItem::getValue, - (a, b) -> a)); - Map ordersMap = dailyOrders != null - ? dailyOrders.stream() - .collect(Collectors.toMap( - CompanyOverviewVO.TrendDataItem::getDate, - CompanyOverviewVO.TrendDataItem::getValue, - (a, b) -> a)) - : Collections.emptyMap(); - - LocalDate startDate = dailySales.stream() - .map(CompanyOverviewVO.TrendDataItem::getDate) - .min(LocalDate::compareTo) - .orElse(null); - LocalDate endDate = dailySales.stream() - .map(CompanyOverviewVO.TrendDataItem::getDate) - .max(LocalDate::compareTo) - .orElse(null); - - int rowIdx = 2; - if (startDate != null && endDate != null) { - LocalDate current = startDate; - while (!current.isAfter(endDate)) { - Row row = sheet.createRow(rowIdx++); - BigDecimal sales = salesMap.getOrDefault(current, BigDecimal.ZERO); - BigDecimal orders = ordersMap.getOrDefault(current, BigDecimal.ZERO); - setCell(row, 0, current.format(DATE_FMT), dataStyle); - setCell(row, 1, sales.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 2, orders.setScale(0, RoundingMode.HALF_UP).doubleValue(), dataStyle); - current = current.plusDays(1); - } - } - - sheet.setColumnWidth(0, 3200); - sheet.setColumnWidth(1, 3200); - sheet.setColumnWidth(2, 3200); - } - private ShopOverviewStatisticsVO.CategorySummary toShopCategorySummary(CompanyOverviewVO.CategorySummary c) { ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary(); s.setCategoryId(c.getCategoryId() != null ? c.getCategoryId() : 0L); 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 new file mode 100644 index 00000000..b9ae9c2a --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/CompanyOverviewServiceImpl.java @@ -0,0 +1,775 @@ +package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import org.springframework.stereotype.Service; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows; +import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode; +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; +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.category.model.po.CategoryPO; +import top.xyquan.ecomdmbbackend.modules.ec.category.service.CategoryService; +import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper; +import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * 工作台汇总表构建(聚合行读路径)。 + */ +@Service +public class CompanyOverviewServiceImpl implements CompanyOverviewService { + + private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04"); + private BigDecimal taxRate = DEFAULT_TAX_RATE; + + private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; + private final ProductMapper productMapper; + private final CategoryService categoryService; + + public CompanyOverviewServiceImpl( + ShopMonthlyTargetMapper shopMonthlyTargetMapper, + ProductMapper productMapper, + CategoryService categoryService) { + this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; + this.productMapper = productMapper; + this.categoryService = categoryService; + } + + private BigDecimal salesTaxOnNetSales(BigDecimal salesAmount, BigDecimal refundAmount) { + BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO; + BigDecimal refund = refundAmount != null ? refundAmount : BigDecimal.ZERO; + BigDecimal base = sales.subtract(refund); + if (base.compareTo(BigDecimal.ZERO) < 0) { + base = BigDecimal.ZERO; + } + BigDecimal rate = taxRate != null ? taxRate : DEFAULT_TAX_RATE; + return base.multiply(rate).setScale(2, RoundingMode.HALF_UP); + } + + /** 计算ROI:(销售额 - 退款金额)/ 推广费用 */ + private BigDecimal calculateSalesROI(BigDecimal netSales, BigDecimal promotionFee) { + if (promotionFee == null || promotionFee.compareTo(BigDecimal.ZERO) <= 0) { + return BigDecimal.ZERO; + } + return netSales.divide(promotionFee, 4, RoundingMode.HALF_UP); + } + + /** 计算店铺汇总的合计行 */ + private CompanyOverviewVO.ShopSummary computeShopTotal(List shops) { + BigDecimal totalSales = BigDecimal.ZERO; + int totalOrders = 0; + BigDecimal totalTargetAmount = BigDecimal.ZERO; + int totalTargetOrders = 0; + BigDecimal totalProductCost = BigDecimal.ZERO; + BigDecimal totalShippingCost = BigDecimal.ZERO; + BigDecimal totalOtherCost = BigDecimal.ZERO; + BigDecimal totalRefund = BigDecimal.ZERO; + BigDecimal totalPromoFee = BigDecimal.ZERO; + BigDecimal totalBrushFee = BigDecimal.ZERO; + BigDecimal totalGmv = BigDecimal.ZERO; + BigDecimal totalGrossProfit = BigDecimal.ZERO; + + for (CompanyOverviewVO.ShopSummary s : shops) { + totalSales = totalSales.add(s.getSalesAmount() != null ? s.getSalesAmount() : BigDecimal.ZERO); + totalGmv = totalGmv.add(s.getGmv() != null ? s.getGmv() : BigDecimal.ZERO); + totalGrossProfit = totalGrossProfit.add(s.getGrossProfit() != null ? s.getGrossProfit() : BigDecimal.ZERO); + totalOrders += s.getOrderCount() != null ? s.getOrderCount() : 0; + totalTargetAmount = totalTargetAmount.add(s.getTargetAmount() != null ? s.getTargetAmount() : BigDecimal.ZERO); + totalTargetOrders += s.getTargetOrderCount() != null ? s.getTargetOrderCount() : 0; + totalProductCost = totalProductCost.add(s.getProductCost() != null ? s.getProductCost() : BigDecimal.ZERO); + totalShippingCost = totalShippingCost.add(s.getShippingCost() != null ? s.getShippingCost() : BigDecimal.ZERO); + totalOtherCost = totalOtherCost.add(s.getOtherCost() != null ? s.getOtherCost() : BigDecimal.ZERO); + totalRefund = totalRefund.add(s.getRefundAmount() != null ? s.getRefundAmount() : BigDecimal.ZERO); + totalPromoFee = totalPromoFee.add(s.getTotalPromotionFee() != null ? s.getTotalPromotionFee() : BigDecimal.ZERO); + totalBrushFee = totalBrushFee.add(s.getBrushFee() != null ? s.getBrushFee() : BigDecimal.ZERO); + } + + BigDecimal avgOrderValue = totalOrders > 0 + ? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); + BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund) + .subtract(totalPromoFee).subtract(totalBrushFee); + BigDecimal salesTax = salesTaxOnNetSales(totalSales, totalRefund); + BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); + BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 + ? totalSales.subtract(totalRefund).divide(totalPromoFee, 4, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 + ? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0 + ? totalSales.divide(totalTargetAmount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")) + : totalSales.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO; + BigDecimal orderAchievementRate = totalTargetOrders > 0 + ? new BigDecimal(totalOrders).divide(new BigDecimal(totalTargetOrders), 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal("100")) + : totalOrders > 0 ? new BigDecimal("100") : BigDecimal.ZERO; + + CompanyOverviewVO.ShopSummary total = new CompanyOverviewVO.ShopSummary(); + total.setShopId(0L); + total.setShopName("合计"); + total.setSalesAmount(totalSales); + total.setGmv(totalGmv); + total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP)); + total.setOrderCount(totalOrders); + total.setAverageOrderValue(avgOrderValue); + total.setTargetAmount(totalTargetAmount); + total.setTargetOrderCount(totalTargetOrders); + total.setSalesAmountAchievementRate(salesAchievementRate); + total.setOrderCountAchievementRate(orderAchievementRate); + total.setProductCost(totalProductCost); + total.setShippingCost(totalShippingCost); + total.setOtherCost(totalOtherCost); + total.setOrderCost(totalCost); + total.setRefundAmount(totalRefund); + total.setTotalPromotionFee(totalPromoFee); + total.setBrushFee(totalBrushFee); + total.setFeeRatio(feeRatio); + total.setTotalProfitBeforeTax(profitBeforeTax); + total.setSalesTaxAmount(salesTax); + total.setRoi(roi); + total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); + return total; + } + + /** 计算品类汇总的合计行 */ + private CompanyOverviewVO.CategorySummary computeCategoryTotal(List categories) { + BigDecimal totalSales = BigDecimal.ZERO; + int totalOrders = 0; + BigDecimal totalProductCost = BigDecimal.ZERO; + BigDecimal totalShippingCost = BigDecimal.ZERO; + BigDecimal totalOtherCost = BigDecimal.ZERO; + BigDecimal totalRefund = BigDecimal.ZERO; + BigDecimal totalPromoFee = BigDecimal.ZERO; + BigDecimal totalBrushFee = BigDecimal.ZERO; + BigDecimal totalGmv = BigDecimal.ZERO; + BigDecimal totalGrossProfit = BigDecimal.ZERO; + + for (CompanyOverviewVO.CategorySummary c : categories) { + totalSales = totalSales.add(c.getSalesAmount() != null ? c.getSalesAmount() : BigDecimal.ZERO); + totalGmv = totalGmv.add(c.getGmv() != null ? c.getGmv() : BigDecimal.ZERO); + totalGrossProfit = totalGrossProfit.add(c.getGrossProfit() != null ? c.getGrossProfit() : BigDecimal.ZERO); + totalOrders += c.getOrderCount() != null ? c.getOrderCount() : 0; + totalProductCost = totalProductCost.add(c.getProductCost() != null ? c.getProductCost() : BigDecimal.ZERO); + totalShippingCost = totalShippingCost.add(c.getShippingCost() != null ? c.getShippingCost() : BigDecimal.ZERO); + totalOtherCost = totalOtherCost.add(c.getOtherCost() != null ? c.getOtherCost() : BigDecimal.ZERO); + totalRefund = totalRefund.add(c.getRefundAmount() != null ? c.getRefundAmount() : BigDecimal.ZERO); + totalPromoFee = totalPromoFee.add(c.getTotalPromotionFee() != null ? c.getTotalPromotionFee() : BigDecimal.ZERO); + totalBrushFee = totalBrushFee.add(c.getBrushFee() != null ? c.getBrushFee() : BigDecimal.ZERO); + } + + BigDecimal avgOrderValue = totalOrders > 0 + ? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); + BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund) + .subtract(totalPromoFee).subtract(totalBrushFee); + BigDecimal salesTax = salesTaxOnNetSales(totalSales, totalRefund); + BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); + BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 + ? totalSales.subtract(totalRefund).divide(totalPromoFee, 4, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 + ? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + + CompanyOverviewVO.CategorySummary total = new CompanyOverviewVO.CategorySummary(); + total.setCategoryId(0L); + total.setCategoryName("合计"); + total.setSalesAmount(totalSales); + total.setGmv(totalGmv); + total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP)); + total.setOrderCount(totalOrders); + total.setAverageOrderValue(avgOrderValue); + total.setProductCost(totalProductCost); + total.setShippingCost(totalShippingCost); + total.setOtherCost(totalOtherCost); + total.setOrderCost(totalCost); + total.setRefundAmount(totalRefund); + total.setTotalPromotionFee(totalPromoFee); + total.setBrushFee(totalBrushFee); + total.setFeeRatio(feeRatio); + total.setTotalProfitBeforeTax(profitBeforeTax); + total.setSalesTaxAmount(salesTax); + total.setRoi(roi); + total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); + return total; + } + + /** 计算平台汇总的合计行 */ + private CompanyOverviewVO.PlatformSummary computePlatformTotal(List platforms) { + BigDecimal totalSalesAmount = BigDecimal.ZERO; + int totalOrderCount = 0; + BigDecimal totalTargetAmount = BigDecimal.ZERO; + int totalTargetOrderCount = 0; + BigDecimal totalProductCost = BigDecimal.ZERO; + BigDecimal totalShippingCost = BigDecimal.ZERO; + BigDecimal totalOtherCost = BigDecimal.ZERO; + BigDecimal totalRefundAmount = BigDecimal.ZERO; + BigDecimal totalPromotionFee = BigDecimal.ZERO; + BigDecimal totalBrushFee = BigDecimal.ZERO; + BigDecimal totalGmv = BigDecimal.ZERO; + BigDecimal totalGrossProfit = BigDecimal.ZERO; + + for (CompanyOverviewVO.PlatformSummary p : platforms) { + totalSalesAmount = totalSalesAmount.add(p.getSalesAmount() != null ? p.getSalesAmount() : BigDecimal.ZERO); + totalGmv = totalGmv.add(p.getGmv() != null ? p.getGmv() : BigDecimal.ZERO); + totalGrossProfit = totalGrossProfit.add(p.getGrossProfit() != null ? p.getGrossProfit() : BigDecimal.ZERO); + totalOrderCount += p.getOrderCount() != null ? p.getOrderCount() : 0; + totalTargetAmount = totalTargetAmount.add(p.getTargetAmount() != null ? p.getTargetAmount() : BigDecimal.ZERO); + totalTargetOrderCount += p.getTargetOrderCount() != null ? p.getTargetOrderCount() : 0; + totalProductCost = totalProductCost.add(p.getProductCost() != null ? p.getProductCost() : BigDecimal.ZERO); + totalShippingCost = totalShippingCost.add(p.getShippingCost() != null ? p.getShippingCost() : BigDecimal.ZERO); + totalOtherCost = totalOtherCost.add(p.getOtherCost() != null ? p.getOtherCost() : BigDecimal.ZERO); + totalRefundAmount = totalRefundAmount.add(p.getRefundAmount() != null ? p.getRefundAmount() : BigDecimal.ZERO); + totalPromotionFee = totalPromotionFee.add(p.getTotalPromotionFee() != null ? p.getTotalPromotionFee() : BigDecimal.ZERO); + totalBrushFee = totalBrushFee.add(p.getBrushFee() != null ? p.getBrushFee() : BigDecimal.ZERO); + } + + BigDecimal avgOrderValue = totalOrderCount > 0 + ? totalSalesAmount.divide(new BigDecimal(totalOrderCount), 2, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); + BigDecimal profitBeforeTax = totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount) + .subtract(totalPromotionFee).subtract(totalBrushFee); + BigDecimal salesTax = salesTaxOnNetSales(totalSalesAmount, totalRefundAmount); + BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); + BigDecimal roi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0 + ? totalSalesAmount.subtract(totalRefundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + BigDecimal feeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0 + ? totalPromotionFee.add(totalBrushFee).divide(totalSalesAmount, 4, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0 + ? totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")) + : totalSalesAmount.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO; + BigDecimal orderAchievementRate = totalTargetOrderCount > 0 + ? new BigDecimal(totalOrderCount).divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal("100")) + : totalOrderCount > 0 ? new BigDecimal("100") : BigDecimal.ZERO; + + CompanyOverviewVO.PlatformSummary total = new CompanyOverviewVO.PlatformSummary(); + total.setPlatformCode(null); + total.setPlatformName("合计"); + total.setSalesAmount(totalSalesAmount); + total.setGmv(totalGmv); + total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP)); + total.setOrderCount(totalOrderCount); + total.setAverageOrderValue(avgOrderValue); + total.setTargetAmount(totalTargetAmount); + total.setTargetOrderCount(totalTargetOrderCount); + total.setSalesAmountAchievementRate(salesAchievementRate); + total.setOrderCountAchievementRate(orderAchievementRate); + total.setProductCost(totalProductCost); + total.setShippingCost(totalShippingCost); + total.setOtherCost(totalOtherCost); + total.setOrderCost(totalCost); + total.setRefundAmount(totalRefundAmount); + total.setTotalPromotionFee(totalPromotionFee); + total.setBrushFee(totalBrushFee); + total.setFeeRatio(feeRatio); + total.setTotalProfitBeforeTax(profitBeforeTax); + total.setSalesTaxAmount(salesTax); + total.setRoi(roi); + total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); + return total; + } + + public CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg( + BigDecimal taxRate, + Long companyId, + List shops, + List orderRows, + List promotionRows, + List brushRows, + LocalDate startDate, + LocalDate endDate) { + synchronized (this) { + BigDecimal saved = this.taxRate; + try { + this.taxRate = taxRate != null ? taxRate : DEFAULT_TAX_RATE; + return buildWorkbenchTablesFromAggInternal(companyId, shops, orderRows, promotionRows, brushRows, startDate, endDate); + } finally { + this.taxRate = saved; + } + } + } + + /** SQL 聚合行 → 四表(推广/刷单分摊规则与明细版一致) */ + private CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchTablesFromAggInternal( + Long companyId, + List shops, + List orderRows, + List promotionRows, + List brushRows, + LocalDate startDate, + LocalDate endDate) { + + Map byShop = new HashMap<>(); + Map byCategory = new HashMap<>(); + Map byProduct = new HashMap<>(); + Map> categorySalesByShop = new HashMap<>(); + Map> productSalesByShop = new HashMap<>(); + Map productCategoryMap = new HashMap<>(); + + for (OverviewAggRows.ShopProductRow row : orderRows) { + long shopId = row.getShopId() != null ? row.getShopId() : 0L; + long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L; + long categoryKey = productId <= 0 ? -1L + : (row.getCategoryId() == null || row.getCategoryId() == 0 ? 0L : row.getCategoryId()); + if (productId > 0) { + productCategoryMap.put(productId, categoryKey <= 0 ? null : categoryKey); + } + mergeAgg(byShop, shopId, row); + mergeAgg(byCategory, categoryKey, row); + mergeAgg(byProduct, productId, row); + BigDecimal sales = nz(row.getSalesAmount()); + categorySalesByShop.computeIfAbsent(categoryKey, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add); + productSalesByShop.computeIfAbsent(productId, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add); + } + + Map promoByShop = new HashMap<>(); + Map directPromoByProduct = new HashMap<>(); + Map directPromoByCategory = new HashMap<>(); + BigDecimal ratioPool = BigDecimal.ZERO; + for (OverviewAggRows.PromotionRow fee : promotionRows) { + BigDecimal amt = nz(fee.getFeeAmount()); + promoByShop.merge(fee.getShopId(), amt, BigDecimal::add); + if (fee.getProductId() != null) { + directPromoByProduct.merge(fee.getProductId(), amt, BigDecimal::add); + } else if (fee.getCategoryId() != null) { + directPromoByCategory.merge(fee.getCategoryId(), amt, BigDecimal::add); + } else { + ratioPool = ratioPool.add(amt); + } + } + Map brushByShop = new HashMap<>(); + for (OverviewAggRows.BrushRow b : brushRows) { + brushByShop.merge(b.getShopId(), nz(b.getBrushAmount()), BigDecimal::add); + } + BigDecimal totalSalesPool = orderRows.stream().map(r -> nz(r.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); + + Map> targetsByShop = loadTargetsByShop(companyId, startDate, endDate); + + CompanyOverviewVO.WorkbenchTableBundle bundle = new CompanyOverviewVO.WorkbenchTableBundle(); + bundle.setShopTable(buildShopOverviewFromAgg(shops, byShop, promoByShop, brushByShop, targetsByShop)); + bundle.setPlatformTable(buildPlatformOverviewFromAgg(shops, byShop, promoByShop, brushByShop, targetsByShop)); + bundle.setCategoryTable(buildCategoryOverviewFromAgg(byCategory, categorySalesByShop, brushByShop, + directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId)); + bundle.setProductTable(buildProductOverviewFromAgg(byProduct, productSalesByShop, brushByShop, + directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId)); + return bundle; + } + + private CompanyOverviewVO.ShopOverview buildShopOverviewFromAgg( + List shops, Map byShop, Map promoByShop, + Map brushByShop, Map> targetsByShop) { + List list = new ArrayList<>(); + for (ShopPO shop : shops) { + AggMetrics m = byShop.getOrDefault(shop.getId(), AggMetrics.EMPTY); + list.add(toShopSummaryFromAgg(shop, m, promoByShop.getOrDefault(shop.getId(), BigDecimal.ZERO), + brushByShop.getOrDefault(shop.getId(), BigDecimal.ZERO), + targetsByShop.getOrDefault(shop.getId(), List.of()))); + } + list.sort(Comparator.comparing(CompanyOverviewVO.ShopSummary::getSalesAmount, + Comparator.nullsFirst(BigDecimal::compareTo)).reversed()); + CompanyOverviewVO.ShopOverview o = new CompanyOverviewVO.ShopOverview(); + o.setShops(list); + o.setTotal(computeShopTotal(list)); + return o; + } + + private CompanyOverviewVO.PlatformOverview buildPlatformOverviewFromAgg( + List shops, Map byShop, Map promoByShop, + Map brushByShop, Map> targetsByShop) { + Map> byPlatform = shops.stream() + .filter(s -> s.getPlatformCode() != null && !s.getPlatformCode().isBlank()) + .collect(Collectors.groupingBy(ShopPO::getPlatformCode)); + List list = new ArrayList<>(); + for (Map.Entry> e : byPlatform.entrySet()) { + list.add(rollupPlatformFromAgg(e.getKey(), PlatformCode.labelOf(e.getKey()), + e.getValue(), byShop, promoByShop, brushByShop, targetsByShop)); + } + list.sort(Comparator.comparing(CompanyOverviewVO.PlatformSummary::getSalesAmount, + Comparator.nullsFirst(BigDecimal::compareTo)).reversed()); + CompanyOverviewVO.PlatformOverview o = new CompanyOverviewVO.PlatformOverview(); + o.setPlatforms(list); + o.setTotal(computePlatformTotal(list)); + return o; + } + + private CompanyOverviewVO.CategoryOverview buildCategoryOverviewFromAgg( + Map byCategory, Map> categorySalesByShop, + Map brushByShop, Map directPromoByProduct, + Map directPromoByCategory, BigDecimal ratioPool, BigDecimal totalSalesPool, + Map productCategoryMap, Long companyId) { + Map categoryNames = loadCategoryNameMap(companyId); + Map salesByCategory = byCategory.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().sales)); + List list = new ArrayList<>(); + for (Map.Entry e : byCategory.entrySet()) { + Long key = e.getKey(); + AggMetrics m = e.getValue(); + BigDecimal promo = resolveCategoryPromo(key, m.sales, salesByCategory, productCategoryMap, + directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool); + BigDecimal brush = allocBrushShare(categorySalesByShop.get(key), brushByShop); + list.add(toCategorySummaryFromAgg(key, categoryAggName(key, categoryNames), m, promo, brush)); + } + list.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount, + Comparator.nullsFirst(BigDecimal::compareTo)).reversed()); + CompanyOverviewVO.CategoryOverview o = new CompanyOverviewVO.CategoryOverview(); + o.setCategories(list); + o.setTotal(computeCategoryTotal(list)); + return o; + } + + private CompanyOverviewVO.CategoryOverview buildProductOverviewFromAgg( + Map byProduct, Map> productSalesByShop, + Map brushByShop, Map directPromoByProduct, + Map directPromoByCategory, BigDecimal ratioPool, BigDecimal totalSalesPool, + Map productCategoryMap, Long companyId) { + Map salesByCategory = new HashMap<>(); + for (Map.Entry e : byProduct.entrySet()) { + if (e.getKey() > 0) { + Long cid = productCategoryMap.get(e.getKey()); + if (cid != null && cid > 0) { + salesByCategory.merge(cid, e.getValue().sales, BigDecimal::add); + } + } + } + Map productNames = loadProductNameMap(byProduct.keySet()); + List list = new ArrayList<>(); + for (Map.Entry e : byProduct.entrySet()) { + Long pid = e.getKey(); + AggMetrics m = e.getValue(); + BigDecimal promo = resolveProductPromo(pid, m.sales, productCategoryMap, salesByCategory, + directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool); + BigDecimal brush = allocBrushShare(productSalesByShop.get(pid), brushByShop); + String name = pid <= 0 ? "未匹配商品" : productNames.getOrDefault(pid, "商品" + pid); + list.add(toCategorySummaryFromAgg(pid, name, m, promo, brush)); + } + list.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount, + Comparator.nullsFirst(BigDecimal::compareTo)).reversed()); + CompanyOverviewVO.CategoryOverview o = new CompanyOverviewVO.CategoryOverview(); + o.setCategories(list); + o.setTotal(computeCategoryTotal(list)); + return o; + } + + private CompanyOverviewVO.PlatformSummary rollupPlatformFromAgg( + String platformCode, String platformName, List platformShops, + Map byShop, Map promoByShop, Map brushByShop, + Map> targetsByShop) { + AggMetrics merged = AggMetrics.EMPTY; + BigDecimal promo = BigDecimal.ZERO; + BigDecimal brush = BigDecimal.ZERO; + BigDecimal targetAmt = BigDecimal.ZERO; + int targetOrders = 0; + for (ShopPO shop : platformShops) { + merged = merged.merge(byShop.getOrDefault(shop.getId(), AggMetrics.EMPTY)); + promo = promo.add(promoByShop.getOrDefault(shop.getId(), BigDecimal.ZERO)); + brush = brush.add(brushByShop.getOrDefault(shop.getId(), BigDecimal.ZERO)); + for (ShopMonthlyTargetPO t : targetsByShop.getOrDefault(shop.getId(), List.of())) { + targetAmt = targetAmt.add(nz(t.getTargetAmount())); + targetOrders += t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0; + } + } + return toPlatformSummaryFromAgg(platformCode, platformName, merged, promo, brush, targetAmt, targetOrders); + } + + private CompanyOverviewVO.ShopSummary toShopSummaryFromAgg( + ShopPO shop, AggMetrics m, BigDecimal promo, BigDecimal brush, + List targets) { + BigDecimal targetAmt = targets.stream().map(t -> nz(t.getTargetAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); + int targetOrders = targets.stream().mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0).sum(); + CompanyOverviewVO.ShopSummary s = new CompanyOverviewVO.ShopSummary(); + s.setShopId(shop.getId()); + s.setShopName(shop.getName()); + s.setPlatform(shop.getPlatformCode() != null ? PlatformCode.labelOf(shop.getPlatformCode()) : null); + fillSummaryMetrics(s, m, promo, brush, targetAmt, targetOrders); + return s; + } + + private CompanyOverviewVO.PlatformSummary toPlatformSummaryFromAgg( + String platformCode, String name, AggMetrics m, BigDecimal promo, BigDecimal brush, + BigDecimal targetAmt, int targetOrders) { + CompanyOverviewVO.PlatformSummary s = new CompanyOverviewVO.PlatformSummary(); + s.setPlatformCode(platformCode != null && !platformCode.isBlank() ? platformCode : null); + s.setPlatformName(name); + fillPlatformLikeMetrics(s, m, promo, brush, targetAmt, targetOrders); + return s; + } + + private CompanyOverviewVO.CategorySummary toCategorySummaryFromAgg( + Long key, String name, AggMetrics m, BigDecimal promo, BigDecimal brush) { + CompanyOverviewVO.CategorySummary s = new CompanyOverviewVO.CategorySummary(); + s.setCategoryId(key != null && key > 0 ? key : null); + s.setCategoryName(name); + fillCategoryLikeMetrics(s, m, promo, brush); + return s; + } + + private void fillSummaryMetrics(CompanyOverviewVO.ShopSummary s, AggMetrics m, BigDecimal promo, + BigDecimal brush, BigDecimal targetAmt, int targetOrders) { + s.setSalesAmount(m.sales); + s.setGmv(m.gmv); + s.setOrderCount(m.orderCount); + s.setAverageOrderValue(aov(m.sales, m.orderCount)); + s.setProductCost(m.productCost); + s.setShippingCost(m.freightCost); + s.setOtherCost(m.otherCost); + s.setOrderCost(m.orderCost()); + s.setRefundAmount(m.refund); + s.setTotalPromotionFee(promo); + s.setBrushFee(brush); + s.setFeeRatio(safeDivide(promo, m.sales)); + s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP)); + BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush); + s.setTotalProfitBeforeTax(pbt); + s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund)); + s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP)); + s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo)); + s.setTargetAmount(targetAmt); + s.setTargetOrderCount(targetOrders); + s.setSalesAmountAchievementRate(achievementRate(m.sales, targetAmt)); + s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.orderCount), BigDecimal.valueOf(targetOrders))); + } + + /** 品类/商品/平台汇总行:填充 GMV、毛利与净利字段 */ + private void fillCategoryLikeMetrics(CompanyOverviewVO.CategorySummary s, AggMetrics m, + BigDecimal promo, BigDecimal brush) { + s.setSalesAmount(m.sales); + s.setGmv(m.gmv); + s.setOrderCount(m.orderCount); + s.setAverageOrderValue(aov(m.sales, m.orderCount)); + s.setProductCost(m.productCost); + s.setShippingCost(m.freightCost); + s.setOtherCost(m.otherCost); + s.setOrderCost(m.orderCost()); + s.setRefundAmount(m.refund); + s.setTotalPromotionFee(promo); + s.setBrushFee(brush); + s.setFeeRatio(safeDivide(promo, m.sales)); + s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP)); + BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush); + s.setTotalProfitBeforeTax(pbt); + s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund)); + s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP)); + s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo)); + } + + private void fillPlatformLikeMetrics(CompanyOverviewVO.PlatformSummary s, AggMetrics m, + BigDecimal promo, BigDecimal brush, + BigDecimal targetAmt, int targetOrders) { + s.setSalesAmount(m.sales); + s.setGmv(m.gmv); + s.setOrderCount(m.orderCount); + s.setAverageOrderValue(aov(m.sales, m.orderCount)); + s.setProductCost(m.productCost); + s.setShippingCost(m.freightCost); + s.setOtherCost(m.otherCost); + s.setOrderCost(m.orderCost()); + s.setRefundAmount(m.refund); + s.setTotalPromotionFee(promo); + s.setBrushFee(brush); + s.setFeeRatio(safeDivide(promo.add(brush), m.sales)); + s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP)); + BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush); + s.setTotalProfitBeforeTax(pbt); + s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund)); + s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP)); + s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo)); + s.setTargetAmount(targetAmt); + s.setTargetOrderCount(targetOrders); + s.setSalesAmountAchievementRate(achievementRate(m.sales, targetAmt)); + s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.orderCount), BigDecimal.valueOf(targetOrders))); + } + + private static void mergeAgg(Map map, long key, OverviewAggRows.ShopProductRow row) { + map.merge(key, AggMetrics.from(row), AggMetrics::merge); + } + + private static BigDecimal resolveCategoryPromo(Long categoryKey, BigDecimal sales, + Map salesByCategory, Map productCategoryMap, + Map directByProduct, Map directByCategory, + BigDecimal ratioPool, BigDecimal totalPool) { + BigDecimal direct = BigDecimal.ZERO; + for (Map.Entry e : productCategoryMap.entrySet()) { + if (matchesCategory(categoryKey, e.getValue())) { + direct = direct.add(directByProduct.getOrDefault(e.getKey(), BigDecimal.ZERO)); + } + } + if (categoryKey != null && categoryKey > 0) { + direct = direct.add(directByCategory.getOrDefault(categoryKey, BigDecimal.ZERO)); + } + return addPoolShare(direct, sales, ratioPool, totalPool); + } + + private static BigDecimal resolveProductPromo(Long productId, BigDecimal sales, + Map productCategoryMap, Map salesByCategory, + Map directByProduct, Map directByCategory, + BigDecimal ratioPool, BigDecimal totalPool) { + if (productId == null || productId <= 0) { + return addPoolShare(BigDecimal.ZERO, sales, ratioPool, totalPool); + } + BigDecimal direct = directByProduct.getOrDefault(productId, BigDecimal.ZERO); + Long cid = productCategoryMap.get(productId); + if (cid != null && cid > 0) { + BigDecimal catSales = salesByCategory.getOrDefault(cid, BigDecimal.ZERO); + if (catSales.compareTo(BigDecimal.ZERO) > 0) { + direct = direct.add(directByCategory.getOrDefault(cid, BigDecimal.ZERO) + .multiply(sales).divide(catSales, 4, RoundingMode.HALF_UP)); + } + } + return addPoolShare(direct, sales, ratioPool, totalPool); + } + + private static boolean matchesCategory(Long categoryKey, Long productCat) { + if (categoryKey == -1L) { + return productCat == null; + } + return Objects.equals(categoryKey, productCat); + } + + private static BigDecimal addPoolShare(BigDecimal base, BigDecimal sales, BigDecimal pool, BigDecimal total) { + if (pool.compareTo(BigDecimal.ZERO) > 0 && total.compareTo(BigDecimal.ZERO) > 0) { + return base.add(pool.multiply(sales).divide(total, 4, RoundingMode.HALF_UP)); + } + return base; + } + + private static BigDecimal allocBrushShare(Map salesByShop, Map brushByShop) { + if (salesByShop == null || salesByShop.isEmpty()) { + return BigDecimal.ZERO; + } + BigDecimal total = salesByShop.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add); + if (total.compareTo(BigDecimal.ZERO) <= 0) { + return BigDecimal.ZERO; + } + BigDecimal brush = BigDecimal.ZERO; + for (Map.Entry e : salesByShop.entrySet()) { + brush = brush.add(brushByShop.getOrDefault(e.getKey(), BigDecimal.ZERO) + .multiply(e.getValue()).divide(total, 6, RoundingMode.HALF_UP)); + } + return brush; + } + + private Map loadCategoryNameMap(Long companyId) { + return categoryService.list(new LambdaQueryWrapper().eq(CategoryPO::getCompanyId, companyId)) + .stream().collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName, (a, b) -> a)); + } + + private Map loadProductNameMap(java.util.Set productKeys) { + List ids = productKeys.stream().filter(id -> id != null && id > 0).distinct().toList(); + if (ids.isEmpty()) { + return Map.of(); + } + return productMapper.selectList(new LambdaQueryWrapper().in(ProductPO::getId, ids)) + .stream().collect(Collectors.toMap(ProductPO::getId, ProductPO::getName, (a, b) -> a)); + } + + private Map> loadTargetsByShop(Long companyId, LocalDate start, LocalDate end) { + List months = new ArrayList<>(); + LocalDate cur = start.withDayOfMonth(1); + LocalDate endMonth = end.withDayOfMonth(1); + while (!cur.isAfter(endMonth)) { + months.add(cur); + cur = cur.plusMonths(1); + } + if (months.isEmpty()) { + return Map.of(); + } + LambdaQueryWrapper w = new LambdaQueryWrapper<>(); + w.eq(ShopMonthlyTargetPO::getCompanyId, companyId).in(ShopMonthlyTargetPO::getTargetMonth, months); + return shopMonthlyTargetMapper.selectList(w).stream() + .collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId)); + } + + private static String categoryAggName(Long key, Map names) { + if (key == null || key == -1L) { + return "其他品类"; + } + if (key == 0L) { + return "未分类"; + } + return names.getOrDefault(key, "类目" + key); + } + + private static BigDecimal aov(BigDecimal sales, int count) { + return count > 0 ? sales.divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; + } + + private static BigDecimal safeDivide(BigDecimal a, BigDecimal b) { + return b.compareTo(BigDecimal.ZERO) > 0 ? a.divide(b, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; + } + + private static BigDecimal achievementRate(BigDecimal actual, BigDecimal target) { + if (target.compareTo(BigDecimal.ZERO) > 0) { + return actual.divide(target, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")); + } + return actual.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO; + } + + private static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } + + private static final class AggMetrics { + static final AggMetrics EMPTY = new AggMetrics(); + BigDecimal sales = BigDecimal.ZERO; + /** 全订单状态 GMV(商家实收合计) */ + BigDecimal gmv = BigDecimal.ZERO; + int orderCount; + BigDecimal refund = BigDecimal.ZERO; + BigDecimal productCost = BigDecimal.ZERO; + BigDecimal freightCost = BigDecimal.ZERO; + BigDecimal otherCost = BigDecimal.ZERO; + + /** 订单成本合计(商品+运费+其他,不含推广/刷单) */ + BigDecimal orderCost() { + return productCost.add(freightCost).add(otherCost); + } + + /** 订单维度毛利:未扣推广/刷单/税 */ + BigDecimal grossProfit() { + return sales.subtract(orderCost()).subtract(refund); + } + + static AggMetrics from(OverviewAggRows.ShopProductRow row) { + AggMetrics a = new AggMetrics(); + a.sales = nz(row.getSalesAmount()); + a.gmv = nz(row.getGmvAllStatus()); + a.orderCount = row.getOrderCount() != null ? row.getOrderCount().intValue() : 0; + a.refund = nz(row.getRefundAmount()); + a.productCost = nz(row.getProductCost()); + a.freightCost = nz(row.getFreightCost()); + a.otherCost = nz(row.getOtherCost()); + return a; + } + + AggMetrics merge(AggMetrics o) { + AggMetrics a = new AggMetrics(); + a.sales = sales.add(o.sales); + a.gmv = gmv.add(o.gmv); + a.orderCount = orderCount + o.orderCount; + a.refund = refund.add(o.refund); + a.productCost = productCost.add(o.productCost); + a.freightCost = freightCost.add(o.freightCost); + a.otherCost = otherCost.add(o.otherCost); + return a; + } + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/ExportServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/ExportServiceImpl.java similarity index 75% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/ExportServiceImpl.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/ExportServiceImpl.java index 489d0df1..4ca7a247 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/ExportServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/ExportServiceImpl.java @@ -1,18 +1,14 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.service.impl; +package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyOverviewQueryDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.PlatformExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CategoryExportExcelService; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CompanyOverviewService; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.ExportService; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CompanyExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.PlatformExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.service.ExportService; import java.io.ByteArrayOutputStream; import java.math.BigDecimal; @@ -24,7 +20,7 @@ import java.util.function.Function; import java.util.stream.Collectors; /** - * 概览导出服务实现类 + * 工作台等多维表导出(按已汇总好的表写入 Excel)。 */ @Service public class ExportServiceImpl implements ExportService { @@ -33,38 +29,20 @@ public class ExportServiceImpl implements ExportService { private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private final ExportStatusRangeHelper exportStatusRangeHelper; - private final CategoryExportExcelService categoryExportExcelService; - private final CompanyOverviewService companyOverviewService; - public ExportServiceImpl(ExportStatusRangeHelper exportStatusRangeHelper, - CategoryExportExcelService categoryExportExcelService, - CompanyOverviewService companyOverviewService) { + public ExportServiceImpl(ExportStatusRangeHelper exportStatusRangeHelper) { this.exportStatusRangeHelper = exportStatusRangeHelper; - this.categoryExportExcelService = categoryExportExcelService; - this.companyOverviewService = companyOverviewService; - } - - @Override - public byte[] exportCompanyOverview(CompanyExportDTO dto) { - BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE; - CompanyOverviewQueryDTO query = new CompanyOverviewQueryDTO(); - query.setDateRange(dto.getDateRange()); - query.setTaxRate(taxRate); - CompanyOverviewVO vo = companyOverviewService.getCompanyOverview(query); - return buildShopOverviewExcelBytes(dto, vo.getShopSummary(), vo, "全店 - 按店铺汇总", true); } @Override public byte[] exportShopOverviewFromTable(CompanyExportDTO dto, CompanyOverviewVO.ShopOverview shopOverview, String summaryTitle) { - return buildShopOverviewExcelBytes(dto, shopOverview, null, summaryTitle, false); + return buildShopOverviewExcelBytes(dto, shopOverview, summaryTitle); } private byte[] buildShopOverviewExcelBytes( CompanyExportDTO dto, CompanyOverviewVO.ShopOverview shopOv, - CompanyOverviewVO voForTrend, - String summarySheetTitle, - boolean appendTrendIfPossible) { + String summarySheetTitle) { BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE; List shops = (shopOv != null && shopOv.getShops() != null) @@ -91,14 +69,6 @@ public class ExportServiceImpl implements ExportService { Sheet summarySheet = workbook.createSheet("汇总"); createCompanyDetailSheet( summarySheet, summarySheetTitle, dateRangeLabel, shopRows, taxRate, totalRowMap); - if (appendTrendIfPossible - && voForTrend != null - && voForTrend.getSalesAmountTrend() != null - && voForTrend.getSalesAmountTrend().getDailyDataList() != null - && !voForTrend.getSalesAmountTrend().getDailyDataList().isEmpty()) { - Sheet trendSheet = workbook.createSheet("销售趋势"); - writeCompanyOverviewTrendSheet(trendSheet, "全店", dateRangeLabel, voForTrend); - } try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { workbook.write(out); return out.toByteArray(); @@ -108,20 +78,6 @@ public class ExportServiceImpl implements ExportService { } } - @Override - public byte[] exportCategoryOverview(CategoryExportDTO dto) { - if (dto.getShopId() != null) { - return categoryExportExcelService.exportCategoryOverview(dto); - } - CompanyOverviewQueryDTO query = new CompanyOverviewQueryDTO(); - query.setDateRange(dto.getDateRange()); - query.setTaxRate(dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE); - CompanyOverviewVO vo = companyOverviewService.getCompanyOverview(query); - return categoryExportExcelService.exportStoreCategoryFromOverview(dto, vo); - } - - // ==================== Sheet 构建方法 ==================== - private void createCompanyDetailSheet( Sheet sheet, String summaryTitle, @@ -282,7 +238,6 @@ public class ExportServiceImpl implements ExportService { return data; } - /** 与全店概览一致:税额 = max(0, 销售额 − 退款) × 税率,两位小数。 */ private static BigDecimal salesTaxOnNetForExport(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) { BigDecimal s = sales != null ? sales : BigDecimal.ZERO; BigDecimal rfd = refund != null ? refund : BigDecimal.ZERO; @@ -467,97 +422,32 @@ public class ExportServiceImpl implements ExportService { return total; } - private void writeCompanyOverviewTrendSheet( - Sheet sheet, String contextTitle, String dateRangeLabel, CompanyOverviewVO vo) { - Workbook wb = sheet.getWorkbook(); - CellStyle headerStyle = createHeaderStyle(wb); - CellStyle dataStyle = createDataStyle(wb); - - Row titleRow = sheet.createRow(0); - Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue(contextTitle + " - 销售趋势 | " + dateRangeLabel); - titleCell.setCellStyle(createTitleStyle(wb)); - sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); - - String[] headers = {"日期", "销售额", "单量"}; - Row headerRow = sheet.createRow(1); - for (int i = 0; i < headers.length; i++) { - Cell cell = headerRow.createCell(i); - cell.setCellValue(headers[i]); - cell.setCellStyle(headerStyle); - } - - List dailySales = vo.getSalesAmountTrend().getDailyDataList(); - List dailyOrders = vo.getOrderCountTrend() != null - ? vo.getOrderCountTrend().getDailyDataList() - : null; - - Map salesMap = dailySales.stream() - .collect(Collectors.toMap( - CompanyOverviewVO.TrendDataItem::getDate, - CompanyOverviewVO.TrendDataItem::getValue, - (a, b) -> a)); - Map ordersMap = dailyOrders != null - ? dailyOrders.stream() - .collect(Collectors.toMap( - CompanyOverviewVO.TrendDataItem::getDate, - CompanyOverviewVO.TrendDataItem::getValue, - (a, b) -> a)) - : Collections.emptyMap(); - - LocalDate startDate = dailySales.stream() - .map(CompanyOverviewVO.TrendDataItem::getDate) - .min(LocalDate::compareTo) - .orElse(null); - LocalDate endDate = dailySales.stream() - .map(CompanyOverviewVO.TrendDataItem::getDate) - .max(LocalDate::compareTo) - .orElse(null); - - int rowIdx = 2; - if (startDate != null && endDate != null) { - LocalDate current = startDate; - while (!current.isAfter(endDate)) { - Row row = sheet.createRow(rowIdx++); - BigDecimal sales = salesMap.getOrDefault(current, BigDecimal.ZERO); - BigDecimal orders = ordersMap.getOrDefault(current, BigDecimal.ZERO); - setCell(row, 0, current.format(DATE_FMT), dataStyle); - setCell(row, 1, sales.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 2, orders.setScale(0, RoundingMode.HALF_UP).doubleValue(), dataStyle); - current = current.plusDays(1); - } - } - - sheet.setColumnWidth(0, 3200); - sheet.setColumnWidth(1, 3200); - sheet.setColumnWidth(2, 3200); - } - private double objToDouble(Object val) { - if (val == null) return 0.0; - if (val instanceof BigDecimal) return ((BigDecimal) val).setScale(2, RoundingMode.HALF_UP).doubleValue(); - if (val instanceof Integer) return ((Integer) val).doubleValue(); - return 0.0; + if (val == null) { + return 0; + } + if (val instanceof Number) { + return ((Number) val).doubleValue(); + } + return 0; } private double objToPct(Object val) { - if (val == null) return 0.0; - if (val instanceof BigDecimal) return ((BigDecimal) val).setScale(2, RoundingMode.HALF_UP).doubleValue(); - if (val instanceof Double) return BigDecimal.valueOf((Double) val).setScale(2, RoundingMode.HALF_UP).doubleValue(); - if (val instanceof Integer) return ((Integer) val).doubleValue(); - return 0.0; + if (val == null) { + return 0; + } + if (val instanceof Number) { + return ((Number) val).doubleValue(); + } + return 0; } - // ==================== Excel 样式工具 ==================== - private CellStyle createTitleStyle(Workbook workbook) { CellStyle style = workbook.createCellStyle(); Font font = workbook.createFont(); font.setBold(true); font.setFontHeightInPoints((short) 14); style.setFont(font); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } @@ -572,8 +462,6 @@ public class ExportServiceImpl implements ExportService { style.setBorderTop(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } @@ -583,10 +471,6 @@ public class ExportServiceImpl implements ExportService { style.setBorderTop(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - DataFormat format = workbook.createDataFormat(); - style.setDataFormat(format.getFormat("#,##0.00")); return style; } @@ -610,27 +494,15 @@ public class ExportServiceImpl implements ExportService { cell.setCellStyle(style); } - @Override - public byte[] exportPlatformOverview(PlatformExportDTO dto) { - BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE; - CompanyOverviewQueryDTO query = new CompanyOverviewQueryDTO(); - query.setDateRange(dto.getDateRange()); - query.setTaxRate(taxRate); - CompanyOverviewVO vo = companyOverviewService.getCompanyOverview(query); - return buildPlatformOverviewExcelBytes(dto, vo.getPlatformSummary(), vo, "全店 - 按平台汇总", true); - } - @Override public byte[] exportPlatformOverviewFromTable(PlatformExportDTO dto, CompanyOverviewVO.PlatformOverview platformOverview, String summaryTitle) { - return buildPlatformOverviewExcelBytes(dto, platformOverview, null, summaryTitle, false); + return buildPlatformOverviewExcelBytes(dto, platformOverview, summaryTitle); } private byte[] buildPlatformOverviewExcelBytes( PlatformExportDTO dto, CompanyOverviewVO.PlatformOverview platformOv, - CompanyOverviewVO voForTrend, - String summarySheetTitle, - boolean appendTrendIfPossible) { + String summarySheetTitle) { BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE; List platforms = (platformOv != null && platformOv.getPlatforms() != null) @@ -661,14 +533,6 @@ public class ExportServiceImpl implements ExportService { Sheet summarySheet = workbook.createSheet("汇总"); createPlatformSummarySheet( summarySheet, summarySheetTitle, dateRangeLabel, platformRows, taxRate, totalRowMap); - if (appendTrendIfPossible - && voForTrend != null - && voForTrend.getSalesAmountTrend() != null - && voForTrend.getSalesAmountTrend().getDailyDataList() != null - && !voForTrend.getSalesAmountTrend().getDailyDataList().isEmpty()) { - Sheet trendSheet = workbook.createSheet("销售趋势"); - writeCompanyOverviewTrendSheet(trendSheet, "全店", dateRangeLabel, voForTrend); - } try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { workbook.write(out); return out.toByteArray(); @@ -677,4 +541,4 @@ public class ExportServiceImpl implements ExportService { throw new BusinessException("导出平台Excel失败: " + e.getMessage()); } } -} \ No newline at end of file +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/ExportStatusRangeHelper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/ExportStatusRangeHelper.java similarity index 96% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/ExportStatusRangeHelper.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/ExportStatusRangeHelper.java index 136c9df0..0778ac20 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/ExportStatusRangeHelper.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/service/impl/ExportStatusRangeHelper.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.service.impl; +package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl; import org.springframework.stereotype.Component; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/util/ExportFilenameUtils.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/util/ExportFilenameUtils.java similarity index 97% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/util/ExportFilenameUtils.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/util/ExportFilenameUtils.java index 485068e1..36375244 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/util/ExportFilenameUtils.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/overview/util/ExportFilenameUtils.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.util; +package top.xyquan.ecomdmbbackend.modules.bi.overview.util; import java.time.LocalDate; import java.time.format.DateTimeFormatter; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/controller/BiProductOverviewController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/controller/BiProductOverviewController.java new file mode 100644 index 00000000..b780015c --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/controller/BiProductOverviewController.java @@ -0,0 +1,33 @@ +package top.xyquan.ecomdmbbackend.modules.bi.productoverview.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +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.productoverview.service.BiProductOverviewService; +import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.dto.ProductOverviewQueryDTO; +import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo.ProductOverviewVO; + +@Tag(name = "BI-商品概览", description = "商品概览(Mongo 订单/SKU 日汇聚)") +@RestController +@RequestMapping("/api/bi/product") +public class BiProductOverviewController { + + private final BiProductOverviewService biProductOverviewService; + + public BiProductOverviewController(BiProductOverviewService biProductOverviewService) { + this.biProductOverviewService = biProductOverviewService; + } + + @Operation(summary = "商品概览", description = "KPI、趋势、规格汇总;订单/SKU 读 Mongo,推广/目标读 MySQL") + @PostMapping("/overview") + @RequirePermission(value = "ecom:product:read", description = "查询商品概览", allowSuper = true) + public ApiResponse overview(@Valid @RequestBody ProductOverviewQueryDTO queryDTO) { + return ApiResponse.success("获取商品总览成功", biProductOverviewService.getProductOverview(queryDTO)); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/model/dto/ProductOverviewQueryDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/model/dto/ProductOverviewQueryDTO.java similarity index 94% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/model/dto/ProductOverviewQueryDTO.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/model/dto/ProductOverviewQueryDTO.java index 9deac0fb..2f6e5564 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/model/dto/ProductOverviewQueryDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/model/dto/ProductOverviewQueryDTO.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.dto; +package top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.dto; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotNull; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/model/vo/ProductOverviewVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/model/vo/ProductOverviewVO.java similarity index 99% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/model/vo/ProductOverviewVO.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/model/vo/ProductOverviewVO.java index 4d450c3c..50dfb2ad 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/model/vo/ProductOverviewVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/model/vo/ProductOverviewVO.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.vo; +package top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.v3.oas.annotations.media.Schema; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/service/BiProductOverviewService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/service/BiProductOverviewService.java new file mode 100644 index 00000000..c793690f --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/service/BiProductOverviewService.java @@ -0,0 +1,12 @@ +package top.xyquan.ecomdmbbackend.modules.bi.productoverview.service; + +import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.dto.ProductOverviewQueryDTO; +import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo.ProductOverviewVO; + +/** + * BI 商品概览:订单/SKU 读 Mongo 日汇聚,推广/目标读 MySQL。 + */ +public interface BiProductOverviewService { + + ProductOverviewVO getProductOverview(ProductOverviewQueryDTO queryDTO); +} 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 new file mode 100644 index 00000000..9dd21957 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/productoverview/service/impl/BiProductOverviewServiceImpl.java @@ -0,0 +1,426 @@ +package top.xyquan.ecomdmbbackend.modules.bi.productoverview.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import org.springframework.stereotype.Service; +import top.xyquan.ecomdmbbackend.common.exception.BusinessException; +import top.xyquan.ecomdmbbackend.modules.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.mapper.ProductSkuMapper; +import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO; +import top.xyquan.ecomdmbbackend.modules.ec.product.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.ec.product.service.ProductService; +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; +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.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 商品概览:Mongo product/sku 日汇聚 + MySQL 推广/目标。 + * 推广分摊复用工作台四表(按店全量商品行作分母),不再扫订单明细。 + */ +@Service +public class BiProductOverviewServiceImpl implements BiProductOverviewService { + + private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04"); + + private final CurrentUserContext currentUserContext; + private final ProductService productService; + private final ShopService shopService; + private final BiOrderStatQueryService orderStatQueryService; + private final BiWorkbenchFeeLoader feeLoader; + private final CompanyOverviewService companyOverviewService; + private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; + private final ProductSkuMapper productSkuMapper; + + public BiProductOverviewServiceImpl(CurrentUserContext currentUserContext, + ProductService productService, + ShopService shopService, + BiOrderStatQueryService orderStatQueryService, + BiWorkbenchFeeLoader feeLoader, + CompanyOverviewService companyOverviewService, + ShopMonthlyTargetMapper shopMonthlyTargetMapper, + ProductSkuMapper productSkuMapper) { + this.currentUserContext = currentUserContext; + this.productService = productService; + this.shopService = shopService; + this.orderStatQueryService = orderStatQueryService; + this.feeLoader = feeLoader; + this.companyOverviewService = companyOverviewService; + this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; + this.productSkuMapper = productSkuMapper; + } + + @Override + public ProductOverviewVO getProductOverview(ProductOverviewQueryDTO queryDTO) { + Long companyId = currentUserContext.getCurrentCompanyId(); + ProductPO product = productService.getById(queryDTO.getProductId()); + if (product == null || !Objects.equals(product.getCompanyId(), companyId)) { + throw new BusinessException("商品不存在"); + } + if (queryDTO.getStartDate().isAfter(queryDTO.getEndDate())) { + throw new BusinessException("开始日期不能晚于结束日期"); + } + + 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; + List thisProductDocs = + orderStatQueryService.listProductDocs(companyId, shopIdFilter, product.getId(), start, end); + + List shopIds; + if (filterShopId != null) { + shopIds = List.of(filterShopId); + } else { + shopIds = thisProductDocs.stream() + .map(BiOrderStatDailyProductDoc::getShopId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + } + + List shops = shopIds.isEmpty() ? List.of() + : shopService.listByIds(shopIds).stream() + .filter(s -> s != null && Objects.equals(s.getCompanyId(), companyId)) + .collect(Collectors.toList()); + Map platformByShopId = shops.stream() + .collect(Collectors.toMap(ShopPO::getId, + 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 orderRows = + orderStatQueryService.toShopProductRows(allProductDocs, platformByShopId); + CompanyOverviewVO.WorkbenchTableBundle tables = shops.isEmpty() + ? emptyTables() + : 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.getOrderCount() != null + ? productRow.getOrderCount() + : sumOrders(thisProductDocs); + BigDecimal refund = productRow != null ? nz(productRow.getRefundAmount()) : sumRefund(thisProductDocs); + BigDecimal promo = productRow != null ? nz(productRow.getTotalPromotionFee()) : BigDecimal.ZERO; + BigDecimal orderCost = productRow != null ? nz(productRow.getOrderCost()) + : sumCost(thisProductDocs); + BigDecimal tax = salesTax(sales, refund, taxRate); + BigDecimal net = sales.subtract(orderCost).subtract(refund).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.subtract(refund), 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; + } + + 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); + } + return curSales.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100.00") : BigDecimal.ZERO; + } + + private void fillTargets(ProductOverviewVO vo, Long companyId, List shopIds, + LocalDate start, LocalDate end, BigDecimal sales, int orderCount) { + if (shopIds == null || shopIds.isEmpty()) { + return; + } + LocalDate first = start.withDayOfMonth(1); + LocalDate last = end.withDayOfMonth(end.lengthOfMonth()); + List targets = shopMonthlyTargetMapper.selectList( + new LambdaQueryWrapper() + .eq(ShopMonthlyTargetPO::getCompanyId, companyId) + .in(ShopMonthlyTargetPO::getShopId, shopIds) + .ge(ShopMonthlyTargetPO::getTargetMonth, first) + .le(ShopMonthlyTargetPO::getTargetMonth, last)); + BigDecimal targetAmt = targets.stream() + .map(ShopMonthlyTargetPO::getTargetAmount) + .filter(Objects::nonNull) + .reduce(BigDecimal.ZERO, BigDecimal::add); + int targetOrders = targets.stream() + .map(ShopMonthlyTargetPO::getTargetOrderCount) + .filter(Objects::nonNull) + .mapToInt(Integer::intValue) + .sum(); + if (targetAmt.compareTo(BigDecimal.ZERO) > 0) { + vo.setSalesAmountAchievementRate(sales.divide(targetAmt, 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP)); + } + if (targetOrders > 0) { + vo.setOrderCountAchievementRate(BigDecimal.valueOf(orderCount) + .divide(BigDecimal.valueOf(targetOrders), 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP)); + } + } + + private ProductOverviewVO.SpecSummary buildSpecSummary( + List metrics, + BigDecimal taxRate, + BigDecimal totalPromo) { + BigDecimal salesPool = metrics.stream() + .map(BiOrderStatQueryService.SkuPeriodMetrics::salesAmount) + .map(BiProductOverviewServiceImpl::nz) + .reduce(BigDecimal.ZERO, BigDecimal::add); + + Set skuIds = metrics.stream() + .map(BiOrderStatQueryService.SkuPeriodMetrics::productSkuId) + .filter(id -> id > 0) + .collect(Collectors.toCollection(HashSet::new)); + Map skuMap = new HashMap<>(); + if (!skuIds.isEmpty()) { + for (ProductSkuPO sku : productSkuMapper.selectBatchIds(skuIds)) { + if (sku != null && sku.getId() != null) { + skuMap.put(sku.getId(), sku); + } + } + } + + List list = new ArrayList<>(); + for (BiOrderStatQueryService.SkuPeriodMetrics m : metrics) { + BigDecimal sales = nz(m.salesAmount()); + BigDecimal sharePromo = salesPool.compareTo(BigDecimal.ZERO) > 0 + ? nz(totalPromo).multiply(sales).divide(salesPool, 4, RoundingMode.HALF_UP) + : BigDecimal.ZERO; + BigDecimal refund = nz(m.refundAmount()); + BigDecimal cost = m.orderCost(); + BigDecimal tax = salesTax(sales, refund, taxRate); + BigDecimal pbt = sales.subtract(cost).subtract(refund).subtract(sharePromo); + BigDecimal pat = pbt.subtract(tax); + + ProductSkuPO sku = m.productSkuId() > 0 ? skuMap.get(m.productSkuId()) : null; + ProductOverviewVO.SpecSummaryItem item = new ProductOverviewVO.SpecSummaryItem(); + item.setSkuId(m.productSkuId() > 0 ? m.productSkuId() : null); + item.setSkuName(sku != null ? sku.getName() + : (m.productSkuId() > 0 ? "规格" + m.productSkuId() : "未绑定规格")); + item.setSkuCode(sku != null ? sku.getSkuCode() : null); + item.setSalesAmount(sales.setScale(2, RoundingMode.HALF_UP)); + item.setOrderCount(m.salesOrderCount()); + item.setQuantity(m.salesQuantitySum()); + 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.setOrderCost(cost.setScale(2, RoundingMode.HALF_UP)); + item.setRefundAmount(refund.setScale(2, RoundingMode.HALF_UP)); + item.setPromotionFee(sharePromo.setScale(2, RoundingMode.HALF_UP)); + item.setFeeRatio(sales.compareTo(BigDecimal.ZERO) > 0 + ? sharePromo.divide(sales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO); + item.setProfitBeforeTax(pbt.setScale(2, RoundingMode.HALF_UP)); + item.setSalesTaxAmount(tax); + item.setRoi(roi(sales.subtract(refund), sharePromo)); + item.setProfitAfterTax(pat.setScale(2, RoundingMode.HALF_UP)); + list.add(item); + } + list.sort(Comparator.comparing(ProductOverviewVO.SpecSummaryItem::getSalesAmount, + 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.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.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.setRoi(roi(total.getSalesAmount().subtract(total.getRefundAmount()), total.getPromotionFee())); + total.setProfitAfterTax(list.stream().map(i -> nz(i.getProfitAfterTax())).reduce(BigDecimal.ZERO, BigDecimal::add)); + + ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary(); + summary.setList(list); + summary.setTotal(total); + return summary; + } + + private static List buildSpecTop10( + ProductOverviewVO.SpecSummary summary) { + if (summary == null || summary.getList() == null) { + return List.of(); + } + return summary.getList().stream() + .sorted(Comparator.comparing( + (ProductOverviewVO.SpecSummaryItem i) -> + i.getOrderCount() != null ? i.getOrderCount() : 0, + Comparator.reverseOrder())) + .limit(10) + .map(i -> { + ProductOverviewVO.SpecSalesRankItem r = new ProductOverviewVO.SpecSalesRankItem(); + r.setSkuId(i.getSkuId()); + r.setSkuName(i.getSkuName()); + r.setSkuCode(i.getSkuCode()); + r.setOrderCount(i.getOrderCount()); + r.setSalesAmount(i.getSalesAmount()); + return r; + }) + .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) { + return null; + } + return table.getCategories().stream() + .filter(c -> Objects.equals(c.getCategoryId(), productId)) + .findFirst() + .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.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); + } + + private static BigDecimal sumRefund(List docs) { + return docs.stream().map(d -> 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 -> d.getSalesOrderCount() != null ? d.getSalesOrderCount() : 0).sum(); + } + + private static BigDecimal salesTax(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) { + BigDecimal base = nz(sales).subtract(nz(refund)); + 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 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); + } + + private static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/shop/controller/ShopExportController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/controller/BiShopExportController.java similarity index 80% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/shop/controller/ShopExportController.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/controller/BiShopExportController.java index 37e79806..aad4ae1f 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/shop/controller/ShopExportController.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/controller/BiShopExportController.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.shop.controller; +package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.controller; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; @@ -11,25 +11,25 @@ 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.modules.ec.overview.model.dto.CategoryExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.util.ExportFilenameUtils; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.util.ExportFilenameUtils; import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO; -import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopExportService; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopExportService; import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService; /** - * 店铺侧 Excel 导出:{@code /ec/shop/export/summary-by-product}、{@code /ec/shop/export/summary-by-category} + * 店铺 Excel 导出:{@code /bi/shop/export/summary-by-product}、{@code /bi/shop/export/summary-by-category} */ -@Tag(name = "电商-店铺导出", description = "店铺数据按商品/按品类汇总导出") +@Tag(name = "BI-店铺导出", description = "店铺概览按商品/按品类汇总导出(Mongo 同源)") @RestController -@RequestMapping("/api/ec/shop/export") -public class ShopExportController { +@RequestMapping("/api/bi/shop/export") +public class BiShopExportController { - private final ShopExportService shopExportService; + private final BiShopExportService shopExportService; private final ShopService shopService; - public ShopExportController(ShopExportService shopExportService, ShopService shopService) { + public BiShopExportController(BiShopExportService shopExportService, ShopService shopService) { this.shopExportService = shopExportService; this.shopService = shopService; } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/controller/BiShopOverviewController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/controller/BiShopOverviewController.java new file mode 100644 index 00000000..d57978df --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/controller/BiShopOverviewController.java @@ -0,0 +1,33 @@ +package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +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.shopoverview.service.BiShopOverviewService; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO; + +@Tag(name = "BI-店铺概览", description = "单店概览(Mongo 订单日汇聚)") +@RestController +@RequestMapping("/api/bi/shop") +public class BiShopOverviewController { + + private final BiShopOverviewService biShopOverviewService; + + public BiShopOverviewController(BiShopOverviewService biShopOverviewService) { + this.biShopOverviewService = biShopOverviewService; + } + + @Operation(summary = "店铺概览", description = "KPI、趋势、商品/品类汇总;订单读 Mongo,推广/刷单/目标读 MySQL") + @PostMapping("/overview") + @RequirePermission(value = "ecom:shop:read", description = "查询店铺概览", allowSuper = true) + public ApiResponse overview(@Valid @RequestBody ShopOverviewQueryDTO queryDTO) { + return ApiResponse.success("获取店铺概览成功", biShopOverviewService.getShopOverview(queryDTO)); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/ShopExportDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/model/dto/ShopExportDTO.java similarity index 94% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/ShopExportDTO.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/model/dto/ShopExportDTO.java index 92800ca4..5cf00ea9 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/ShopExportDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/model/dto/ShopExportDTO.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto; +package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotEmpty; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/ShopOverviewQueryDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/model/dto/ShopOverviewQueryDTO.java similarity index 95% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/ShopOverviewQueryDTO.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/model/dto/ShopOverviewQueryDTO.java index b27cd392..e70efabe 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/ShopOverviewQueryDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/model/dto/ShopOverviewQueryDTO.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto; +package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotEmpty; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/vo/ShopOverviewStatisticsVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/model/vo/ShopOverviewStatisticsVO.java similarity index 99% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/vo/ShopOverviewStatisticsVO.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/model/vo/ShopOverviewStatisticsVO.java index e93db17c..1c3d556a 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/vo/ShopOverviewStatisticsVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/model/vo/ShopOverviewStatisticsVO.java @@ -1,4 +1,4 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo; +package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.v3.oas.annotations.media.Schema; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/BiShopExportService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/BiShopExportService.java new file mode 100644 index 00000000..f36ef0da --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/BiShopExportService.java @@ -0,0 +1,14 @@ +package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service; + +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO; + +/** + * BI 店铺概览 Excel 导出(按商品 / 按品类)。 + */ +public interface BiShopExportService { + + byte[] exportShopSummaryByProduct(ShopExportDTO dto); + + byte[] exportShopSummaryByCategory(CategoryExportDTO dto); +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/BiShopOverviewService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/BiShopOverviewService.java new file mode 100644 index 00000000..2a67e1f8 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/BiShopOverviewService.java @@ -0,0 +1,12 @@ +package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service; + +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO; + +/** + * BI 单店概览:订单读 Mongo 日汇聚,推广/刷单/目标读 MySQL。 + */ +public interface BiShopOverviewService { + + ShopOverviewStatisticsVO getShopOverview(ShopOverviewQueryDTO queryDTO); +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/shop/service/impl/ShopExportServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/impl/BiShopExportServiceImpl.java similarity index 93% rename from ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/shop/service/impl/ShopExportServiceImpl.java rename to ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/impl/BiShopExportServiceImpl.java index 544e40a8..2faf68f0 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/shop/service/impl/ShopExportServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/impl/BiShopExportServiceImpl.java @@ -1,17 +1,17 @@ -package top.xyquan.ecomdmbbackend.modules.ec.shop.service.impl; +package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.impl; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopOverviewQueryDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.ShopOverviewStatisticsVO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.ShopOverviewStatisticsService; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CategoryExportExcelService; -import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopExportService; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopOverviewService; +import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CategoryExportExcelService; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopExportService; import java.io.ByteArrayOutputStream; import java.math.BigDecimal; @@ -24,7 +24,7 @@ import java.util.Map; import java.util.stream.Collectors; @Service -public class ShopExportServiceImpl implements ShopExportService { +public class BiShopExportServiceImpl implements BiShopExportService { private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04"); private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); @@ -41,13 +41,13 @@ public class ShopExportServiceImpl implements ShopExportService { return base.multiply(r).setScale(2, RoundingMode.HALF_UP); } - private final ShopOverviewStatisticsService shopOverviewStatisticsService; + private final BiShopOverviewService biShopOverviewService; private final CategoryExportExcelService categoryExportExcelService; - public ShopExportServiceImpl( - ShopOverviewStatisticsService shopOverviewStatisticsService, + public BiShopExportServiceImpl( + BiShopOverviewService biShopOverviewService, CategoryExportExcelService categoryExportExcelService) { - this.shopOverviewStatisticsService = shopOverviewStatisticsService; + this.biShopOverviewService = biShopOverviewService; this.categoryExportExcelService = categoryExportExcelService; } @@ -59,7 +59,7 @@ public class ShopExportServiceImpl implements ShopExportService { BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE; queryDTO.setTaxRate(taxRate); - ShopOverviewStatisticsVO vo = shopOverviewStatisticsService.getShopOverviewStatistics(queryDTO); + ShopOverviewStatisticsVO vo = biShopOverviewService.getShopOverview(queryDTO); String dateRangeLabel = dto.getDateRange().get(0).format(DATE_FMT) + " 至 " + dto.getDateRange().get(dto.getDateRange().size() - 1).format(DATE_FMT); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/impl/BiShopOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/impl/BiShopOverviewServiceImpl.java new file mode 100644 index 00000000..922bf765 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/shopoverview/service/impl/BiShopOverviewServiceImpl.java @@ -0,0 +1,387 @@ +package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import org.springframework.stereotype.Service; +import top.xyquan.ecomdmbbackend.common.exception.BusinessException; +import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc; +import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc; +import top.xyquan.ecomdmbbackend.modules.bi.orderstat.query.BiOrderStatQueryService; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopOverviewService; +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.shopoverview.model.dto.ShopOverviewQueryDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO; +import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CompanyOverviewService; +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.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; +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.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 单店概览:Mongo shop/product 日汇聚 + MySQL 推广/刷单/目标;表结构复用工作台四表构建。 + */ +@Service +public class BiShopOverviewServiceImpl implements BiShopOverviewService { + + private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04"); + + private final CurrentUserContext currentUserContext; + private final ShopService shopService; + private final BiOrderStatQueryService orderStatQueryService; + private final BiWorkbenchFeeLoader feeLoader; + private final CompanyOverviewService companyOverviewService; + private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; + private final ProductMapper productMapper; + + public BiShopOverviewServiceImpl(CurrentUserContext currentUserContext, + ShopService shopService, + BiOrderStatQueryService orderStatQueryService, + BiWorkbenchFeeLoader feeLoader, + CompanyOverviewService companyOverviewService, + ShopMonthlyTargetMapper shopMonthlyTargetMapper, + ProductMapper productMapper) { + this.currentUserContext = currentUserContext; + this.shopService = shopService; + this.orderStatQueryService = orderStatQueryService; + this.feeLoader = feeLoader; + this.companyOverviewService = companyOverviewService; + this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; + this.productMapper = productMapper; + } + + @Override + public ShopOverviewStatisticsVO getShopOverview(ShopOverviewQueryDTO queryDTO) { + BigDecimal taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE; + Long companyId = currentUserContext.getCurrentCompanyId(); + + LocalDate startDate; + LocalDate endDate; + if (queryDTO.getDateRange().size() == 1) { + startDate = queryDTO.getDateRange().get(0); + endDate = startDate; + } else { + startDate = queryDTO.getDateRange().get(0); + endDate = queryDTO.getDateRange().get(1); + if (startDate.isAfter(endDate)) { + throw new BusinessException("开始日期不能晚于结束日期"); + } + } + + ShopPO shop = shopService.getById(queryDTO.getShopId()); + if (shop == null || !Objects.equals(shop.getCompanyId(), companyId)) { + throw new BusinessException("店铺不存在"); + } + + List shopIds = List.of(shop.getId()); + List shops = List.of(shop); + Map platformByShopId = Map.of(shop.getId(), + shop.getPlatformCode() != null ? shop.getPlatformCode() : ""); + + List shopDocs = + orderStatQueryService.listShopDocs(companyId, shopIds, startDate, endDate); + List productDocs = + orderStatQueryService.listProductDocs(companyId, shopIds, startDate, endDate); + BiWorkbenchFeeLoader.FeeBundle fees = feeLoader.load(companyId, shopIds, startDate, endDate); + + List orderRows = + orderStatQueryService.toShopProductRows(productDocs, platformByShopId); + CompanyOverviewVO.WorkbenchTableBundle tables = + companyOverviewService.buildWorkbenchSummaryTablesFromAgg( + taxRate, companyId, shops, orderRows, + fees.promotionRows(), fees.brushRows(), startDate, endDate); + + BiOrderStatQueryService.ShopPeriodMetrics m = orderStatQueryService.sumShopDocs(shopDocs); + BigDecimal promo = fees.promoTotal(); + BigDecimal brush = fees.brushTotal(); + BigDecimal orderCost = nz(m.productCost()).add(nz(m.freightCost())).add(nz(m.otherCost())); + BigDecimal gross = nz(m.salesAmount()).subtract(orderCost).subtract(nz(m.refundAmount())); + BigDecimal pbt = gross.subtract(promo).subtract(brush); + BigDecimal tax = salesTax(m.salesAmount(), m.refundAmount(), taxRate); + + ShopOverviewStatisticsVO vo = new ShopOverviewStatisticsVO(); + vo.setShopId(shop.getId()); + vo.setShopName(shop.getName()); + vo.setTotalSalesAmount(nz(m.salesAmount()).setScale(2, RoundingMode.HALF_UP)); + vo.setTotalOrderCount(m.salesOrderCount()); + vo.setRefundAmount(nz(m.refundAmount()).setScale(2, RoundingMode.HALF_UP)); + vo.setAverageOrderValue(m.salesOrderCount() > 0 + ? nz(m.salesAmount()).divide(BigDecimal.valueOf(m.salesOrderCount()), 2, RoundingMode.HALF_UP) + : BigDecimal.ZERO); + vo.setTotalPromotionFee(promo.setScale(2, RoundingMode.HALF_UP)); + vo.setAverageFeeRatio(nz(m.salesAmount()).compareTo(BigDecimal.ZERO) > 0 + ? promo.divide(nz(m.salesAmount()), 4, RoundingMode.HALF_UP) + : BigDecimal.ZERO); + vo.setTotalProfitBeforeTax(pbt.setScale(2, RoundingMode.HALF_UP)); + vo.setTotalTaxAmount(tax); + vo.setTotalNetProfitAfterTax(pbt.subtract(tax).setScale(2, RoundingMode.HALF_UP)); + vo.setTotalROI(roi(nz(m.salesAmount()).subtract(nz(m.refundAmount())), promo)); + vo.setMonthOverMonthGrowth(calcMomGrowth(companyId, shopIds, startDate, endDate, m.salesAmount())); + + fillTargets(vo, companyId, shop.getId(), startDate, endDate, m.salesAmount(), m.salesOrderCount()); + + Map daily = + orderStatQueryService.toDailyRows(shopDocs).stream() + .filter(d -> d.getStatDate() != null) + .collect(Collectors.toMap(OverviewAggRows.DailyRow::getStatDate, d -> d, (a, b) -> a)); + vo.setSalesAmountTrend(buildTrend(startDate, endDate, daily, true)); + vo.setOrderCountTrend(buildTrend(startDate, endDate, daily, false)); + + Map products = loadProducts(tables.getProductTable()); + vo.setProductOverview(mapProductOverview(tables.getProductTable(), products)); + vo.setCategoryOverview(mapCategoryOverview(tables.getCategoryTable())); + fillProductSalesTop10(vo); + + return vo; + } + + private BigDecimal calcMomGrowth(Long companyId, List shopIds, + LocalDate start, LocalDate end, BigDecimal curSales) { + LocalDate prevStart = start.minusMonths(1); + LocalDate prevEnd = end.minusMonths(1); + BiOrderStatQueryService.ShopPeriodMetrics prev = + orderStatQueryService.sumShopDocs( + orderStatQueryService.listShopDocs(companyId, shopIds, prevStart, prevEnd)); + BigDecimal last = nz(prev.salesAmount()); + if (last.compareTo(BigDecimal.ZERO) > 0) { + return nz(curSales).subtract(last) + .divide(last, 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal("100")); + } + return nz(curSales).compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO; + } + + private void fillTargets(ShopOverviewStatisticsVO vo, Long companyId, Long shopId, + LocalDate startDate, LocalDate endDate, + BigDecimal sales, int orderCount) { + List months = new ArrayList<>(); + LocalDate cur = startDate.withDayOfMonth(1); + LocalDate endMonth = endDate.withDayOfMonth(1); + while (!cur.isAfter(endMonth)) { + months.add(cur); + cur = cur.plusMonths(1); + } + List targets = months.isEmpty() ? List.of() + : shopMonthlyTargetMapper.selectList(new LambdaQueryWrapper() + .eq(ShopMonthlyTargetPO::getCompanyId, companyId) + .eq(ShopMonthlyTargetPO::getShopId, shopId) + .in(ShopMonthlyTargetPO::getTargetMonth, months)); + + BigDecimal targetAmt = targets.stream() + .map(t -> t.getTargetAmount() != null ? t.getTargetAmount() : BigDecimal.ZERO) + .reduce(BigDecimal.ZERO, BigDecimal::add); + int targetOrders = targets.stream() + .mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0) + .sum(); + vo.setTotalTargetAmount(targetAmt); + vo.setTotalTargetOrderCount(targetOrders); + vo.setSalesAmountAchievementRate(achievement(sales, targetAmt)); + vo.setOrderCountAchievementRate(achievement(BigDecimal.valueOf(orderCount), BigDecimal.valueOf(targetOrders))); + } + + private static BigDecimal achievement(BigDecimal actual, BigDecimal target) { + if (target != null && target.compareTo(BigDecimal.ZERO) > 0) { + return nz(actual).divide(target, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")); + } + return nz(actual).compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO; + } + + private ShopOverviewStatisticsVO.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); + ShopOverviewStatisticsVO.TrendDataItem item = new ShopOverviewStatisticsVO.TrendDataItem(); + item.setDate(d); + item.setValue(value); + items.add(item); + total = total.add(value); + } + ShopOverviewStatisticsVO.TrendData trend = new ShopOverviewStatisticsVO.TrendData(); + trend.setTotal(total); + trend.setDailyDataList(items); + return trend; + } + + private Map loadProducts(CompanyOverviewVO.CategoryOverview productTable) { + if (productTable == null || productTable.getCategories() == null) { + return Map.of(); + } + Set ids = productTable.getCategories().stream() + .map(CompanyOverviewVO.CategorySummary::getCategoryId) + .filter(Objects::nonNull) + .filter(id -> id > 0) + .collect(Collectors.toSet()); + if (ids.isEmpty()) { + return Map.of(); + } + Map map = new HashMap<>(); + for (ProductPO p : productMapper.selectBatchIds(ids)) { + if (p != null && p.getId() != null) { + map.put(p.getId(), p); + } + } + return map; + } + + private static ShopOverviewStatisticsVO.ProductOverview mapProductOverview( + CompanyOverviewVO.CategoryOverview table, Map products) { + ShopOverviewStatisticsVO.ProductOverview po = new ShopOverviewStatisticsVO.ProductOverview(); + if (table == null) { + po.setProducts(List.of()); + return po; + } + po.setTotal(mapToProductSummary(table.getTotal(), null, products)); + if (table.getCategories() != null) { + po.setProducts(table.getCategories().stream() + .map(c -> mapToProductSummary(c, c.getCategoryId(), products)) + .collect(Collectors.toList())); + } else { + po.setProducts(List.of()); + } + return po; + } + + private static ShopOverviewStatisticsVO.ProductSummary mapToProductSummary( + CompanyOverviewVO.CategorySummary c, Long productId, Map products) { + ShopOverviewStatisticsVO.ProductSummary p = new ShopOverviewStatisticsVO.ProductSummary(); + if (c == null) { + return p; + } + p.setProductId(productId); + ProductPO product = productId != null ? products.get(productId) : null; + p.setProductName(product != null ? product.getName() : c.getCategoryName()); + p.setProductCode(product != null ? product.getProductCode() : null); + copyMetrics(p, c); + return p; + } + + private static void copyMetrics(ShopOverviewStatisticsVO.ProductSummary p, + CompanyOverviewVO.CategorySummary c) { + p.setSalesAmount(c.getSalesAmount()); + p.setOrderCount(c.getOrderCount()); + p.setAverageOrderValue(c.getAverageOrderValue()); + p.setProductCost(c.getProductCost()); + p.setShippingCost(c.getShippingCost()); + p.setOtherCost(c.getOtherCost()); + p.setOrderCost(c.getOrderCost()); + p.setRefundAmount(c.getRefundAmount()); + p.setTotalPromotionFee(c.getTotalPromotionFee()); + p.setBrushFee(c.getBrushFee()); + p.setFeeRatio(c.getFeeRatio()); + p.setTotalProfitBeforeTax(c.getTotalProfitBeforeTax()); + p.setSalesTaxAmount(c.getSalesTaxAmount()); + p.setProfitAfterTax(c.getProfitAfterTax()); + p.setRoi(c.getRoi()); + } + + private static ShopOverviewStatisticsVO.CategoryOverview mapCategoryOverview( + CompanyOverviewVO.CategoryOverview table) { + ShopOverviewStatisticsVO.CategoryOverview co = new ShopOverviewStatisticsVO.CategoryOverview(); + if (table == null) { + co.setCategories(List.of()); + return co; + } + co.setTotal(mapToCategorySummary(table.getTotal())); + if (table.getCategories() != null) { + co.setCategories(table.getCategories().stream() + .map(BiShopOverviewServiceImpl::mapToCategorySummary) + .collect(Collectors.toList())); + } else { + co.setCategories(List.of()); + } + return co; + } + + private static ShopOverviewStatisticsVO.CategorySummary mapToCategorySummary( + CompanyOverviewVO.CategorySummary c) { + ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary(); + if (c == null) { + return s; + } + s.setCategoryId(c.getCategoryId()); + s.setCategoryName(c.getCategoryName()); + s.setSalesAmount(c.getSalesAmount()); + s.setOrderCount(c.getOrderCount()); + s.setAverageOrderValue(c.getAverageOrderValue()); + s.setProductCost(c.getProductCost()); + s.setShippingCost(c.getShippingCost()); + s.setOtherCost(c.getOtherCost()); + s.setOrderCost(c.getOrderCost()); + s.setRefundAmount(c.getRefundAmount()); + s.setTotalPromotionFee(c.getTotalPromotionFee()); + s.setBrushFee(c.getBrushFee()); + s.setFeeRatio(c.getFeeRatio()); + s.setTotalProfitBeforeTax(c.getTotalProfitBeforeTax()); + s.setSalesTaxAmount(c.getSalesTaxAmount()); + s.setProfitAfterTax(c.getProfitAfterTax()); + s.setRoi(c.getRoi()); + return s; + } + + private static void fillProductSalesTop10(ShopOverviewStatisticsVO vo) { + ShopOverviewStatisticsVO.ProductOverview po = vo.getProductOverview(); + if (po == null || po.getProducts() == null || po.getProducts().isEmpty()) { + vo.setProductSalesTop10(Collections.emptyList()); + return; + } + vo.setProductSalesTop10(po.getProducts().stream() + .sorted(Comparator.comparing( + (ShopOverviewStatisticsVO.ProductSummary p) -> + p.getOrderCount() != null ? p.getOrderCount() : 0, + Comparator.reverseOrder())) + .limit(10) + .map(p -> { + ShopOverviewStatisticsVO.ProductSalesRankItem item = + new ShopOverviewStatisticsVO.ProductSalesRankItem(); + item.setProductId(p.getProductId()); + item.setProductName(p.getProductName()); + item.setProductCode(p.getProductCode()); + item.setOrderCount(p.getOrderCount()); + item.setSalesAmount(p.getSalesAmount()); + return item; + }) + .collect(Collectors.toList())); + } + + private static BigDecimal salesTax(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) { + BigDecimal base = nz(sales).subtract(nz(refund)); + 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 BigDecimal roi(BigDecimal netSales, BigDecimal promo) { + if (promo == null || promo.compareTo(BigDecimal.ZERO) <= 0) { + return BigDecimal.ZERO; + } + return nz(netSales).divide(promo, 2, RoundingMode.HALF_UP); + } + + private static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/controller/BiWorkbenchExportController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/controller/BiWorkbenchExportController.java index 517a112c..7d749959 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/controller/BiWorkbenchExportController.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/controller/BiWorkbenchExportController.java @@ -12,7 +12,7 @@ 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.modules.bi.workbench.service.BiWorkbenchExportService; -import top.xyquan.ecomdmbbackend.modules.ec.overview.util.ExportFilenameUtils; +import top.xyquan.ecomdmbbackend.modules.bi.overview.util.ExportFilenameUtils; import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchExportDTO; @Tag(name = "BI-工作台导出", description = "多维度经营明细 Excel 导出(Mongo 订单日汇聚)") diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/model/vo/WorkbenchFinanceSliceVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/model/vo/WorkbenchFinanceSliceVO.java index af9b1ba5..4c6e32d0 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/model/vo/WorkbenchFinanceSliceVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/model/vo/WorkbenchFinanceSliceVO.java @@ -5,7 +5,7 @@ import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO; /** * 工作台「经营概览」Tab 专用:KPI/趋势/饼图 + 底部四张汇总表。 diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/model/vo/WorkbenchPeriodCompareSliceVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/model/vo/WorkbenchPeriodCompareSliceVO.java index e890ccc3..0c3a9bf5 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/model/vo/WorkbenchPeriodCompareSliceVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/model/vo/WorkbenchPeriodCompareSliceVO.java @@ -5,7 +5,7 @@ import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO; import java.time.LocalDate; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/BiWorkbenchService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/BiWorkbenchService.java index 3005d5d7..f4938680 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/BiWorkbenchService.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/BiWorkbenchService.java @@ -1,6 +1,6 @@ package top.xyquan.ecomdmbbackend.modules.bi.workbench.service; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO; import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchExportDTO; import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchQueryDTO; import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinanceSliceVO; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/impl/BiWorkbenchExportServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/impl/BiWorkbenchExportServiceImpl.java index c1e971eb..47f19c05 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/impl/BiWorkbenchExportServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/service/impl/BiWorkbenchExportServiceImpl.java @@ -3,12 +3,12 @@ package top.xyquan.ecomdmbbackend.modules.bi.workbench.service.impl; import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.modules.bi.workbench.service.BiWorkbenchExportService; import top.xyquan.ecomdmbbackend.modules.bi.workbench.service.BiWorkbenchService; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.PlatformExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CategoryExportExcelService; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.ExportService; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CompanyExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.PlatformExportDTO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO; +import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CategoryExportExcelService; +import top.xyquan.ecomdmbbackend.modules.bi.overview.service.ExportService; import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchExportDTO; import java.math.BigDecimal; 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 1175c661..39977c4e 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 @@ -5,11 +5,11 @@ import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; import top.xyquan.ecomdmbbackend.modules.ec.category.model.po.CategoryPO; import top.xyquan.ecomdmbbackend.modules.ec.category.service.CategoryService; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.agg.OverviewAggRows; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows; import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver; import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CompanyOverviewService; +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.platform.model.enums.PlatformCode; import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper; import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/support/BiWorkbenchFeeLoader.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/support/BiWorkbenchFeeLoader.java index 704ba135..9d9f8159 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/support/BiWorkbenchFeeLoader.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/bi/workbench/support/BiWorkbenchFeeLoader.java @@ -5,7 +5,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; import top.xyquan.ecomdmbbackend.modules.ec.brushorder.mapper.BrushOrderMapper; import top.xyquan.ecomdmbbackend.modules.ec.brushorder.model.po.BrushOrderPO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.agg.OverviewAggRows; +import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows; import top.xyquan.ecomdmbbackend.modules.ec.promotion.mapper.PromotionFeeMapper; import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/controller/CompanyOverviewController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/controller/CompanyOverviewController.java deleted file mode 100644 index 871f62e2..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/controller/CompanyOverviewController.java +++ /dev/null @@ -1,34 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.controller; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.validation.Valid; -import org.springframework.web.bind.annotation.*; -import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission; -import top.xyquan.ecomdmbbackend.common.response.ApiResponse; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyOverviewQueryDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CompanyOverviewService; - -/** - * 全店铺概览控制器 - */ -@Tag(name = "电商-全店铺概览", description = "全店铺概览统计接口") -@RestController -@RequestMapping("/api/ec/store") -public class CompanyOverviewController { - - private final CompanyOverviewService companyOverviewService; - - public CompanyOverviewController(CompanyOverviewService companyOverviewService) { - this.companyOverviewService = companyOverviewService; - } - - @Operation(summary = "获取全店铺概览统计数据", description = "获取当前公司所有店铺的概览统计数据,包括销售额、单量、推广费、利润、ROI等") - @PostMapping("/overview") - @RequirePermission(value = "ecom:shop:read", description = "查询全店铺概览", allowSuper = true) - public ApiResponse getCompanyOverview(@Valid @RequestBody CompanyOverviewQueryDTO queryDTO) { - CompanyOverviewVO overviewVO = companyOverviewService.getCompanyOverview(queryDTO); - return ApiResponse.success("获取全店铺概览成功", overviewVO); - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/controller/ExportController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/controller/ExportController.java deleted file mode 100644 index 915822f0..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/controller/ExportController.java +++ /dev/null @@ -1,70 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.controller; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.validation.Valid; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.*; -import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.PlatformExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.ExportService; - -import jakarta.servlet.http.HttpServletResponse; -import top.xyquan.ecomdmbbackend.modules.ec.overview.util.ExportFilenameUtils; - -/** - * 全店概览导出:{@code POST /ec/store-overview/export/{by-shop|by-category|by-platform}} - */ -@Tag(name = "电商-全店概览导出", description = "全店概览:按店铺 / 按品类 / 按平台汇总 Excel 导出") -@RestController -@RequestMapping("/api/ec/store-overview/export") -public class ExportController { - - private final ExportService exportService; - - public ExportController(ExportService exportService) { - this.exportService = exportService; - } - - @Operation(summary = "全店概览-按店铺汇总", description = "导出全店按店铺维度的汇总数据为 Excel,可按店铺筛选") - @PostMapping("/by-shop") - @RequirePermission(value = "data:export", description = "导出全店概览(按店铺汇总)", allowSuper = true) - public void exportCompanyOverview(@Valid @RequestBody CompanyExportDTO dto, HttpServletResponse response) { - byte[] data = exportService.exportCompanyOverview(dto); - String filename = ExportFilenameUtils.buildFullStoreOverviewXlsxName("按店铺汇总", dto.getDateRange()); - writeExcel(response, filename, data); - } - - @Operation(summary = "全店概览-按品类汇总", description = "导出全店按品类维度的汇总数据为 Excel,支持指定品类或导出全部") - @PostMapping("/by-category") - @RequirePermission(value = "data:export", description = "导出全店概览(按品类汇总)", allowSuper = true) - public void exportCategoryOverview(@Valid @RequestBody CategoryExportDTO dto, HttpServletResponse response) { - byte[] data = exportService.exportCategoryOverview(dto); - String filename = ExportFilenameUtils.buildFullStoreOverviewXlsxName("按品类汇总", dto.getDateRange()); - writeExcel(response, filename, data); - } - - @Operation(summary = "全店概览-按平台汇总", description = "导出全店按平台维度的汇总数据为 Excel,支持指定平台或导出全部") - @PostMapping("/by-platform") - @RequirePermission(value = "data:export", description = "导出全店概览(按平台汇总)", allowSuper = true) - public void exportPlatformOverview(@Valid @RequestBody PlatformExportDTO dto, HttpServletResponse response) { - byte[] data = exportService.exportPlatformOverview(dto); - String filename = ExportFilenameUtils.buildFullStoreOverviewXlsxName("按平台汇总", dto.getDateRange()); - writeExcel(response, filename, data); - } - - private void writeExcel(HttpServletResponse response, String filename, byte[] data) { - try { - response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); - response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\""); - response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length)); - response.getOutputStream().write(data); - response.getOutputStream().flush(); - } catch (Exception e) { - throw new RuntimeException("写入Excel文件失败: " + e.getMessage()); - } - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/CompanyOverviewQueryDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/CompanyOverviewQueryDTO.java deleted file mode 100644 index 93c194f9..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/model/dto/CompanyOverviewQueryDTO.java +++ /dev/null @@ -1,35 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import jakarta.validation.constraints.NotEmpty; -import jakarta.validation.constraints.Size; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.util.List; - -/** - * 全店铺概览查询DTO - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -@Schema(description = "全店铺概览查询DTO") -public class CompanyOverviewQueryDTO { - - /** - * 日期范围数组(第一个是开始日期,第二个是结束日期,只有一个日期则返回当天数据) - */ - @Schema(description = "日期范围数组", example = "[\"2024-01-01\", \"2024-01-31\"]", requiredMode = Schema.RequiredMode.REQUIRED) - @NotEmpty(message = "日期范围不能为空") - @Size(min = 1, max = 2, message = "日期范围数组必须包含1-2个日期") - private List dateRange; - - /** - * 税率(默认4%) - */ - @Schema(description = "税率,默认为0.04(即4%)", example = "0.04") - private BigDecimal taxRate = new BigDecimal("0.04"); -} - diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/CompanyOverviewService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/CompanyOverviewService.java deleted file mode 100644 index e64e1d2b..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/CompanyOverviewService.java +++ /dev/null @@ -1,68 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.service; - -import top.xyquan.ecomdmbbackend.modules.ec.brushorder.model.po.BrushOrderPO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.agg.OverviewAggRows; -import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO; -import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyOverviewQueryDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; -import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO; -import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.util.List; - -/** - * 全店铺概览服务接口 - */ -public interface CompanyOverviewService { - - /** - * 获取全店铺概览统计数据 - * - * @param queryDTO 查询DTO - * @return 全店铺概览VO - */ - CompanyOverviewVO getCompanyOverview(CompanyOverviewQueryDTO queryDTO); - - /** - * 构建工作台底部四张汇总表:与 {@link #getCompanyOverview(CompanyOverviewQueryDTO)} 中 - * shopSummary / platformSummary / categorySummary 同源(另含按商品聚合表)。 - * 入参订单、推广费、刷单费须已按工作台筛选(店铺、日期等)准备好。 - * - * @param taxRate 请求税率(与概览接口一致) - * @param companyId 当前公司 - * @param shops 参与汇总的店铺列表(须属于该公司) - * @param orders 已筛选订单 - * @param promotionFees 已筛选推广费 - * @param brushOrders 已筛选刷单费 - * @param stat 订单状态统计集合 - * @param startDate 开始日期 - * @param endDate 结束日期 - */ - CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTables( - BigDecimal taxRate, - Long companyId, - List shops, - List orders, - List promotionFees, - List brushOrders, - OrderStatusStatSets stat, - LocalDate startDate, - LocalDate endDate); - - /** - * 基于 SQL 聚合行构建四表(与 {@link #buildWorkbenchSummaryTables} 口径一致,不拉订单明细)。 - */ - CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg( - BigDecimal taxRate, - Long companyId, - List shops, - List orderRows, - List promotionRows, - List brushRows, - LocalDate startDate, - LocalDate endDate); -} - diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/ExportService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/ExportService.java deleted file mode 100644 index 7d26af36..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/ExportService.java +++ /dev/null @@ -1,37 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.service; - -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.PlatformExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; - -/** - * 全店概览导出服务(按店铺 / 按品类 / 按平台) - */ -public interface ExportService { - - /** - * 全店概览:按店铺汇总 Excel - */ - byte[] exportCompanyOverview(CompanyExportDTO dto); - - /** - * 全店概览:按品类汇总 Excel - */ - byte[] exportCategoryOverview(CategoryExportDTO dto); - - /** - * 全店概览:按平台汇总 Excel - */ - byte[] exportPlatformOverview(PlatformExportDTO dto); - - /** - * 多维度经营明细:已按筛选口径汇总好的「按店铺」表写入 Excel(不含趋势表)。 - */ - byte[] exportShopOverviewFromTable(CompanyExportDTO dto, CompanyOverviewVO.ShopOverview shopOverview, String summaryTitle); - - /** - * 多维度经营明细:已按筛选口径汇总好的「按平台」表写入 Excel(不含趋势表)。 - */ - byte[] exportPlatformOverviewFromTable(PlatformExportDTO dto, CompanyOverviewVO.PlatformOverview platformOverview, String summaryTitle); -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/ShopOverviewStatisticsService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/ShopOverviewStatisticsService.java deleted file mode 100644 index 0d0c8fc6..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/ShopOverviewStatisticsService.java +++ /dev/null @@ -1,19 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.service; - -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopOverviewQueryDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.ShopOverviewStatisticsVO; - -/** - * 单店铺概览统计服务接口 - */ -public interface ShopOverviewStatisticsService { - - /** - * 获取单店铺概览统计数据 - * - * @param queryDTO 查询DTO - * @return 单店铺概览统计VO - */ - ShopOverviewStatisticsVO getShopOverviewStatistics(ShopOverviewQueryDTO queryDTO); -} - diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/CompanyOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/CompanyOverviewServiceImpl.java deleted file mode 100644 index 074c4263..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/CompanyOverviewServiceImpl.java +++ /dev/null @@ -1,2333 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import org.springframework.stereotype.Service; -import top.xyquan.ecomdmbbackend.common.exception.BusinessException; -import top.xyquan.ecomdmbbackend.modules.ec.brushorder.mapper.BrushOrderMapper; -import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.agg.OverviewAggRows; -import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode; -import top.xyquan.ecomdmbbackend.modules.ec.promotion.mapper.PromotionFeeMapper; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyOverviewQueryDTO; -import top.xyquan.ecomdmbbackend.modules.ec.brushorder.model.po.BrushOrderPO; -import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO; -import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper; -import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO; -import top.xyquan.ecomdmbbackend.modules.ec.order.support.OrderOverviewSupport; -import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver; -import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets; -import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO; -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; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CompanyOverviewService; -import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService; -import top.xyquan.ecomdmbbackend.modules.ec.category.model.po.CategoryPO; -import top.xyquan.ecomdmbbackend.modules.ec.category.service.CategoryService; -import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper; -import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductSkuMapper; -import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO; -import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO; -import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * 全店铺概览服务实现类 - */ -@Service -public class CompanyOverviewServiceImpl implements CompanyOverviewService { - - private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04"); - private BigDecimal taxRate = DEFAULT_TAX_RATE; - - private final CurrentUserContext currentUserContext; - private final OrderMapper orderMapper; - private final OrderItemMapper orderItemMapper; - private final PromotionFeeMapper promotionFeeMapper; - private final BrushOrderMapper brushOrderMapper; - private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; - private final ShopService shopService; - private final OrderStatusStatResolver orderStatusStatResolver; - private final ProductMapper productMapper; - private final ProductSkuMapper productSkuMapper; - private final CategoryService categoryService; - - public CompanyOverviewServiceImpl(CurrentUserContext currentUserContext, - OrderMapper orderMapper, - OrderItemMapper orderItemMapper, - PromotionFeeMapper promotionFeeMapper, - BrushOrderMapper brushOrderMapper, - ShopMonthlyTargetMapper shopMonthlyTargetMapper, - ShopService shopService, - OrderStatusStatResolver orderStatusStatResolver, - ProductMapper productMapper, - ProductSkuMapper productSkuMapper, - CategoryService categoryService) { - this.currentUserContext = currentUserContext; - this.orderMapper = orderMapper; - this.orderItemMapper = orderItemMapper; - this.promotionFeeMapper = promotionFeeMapper; - this.brushOrderMapper = brushOrderMapper; - this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; - this.shopService = shopService; - this.orderStatusStatResolver = orderStatusStatResolver; - this.productMapper = productMapper; - this.productSkuMapper = productSkuMapper; - this.categoryService = categoryService; - } - - /** - * 税额 = max(0, 销售额 − 退款) × 税率,保留两位小数。 - */ - private BigDecimal salesTaxOnNetSales(BigDecimal salesAmount, BigDecimal refundAmount) { - BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO; - BigDecimal refund = refundAmount != null ? refundAmount : BigDecimal.ZERO; - BigDecimal base = sales.subtract(refund); - if (base.compareTo(BigDecimal.ZERO) < 0) { - base = BigDecimal.ZERO; - } - BigDecimal rate = taxRate != null ? taxRate : DEFAULT_TAX_RATE; - return base.multiply(rate).setScale(2, RoundingMode.HALF_UP); - } - - private BigDecimal salesTaxOnNetSales(BigDecimal salesAmount, BigDecimal refundAmount, BigDecimal rate) { - BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO; - BigDecimal refund = refundAmount != null ? refundAmount : BigDecimal.ZERO; - BigDecimal base = sales.subtract(refund); - if (base.compareTo(BigDecimal.ZERO) < 0) { - base = BigDecimal.ZERO; - } - BigDecimal r = rate != null ? rate : DEFAULT_TAX_RATE; - return base.multiply(r).setScale(2, RoundingMode.HALF_UP); - } - - @Override - public CompanyOverviewVO getCompanyOverview(CompanyOverviewQueryDTO queryDTO) { - synchronized (this) { - // 取请求参数中的税率,默认4% - this.taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE; - - Long companyId = currentUserContext.getCurrentCompanyId(); - - // 解析日期范围 - LocalDate startDate; - LocalDate endDate; - if (queryDTO.getDateRange().size() == 1) { - // 只有一个日期,返回当天数据 - startDate = queryDTO.getDateRange().get(0); - endDate = startDate; - } else { - startDate = queryDTO.getDateRange().get(0); - endDate = queryDTO.getDateRange().get(1); - if (startDate.isAfter(endDate)) { - throw new BusinessException("开始日期不能晚于结束日期"); - } - } - - LocalDateTime startDateTime = startDate.atStartOfDay(); - LocalDateTime endDateTime = endDate.atTime(23, 59, 59); - OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); - List unionStatusCodes = stat.getUnionStatusCodes(); - - // 查询所有店铺 - LambdaQueryWrapper shopWrapper = new LambdaQueryWrapper<>(); - shopWrapper.eq(ShopPO::getCompanyId, companyId); - List shops = shopService.list(shopWrapper); - if (shops.isEmpty()) { - throw new BusinessException("当前公司没有店铺"); - } - - // 查询订单数据(所有店铺) - LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); - orderWrapper.eq(OrderPO::getCompanyId, companyId) - .ge(OrderPO::getOrderTime, startDateTime) - .le(OrderPO::getOrderTime, endDateTime); - if (!unionStatusCodes.isEmpty()) { - orderWrapper.in(OrderPO::getStatus, unionStatusCodes); - } else { - orderWrapper.isNull(OrderPO::getId); - } - List orders = orderMapper.selectList(orderWrapper); - - // 查询推广费数据(所有店铺) - LambdaQueryWrapper promotionWrapper = new LambdaQueryWrapper<>(); - promotionWrapper.eq(PromotionFeePO::getCompanyId, companyId) - .ge(PromotionFeePO::getFeeDate, startDate) - .le(PromotionFeePO::getFeeDate, endDate); - List promotionFees = promotionFeeMapper.selectList(promotionWrapper); - - // 查询刷单费数据(所有店铺) - LambdaQueryWrapper brushWrapper = new LambdaQueryWrapper<>(); - brushWrapper.eq(BrushOrderPO::getCompanyId, companyId) - .ge(BrushOrderPO::getBrushTime, startDateTime) - .le(BrushOrderPO::getBrushTime, endDateTime); - List brushOrders = brushOrderMapper.selectList(brushWrapper); - - // 计算上月同期数据(用于增长百分比) - LocalDate lastMonthStartDate = startDate.minusMonths(1); - LocalDate lastMonthEndDate = endDate.minusMonths(1); - LocalDateTime lastMonthStartDateTime = lastMonthStartDate.atStartOfDay(); - LocalDateTime lastMonthEndDateTime = lastMonthEndDate.atTime(23, 59, 59); - - LambdaQueryWrapper lastMonthOrderWrapper = new LambdaQueryWrapper<>(); - lastMonthOrderWrapper.eq(OrderPO::getCompanyId, companyId) - .ge(OrderPO::getOrderTime, lastMonthStartDateTime) - .le(OrderPO::getOrderTime, lastMonthEndDateTime); - if (!unionStatusCodes.isEmpty()) { - lastMonthOrderWrapper.in(OrderPO::getStatus, unionStatusCodes); - } else { - lastMonthOrderWrapper.isNull(OrderPO::getId); - } - List lastMonthOrders = orderMapper.selectList(lastMonthOrderWrapper); - - // 构建返回对象 - CompanyOverviewVO overviewVO = new CompanyOverviewVO(); - - // 1. 计算全店总销售额(按状态「计入销售额」维度,与单店概览一致) - BigDecimal totalSalesAmount = orders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - overviewVO.setTotalSalesAmount(totalSalesAmount); - - BigDecimal totalRefundAmountCompany = orders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 2. 计算较上月同期增长百分比 - BigDecimal lastMonthSalesAmount = lastMonthOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal monthOverMonthGrowth = BigDecimal.ZERO; - if (lastMonthSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - monthOverMonthGrowth = totalSalesAmount.subtract(lastMonthSalesAmount) - .divide(lastMonthSalesAmount, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")); - } else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - monthOverMonthGrowth = new BigDecimal("100"); // 上月为0,本月有数据,增长100% - } - overviewVO.setMonthOverMonthGrowth(monthOverMonthGrowth); - - // 3. 计算全店总单量(按状态「计入销售额」维度计单) - int totalOrderCount = (int) orders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - overviewVO.setTotalOrderCount(totalOrderCount); - - // 4. 计算总推广费支出 - BigDecimal totalPromotionFee = promotionFees.stream() - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - overviewVO.setTotalPromotionFee(totalPromotionFee); - - BigDecimal totalBrushFee = brushOrders.stream() - .map(b -> b.getBrushAmount() != null ? b.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 5. 计算平均费比 - BigDecimal averageFeeRatio = BigDecimal.ZERO; - if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - averageFeeRatio = totalPromotionFee.divide(totalSalesAmount, 4, RoundingMode.HALF_UP); - } - overviewVO.setAverageFeeRatio(averageFeeRatio); - - // 6. 计算全店总净利(税后)和总税额:税前盈亏 = 订单维度毛利 − 推广费 − 刷单费;税额按 (销售额 − 退款) × 税率 - BigDecimal totalProfitBeforeTax = calculateTotalProfit(orders, stat) - .subtract(totalPromotionFee) - .subtract(totalBrushFee); - BigDecimal totalTaxAmount = salesTaxOnNetSales(totalSalesAmount, totalRefundAmountCompany); - BigDecimal totalNetProfitAfterTax = totalProfitBeforeTax.subtract(totalTaxAmount).setScale(2, RoundingMode.HALF_UP); - overviewVO.setTotalNetProfitAfterTax(totalNetProfitAfterTax); - overviewVO.setTotalTaxAmount(totalTaxAmount); - - // 7. 计算各店铺销售占比排行 - List shopSalesRatios = calculateShopSalesRatios(shops, orders, totalSalesAmount, stat); - overviewVO.setShopSalesRatios(shopSalesRatios); - - // 8. 计算销售额与单量趋势 - CompanyOverviewVO.TrendData salesAmountTrend = calculateSalesAmountTrend(orders, startDate, endDate, stat); - CompanyOverviewVO.TrendData orderCountTrend = calculateOrderCountTrend(orders, startDate, endDate, stat); - overviewVO.setSalesAmountTrend(salesAmountTrend); - overviewVO.setOrderCountTrend(orderCountTrend); - - // 9. 计算店铺效率象限(ROI vs 净利) - List shopEfficiencyQuadrants = calculateShopEfficiencyQuadrants( - shops, orders, promotionFees, brushOrders, stat); - overviewVO.setShopEfficiencyQuadrants(shopEfficiencyQuadrants); - - // 9. 多店铺数据横向汇总 - GmvDimensionMaps gmvMaps = loadGmvDimensionMaps(companyId, shops, startDate, endDate); - CompanyOverviewVO.ShopOverview shopOverview = calculateShopSummary( - shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps); - overviewVO.setShopSummary(shopOverview); - - // 10. 多品类数据横向汇总 - CompanyOverviewVO.CategoryOverview categoryOverview = calculateCategorySummary( - orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps); - overviewVO.setCategorySummary(categoryOverview); - - // 11. 平台维度汇总 - CompanyOverviewVO.PlatformOverview platformOverview = calculatePlatformSummary( - shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps); - overviewVO.setPlatformSummary(platformOverview); - - // 12. 汇总ROI和总税后盈亏 - BigDecimal totalROI = calculateTotalROI(orders, promotionFees, brushOrders, stat); - overviewVO.setTotalROI(totalROI); - overviewVO.setTotalProfitAfterTax(totalNetProfitAfterTax); - - // 11. 计算目标维度的数据 - calculateTargetData(overviewVO, companyId, startDate, endDate, totalSalesAmount, totalOrderCount); - - return overviewVO; - } - } - - /** - * 计算目标维度的数据 - */ - private void calculateTargetData(CompanyOverviewVO overviewVO, Long companyId, LocalDate startDate, LocalDate endDate, - BigDecimal totalSalesAmount, Integer totalOrderCount) { - // 生成日期范围内所有月份的第一天列表 - List targetMonths = new ArrayList<>(); - LocalDate currentMonth = startDate.withDayOfMonth(1); - LocalDate endMonth = endDate.withDayOfMonth(1); - - while (!currentMonth.isAfter(endMonth)) { - targetMonths.add(currentMonth); - currentMonth = currentMonth.plusMonths(1); - } - - // 查询所有店铺在这些月份的目标数据 - LambdaQueryWrapper targetWrapper = new LambdaQueryWrapper<>(); - targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId) - .in(ShopMonthlyTargetPO::getTargetMonth, targetMonths); - List targets = shopMonthlyTargetMapper.selectList(targetWrapper); - - // 汇总所有店铺的目标数据(按店铺汇总,因为同一店铺可能有多个月的目标) - Map> targetsByShop = targets.stream() - .collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId)); - - // 计算总目标销售额和总目标订单数 - BigDecimal totalTargetAmount = BigDecimal.ZERO; - Integer totalTargetOrderCount = 0; - - for (List shopTargets : targetsByShop.values()) { - // 对于每个店铺,汇总其所有月份的目标 - BigDecimal shopTargetAmount = shopTargets.stream() - .map(target -> target.getTargetAmount() != null ? target.getTargetAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - Integer shopTargetOrderCount = shopTargets.stream() - .mapToInt(target -> target.getTargetOrderCount() != null ? target.getTargetOrderCount() : 0) - .sum(); - - totalTargetAmount = totalTargetAmount.add(shopTargetAmount); - totalTargetOrderCount += shopTargetOrderCount; - } - - overviewVO.setTotalTargetAmount(totalTargetAmount); - overviewVO.setTotalTargetOrderCount(totalTargetOrderCount); - - // 计算达成率 - BigDecimal salesAmountAchievementRate = BigDecimal.ZERO; - if (totalTargetAmount.compareTo(BigDecimal.ZERO) > 0) { - salesAmountAchievementRate = totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")); - } else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - // 目标为0但实际有销售额,达成率设为100% - salesAmountAchievementRate = new BigDecimal("100"); - } - overviewVO.setSalesAmountAchievementRate(salesAmountAchievementRate); - - BigDecimal orderCountAchievementRate = BigDecimal.ZERO; - if (totalTargetOrderCount > 0) { - orderCountAchievementRate = new BigDecimal(totalOrderCount) - .divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")); - } else if (totalOrderCount > 0) { - // 目标为0但实际有订单,达成率设为100% - orderCountAchievementRate = new BigDecimal("100"); - } - overviewVO.setOrderCountAchievementRate(orderCountAchievementRate); - } - - /** - * 订单维度毛利(未扣推广费/刷单费);全公司税前盈亏在入口再减总推广费与总刷单费 - */ - private BigDecimal calculateTotalProfit(List orders, OrderStatusStatSets stat) { - return orders.stream() - .map(order -> stat.receivedForSales(order).subtract(stat.totalCostForStats(order))) - .reduce(BigDecimal.ZERO, BigDecimal::add); - } - - /** - * 计算各店铺销售占比排行 - */ - private List calculateShopSalesRatios( - List shops, List orders, BigDecimal totalSalesAmount, OrderStatusStatSets stat) { - Map shopSalesMap = orders.stream() - .collect(Collectors.groupingBy( - OrderPO::getShopId, - Collectors.reducing( - BigDecimal.ZERO, - stat::receivedForSales, - BigDecimal::add))); - - List ratios = new ArrayList<>(); - for (ShopPO shop : shops) { - BigDecimal salesAmount = shopSalesMap.getOrDefault(shop.getId(), BigDecimal.ZERO); - BigDecimal ratio = BigDecimal.ZERO; - if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - ratio = salesAmount.divide(totalSalesAmount, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")); - } - - CompanyOverviewVO.ShopSalesRatio shopRatio = new CompanyOverviewVO.ShopSalesRatio(); - shopRatio.setShopId(shop.getId()); - shopRatio.setShopName(shop.getName()); - shopRatio.setSalesAmount(salesAmount); - shopRatio.setRatio(ratio); - ratios.add(shopRatio); - } - - // 按销售额降序排序 - ratios.sort(Comparator.comparing(CompanyOverviewVO.ShopSalesRatio::getSalesAmount).reversed()); - return ratios; - } - - /** - * 计算店铺效率象限(ROI vs 净利) - */ - private List calculateShopEfficiencyQuadrants( - List shops, List orders, List promotionFees, - List brushOrders, OrderStatusStatSets stat) { - List quadrants = new ArrayList<>(); - - // 按店铺分组数据 - Map> ordersByShop = orders.stream() - .collect(Collectors.groupingBy(OrderPO::getShopId)); - Map> promotionFeesByShop = promotionFees.stream() - .collect(Collectors.groupingBy(PromotionFeePO::getShopId)); - Map> brushOrdersByShop = brushOrders.stream() - .collect(Collectors.groupingBy(BrushOrderPO::getShopId)); - - // 计算所有店铺的平均ROI和平均净利(用于划分象限) - List allROIs = new ArrayList<>(); - List allNetProfits = new ArrayList<>(); - - for (ShopPO shop : shops) { - List shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopPromotionFees = promotionFeesByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopBrushOrders = brushOrdersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - - BigDecimal shopSales = shopOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal shopRefund = shopOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal shopPromotionFee = shopPromotionFees.stream() - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal shopBrushTotal = shopBrushOrders.stream() - .map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal roi = calculateSalesROI(shopSales.subtract(shopRefund), shopPromotionFee); - BigDecimal profit = calculateShopProfit(shopOrders, stat, shopPromotionFee, shopBrushTotal); - BigDecimal netProfit = calculateShopNetProfit(profit, shopSales, shopRefund); - - allROIs.add(roi); - allNetProfits.add(netProfit); - } - - BigDecimal avgROI = allROIs.isEmpty() ? BigDecimal.ZERO : - allROIs.stream().reduce(BigDecimal.ZERO, BigDecimal::add) - .divide(new BigDecimal(allROIs.size()), 4, RoundingMode.HALF_UP); - BigDecimal avgNetProfit = allNetProfits.isEmpty() ? BigDecimal.ZERO : - allNetProfits.stream().reduce(BigDecimal.ZERO, BigDecimal::add) - .divide(new BigDecimal(allNetProfits.size()), 4, RoundingMode.HALF_UP); - - // 计算每个店铺的象限 - for (ShopPO shop : shops) { - List shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopPromotionFees = promotionFeesByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopBrushOrders = brushOrdersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - - BigDecimal shopSales = shopOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal shopRefund = shopOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal shopPromotionFee = shopPromotionFees.stream() - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal shopBrushTotal = shopBrushOrders.stream() - .map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal roi = calculateSalesROI(shopSales.subtract(shopRefund), shopPromotionFee); - BigDecimal profit = calculateShopProfit(shopOrders, stat, shopPromotionFee, shopBrushTotal); - BigDecimal netProfit = calculateShopNetProfit(profit, shopSales, shopRefund); - - int quadrant; - if (roi.compareTo(avgROI) >= 0 && netProfit.compareTo(avgNetProfit) >= 0) { - quadrant = 1; // 高ROI高净利 - } else if (roi.compareTo(avgROI) >= 0 && netProfit.compareTo(avgNetProfit) < 0) { - quadrant = 2; // 高ROI低净利 - } else if (roi.compareTo(avgROI) < 0 && netProfit.compareTo(avgNetProfit) >= 0) { - quadrant = 3; // 低ROI高净利 - } else { - quadrant = 4; // 低ROI低净利 - } - - CompanyOverviewVO.ShopEfficiencyQuadrant shopQuadrant = new CompanyOverviewVO.ShopEfficiencyQuadrant(); - shopQuadrant.setShopId(shop.getId()); - shopQuadrant.setShopName(shop.getName()); - shopQuadrant.setRoi(roi); - shopQuadrant.setNetProfit(netProfit.setScale(2, RoundingMode.HALF_UP)); - shopQuadrant.setQuadrant(quadrant); - quadrants.add(shopQuadrant); - } - - return quadrants; - } - - /** - * 计算多店铺数据横向汇总 - */ - private CompanyOverviewVO.ShopOverview calculateShopSummary( - List shops, List orders, List promotionFees, - List brushOrders, OrderStatusStatSets stat, Long companyId, LocalDate startDate, - LocalDate endDate, GmvDimensionMaps gmvMaps) { - List summaries = new ArrayList<>(); - - // 按店铺分组数据 - Map> ordersByShop = orders.stream() - .collect(Collectors.groupingBy(OrderPO::getShopId)); - Map> promotionFeesByShop = promotionFees.stream() - .collect(Collectors.groupingBy(PromotionFeePO::getShopId)); - Map> brushOrdersByShop = brushOrders.stream() - .collect(Collectors.groupingBy(BrushOrderPO::getShopId)); - - // 查询所有店铺的目标数据 - List targetMonths = new ArrayList<>(); - LocalDate currentMonth = startDate.withDayOfMonth(1); - LocalDate endMonth = endDate.withDayOfMonth(1); - while (!currentMonth.isAfter(endMonth)) { - targetMonths.add(currentMonth); - currentMonth = currentMonth.plusMonths(1); - } - - LambdaQueryWrapper targetWrapper = new LambdaQueryWrapper<>(); - targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId) - .in(ShopMonthlyTargetPO::getTargetMonth, targetMonths); - List allTargets = shopMonthlyTargetMapper.selectList(targetWrapper); - - // 按店铺分组目标数据 - Map> targetsByShop = allTargets.stream() - .collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId)); - - for (ShopPO shop : shops) { - List shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopPromotionFees = promotionFeesByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopBrushOrders = brushOrdersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopTargets = targetsByShop.getOrDefault(shop.getId(), new ArrayList<>()); - - // 计算各项指标(与单店概览:按订单状态统计维度) - BigDecimal salesAmount = shopOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - int orderCount = (int) shopOrders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - - BigDecimal refundAmount = shopOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal brushFee = shopBrushOrders.stream() - .map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal totalPromotionFee = shopPromotionFees.stream() - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 计算商品成本 - BigDecimal productCost = shopOrders.stream() - .map(stat::productCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 计算运费成本 - BigDecimal shippingCost = shopOrders.stream() - .map(stat::freightCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 计算其他成本 - BigDecimal otherCost = shopOrders.stream() - .map(stat::otherCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal orderLineCost = productCost.add(shippingCost).add(otherCost); - BigDecimal profitBeforeTax = salesAmount.subtract(orderLineCost).subtract(refundAmount) - .subtract(totalPromotionFee).subtract(brushFee); - - BigDecimal salesTaxAmount = salesTaxOnNetSales(salesAmount, refundAmount); - - // 税后盈亏(扣除税额) - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount); - - BigDecimal roi = calculateSalesROI(salesAmount.subtract(refundAmount), totalPromotionFee); - - BigDecimal feeRatio = BigDecimal.ZERO; - if (salesAmount.compareTo(BigDecimal.ZERO) > 0) { - feeRatio = totalPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP); - } - - BigDecimal averageOrderValue = BigDecimal.ZERO; - if (orderCount > 0) { - averageOrderValue = salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP); - } - - // 计算目标数据 - BigDecimal targetAmount = shopTargets.stream() - .map(target -> target.getTargetAmount() != null ? target.getTargetAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - Integer targetOrderCount = shopTargets.stream() - .mapToInt(target -> target.getTargetOrderCount() != null ? target.getTargetOrderCount() : 0) - .sum(); - - // 计算达成率 - BigDecimal salesAmountAchievementRate = BigDecimal.ZERO; - if (targetAmount.compareTo(BigDecimal.ZERO) > 0) { - salesAmountAchievementRate = salesAmount.divide(targetAmount, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")); - } else if (salesAmount.compareTo(BigDecimal.ZERO) > 0) { - salesAmountAchievementRate = new BigDecimal("100"); - } - - BigDecimal orderCountAchievementRate = BigDecimal.ZERO; - if (targetOrderCount > 0) { - orderCountAchievementRate = new BigDecimal(orderCount) - .divide(new BigDecimal(targetOrderCount), 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")); - } else if (orderCount > 0) { - orderCountAchievementRate = new BigDecimal("100"); - } - - CompanyOverviewVO.ShopSummary summary = new CompanyOverviewVO.ShopSummary(); - summary.setShopId(shop.getId()); - summary.setShopName(shop.getName()); - summary.setPlatform(shop.getPlatformCode() != null ? PlatformCode.labelOf(shop.getPlatformCode()) : null); - summary.setTargetOrderCount(targetOrderCount); - summary.setOrderCountAchievementRate(orderCountAchievementRate); - summary.setTargetAmount(targetAmount); - summary.setSalesAmountAchievementRate(salesAmountAchievementRate); - summary.setSalesAmount(salesAmount); - summary.setGmv(gmvMaps.byShop().getOrDefault(shop.getId(), BigDecimal.ZERO)); - summary.setGrossProfit(salesAmount.subtract(orderLineCost).subtract(refundAmount) - .setScale(2, RoundingMode.HALF_UP)); - summary.setOrderCount(orderCount); - summary.setAverageOrderValue(averageOrderValue); - summary.setProductCost(productCost); - summary.setShippingCost(shippingCost); - summary.setOtherCost(otherCost); - summary.setOrderCost(productCost.add(shippingCost).add(otherCost)); - summary.setRefundAmount(refundAmount); - summary.setTotalPromotionFee(totalPromotionFee); - summary.setBrushFee(brushFee); - summary.setFeeRatio(feeRatio); - summary.setTotalProfitBeforeTax(profitBeforeTax); - summary.setSalesTaxAmount(salesTaxAmount); - summary.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - summary.setRoi(roi); - summaries.add(summary); - } - - // 按销售额降序排序 - summaries.sort(Comparator.comparing(CompanyOverviewVO.ShopSummary::getSalesAmount).reversed()); - - // 计算合计行 - CompanyOverviewVO.ShopSummary total = computeShopTotal(summaries); - - // 封装为 ShopOverview - CompanyOverviewVO.ShopOverview overview = new CompanyOverviewVO.ShopOverview(); - overview.setTotal(total); - overview.setShops(summaries); - return overview; - } - - /** - * 计算店铺汇总的合计行 - */ - private CompanyOverviewVO.ShopSummary computeShopTotal(List shops) { - BigDecimal totalSales = BigDecimal.ZERO; - int totalOrders = 0; - BigDecimal totalTargetAmount = BigDecimal.ZERO; - int totalTargetOrders = 0; - BigDecimal totalProductCost = BigDecimal.ZERO; - BigDecimal totalShippingCost = BigDecimal.ZERO; - BigDecimal totalOtherCost = BigDecimal.ZERO; - BigDecimal totalRefund = BigDecimal.ZERO; - BigDecimal totalPromoFee = BigDecimal.ZERO; - BigDecimal totalBrushFee = BigDecimal.ZERO; - BigDecimal totalGmv = BigDecimal.ZERO; - BigDecimal totalGrossProfit = BigDecimal.ZERO; - - for (CompanyOverviewVO.ShopSummary s : shops) { - totalSales = totalSales.add(s.getSalesAmount() != null ? s.getSalesAmount() : BigDecimal.ZERO); - totalGmv = totalGmv.add(s.getGmv() != null ? s.getGmv() : BigDecimal.ZERO); - totalGrossProfit = totalGrossProfit.add(s.getGrossProfit() != null ? s.getGrossProfit() : BigDecimal.ZERO); - totalOrders += s.getOrderCount() != null ? s.getOrderCount() : 0; - totalTargetAmount = totalTargetAmount.add(s.getTargetAmount() != null ? s.getTargetAmount() : BigDecimal.ZERO); - totalTargetOrders += s.getTargetOrderCount() != null ? s.getTargetOrderCount() : 0; - totalProductCost = totalProductCost.add(s.getProductCost() != null ? s.getProductCost() : BigDecimal.ZERO); - totalShippingCost = totalShippingCost.add(s.getShippingCost() != null ? s.getShippingCost() : BigDecimal.ZERO); - totalOtherCost = totalOtherCost.add(s.getOtherCost() != null ? s.getOtherCost() : BigDecimal.ZERO); - totalRefund = totalRefund.add(s.getRefundAmount() != null ? s.getRefundAmount() : BigDecimal.ZERO); - totalPromoFee = totalPromoFee.add(s.getTotalPromotionFee() != null ? s.getTotalPromotionFee() : BigDecimal.ZERO); - totalBrushFee = totalBrushFee.add(s.getBrushFee() != null ? s.getBrushFee() : BigDecimal.ZERO); - } - - BigDecimal avgOrderValue = totalOrders > 0 - ? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); - BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund) - .subtract(totalPromoFee).subtract(totalBrushFee); - BigDecimal salesTax = salesTaxOnNetSales(totalSales, totalRefund); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); - BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 - ? totalSales.subtract(totalRefund).divide(totalPromoFee, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 - ? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0 - ? totalSales.divide(totalTargetAmount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")) - : totalSales.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO; - BigDecimal orderAchievementRate = totalTargetOrders > 0 - ? new BigDecimal(totalOrders).divide(new BigDecimal(totalTargetOrders), 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) - : totalOrders > 0 ? new BigDecimal("100") : BigDecimal.ZERO; - - CompanyOverviewVO.ShopSummary total = new CompanyOverviewVO.ShopSummary(); - total.setShopId(0L); - total.setShopName("合计"); - total.setSalesAmount(totalSales); - total.setGmv(totalGmv); - total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP)); - total.setOrderCount(totalOrders); - total.setAverageOrderValue(avgOrderValue); - total.setTargetAmount(totalTargetAmount); - total.setTargetOrderCount(totalTargetOrders); - total.setSalesAmountAchievementRate(salesAchievementRate); - total.setOrderCountAchievementRate(orderAchievementRate); - total.setProductCost(totalProductCost); - total.setShippingCost(totalShippingCost); - total.setOtherCost(totalOtherCost); - total.setOrderCost(totalCost); - total.setRefundAmount(totalRefund); - total.setTotalPromotionFee(totalPromoFee); - total.setBrushFee(totalBrushFee); - total.setFeeRatio(feeRatio); - total.setTotalProfitBeforeTax(profitBeforeTax); - total.setSalesTaxAmount(salesTax); - total.setRoi(roi); - total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - return total; - } - - /** - * 店铺维度税前利润:订单统计口径毛利 − 推广费 − 刷单费 - */ - private BigDecimal calculateShopProfit(List orders, OrderStatusStatSets stat, - BigDecimal promotionFee, BigDecimal brushFee) { - BigDecimal salesAmount = orders.stream().map(stat::receivedForSales).reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal orderLineCost = orders.stream().map(stat::totalCostForStats).reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal refundAmount = orders.stream().map(stat::receivedForRefund).reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal p = promotionFee != null ? promotionFee : BigDecimal.ZERO; - BigDecimal b = brushFee != null ? brushFee : BigDecimal.ZERO; - return salesAmount.subtract(orderLineCost).subtract(refundAmount).subtract(p).subtract(b); - } - - /** - * 计算ROI(新公式):(销售额 - 退款金额)/ 推广费用 - */ - private BigDecimal calculateSalesROI(BigDecimal netSales, BigDecimal promotionFee) { - if (promotionFee == null || promotionFee.compareTo(BigDecimal.ZERO) <= 0) { - return BigDecimal.ZERO; - } - return netSales.divide(promotionFee, 4, RoundingMode.HALF_UP); - } - - /** - * 店铺净利(税后):税额按 (销售额 − 退款) × 税率,与单店概览一致 - */ - private BigDecimal calculateShopNetProfit(BigDecimal profitBeforeTax, BigDecimal salesAmount, BigDecimal refundAmount) { - return profitBeforeTax.subtract(salesTaxOnNetSales(salesAmount, refundAmount)); - } - - /** - * 计算汇总ROI(新公式):(销售额 - 退款金额)/ 推广费用 - */ - private BigDecimal calculateTotalROI(List orders, List promotionFees, - List brushOrders, OrderStatusStatSets stat) { - BigDecimal totalSales = orders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal totalRefund = orders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal netSales = totalSales.subtract(totalRefund); - BigDecimal totalPromotionFee = promotionFees.stream() - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - return calculateSalesROI(netSales, totalPromotionFee); - } - - /** 订单明细 product_sku_id → 商品 id */ - private Map orderSpecIdToProductIdMap(List orders) { - return OrderOverviewSupport.orderSpecIdToProductIdMap(productSkuMapper, orderItemMapper, orders); - } - - /** - * Calculate category comparison data - */ - private CompanyOverviewVO.CategoryOverview calculateCategorySummary( - List orders, List promotionFees, - List brushOrders, OrderStatusStatSets stat, Long companyId, - LocalDate startDate, LocalDate endDate, GmvDimensionMaps gmvMaps) { - - // Query all categories to build categoryId -> categoryName map - LambdaQueryWrapper categoryWrapper = new LambdaQueryWrapper<>(); - categoryWrapper.eq(CategoryPO::getCompanyId, companyId); - List allCategories = categoryService.list(categoryWrapper); - Map categoryNameMap = allCategories.stream() - .collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName)); - - Map skuIdToProductId = orderSpecIdToProductIdMap(orders); - List productIds = skuIdToProductId.values().stream().filter(Objects::nonNull).distinct() - .collect(Collectors.toList()); - - Map productCategoryMap = new java.util.HashMap<>(); - if (!productIds.isEmpty()) { - LambdaQueryWrapper productWrapper = new LambdaQueryWrapper<>(); - productWrapper.in(ProductPO::getId, productIds).select(ProductPO::getId, ProductPO::getCategoryId); - List products = productMapper.selectList(productWrapper); - for (ProductPO product : products) { - productCategoryMap.put(product.getId(), product.getCategoryId()); - } - } - - // Group orders by category - Map firstItems = OrderOverviewSupport.firstItemsForOrders(orderItemMapper, orders); - Map> ordersByCategory = orders.stream() - .collect(Collectors.groupingBy(order -> { - OrderItemPO item = firstItems.get(order.getId()); - Long skuId = item != null ? item.getProductSkuId() : null; - Long productId = skuId != null ? skuIdToProductId.get(skuId) : null; - if (productId == null) { - return -1L; - } - Long categoryId = productCategoryMap.get(productId); - return categoryId != null ? categoryId : -1L; - })); - - // 推广费:与单店品类概览一致 — 商品级直接归属、仅类目、全店比例池;刷单费仍按店铺×品类销售额占比摊 - Map directPromotionByProduct = promotionFees.stream() - .filter(fee -> fee.getProductId() != null) - .collect(Collectors.groupingBy( - PromotionFeePO::getProductId, - Collectors.reducing( - BigDecimal.ZERO, - fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); - Map directPromotionByCategory = promotionFees.stream() - .filter(fee -> fee.getProductId() == null && fee.getCategoryId() != null) - .collect(Collectors.groupingBy( - PromotionFeePO::getCategoryId, - Collectors.reducing( - BigDecimal.ZERO, - fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); - BigDecimal ratioPool = promotionFees.stream() - .filter(fee -> fee.getProductId() == null && fee.getCategoryId() == null) - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal totalCategorySalesForPool = ordersByCategory.values().stream() - .flatMap(List::stream) - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - Map shopTotalBrushFeeMap = brushOrders.stream() - .collect(Collectors.groupingBy( - BrushOrderPO::getShopId, - Collectors.reducing(BigDecimal.ZERO, - brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO, - BigDecimal::add))); - - List summaries = new ArrayList<>(); - for (Map.Entry> entry : ordersByCategory.entrySet()) { - Long categoryId = entry.getKey(); - List categoryOrders = entry.getValue(); - - BigDecimal salesAmount = categoryOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - int orderCount = (int) categoryOrders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - - BigDecimal refundAmount = categoryOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal productCost = categoryOrders.stream() - .map(stat::productCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal shippingCost = categoryOrders.stream() - .map(stat::freightCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal otherCost = categoryOrders.stream() - .map(stat::otherCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - Map categorySalesByShop = categoryOrders.stream() - .collect(Collectors.groupingBy( - OrderPO::getShopId, - Collectors.reducing(BigDecimal.ZERO, stat::receivedForSales, BigDecimal::add))); - - BigDecimal categoryTotalSales = categorySalesByShop.values().stream() - .reduce(BigDecimal.ZERO, BigDecimal::add); - - Set catProductIds = new HashSet<>(); - for (OrderPO order : categoryOrders) { - OrderItemPO item = firstItems.get(order.getId()); - Long skuId = item != null ? item.getProductSkuId() : null; - Long productId = skuId != null ? skuIdToProductId.get(skuId) : null; - if (productId != null) { - catProductIds.add(productId); - } - } - BigDecimal directCatPromotion = catProductIds.stream() - .map(pid -> directPromotionByProduct.getOrDefault(pid, BigDecimal.ZERO)) - .reduce(BigDecimal.ZERO, BigDecimal::add); - if (categoryId != null && categoryId > 0L) { - directCatPromotion = directCatPromotion.add( - directPromotionByCategory.getOrDefault(categoryId, BigDecimal.ZERO)); - } - BigDecimal totalPromotionFee = directCatPromotion; - if (ratioPool.compareTo(BigDecimal.ZERO) > 0 && totalCategorySalesForPool.compareTo(BigDecimal.ZERO) > 0) { - BigDecimal poolShareRatio = salesAmount.divide(totalCategorySalesForPool, 4, RoundingMode.HALF_UP); - totalPromotionFee = totalPromotionFee.add(ratioPool.multiply(poolShareRatio)); - } - - BigDecimal totalBrushFee = BigDecimal.ZERO; - if (categoryTotalSales.compareTo(BigDecimal.ZERO) > 0) { - for (Map.Entry shopEntry : categorySalesByShop.entrySet()) { - Long shopId = shopEntry.getKey(); - BigDecimal shopCategorySales = shopEntry.getValue(); - BigDecimal ratio = shopCategorySales.divide(categoryTotalSales, 6, RoundingMode.HALF_UP); - - BigDecimal shopBrushFee = shopTotalBrushFeeMap.getOrDefault(shopId, BigDecimal.ZERO); - totalBrushFee = totalBrushFee.add(shopBrushFee.multiply(ratio)); - } - } - - BigDecimal totalCost = productCost.add(shippingCost).add(otherCost); - BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount) - .subtract(totalPromotionFee).subtract(totalBrushFee); - BigDecimal salesTaxAmount = salesTaxOnNetSales(salesAmount, refundAmount); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount); - - BigDecimal roi = BigDecimal.ZERO; - if (totalPromotionFee.compareTo(BigDecimal.ZERO) > 0) { - roi = salesAmount.subtract(refundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP); - } - - BigDecimal feeRatio = BigDecimal.ZERO; - if (salesAmount.compareTo(BigDecimal.ZERO) > 0) { - feeRatio = totalPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP); - } - - BigDecimal averageOrderValue = BigDecimal.ZERO; - if (orderCount > 0) { - averageOrderValue = salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP); - } - - String categoryName = categoryId == -1L ? "其他品类" : categoryNameMap.getOrDefault(categoryId, "Unknown"); - - CompanyOverviewVO.CategorySummary summary = new CompanyOverviewVO.CategorySummary(); - summary.setCategoryId(categoryId == -1L ? null : categoryId); - summary.setCategoryName(categoryName); - summary.setSalesAmount(salesAmount); - summary.setGmv(gmvMaps.byCategoryKey().getOrDefault(categoryId, BigDecimal.ZERO)); - summary.setGrossProfit(salesAmount.subtract(totalCost).subtract(refundAmount) - .setScale(2, RoundingMode.HALF_UP)); - summary.setOrderCount(orderCount); - summary.setAverageOrderValue(averageOrderValue); - summary.setProductCost(productCost); - summary.setShippingCost(shippingCost); - summary.setOtherCost(otherCost); - summary.setOrderCost(totalCost); - summary.setRefundAmount(refundAmount); - summary.setTotalPromotionFee(totalPromotionFee); - summary.setBrushFee(totalBrushFee); - summary.setFeeRatio(feeRatio); - summary.setTotalProfitBeforeTax(profitBeforeTax); - summary.setSalesTaxAmount(salesTaxAmount); - summary.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - summary.setRoi(roi); - summaries.add(summary); - } - - summaries.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount).reversed()); - - // 计算合计行 - CompanyOverviewVO.CategorySummary total = computeCategoryTotal(summaries); - - // 封装为 CategoryOverview - CompanyOverviewVO.CategoryOverview overview = new CompanyOverviewVO.CategoryOverview(); - overview.setTotal(total); - overview.setCategories(summaries); - return overview; - } - - /** - * 计算品类汇总的合计行 - */ - private CompanyOverviewVO.CategorySummary computeCategoryTotal(List categories) { - BigDecimal totalSales = BigDecimal.ZERO; - int totalOrders = 0; - BigDecimal totalProductCost = BigDecimal.ZERO; - BigDecimal totalShippingCost = BigDecimal.ZERO; - BigDecimal totalOtherCost = BigDecimal.ZERO; - BigDecimal totalRefund = BigDecimal.ZERO; - BigDecimal totalPromoFee = BigDecimal.ZERO; - BigDecimal totalBrushFee = BigDecimal.ZERO; - BigDecimal totalGmv = BigDecimal.ZERO; - BigDecimal totalGrossProfit = BigDecimal.ZERO; - - for (CompanyOverviewVO.CategorySummary c : categories) { - totalSales = totalSales.add(c.getSalesAmount() != null ? c.getSalesAmount() : BigDecimal.ZERO); - totalGmv = totalGmv.add(c.getGmv() != null ? c.getGmv() : BigDecimal.ZERO); - totalGrossProfit = totalGrossProfit.add(c.getGrossProfit() != null ? c.getGrossProfit() : BigDecimal.ZERO); - totalOrders += c.getOrderCount() != null ? c.getOrderCount() : 0; - totalProductCost = totalProductCost.add(c.getProductCost() != null ? c.getProductCost() : BigDecimal.ZERO); - totalShippingCost = totalShippingCost.add(c.getShippingCost() != null ? c.getShippingCost() : BigDecimal.ZERO); - totalOtherCost = totalOtherCost.add(c.getOtherCost() != null ? c.getOtherCost() : BigDecimal.ZERO); - totalRefund = totalRefund.add(c.getRefundAmount() != null ? c.getRefundAmount() : BigDecimal.ZERO); - totalPromoFee = totalPromoFee.add(c.getTotalPromotionFee() != null ? c.getTotalPromotionFee() : BigDecimal.ZERO); - totalBrushFee = totalBrushFee.add(c.getBrushFee() != null ? c.getBrushFee() : BigDecimal.ZERO); - } - - BigDecimal avgOrderValue = totalOrders > 0 - ? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); - BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund) - .subtract(totalPromoFee).subtract(totalBrushFee); - BigDecimal salesTax = salesTaxOnNetSales(totalSales, totalRefund); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); - BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 - ? totalSales.subtract(totalRefund).divide(totalPromoFee, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 - ? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - - CompanyOverviewVO.CategorySummary total = new CompanyOverviewVO.CategorySummary(); - total.setCategoryId(0L); - total.setCategoryName("合计"); - total.setSalesAmount(totalSales); - total.setGmv(totalGmv); - total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP)); - total.setOrderCount(totalOrders); - total.setAverageOrderValue(avgOrderValue); - total.setProductCost(totalProductCost); - total.setShippingCost(totalShippingCost); - total.setOtherCost(totalOtherCost); - total.setOrderCost(totalCost); - total.setRefundAmount(totalRefund); - total.setTotalPromotionFee(totalPromoFee); - total.setBrushFee(totalBrushFee); - total.setFeeRatio(feeRatio); - total.setTotalProfitBeforeTax(profitBeforeTax); - total.setSalesTaxAmount(salesTax); - total.setRoi(roi); - total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - return total; - } - - /** - * 计算平台维度汇总 - */ - private CompanyOverviewVO.PlatformOverview calculatePlatformSummary( - List shops, List orders, List promotionFees, - List brushOrders, OrderStatusStatSets stat, Long companyId, - LocalDate startDate, LocalDate endDate, GmvDimensionMaps gmvMaps) { - - List platformSummaries = new ArrayList<>(); - - // 按平台代码分组店铺 - Map> shopsByPlatform = shops.stream() - .filter(shop -> shop.getPlatformCode() != null && !shop.getPlatformCode().isBlank()) - .collect(Collectors.groupingBy(ShopPO::getPlatformCode)); - - // 没有 platformCode 的店铺,汇总为"其他平台" - List shopsWithoutPlatform = shops.stream() - .filter(shop -> shop.getPlatformCode() == null || shop.getPlatformCode().isBlank()) - .collect(Collectors.toList()); - - // 生成目标月份列表 - List targetMonths = new ArrayList<>(); - LocalDate currentMonth = startDate.withDayOfMonth(1); - LocalDate endMonth = endDate.withDayOfMonth(1); - while (!currentMonth.isAfter(endMonth)) { - targetMonths.add(currentMonth); - currentMonth = currentMonth.plusMonths(1); - } - - // 查询所有店铺的目标数据 - LambdaQueryWrapper targetWrapper = new LambdaQueryWrapper<>(); - targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId) - .in(ShopMonthlyTargetPO::getTargetMonth, targetMonths); - List allTargets = shopMonthlyTargetMapper.selectList(targetWrapper); - Map> targetsByShop = allTargets.stream() - .collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId)); - - // 按店铺分组订单和费用 - Map> ordersByShop = orders.stream() - .collect(Collectors.groupingBy(OrderPO::getShopId)); - Map> promotionFeesByShop = promotionFees.stream() - .collect(Collectors.groupingBy(PromotionFeePO::getShopId)); - Map> brushOrdersByShop = brushOrders.stream() - .collect(Collectors.groupingBy(BrushOrderPO::getShopId)); - - // 计算每个平台的数据 - for (Map.Entry> entry : shopsByPlatform.entrySet()) { - String platformCode = entry.getKey(); - List platformShops = entry.getValue(); - - // 汇总该平台下所有店铺的数据 - BigDecimal totalSalesAmount = BigDecimal.ZERO; - int totalOrderCount = 0; - BigDecimal totalRefundAmount = BigDecimal.ZERO; - BigDecimal totalProductCost = BigDecimal.ZERO; - BigDecimal totalShippingCost = BigDecimal.ZERO; - BigDecimal totalOtherCost = BigDecimal.ZERO; - BigDecimal totalPromotionFee = BigDecimal.ZERO; - BigDecimal totalBrushFee = BigDecimal.ZERO; - BigDecimal totalTargetAmount = BigDecimal.ZERO; - int totalTargetOrderCount = 0; - BigDecimal totalGmv = BigDecimal.ZERO; - - for (ShopPO shop : platformShops) { - List shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopPromotionFees = promotionFeesByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopBrushOrders = brushOrdersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopTargets = targetsByShop.getOrDefault(shop.getId(), new ArrayList<>()); - - // 销售额(按状态「计入销售额」) - BigDecimal shopSales = shopOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalSalesAmount = totalSalesAmount.add(shopSales); - - // 订单数(按状态「计入销售额」计单) - totalOrderCount += (int) shopOrders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - - // 退款金额(按状态「计入退款」) - BigDecimal shopRefund = shopOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalRefundAmount = totalRefundAmount.add(shopRefund); - - // 商品成本 - BigDecimal shopProductCost = shopOrders.stream() - .map(stat::productCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalProductCost = totalProductCost.add(shopProductCost); - - // 运费成本 - BigDecimal shopShippingCost = shopOrders.stream() - .map(stat::freightCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalShippingCost = totalShippingCost.add(shopShippingCost); - - // 其他成本 - BigDecimal shopOtherCost = shopOrders.stream() - .map(stat::otherCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalOtherCost = totalOtherCost.add(shopOtherCost); - - // 推广费 - BigDecimal shopPromoFee = shopPromotionFees.stream() - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalPromotionFee = totalPromotionFee.add(shopPromoFee); - - // 刷单费 - BigDecimal shopBrush = shopBrushOrders.stream() - .map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalBrushFee = totalBrushFee.add(shopBrush); - - totalGmv = totalGmv.add(gmvMaps.byShop().getOrDefault(shop.getId(), BigDecimal.ZERO)); - - // 目标金额和目标单量 - BigDecimal shopTargetAmount = shopTargets.stream() - .map(target -> target.getTargetAmount() != null ? target.getTargetAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalTargetAmount = totalTargetAmount.add(shopTargetAmount); - - int shopTargetOrderCount = shopTargets.stream() - .mapToInt(target -> target.getTargetOrderCount() != null ? target.getTargetOrderCount() : 0) - .sum(); - totalTargetOrderCount += shopTargetOrderCount; - } - - // 计算派生指标 - BigDecimal averageOrderValue = BigDecimal.ZERO; - if (totalOrderCount > 0) { - averageOrderValue = totalSalesAmount.divide(new BigDecimal(totalOrderCount), 2, RoundingMode.HALF_UP); - } - - BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); - BigDecimal profitBeforeTax = totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount) - .subtract(totalPromotionFee).subtract(totalBrushFee); - BigDecimal salesTaxAmount = salesTaxOnNetSales(totalSalesAmount, totalRefundAmount); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount); - - BigDecimal roi = BigDecimal.ZERO; - if (totalPromotionFee.compareTo(BigDecimal.ZERO) > 0) { - roi = totalSalesAmount.subtract(totalRefundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP); - } - - BigDecimal feeRatio = BigDecimal.ZERO; - if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - feeRatio = totalPromotionFee.add(totalBrushFee).divide(totalSalesAmount, 4, RoundingMode.HALF_UP); - } - - // 计算达成率 - BigDecimal salesAmountAchievementRate = BigDecimal.ZERO; - if (totalTargetAmount.compareTo(BigDecimal.ZERO) > 0) { - salesAmountAchievementRate = totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")); - } else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - salesAmountAchievementRate = new BigDecimal("100"); - } - - BigDecimal orderCountAchievementRate = BigDecimal.ZERO; - if (totalTargetOrderCount > 0) { - orderCountAchievementRate = new BigDecimal(totalOrderCount) - .divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")); - } else if (totalOrderCount > 0) { - orderCountAchievementRate = new BigDecimal("100"); - } - - CompanyOverviewVO.PlatformSummary platformSummary = new CompanyOverviewVO.PlatformSummary(); - platformSummary.setPlatformCode(platformCode); - platformSummary.setPlatformName(PlatformCode.labelOf(platformCode)); - platformSummary.setTargetOrderCount(totalTargetOrderCount); - platformSummary.setOrderCountAchievementRate(orderCountAchievementRate); - platformSummary.setTargetAmount(totalTargetAmount); - platformSummary.setSalesAmountAchievementRate(salesAmountAchievementRate); - platformSummary.setSalesAmount(totalSalesAmount); - platformSummary.setGmv(totalGmv); - platformSummary.setGrossProfit(totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount) - .setScale(2, RoundingMode.HALF_UP)); - platformSummary.setOrderCount(totalOrderCount); - platformSummary.setAverageOrderValue(averageOrderValue); - platformSummary.setProductCost(totalProductCost); - platformSummary.setShippingCost(totalShippingCost); - platformSummary.setOtherCost(totalOtherCost); - platformSummary.setOrderCost(totalCost); - platformSummary.setRefundAmount(totalRefundAmount); - platformSummary.setTotalPromotionFee(totalPromotionFee); - platformSummary.setBrushFee(totalBrushFee); - platformSummary.setFeeRatio(feeRatio); - platformSummary.setTotalProfitBeforeTax(profitBeforeTax); - platformSummary.setSalesTaxAmount(salesTaxAmount); - platformSummary.setRoi(roi); - platformSummary.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - - platformSummaries.add(platformSummary); - } - - // 处理没有平台的店铺,汇总为"其他平台" - if (!shopsWithoutPlatform.isEmpty()) { - CompanyOverviewVO.PlatformSummary otherSummary = calculateOtherPlatformSummary( - shopsWithoutPlatform, ordersByShop, promotionFeesByShop, brushOrdersByShop, - targetsByShop, stat, taxRate, gmvMaps); - if (otherSummary.getOrderCount() > 0) { - platformSummaries.add(otherSummary); - } - } - - // 按销售额降序排序 - platformSummaries.sort(Comparator.comparing(CompanyOverviewVO.PlatformSummary::getSalesAmount).reversed()); - - // 计算合计行 - CompanyOverviewVO.PlatformSummary total = computePlatformTotal(platformSummaries); - - // 封装为 PlatformOverview - CompanyOverviewVO.PlatformOverview overview = new CompanyOverviewVO.PlatformOverview(); - overview.setTotal(total); - overview.setPlatforms(platformSummaries); - return overview; - } - - /** - * 计算平台汇总的合计行 - */ - private CompanyOverviewVO.PlatformSummary computePlatformTotal(List platforms) { - BigDecimal totalSalesAmount = BigDecimal.ZERO; - int totalOrderCount = 0; - BigDecimal totalTargetAmount = BigDecimal.ZERO; - int totalTargetOrderCount = 0; - BigDecimal totalProductCost = BigDecimal.ZERO; - BigDecimal totalShippingCost = BigDecimal.ZERO; - BigDecimal totalOtherCost = BigDecimal.ZERO; - BigDecimal totalRefundAmount = BigDecimal.ZERO; - BigDecimal totalPromotionFee = BigDecimal.ZERO; - BigDecimal totalBrushFee = BigDecimal.ZERO; - BigDecimal totalGmv = BigDecimal.ZERO; - BigDecimal totalGrossProfit = BigDecimal.ZERO; - - for (CompanyOverviewVO.PlatformSummary p : platforms) { - totalSalesAmount = totalSalesAmount.add(p.getSalesAmount() != null ? p.getSalesAmount() : BigDecimal.ZERO); - totalGmv = totalGmv.add(p.getGmv() != null ? p.getGmv() : BigDecimal.ZERO); - totalGrossProfit = totalGrossProfit.add(p.getGrossProfit() != null ? p.getGrossProfit() : BigDecimal.ZERO); - totalOrderCount += p.getOrderCount() != null ? p.getOrderCount() : 0; - totalTargetAmount = totalTargetAmount.add(p.getTargetAmount() != null ? p.getTargetAmount() : BigDecimal.ZERO); - totalTargetOrderCount += p.getTargetOrderCount() != null ? p.getTargetOrderCount() : 0; - totalProductCost = totalProductCost.add(p.getProductCost() != null ? p.getProductCost() : BigDecimal.ZERO); - totalShippingCost = totalShippingCost.add(p.getShippingCost() != null ? p.getShippingCost() : BigDecimal.ZERO); - totalOtherCost = totalOtherCost.add(p.getOtherCost() != null ? p.getOtherCost() : BigDecimal.ZERO); - totalRefundAmount = totalRefundAmount.add(p.getRefundAmount() != null ? p.getRefundAmount() : BigDecimal.ZERO); - totalPromotionFee = totalPromotionFee.add(p.getTotalPromotionFee() != null ? p.getTotalPromotionFee() : BigDecimal.ZERO); - totalBrushFee = totalBrushFee.add(p.getBrushFee() != null ? p.getBrushFee() : BigDecimal.ZERO); - } - - BigDecimal avgOrderValue = totalOrderCount > 0 - ? totalSalesAmount.divide(new BigDecimal(totalOrderCount), 2, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); - BigDecimal profitBeforeTax = totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount) - .subtract(totalPromotionFee).subtract(totalBrushFee); - BigDecimal salesTax = salesTaxOnNetSales(totalSalesAmount, totalRefundAmount); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); - BigDecimal roi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0 - ? totalSalesAmount.subtract(totalRefundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal feeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0 - ? totalPromotionFee.add(totalBrushFee).divide(totalSalesAmount, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0 - ? totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")) - : totalSalesAmount.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO; - BigDecimal orderAchievementRate = totalTargetOrderCount > 0 - ? new BigDecimal(totalOrderCount).divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) - : totalOrderCount > 0 ? new BigDecimal("100") : BigDecimal.ZERO; - - CompanyOverviewVO.PlatformSummary total = new CompanyOverviewVO.PlatformSummary(); - total.setPlatformCode(null); - total.setPlatformName("合计"); - total.setSalesAmount(totalSalesAmount); - total.setGmv(totalGmv); - total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP)); - total.setOrderCount(totalOrderCount); - total.setAverageOrderValue(avgOrderValue); - total.setTargetAmount(totalTargetAmount); - total.setTargetOrderCount(totalTargetOrderCount); - total.setSalesAmountAchievementRate(salesAchievementRate); - total.setOrderCountAchievementRate(orderAchievementRate); - total.setProductCost(totalProductCost); - total.setShippingCost(totalShippingCost); - total.setOtherCost(totalOtherCost); - total.setOrderCost(totalCost); - total.setRefundAmount(totalRefundAmount); - total.setTotalPromotionFee(totalPromotionFee); - total.setBrushFee(totalBrushFee); - total.setFeeRatio(feeRatio); - total.setTotalProfitBeforeTax(profitBeforeTax); - total.setSalesTaxAmount(salesTax); - total.setRoi(roi); - total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - return total; - } - - /** - * 计算"其他平台"汇总(没有绑定平台的店铺) - */ - private CompanyOverviewVO.PlatformSummary calculateOtherPlatformSummary( - List shops, - Map> ordersByShop, - Map> promotionFeesByShop, - Map> brushOrdersByShop, - Map> targetsByShop, - OrderStatusStatSets stat, - BigDecimal taxRate, - GmvDimensionMaps gmvMaps) { - - BigDecimal totalSalesAmount = BigDecimal.ZERO; - int totalOrderCount = 0; - BigDecimal totalRefundAmount = BigDecimal.ZERO; - BigDecimal totalProductCost = BigDecimal.ZERO; - BigDecimal totalShippingCost = BigDecimal.ZERO; - BigDecimal totalOtherCost = BigDecimal.ZERO; - BigDecimal totalPromotionFee = BigDecimal.ZERO; - BigDecimal totalBrushFee = BigDecimal.ZERO; - BigDecimal totalTargetAmount = BigDecimal.ZERO; - int totalTargetOrderCount = 0; - BigDecimal totalGmv = BigDecimal.ZERO; - - for (ShopPO shop : shops) { - List shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopPromotionFees = promotionFeesByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopBrushOrders = brushOrdersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopTargets = targetsByShop.getOrDefault(shop.getId(), new ArrayList<>()); - - BigDecimal shopSales = shopOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalSalesAmount = totalSalesAmount.add(shopSales); - totalOrderCount += (int) shopOrders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - - BigDecimal shopRefund = shopOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalRefundAmount = totalRefundAmount.add(shopRefund); - - BigDecimal shopProductCost = shopOrders.stream() - .map(stat::productCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalProductCost = totalProductCost.add(shopProductCost); - - BigDecimal shopShippingCost = shopOrders.stream() - .map(stat::freightCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalShippingCost = totalShippingCost.add(shopShippingCost); - - BigDecimal shopOtherCost = shopOrders.stream() - .map(stat::otherCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalOtherCost = totalOtherCost.add(shopOtherCost); - - BigDecimal shopPromoFee = shopPromotionFees.stream() - .map(f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalPromotionFee = totalPromotionFee.add(shopPromoFee); - - BigDecimal shopBrush = shopBrushOrders.stream() - .map(b -> b.getBrushAmount() != null ? b.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalBrushFee = totalBrushFee.add(shopBrush); - - BigDecimal shopTargetAmount = shopTargets.stream() - .map(t -> t.getTargetAmount() != null ? t.getTargetAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalTargetAmount = totalTargetAmount.add(shopTargetAmount); - - int shopTargetOrderCount = shopTargets.stream() - .mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0) - .sum(); - totalTargetOrderCount += shopTargetOrderCount; - totalGmv = totalGmv.add(gmvMaps.byShop().getOrDefault(shop.getId(), BigDecimal.ZERO)); - } - - BigDecimal averageOrderValue = totalOrderCount > 0 - ? totalSalesAmount.divide(new BigDecimal(totalOrderCount), 2, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); - BigDecimal profitBeforeTax = totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount) - .subtract(totalPromotionFee).subtract(totalBrushFee); - BigDecimal salesTaxAmount = salesTaxOnNetSales(totalSalesAmount, totalRefundAmount, taxRate); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount); - BigDecimal roi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0 - ? totalSalesAmount.subtract(totalRefundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal feeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0 - ? totalPromotionFee.add(totalBrushFee).divide(totalSalesAmount, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0 - ? totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")) - : totalSalesAmount.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO; - BigDecimal orderAchievementRate = totalTargetOrderCount > 0 - ? new BigDecimal(totalOrderCount).divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) - : totalOrderCount > 0 ? new BigDecimal("100") : BigDecimal.ZERO; - - CompanyOverviewVO.PlatformSummary summary = new CompanyOverviewVO.PlatformSummary(); - summary.setPlatformCode(null); - summary.setPlatformName("其他平台"); - summary.setTargetOrderCount(totalTargetOrderCount); - summary.setOrderCountAchievementRate(orderAchievementRate); - summary.setTargetAmount(totalTargetAmount); - summary.setSalesAmountAchievementRate(salesAchievementRate); - summary.setSalesAmount(totalSalesAmount); - summary.setGmv(totalGmv); - summary.setGrossProfit(totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount) - .setScale(2, RoundingMode.HALF_UP)); - summary.setOrderCount(totalOrderCount); - summary.setAverageOrderValue(averageOrderValue); - summary.setProductCost(totalProductCost); - summary.setShippingCost(totalShippingCost); - summary.setOtherCost(totalOtherCost); - summary.setOrderCost(totalCost); - summary.setRefundAmount(totalRefundAmount); - summary.setTotalPromotionFee(totalPromotionFee); - summary.setBrushFee(totalBrushFee); - summary.setFeeRatio(feeRatio); - summary.setTotalProfitBeforeTax(profitBeforeTax); - summary.setSalesTaxAmount(salesTaxAmount); - summary.setRoi(roi); - summary.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - - return summary; - } - - private CompanyOverviewVO.TrendData calculateSalesAmountTrend(List orders, LocalDate startDate, - LocalDate endDate, OrderStatusStatSets stat) { - CompanyOverviewVO.TrendData trendData = new CompanyOverviewVO.TrendData(); - Map> ordersByDate = orders.stream() - .collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate())); - BigDecimal total = orders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - trendData.setTotal(total); - List dateList = new ArrayList<>(); - LocalDate currentDate = startDate; - while (!currentDate.isAfter(endDate)) { - dateList.add(currentDate); - currentDate = currentDate.plusDays(1); - } - List dailyDataList = dateList.stream() - .map(date -> { - CompanyOverviewVO.TrendDataItem item = new CompanyOverviewVO.TrendDataItem(); - item.setDate(date); - List dayOrders = ordersByDate.getOrDefault(date, List.of()); - BigDecimal dayTotal = dayOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - item.setValue(dayTotal); - return item; - }) - .sorted(Comparator.comparing(CompanyOverviewVO.TrendDataItem::getDate)) - .collect(Collectors.toList()); - trendData.setDailyDataList(dailyDataList); - return trendData; - } - - private CompanyOverviewVO.TrendData calculateOrderCountTrend(List orders, LocalDate startDate, - LocalDate endDate, OrderStatusStatSets stat) { - CompanyOverviewVO.TrendData trendData = new CompanyOverviewVO.TrendData(); - Map> ordersByDate = orders.stream() - .collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate())); - int total = (int) orders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - trendData.setTotal(new BigDecimal(total)); - List dateList = new ArrayList<>(); - LocalDate currentDate = startDate; - while (!currentDate.isAfter(endDate)) { - dateList.add(currentDate); - currentDate = currentDate.plusDays(1); - } - List dailyDataList = dateList.stream() - .map(date -> { - CompanyOverviewVO.TrendDataItem item = new CompanyOverviewVO.TrendDataItem(); - item.setDate(date); - List dayOrders = ordersByDate.getOrDefault(date, List.of()); - int dayCount = (int) dayOrders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - item.setValue(new BigDecimal(dayCount)); - return item; - }) - .sorted(Comparator.comparing(CompanyOverviewVO.TrendDataItem::getDate)) - .collect(Collectors.toList()); - trendData.setDailyDataList(dailyDataList); - return trendData; - } - - @Override - public CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTables( - BigDecimal taxRate, - Long companyId, - List shops, - List orders, - List promotionFees, - List brushOrders, - OrderStatusStatSets stat, - LocalDate startDate, - LocalDate endDate) { - synchronized (this) { - BigDecimal saved = this.taxRate; - try { - this.taxRate = taxRate != null ? taxRate : DEFAULT_TAX_RATE; - GmvDimensionMaps gmvMaps = loadGmvDimensionMaps(companyId, shops, startDate, endDate); - CompanyOverviewVO.WorkbenchTableBundle bundle = new CompanyOverviewVO.WorkbenchTableBundle(); - bundle.setShopTable(calculateShopSummary(shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps)); - bundle.setPlatformTable(calculatePlatformSummary(shops, orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps)); - bundle.setCategoryTable(calculateCategorySummary(orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps)); - bundle.setProductTable(calculateProductSummaryAsCategory(orders, promotionFees, brushOrders, stat, companyId, startDate, endDate, gmvMaps)); - return bundle; - } finally { - this.taxRate = saved; - } - } - } - - /** - * 商品维度横向汇总(与 {@link #calculateCategorySummary} 同款推广/刷单/税额逻辑; - * 行使用 {@link CompanyOverviewVO.CategorySummary},categoryId 存商品 ID)。 - */ - private CompanyOverviewVO.CategoryOverview calculateProductSummaryAsCategory( - List orders, List promotionFees, - List brushOrders, OrderStatusStatSets stat, Long companyId, - LocalDate startDate, LocalDate endDate, GmvDimensionMaps gmvMaps) { - - Map skuIdToProductId = orderSpecIdToProductIdMap(orders); - List productIds = skuIdToProductId.values().stream().filter(Objects::nonNull).distinct() - .collect(Collectors.toList()); - - Map productCategoryMap = new java.util.HashMap<>(); - Map productNameMap = new java.util.HashMap<>(); - if (!productIds.isEmpty()) { - LambdaQueryWrapper productWrapper = new LambdaQueryWrapper<>(); - productWrapper.in(ProductPO::getId, productIds).select(ProductPO::getId, ProductPO::getCategoryId, ProductPO::getName); - List products = productMapper.selectList(productWrapper); - for (ProductPO product : products) { - productCategoryMap.put(product.getId(), product.getCategoryId()); - productNameMap.put(product.getId(), product.getName()); - } - } - - Map firstItems = OrderOverviewSupport.firstItemsForOrders(orderItemMapper, orders); - Map> ordersByProduct = orders.stream() - .collect(Collectors.groupingBy(order -> { - OrderItemPO item = firstItems.get(order.getId()); - Long skuId = item != null ? item.getProductSkuId() : null; - Long productId = skuId != null ? skuIdToProductId.get(skuId) : null; - return productId != null ? productId : -1L; - })); - - Map directPromotionByProduct = promotionFees.stream() - .filter(fee -> fee.getProductId() != null) - .collect(Collectors.groupingBy( - PromotionFeePO::getProductId, - Collectors.reducing( - BigDecimal.ZERO, - fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); - Map directPromotionByCategory = promotionFees.stream() - .filter(fee -> fee.getProductId() == null && fee.getCategoryId() != null) - .collect(Collectors.groupingBy( - PromotionFeePO::getCategoryId, - Collectors.reducing( - BigDecimal.ZERO, - fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); - BigDecimal ratioPool = promotionFees.stream() - .filter(fee -> fee.getProductId() == null && fee.getCategoryId() == null) - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal totalSalesForRatioPool = orders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - Map salesByCategory = new java.util.HashMap<>(); - for (OrderPO o : orders) { - OrderItemPO item = firstItems.get(o.getId()); - Long skuId = item != null ? item.getProductSkuId() : null; - Long pid = skuId != null ? skuIdToProductId.get(skuId) : null; - if (pid == null) { - continue; - } - Long cid = productCategoryMap.get(pid); - if (cid == null) { - continue; - } - salesByCategory.merge(cid, stat.receivedForSales(o), BigDecimal::add); - } - - Map shopTotalBrushFeeMap = brushOrders.stream() - .collect(Collectors.groupingBy( - BrushOrderPO::getShopId, - Collectors.reducing(BigDecimal.ZERO, - brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO, - BigDecimal::add))); - - List summaries = new ArrayList<>(); - for (Map.Entry> entry : ordersByProduct.entrySet()) { - Long productId = entry.getKey(); - List productOrders = entry.getValue(); - - BigDecimal salesAmount = productOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - int orderCount = (int) productOrders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - BigDecimal refundAmount = productOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal productCost = productOrders.stream() - .map(stat::productCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal shippingCost = productOrders.stream() - .map(stat::freightCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal otherCost = productOrders.stream() - .map(stat::otherCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - Map productSalesByShop = productOrders.stream() - .collect(Collectors.groupingBy( - OrderPO::getShopId, - Collectors.reducing(BigDecimal.ZERO, stat::receivedForSales, BigDecimal::add))); - BigDecimal productTotalSales = productSalesByShop.values().stream() - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal directP = BigDecimal.ZERO; - if (productId > 0) { - directP = directPromotionByProduct.getOrDefault(productId, BigDecimal.ZERO); - } - - BigDecimal fromCategoryPool = BigDecimal.ZERO; - if (productId > 0) { - Long cid = productCategoryMap.get(productId); - if (cid != null && cid > 0) { - BigDecimal pool = directPromotionByCategory.getOrDefault(cid, BigDecimal.ZERO); - BigDecimal catSales = salesByCategory.getOrDefault(cid, BigDecimal.ZERO); - if (catSales.compareTo(BigDecimal.ZERO) > 0) { - fromCategoryPool = pool.multiply(salesAmount).divide(catSales, 4, RoundingMode.HALF_UP); - } - } - } - - BigDecimal totalPromotionFee = directP.add(fromCategoryPool); - if (ratioPool.compareTo(BigDecimal.ZERO) > 0 && totalSalesForRatioPool.compareTo(BigDecimal.ZERO) > 0) { - totalPromotionFee = totalPromotionFee.add( - ratioPool.multiply(salesAmount).divide(totalSalesForRatioPool, 4, RoundingMode.HALF_UP)); - } - - BigDecimal totalBrushFee = BigDecimal.ZERO; - if (productTotalSales.compareTo(BigDecimal.ZERO) > 0) { - for (Map.Entry shopEntry : productSalesByShop.entrySet()) { - Long shopId = shopEntry.getKey(); - BigDecimal shopProductSales = shopEntry.getValue(); - BigDecimal ratio = shopProductSales.divide(productTotalSales, 6, RoundingMode.HALF_UP); - BigDecimal shopBrushFee = shopTotalBrushFeeMap.getOrDefault(shopId, BigDecimal.ZERO); - totalBrushFee = totalBrushFee.add(shopBrushFee.multiply(ratio)); - } - } - - BigDecimal totalCost = productCost.add(shippingCost).add(otherCost); - BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount) - .subtract(totalPromotionFee).subtract(totalBrushFee); - BigDecimal salesTaxAmount = salesTaxOnNetSales(salesAmount, refundAmount); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount); - - BigDecimal roi = BigDecimal.ZERO; - if (totalPromotionFee.compareTo(BigDecimal.ZERO) > 0) { - roi = salesAmount.subtract(refundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP); - } - - BigDecimal feeRatio = BigDecimal.ZERO; - if (salesAmount.compareTo(BigDecimal.ZERO) > 0) { - feeRatio = totalPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP); - } - - BigDecimal averageOrderValue = BigDecimal.ZERO; - if (orderCount > 0) { - averageOrderValue = salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP); - } - - String productName = productId == -1L ? "未匹配商品" : productNameMap.getOrDefault(productId, "Unknown"); - CompanyOverviewVO.CategorySummary summary = new CompanyOverviewVO.CategorySummary(); - summary.setCategoryId(productId == -1L ? null : productId); - summary.setCategoryName(productName); - summary.setSalesAmount(salesAmount); - summary.setGmv(gmvMaps.byProductKey().getOrDefault(productId, BigDecimal.ZERO)); - summary.setGrossProfit(salesAmount.subtract(totalCost).subtract(refundAmount) - .setScale(2, RoundingMode.HALF_UP)); - summary.setOrderCount(orderCount); - summary.setAverageOrderValue(averageOrderValue); - summary.setProductCost(productCost); - summary.setShippingCost(shippingCost); - summary.setOtherCost(otherCost); - summary.setOrderCost(totalCost); - summary.setRefundAmount(refundAmount); - summary.setTotalPromotionFee(totalPromotionFee); - summary.setBrushFee(totalBrushFee); - summary.setFeeRatio(feeRatio); - summary.setTotalProfitBeforeTax(profitBeforeTax); - summary.setSalesTaxAmount(salesTaxAmount); - summary.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - summary.setRoi(roi); - summaries.add(summary); - } - - summaries.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount).reversed()); - CompanyOverviewVO.CategorySummary total = computeCategoryTotal(summaries); - CompanyOverviewVO.CategoryOverview overview = new CompanyOverviewVO.CategoryOverview(); - overview.setTotal(total); - overview.setCategories(summaries); - return overview; - } - - @Override - public CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg( - BigDecimal taxRate, - Long companyId, - List shops, - List orderRows, - List promotionRows, - List brushRows, - LocalDate startDate, - LocalDate endDate) { - synchronized (this) { - BigDecimal saved = this.taxRate; - try { - this.taxRate = taxRate != null ? taxRate : DEFAULT_TAX_RATE; - return buildWorkbenchTablesFromAggInternal(companyId, shops, orderRows, promotionRows, brushRows, startDate, endDate); - } finally { - this.taxRate = saved; - } - } - } - - /** SQL 聚合行 → 四表(推广/刷单分摊规则与明细版一致) */ - private CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchTablesFromAggInternal( - Long companyId, - List shops, - List orderRows, - List promotionRows, - List brushRows, - LocalDate startDate, - LocalDate endDate) { - - Map byShop = new HashMap<>(); - Map byCategory = new HashMap<>(); - Map byProduct = new HashMap<>(); - Map> categorySalesByShop = new HashMap<>(); - Map> productSalesByShop = new HashMap<>(); - Map productCategoryMap = new HashMap<>(); - - for (OverviewAggRows.ShopProductRow row : orderRows) { - long shopId = row.getShopId() != null ? row.getShopId() : 0L; - long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L; - long categoryKey = productId <= 0 ? -1L - : (row.getCategoryId() == null || row.getCategoryId() == 0 ? 0L : row.getCategoryId()); - if (productId > 0) { - productCategoryMap.put(productId, categoryKey <= 0 ? null : categoryKey); - } - mergeAgg(byShop, shopId, row); - mergeAgg(byCategory, categoryKey, row); - mergeAgg(byProduct, productId, row); - BigDecimal sales = nz(row.getSalesAmount()); - categorySalesByShop.computeIfAbsent(categoryKey, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add); - productSalesByShop.computeIfAbsent(productId, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add); - } - - Map promoByShop = new HashMap<>(); - Map directPromoByProduct = new HashMap<>(); - Map directPromoByCategory = new HashMap<>(); - BigDecimal ratioPool = BigDecimal.ZERO; - for (OverviewAggRows.PromotionRow fee : promotionRows) { - BigDecimal amt = nz(fee.getFeeAmount()); - promoByShop.merge(fee.getShopId(), amt, BigDecimal::add); - if (fee.getProductId() != null) { - directPromoByProduct.merge(fee.getProductId(), amt, BigDecimal::add); - } else if (fee.getCategoryId() != null) { - directPromoByCategory.merge(fee.getCategoryId(), amt, BigDecimal::add); - } else { - ratioPool = ratioPool.add(amt); - } - } - Map brushByShop = new HashMap<>(); - for (OverviewAggRows.BrushRow b : brushRows) { - brushByShop.merge(b.getShopId(), nz(b.getBrushAmount()), BigDecimal::add); - } - BigDecimal totalSalesPool = orderRows.stream().map(r -> nz(r.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); - - Map> targetsByShop = loadTargetsByShop(companyId, startDate, endDate); - - CompanyOverviewVO.WorkbenchTableBundle bundle = new CompanyOverviewVO.WorkbenchTableBundle(); - bundle.setShopTable(buildShopOverviewFromAgg(shops, byShop, promoByShop, brushByShop, targetsByShop)); - bundle.setPlatformTable(buildPlatformOverviewFromAgg(shops, byShop, promoByShop, brushByShop, targetsByShop)); - bundle.setCategoryTable(buildCategoryOverviewFromAgg(byCategory, categorySalesByShop, brushByShop, - directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId)); - bundle.setProductTable(buildProductOverviewFromAgg(byProduct, productSalesByShop, brushByShop, - directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId)); - return bundle; - } - - private CompanyOverviewVO.ShopOverview buildShopOverviewFromAgg( - List shops, Map byShop, Map promoByShop, - Map brushByShop, Map> targetsByShop) { - List list = new ArrayList<>(); - for (ShopPO shop : shops) { - AggMetrics m = byShop.getOrDefault(shop.getId(), AggMetrics.EMPTY); - list.add(toShopSummaryFromAgg(shop, m, promoByShop.getOrDefault(shop.getId(), BigDecimal.ZERO), - brushByShop.getOrDefault(shop.getId(), BigDecimal.ZERO), - targetsByShop.getOrDefault(shop.getId(), List.of()))); - } - list.sort(Comparator.comparing(CompanyOverviewVO.ShopSummary::getSalesAmount, - Comparator.nullsFirst(BigDecimal::compareTo)).reversed()); - CompanyOverviewVO.ShopOverview o = new CompanyOverviewVO.ShopOverview(); - o.setShops(list); - o.setTotal(computeShopTotal(list)); - return o; - } - - private CompanyOverviewVO.PlatformOverview buildPlatformOverviewFromAgg( - List shops, Map byShop, Map promoByShop, - Map brushByShop, Map> targetsByShop) { - Map> byPlatform = shops.stream() - .filter(s -> s.getPlatformCode() != null && !s.getPlatformCode().isBlank()) - .collect(Collectors.groupingBy(ShopPO::getPlatformCode)); - List list = new ArrayList<>(); - for (Map.Entry> e : byPlatform.entrySet()) { - list.add(rollupPlatformFromAgg(e.getKey(), PlatformCode.labelOf(e.getKey()), - e.getValue(), byShop, promoByShop, brushByShop, targetsByShop)); - } - list.sort(Comparator.comparing(CompanyOverviewVO.PlatformSummary::getSalesAmount, - Comparator.nullsFirst(BigDecimal::compareTo)).reversed()); - CompanyOverviewVO.PlatformOverview o = new CompanyOverviewVO.PlatformOverview(); - o.setPlatforms(list); - o.setTotal(computePlatformTotal(list)); - return o; - } - - private CompanyOverviewVO.CategoryOverview buildCategoryOverviewFromAgg( - Map byCategory, Map> categorySalesByShop, - Map brushByShop, Map directPromoByProduct, - Map directPromoByCategory, BigDecimal ratioPool, BigDecimal totalSalesPool, - Map productCategoryMap, Long companyId) { - Map categoryNames = loadCategoryNameMap(companyId); - Map salesByCategory = byCategory.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().sales)); - List list = new ArrayList<>(); - for (Map.Entry e : byCategory.entrySet()) { - Long key = e.getKey(); - AggMetrics m = e.getValue(); - BigDecimal promo = resolveCategoryPromo(key, m.sales, salesByCategory, productCategoryMap, - directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool); - BigDecimal brush = allocBrushShare(categorySalesByShop.get(key), brushByShop); - list.add(toCategorySummaryFromAgg(key, categoryAggName(key, categoryNames), m, promo, brush)); - } - list.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount, - Comparator.nullsFirst(BigDecimal::compareTo)).reversed()); - CompanyOverviewVO.CategoryOverview o = new CompanyOverviewVO.CategoryOverview(); - o.setCategories(list); - o.setTotal(computeCategoryTotal(list)); - return o; - } - - private CompanyOverviewVO.CategoryOverview buildProductOverviewFromAgg( - Map byProduct, Map> productSalesByShop, - Map brushByShop, Map directPromoByProduct, - Map directPromoByCategory, BigDecimal ratioPool, BigDecimal totalSalesPool, - Map productCategoryMap, Long companyId) { - Map salesByCategory = new HashMap<>(); - for (Map.Entry e : byProduct.entrySet()) { - if (e.getKey() > 0) { - Long cid = productCategoryMap.get(e.getKey()); - if (cid != null && cid > 0) { - salesByCategory.merge(cid, e.getValue().sales, BigDecimal::add); - } - } - } - Map productNames = loadProductNameMap(byProduct.keySet()); - List list = new ArrayList<>(); - for (Map.Entry e : byProduct.entrySet()) { - Long pid = e.getKey(); - AggMetrics m = e.getValue(); - BigDecimal promo = resolveProductPromo(pid, m.sales, productCategoryMap, salesByCategory, - directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool); - BigDecimal brush = allocBrushShare(productSalesByShop.get(pid), brushByShop); - String name = pid <= 0 ? "未匹配商品" : productNames.getOrDefault(pid, "商品" + pid); - list.add(toCategorySummaryFromAgg(pid, name, m, promo, brush)); - } - list.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount, - Comparator.nullsFirst(BigDecimal::compareTo)).reversed()); - CompanyOverviewVO.CategoryOverview o = new CompanyOverviewVO.CategoryOverview(); - o.setCategories(list); - o.setTotal(computeCategoryTotal(list)); - return o; - } - - private CompanyOverviewVO.PlatformSummary rollupPlatformFromAgg( - String platformCode, String platformName, List platformShops, - Map byShop, Map promoByShop, Map brushByShop, - Map> targetsByShop) { - AggMetrics merged = AggMetrics.EMPTY; - BigDecimal promo = BigDecimal.ZERO; - BigDecimal brush = BigDecimal.ZERO; - BigDecimal targetAmt = BigDecimal.ZERO; - int targetOrders = 0; - for (ShopPO shop : platformShops) { - merged = merged.merge(byShop.getOrDefault(shop.getId(), AggMetrics.EMPTY)); - promo = promo.add(promoByShop.getOrDefault(shop.getId(), BigDecimal.ZERO)); - brush = brush.add(brushByShop.getOrDefault(shop.getId(), BigDecimal.ZERO)); - for (ShopMonthlyTargetPO t : targetsByShop.getOrDefault(shop.getId(), List.of())) { - targetAmt = targetAmt.add(nz(t.getTargetAmount())); - targetOrders += t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0; - } - } - return toPlatformSummaryFromAgg(platformCode, platformName, merged, promo, brush, targetAmt, targetOrders); - } - - private CompanyOverviewVO.ShopSummary toShopSummaryFromAgg( - ShopPO shop, AggMetrics m, BigDecimal promo, BigDecimal brush, - List targets) { - BigDecimal targetAmt = targets.stream().map(t -> nz(t.getTargetAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); - int targetOrders = targets.stream().mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0).sum(); - CompanyOverviewVO.ShopSummary s = new CompanyOverviewVO.ShopSummary(); - s.setShopId(shop.getId()); - s.setShopName(shop.getName()); - s.setPlatform(shop.getPlatformCode() != null ? PlatformCode.labelOf(shop.getPlatformCode()) : null); - fillSummaryMetrics(s, m, promo, brush, targetAmt, targetOrders); - return s; - } - - private CompanyOverviewVO.PlatformSummary toPlatformSummaryFromAgg( - String platformCode, String name, AggMetrics m, BigDecimal promo, BigDecimal brush, - BigDecimal targetAmt, int targetOrders) { - CompanyOverviewVO.PlatformSummary s = new CompanyOverviewVO.PlatformSummary(); - s.setPlatformCode(platformCode != null && !platformCode.isBlank() ? platformCode : null); - s.setPlatformName(name); - fillPlatformLikeMetrics(s, m, promo, brush, targetAmt, targetOrders); - return s; - } - - private CompanyOverviewVO.CategorySummary toCategorySummaryFromAgg( - Long key, String name, AggMetrics m, BigDecimal promo, BigDecimal brush) { - CompanyOverviewVO.CategorySummary s = new CompanyOverviewVO.CategorySummary(); - s.setCategoryId(key != null && key > 0 ? key : null); - s.setCategoryName(name); - fillCategoryLikeMetrics(s, m, promo, brush); - return s; - } - - private void fillSummaryMetrics(CompanyOverviewVO.ShopSummary s, AggMetrics m, BigDecimal promo, - BigDecimal brush, BigDecimal targetAmt, int targetOrders) { - s.setSalesAmount(m.sales); - s.setGmv(m.gmv); - s.setOrderCount(m.orderCount); - s.setAverageOrderValue(aov(m.sales, m.orderCount)); - s.setProductCost(m.productCost); - s.setShippingCost(m.freightCost); - s.setOtherCost(m.otherCost); - s.setOrderCost(m.orderCost()); - s.setRefundAmount(m.refund); - s.setTotalPromotionFee(promo); - s.setBrushFee(brush); - s.setFeeRatio(safeDivide(promo, m.sales)); - s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP)); - BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush); - s.setTotalProfitBeforeTax(pbt); - s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund)); - s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP)); - s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo)); - s.setTargetAmount(targetAmt); - s.setTargetOrderCount(targetOrders); - s.setSalesAmountAchievementRate(achievementRate(m.sales, targetAmt)); - s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.orderCount), BigDecimal.valueOf(targetOrders))); - } - - /** 品类/商品/平台汇总行:填充 GMV、毛利与净利字段 */ - private void fillCategoryLikeMetrics(CompanyOverviewVO.CategorySummary s, AggMetrics m, - BigDecimal promo, BigDecimal brush) { - s.setSalesAmount(m.sales); - s.setGmv(m.gmv); - s.setOrderCount(m.orderCount); - s.setAverageOrderValue(aov(m.sales, m.orderCount)); - s.setProductCost(m.productCost); - s.setShippingCost(m.freightCost); - s.setOtherCost(m.otherCost); - s.setOrderCost(m.orderCost()); - s.setRefundAmount(m.refund); - s.setTotalPromotionFee(promo); - s.setBrushFee(brush); - s.setFeeRatio(safeDivide(promo, m.sales)); - s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP)); - BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush); - s.setTotalProfitBeforeTax(pbt); - s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund)); - s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP)); - s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo)); - } - - private void fillPlatformLikeMetrics(CompanyOverviewVO.PlatformSummary s, AggMetrics m, - BigDecimal promo, BigDecimal brush, - BigDecimal targetAmt, int targetOrders) { - s.setSalesAmount(m.sales); - s.setGmv(m.gmv); - s.setOrderCount(m.orderCount); - s.setAverageOrderValue(aov(m.sales, m.orderCount)); - s.setProductCost(m.productCost); - s.setShippingCost(m.freightCost); - s.setOtherCost(m.otherCost); - s.setOrderCost(m.orderCost()); - s.setRefundAmount(m.refund); - s.setTotalPromotionFee(promo); - s.setBrushFee(brush); - s.setFeeRatio(safeDivide(promo.add(brush), m.sales)); - s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP)); - BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush); - s.setTotalProfitBeforeTax(pbt); - s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund)); - s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP)); - s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo)); - s.setTargetAmount(targetAmt); - s.setTargetOrderCount(targetOrders); - s.setSalesAmountAchievementRate(achievementRate(m.sales, targetAmt)); - s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.orderCount), BigDecimal.valueOf(targetOrders))); - } - - private static void mergeAgg(Map map, long key, OverviewAggRows.ShopProductRow row) { - map.merge(key, AggMetrics.from(row), AggMetrics::merge); - } - - private static BigDecimal resolveCategoryPromo(Long categoryKey, BigDecimal sales, - Map salesByCategory, Map productCategoryMap, - Map directByProduct, Map directByCategory, - BigDecimal ratioPool, BigDecimal totalPool) { - BigDecimal direct = BigDecimal.ZERO; - for (Map.Entry e : productCategoryMap.entrySet()) { - if (matchesCategory(categoryKey, e.getValue())) { - direct = direct.add(directByProduct.getOrDefault(e.getKey(), BigDecimal.ZERO)); - } - } - if (categoryKey != null && categoryKey > 0) { - direct = direct.add(directByCategory.getOrDefault(categoryKey, BigDecimal.ZERO)); - } - return addPoolShare(direct, sales, ratioPool, totalPool); - } - - private static BigDecimal resolveProductPromo(Long productId, BigDecimal sales, - Map productCategoryMap, Map salesByCategory, - Map directByProduct, Map directByCategory, - BigDecimal ratioPool, BigDecimal totalPool) { - if (productId == null || productId <= 0) { - return addPoolShare(BigDecimal.ZERO, sales, ratioPool, totalPool); - } - BigDecimal direct = directByProduct.getOrDefault(productId, BigDecimal.ZERO); - Long cid = productCategoryMap.get(productId); - if (cid != null && cid > 0) { - BigDecimal catSales = salesByCategory.getOrDefault(cid, BigDecimal.ZERO); - if (catSales.compareTo(BigDecimal.ZERO) > 0) { - direct = direct.add(directByCategory.getOrDefault(cid, BigDecimal.ZERO) - .multiply(sales).divide(catSales, 4, RoundingMode.HALF_UP)); - } - } - return addPoolShare(direct, sales, ratioPool, totalPool); - } - - private static boolean matchesCategory(Long categoryKey, Long productCat) { - if (categoryKey == -1L) { - return productCat == null; - } - return Objects.equals(categoryKey, productCat); - } - - private static BigDecimal addPoolShare(BigDecimal base, BigDecimal sales, BigDecimal pool, BigDecimal total) { - if (pool.compareTo(BigDecimal.ZERO) > 0 && total.compareTo(BigDecimal.ZERO) > 0) { - return base.add(pool.multiply(sales).divide(total, 4, RoundingMode.HALF_UP)); - } - return base; - } - - private static BigDecimal allocBrushShare(Map salesByShop, Map brushByShop) { - if (salesByShop == null || salesByShop.isEmpty()) { - return BigDecimal.ZERO; - } - BigDecimal total = salesByShop.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add); - if (total.compareTo(BigDecimal.ZERO) <= 0) { - return BigDecimal.ZERO; - } - BigDecimal brush = BigDecimal.ZERO; - for (Map.Entry e : salesByShop.entrySet()) { - brush = brush.add(brushByShop.getOrDefault(e.getKey(), BigDecimal.ZERO) - .multiply(e.getValue()).divide(total, 6, RoundingMode.HALF_UP)); - } - return brush; - } - - private Map loadCategoryNameMap(Long companyId) { - return categoryService.list(new LambdaQueryWrapper().eq(CategoryPO::getCompanyId, companyId)) - .stream().collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName, (a, b) -> a)); - } - - private Map loadProductNameMap(java.util.Set productKeys) { - List ids = productKeys.stream().filter(id -> id != null && id > 0).distinct().toList(); - if (ids.isEmpty()) { - return Map.of(); - } - return productMapper.selectList(new LambdaQueryWrapper().in(ProductPO::getId, ids)) - .stream().collect(Collectors.toMap(ProductPO::getId, ProductPO::getName, (a, b) -> a)); - } - - private Map> loadTargetsByShop(Long companyId, LocalDate start, LocalDate end) { - List months = new ArrayList<>(); - LocalDate cur = start.withDayOfMonth(1); - LocalDate endMonth = end.withDayOfMonth(1); - while (!cur.isAfter(endMonth)) { - months.add(cur); - cur = cur.plusMonths(1); - } - if (months.isEmpty()) { - return Map.of(); - } - LambdaQueryWrapper w = new LambdaQueryWrapper<>(); - w.eq(ShopMonthlyTargetPO::getCompanyId, companyId).in(ShopMonthlyTargetPO::getTargetMonth, months); - return shopMonthlyTargetMapper.selectList(w).stream() - .collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId)); - } - - private static String categoryAggName(Long key, Map names) { - if (key == null || key == -1L) { - return "其他品类"; - } - if (key == 0L) { - return "未分类"; - } - return names.getOrDefault(key, "类目" + key); - } - - private static BigDecimal aov(BigDecimal sales, int count) { - return count > 0 ? sales.divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; - } - - private static BigDecimal safeDivide(BigDecimal a, BigDecimal b) { - return b.compareTo(BigDecimal.ZERO) > 0 ? a.divide(b, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; - } - - private static BigDecimal achievementRate(BigDecimal actual, BigDecimal target) { - if (target.compareTo(BigDecimal.ZERO) > 0) { - return actual.divide(target, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")); - } - return actual.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO; - } - - private static BigDecimal nz(BigDecimal v) { - return v != null ? v : BigDecimal.ZERO; - } - - /** 全状态 GMV 按店铺/品类/商品维度预聚合(明细汇总路径用) */ - private record GmvDimensionMaps( - Map byShop, - Map byCategoryKey, - Map byProductKey) { - } - - private GmvDimensionMaps loadGmvDimensionMaps(Long companyId, List shops, - LocalDate startDate, LocalDate endDate) { - List shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).distinct().toList(); - if (shopIds.isEmpty()) { - return new GmvDimensionMaps(Map.of(), Map.of(), Map.of()); - } - LambdaQueryWrapper w = new LambdaQueryWrapper<>(); - w.eq(OrderPO::getCompanyId, companyId) - .in(OrderPO::getShopId, shopIds) - .ge(OrderPO::getOrderTime, startDate.atStartOfDay()) - .le(OrderPO::getOrderTime, endDate.atTime(23, 59, 59)); - List allOrders = orderMapper.selectList(w); - Map skuToProduct = orderSpecIdToProductIdMap(allOrders); - Map productCategoryMap = new HashMap<>(); - List productIds = skuToProduct.values().stream().filter(Objects::nonNull).distinct().toList(); - if (!productIds.isEmpty()) { - productMapper.selectList(new LambdaQueryWrapper().in(ProductPO::getId, productIds)) - .forEach(p -> productCategoryMap.put(p.getId(), p.getCategoryId())); - } - Map firstItems = OrderOverviewSupport.firstItemsForOrders(orderItemMapper, allOrders); - Map byShop = new HashMap<>(); - Map byCategoryKey = new HashMap<>(); - Map byProductKey = new HashMap<>(); - for (OrderPO o : allOrders) { - BigDecimal amt = nz(o.getPayAmount()); - if (o.getShopId() != null) { - byShop.merge(o.getShopId(), amt, BigDecimal::add); - } - OrderItemPO item = firstItems.get(o.getId()); - Long skuId = item != null ? item.getProductSkuId() : null; - long productId = skuId != null ? skuToProduct.getOrDefault(skuId, -1L) : -1L; - byProductKey.merge(productId, amt, BigDecimal::add); - long categoryKey; - if (productId <= 0) { - categoryKey = -1L; - } else { - Long cid = productCategoryMap.get(productId); - categoryKey = cid == null || cid == 0 ? 0L : cid; - } - byCategoryKey.merge(categoryKey, amt, BigDecimal::add); - } - return new GmvDimensionMaps(byShop, byCategoryKey, byProductKey); - } - - /** SQL 聚合指标桶 */ - private static final class AggMetrics { - static final AggMetrics EMPTY = new AggMetrics(); - BigDecimal sales = BigDecimal.ZERO; - /** 全订单状态 GMV(商家实收合计) */ - BigDecimal gmv = BigDecimal.ZERO; - int orderCount; - BigDecimal refund = BigDecimal.ZERO; - BigDecimal productCost = BigDecimal.ZERO; - BigDecimal freightCost = BigDecimal.ZERO; - BigDecimal otherCost = BigDecimal.ZERO; - - /** 订单成本合计(商品+运费+其他,不含推广/刷单) */ - BigDecimal orderCost() { - return productCost.add(freightCost).add(otherCost); - } - - /** 订单维度毛利:未扣推广/刷单/税 */ - BigDecimal grossProfit() { - return sales.subtract(orderCost()).subtract(refund); - } - - static AggMetrics from(OverviewAggRows.ShopProductRow row) { - AggMetrics a = new AggMetrics(); - a.sales = nz(row.getSalesAmount()); - a.gmv = nz(row.getGmvAllStatus()); - a.orderCount = row.getOrderCount() != null ? row.getOrderCount().intValue() : 0; - a.refund = nz(row.getRefundAmount()); - a.productCost = nz(row.getProductCost()); - a.freightCost = nz(row.getFreightCost()); - a.otherCost = nz(row.getOtherCost()); - return a; - } - - AggMetrics merge(AggMetrics o) { - AggMetrics a = new AggMetrics(); - a.sales = sales.add(o.sales); - a.gmv = gmv.add(o.gmv); - a.orderCount = orderCount + o.orderCount; - a.refund = refund.add(o.refund); - a.productCost = productCost.add(o.productCost); - a.freightCost = freightCost.add(o.freightCost); - a.otherCost = otherCost.add(o.otherCost); - return a; - } - } -} - diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/ShopOverviewStatisticsServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/ShopOverviewStatisticsServiceImpl.java deleted file mode 100644 index 121255ce..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/overview/service/impl/ShopOverviewStatisticsServiceImpl.java +++ /dev/null @@ -1,1072 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.overview.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import org.springframework.stereotype.Service; -import top.xyquan.ecomdmbbackend.common.exception.BusinessException; -import top.xyquan.ecomdmbbackend.modules.ec.brushorder.mapper.BrushOrderMapper; -import top.xyquan.ecomdmbbackend.modules.ec.category.model.po.CategoryPO; -import top.xyquan.ecomdmbbackend.modules.ec.category.service.CategoryService; -import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CompanyOverviewService; -import top.xyquan.ecomdmbbackend.modules.ec.promotion.mapper.PromotionFeeMapper; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopOverviewQueryDTO; -import top.xyquan.ecomdmbbackend.modules.ec.brushorder.model.po.BrushOrderPO; -import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO; -import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper; -import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO; -import top.xyquan.ecomdmbbackend.modules.ec.order.support.OrderOverviewSupport; -import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver; -import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets; -import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductSkuMapper; -import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO; -import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO; -import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO; -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; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.ShopOverviewStatisticsVO; -import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductService; -import top.xyquan.ecomdmbbackend.modules.ec.overview.service.ShopOverviewStatisticsService; -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.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * 单店铺概览统计服务实现类 - */ -@Service -public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatisticsService { - - private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04"); - private BigDecimal taxRate = DEFAULT_TAX_RATE; - - private final CurrentUserContext currentUserContext; - private final OrderMapper orderMapper; - private final OrderItemMapper orderItemMapper; - private final PromotionFeeMapper promotionFeeMapper; - private final BrushOrderMapper brushOrderMapper; - private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; - private final ShopService shopService; - private final ProductService productService; - private final ProductSkuMapper productSkuMapper; - private final OrderStatusStatResolver orderStatusStatResolver; - private final CategoryService categoryService; - private final CompanyOverviewService companyOverviewService; - - public ShopOverviewStatisticsServiceImpl(CurrentUserContext currentUserContext, - OrderMapper orderMapper, - OrderItemMapper orderItemMapper, - PromotionFeeMapper promotionFeeMapper, - BrushOrderMapper brushOrderMapper, - ShopMonthlyTargetMapper shopMonthlyTargetMapper, - ShopService shopService, - ProductService productService, - ProductSkuMapper productSkuMapper, - OrderStatusStatResolver orderStatusStatResolver, - CategoryService categoryService, - CompanyOverviewService companyOverviewService) { - this.currentUserContext = currentUserContext; - this.orderMapper = orderMapper; - this.orderItemMapper = orderItemMapper; - this.promotionFeeMapper = promotionFeeMapper; - this.brushOrderMapper = brushOrderMapper; - this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; - this.shopService = shopService; - this.productService = productService; - this.productSkuMapper = productSkuMapper; - this.orderStatusStatResolver = orderStatusStatResolver; - this.categoryService = categoryService; - this.companyOverviewService = companyOverviewService; - } - - /** - * 税额 = max(0, 销售额 − 退款) × 当前税率,四舍五入保留两位小数(与税后盈亏扣减口径一致)。 - */ - private BigDecimal toSalesTaxAmount(BigDecimal salesAmount, BigDecimal refundAmount) { - BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO; - BigDecimal refund = refundAmount != null ? refundAmount : BigDecimal.ZERO; - BigDecimal base = sales.subtract(refund); - if (base.compareTo(BigDecimal.ZERO) < 0) { - base = BigDecimal.ZERO; - } - return base.multiply(taxRate).setScale(2, RoundingMode.HALF_UP); - } - - @Override - public ShopOverviewStatisticsVO getShopOverviewStatistics(ShopOverviewQueryDTO queryDTO) { - // 取请求参数中的税率,默认4% - this.taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE; - - Long companyId = currentUserContext.getCurrentCompanyId(); - - // 解析日期范围 - LocalDate startDate; - LocalDate endDate; - if (queryDTO.getDateRange().size() == 1) { - startDate = queryDTO.getDateRange().get(0); - endDate = startDate; - } else { - startDate = queryDTO.getDateRange().get(0); - endDate = queryDTO.getDateRange().get(1); - if (startDate.isAfter(endDate)) { - throw new BusinessException("开始日期不能晚于结束日期"); - } - } - - LocalDateTime startDateTime = startDate.atStartOfDay(); - LocalDateTime endDateTime = endDate.atTime(23, 59, 59); - OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); - List unionStatusCodes = stat.getUnionStatusCodes(); - - // 验证店铺是否存在 - ShopPO shop = shopService.getById(queryDTO.getShopId()); - if (shop == null || !shop.getCompanyId().equals(companyId)) { - throw new BusinessException("店铺不存在"); - } - - // 查询订单数据(该店铺) - LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); - orderWrapper.eq(OrderPO::getCompanyId, companyId) - .eq(OrderPO::getShopId, queryDTO.getShopId()) - .ge(OrderPO::getOrderTime, startDateTime) - .le(OrderPO::getOrderTime, endDateTime); - if (!unionStatusCodes.isEmpty()) { - orderWrapper.in(OrderPO::getStatus, unionStatusCodes); - } else { - orderWrapper.isNull(OrderPO::getId); - } - List orders = orderMapper.selectList(orderWrapper); - - // 查询推广费数据(该店铺) - LambdaQueryWrapper promotionWrapper = new LambdaQueryWrapper<>(); - promotionWrapper.eq(PromotionFeePO::getCompanyId, companyId) - .eq(PromotionFeePO::getShopId, queryDTO.getShopId()) - .ge(PromotionFeePO::getFeeDate, startDate) - .le(PromotionFeePO::getFeeDate, endDate); - List promotionFees = promotionFeeMapper.selectList(promotionWrapper); - - // 查询刷单费数据(该店铺) - LambdaQueryWrapper brushWrapper = new LambdaQueryWrapper<>(); - brushWrapper.eq(BrushOrderPO::getCompanyId, companyId) - .eq(BrushOrderPO::getShopId, queryDTO.getShopId()) - .ge(BrushOrderPO::getBrushTime, startDateTime) - .le(BrushOrderPO::getBrushTime, endDateTime); - List brushOrders = brushOrderMapper.selectList(brushWrapper); - - // 计算上月同期数据(用于增长百分比) - LocalDate lastMonthStartDate = startDate.minusMonths(1); - LocalDate lastMonthEndDate = endDate.minusMonths(1); - LocalDateTime lastMonthStartDateTime = lastMonthStartDate.atStartOfDay(); - LocalDateTime lastMonthEndDateTime = lastMonthEndDate.atTime(23, 59, 59); - - LambdaQueryWrapper lastMonthOrderWrapper = new LambdaQueryWrapper<>(); - lastMonthOrderWrapper.eq(OrderPO::getCompanyId, companyId) - .eq(OrderPO::getShopId, queryDTO.getShopId()) - .ge(OrderPO::getOrderTime, lastMonthStartDateTime) - .le(OrderPO::getOrderTime, lastMonthEndDateTime); - if (!unionStatusCodes.isEmpty()) { - lastMonthOrderWrapper.in(OrderPO::getStatus, unionStatusCodes); - } else { - lastMonthOrderWrapper.isNull(OrderPO::getId); - } - List lastMonthOrders = orderMapper.selectList(lastMonthOrderWrapper); - - // 构建返回对象 - ShopOverviewStatisticsVO overviewVO = new ShopOverviewStatisticsVO(); - overviewVO.setShopId(queryDTO.getShopId()); - // 获取店铺名称 - ShopPO shopEntity = shopService.getById(queryDTO.getShopId()); - if (shopEntity != null) { - overviewVO.setShopName(shopEntity.getName()); - } - - // 1. 计算店铺总销售额(按状态「计入销售额」维度) - BigDecimal totalSalesAmount = orders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - overviewVO.setTotalSalesAmount(totalSalesAmount); - - // 2. 计算较上月同期增长百分比 - BigDecimal lastMonthSalesAmount = lastMonthOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal monthOverMonthGrowth = BigDecimal.ZERO; - if (lastMonthSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - monthOverMonthGrowth = totalSalesAmount.subtract(lastMonthSalesAmount) - .divide(lastMonthSalesAmount, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")); - } else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - monthOverMonthGrowth = new BigDecimal("100"); - } - overviewVO.setMonthOverMonthGrowth(monthOverMonthGrowth); - - // 3. 计算店铺总单量(按状态「计入销售额」维度计单) - int totalOrderCount = (int) orders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - overviewVO.setTotalOrderCount(totalOrderCount); - - // 3.1 退款金额、客单价(按状态「计入退款」维度) - BigDecimal refundAmountAgg = orders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - overviewVO.setRefundAmount(refundAmountAgg); - BigDecimal averageOrderValue = BigDecimal.ZERO; - if (totalOrderCount > 0) { - averageOrderValue = totalSalesAmount.divide( - BigDecimal.valueOf(totalOrderCount), 2, RoundingMode.HALF_UP); - } - overviewVO.setAverageOrderValue(averageOrderValue); - - // 4. 计算总推广费支出 - BigDecimal totalPromotionFee = promotionFees.stream() - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - overviewVO.setTotalPromotionFee(totalPromotionFee); - - BigDecimal totalBrushFee = brushOrders.stream() - .map(b -> b.getBrushAmount() != null ? b.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 5. 计算平均费比 - BigDecimal averageFeeRatio = BigDecimal.ZERO; - if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - averageFeeRatio = totalPromotionFee.divide(totalSalesAmount, 4, RoundingMode.HALF_UP); - } - overviewVO.setAverageFeeRatio(averageFeeRatio); - - // 6. 计算店铺总净利(税后)和总税额:税前盈亏 = 订单维度毛利 − 推广费 − 刷单费 - BigDecimal totalProfitBeforeTax = calculateTotalProfit(orders, stat) - .subtract(totalPromotionFee) - .subtract(totalBrushFee); - overviewVO.setTotalProfitBeforeTax(totalProfitBeforeTax); - BigDecimal totalSalesTaxAmount = toSalesTaxAmount(totalSalesAmount, refundAmountAgg); - BigDecimal totalNetProfitAfterTax = totalProfitBeforeTax.subtract(totalSalesTaxAmount); - overviewVO.setTotalNetProfitAfterTax(totalNetProfitAfterTax.setScale(2, RoundingMode.HALF_UP)); - overviewVO.setTotalTaxAmount(totalSalesTaxAmount); - - // 7. 计算目标维度的数据 - calculateTargetData(overviewVO, companyId, queryDTO.getShopId(), startDate, endDate, totalSalesAmount, totalOrderCount); - - // 8. 汇总ROI - BigDecimal totalROI = calculateTotalROI(orders, promotionFees, brushOrders, stat); - overviewVO.setTotalROI(totalROI); - - // 9. 计算趋势分析数据 - ShopOverviewStatisticsVO.TrendData salesAmountTrend = calculateSalesAmountTrend(orders, startDate, endDate, stat); - ShopOverviewStatisticsVO.TrendData orderCountTrend = calculateOrderCountTrend(orders, startDate, endDate, stat); - overviewVO.setSalesAmountTrend(salesAmountTrend); - overviewVO.setOrderCountTrend(orderCountTrend); - - // 10. 多商品数据横向汇总 - ShopOverviewStatisticsVO.ProductOverview productOverview = calculateProductSummary( - orders, promotionFees, brushOrders, stat); - overviewVO.setProductOverview(productOverview); - - // 11. 品类多维度数据汇总 - ShopOverviewStatisticsVO.CategoryOverview categoryOverview = calculateCategorySummary( - orders, promotionFees, brushOrders, stat); - overviewVO.setCategoryOverview(categoryOverview); - - fillProductSalesTop10(overviewVO); - - return overviewVO; - } - - /** - * 从商品横向汇总中按单量取 Top10,供概览榜单展示(不重复计算订单) - */ - private void fillProductSalesTop10(ShopOverviewStatisticsVO vo) { - ShopOverviewStatisticsVO.ProductOverview po = vo.getProductOverview(); - if (po == null || po.getProducts() == null || po.getProducts().isEmpty()) { - vo.setProductSalesTop10(Collections.emptyList()); - return; - } - List top10 = po.getProducts().stream() - .sorted(Comparator.comparing( - (ShopOverviewStatisticsVO.ProductSummary p) -> - p.getOrderCount() != null ? p.getOrderCount() : 0, - Comparator.reverseOrder())) - .limit(10) - .map(p -> { - ShopOverviewStatisticsVO.ProductSalesRankItem item = - new ShopOverviewStatisticsVO.ProductSalesRankItem(); - item.setProductId(p.getProductId()); - item.setProductName(p.getProductName()); - item.setProductCode(p.getProductCode()); - item.setOrderCount(p.getOrderCount()); - item.setSalesAmount(p.getSalesAmount()); - return item; - }) - .collect(Collectors.toList()); - vo.setProductSalesTop10(top10); - } - - /** - * 订单维度毛利(税前、未扣推广费/刷单费),全店税前盈亏需再减推广费与刷单费 - */ - private BigDecimal calculateTotalProfit(List orders, OrderStatusStatSets stat) { - return orders.stream() - .map(order -> stat.receivedForSales(order).subtract(stat.totalCostForStats(order))) - .reduce(BigDecimal.ZERO, BigDecimal::add); - } - - /** - * 计算目标维度的数据 - */ - private void calculateTargetData(ShopOverviewStatisticsVO overviewVO, Long companyId, Long shopId, - LocalDate startDate, LocalDate endDate, - BigDecimal totalSalesAmount, Integer totalOrderCount) { - // 生成日期范围内所有月份的第一天列表 - List targetMonths = new ArrayList<>(); - LocalDate currentMonth = startDate.withDayOfMonth(1); - LocalDate endMonth = endDate.withDayOfMonth(1); - while (!currentMonth.isAfter(endMonth)) { - targetMonths.add(currentMonth); - currentMonth = currentMonth.plusMonths(1); - } - - // 查询该店铺在这些月份的目标数据 - LambdaQueryWrapper targetWrapper = new LambdaQueryWrapper<>(); - targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId) - .eq(ShopMonthlyTargetPO::getShopId, shopId) - .in(ShopMonthlyTargetPO::getTargetMonth, targetMonths); - List targets = shopMonthlyTargetMapper.selectList(targetWrapper); - - // 汇总目标数据 - BigDecimal totalTargetAmount = targets.stream() - .map(target -> target.getTargetAmount() != null ? target.getTargetAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - Integer totalTargetOrderCount = targets.stream() - .mapToInt(target -> target.getTargetOrderCount() != null ? target.getTargetOrderCount() : 0) - .sum(); - - overviewVO.setTotalTargetAmount(totalTargetAmount); - overviewVO.setTotalTargetOrderCount(totalTargetOrderCount); - - // 计算达成率 - BigDecimal salesAmountAchievementRate = BigDecimal.ZERO; - if (totalTargetAmount.compareTo(BigDecimal.ZERO) > 0) { - salesAmountAchievementRate = totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")); - } else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - salesAmountAchievementRate = new BigDecimal("100"); - } - overviewVO.setSalesAmountAchievementRate(salesAmountAchievementRate); - - BigDecimal orderCountAchievementRate = BigDecimal.ZERO; - if (totalTargetOrderCount > 0) { - orderCountAchievementRate = new BigDecimal(totalOrderCount) - .divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")); - } else if (totalOrderCount > 0) { - orderCountAchievementRate = new BigDecimal("100"); - } - overviewVO.setOrderCountAchievementRate(orderCountAchievementRate); - } - - /** - * 计算汇总ROI - */ - private BigDecimal calculateTotalROI(List orders, List promotionFees, - List brushOrders, OrderStatusStatSets stat) { - BigDecimal totalSales = orders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal totalRefund = orders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal totalPromotionFee = promotionFees.stream() - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - return calculateSalesROI(totalSales.subtract(totalRefund), totalPromotionFee); - } - - /** - * 计算ROI(新公式):(销售额 - 退款金额)/ 推广费用 - */ - private BigDecimal calculateSalesROI(BigDecimal netSales, BigDecimal promotionFee) { - if (promotionFee == null || promotionFee.compareTo(BigDecimal.ZERO) <= 0) { - return BigDecimal.ZERO; - } - return netSales.divide(promotionFee, 2, RoundingMode.HALF_UP); - } - - private Map orderSpecIdToProductIdMap(List orders) { - return OrderOverviewSupport.orderSpecIdToProductIdMap(productSkuMapper, orderItemMapper, orders); - } - - /** - * 计算多商品数据横向汇总 - */ - private ShopOverviewStatisticsVO.ProductOverview calculateProductSummary( - List orders, List promotionFees, - List brushOrders, OrderStatusStatSets stat) { - List summaries = new ArrayList<>(); - - Map skuToProduct = orderSpecIdToProductIdMap(orders); - Map firstItems = OrderOverviewSupport.firstItemsForOrders(orderItemMapper, orders); - Map> ordersByProduct = orders.stream() - .collect(Collectors.groupingBy(o -> - OrderOverviewSupport.productIdOfOrder(o, firstItems, skuToProduct))); - - // 按商品分组刷单费数据(如果有商品ID) - Map> brushOrdersByProduct = brushOrders.stream() - .filter(brush -> brush.getProductId() != null) - .collect(Collectors.groupingBy(BrushOrderPO::getProductId)); - - // 按商品ID分组推广费:有 product_id 的为直接归属,无 product_id 的进入比例池 - Map directPromotionByProduct = promotionFees.stream() - .filter(fee -> fee.getProductId() != null) - .collect(Collectors.groupingBy( - PromotionFeePO::getProductId, - Collectors.reducing( - BigDecimal.ZERO, - fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); - - Map categoryOnlyPool = promotionFees.stream() - .filter(fee -> fee.getProductId() == null && fee.getCategoryId() != null) - .collect(Collectors.groupingBy( - PromotionFeePO::getCategoryId, - Collectors.reducing( - BigDecimal.ZERO, - fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); - - BigDecimal globalRatioPool = promotionFees.stream() - .filter(fee -> fee.getProductId() == null && fee.getCategoryId() == null) - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - Map productPromotionFromCategory = new HashMap<>(); - for (Map.Entry catEntry : categoryOnlyPool.entrySet()) { - Long catId = catEntry.getKey(); - BigDecimal pool = catEntry.getValue(); - if (catId == null || pool == null || pool.compareTo(BigDecimal.ZERO) <= 0) { - continue; - } - Map eligibleSalesByProduct = new HashMap<>(); - for (Map.Entry> e : ordersByProduct.entrySet()) { - Long pid = e.getKey(); - if (pid == null || pid < 0) { - continue; - } - BigDecimal direct = directPromotionByProduct.getOrDefault(pid, BigDecimal.ZERO); - if (direct.compareTo(BigDecimal.ZERO) > 0) { - continue; - } - ProductPO p = productService.getById(pid); - if (p == null || !Objects.equals(p.getCategoryId(), catId)) { - continue; - } - BigDecimal sal = e.getValue().stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - eligibleSalesByProduct.put(pid, sal); - } - BigDecimal totalElig = eligibleSalesByProduct.values().stream() - .reduce(BigDecimal.ZERO, BigDecimal::add); - if (totalElig.compareTo(BigDecimal.ZERO) <= 0) { - globalRatioPool = globalRatioPool.add(pool); - continue; - } - for (Map.Entry pe : eligibleSalesByProduct.entrySet()) { - BigDecimal share = pool.multiply(pe.getValue()) - .divide(totalElig, 4, RoundingMode.HALF_UP); - productPromotionFromCategory.merge(pe.getKey(), share, BigDecimal::add); - } - } - - // 计算各商品销售额(仅用于比例分配) - Map salesByProduct = ordersByProduct.entrySet().stream() - .collect(Collectors.toMap( - Map.Entry::getKey, - e -> e.getValue().stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add))); - BigDecimal totalSalesAmount = salesByProduct.values().stream() - .reduce(BigDecimal.ZERO, BigDecimal::add); - - for (Map.Entry> entry : ordersByProduct.entrySet()) { - Long productId = entry.getKey(); - List productOrders = entry.getValue(); - if (productId == null || productId < 0) { - continue; - } - - // 获取商品信息 - ProductPO product = productService.getById(productId); - if (product == null) { - continue; - } - - // 计算各项指标 - BigDecimal salesAmount = productOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - int orderCount = (int) productOrders.stream() - .filter(o -> stat.includesSales(o.getStatus())) - .count(); - - BigDecimal refundAmount = productOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal brushFee = brushOrdersByProduct.getOrDefault(productId, new ArrayList<>()).stream() - .map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 推广费:商品级直接归属 + 类目级分摊 + 店铺级比例池 - BigDecimal productPromotionFee = directPromotionByProduct.getOrDefault(productId, BigDecimal.ZERO) - .add(productPromotionFromCategory.getOrDefault(productId, BigDecimal.ZERO)); - if (productPromotionFee.compareTo(BigDecimal.ZERO) == 0 && globalRatioPool.compareTo(BigDecimal.ZERO) > 0 && totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - BigDecimal ratio = salesAmount.divide(totalSalesAmount, 4, RoundingMode.HALF_UP); - productPromotionFee = globalRatioPool.multiply(ratio); - } - - // 计算商品成本 - BigDecimal productCost = productOrders.stream() - .map(stat::productCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 计算运费成本 - BigDecimal shippingCost = productOrders.stream() - .map(stat::freightCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 计算其他成本 - BigDecimal otherCost = productOrders.stream() - .map(stat::otherCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal totalCost = calculateProductTotalCost(productOrders, stat); - BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount) - .subtract(productPromotionFee).subtract(brushFee); - - // (销售额 − 退款) × 税率,税额保留两位小数 - BigDecimal salesTaxAmount = toSalesTaxAmount(salesAmount, refundAmount); - - // 税后盈亏(扣除税额) - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount); - - BigDecimal roi = calculateSalesROI(salesAmount.subtract(refundAmount), productPromotionFee); - - BigDecimal feeRatio = BigDecimal.ZERO; - if (salesAmount.compareTo(BigDecimal.ZERO) > 0) { - feeRatio = productPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP); - } - - BigDecimal averageOrderValue = BigDecimal.ZERO; - if (orderCount > 0) { - averageOrderValue = salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP); - } - - ShopOverviewStatisticsVO.ProductSummary summary = new ShopOverviewStatisticsVO.ProductSummary(); - summary.setProductId(productId); - summary.setProductName(product.getName()); - summary.setProductCode(product.getProductCode()); - summary.setSalesAmount(salesAmount); - summary.setOrderCount(orderCount); - summary.setAverageOrderValue(averageOrderValue); - summary.setProductCost(productCost); - summary.setShippingCost(shippingCost); - summary.setOtherCost(otherCost); - summary.setOrderCost(productCost.add(shippingCost).add(otherCost)); - summary.setRefundAmount(refundAmount); - summary.setTotalPromotionFee(productPromotionFee); - summary.setBrushFee(brushFee); - summary.setFeeRatio(feeRatio); - summary.setTotalProfitBeforeTax(profitBeforeTax); - summary.setSalesTaxAmount(salesTaxAmount); - summary.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - summary.setRoi(roi); - summaries.add(summary); - } - - // 按销售额降序排序 - summaries.sort(Comparator.comparing(ShopOverviewStatisticsVO.ProductSummary::getSalesAmount).reversed()); - - // 计算合计行 - ShopOverviewStatisticsVO.ProductSummary total = computeProductTotal(summaries); - - // 封装为 ProductOverview - ShopOverviewStatisticsVO.ProductOverview overview = new ShopOverviewStatisticsVO.ProductOverview(); - overview.setTotal(total); - overview.setProducts(summaries); - return overview; - } - - /** - * 计算商品汇总的合计行 - */ - private ShopOverviewStatisticsVO.ProductSummary computeProductTotal(List products) { - BigDecimal totalSales = BigDecimal.ZERO; - int totalOrders = 0; - BigDecimal totalProductCost = BigDecimal.ZERO; - BigDecimal totalShippingCost = BigDecimal.ZERO; - BigDecimal totalOtherCost = BigDecimal.ZERO; - BigDecimal totalRefund = BigDecimal.ZERO; - BigDecimal totalPromoFee = BigDecimal.ZERO; - BigDecimal totalBrushFee = BigDecimal.ZERO; - - for (ShopOverviewStatisticsVO.ProductSummary p : products) { - totalSales = totalSales.add(p.getSalesAmount() != null ? p.getSalesAmount() : BigDecimal.ZERO); - totalOrders += p.getOrderCount() != null ? p.getOrderCount() : 0; - totalProductCost = totalProductCost.add(p.getProductCost() != null ? p.getProductCost() : BigDecimal.ZERO); - totalShippingCost = totalShippingCost.add(p.getShippingCost() != null ? p.getShippingCost() : BigDecimal.ZERO); - totalOtherCost = totalOtherCost.add(p.getOtherCost() != null ? p.getOtherCost() : BigDecimal.ZERO); - totalRefund = totalRefund.add(p.getRefundAmount() != null ? p.getRefundAmount() : BigDecimal.ZERO); - totalPromoFee = totalPromoFee.add(p.getTotalPromotionFee() != null ? p.getTotalPromotionFee() : BigDecimal.ZERO); - totalBrushFee = totalBrushFee.add(p.getBrushFee() != null ? p.getBrushFee() : BigDecimal.ZERO); - } - - BigDecimal avgOrderValue = totalOrders > 0 - ? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); - BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund) - .subtract(totalPromoFee).subtract(totalBrushFee); - BigDecimal salesTax = toSalesTaxAmount(totalSales, totalRefund); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); - BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 - ? totalSales.subtract(totalRefund).divide(totalPromoFee, 2, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 - ? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - - ShopOverviewStatisticsVO.ProductSummary total = new ShopOverviewStatisticsVO.ProductSummary(); - total.setProductId(0L); - total.setProductName("合计"); - total.setSalesAmount(totalSales); - total.setOrderCount(totalOrders); - total.setAverageOrderValue(avgOrderValue); - total.setProductCost(totalProductCost); - total.setShippingCost(totalShippingCost); - total.setOtherCost(totalOtherCost); - total.setOrderCost(totalCost); - total.setRefundAmount(totalRefund); - total.setTotalPromotionFee(totalPromoFee); - total.setBrushFee(totalBrushFee); - total.setFeeRatio(feeRatio); - total.setTotalProfitBeforeTax(profitBeforeTax); - total.setSalesTaxAmount(salesTax); - total.setRoi(roi); - total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - return total; - } - - /** - * 计算商品订单成本(订单维度商品+运费+其他) - */ - private BigDecimal calculateProductTotalCost(List orders, OrderStatusStatSets stat) { - return orders.stream() - .map(stat::totalCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - } - - /** - * 计算销售额趋势分析 - */ - private ShopOverviewStatisticsVO.TrendData calculateSalesAmountTrend(List orders, LocalDate startDate, - LocalDate endDate, OrderStatusStatSets stat) { - ShopOverviewStatisticsVO.TrendData trendData = new ShopOverviewStatisticsVO.TrendData(); - - // 按日期分组订单数据 - Map> ordersByDate = orders.stream() - .collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate())); - - BigDecimal total = orders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - trendData.setTotal(total); - - // 生成日期范围内的所有日期列表 - List dateList = new ArrayList<>(); - LocalDate currentDate = startDate; - while (!currentDate.isAfter(endDate)) { - dateList.add(currentDate); - currentDate = currentDate.plusDays(1); - } - - // 计算每日销售额 - List dailyDataList = dateList.stream() - .map(date -> { - ShopOverviewStatisticsVO.TrendDataItem item = new ShopOverviewStatisticsVO.TrendDataItem(); - item.setDate(date); - List dayOrders = ordersByDate.getOrDefault(date, new ArrayList<>()); - BigDecimal dayAmount = dayOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - item.setValue(dayAmount); - return item; - }) - .sorted(Comparator.comparing(ShopOverviewStatisticsVO.TrendDataItem::getDate)) - .collect(Collectors.toList()); - trendData.setDailyDataList(dailyDataList); - - return trendData; - } - - /** - * 计算单量趋势分析 - */ - private ShopOverviewStatisticsVO.TrendData calculateOrderCountTrend(List orders, LocalDate startDate, - LocalDate endDate, OrderStatusStatSets stat) { - ShopOverviewStatisticsVO.TrendData trendData = new ShopOverviewStatisticsVO.TrendData(); - - // 按日期分组订单数据 - Map> ordersByDate = orders.stream() - .collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate())); - - int totalCount = (int) orders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - trendData.setTotal(new BigDecimal(totalCount)); - - // 生成日期范围内的所有日期列表 - List dateList = new ArrayList<>(); - LocalDate currentDate = startDate; - while (!currentDate.isAfter(endDate)) { - dateList.add(currentDate); - currentDate = currentDate.plusDays(1); - } - - // 计算每日单量 - List dailyDataList = dateList.stream() - .map(date -> { - ShopOverviewStatisticsVO.TrendDataItem item = new ShopOverviewStatisticsVO.TrendDataItem(); - item.setDate(date); - List dayOrders = ordersByDate.getOrDefault(date, new ArrayList<>()); - int dayCount = (int) dayOrders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - item.setValue(new BigDecimal(dayCount)); - return item; - }) - .sorted(Comparator.comparing(ShopOverviewStatisticsVO.TrendDataItem::getDate)) - .collect(Collectors.toList()); - trendData.setDailyDataList(dailyDataList); - - return trendData; - } - - /** - * 计算品类多维度数据汇总 - */ - private ShopOverviewStatisticsVO.CategoryOverview calculateCategorySummary( - List orders, List promotionFees, - List brushOrders, OrderStatusStatSets stat) { - - // 构建商品ID->品类ID的映射 - Map productCategoryMap = new HashMap<>(); - Map categoryMap = new HashMap<>(); - - // 查询该店铺所有商品 - LambdaQueryWrapper productWrapper = new LambdaQueryWrapper<>(); - productWrapper.eq(ProductPO::getCompanyId, currentUserContext.getCurrentCompanyId()); - List allProducts = productService.list(productWrapper); - for (ProductPO p : allProducts) { - productCategoryMap.put(p.getId(), p.getCategoryId()); - } - - // 查询所有品类并建索引 - List allCategories = categoryService.list(); - for (CategoryPO c : allCategories) { - categoryMap.put(c.getId(), c); - } - - Map skuToProduct = orderSpecIdToProductIdMap(orders); - Map firstItems = OrderOverviewSupport.firstItemsForOrders(orderItemMapper, orders); - // 按品类分组订单 - Map> ordersByCategory = new HashMap<>(); - for (OrderPO order : orders) { - OrderItemPO item = firstItems.get(order.getId()); - Long sid = item != null ? item.getProductSkuId() : null; - Long pid = sid != null ? skuToProduct.get(sid) : null; - Long categoryId = pid != null ? productCategoryMap.get(pid) : null; - if (categoryId == null) { - categoryId = 0L; // 未分类 - } - ordersByCategory.computeIfAbsent(categoryId, k -> new ArrayList<>()).add(order); - } - - // 推广费:按商品ID聚合直接归属;无商品有类目则直接记类目;全无则进入比例池 - Map directPromotionByProduct = promotionFees.stream() - .filter(fee -> fee.getProductId() != null) - .collect(Collectors.groupingBy( - PromotionFeePO::getProductId, - Collectors.reducing( - BigDecimal.ZERO, - fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); - Map directPromotionByCategory = promotionFees.stream() - .filter(fee -> fee.getProductId() == null && fee.getCategoryId() != null) - .collect(Collectors.groupingBy( - PromotionFeePO::getCategoryId, - Collectors.reducing( - BigDecimal.ZERO, - fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); - BigDecimal ratioPool = promotionFees.stream() - .filter(fee -> fee.getProductId() == null && fee.getCategoryId() == null) - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 品类总销售额(用于比例分配) - Map salesByCategory = new HashMap<>(); - for (Map.Entry> e : ordersByCategory.entrySet()) { - BigDecimal catSales = e.getValue().stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - salesByCategory.put(e.getKey(), catSales); - } - BigDecimal totalSalesAmount = salesByCategory.values().stream() - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal totalBrushFeeAll = brushOrders.stream() - .map(b -> b.getBrushAmount() != null ? b.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 按品类聚合 - List results = new ArrayList<>(); - for (Map.Entry> entry : ordersByCategory.entrySet()) { - Long categoryId = entry.getKey(); - List catOrders = entry.getValue(); - - BigDecimal salesAmount = catOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - int orderCount = (int) catOrders.stream().filter(o -> stat.includesSales(o.getStatus())).count(); - - BigDecimal refundAmount = catOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 推广费:先汇总品类内各商品的直接归属推广费,再按品类销售额比例分配比例池 - Set catProductIds = new HashSet<>(); - for (OrderPO order : catOrders) { - OrderItemPO item = firstItems.get(order.getId()); - Long sid = item != null ? item.getProductSkuId() : null; - Long pid = sid != null ? skuToProduct.get(sid) : null; - if (pid != null) catProductIds.add(pid); - } - BigDecimal directCatPromotion = catProductIds.stream() - .map(pid -> directPromotionByProduct.getOrDefault(pid, BigDecimal.ZERO)) - .reduce(BigDecimal.ZERO, BigDecimal::add); - directCatPromotion = directCatPromotion.add( - directPromotionByCategory.getOrDefault(categoryId, BigDecimal.ZERO)); - // 分配比例池 - BigDecimal catPromotionFee = directCatPromotion; - if (ratioPool.compareTo(BigDecimal.ZERO) > 0 && totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - BigDecimal ratio = salesAmount.divide(totalSalesAmount, 4, RoundingMode.HALF_UP); - catPromotionFee = catPromotionFee.add(ratioPool.multiply(ratio)); - } - - BigDecimal catBrushFee = BigDecimal.ZERO; - if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - catBrushFee = totalBrushFeeAll.multiply( - salesAmount.divide(totalSalesAmount, 4, RoundingMode.HALF_UP)); - } - - BigDecimal productCost = catOrders.stream() - .map(stat::productCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal shippingCost = catOrders.stream() - .map(stat::freightCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal otherCost = catOrders.stream() - .map(stat::otherCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal totalCost = productCost.add(shippingCost).add(otherCost); - BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount) - .subtract(catPromotionFee).subtract(catBrushFee); - BigDecimal salesTaxAmount = toSalesTaxAmount(salesAmount, refundAmount); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount); - - BigDecimal roi = calculateSalesROI(salesAmount.subtract(refundAmount), catPromotionFee); - - BigDecimal feeRatio = BigDecimal.ZERO; - if (salesAmount.compareTo(BigDecimal.ZERO) > 0) { - feeRatio = catPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP); - } - - BigDecimal averageOrderValue = orderCount > 0 - ? salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - - ShopOverviewStatisticsVO.CategorySummary summary = new ShopOverviewStatisticsVO.CategorySummary(); - summary.setCategoryId(categoryId); - summary.setCategoryName(categoryId == 0L ? "未分类" : categoryMap.get(categoryId).getName()); - summary.setSalesAmount(salesAmount); - summary.setOrderCount(orderCount); - summary.setAverageOrderValue(averageOrderValue); - summary.setProductCost(productCost); - summary.setShippingCost(shippingCost); - summary.setOtherCost(otherCost); - summary.setOrderCost(totalCost); - summary.setRefundAmount(refundAmount); - summary.setTotalPromotionFee(catPromotionFee); - summary.setBrushFee(catBrushFee); - summary.setFeeRatio(feeRatio); - summary.setTotalProfitBeforeTax(profitBeforeTax); - summary.setSalesTaxAmount(salesTaxAmount); - summary.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - summary.setRoi(roi); - results.add(summary); - } - - results.sort(Comparator.comparing(ShopOverviewStatisticsVO.CategorySummary::getSalesAmount).reversed()); - - // 计算合计行 - ShopOverviewStatisticsVO.CategorySummary total = computeCategoryTotalForShop(results); - - // 封装为 CategoryOverview - ShopOverviewStatisticsVO.CategoryOverview overview = new ShopOverviewStatisticsVO.CategoryOverview(); - overview.setTotal(total); - overview.setCategories(results); - return overview; - } - - /** - * 计算店铺视角品类汇总的合计行 - */ - private ShopOverviewStatisticsVO.CategorySummary computeCategoryTotalForShop(List categories) { - BigDecimal totalSales = BigDecimal.ZERO; - int totalOrders = 0; - BigDecimal totalProductCost = BigDecimal.ZERO; - BigDecimal totalShippingCost = BigDecimal.ZERO; - BigDecimal totalOtherCost = BigDecimal.ZERO; - BigDecimal totalRefund = BigDecimal.ZERO; - BigDecimal totalPromoFee = BigDecimal.ZERO; - BigDecimal totalBrushFee = BigDecimal.ZERO; - - for (ShopOverviewStatisticsVO.CategorySummary c : categories) { - totalSales = totalSales.add(c.getSalesAmount() != null ? c.getSalesAmount() : BigDecimal.ZERO); - totalOrders += c.getOrderCount() != null ? c.getOrderCount() : 0; - totalProductCost = totalProductCost.add(c.getProductCost() != null ? c.getProductCost() : BigDecimal.ZERO); - totalShippingCost = totalShippingCost.add(c.getShippingCost() != null ? c.getShippingCost() : BigDecimal.ZERO); - totalOtherCost = totalOtherCost.add(c.getOtherCost() != null ? c.getOtherCost() : BigDecimal.ZERO); - totalRefund = totalRefund.add(c.getRefundAmount() != null ? c.getRefundAmount() : BigDecimal.ZERO); - totalPromoFee = totalPromoFee.add(c.getTotalPromotionFee() != null ? c.getTotalPromotionFee() : BigDecimal.ZERO); - totalBrushFee = totalBrushFee.add(c.getBrushFee() != null ? c.getBrushFee() : BigDecimal.ZERO); - } - - BigDecimal avgOrderValue = totalOrders > 0 - ? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); - BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund) - .subtract(totalPromoFee).subtract(totalBrushFee); - BigDecimal salesTax = toSalesTaxAmount(totalSales, totalRefund); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); - BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 - ? totalSales.subtract(totalRefund).divide(totalPromoFee, 2, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 - ? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - - ShopOverviewStatisticsVO.CategorySummary total = new ShopOverviewStatisticsVO.CategorySummary(); - total.setCategoryId(0L); - total.setCategoryName("合计"); - total.setSalesAmount(totalSales); - total.setOrderCount(totalOrders); - total.setAverageOrderValue(avgOrderValue); - total.setProductCost(totalProductCost); - total.setShippingCost(totalShippingCost); - total.setOtherCost(totalOtherCost); - total.setOrderCost(totalCost); - total.setRefundAmount(totalRefund); - total.setTotalPromotionFee(totalPromoFee); - total.setBrushFee(totalBrushFee); - total.setFeeRatio(feeRatio); - total.setTotalProfitBeforeTax(profitBeforeTax); - total.setSalesTaxAmount(salesTax); - total.setRoi(roi); - total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - return total; - } - - private static ShopOverviewStatisticsVO.ProductOverview mapProductOverview(CompanyOverviewVO.CategoryOverview table) { - if (table == null) { - return new ShopOverviewStatisticsVO.ProductOverview(); - } - ShopOverviewStatisticsVO.ProductOverview po = new ShopOverviewStatisticsVO.ProductOverview(); - po.setTotal(mapCategorySummaryToProductTotal(table.getTotal())); - if (table.getCategories() != null) { - po.setProducts(table.getCategories().stream().map(c -> { - ShopOverviewStatisticsVO.ProductSummary p = new ShopOverviewStatisticsVO.ProductSummary(); - p.setProductId(c.getCategoryId()); - p.setProductName(c.getCategoryName()); - p.setSalesAmount(c.getSalesAmount()); - p.setOrderCount(c.getOrderCount()); - p.setProfitAfterTax(c.getProfitAfterTax()); - return p; - }).collect(Collectors.toList())); - } - return po; - } - - private static ShopOverviewStatisticsVO.CategoryOverview mapCategoryOverview(CompanyOverviewVO.CategoryOverview table) { - if (table == null) { - return new ShopOverviewStatisticsVO.CategoryOverview(); - } - ShopOverviewStatisticsVO.CategoryOverview co = new ShopOverviewStatisticsVO.CategoryOverview(); - co.setTotal(mapCategorySummaryToShopCategoryTotal(table.getTotal())); - if (table.getCategories() != null) { - co.setCategories(table.getCategories().stream().map(c -> { - ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary(); - s.setCategoryId(c.getCategoryId()); - s.setCategoryName(c.getCategoryName()); - s.setSalesAmount(c.getSalesAmount()); - s.setOrderCount(c.getOrderCount()); - s.setProfitAfterTax(c.getProfitAfterTax()); - return s; - }).collect(Collectors.toList())); - } - return co; - } - - private static ShopOverviewStatisticsVO.ProductSummary mapCategorySummaryToProductTotal(CompanyOverviewVO.CategorySummary t) { - ShopOverviewStatisticsVO.ProductSummary p = new ShopOverviewStatisticsVO.ProductSummary(); - if (t == null) { - return p; - } - p.setSalesAmount(t.getSalesAmount()); - p.setOrderCount(t.getOrderCount()); - p.setProfitAfterTax(t.getProfitAfterTax()); - return p; - } - - private static ShopOverviewStatisticsVO.CategorySummary mapCategorySummaryToShopCategoryTotal(CompanyOverviewVO.CategorySummary t) { - ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary(); - if (t == null) { - return s; - } - s.setSalesAmount(t.getSalesAmount()); - s.setOrderCount(t.getOrderCount()); - s.setProfitAfterTax(t.getProfitAfterTax()); - return s; - } - - private static BigDecimal nz(BigDecimal v) { - return v != null ? v : BigDecimal.ZERO; - } -} - diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/controller/ProductOverviewController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/controller/ProductOverviewController.java deleted file mode 100644 index 5d461ae4..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/controller/ProductOverviewController.java +++ /dev/null @@ -1,39 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.product.overview.controller; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.tags.Tag; -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.ec.product.overview.model.dto.ProductOverviewQueryDTO; -import top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.vo.ProductOverviewVO; -import top.xyquan.ecomdmbbackend.modules.ec.product.overview.service.ProductOverviewService; - -/** - * 商品概览控制器 - */ -@Tag(name = "电商-商品概览", description = "商品统计概览接口") -@RestController -@RequestMapping("/ec/product") -public class ProductOverviewController { - - private final ProductOverviewService productOverviewService; - - public ProductOverviewController(ProductOverviewService productOverviewService) { - this.productOverviewService = productOverviewService; - } - - @Operation(summary = "获取商品总览", description = "获取指定商品在日期范围内的销售额、订单数、客单价、成本、退款金额、推广费、费比等统计数据") - @PostMapping("/overview") - @RequirePermission(value = "ecom:product:read", description = "查询商品总览", allowSuper = true) - public ApiResponse getProductOverview( - @Valid @RequestBody ProductOverviewQueryDTO queryDTO) { - ProductOverviewVO overview = productOverviewService.getProductOverview(queryDTO); - return ApiResponse.success("获取商品总览成功", overview); - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/service/ProductOverviewService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/service/ProductOverviewService.java deleted file mode 100644 index a0c2fc39..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/service/ProductOverviewService.java +++ /dev/null @@ -1,18 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.product.overview.service; - -import top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.dto.ProductOverviewQueryDTO; -import top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.vo.ProductOverviewVO; - -/** - * 商品概览服务接口 - */ -public interface ProductOverviewService { - - /** - * 获取商品总览统计数据 - * - * @param queryDTO 查询参数(商品ID + 日期范围) - * @return 商品总览数据 - */ - ProductOverviewVO getProductOverview(ProductOverviewQueryDTO queryDTO); -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/service/impl/ProductOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/service/impl/ProductOverviewServiceImpl.java deleted file mode 100644 index 33d833ee..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/overview/service/impl/ProductOverviewServiceImpl.java +++ /dev/null @@ -1,834 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.product.overview.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import org.springframework.stereotype.Service; -import top.xyquan.ecomdmbbackend.common.exception.BusinessException; -import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO; -import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper; -import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO; -import top.xyquan.ecomdmbbackend.modules.ec.order.support.OrderOverviewSupport; -import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver; -import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets; -import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO; -import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO; -import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductSkuMapper; -import top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.dto.ProductOverviewQueryDTO; -import top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.vo.ProductOverviewVO; -import top.xyquan.ecomdmbbackend.modules.ec.product.overview.service.ProductOverviewService; -import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductService; -import top.xyquan.ecomdmbbackend.modules.ec.promotion.mapper.PromotionFeeMapper; -import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO; -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; -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.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.*; -import java.util.stream.Collectors; - -/** - * 商品概览服务实现类 - */ -@Service -public class ProductOverviewServiceImpl implements ProductOverviewService { - - private final CurrentUserContext currentUserContext; - private final OrderMapper orderMapper; - private final OrderItemMapper orderItemMapper; - private final PromotionFeeMapper promotionFeeMapper; - private final OrderStatusStatResolver orderStatusStatResolver; - private final ProductService productService; - private final ProductSkuMapper productSkuMapper; - private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; - private final ShopService shopService; - - public ProductOverviewServiceImpl(CurrentUserContext currentUserContext, - OrderMapper orderMapper, - OrderItemMapper orderItemMapper, - PromotionFeeMapper promotionFeeMapper, - OrderStatusStatResolver orderStatusStatResolver, - ProductService productService, - ProductSkuMapper productSkuMapper, - ShopMonthlyTargetMapper shopMonthlyTargetMapper, - ShopService shopService) { - this.currentUserContext = currentUserContext; - this.orderMapper = orderMapper; - this.orderItemMapper = orderItemMapper; - this.promotionFeeMapper = promotionFeeMapper; - this.orderStatusStatResolver = orderStatusStatResolver; - this.productService = productService; - this.productSkuMapper = productSkuMapper; - this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; - this.shopService = shopService; - } - - private void applyProductOverviewOrderScope(LambdaQueryWrapper wrapper, - Long companyId, - Long productId, - Long shopId, - LocalDateTime startDateTime, - LocalDateTime endDateTime, - List unionStatusCodes) { - wrapper.eq(OrderPO::getCompanyId, companyId) - .apply("EXISTS (SELECT 1 FROM ec_order_item i WHERE i.order_id = ec_order.id AND i.product_id = {0})", - productId) - .ge(OrderPO::getOrderTime, startDateTime) - .le(OrderPO::getOrderTime, endDateTime); - if (shopId != null) { - wrapper.eq(OrderPO::getShopId, shopId); - } - if (!unionStatusCodes.isEmpty()) { - wrapper.in(OrderPO::getStatus, unionStatusCodes); - } else { - wrapper.isNull(OrderPO::getId); - } - } - - /** 税额 = max(0, 销售额 − 退款) × 税率,保留两位小数。 */ - private static BigDecimal salesTaxOnNetSales(BigDecimal salesAmount, BigDecimal refundAmount, BigDecimal taxRate) { - BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO; - BigDecimal refund = refundAmount != null ? refundAmount : BigDecimal.ZERO; - BigDecimal rate = taxRate != null ? taxRate : new BigDecimal("0.04"); - BigDecimal base = sales.subtract(refund); - if (base.compareTo(BigDecimal.ZERO) < 0) { - base = BigDecimal.ZERO; - } - return base.multiply(rate).setScale(2, RoundingMode.HALF_UP); - } - - @Override - public ProductOverviewVO getProductOverview(ProductOverviewQueryDTO queryDTO) { - Long companyId = currentUserContext.getCurrentCompanyId(); - - // 验证商品是否存在 - ProductPO product = productService.getById(queryDTO.getProductId()); - if (product == null || !product.getCompanyId().equals(companyId)) { - throw new BusinessException("商品不存在"); - } - - // 验证日期范围 - if (queryDTO.getStartDate().isAfter(queryDTO.getEndDate())) { - throw new BusinessException("开始日期不能晚于结束日期"); - } - - Long filterShopId = queryDTO.getShopId(); - if (filterShopId != null) { - ShopPO shop = shopService.getById(filterShopId); - if (shop == null || !shop.getCompanyId().equals(companyId)) { - throw new BusinessException("店铺不存在"); - } - } - - LocalDate startDate = queryDTO.getStartDate(); - LocalDate endDate = queryDTO.getEndDate(); - LocalDateTime startDateTime = startDate.atStartOfDay(); - LocalDateTime endDateTime = endDate.atTime(23, 59, 59); - - // 税率 - BigDecimal taxRate = queryDTO.getTaxRate() != null - ? queryDTO.getTaxRate() - : new BigDecimal("0.04"); - - OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); - List unionStatusCodes = stat.getUnionStatusCodes(); - - // 查询订单数据 - LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); - applyProductOverviewOrderScope(orderWrapper, companyId, queryDTO.getProductId(), filterShopId, - startDateTime, endDateTime, unionStatusCodes); - List orders = orderMapper.selectList(orderWrapper); - - // 推广费/达成率所用店铺:指定店铺时固定该店,否则取订单涉及店铺 - List shopIds; - if (filterShopId != null) { - shopIds = List.of(filterShopId); - } else { - shopIds = orders.stream() - .map(OrderPO::getShopId) - .filter(Objects::nonNull) - .distinct() - .collect(Collectors.toList()); - } - - // 查询推广费(相关店铺 + 日期) - List promotionFees = new ArrayList<>(); - if (!shopIds.isEmpty()) { - LambdaQueryWrapper promoWrapper = new LambdaQueryWrapper<>(); - promoWrapper.eq(PromotionFeePO::getCompanyId, companyId) - .in(PromotionFeePO::getShopId, shopIds) - .ge(PromotionFeePO::getFeeDate, startDate) - .le(PromotionFeePO::getFeeDate, endDate); - promotionFees = promotionFeeMapper.selectList(promoWrapper); - } - - // 店铺维度全部订单(推广费按商品/类目/全店口径分摊,与店铺概览商品汇总一致) - List allShopOrdersForPromo = new ArrayList<>(); - if (!shopIds.isEmpty()) { - LambdaQueryWrapper allOrdersWrapper = new LambdaQueryWrapper<>(); - allOrdersWrapper.eq(OrderPO::getCompanyId, companyId) - .in(OrderPO::getShopId, shopIds) - .ge(OrderPO::getOrderTime, startDateTime) - .le(OrderPO::getOrderTime, endDateTime); - if (!unionStatusCodes.isEmpty()) { - allOrdersWrapper.in(OrderPO::getStatus, unionStatusCodes); - } else { - allOrdersWrapper.isNull(OrderPO::getId); - } - allShopOrdersForPromo = orderMapper.selectList(allOrdersWrapper); - } - - // 查询上月同期数据(用于环比计算) - long dayCount = ChronoUnit.DAYS.between(startDate, endDate) + 1; - LocalDate lastStartDate = startDate.minusDays(dayCount); - LocalDate lastEndDate = startDate.minusDays(1); - LocalDateTime lastStartTime = lastStartDate.atStartOfDay(); - LocalDateTime lastEndTime = lastEndDate.atTime(23, 59, 59); - - LambdaQueryWrapper lastPeriodWrapper = new LambdaQueryWrapper<>(); - applyProductOverviewOrderScope(lastPeriodWrapper, companyId, queryDTO.getProductId(), filterShopId, - lastStartTime, lastEndTime, unionStatusCodes); - List lastPeriodOrders = orderMapper.selectList(lastPeriodWrapper); - - // ========== 构建返回对象 ========== - ProductOverviewVO vo = new ProductOverviewVO(); - vo.setProductId(product.getId()); - vo.setProductName(product.getName()); - - // ---------- KPI 汇总指标 ---------- - // 总销售额(按状态「计入销售额」维度) - BigDecimal totalSalesAmount = orders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - vo.setTotalSalesAmount(totalSalesAmount); - - // 总订单量(按状态「计入销售额」维度计单,与店铺概览一致) - int totalOrderCount = (int) orders.stream() - .filter(o -> stat.includesSales(o.getStatus())) - .count(); - vo.setTotalOrderCount(totalOrderCount); - - // 总退款金额(用于 ROI 计算) - BigDecimal totalRefundAmount = orders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 订单成本(商品/运费/其他成本按各维度开关,含数量) - BigDecimal totalCostAmount = orders.stream() - .map(stat::totalCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - vo.setAverageFeeRatio(null); // 由 spec 维度均化,待后面补充 - - // 总推广费(与 ShopOverviewStatisticsServiceImpl 商品维度推广费归属一致) - BigDecimal totalPromotionFee = computeAttributedPromotionForProduct( - queryDTO.getProductId(), - product, - allShopOrdersForPromo, - promotionFees, - stat); - - // 费比 - BigDecimal avgFeeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0 - ? totalPromotionFee.divide(totalSalesAmount, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - vo.setAverageFeeRatio(avgFeeRatio.multiply(new BigDecimal("100")) - .setScale(2, RoundingMode.HALF_UP)); // 转为百分比 - - BigDecimal totalTaxAmount = salesTaxOnNetSales(totalSalesAmount, totalRefundAmount, taxRate); - vo.setTotalTaxAmount(totalTaxAmount); - - // 税后盈亏 - BigDecimal totalProfitAfterTax = totalSalesAmount - .subtract(totalCostAmount) - .subtract(totalRefundAmount) - .subtract(totalPromotionFee) - .subtract(totalTaxAmount); - vo.setTotalNetProfitAfterTax(totalProfitAfterTax.setScale(2, RoundingMode.HALF_UP)); - - // ROI = (销售额 - 退款金额) / 推广费(与店铺概览 calculateSalesROI 口径一致) - BigDecimal totalROI = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0 - ? totalSalesAmount.subtract(totalRefundAmount) - .divide(totalPromotionFee, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - vo.setTotalROI(totalROI); - - // ---------- 环比增长(上月同期) ---------- - BigDecimal lastPeriodSales = lastPeriodOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal monthOverMonthGrowth = BigDecimal.ZERO; - if (lastPeriodSales.compareTo(BigDecimal.ZERO) > 0) { - monthOverMonthGrowth = totalSalesAmount - .subtract(lastPeriodSales) - .divide(lastPeriodSales, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) - .setScale(2, RoundingMode.HALF_UP); - } else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - monthOverMonthGrowth = new BigDecimal("100.00"); - } - vo.setMonthOverMonthGrowth(monthOverMonthGrowth); - - // ---------- 达成率(简化:按店铺月度目标计算) ---------- - if (!shopIds.isEmpty()) { - LocalDate firstDayOfMonth = startDate.withDayOfMonth(1); - LocalDate lastDayOfMonth = endDate.withDayOfMonth(endDate.lengthOfMonth()); - - LambdaQueryWrapper targetWrapper = new LambdaQueryWrapper<>(); - targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId) - .in(ShopMonthlyTargetPO::getShopId, shopIds) - .ge(ShopMonthlyTargetPO::getTargetMonth, firstDayOfMonth) - .le(ShopMonthlyTargetPO::getTargetMonth, lastDayOfMonth); - List shopTargets = shopMonthlyTargetMapper.selectList(targetWrapper); - - BigDecimal totalTargetAmount = shopTargets.stream() - .map(ShopMonthlyTargetPO::getTargetAmount) - .filter(Objects::nonNull) - .reduce(BigDecimal.ZERO, BigDecimal::add); - int totalTargetOrderCount = shopTargets.stream() - .map(ShopMonthlyTargetPO::getTargetOrderCount) - .filter(Objects::nonNull) - .mapToInt(Integer::intValue) - .sum(); - - if (totalTargetAmount.compareTo(BigDecimal.ZERO) > 0) { - BigDecimal salesRate = totalSalesAmount - .divide(totalTargetAmount, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) - .setScale(2, RoundingMode.HALF_UP); - vo.setSalesAmountAchievementRate(salesRate); - } - if (totalTargetOrderCount > 0) { - BigDecimal orderRate = BigDecimal.valueOf((long) totalOrderCount) - .divide(BigDecimal.valueOf(totalTargetOrderCount), 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) - .setScale(2, RoundingMode.HALF_UP); - vo.setOrderCountAchievementRate(orderRate); - } - } - - // ---------- 趋势数据 ---------- - vo.setSalesAmountTrend(buildTrend(orders, dateList -> dateList.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add), startDate, endDate)); - - vo.setOrderCountTrend(buildOrderCountTrend(orders, stat, startDate, endDate)); - - // ---------- 规格销售汇总 ---------- - vo.setSpecSummaries(buildSpecSummary(orders, stat, taxRate, totalPromotionFee)); - - // ---------- 各规格销量 Top10 ---------- - vo.setSpecSalesTop10(buildSpecSalesTop10(orders, stat, shopIds)); - - return vo; - } - - /** - * 构建销售趋势 - */ - private ProductOverviewVO.TrendData buildTrend(List orders, - java.util.function.Function, BigDecimal> reducer, - LocalDate startDate, LocalDate endDate) { - Map> ordersByDate = orders.stream() - .collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate())); - - List dailyList = new ArrayList<>(); - LocalDate current = startDate; - while (!current.isAfter(endDate)) { - List dayOrders = ordersByDate.getOrDefault(current, List.of()); - BigDecimal value = reducer.apply(dayOrders); - - ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem(); - item.setDate(current); - item.setValue(value); - dailyList.add(item); - current = current.plusDays(1); - } - - BigDecimal total = dailyList.stream() - .map(ProductOverviewVO.TrendDataItem::getValue) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData(); - trend.setTotal(total); - trend.setDailyDataList(dailyList); - return trend; - } - - /** - * 构建订单数趋势 - */ - private ProductOverviewVO.TrendData buildOrderCountTrend(List orders, - OrderStatusStatSets stat, - LocalDate startDate, LocalDate endDate) { - Map> ordersByDate = orders.stream() - .collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate())); - - List dailyList = new ArrayList<>(); - LocalDate current = startDate; - while (!current.isAfter(endDate)) { - List dayOrders = ordersByDate.getOrDefault(current, List.of()); - long count = dayOrders.stream() - .filter(o -> stat.includesSales(o.getStatus())) - .count(); - - ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem(); - item.setDate(current); - item.setValue(BigDecimal.valueOf(count)); - dailyList.add(item); - current = current.plusDays(1); - } - - long sumDaily = dailyList.stream().mapToLong(i -> i.getValue().longValue()).sum(); - BigDecimal total = BigDecimal.valueOf(sumDaily); - - ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData(); - trend.setTotal(total); - trend.setDailyDataList(dailyList); - return trend; - } - - private Map orderSpecIdToProductIdMapForOverview(List orders) { - return OrderOverviewSupport.orderSpecIdToProductIdMap(productSkuMapper, orderItemMapper, orders); - } - - /** - * 将店铺范围内推广费归属到指定商品(与店铺概览「按商品汇总」推广费口径一致) - */ - private BigDecimal computeAttributedPromotionForProduct( - Long productId, - ProductPO product, - List allShopOrders, - List promotionFees, - OrderStatusStatSets stat) { - if (productId == null || allShopOrders == null || allShopOrders.isEmpty()) { - return promotionFees.stream() - .filter(f -> productId != null && productId.equals(f.getProductId())) - .map(f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - } - - Map skuToProduct = orderSpecIdToProductIdMapForOverview(allShopOrders); - Map firstItems = OrderOverviewSupport.firstItemsForOrders(orderItemMapper, allShopOrders); - Map> ordersByProduct = allShopOrders.stream() - .collect(Collectors.groupingBy(o -> - OrderOverviewSupport.productIdOfOrder(o, firstItems, skuToProduct))); - - Map directPromotionByProduct = promotionFees.stream() - .filter(fee -> fee.getProductId() != null) - .collect(Collectors.groupingBy( - PromotionFeePO::getProductId, - Collectors.reducing( - BigDecimal.ZERO, - fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); - - Map categoryOnlyPool = promotionFees.stream() - .filter(fee -> fee.getProductId() == null && fee.getCategoryId() != null) - .collect(Collectors.groupingBy( - PromotionFeePO::getCategoryId, - Collectors.reducing( - BigDecimal.ZERO, - fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); - - BigDecimal globalRatioPool = promotionFees.stream() - .filter(fee -> fee.getProductId() == null && fee.getCategoryId() == null) - .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - Map productPromotionFromCategory = new HashMap<>(); - for (Map.Entry catEntry : categoryOnlyPool.entrySet()) { - Long catId = catEntry.getKey(); - BigDecimal pool = catEntry.getValue(); - if (catId == null || pool == null || pool.compareTo(BigDecimal.ZERO) <= 0) { - continue; - } - Map eligibleSalesByProduct = new HashMap<>(); - for (Map.Entry> e : ordersByProduct.entrySet()) { - Long pid = e.getKey(); - if (pid == null || pid < 0) { - continue; - } - BigDecimal direct = directPromotionByProduct.getOrDefault(pid, BigDecimal.ZERO); - if (direct.compareTo(BigDecimal.ZERO) > 0) { - continue; - } - ProductPO p = productService.getById(pid); - if (p == null || !Objects.equals(p.getCategoryId(), catId)) { - continue; - } - BigDecimal sal = e.getValue().stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - eligibleSalesByProduct.put(pid, sal); - } - BigDecimal totalElig = eligibleSalesByProduct.values().stream() - .reduce(BigDecimal.ZERO, BigDecimal::add); - if (totalElig.compareTo(BigDecimal.ZERO) <= 0) { - globalRatioPool = globalRatioPool.add(pool); - continue; - } - for (Map.Entry pe : eligibleSalesByProduct.entrySet()) { - BigDecimal share = pool.multiply(pe.getValue()) - .divide(totalElig, 4, RoundingMode.HALF_UP); - productPromotionFromCategory.merge(pe.getKey(), share, BigDecimal::add); - } - } - - Map salesByProduct = ordersByProduct.entrySet().stream() - .collect(Collectors.toMap( - Map.Entry::getKey, - e -> e.getValue().stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add))); - BigDecimal totalSalesAmount = salesByProduct.values().stream() - .reduce(BigDecimal.ZERO, BigDecimal::add); - - List productOrders = ordersByProduct.getOrDefault(productId, Collections.emptyList()); - BigDecimal salesAmount = productOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal productPromotionFee = directPromotionByProduct.getOrDefault(productId, BigDecimal.ZERO) - .add(productPromotionFromCategory.getOrDefault(productId, BigDecimal.ZERO)); - if (productPromotionFee.compareTo(BigDecimal.ZERO) == 0 - && globalRatioPool.compareTo(BigDecimal.ZERO) > 0 - && totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { - BigDecimal ratio = salesAmount.divide(totalSalesAmount, 4, RoundingMode.HALF_UP); - productPromotionFee = globalRatioPool.multiply(ratio); - } - return productPromotionFee; - } - - /** - * 构建规格销售汇总(推广费总额为已归属到本商品的金额,再按规格订单数比例拆到各规格) - */ - private ProductOverviewVO.SpecSummary buildSpecSummary(List orders, - OrderStatusStatSets stat, - BigDecimal taxRate, - BigDecimal attributedPromotionForProduct) { - // 查询商品所有规格 - if (orders.isEmpty()) { - return buildEmptySpecSummary(); - } - - OrderPO firstOrder = orders.get(0); - Long companyId = firstOrder.getCompanyId(); - Map firstItems = OrderOverviewSupport.firstItemsForOrders(orderItemMapper, orders); - OrderItemPO firstItem = firstItems.get(firstOrder.getId()); - Long productId = firstItem != null ? firstItem.getProductId() : null; - if (productId == null && firstItem != null && firstItem.getProductSkuId() != null) { - ProductSkuPO firstSpec = productSkuMapper.selectById(firstItem.getProductSkuId()); - if (firstSpec != null) { - productId = firstSpec.getProductId(); - } - } - if (productId == null) { - return buildEmptySpecSummary(); - } - - LambdaQueryWrapper skuWrapper = new LambdaQueryWrapper<>(); - skuWrapper.eq(ProductSkuPO::getCompanyId, companyId) - .eq(ProductSkuPO::getProductId, productId); - List allSkus = productSkuMapper.selectList(skuWrapper); - Map skuMap = allSkus.stream() - .collect(Collectors.toMap(ProductSkuPO::getId, s -> s, (a, b) -> a)); - - BigDecimal totalAttributed = attributedPromotionForProduct != null - ? attributedPromotionForProduct - : BigDecimal.ZERO; - - // 按规格分组订单 - Map> ordersBySpec = orders.stream() - .collect(Collectors.groupingBy(o -> { - OrderItemPO item = firstItems.get(o.getId()); - Long skuId = item != null ? item.getProductSkuId() : null; - return skuId != null ? skuId : 0L; - })); - - List specItems = new ArrayList<>(); - - for (Map.Entry> entry : ordersBySpec.entrySet()) { - Long skuId = entry.getKey(); - if (skuId == 0L) continue; // 跳过未关联规格的订单 - - List specOrders = entry.getValue(); - ProductSkuPO spec = skuMap.get(skuId); - - // 该规格的销售额(计入销售额维度) - BigDecimal salesAmount = specOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 该规格的订单量(计入销售额维度计单) - int orderCount = (int) specOrders.stream() - .filter(o -> stat.includesSales(o.getStatus())) - .count(); - - // 总件数 - int quantity = specOrders.stream() - .mapToInt(o -> { - OrderItemPO item = firstItems.get(o.getId()); - return item != null && item.getQuantity() != null ? item.getQuantity() : 1; - }) - .sum(); - - // 客单价 - BigDecimal avgOV = orderCount > 0 - ? salesAmount.divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - - // 商品 / 运费 / 其他成本(各维度开关 + 数量,与店铺商品对比一致) - BigDecimal productCostTotal = specOrders.stream() - .map(stat::productCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal shippingCostTotal = specOrders.stream() - .map(stat::freightCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal otherCostTotal = specOrders.stream() - .map(stat::otherCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal totalCostStat = specOrders.stream() - .map(stat::totalCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 退款金额(计入退款维度) - BigDecimal refundAmount = specOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 推广费分摊(按该规格订单数占所有订单数比例) - int totalOrderCountAll = orders.size(); - BigDecimal specPromotionFee = BigDecimal.ZERO; - if (totalOrderCountAll > 0) { - BigDecimal proportion = BigDecimal.valueOf((long) orderCount) - .divide(BigDecimal.valueOf(totalOrderCountAll), 4, RoundingMode.HALF_UP); - specPromotionFee = totalAttributed.multiply(proportion) - .setScale(2, RoundingMode.HALF_UP); - } - - // 费比 - BigDecimal feeRatio = salesAmount.compareTo(BigDecimal.ZERO) > 0 - ? specPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - - // 税前净利(与店铺商品对比:销售额 - 订单成本 - 退款金额 - 推广费) - BigDecimal profitBeforeTax = salesAmount - .subtract(totalCostStat) - .subtract(refundAmount) - .subtract(specPromotionFee); - - BigDecimal salesTaxAmount = salesTaxOnNetSales(salesAmount, refundAmount, taxRate); - - // ROI = (销售额 - 退款) / 推广费 - BigDecimal roi = specPromotionFee.compareTo(BigDecimal.ZERO) > 0 - ? salesAmount.subtract(refundAmount) - .divide(specPromotionFee, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - - // 税后盈亏 - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount); - - ProductOverviewVO.SpecSummaryItem item = new ProductOverviewVO.SpecSummaryItem(); - item.setSkuId(skuId); - item.setSkuName(spec != null ? spec.getName() : "未知规格"); - item.setSkuCode(spec != null ? spec.getSkuCode() : null); - item.setSalesAmount(salesAmount); - item.setOrderCount(orderCount); - item.setQuantity(quantity); - item.setAverageOrderValue(avgOV); - item.setProductCost(productCostTotal); - item.setShippingCost(shippingCostTotal); - item.setOtherCost(otherCostTotal); - item.setOrderCost(totalCostStat); - item.setRefundAmount(refundAmount); - item.setPromotionFee(specPromotionFee); - item.setFeeRatio(feeRatio.multiply(new BigDecimal("100")) - .setScale(2, RoundingMode.HALF_UP)); - item.setProfitBeforeTax(profitBeforeTax); - item.setSalesTaxAmount(salesTaxAmount); - item.setRoi(roi); - item.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - - specItems.add(item); - } - - // 构建合计行 - ProductOverviewVO.SpecSummaryTotal total = new ProductOverviewVO.SpecSummaryTotal(); - total.setSalesAmount(specItems.stream() - .map(ProductOverviewVO.SpecSummaryItem::getSalesAmount) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setOrderCount(specItems.stream() - .mapToInt(ProductOverviewVO.SpecSummaryItem::getOrderCount).sum()); - total.setQuantity(specItems.stream() - .mapToInt(ProductOverviewVO.SpecSummaryItem::getQuantity).sum()); - total.setProductCost(specItems.stream() - .map(ProductOverviewVO.SpecSummaryItem::getProductCost) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setShippingCost(specItems.stream() - .map(ProductOverviewVO.SpecSummaryItem::getShippingCost) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setOtherCost(specItems.stream() - .map(ProductOverviewVO.SpecSummaryItem::getOtherCost) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setOrderCost(specItems.stream() - .map(ProductOverviewVO.SpecSummaryItem::getOrderCost) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setRefundAmount(specItems.stream() - .map(ProductOverviewVO.SpecSummaryItem::getRefundAmount) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setPromotionFee(specItems.stream() - .map(ProductOverviewVO.SpecSummaryItem::getPromotionFee) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - - BigDecimal totalSalesAmt = total.getSalesAmount(); - BigDecimal totalPromoFee = total.getPromotionFee(); - BigDecimal totalFeeRatio = totalSalesAmt.compareTo(BigDecimal.ZERO) > 0 - ? totalPromoFee.divide(totalSalesAmt, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - total.setFeeRatio(totalFeeRatio.multiply(new BigDecimal("100")) - .setScale(2, RoundingMode.HALF_UP)); - - BigDecimal totalProfitBT = total.getSalesAmount() - .subtract(total.getOrderCost()) - .subtract(total.getRefundAmount()) - .subtract(total.getPromotionFee()); - total.setProfitBeforeTax(totalProfitBT); - - BigDecimal totalRefundAgg = total.getRefundAmount(); - BigDecimal totalSalesTax = salesTaxOnNetSales(totalSalesAmt, totalRefundAgg, taxRate); - total.setSalesTaxAmount(totalSalesTax); - - BigDecimal totalRefundForRoi = totalRefundAgg; - BigDecimal totalRoi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 - ? totalSalesAmt.subtract(totalRefundForRoi) - .divide(totalPromoFee, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - total.setRoi(totalRoi); - - total.setProfitAfterTax(totalProfitBT.subtract(totalSalesTax).setScale(2, RoundingMode.HALF_UP)); - - ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary(); - summary.setList(specItems); - summary.setTotal(total); - - return summary; - } - - private ProductOverviewVO.SpecSummary buildEmptySpecSummary() { - ProductOverviewVO.SpecSummaryTotal total = new ProductOverviewVO.SpecSummaryTotal(); - total.setSalesAmount(BigDecimal.ZERO); - total.setOrderCount(0); - total.setQuantity(0); - total.setProductCost(BigDecimal.ZERO); - total.setShippingCost(BigDecimal.ZERO); - total.setOtherCost(BigDecimal.ZERO); - total.setOrderCost(BigDecimal.ZERO); - total.setRefundAmount(BigDecimal.ZERO); - total.setPromotionFee(BigDecimal.ZERO); - total.setFeeRatio(BigDecimal.ZERO); - total.setProfitBeforeTax(BigDecimal.ZERO); - total.setSalesTaxAmount(BigDecimal.ZERO); - total.setRoi(BigDecimal.ZERO); - total.setProfitAfterTax(BigDecimal.ZERO); - - ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary(); - summary.setList(new ArrayList<>()); - summary.setTotal(total); - return summary; - } - - /** - * 构建各规格销量 Top10 - */ - private List buildSpecSalesTop10(List orders, - OrderStatusStatSets stat, - List shopIds) { - if (orders.isEmpty()) { - return new ArrayList<>(); - } - - OrderPO firstOrder = orders.get(0); - Long companyId = firstOrder.getCompanyId(); - Map firstItems = OrderOverviewSupport.firstItemsForOrders(orderItemMapper, orders); - OrderItemPO firstItem = firstItems.get(firstOrder.getId()); - Long productId = firstItem != null ? firstItem.getProductId() : null; - if (productId == null && firstItem != null && firstItem.getProductSkuId() != null) { - ProductSkuPO firstSpec = productSkuMapper.selectById(firstItem.getProductSkuId()); - if (firstSpec != null) { - productId = firstSpec.getProductId(); - } - } - if (productId == null) { - return new ArrayList<>(); - } - - LambdaQueryWrapper skuWrapper = new LambdaQueryWrapper<>(); - skuWrapper.eq(ProductSkuPO::getCompanyId, companyId) - .eq(ProductSkuPO::getProductId, productId); - List allSkus = productSkuMapper.selectList(skuWrapper); - Map skuMap = allSkus.stream() - .collect(Collectors.toMap(ProductSkuPO::getId, s -> s, (a, b) -> a)); - - // 按规格分组计算 - Map> ordersBySpec = orders.stream() - .collect(Collectors.groupingBy(o -> { - OrderItemPO item = firstItems.get(o.getId()); - Long skuId = item != null ? item.getProductSkuId() : null; - return skuId != null ? skuId : 0L; - })); - - List rankItems = new ArrayList<>(); - - for (Map.Entry> entry : ordersBySpec.entrySet()) { - Long skuId = entry.getKey(); - if (skuId == 0L) continue; - - List specOrders = entry.getValue(); - ProductSkuPO spec = skuMap.get(skuId); - - // 订单量(计入销售额维度) - int orderCount = (int) specOrders.stream() - .filter(o -> stat.includesSales(o.getStatus())) - .count(); - - // 销售额 - BigDecimal salesAmount = specOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - ProductOverviewVO.SpecSalesRankItem item = new ProductOverviewVO.SpecSalesRankItem(); - item.setSkuId(skuId); - item.setSkuName(spec != null ? spec.getName() : "未知规格"); - item.setSkuCode(spec != null ? spec.getSkuCode() : null); - item.setOrderCount(orderCount); - item.setSalesAmount(salesAmount); - rankItems.add(item); - } - - // 按订单量降序排序,取前10 - return rankItems.stream() - .sorted(Comparator.comparing(ProductOverviewVO.SpecSalesRankItem::getOrderCount).reversed()) - .limit(10) - .collect(Collectors.toList()); - } - - private static BigDecimal growthPct(BigDecimal cur, BigDecimal prev) { - if (prev.signum() > 0) { - return cur.subtract(prev).divide(prev, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)) - .setScale(2, RoundingMode.HALF_UP); - } - return cur.signum() > 0 ? new BigDecimal("100.00") : BigDecimal.ZERO; - } - - private static BigDecimal nz(BigDecimal v) { - return v != null ? v : BigDecimal.ZERO; - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/shop/service/ShopExportService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/shop/service/ShopExportService.java deleted file mode 100644 index 1c395e6c..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/shop/service/ShopExportService.java +++ /dev/null @@ -1,16 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ec.shop.service; - -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO; -import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopExportDTO; - -/** - * 店铺侧 Excel 导出(按商品汇总、按品类汇总) - */ -public interface ShopExportService { - - /** 单店铺按商品维度汇总 Excel */ - byte[] exportShopSummaryByProduct(ShopExportDTO dto); - - /** 单店铺按品类维度汇总 Excel(与品类概览导出逻辑一致) */ - byte[] exportShopSummaryByCategory(CategoryExportDTO dto); -} 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 671a7c94..f5d67dcb 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 @@ -337,10 +337,6 @@ INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `co SELECT 12010, NULL, 0, '工作台', '工作台', '/dashboard/workbench', '/dashboard/workbench/index', '', 'icon-park-outline:workbench', 'menu', 1, 1, 1, 1 FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '工作台'); -INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`) -SELECT 12011, NULL, 0, '全店概览', '全店概览', '/store-overview', '/dashboard/store-overview/index', '', 'lucide:line-chart', 'menu', 0, 1, 1, 2 -FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '全店概览'); - INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`) SELECT 12012, NULL, 0, '订单导入', '订单导入', '/import/order', '/ecommerce/import/order/index', '', 'lucide:upload', 'menu', 1, 1, 0, 3 FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '订单导入'); diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/product-overview/apis.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/product-overview/apis.ts index 6a4f0457..05db7f87 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/product-overview/apis.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/product-overview/apis.ts @@ -11,7 +11,7 @@ import { requestClient } from '#/api/request'; */ export async function getProductOverviewApi(params: ProductOverviewDTO.Query) { return requestClient.post( - '/ec/product/overview', + '/bi/product/overview', params, ); } diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/shop/apis.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/shop/apis.ts index 8c0a165d..b6519e05 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/shop/apis.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/shop/apis.ts @@ -62,6 +62,20 @@ export async function getShopProductPageApi( ); } +/** + * 店铺概览统计(BI:Mongo 订单日汇聚) + */ +export async function getShopOverviewApi(params: { + shopId: number; + dateRange: string[]; + taxRate?: number; +}) { + return requestClient.post( + '/bi/shop/overview', + params, + ); +} + /** * 店铺数据统计-按商品汇总(Excel) */ @@ -70,20 +84,7 @@ export async function exportShopSummaryByProductApi(params: { dateRange: string[]; exportType?: string; }) { - return requestClient.post('/ec/shop/export/summary-by-product', params, { - responseType: 'blob', - }); -} - -/** - * 全店概览-按店铺汇总(Excel) - */ -export async function exportCompanyOverviewApi(params: { - dateRange: string[]; - shopIds?: number[]; - exportType?: string; -}) { - return requestClient.post('/ec/store-overview/export/by-shop', params, { + return requestClient.post('/bi/shop/export/summary-by-product', params, { responseType: 'blob', }); } diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/apis.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/apis.ts deleted file mode 100644 index d3b87217..00000000 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/apis.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { CompanyOverviewDTO, CompanyOverviewVO } from './types'; - -import { requestClient } from '#/api/request'; - -/** - * 全店概览 API(统计与导出) - */ - -/** - * 获取全店概览统计数据 - */ -export async function getCompanyOverviewApi(data: CompanyOverviewDTO.Query) { - return requestClient.post( - '/ec/store/overview', - data, - ); -} - -/** - * 全店概览-按品类汇总(Excel) - */ -export async function exportCategoryOverviewApi(params: { - dateRange: string[]; - categoryIds?: number[]; - taxRate: number; -}) { - return requestClient.post('/ec/store-overview/export/by-category', params, { - responseType: 'blob', - }); -} - -/** - * 全店概览-按店铺汇总(Excel) - */ -export async function exportCompanyOverviewApi(params: { - dateRange: string[]; - shopIds?: number[]; - exportType?: string; -}) { - return requestClient.post('/ec/store-overview/export/by-shop', params, { - responseType: 'blob', - }); -} diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/index.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/index.ts index df2562e9..11a39e38 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/index.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/index.ts @@ -1,6 +1,4 @@ /** - * 全店铺概览管理模块API导出 + * 工作台底表等复用的汇总表类型(原全店概览 VO,页面已下线)。 */ - -export * from './apis'; export * from './types'; diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/index.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/index.ts index 81a09cd8..af2a639e 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/index.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/index.ts @@ -1,6 +1,4 @@ /** - * 全店铺概览管理模块类型定义导出 + * 工作台汇总表类型(原全店概览 VO 字段,页面已下线)。 */ - -export * from './types.dto'; export * from './types.vo'; diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/types.dto.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/types.dto.ts deleted file mode 100644 index 2500a6d9..00000000 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/types.dto.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * 全店铺概览相关DTO类型定义 - */ - -export namespace CompanyOverviewDTO { - /** 全店铺概览查询参数 */ - export interface Query { - /** 日期范围数组(第一个是开始日期,第二个是结束日期,只有一个日期则返回当天数据) */ - dateRange: string[]; - /** 税率(默认0.04,即4%) */ - taxRate?: number; - } -} diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/types.vo.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/types.vo.ts index ef38062f..49910ede 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/types.vo.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/store-overview/types/types.vo.ts @@ -257,7 +257,7 @@ export namespace CompanyOverviewVO { categories: CategorySummary[]; } - /** 工作台底部四张汇总表(与全店概览同源字段) */ + /** 工作台底部四张汇总表 */ export interface WorkbenchTableBundle { shopTable?: ShopOverview | null; platformTable?: PlatformOverview | null; diff --git a/ecom-dmb-frontend/apps/web-antd/src/locales/langs/en-US/page.json b/ecom-dmb-frontend/apps/web-antd/src/locales/langs/en-US/page.json index 06d03645..8b08fa32 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/locales/langs/en-US/page.json +++ b/ecom-dmb-frontend/apps/web-antd/src/locales/langs/en-US/page.json @@ -20,7 +20,6 @@ "title": "Dashboard", "analytics": "Analytics", "workspace": "Workspace", - "storeOverview": "Store overview", "workbench": "E-commerce operations workbench" } } diff --git a/ecom-dmb-frontend/apps/web-antd/src/locales/langs/zh-CN/page.json b/ecom-dmb-frontend/apps/web-antd/src/locales/langs/zh-CN/page.json index 40b6ea9b..efb18d5d 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/locales/langs/zh-CN/page.json +++ b/ecom-dmb-frontend/apps/web-antd/src/locales/langs/zh-CN/page.json @@ -20,7 +20,6 @@ "title": "概览", "analytics": "分析页", "workspace": "工作台", - "storeOverview": "全店概览", "workbench": "电商运营工作台" } } diff --git a/ecom-dmb-frontend/apps/web-antd/src/router/routes/modules/dashboard.ts b/ecom-dmb-frontend/apps/web-antd/src/router/routes/modules/dashboard.ts index 65532d1c..86ba973e 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/router/routes/modules/dashboard.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/router/routes/modules/dashboard.ts @@ -12,34 +12,16 @@ const routes: RouteRecordRaw[] = [ name: 'Dashboard', path: '/dashboard', children: [ - { - name: 'Analytics', - path: '/store-overview', - component: () => import('#/views/dashboard/store-overview/index.vue'), - meta: { - affixTab: true, - icon: 'lucide:area-chart', - title: $t('page.dashboard.storeOverview'), - }, - }, { name: 'PddWorkbench', path: '/workbench', component: () => import('#/views/dashboard/workbench/index.vue'), meta: { + affixTab: true, icon: 'lucide:gauge', title: $t('page.dashboard.workbench'), }, }, - // { - // name: 'Workspace', - // path: '/workspace', - // component: () => import('#/views/dashboard/workspace/index.vue'), - // meta: { - // icon: 'carbon:workspace', - // title: $t('page.dashboard.workspace'), - // }, - // }, ], }, ]; diff --git a/ecom-dmb-frontend/apps/web-antd/src/utils/overview-date-range.ts b/ecom-dmb-frontend/apps/web-antd/src/utils/overview-date-range.ts index 9bc8449f..469da992 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/utils/overview-date-range.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/utils/overview-date-range.ts @@ -53,7 +53,7 @@ export type OverviewRouteQuery = { shopId?: string; }; -/** 概览页跳转(店铺/商品)时附带的 query,与全店概览一致 */ +/** 概览页跳转(店铺/商品)时附带的 query,与工作台筛选一致 */ export function buildOverviewRouteQuery( dateRange: [Dayjs, Dayjs], options?: { shopId?: number }, diff --git a/ecom-dmb-frontend/apps/web-antd/src/utils/overview-fee-ratio.ts b/ecom-dmb-frontend/apps/web-antd/src/utils/overview-fee-ratio.ts index 66a77904..278b6a9c 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/utils/overview-fee-ratio.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/utils/overview-fee-ratio.ts @@ -1,5 +1,5 @@ /** - * 店铺/全店概览接口:费比 feeRatio / averageFeeRatio 为小数(推广费÷销售额,如 0.05 = 5%)。 + * 店铺/工作台接口:费比 feeRatio / averageFeeRatio 为小数(推广费÷销售额,如 0.05 = 5%)。 * 达成率等字段后端已为 0–100 的数值,勿用本函数。 */ export function formatFeeRatioPercent(value: number | undefined | null): string { diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/CategoryComparisonTable.vue b/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/CategoryComparisonTable.vue deleted file mode 100644 index 9bcdba49..00000000 --- a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/CategoryComparisonTable.vue +++ /dev/null @@ -1,322 +0,0 @@ - - - diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ComparisonSwitcher.vue b/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ComparisonSwitcher.vue deleted file mode 100644 index f9204d69..00000000 --- a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ComparisonSwitcher.vue +++ /dev/null @@ -1,159 +0,0 @@ - - - - - diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/KpiCards.vue b/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/KpiCards.vue deleted file mode 100644 index 840de280..00000000 --- a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/KpiCards.vue +++ /dev/null @@ -1,142 +0,0 @@ - - - diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/PlatformSummaryCard.vue b/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/PlatformSummaryCard.vue deleted file mode 100644 index 830553f4..00000000 --- a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/PlatformSummaryCard.vue +++ /dev/null @@ -1,424 +0,0 @@ - - - diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ShopCharts.vue b/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ShopCharts.vue deleted file mode 100644 index 84ff1b84..00000000 --- a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ShopCharts.vue +++ /dev/null @@ -1,275 +0,0 @@ - - - diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ShopComparisonTable.vue b/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ShopComparisonTable.vue deleted file mode 100644 index d57766b6..00000000 --- a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/components/ShopComparisonTable.vue +++ /dev/null @@ -1,424 +0,0 @@ - - - diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/index.vue b/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/index.vue deleted file mode 100644 index 83612ae2..00000000 --- a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/index.vue +++ /dev/null @@ -1,615 +0,0 @@ - - - - - diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/workbench/index.vue b/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/workbench/index.vue index 8e02d76a..e6a49638 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/workbench/index.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/workbench/index.vue @@ -101,7 +101,7 @@ function goToImportPromotionFee() { void router.push('/import/promotion-fee'); } -/** 与全店概览一致:快捷区间 + 自定义 RangePicker */ +/** 与工作台一致:快捷区间 + 自定义 RangePicker */ const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([ dayjs().startOf('month'), dayjs(), diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/workbench/tabs/finance/components/OverviewTables.vue b/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/workbench/tabs/finance/components/OverviewTables.vue index 748e89b6..0641723e 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/workbench/tabs/finance/components/OverviewTables.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/workbench/tabs/finance/components/OverviewTables.vue @@ -200,7 +200,7 @@ async function handleProductExport() { 销售/毛利/净利/退款(柱)与毛利率、净利率(线)· - {{ liveData ? '接口数据(与全店概览订单口径一致)' : '演示数据' }} + {{ liveData ? '接口数据(与工作台订单口径一致)' : '演示数据' }}

- 按平台、店铺、品类、商品各一张卡;数据与全店概览订单统计口径一致 + 按平台、店铺、品类、商品各一张卡;数据与工作台订单统计口径一致

{ isRequesting.value = true; try { loading.value = true; - // 原 /ec/shop/overview 已下线,待接入 Mongo BI 读模型 + const [startDate, endDate] = dateRange.value; + overviewData.value = await getShopOverviewApi({ + shopId: shopId.value, + dateRange: [ + startDate.format('YYYY-MM-DD'), + endDate.format('YYYY-MM-DD'), + ], + taxRate: taxRate.value, + }); + } catch (err: any) { overviewData.value = null; + message.error(err?.message || '加载店铺概览失败'); } finally { loading.value = false; isRequesting.value = false; @@ -267,7 +277,7 @@ const handleExportShopOverview = async () => { const safeName = String(shopName).replace(/[/\\:*?"<>|]/g, '_'); const filename = `${safeName}_按商品汇总统计_${startDate.format('YYYYMMDD')}-${endDate.format('YYYYMMDD')}.xlsx`; await exportByPost( - '/ec/shop/export/summary-by-product', + '/bi/shop/export/summary-by-product', { shopId: shopId.value, dateRange: [ @@ -309,7 +319,7 @@ const handleCategoryExport = async () => { const catShopName = overviewData.value?.shopName || `店铺${shopId.value}`; const catSafeName = String(catShopName).replace(/[/\\:*?"<>|]/g, '_'); await exportByPost( - '/ec/shop/export/summary-by-category', + '/bi/shop/export/summary-by-category', params, `${catSafeName}_按品类汇总统计_${catStart.format('YYYYMMDD')}-${catEnd.format('YYYYMMDD')}.xlsx`, ); diff --git a/ecom-dmb-frontend/packages/@core/preferences/__tests__/__snapshots__/config.test.ts.snap b/ecom-dmb-frontend/packages/@core/preferences/__tests__/__snapshots__/config.test.ts.snap index 48f86855..64ecb3b8 100644 --- a/ecom-dmb-frontend/packages/@core/preferences/__tests__/__snapshots__/config.test.ts.snap +++ b/ecom-dmb-frontend/packages/@core/preferences/__tests__/__snapshots__/config.test.ts.snap @@ -17,7 +17,7 @@ exports[`defaultPreferences immutability test > should not modify the config obj "contentPaddingRight": 0, "contentPaddingTop": 0, "defaultAvatar": "https://unpkg.com/@vbenjs/static-source@0.1.7/source/avatar-v1.webp", - "defaultHomePath": "/store-overview", + "defaultHomePath": "/workbench", "dynamicTitle": true, "enableCheckUpdates": true, "enablePreferences": true, diff --git a/ecom-dmb-frontend/packages/@core/preferences/src/config.ts b/ecom-dmb-frontend/packages/@core/preferences/src/config.ts index 028e7324..7e69516b 100644 --- a/ecom-dmb-frontend/packages/@core/preferences/src/config.ts +++ b/ecom-dmb-frontend/packages/@core/preferences/src/config.ts @@ -17,7 +17,7 @@ const defaultPreferences: Preferences = { contentPaddingTop: 0, defaultAvatar: 'https://unpkg.com/@vbenjs/static-source@0.1.7/source/avatar-v1.webp', - defaultHomePath: '/store-overview', + defaultHomePath: '/workbench', dynamicTitle: true, enableCheckUpdates: true, enablePreferences: true,