Просмотр исходного кода

feat(teamshare): S-cfc-406 cf.teamshare.createPool 团队池建池实现使绿

- CfCommissionService: 新增 RULE_TEAM_POOL=F03c 常量 + settleTeamPool 建池入口
  (解析 T → 算池金额 → uk_order 幂等建 cf_team_pool_order),settle/settleReferrerOnly
  结算顺序 ⑤ 接线;依赖缺省/开关关闭/T<=0/poolCent<=0 时静默跳过,不影响既有链路
- TeamShareConfigService: T% 多作用域解析(MINIAPP→SYSTEM→GLOBAL→3000bps 兜底,TTL 60s 缓存)
- 新增 CfTeamPoolOrder / CfTeamShareConfig 实体 + 对应 Mapper(schema.sql 三表已由迁移493落地)
- TeamPoolCreateContractTest 13 例全绿(Failures 7→0)
Sisyphus 1 день назад
Родитель
Сommit
ae2196a310

+ 56 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/CfTeamPoolOrder.java

@@ -0,0 +1,56 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 团队分润池整单(能力键 cf.teamshare.createPool,T04 建池落库)。
+ *
+ * <p>口径见 docs/superpowers/plans/2026-11-14-cf-reward-model-v2-design.md §2.2:
+ * 池金额 = 成本 × T%(从成本侧切出,与毛利 base 脱钩);唯一键 {@code uk_order(order_type, order_id)}
+ * 幂等建池——同一订单重复结算命中唯一键直接返回,不重复建池(设计 §7 风险 1 三层兜底第一层)。
+ * 状态流转:pooled=已建池(待瓜分)→ share_issued=已瓜分 / unclaimed=无成员可瓜分。</p>
+ */
+@Data
+@TableName("cf_team_pool_order")
+public class CfTeamPoolOrder implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 来源订单ID(幂等键 uk_order 的一半) */
+    private Long orderId;
+
+    /** 来源订单类型(product/membership/assessment 等,幂等键 uk_order 的一半) */
+    private String orderType;
+
+    /** 商品ID(商品订单) */
+    private Long productId;
+
+    /** 买家用户ID(users.id) */
+    private Long buyerUserId;
+
+    /** 团队池金额(分)= Σ floor(成本 × qty × T_bps / 10000) */
+    private Integer poolCent;
+
+    /** 实际采用 T(bps,如 3000=30%) */
+    private Integer tBps;
+
+    /** 命中作用域 GLOBAL/SYSTEM/MINIAPP(resolveTbps 优先级链结果) */
+    private String configScope;
+
+    /** pooled=已建池 / share_issued=已瓜分 / unclaimed=无成员可瓜分 */
+    private String status;
+
+    private String remark;
+
+    private Date createdAt;
+
+    /** 瓜分完成时间(share_issued 时回填,pooled 阶段为 null) */
+    private Date settledAt;
+}

+ 41 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/CfTeamShareConfig.java

@@ -0,0 +1,41 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 团队分润池比例配置(T% 多作用域解析,能力键 cf.teamshare.config.resolve)。
+ *
+ * <p>口径见 docs/superpowers/plans/2026-11-14-cf-reward-model-v2-design.md §2.1:
+ * owner_type 三作用域 GLOBAL/SYSTEM/MINIAPP,优先级链 MINIAPP(mp_code) → SYSTEM(商品所属
+ * distribution_system_id) → GLOBAL → 代码兜底 3000bps;唯一键 {@code uk_scope(owner_type, owner_id)}
+ * 幂等。</p>
+ */
+@Data
+@TableName("cf_team_share_config")
+public class CfTeamShareConfig implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 作用域: GLOBAL / SYSTEM / MINIAPP */
+    private String ownerType;
+
+    /** SYSTEM=distribution_systems.id / MINIAPP=miniapp_config.mp_code / GLOBAL=NULL */
+    private String ownerId;
+
+    /** 团队池比例(bps,如 3000 = 30%) */
+    private Integer tBps;
+
+    /** 1启用 0停用 */
+    private Integer enabled;
+
+    private Date createdAt;
+
+    private Date updatedAt;
+}

+ 15 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/CfTeamPoolOrderMapper.java

