feat(promotion-fee): 新增推广费类目级归属,区分商品级/类目级/全店比例池

This commit is contained in:
小蟑螂
2026-05-12 13:24:30 +08:00
parent 1621388d9f
commit f5d7fbe2b0
15 changed files with 470 additions and 48 deletions
+3
View File
@@ -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
@@ -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;
@@ -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<Long, BigDecimal> shopTotalPromotionFeeMap = promotionFees.stream()
// 推广费:与单店品类概览一致 — 商品级直接归属、仅类目、全店比例池;刷单费仍按店铺×品类销售额占比摊
Map<Long, BigDecimal> 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<Long, BigDecimal> 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<Long, BigDecimal> 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<Long> 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<Long, BigDecimal> 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));
}
}
@@ -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<Long, BigDecimal> 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<Long, BigDecimal> productPromotionFromCategory = new HashMap<>();
for (Map.Entry<Long, BigDecimal> catEntry : categoryOnlyPool.entrySet()) {
Long catId = catEntry.getKey();
BigDecimal pool = catEntry.getValue();
if (catId == null || pool == null || pool.compareTo(BigDecimal.ZERO) <= 0) {
continue;
}
Map<Long, BigDecimal> eligibleSalesByProduct = new HashMap<>();
for (Map.Entry<Long, List<OrderPO>> 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<Long, BigDecimal> pe : eligibleSalesByProduct.entrySet()) {
BigDecimal share = pool.multiply(pe.getValue())
.divide(totalElig, 4, RoundingMode.HALF_UP);
productPromotionFromCategory.merge(pe.getKey(), share, BigDecimal::add);
}
}
// 计算各商品销售额(仅用于比例分配)
Map<Long, BigDecimal> 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<Long, BigDecimal> 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<Long, BigDecimal> 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) {
@@ -119,7 +119,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
.distinct()
.collect(Collectors.toList());
// 查询推广费(店铺粒度)
// 查询推广费(相关店铺 + 日期)
List<PromotionFeePO> promotionFees = new ArrayList<>();
if (!shopIds.isEmpty()) {
LambdaQueryWrapper<PromotionFeePO> promoWrapper = new LambdaQueryWrapper<>();
@@ -130,6 +130,22 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
promotionFees = promotionFeeMapper.selectList(promoWrapper);
}
// 店铺维度全部订单(推广费按商品/类目/全店口径分摊,与店铺概览商品汇总一致)
List<OrderPO> allShopOrdersForPromo = new ArrayList<>();
if (!shopIds.isEmpty()) {
LambdaQueryWrapper<OrderPO> 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<Long, Long> orderSpecIdToProductIdMapForOverview(List<OrderPO> orders) {
List<Long> specIds = orders.stream()
.map(OrderPO::getProductSpecId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (specIds.isEmpty()) {
return Collections.emptyMap();
}
List<ProductSpecPO> specs = productSpecMapper.selectList(new LambdaQueryWrapper<ProductSpecPO>()
.in(ProductSpecPO::getId, specIds)
.select(ProductSpecPO::getId, ProductSpecPO::getProductId));
Map<Long, Long> map = new HashMap<>();
for (ProductSpecPO s : specs) {
map.put(s.getId(), s.getProductId());
}
return map;
}
/**
* 构建规格销售汇总
* 将店铺范围内推广费归属到指定商品(与店铺概览「按商品汇总」推广费口径一致)
*/
private BigDecimal computeAttributedPromotionForProduct(
Long productId,
ProductPO product,
List<OrderPO> allShopOrders,
List<PromotionFeePO> 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<Long, Long> specToProduct = orderSpecIdToProductIdMapForOverview(allShopOrders);
Map<Long, List<OrderPO>> ordersByProduct = allShopOrders.stream()
.collect(Collectors.groupingBy(o -> {
Long sid = o.getProductSpecId();
return sid != null ? specToProduct.getOrDefault(sid, -1L) : -1L;
}));
Map<Long, BigDecimal> 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<Long, BigDecimal> 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<Long, BigDecimal> productPromotionFromCategory = new HashMap<>();
for (Map.Entry<Long, BigDecimal> catEntry : categoryOnlyPool.entrySet()) {
Long catId = catEntry.getKey();
BigDecimal pool = catEntry.getValue();
if (catId == null || pool == null || pool.compareTo(BigDecimal.ZERO) <= 0) {
continue;
}
Map<Long, BigDecimal> eligibleSalesByProduct = new HashMap<>();
for (Map.Entry<Long, List<OrderPO>> 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<Long, BigDecimal> pe : eligibleSalesByProduct.entrySet()) {
BigDecimal share = pool.multiply(pe.getValue())
.divide(totalElig, 4, RoundingMode.HALF_UP);
productPromotionFromCategory.merge(pe.getKey(), share, BigDecimal::add);
}
}
Map<Long, BigDecimal> 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<OrderPO> 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<OrderPO> orders,
List<PromotionFeePO> promotionFees,
OrderStatusStatSets stat,
BigDecimal taxRate,
List<Long> shopIds) {
BigDecimal attributedPromotionForProduct) {
// 查询商品所有规格
if (orders.isEmpty()) {
return buildEmptySpecSummary();
@@ -381,12 +523,9 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
Map<Long, ProductSpecPO> specMap = allSpecs.stream()
.collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a));
// 推广费按店铺维度收集,后面按订单数比例拆分
Map<Long, BigDecimal> 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<Long, List<OrderPO>> 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);
}
@@ -28,6 +28,12 @@ public class CreatePromotionFeeDTO {
@NotNull(message = "推广费类型ID不能为空")
private Long feeTypeId;
/**
* 类目ID(可选,类目级推广费)
*/
@Schema(description = "类目ID(可选)", example = "1")
private Long categoryId;
/**
* 商品ID(可选,关联到具体商品)
*/
@@ -30,6 +30,12 @@ public class PromotionFeeFilterDTO {
@Schema(description = "商品ID(可选)", example = "1")
private Long productId;
/**
* 类目ID(可选)
*/
@Schema(description = "类目ID(可选)", example = "1")
private Long categoryId;
/**
* 推广费发生日期开始
*/
@@ -35,6 +35,12 @@ public class UpdatePromotionFeeDTO {
@NotNull(message = "推广费类型ID不能为空")
private Long feeTypeId;
/**
* 类目ID(可选,类目级推广费)
*/
@Schema(description = "类目ID(可选)", example = "1")
private Long categoryId;
/**
* 商品ID(可选,关联到具体商品)
*/
@@ -34,6 +34,12 @@ public class PromotionFeePO {
@TableField("shop_id")
private Long shopId;
/**
* 类目ID(可选,无商品时可用于类目级推广费)
*/
@TableField("category_id")
private Long categoryId;
/**
* 推广费类型ID
*/
@@ -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(可选)
*/
@@ -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("类目不存在或不属于当前公司");
}
}
}
@@ -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;
/** 推广活动名称 */
@@ -17,6 +17,10 @@ export namespace PromotionFeeVO {
feeTypeId: number;
/** 推广费类型名称 */
feeTypeName?: string;
/** 类目ID(可选) */
categoryId?: number;
/** 类目名称 */
categoryName?: string;
/** 商品ID(可选) */
productId?: number;
/** 商品名称 */
@@ -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<PromotionFeeDTO.Create, 'feeDate'> & {
const formData = ref<PromotionFeeFormState>({
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<PromotionFeeTypeVO.Info[]>([]);
const feeTypeListLoading = ref(false);
// 类目树(与商品卡片 TreeSelect 一致:label=name, value=id)
const categoryOptions = ref<any[]>([]);
const categoryTreeLoading = ref(false);
// 商品列表
const productList = ref<ProductVO.Info[]>([]);
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();
});
</script>
@@ -279,20 +340,30 @@ onMounted(() => {
</Select>
</Form.Item>
<Form.Item label="类目(可选)" name="categoryId">
<TreeSelect
v-model:value="formData.categoryId"
class="w-full"
placeholder="请选择类目(可选,用于类目级推广费或筛选商品)"
:tree-data="categoryOptions"
:field-names="{ label: 'name', value: 'id', children: 'children' }"
:loading="categoryTreeLoading"
allow-clear
tree-default-expand-all
/>
</Form.Item>
<Form.Item label="商品(可选)" name="productId">
<Select
v-model:value="formData.productId"
placeholder="请选择商品(可选,不选则为店铺级推广费)"
placeholder="请选择商品(可选;已选类目时仅显示该类目下商品)"
:loading="productListLoading"
allow-clear
show-search
:filter-option="(input: string, option: any) =>
option?.children?.props?.children?.props?.children?.props?.children?.props?.children?.props?.children
?.toLowerCase?.().includes?.(input.toLowerCase()) ?? false
"
:filter-option="productSelectFilterOption"
>
<Select.Option
v-for="product in productList"
v-for="product in filteredProductList"
:key="product.id"
:value="product.id"
>
@@ -97,6 +97,13 @@ const gridOptions: VxeGridProps<any> = {
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
field: 'categoryName',
title: '类目',
minWidth: 120,
showOverflow: 'tooltip' as const,
slots: { default: 'category' },
},
{
field: 'productName',
title: '商品',
@@ -328,6 +335,10 @@ const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
</Space>
</template>
<template #category="{ row }: { row: any }">
<span>{{ row.categoryName || '—' }}</span>
</template>
<template #feeAmount="{ row }: { row: any }">
<span class="font-medium text-red-600">
{{ formatAmount(row.feeAmount) }}