From f5d7fbe2b01b2a34c449d0e59fe1b52905c28de4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E8=9F=91=E8=9E=82?= Date: Tue, 12 May 2026 13:24:30 +0800 Subject: [PATCH] =?UTF-8?q?feat(promotion-fee):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=8E=A8=E5=B9=BF=E8=B4=B9=E7=B1=BB=E7=9B=AE=E7=BA=A7=E5=BD=92?= =?UTF-8?q?=E5=B1=9E=EF=BC=8C=E5=8C=BA=E5=88=86=E5=95=86=E5=93=81=E7=BA=A7?= =?UTF-8?q?/=E7=B1=BB=E7=9B=AE=E7=BA=A7/=E5=85=A8=E5=BA=97=E6=AF=94?= =?UTF-8?q?=E4=BE=8B=E6=B1=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ecom-dmb-backend/sql/ec_design.sql | 3 + ...0605__ec_promotion_fee_add_category_id.sql | 15 ++ .../impl/CompanyOverviewServiceImpl.java | 55 +++++- .../ShopOverviewStatisticsServiceImpl.java | 77 +++++++- .../impl/ProductOverviewServiceImpl.java | 183 +++++++++++++++--- .../model/dto/CreatePromotionFeeDTO.java | 6 + .../model/dto/PromotionFeeFilterDTO.java | 6 + .../model/dto/UpdatePromotionFeeDTO.java | 6 + .../promotion/model/po/PromotionFeePO.java | 6 + .../promotion/model/vo/PromotionFeeVO.java | 12 ++ .../service/impl/PromotionFeeServiceImpl.java | 43 +++- .../promotion-fee/types/types.dto.ts | 6 + .../ecommerce/promotion-fee/types/types.vo.ts | 4 + .../components/PromotionFeeFormModal.vue | 85 +++++++- .../views/ecommerce/promotion-fee/index.vue | 11 ++ 15 files changed, 470 insertions(+), 48 deletions(-) create mode 100644 ecom-dmb-backend/sql/migration/V20260605__ec_promotion_fee_add_category_id.sql diff --git a/ecom-dmb-backend/sql/ec_design.sql b/ecom-dmb-backend/sql/ec_design.sql index beeacfe0..10dc8703 100644 --- a/ecom-dmb-backend/sql/ec_design.sql +++ b/ecom-dmb-backend/sql/ec_design.sql @@ -288,6 +288,7 @@ CREATE TABLE `ec_promotion_fee` ( `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '推广费记录ID', `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', + `category_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '类目ID(可选,无商品时可用于类目级推广费)', `product_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '商品ID(可选)', `fee_type_id` bigint UNSIGNED NOT NULL COMMENT '推广费类型ID', `campaign_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '推广活动名称', @@ -301,6 +302,7 @@ CREATE TABLE `ec_promotion_fee` ( PRIMARY KEY (`id`) USING BTREE, INDEX `idx_company_id`(`company_id` ASC) USING BTREE, INDEX `idx_shop_id`(`shop_id` ASC) USING BTREE, + INDEX `idx_category_id`(`category_id` ASC) USING BTREE, INDEX `idx_product_id`(`product_id` ASC) USING BTREE, INDEX `idx_fee_type_id`(`fee_type_id` ASC) USING BTREE, INDEX `idx_fee_date`(`fee_date` ASC) USING BTREE, @@ -309,6 +311,7 @@ CREATE TABLE `ec_promotion_fee` ( CONSTRAINT `fk_ec_promotion_fee_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_ec_promotion_fee_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `fk_ec_promotion_fee_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_ec_promotion_fee_category` FOREIGN KEY (`category_id`) REFERENCES `ec_category` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `fk_ec_promotion_fee_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `fk_ec_promotion_fee_type` FOREIGN KEY (`fee_type_id`) REFERENCES `ec_promotion_fee_type` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, CONSTRAINT `fk_ec_promotion_fee_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE diff --git a/ecom-dmb-backend/sql/migration/V20260605__ec_promotion_fee_add_category_id.sql b/ecom-dmb-backend/sql/migration/V20260605__ec_promotion_fee_add_category_id.sql new file mode 100644 index 00000000..15cd729d --- /dev/null +++ b/ecom-dmb-backend/sql/migration/V20260605__ec_promotion_fee_add_category_id.sql @@ -0,0 +1,15 @@ +-- ================================================ +-- ec_promotion_fee:新增 category_id(可空,关联 ec_category) +-- 用于类目级推广费;与 product_id 可同时为空表示店铺级按比例分摊 +-- ================================================ + +ALTER TABLE ec_promotion_fee + ADD COLUMN `category_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '类目ID(可选,无商品时可用于类目级推广费)' AFTER `shop_id`; + +ALTER TABLE ec_promotion_fee + ADD INDEX `idx_category_id`(`category_id` ASC); + +ALTER TABLE ec_promotion_fee + ADD CONSTRAINT `fk_ec_promotion_fee_category` + FOREIGN KEY (`category_id`) REFERENCES `ec_category` (`id`) + ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java index 4e284f99..6d50bd9e 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java @@ -35,9 +35,11 @@ import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; +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; /** @@ -841,13 +843,33 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { return categoryId != null ? categoryId : -1L; })); - // Aggregate promotion fees and brush fees by shop - Map shopTotalPromotionFeeMap = promotionFees.stream() + // 推广费:与单店品类概览一致 — 商品级直接归属、仅类目、全店比例池;刷单费仍按店铺×品类销售额占比摊 + Map directPromotionByProduct = promotionFees.stream() + .filter(fee -> fee.getProductId() != null) .collect(Collectors.groupingBy( - PromotionFeePO::getShopId, - Collectors.reducing(BigDecimal.ZERO, + 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, @@ -890,18 +912,35 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { BigDecimal categoryTotalSales = categorySalesByShop.values().stream() .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal totalPromotionFee = BigDecimal.ZERO; - BigDecimal totalBrushFee = BigDecimal.ZERO; + Set catProductIds = new HashSet<>(); + for (OrderPO order : categoryOrders) { + Long specId = order.getProductSpecId(); + Long productId = specId != null ? specIdToProductId.get(specId) : 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 shopPromoFee = shopTotalPromotionFeeMap.getOrDefault(shopId, BigDecimal.ZERO); BigDecimal shopBrushFee = shopTotalBrushFeeMap.getOrDefault(shopId, BigDecimal.ZERO); - totalPromotionFee = totalPromotionFee.add(shopPromoFee.multiply(ratio)); totalBrushFee = totalBrushFee.add(shopBrushFee.multiply(ratio)); } } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java index 222228e9..9a02e7f4 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java @@ -453,12 +453,60 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics BigDecimal.ZERO, fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO, BigDecimal::add))); - // 无商品归属的推广费(店铺级),按销售比例分配 - BigDecimal ratioPool = promotionFees.stream() - .filter(fee -> fee.getProductId() == null) + + 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( @@ -499,11 +547,12 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics .map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO) .reduce(BigDecimal.ZERO, BigDecimal::add); - // 推广费:有商品级直接归属的用直接归属,其余用比例分配 - BigDecimal productPromotionFee = directPromotionByProduct.getOrDefault(productId, BigDecimal.ZERO); - if (productPromotionFee.compareTo(BigDecimal.ZERO) == 0 && ratioPool.compareTo(BigDecimal.ZERO) > 0 && totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) { + // 推广费:商品级直接归属 + 类目级分摊 + 店铺级比例池 + 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 = ratioPool.multiply(ratio); + productPromotionFee = globalRatioPool.multiply(ratio); } // 计算商品成本 @@ -767,7 +816,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics ordersByCategory.computeIfAbsent(categoryId, k -> new ArrayList<>()).add(order); } - // 推广费:按商品ID聚合直接归属 + 无商品归属的进入比例池 + // 推广费:按商品ID聚合直接归属;无商品有类目则直接记类目;全无则进入比例池 Map directPromotionByProduct = promotionFees.stream() .filter(fee -> fee.getProductId() != null) .collect(Collectors.groupingBy( @@ -776,8 +825,16 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics 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) + .filter(fee -> fee.getProductId() == null && fee.getCategoryId() == null) .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) .reduce(BigDecimal.ZERO, BigDecimal::add); @@ -820,6 +877,8 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics 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) { diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java index 6c76c6c2..593d1c5c 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java @@ -119,7 +119,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { .distinct() .collect(Collectors.toList()); - // 查询推广费(店铺粒度) + // 查询推广费(相关店铺 + 日期) List promotionFees = new ArrayList<>(); if (!shopIds.isEmpty()) { LambdaQueryWrapper promoWrapper = new LambdaQueryWrapper<>(); @@ -130,6 +130,22 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { 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 (!unionStatusIds.isEmpty()) { + allOrdersWrapper.in(OrderPO::getStatusId, unionStatusIds); + } else { + allOrdersWrapper.isNull(OrderPO::getId); + } + allShopOrdersForPromo = orderMapper.selectList(allOrdersWrapper); + } + // 查询上月同期数据(用于环比计算) long dayCount = ChronoUnit.DAYS.between(startDate, endDate) + 1; LocalDate lastStartDate = startDate.minusDays(dayCount); @@ -179,15 +195,13 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { .reduce(BigDecimal.ZERO, BigDecimal::add); vo.setAverageFeeRatio(null); // 由 spec 维度均化,待后面补充 - // 总推广费 - BigDecimal totalPromotionFee = promotionFees.stream() - .map(f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - // 按订单数量比例分摊到当前商品(简化处理) - if (!shopIds.isEmpty() && totalPromotionFee.compareTo(BigDecimal.ZERO) > 0) { - // 按商品所在订单数占总订单比例分摊(近似) - // 这里不做细粒度分摊,保持店铺维度总额在 spec 维度按比例拆分 - } + // 总推广费(与 ShopOverviewStatisticsServiceImpl 商品维度推广费归属一致) + BigDecimal totalPromotionFee = computeAttributedPromotionForProduct( + queryDTO.getProductId(), + product, + allShopOrdersForPromo, + promotionFees, + stat); // 费比 BigDecimal avgFeeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0 @@ -275,7 +289,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { vo.setOrderCountTrend(buildOrderCountTrend(orders, stat, startDate, endDate)); // ---------- 规格销售汇总 ---------- - vo.setSpecSummaries(buildSpecSummary(orders, promotionFees, stat, taxRate, shopIds)); + vo.setSpecSummaries(buildSpecSummary(orders, stat, taxRate, totalPromotionFee)); // ---------- 各规格销量 Top10 ---------- vo.setSpecSalesTop10(buildSpecSalesTop10(orders, stat, shopIds)); @@ -348,14 +362,142 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { return trend; } + private Map orderSpecIdToProductIdMapForOverview(List orders) { + List specIds = orders.stream() + .map(OrderPO::getProductSpecId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (specIds.isEmpty()) { + return Collections.emptyMap(); + } + List specs = productSpecMapper.selectList(new LambdaQueryWrapper() + .in(ProductSpecPO::getId, specIds) + .select(ProductSpecPO::getId, ProductSpecPO::getProductId)); + Map map = new HashMap<>(); + for (ProductSpecPO s : specs) { + map.put(s.getId(), s.getProductId()); + } + return map; + } + /** - * 构建规格销售汇总 + * 将店铺范围内推广费归属到指定商品(与店铺概览「按商品汇总」推广费口径一致) + */ + 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 specToProduct = orderSpecIdToProductIdMapForOverview(allShopOrders); + Map> ordersByProduct = allShopOrders.stream() + .collect(Collectors.groupingBy(o -> { + Long sid = o.getProductSpecId(); + return sid != null ? specToProduct.getOrDefault(sid, -1L) : -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 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, - List promotionFees, OrderStatusStatSets stat, BigDecimal taxRate, - List shopIds) { + BigDecimal attributedPromotionForProduct) { // 查询商品所有规格 if (orders.isEmpty()) { return buildEmptySpecSummary(); @@ -381,12 +523,9 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { Map specMap = allSpecs.stream() .collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a)); - // 推广费按店铺维度收集,后面按订单数比例拆分 - Map shopPromotionFeeMap = promotionFees.stream() - .collect(Collectors.groupingBy(PromotionFeePO::getShopId, - Collectors.reducing(BigDecimal.ZERO, - f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); + BigDecimal totalAttributed = attributedPromotionForProduct != null + ? attributedPromotionForProduct + : BigDecimal.ZERO; // 按规格分组订单 Map> ordersBySpec = orders.stream() @@ -450,9 +589,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { if (totalOrderCountAll > 0) { BigDecimal proportion = BigDecimal.valueOf((long) orderCount) .divide(BigDecimal.valueOf(totalOrderCountAll), 4, RoundingMode.HALF_UP); - BigDecimal totalPromo = shopPromotionFeeMap.values().stream() - .reduce(BigDecimal.ZERO, BigDecimal::add); - specPromotionFee = totalPromo.multiply(proportion) + specPromotionFee = totalAttributed.multiply(proportion) .setScale(2, RoundingMode.HALF_UP); } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/CreatePromotionFeeDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/CreatePromotionFeeDTO.java index 799b6fd6..e33b4c71 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/CreatePromotionFeeDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/CreatePromotionFeeDTO.java @@ -28,6 +28,12 @@ public class CreatePromotionFeeDTO { @NotNull(message = "推广费类型ID不能为空") private Long feeTypeId; + /** + * 类目ID(可选,类目级推广费) + */ + @Schema(description = "类目ID(可选)", example = "1") + private Long categoryId; + /** * 商品ID(可选,关联到具体商品) */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/PromotionFeeFilterDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/PromotionFeeFilterDTO.java index f106e2a9..ae2c9d6f 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/PromotionFeeFilterDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/PromotionFeeFilterDTO.java @@ -30,6 +30,12 @@ public class PromotionFeeFilterDTO { @Schema(description = "商品ID(可选)", example = "1") private Long productId; + /** + * 类目ID(可选) + */ + @Schema(description = "类目ID(可选)", example = "1") + private Long categoryId; + /** * 推广费发生日期开始 */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/UpdatePromotionFeeDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/UpdatePromotionFeeDTO.java index 02d49d88..2d718e43 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/UpdatePromotionFeeDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/dto/UpdatePromotionFeeDTO.java @@ -35,6 +35,12 @@ public class UpdatePromotionFeeDTO { @NotNull(message = "推广费类型ID不能为空") private Long feeTypeId; + /** + * 类目ID(可选,类目级推广费) + */ + @Schema(description = "类目ID(可选)", example = "1") + private Long categoryId; + /** * 商品ID(可选,关联到具体商品) */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/po/PromotionFeePO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/po/PromotionFeePO.java index aec5bc5a..d127ed15 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/po/PromotionFeePO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/po/PromotionFeePO.java @@ -34,6 +34,12 @@ public class PromotionFeePO { @TableField("shop_id") private Long shopId; + /** + * 类目ID(可选,无商品时可用于类目级推广费) + */ + @TableField("category_id") + private Long categoryId; + /** * 推广费类型ID */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/vo/PromotionFeeVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/vo/PromotionFeeVO.java index 905f23fd..6feda2ed 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/vo/PromotionFeeVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/model/vo/PromotionFeeVO.java @@ -50,6 +50,18 @@ public class PromotionFeeVO { @Schema(description = "推广费类型名称", example = "直通车") private String feeTypeName; + /** + * 类目ID(可选) + */ + @Schema(description = "类目ID(可选)", example = "1") + private Long categoryId; + + /** + * 类目名称 + */ + @Schema(description = "类目名称", example = "数码") + private String categoryName; + /** * 商品ID(可选) */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java index 7b92534d..432fd05c 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java @@ -18,7 +18,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeVO; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeService; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeTypeService; -import top.xyquan.ecomdmbbackend.modules.ecom.platform.service.PlatformService; +import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO; +import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService; import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; @@ -39,6 +40,7 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { private final ShopService shopService; private final PromotionFeeTypeService promotionFeeTypeService; private final ProductService productService; + private final CategoryService categoryService; /** @@ -49,6 +51,7 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { @Override @Transactional(rollbackFor = Exception.class) public Long createPromotionFee(CreatePromotionFeeDTO dto) { + assertOptionalCategoryInCompany(dto.getCategoryId()); PromotionFeePO po = new PromotionFeePO(); BeanUtils.copyProperties(dto, po); po.setCompanyId(currentUserContext.getCurrentCompanyId()); @@ -71,6 +74,7 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { if (existing == null || !existing.getCompanyId().equals(companyId)) { throw new BusinessException("推广费记录不存在"); } + assertOptionalCategoryInCompany(dto.getCategoryId()); PromotionFeePO po = new PromotionFeePO(); BeanUtils.copyProperties(dto, po); po.setUpdateBy(currentUserContext.getCurrentUserId()); @@ -133,6 +137,9 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { if (filter.getProductId() != null) { wrapper.eq(PromotionFeePO::getProductId, filter.getProductId()); } + if (filter.getCategoryId() != null) { + wrapper.eq(PromotionFeePO::getCategoryId, filter.getCategoryId()); + } if (filter.getFeeDateStart() != null) { wrapper.ge(PromotionFeePO::getFeeDate, filter.getFeeDateStart()); } @@ -194,6 +201,40 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { } } + if (po.getCategoryId() != null) { + try { + CategoryPO category = categoryService.getById(po.getCategoryId()); + if (category != null) { + vo.setCategoryName(category.getName()); + } + } catch (Exception ignored) { + } + } else if (po.getProductId() != null) { + // 列表/详情展示:记录未选类目时,带出商品所属类目(便于与「仅选商品」的旧数据对齐) + try { + ProductPO p = productService.getById(po.getProductId()); + if (p != null && p.getCategoryId() != null) { + vo.setCategoryId(p.getCategoryId()); + CategoryPO category = categoryService.getById(p.getCategoryId()); + if (category != null) { + vo.setCategoryName(category.getName()); + } + } + } catch (Exception ignored) { + } + } + return vo; } + + private void assertOptionalCategoryInCompany(Long categoryId) { + if (categoryId == null) { + return; + } + Long companyId = currentUserContext.getCurrentCompanyId(); + CategoryPO category = categoryService.getById(categoryId); + if (category == null || !companyId.equals(category.getCompanyId())) { + throw new BusinessException("类目不存在或不属于当前公司"); + } + } } \ No newline at end of file diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/promotion-fee/types/types.dto.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/promotion-fee/types/types.dto.ts index 37dee375..e1370e68 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/promotion-fee/types/types.dto.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/promotion-fee/types/types.dto.ts @@ -9,6 +9,8 @@ export namespace PromotionFeeDTO { shopId?: number; /** 推广费类型ID */ feeTypeId?: number; + /** 类目ID(可选) */ + categoryId?: number; /** 商品ID(可选) */ productId?: number; /** 推广费发生日期开始 */ @@ -23,6 +25,8 @@ export namespace PromotionFeeDTO { shopId: number; /** 推广费类型ID */ feeTypeId: number; + /** 类目ID(可选,类目级推广费) */ + categoryId?: number; /** 商品ID(可选,关联到具体商品) */ productId?: number; /** 推广活动名称 */ @@ -43,6 +47,8 @@ export namespace PromotionFeeDTO { shopId: number; /** 推广费类型ID */ feeTypeId: number; + /** 类目ID(可选,类目级推广费) */ + categoryId?: number; /** 商品ID(可选,关联到具体商品) */ productId?: number; /** 推广活动名称 */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/promotion-fee/types/types.vo.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/promotion-fee/types/types.vo.ts index 8d0acbf7..087f1258 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/promotion-fee/types/types.vo.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/promotion-fee/types/types.vo.ts @@ -17,6 +17,10 @@ export namespace PromotionFeeVO { feeTypeId: number; /** 推广费类型名称 */ feeTypeName?: string; + /** 类目ID(可选) */ + categoryId?: number; + /** 类目名称 */ + categoryName?: string; /** 商品ID(可选) */ productId?: number; /** 商品名称 */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/promotion-fee/components/PromotionFeeFormModal.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/promotion-fee/components/PromotionFeeFormModal.vue index 607df0ce..98ce2d13 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/promotion-fee/components/PromotionFeeFormModal.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/promotion-fee/components/PromotionFeeFormModal.vue @@ -7,7 +7,7 @@ import type { import type { ProductVO } from '#/api/ecommerce/product/types'; import type { ShopVO } from '#/api/ecommerce/shop/types'; -import { nextTick, onMounted, ref, watch } from 'vue'; +import { computed, nextTick, onMounted, ref, watch } from 'vue'; import type { Dayjs } from 'dayjs'; import dayjs from 'dayjs'; @@ -21,12 +21,14 @@ import { InputNumber, message, Select, + TreeSelect, } from 'ant-design-vue'; import { createPromotionFeeApi, updatePromotionFeeApi, } from '#/api/ecommerce/promotion-fee'; +import { getCategoryTreeApi } from '#/api/ecommerce/category'; import { getActivePromotionFeeTypeListApi } from '#/api/ecommerce/promotion-fee-type'; import { getProductPageApi } from '#/api/ecommerce/product'; import { getShopPageApi } from '#/api/ecommerce/shop'; @@ -79,6 +81,7 @@ type PromotionFeeFormState = Omit & { const formData = ref({ shopId: undefined as any, feeTypeId: undefined as any, + categoryId: undefined, productId: undefined, campaignName: '', feeAmount: undefined as any, @@ -103,10 +106,36 @@ const shopListLoading = ref(false); const feeTypeList = ref([]); const feeTypeListLoading = ref(false); +// 类目树(与商品卡片 TreeSelect 一致:label=name, value=id) +const categoryOptions = ref([]); +const categoryTreeLoading = ref(false); + // 商品列表 const productList = ref([]); const productListLoading = ref(false); +const filteredProductList = computed(() => { + const cid = formData.value.categoryId; + if (cid == null) { + return productList.value; + } + return productList.value.filter((p) => p.categoryId === cid); +}); + +watch( + () => formData.value.categoryId, + (cid) => { + const pid = formData.value.productId; + if (pid == null || cid == null) { + return; + } + const p = productList.value.find((x) => x.id === pid); + if (p && p.categoryId !== cid) { + formData.value.productId = undefined; + } + }, +); + watch( () => props.open, async (newVal) => { @@ -119,6 +148,7 @@ watch( formData.value = { shopId: props.promotionFeeData.shopId, feeTypeId: props.promotionFeeData.feeTypeId, + categoryId: props.promotionFeeData.categoryId, productId: props.promotionFeeData.productId, campaignName: props.promotionFeeData.campaignName || '', feeAmount: props.promotionFeeData.feeAmount, @@ -134,6 +164,18 @@ watch( modalApi.open(); await nextTick(); formRef.value?.clearValidate?.(); + + if (props.promotionFeeData?.productId && productList.value.length > 0) { + const p = productList.value.find( + (x) => x.id === props.promotionFeeData!.productId, + ); + if ( + p?.categoryId != null && + (formData.value.categoryId == null || formData.value.categoryId === undefined) + ) { + formData.value.categoryId = p.categoryId; + } + } }, ); @@ -165,6 +207,18 @@ const loadFeeTypeList = async () => { } }; +const loadCategoryTree = async () => { + categoryTreeLoading.value = true; + try { + categoryOptions.value = (await getCategoryTreeApi()) ?? []; + } catch (error) { + console.error('加载类目树失败:', error); + categoryOptions.value = []; + } finally { + categoryTreeLoading.value = false; + } +}; + const loadProductList = async () => { productListLoading.value = true; try { @@ -185,6 +239,7 @@ const resetFormData = () => { formData.value = { shopId: undefined as any, feeTypeId: undefined as any, + categoryId: undefined, productId: undefined, campaignName: '', feeAmount: undefined as any, @@ -196,6 +251,11 @@ const resetFormData = () => { /** 发生日期仅表示日历日,格式化为本地 YYYY-MM-DD,避免 JSON 序列化为 UTC ISO 后日期错位 */ const feeDateToApiString = (v: Dayjs) => dayjs(v).format('YYYY-MM-DD'); +function productSelectFilterOption(input: string, option?: any) { + const o = filteredProductList.value.find((x) => x.id === option?.value); + return (o?.name ?? '').toLowerCase().includes(input.toLowerCase()); +} + const handleOk = async () => { try { await formRef.value?.validate(); @@ -234,6 +294,7 @@ const handleCancel = () => { onMounted(() => { loadShopList(); loadFeeTypeList(); + loadCategoryTree(); loadProductList(); }); @@ -279,20 +340,30 @@ onMounted(() => { + + + +