@@ -0,0 +1,15 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.CfTeamPoolOrder;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 团队分润池整单 Mapper(能力键 cf.teamshare.createPool,T04 建池落库)。
+ *
+ * <p>建池走 {@code uk_order(order_type, order_id)} 幂等:重复结算命中唯一键
+ * 抛 {@link org.springframework.dao.DuplicateKeyException},由调用方捕获短路(设计 §7 风险 1)。</p>
+ */
+@Mapper
+public interface CfTeamPoolOrderMapper extends BaseMapper<CfTeamPoolOrder> {
+}

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/CfTeamShareConfigMapper.java

@@ -0,0 +1,12 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.CfTeamShareConfig;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 团队分润池比例配置 Mapper(能力键 cf.teamshare.config.resolve,T02 T% 解析依赖)。
+ */
+@Mapper
+public interface CfTeamShareConfigMapper extends BaseMapper<CfTeamShareConfig> {
+}

+ 150 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/CfCommissionService.java

@@ -3,11 +3,13 @@ package com.etotem.cfc.service;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.etotem.cfc.config.ConfigService;
 import com.etotem.cfc.constant.CfConfigKeys;
+import com.etotem.cfc.context.MiniAppContextHolder;
 import com.etotem.cfc.dto.CfEarnResult;
 import com.etotem.cfc.entity.CfDirectSalesTier;
 import com.etotem.cfc.entity.CfEarnRule;
 import com.etotem.cfc.entity.CfIndirectSalesTier;
 import com.etotem.cfc.entity.CfPlatformRevenueLog;
+import com.etotem.cfc.entity.CfTeamPoolOrder;
 import com.etotem.cfc.entity.FamilyMember;
 import com.etotem.cfc.entity.OctopusEffectKeyPerson;
 import com.etotem.cfc.entity.OctopusEffectRecord;
@@ -21,6 +23,7 @@ import com.etotem.cfc.entity.ProductOrder;
 import com.etotem.cfc.entity.ReferralTree;
 import com.etotem.cfc.entity.User;
 import com.etotem.cfc.mapper.CfPlatformRevenueLogMapper;
+import com.etotem.cfc.mapper.CfTeamPoolOrderMapper;
 import com.etotem.cfc.mapper.FamilyMemberMapper;
 import com.etotem.cfc.mapper.MembershipLevelMapper;
 import com.etotem.cfc.mapper.ProductGiftRuleMapper;
@@ -83,6 +86,9 @@ public class CfCommissionService {
     /** 间接销售奖规则编码(cf_earn_rule.code) */
     public static final String RULE_INDIRECT_SALES = "F03b";
 
+    /** 团队分润池规则编码(cf_earn_rule.code,分润 v2 §3.1:成本 × T% 池内瓜分) */
+    public static final String RULE_TEAM_POOL = "F03c";
+
     /** F03a 团队口径最大层级(§4.1.1:团队 8 层以内) */
     private static final int TEAM_DEPTH = 8;
 
@@ -132,6 +138,10 @@ public class CfCommissionService {
     private ObjectMapper objectMapper;
     @Resource
     private CfPlatformRevenueLogMapper cfPlatformRevenueLogMapper;
+    @Resource
+    private CfTeamPoolOrderMapper cfTeamPoolOrderMapper;
+    @Resource
+    private TeamShareConfigService teamShareConfigService;
 
     /**
      * 通用分佣(双返):当前人 + 推荐人。
@@ -158,6 +168,8 @@ public class CfCommissionService {
         // 推荐人分润(两级销售奖)
         distributeToReferrers(orderId, orderType, buyerUserId, buyerFamilyId,
                 orderAmountCent, paidAmountCent, productId);
+        // ⑤ 团队池建池(分润 v2:成本 × T%,从成本侧切出、不占 base;uk_order 幂等)
+        settleTeamPool(orderId, orderType, buyerUserId, buyerFamilyId, paidAmountCent, productId);
     }
 
     /**
@@ -183,6 +195,8 @@ public class CfCommissionService {
         earnBuyerCf(orderId, orderType, buyerUserId, paidAmountCent);
         distributeToReferrers(orderId, orderType, buyerUserId, buyerFamilyId,
                 orderAmountCent, paidAmountCent, null);
+        // ⑤ 团队池建池(会员/订阅/测评等非商品订单:成本 = 实付 × non_goods_cost_rate)
+        settleTeamPool(orderId, orderType, buyerUserId, buyerFamilyId, paidAmountCent, null);
     }
 
     /**
@@ -267,6 +281,142 @@ public class CfCommissionService {
         return base > 0 ? base : 0;
     }
 
+    /**
+     * 团队池建池(分润 v2 §3.1 结算顺序 ⑤,能力键 cf.teamshare.createPool,T04)。
+     *
+     * <p>解析 T({@link TeamShareConfigService}:MINIAPP→SYSTEM→GLOBAL→兜底 3000bps)→ 算池金额
+     * (商品 = Σ floor(C × qty × T_bps / 10000);非商品 = floor(实付 × non_goods_cost_rate × T_bps / 10000))
+     * → 幂等建 {@code cf_team_pool_order}(唯一键 {@code uk_order(order_type, order_id)},重复结算命中
+     * 唯一键直接返回,设计 §7 风险 1 三层兜底第一层)。池内瓜分(distributeTeamPool)由 T05 能力键
+     * {@code cf.teamshare.weightedShare} 承接。</p>
+     */
+    @Transactional
+    public void settleTeamPool(Long orderId, String orderType, Long buyerUserId, Long buyerFamilyId,
+                               Integer paidAmountCent, Long productId) {
+        try {
+            if (orderId == null || orderType == null || buyerUserId == null) {
+                return;
+            }
+            // 依赖注入缺省(既有单测裸实例/部分 mock)时静默跳过,不影响既有结算链路
+            if (cfTeamPoolOrderMapper == null || teamShareConfigService == null || configService == null) {
+                return;
+            }
+            // 团队池总开关(cf.team_pool.enabled,默认 true)
+            if (!configService.getBooleanConfig(CfConfigKeys.TEAM_POOL_ENABLED, true)) {
+                return;
+            }
+            // 1. 解析 T:MINIAPP(mp_code) → SYSTEM(商品所属 distribution_system_id) → GLOBAL → 兜底 3000
+            String mpCode = MiniAppContextHolder.mpCode();
+            Long distributionSystemId = resolveProductDistributionSystemId(orderType, productId);
+            int tBps = teamShareConfigService.resolveTbps(mpCode, distributionSystemId);
+            if (tBps <= 0) {
+                log.info("团队池比例 T<=0,跳过建池: orderType={}, orderId={}", orderType, orderId);
+                return;
+            }
+            // 2. 算池金额(从成本侧切出,独立于 base;亏损仓仍按成本 × T% 照常发)
+            int poolCent = calcTeamPoolCent(orderId, orderType, paidAmountCent, productId, tBps);
+            if (poolCent <= 0) {
+                log.info("团队池金额为 0,跳过建池: orderType={}, orderId={}", orderType, orderId);
+                return;
+            }
+            // 3. 幂等建池(uk_order(order_type, order_id),重复结算命中唯一键直接返回)
+            CfTeamPoolOrder pool = new CfTeamPoolOrder();
+            pool.setOrderId(orderId);
+            pool.setOrderType(orderType);
+            pool.setProductId(productId);
+            pool.setBuyerUserId(buyerUserId);
+            pool.setPoolCent(poolCent);
+            pool.setTBps(tBps);
+            pool.setConfigScope(resolveScope(mpCode, distributionSystemId));
+            pool.setStatus("pooled");
+            pool.setCreatedAt(new Date());
+            pool.setRemark("成本×T%建池");
+            cfTeamPoolOrderMapper.insert(pool);
+            log.info("团队池建池成功: orderType={}, orderId={}, poolCent={}分, tBps={}, scope={}",
+                    orderType, orderId, poolCent, tBps, pool.getConfigScope());
+        } catch (DuplicateKeyException e) {
+            // 幂等:重复结算命中 uk_order,直接返回(设计 §7 风险 1 三层兜底第一层)
+            log.info("团队池已存在,幂等跳过建池: orderType={}, orderId={}", orderType, orderId);
+        } catch (Exception e) {
+            log.warn("团队池建池失败: orderType={}, orderId={}, err={}", orderType, orderId, e.getMessage());
+        }
+    }
+
+    /** 命中作用域标注(供 cf_team_pool_order.config_scope 落库,与 resolveTbps 优先级同源) */
+    private String resolveScope(String mpCode, Long distributionSystemId) {
+        if (mpCode != null && !mpCode.trim().isEmpty()) {
+            return TeamShareConfigService.SCOPE_MINIAPP;
+        }
+        if (distributionSystemId != null) {
+            return TeamShareConfigService.SCOPE_SYSTEM;
+        }
+        return TeamShareConfigService.SCOPE_GLOBAL;
+    }
+
+    /** 商品所属销售体系ID(SYSTEM 作用域键;非商品/无商品返回 null) */
+    private Long resolveProductDistributionSystemId(String orderType, Long productId) {
+        if (!"product".equals(orderType) || productId == null) {
+            return null;
+        }
+        try {
+            Product p = productMapper.selectById(productId);
+            return p != null ? p.getDistributionSystemId() : null;
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    /**
+     * 团队池金额(分):
+     * 商品订单 = Σ floor(C_i × qty_i × T_bps / 10000)(按行成本加总,无分摊歧义);
+     * 非商品订单 = floor(实付 × non_goods_cost_rate × T_bps / 10000)(成本模型,设计 §1.3)。
+     */
+    private int calcTeamPoolCent(Long orderId, String orderType, Integer paidAmountCent, Long productId, int tBps) {
+        int paid = paidAmountCent != null ? paidAmountCent : 0;
+        if (!"product".equals(orderType)) {
+            int ncd = configService.getIntConfig(CfConfigKeys.TEAM_POOL_NON_GOODS_COST_RATE, 5000);
+            long nonGoodsCost = (long) paid * ncd / 10000;
+            long pool = nonGoodsCost * tBps / 10000;
+            return pool > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) pool;
+        }
+        try {
+            ProductOrder order = productOrderMapper.selectById(orderId);
+            if (order == null) {
+                return 0;
+            }
+            List<OrderItem> items = orderItemMapper.findByOrderId(orderId);
+            if (items != null && !items.isEmpty()) {
+                long total = 0L;
+                for (OrderItem it : items) {
+                    int qty = it.getQuantity() != null ? it.getQuantity() : 0;
+                    if (qty <= 0 || it.getProductId() == null) {
+                        continue;
+                    }
+                    Product p = productMapper.selectById(it.getProductId());
+                    if (p == null || p.getPurchasePrice() == null) {
+                        continue;
+                    }
+                    total += (long) p.getPurchasePrice() * qty * tBps / 10000;
+                }
+                return total > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) total;
+            }
+            // 单商品订单:实付结算传 productId;成本价未配(null)时按 0 处理→池 0 跳过
+            if (productId == null) {
+                return 0;
+            }
+            Product p = productMapper.selectById(productId);
+            if (p == null || p.getPurchasePrice() == null) {
+                return 0;
+            }
+            int qty = order.getQuantity() != null ? order.getQuantity() : 1;
+            long single = (long) p.getPurchasePrice() * qty * tBps / 10000;
+            return single > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) single;
+        } catch (Exception e) {
+            log.warn("计算团队池金额失败: orderId={}, err={}", orderId, e.getMessage());
+            return 0;
+        }
+    }
+
     /**
      * 推荐人分润:两级销售奖(F03a 直接销售奖 + F03b 间接销售奖)。
      *

+ 116 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TeamShareConfigService.java

@@ -0,0 +1,116 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.config.ConfigService;
+import com.etotem.cfc.constant.CfConfigKeys;
+import com.etotem.cfc.entity.CfTeamShareConfig;
+import com.etotem.cfc.mapper.CfTeamShareConfigMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * 团队分润池比例(T%)多作用域解析服务(能力键 cf.teamshare.config.resolve,T02 交付、T04 建池依赖)。
+ *
+ * <p>口径见 docs/superpowers/plans/2026-11-14-cf-reward-model-v2-design.md §2.1 / §3.2:
+ * 优先级链 <b>MINIAPP(mp_code) → SYSTEM(商品所属 distribution_system_id) → GLOBAL → 代码兜底
+ * 3000bps</b>({@code cf.team_pool.default_t_bps},默认 3000);本地缓存 TTL 60s(对齐
+ * {@link ConfigService} 的 CF 配置读取链路),命中 GLOBAL 兜底键时同时缓存兜底结果。</p>
+ */
+@Service
+public class TeamShareConfigService {
+
+    private static final Logger log = LoggerFactory.getLogger(TeamShareConfigService.class);
+
+    /** 作用域枚举 */
+    public static final String SCOPE_GLOBAL = "GLOBAL";
+    public static final String SCOPE_SYSTEM = "SYSTEM";
+    public static final String SCOPE_MINIAPP = "MINIAPP";
+
+    /** 未配置时的代码兜底 T(bps)= 30% */
+    public static final int DEFAULT_T_BPS = 3000;
+
+    /** 缓存 TTL:60 秒(对齐 CF 配置读取链路) */
+    private static final long CACHE_TTL_MS = 60_000L;
+
+    private final ConcurrentHashMap<String, Entry> cache = new ConcurrentHashMap<>();
+
+    @Resource
+    private CfTeamShareConfigMapper cfTeamShareConfigMapper;
+    @Resource
+    private ConfigService configService;
+
+    /**
+     * 按作用域优先级解析团队池比例 T(bps)。
+     *
+     * @param mpCode               当前小程序短码(MINIAPP 作用域键;无请求上下文时传 null)
+     * @param distributionSystemId 商品所属销售体系ID(SYSTEM 作用域键;非商品/无体系时传 null)
+     * @return T(bps);优先级 MINIAPP > SYSTEM > GLOBAL > 兜底默认值
+     */
+    public int resolveTbps(String mpCode, Long distributionSystemId) {
+        // 1. MINIAPP 作用域(粒度最细,优先)
+        if (mpCode != null && !mpCode.trim().isEmpty()) {
+            CfTeamShareConfig mini = queryEnabled(SCOPE_MINIAPP, mpCode.trim());
+            if (mini != null && mini.getTBps() != null) {
+                return mini.getTBps();
+            }
+        }
+        // 2. SYSTEM 作用域(商品所属销售体系)
+        if (distributionSystemId != null) {
+            CfTeamShareConfig sys = queryEnabled(SCOPE_SYSTEM, String.valueOf(distributionSystemId));
+            if (sys != null && sys.getTBps() != null) {
+                return sys.getTBps();
+            }
+        }
+        // 3. GLOBAL 作用域(owner_id = NULL)
+        CfTeamShareConfig global = queryEnabled(SCOPE_GLOBAL, null);
+        if (global != null && global.getTBps() != null) {
+            return global.getTBps();
+        }
+        // 4. 代码兜底:cf.team_pool.default_t_bps(未配置时 3000bps = 30%)
+        return configService.getIntConfig(CfConfigKeys.TEAM_POOL_DEFAULT_T_BPS, DEFAULT_T_BPS);
+    }
+
+    /**
+     * 查询启用中的作用域配置(本地缓存 TTL 60s),GLOBAL 的 owner_id 存 NULL。
+     */
+    private CfTeamShareConfig queryEnabled(String ownerType, String ownerId) {
+        String cacheKey = ownerType + ":" + (ownerId == null ? "" : ownerId);
+        Entry entry = cache.get(cacheKey);
+        if (entry != null && entry.expireAt >= System.currentTimeMillis()) {
+            return entry.value;
+        }
+        CfTeamShareConfig value = null;
+        try {
+            LambdaQueryWrapper<CfTeamShareConfig> qw = new LambdaQueryWrapper<CfTeamShareConfig>()
+                    .eq(CfTeamShareConfig::getOwnerType, ownerType)
+                    .eq(CfTeamShareConfig::getEnabled, 1);
+            // GLOBAL 作用域 owner_id 存 NULL,需 IS NULL 匹配(= NULL 在 MySQL 不命中)
+            if (ownerId == null) {
+                qw.isNull(CfTeamShareConfig::getOwnerId);
+            } else {
+                qw.eq(CfTeamShareConfig::getOwnerId, ownerId);
+            }
+            value = cfTeamShareConfigMapper.selectOne(qw.last("LIMIT 1"));
+        } catch (Exception e) {
+            log.warn("查询团队池比例配置失败 ownerType={}, ownerId={},按未命中处理:{}",
+                    ownerType, ownerId, e.getMessage());
+        }
+        cache.put(cacheKey, new Entry(value, System.currentTimeMillis() + CACHE_TTL_MS));
+        return value;
+    }
+
+    /** 缓存条目 */
+    private static final class Entry {
+        private final CfTeamShareConfig value;
+        private final long expireAt;
+
+        private Entry(CfTeamShareConfig value, long expireAt) {
+            this.value = value;
+            this.expireAt = expireAt;
+        }
+    }
+}