Browse Source

S-cfc-409: 实现旧体系废弃清理 cf.rewardv2.removeLegacy

- 删除 6 个契约类:ProfitPoolService/TeamProfitService/TeamProfitFlowService/
  StarScoreCalculator/TeamProfitCronTask/TeamProfitAdminController
- 删除无前端调用者的 TeamStarController(依赖 StarScoreCalculator)
- DatabaseInitializer 去除 4 旧表(profit_pool_order/team_share_record/
  team_award_record/service_cost_config)CREATE DDL,schema.sql 保留
- 5 个订单服务移除 ProfitPoolService 结算调用块
- StarDigestService 走既有 fallback,不再依赖 calculator
- 删除 TeamProfitPipelineContractTest:硬编译依赖 ProfitPoolService,
  不删则 test-compile 失败(RED 契约测试 RewardV2RemoveLegacyContractTest
  6/6 绿;其余旧体系测试由测试侧退役/排除清单处理)
- 保留 TeamProfitConfigService/ServiceCostConfigService 与 4 表实体

Refs: cf.rewardv2.removeLegacy
Sisyphus 1 day ago
parent
commit
b4c755f6b2

+ 0 - 131
cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java

@@ -3538,19 +3538,8 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         // 迁移457: survey_records 添加 source 列(区分定期调研/健康阅卷,HL-01 健康阅卷入口)
         ensureColumn("survey_records", "source", "VARCHAR(32) DEFAULT 'periodic' COMMENT '记录来源: periodic=定期调研 / health_review=健康阅卷'");
 
-        // 迁移458: 单笔订单利润池计算明细表(团队分润 §7.1,uk_order 幂等)
-        createProfitPoolOrderTable();
-        // 迁移459: 团队8份分佣流水表(§7.3,uk_order_rec 幂等)
-        createTeamShareRecordTable();
-        // 迁移460: 团队奖流水表(§7.4,uk_order_team 幂等)
-        createTeamAwardRecordTable();
         // 迁移461: 团队成员星级月度快照表(§7.6,uk_user_period 幂等)
         createTeamStarSnapshotTable();
-        // 迁移462: 服务成本价配置表(§7.5,uk_service_cost 幂等;成本价回填通道,S-cfc-62 team.profit.hook)
-        createServiceCostConfigTable();
-        // 迁移463: service_cost_config 补 §7.5 规格列 service_name/enabled(S-cfc-68 team.admin.manage 成本价管理端维护载体)
-        ensureColumn("service_cost_config", "service_name", "VARCHAR(64) NULL COMMENT '服务名称'");
-        ensureColumn("service_cost_config", "enabled", "TINYINT DEFAULT 1 COMMENT '是否启用: 1=启用 0=停用'");
 
         // 迁移464: 创建 P3 跨案例聚合承载表 attribution_case_strategies(T15 跨案例聚合,S-cfc-119 guhe.p3.lowSideAggregate)
         createAttributionCaseStrategyTable();
@@ -4186,97 +4175,6 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         }
     }
 
-    /**
-     * 迁移458: 创建单笔订单利润池计算明细表(§7.1)。
-     *
-     * <p>承载 §2.1 总账模型逐项核算;{@code uk_order(order_type, order_id)} 唯一键
-     * 保证重复回调幂等(§8.3)。触发源(order_type)在 §4.7 杠杆 1 扩展
-     * membership/subscription/assessment_retest(T9 收入管道化)。</p>
-     */
-    private void createProfitPoolOrderTable() {
-        try {
-            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS profit_pool_order ("
-                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY,"
-                    + "order_id BIGINT NOT NULL COMMENT '来源订单ID',"
-                    + "order_type VARCHAR(32) NOT NULL COMMENT '触发源: product/service/assessment/package/membership/subscription/assessment_retest',"
-                    + "product_id BIGINT NULL COMMENT '商品/服务ID',"
-                    + "amount_cent INT NOT NULL COMMENT '售价S(分)',"
-                    + "cost_cent INT NOT NULL COMMENT '平台成本价C(分)',"
-                    + "platform_retain_cent INT NOT NULL COMMENT '平台留存P=S-C(分)',"
-                    + "ops_cent INT NOT NULL COMMENT '平台运营O(分)',"
-                    + "cf_cost_cent INT NOT NULL COMMENT 'CF值成本F(分)',"
-                    + "pool_cent INT NOT NULL COMMENT '可分配池D(分)',"
-                    + "referral_share_cent INT NOT NULL COMMENT '推荐人体系R(分,CF值预算参照)',"
-                    + "team_share_cent INT NOT NULL COMMENT '团队体系T(分,货币)',"
-                    + "team_eight_share_cent INT NOT NULL COMMENT '8份分佣池(分,默认T×80%)',"
-                    + "team_award_cent INT NOT NULL COMMENT '团队奖池(分,默认T×20%)',"
-                    + "status VARCHAR(16) NOT NULL DEFAULT 'pending' COMMENT 'pending/settled/cancelled',"
-                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',"
-                    + "settled_at DATETIME NULL COMMENT '结算时间',"
-                    + "UNIQUE KEY uk_order (order_type, order_id)"
-                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='单笔订单利润池计算明细'");
-            log.info("迁移458: profit_pool_order 表已就绪");
-        } catch (Exception e) {
-            log.warn("迁移458: profit_pool_order 创建失败: {}", e.getMessage());
-        }
-    }
-
-    /**
-     * 迁移459: 创建团队 8 份分佣流水表(§7.3)。
-     *
-     * <p>{@code uk_order_rec(order_id, recipient_user_id, layer)} 唯一键保证重复回调幂等(§8.3)。</p>
-     */
-    private void createTeamShareRecordTable() {
-        try {
-            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS team_share_record ("
-                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY,"
-                    + "order_id BIGINT NOT NULL COMMENT '来源订单ID',"
-                    + "order_type VARCHAR(32) NOT NULL COMMENT '触发源',"
-                    + "pool_id BIGINT NOT NULL COMMENT '归属利润池明细profit_pool_order.id',"
-                    + "provider_user_id BIGINT NOT NULL COMMENT '服务提供者(规划师/测评师)',"
-                    + "recipient_user_id BIGINT NOT NULL COMMENT '获得分润的团队成员',"
-                    + "layer INT NOT NULL COMMENT '1=服务者本人 2=引荐人 3=引荐人的引荐人',"
-                    + "star_level INT NULL COMMENT '该成员当期星级快照(1-6)',"
-                    + "shares INT NOT NULL COMMENT '分得份数(0-8)',"
-                    + "share_cent INT NOT NULL COMMENT '分润金额(分)',"
-                    + "status VARCHAR(16) NOT NULL DEFAULT 'pending' COMMENT 'pending/settled/cancelled',"
-                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',"
-                    + "UNIQUE KEY uk_order_rec (order_id, recipient_user_id, layer),"
-                    + "KEY idx_recipient (recipient_user_id)"
-                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='团队8份分佣流水(货币)'");
-            log.info("迁移459: team_share_record 表已就绪");
-        } catch (Exception e) {
-            log.warn("迁移459: team_share_record 创建失败: {}", e.getMessage());
-        }
-    }
-
-    /**
-     * 迁移460: 创建团队奖流水表(§7.4)。
-     *
-     * <p>{@code uk_order_team(order_id, team_id)} 唯一键保证重复回调幂等(§8.3)。</p>
-     */
-    private void createTeamAwardRecordTable() {
-        try {
-            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS team_award_record ("
-                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY,"
-                    + "order_id BIGINT NOT NULL COMMENT '来源订单ID',"
-                    + "order_type VARCHAR(32) NOT NULL COMMENT '触发源',"
-                    + "pool_id BIGINT NOT NULL COMMENT '归属利润池明细profit_pool_order.id',"
-                    + "team_id BIGINT NOT NULL COMMENT 'distribution_systems.id',"
-                    + "owner_user_id BIGINT NOT NULL COMMENT '团队负责人(owner_id/根)',"
-                    + "tier VARCHAR(8) NOT NULL COMMENT 'TA0/TA1/TA2/TA3',"
-                    + "award_cent INT NOT NULL COMMENT '团队奖金额(分)',"
-                    + "status VARCHAR(16) NOT NULL DEFAULT 'pending' COMMENT 'pending/settled/cancelled',"
-                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',"
-                    + "UNIQUE KEY uk_order_team (order_id, team_id),"
-                    + "KEY idx_owner (owner_user_id)"
-                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='团队奖流水(货币)'");
-            log.info("迁移460: team_award_record 表已就绪");
-        } catch (Exception e) {
-            log.warn("迁移460: team_award_record 创建失败: {}", e.getMessage());
-        }
-    }
-
     /**
      * 迁移461: 创建团队成员星级月度快照表(§7.6)。
      *
@@ -4304,35 +4202,6 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         }
     }
 
-    /**
-     * 迁移462: 创建服务成本价配置表(§7.5)。
-     *
-     * <p>{@code uk_service_cost(service_type, product_id)} 唯一键(NULL=对该类型通配);
-     * 供 §2.1 利润漏斗平台成本价 C 取值回填通道(默认 0,由配置键/管理端维护)。幂等:
-     * CREATE TABLE IF NOT EXISTS。</p>
-     *
-     * <p>口径来源:docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md §7.5,
-     * 能力键 S-cfc-62 team.profit.hook 第 4 张表。</p>
-     */
-    private void createServiceCostConfigTable() {
-        try {
-            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS service_cost_config ("
-                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY,"
-                    + "service_type VARCHAR(32) NOT NULL COMMENT '触发源',"
-                    + "product_id BIGINT NULL COMMENT '商品/服务ID(NULL=对该类型通配)',"
-                    + "cost_cent INT NOT NULL COMMENT '平台成本价 C(分)',"
-                    + "source VARCHAR(16) NOT NULL DEFAULT 'manual' COMMENT '成本来源: manual=人工维护/auto=自动测算',"
-                    + "remark VARCHAR(255) NULL COMMENT '备注',"
-                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',"
-                    + "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',"
-                    + "UNIQUE KEY uk_service_cost (service_type, product_id)"
-                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='服务成本价配置'");
-            log.info("迁移462: service_cost_config 表已就绪");
-        } catch (Exception e) {
-            log.warn("迁移462: service_cost_config 创建失败: {}", e.getMessage());
-        }
-    }
-
     /**
      * 迁移450: 会员权益文案与实际成交口径对齐(DML,幂等)。
      *

+ 0 - 46
cfc-backend/src/main/java/com/etotem/cfc/controller/TeamStarController.java

@@ -1,46 +0,0 @@
-package com.etotem.cfc.controller;
-
-import com.etotem.cfc.common.Result;
-import com.etotem.cfc.dto.TeamStarMyViewVO;
-import com.etotem.cfc.service.StarScoreCalculator;
-import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestAttribute;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.annotation.Resource;
-
-/**
- * 用户端团队星级看板(能力键 {@code team.star.myView},单元 team,§12-T7)。
- *
- * <p>契约溯源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
- * §12-T7(星级看板与换算)+ §11-#13(按推荐全做 P1 看板+换算)+ §4.3.1 ①②。</p>
- *
- * <p><b>接口约定(项目规范)</b>:统一 {@code @PostMapping},统一返回 {@code Result<T>};
- * 面向已入团成员本人查询「我的星级」,鉴权由 JwtInterceptor 统一完成(需登录),
- * 接口内无独立角色分支。</p>
- */
-@Tag(name = "团队星级-我的星级")
-@RestController
-@RequestMapping("/api/team-star")
-public class TeamStarController {
-
-    @Resource
-    private StarScoreCalculator starScoreCalculator;
-
-    /**
-     * 我的星级看板:当前星级 / 总分 / 三维构成 / 距下一档差距 / 升级双门槛进度 /
-     * 三条换算路径 / 近 12 月轨迹(§4.3.1 ①②)。
-     */
-    @Operation(summary = "我的星级看板(当前星级/三维构成/差距/双门槛进度/换算路径/近12月轨迹)")
-    @PostMapping("/my-view")
-    public Result<TeamStarMyViewVO> myView(
-            @RequestAttribute(value = "userId", required = false) Long userId) {
-        if (userId == null) {
-            return Result.error(401, "未登录或登录已过期");
-        }
-        return Result.success(starScoreCalculator.myView(userId));
-    }
-}

+ 0 - 276
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/TeamProfitAdminController.java

@@ -1,276 +0,0 @@
-package com.etotem.cfc.controller.admin;
-
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.etotem.cfc.common.AdminRoles;
-import com.etotem.cfc.common.Result;
-import com.etotem.cfc.entity.TeamAwardRecord;
-import com.etotem.cfc.entity.TeamShareRecord;
-import com.etotem.cfc.entity.WithdrawalRequest;
-import com.etotem.cfc.service.ServiceCostConfigService;
-import com.etotem.cfc.service.TeamProfitConfigService;
-import com.etotem.cfc.service.TeamProfitFlowService;
-import com.etotem.cfc.service.WithdrawalService;
-import com.etotem.cfc.util.ParamUtils;
-import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-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.RequestAttribute;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.annotation.Resource;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * 管理端团队分润(能力键 {@code team.admin.manage},单元 admin,§12-T5)。
- *
- * <p>契约溯源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
- * §12-T5:成本价/星级档位(后台配置 #12)/团队门槛/团队奖分档配置 + 分润流水查询与提现审核
- * (复用现有管理端佣金模式)。</p>
- *
- * <p><b>接口约定(项目规范)</b>:{@code /api/admin} 前缀统一 {@code @PostMapping},
- * JwtInterceptor 拦截 + 控制器内管理员角色门禁(admin/operator/finance 平台角色)。</p>
- *
- * <p><b>规格:docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md v0.7
- * §7.5 + §7.8 + §11-#12 + §12-T5。</b></p>
- */
-@Tag(name = "管理端-团队分润")
-@RestController
-@RequestMapping("/api/admin/team-profit")
-public class TeamProfitAdminController {
-
-    @Resource
-    private TeamProfitConfigService teamProfitConfigService;
-
-    @Resource
-    private TeamProfitFlowService teamProfitFlowService;
-
-    @Resource
-    private ServiceCostConfigService serviceCostConfigService;
-
-    @Resource
-    private WithdrawalService withdrawalService;
-
-    // ==================== 配置(§7.8 + §11-#12) ====================
-
-    @Operation(summary = "团队分润配置总览(星级档位/比率/份额/归属/权重)")
-    @PostMapping("/config")
-    public Result<Map<String, Object>> config(@RequestAttribute("role") String role,
-                                              @RequestAttribute(value = "roles", required = false) List<String> roles) {
-        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
-        if (gate != null) {
-            return gate;
-        }
-        Map<String, Object> data = new LinkedHashMap<>();
-        data.put("starTiers", teamProfitConfigService.getStarTiers());
-        data.put("eightShareRatio", teamProfitConfigService.getEightShareRatio());
-        data.put("teamAwardRatio", teamProfitConfigService.getTeamAwardRatio());
-        data.put("shareTotal", teamProfitConfigService.getShareTotal());
-        data.put("awardDistribute", teamProfitConfigService.getAwardDistribute());
-        data.put("starWeight", teamProfitConfigService.getStarWeight());
-        return Result.success(data);
-    }
-
-    @Operation(summary = "保存星级档位(后台配置 #12,非 6 档拒收)")
-    @PostMapping("/config/star-tiers")
-    public Result<String> saveStarTiers(@RequestBody(required = false) Map<String, Object> body,
-                                        @RequestAttribute("role") String role,
-                                        @RequestAttribute(value = "roles", required = false) List<String> roles) {
-        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
-        if (gate != null) {
-            return Result.error(gate.getCode(), gate.getMessage());
-        }
-        if (body == null) {
-            return Result.badRequest("请求体不能为空");
-        }
-        int[] tiers = toIntArray(body.get("starTiers"));
-        if (tiers == null) {
-            return Result.badRequest("starTiers 不能为空");
-        }
-        try {
-            teamProfitConfigService.saveStarTiers(tiers);
-        } catch (IllegalArgumentException e) {
-            return Result.badRequest(e.getMessage());
-        }
-        return Result.success("星级档位已保存");
-    }
-
-    @Operation(summary = "保存团队分润配置项(写入 service_config group_key='team_profit')")
-    @PostMapping("/config/save")
-    public Result<String> saveConfig(@RequestBody(required = false) Map<String, Object> body,
-                                     @RequestAttribute("role") String role,
-                                     @RequestAttribute(value = "roles", required = false) List<String> roles) {
-        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
-        if (gate != null) {
-            return Result.error(gate.getCode(), gate.getMessage());
-        }
-        if (body == null) {
-            return Result.badRequest("请求体不能为空");
-        }
-        String key = (String) body.get("key");
-        String value = body.get("value") != null ? String.valueOf(body.get("value")) : null;
-        if (key == null || key.trim().isEmpty()) {
-            return Result.badRequest("配置键不能为空");
-        }
-        try {
-            teamProfitConfigService.saveConfig(key, value);
-        } catch (IllegalArgumentException e) {
-            return Result.badRequest(e.getMessage());
-        }
-        return Result.success("配置已保存");
-    }
-
-    // ==================== 分润流水查询(§7.3/§7.4) ====================
-
-    @Operation(summary = "8 份分佣流水分页查询(§7.3 team_share_record)")
-    @PostMapping("/flow/share-records")
-    public Result<Page<TeamShareRecord>> shareRecords(@RequestBody(required = false) Map<String, Object> body,
-                                                      @RequestAttribute("role") String role,
-                                                      @RequestAttribute(value = "roles", required = false) List<String> roles) {
-        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
-        if (gate != null) {
-            return Result.error(gate.getCode(), gate.getMessage());
-        }
-        Long recipientUserId = ParamUtils.getLong(body != null ? body.get("recipientUserId") : null);
-        String status = body != null ? (String) body.get("status") : null;
-        int page = (int) ParamUtils.getLong(body != null ? body.get("page") : null, 1L);
-        int size = (int) ParamUtils.getLong(body != null ? body.get("size") : null, 10L);
-        return Result.success(teamProfitFlowService.queryTeamShareRecords(recipientUserId, status, page, size));
-    }
-
-    @Operation(summary = "团队奖流水分页查询(§7.4 team_award_record)")
-    @PostMapping("/flow/award-records")
-    public Result<Page<TeamAwardRecord>> awardRecords(@RequestBody(required = false) Map<String, Object> body,
-                                                      @RequestAttribute("role") String role,
-                                                      @RequestAttribute(value = "roles", required = false) List<String> roles) {
-        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
-        if (gate != null) {
-            return Result.error(gate.getCode(), gate.getMessage());
-        }
-        Long teamId = ParamUtils.getLong(body != null ? body.get("teamId") : null);
-        String status = body != null ? (String) body.get("status") : null;
-        int page = (int) ParamUtils.getLong(body != null ? body.get("page") : null, 1L);
-        int size = (int) ParamUtils.getLong(body != null ? body.get("size") : null, 10L);
-        return Result.success(teamProfitFlowService.queryTeamAwardRecords(teamId, status, page, size));
-    }
-
-    // ==================== 成本价配置(§7.5) ====================
-
-    @Operation(summary = "读取服务成本价 C(分)")
-    @PostMapping("/cost/get")
-    public Result<Integer> getCost(@RequestBody(required = false) Map<String, Object> body,
-                                   @RequestAttribute("role") String role,
-                                   @RequestAttribute(value = "roles", required = false) List<String> roles) {
-        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
-        if (gate != null) {
-            return Result.error(gate.getCode(), gate.getMessage());
-        }
-        String serviceType = body != null ? (String) body.get("serviceType") : null;
-        return Result.success(serviceCostConfigService.getCostCent(serviceType));
-    }
-
-    @Operation(summary = "保存服务成本价 C(分,管理端维护)")
-    @PostMapping("/cost/save")
-    public Result<Integer> saveCost(@RequestBody(required = false) Map<String, Object> body,
-                                    @RequestAttribute("role") String role,
-                                    @RequestAttribute(value = "roles", required = false) List<String> roles) {
-        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
-        if (gate != null) {
-            return Result.error(gate.getCode(), gate.getMessage());
-        }
-        if (body == null) {
-            return Result.badRequest("请求体不能为空");
-        }
-        String serviceType = (String) body.get("serviceType");
-        String serviceName = (String) body.get("serviceName");
-        int costCent = (int) ParamUtils.getLong(body.get("costCent"), -1L);
-        if (serviceType == null || serviceType.trim().isEmpty()) {
-            return Result.badRequest("serviceType 不能为空");
-        }
-        if (costCent < 0) {
-            return Result.badRequest("costCent 不能为负数");
-        }
-        try {
-            return Result.success(serviceCostConfigService.saveCostCent(serviceType, serviceName, costCent));
-        } catch (IllegalArgumentException e) {
-            return Result.badRequest(e.getMessage());
-        }
-    }
-
-    // ==================== 提现审核(复用 withdrawal_requests,type=team_share/team_award,§11-#7) ====================
-
-    @Operation(summary = "提现审核列表(按来源 type=team_share/team_award 过滤,§11-#7)")
-    @PostMapping("/withdrawal/list")
-    public Result<Page<WithdrawalRequest>> withdrawalList(@RequestBody(required = false) Map<String, Object> body,
-                                                          @RequestAttribute("role") String role,
-                                                          @RequestAttribute(value = "roles", required = false) List<String> roles) {
-        Result<Map<String, Object>> gate = requirePlatformRole(role, roles);
-        if (gate != null) {
-            return Result.error(gate.getCode(), gate.getMessage());
-        }
-        String status = body != null ? (String) body.get("status") : null;
-        String type = body != null ? (String) body.get("type") : null;
-        int page = (int) ParamUtils.getLong(body != null ? body.get("page") : null, 1L);
-        int size = (int) ParamUtils.getLong(body != null ? body.get("size") : null, 10L);
-        return Result.success(withdrawalService.getAdminList(status, type, page, size));
-    }
-
-    // ==================== 内部辅助 ====================
-
-    /** 管理员角色门禁:平台角色(admin/operator/finance)直通;否则 403。 */
-    private Result<Map<String, Object>> requirePlatformRole(String role, List<String> roles) {
-        if ("admin".equals(role) || AdminRoles.hasAnyPlatformRole(roles)) {
-            return null;
-        }
-        return Result.forbidden("无权限:需要管理员角色");
-    }
-
-    /** 解析请求体中的 int[](接受 List<Number>/List<String>/int[]),失败返回 null。 */
-    private int[] toIntArray(Object value) {
-        if (value == null) {
-            return null;
-        }
-        if (value instanceof int[]) {
-            return ((int[]) value).clone();
-        }
-        if (value instanceof List) {
-            List<?> list = (List<?>) value;
-            int[] result = new int[list.size()];
-            for (int i = 0; i < list.size(); i++) {
-                Object item = list.get(i);
-                if (item instanceof Number) {
-                    result[i] = ((Number) item).intValue();
-                } else if (item instanceof String) {
-                    try {
-                        result[i] = Integer.parseInt(((String) item).trim());
-                    } catch (NumberFormatException e) {
-                        return null;
-                    }
-                } else {
-                    return null;
-                }
-            }
-            return result;
-        }
-        if (value instanceof String) {
-            String raw = ((String) value).replace('[', ' ').replace(']', ' ').trim();
-            if (raw.isEmpty()) {
-                return null;
-            }
-            String[] parts = raw.split("[,/]");
-            int[] result = new int[parts.length];
-            for (int i = 0; i < parts.length; i++) {
-                try {
-                    result[i] = Integer.parseInt(parts[i].trim());
-                } catch (NumberFormatException e) {
-                    return null;
-                }
-            }
-            return result;
-        }
-        return null;
-    }
-}

+ 0 - 10
cfc-backend/src/main/java/com/etotem/cfc/service/AssessmentOrderService.java

@@ -34,9 +34,6 @@ public class AssessmentOrderService extends ServiceImpl<AssessmentOrderMapper, A
     @Resource
     private CfCommissionService cfCommissionService;
 
-    @Resource
-    private ProfitPoolService profitPoolService;
-
     @Resource
     private AssessmentQuotaService assessmentQuotaService;
 
@@ -93,13 +90,6 @@ public class AssessmentOrderService extends ServiceImpl<AssessmentOrderMapper, A
             cfCommissionService.settle(order.getId(), "assessment", order.getUserId(),
                     buyerFamilyId,
                     order.getActualPrice() != null ? order.getActualPrice().intValue() : 0, null);
-            // 团队分润池钩子(§12-T3 同点位并行调用,S-cfc-62 team.profit.hook)
-            try {
-                profitPoolService.settle(order.getId(), "assessment", null,
-                        (long) (order.getActualPrice() != null ? order.getActualPrice().intValue() : 0), 0L);
-            } catch (Exception e) {
-                log.error("团队分润池核算失败: orderId={}, type=assessment, error={}", order.getId(), e.getMessage());
-            }
             // 支付成功生成测评额度(SC-P-34/SC-P-35:额度过期不可用于预约)
             grantQuotaForPaidOrder(order);
         }

+ 0 - 15
cfc-backend/src/main/java/com/etotem/cfc/service/MemberSubscriptionService.java

@@ -32,9 +32,6 @@ public class MemberSubscriptionService {
     @Resource
     private CfCommissionService cfCommissionService;
 
-    @Resource
-    private ProfitPoolService profitPoolService;
-
     @Resource
     private ButlerService butlerService;
 
@@ -168,12 +165,6 @@ public class MemberSubscriptionService {
         if (family != null && family.getCreatorId() != null) {
             cfCommissionService.settleReferrerOnly(order.getId(), "subscription", family.getCreatorId(),
                     family.getId(), amount);
-            // 团队分润池钩子(§12-T3 同点位并行调用,S-cfc-62 team.profit.hook)
-            try {
-                profitPoolService.settle(order.getId(), "subscription", null, amount, 0L);
-            } catch (Exception e) {
-                log.error("团队分润池核算失败: orderId={}, type=subscription, error={}", order.getId(), e.getMessage());
-            }
         }
 
         return subscription;
@@ -246,12 +237,6 @@ public class MemberSubscriptionService {
         if (family != null && family.getCreatorId() != null) {
             cfCommissionService.settleReferrerOnly(order.getId(), "subscription", family.getCreatorId(),
                     family.getId(), amount);
-            // 团队分润池钩子(§12-T3 同点位并行调用,S-cfc-62 team.profit.hook)
-            try {
-                profitPoolService.settle(order.getId(), "subscription", null, amount, 0L);
-            } catch (Exception e) {
-                log.error("团队分润池核算失败: orderId={}, type=subscription, error={}", order.getId(), e.getMessage());
-            }
         }
 
         return current;

+ 0 - 11
cfc-backend/src/main/java/com/etotem/cfc/service/MembershipService.java

@@ -55,9 +55,6 @@ public class MembershipService implements MembershipServiceInterface {
     @Lazy
     private CfCommissionService cfCommissionService;
 
-    @Resource
-    private ProfitPoolService profitPoolService;
-
     @Resource
     private SysConfigService sysConfigService;
 
@@ -1009,14 +1006,6 @@ public class MembershipService implements MembershipServiceInterface {
             Long buyerFamilyId = (buyer != null) ? buyer.getFamilyId() : null;
             cfCommissionService.settleReferrerOnly(order.getId(), "membership", adminUserId, buyerFamilyId, order.getAmount());
 
-            // 团队分润池钩子(§12-T3 同点位并行调用,S-cfc-62 team.profit.hook)
-            try {
-                profitPoolService.settle(order.getId(), "membership", null,
-                        order.getAmount() != null ? order.getAmount() : 0, 0L);
-            } catch (Exception e) {
-                log.error("团队分润池核算失败: orderId={}, type=membership, error={}", order.getId(), e.getMessage());
-            }
-
             log.info("会员开通完成: orderNo={}, levelCode={}, amount={}, fromLevel={}",
                     order.getOrderNo(), order.getLevelCode(), order.getAmount(), fromLevel);
 

+ 0 - 9
cfc-backend/src/main/java/com/etotem/cfc/service/PaymentService.java

@@ -67,9 +67,6 @@ public class PaymentService implements PaymentServiceInterface {
     @Resource
     private CfCommissionService cfCommissionService;
 
-    @Resource
-    private ProfitPoolService profitPoolService;
-
     @Lazy
     @Resource
     private ProductOrderService productOrderService;
@@ -281,12 +278,6 @@ public class PaymentService implements PaymentServiceInterface {
         if (updated) {
             cfCommissionService.settle(order.getId(), "package", order.getUserId(),
                     order.getFamilyId(), order.getPrice(), null);
-            // 团队分润池钩子(§12-T3 同点位并行调用,S-cfc-62 team.profit.hook)
-            try {
-                profitPoolService.settle(order.getId(), "package", null, order.getPrice(), 0L);
-            } catch (Exception e) {
-                log.error("团队分润池核算失败: orderId={}, type=package, error={}", order.getId(), e.getMessage());
-            }
         }
         return updated;
     }

+ 0 - 19
cfc-backend/src/main/java/com/etotem/cfc/service/ProductOrderService.java

@@ -100,9 +100,6 @@ public class ProductOrderService {
     @Resource
     private CfCommissionService cfCommissionService;
 
-    @Resource
-    private ProfitPoolService profitPoolService;
-
     @Resource
     private PaymentService paymentService;
 
@@ -1074,22 +1071,6 @@ public class ProductOrderService {
             log.error("CF值分佣失败: orderId={}, error={}", order.getId(), e.getMessage());
         }
 
-        // 团队分润池钩子(§12-T3 同点位并行调用,S-cfc-62 team.profit.hook)
-        try {
-            Integer paidCent = order.getMoneyAmount() != null ? order.getMoneyAmount() : order.getTotalAmount();
-            Integer costCent = 0;
-            if (order.getProductId() != null) {
-                Product hp = productMapper.selectById(order.getProductId());
-                if (hp != null && hp.getPurchasePrice() != null) {
-                    costCent = hp.getPurchasePrice();
-                }
-            }
-            profitPoolService.settle(order.getId(), "product", order.getProductId(),
-                    (long) (paidCent != null ? paidCent : 0), (long) (costCent != null ? costCent : 0));
-        } catch (Exception e) {
-            log.error("团队分润池核算失败: orderId={}, type=product, error={}", order.getId(), e.getMessage());
-        }
-
         // 原佣金结算标记为废弃,保留兼容
         // commissionService.settle(order.getId(), "product", order.getBuyerId(),
         //        order.getTotalAmount(), order.getProductId());

+ 0 - 283
cfc-backend/src/main/java/com/etotem/cfc/service/ProfitPoolService.java

@@ -1,283 +0,0 @@
-package com.etotem.cfc.service;
-
-import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.etotem.cfc.config.ConfigService;
-import com.etotem.cfc.entity.ProfitPoolOrder;
-import com.etotem.cfc.entity.ServiceConfigItem;
-import com.etotem.cfc.entity.TeamShareRecord;
-import com.etotem.cfc.mapper.ProfitPoolOrderMapper;
-import com.etotem.cfc.mapper.ServiceConfigItemMapper;
-import com.etotem.cfc.mapper.TeamAwardRecordMapper;
-import com.etotem.cfc.mapper.TeamShareRecordMapper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.Resource;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * 单笔订单利润池计算服务(规格 §2.1 总账模型 + §4.7 杠杆 1 收入管道化 + §8.3 幂等)。
- *
- * <p><b>核心职责(T9 收入管道化,能力键 {@code team.profit.pipeline})</b>:</p>
- * <ul>
- *   <li>分润触发源扩展 {@code membership / subscription / assessment_retest}(§4.7 杠杆 1),
- *       续费/复购在推荐关系存续期间持续产生分润;</li>
- *   <li>按 §2.1 对每笔订单完成利润漏斗核算(S/C/P/O/F/D/R/T + 8 份池 + 团队奖),
- *       只扩展触发源、不提高分配比率(§10#5);</li>
- *   <li>{@code D > 0} 才进入分润流程并生成 {@code team_share_record}(pending),
- *       {@code D ≤ 0}(低于保本线)整单不分润、仅落 {@code profit_pool_order} 供统计(§9#3);</li>
- *   <li>重复回调按唯一键 {@code uk_order(order_type, order_id)} 幂等(§8.3),不重复发放;</li>
- *   <li>未知触发源被拒绝(防误分配)。</li>
- * </ul>
- *
- * <p>配置读取:优先 {@link ConfigService}(缓存 + 兜底),未注入时回退
- * {@link ServiceConfigItemMapper} 直读,均缺失则用 §7.8 默认比率
- * (ops 10% / cf 1% / referral 70% / team 30% / eight 80% / award 20%)。</p>
- *
- * <p>规格:docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md v0.7
- * §2.1 + §2.2 + §4.7 杠杆 1 + §7.1 + §7.8 + §8.3 + §9#3 + §10#5 + §12-T9。</p>
- */
-@Service
-public class ProfitPoolService {
-
-    private static final Logger log = LoggerFactory.getLogger(ProfitPoolService.class);
-
-    /** §7.1 order_type 允许值(§4.7 杠杆 1 扩展 membership/subscription/assessment_retest) */
-    private static final Set<String> ALLOWED_ORDER_TYPES = new HashSet<>(Arrays.asList(
-            "product", "service", "assessment", "package",
-            "membership", "subscription", "assessment_retest"));
-
-    // §7.8 默认比率(配置未写入时使用)
-    private static final double DEFAULT_OPS_RATE = 0.10;
-    private static final double DEFAULT_CF_COST_RATE = 0.01;
-    private static final double DEFAULT_REFERRAL_SHARE = 0.70;
-    private static final double DEFAULT_TEAM_SHARE = 0.30;
-    private static final double DEFAULT_EIGHT_SHARE_RATIO = 0.80;
-    private static final double DEFAULT_TEAM_AWARD_RATIO = 0.20;
-    private static final int DEFAULT_SHARE_TOTAL = 8;
-
-    private static final String CFG_OPS_RATE = "referral_profit.ops_rate";
-    private static final String CFG_CF_COST_RATE = "referral_profit.cf_cost_rate";
-    private static final String CFG_REFERRAL_SHARE = "referral_profit.referral_share";
-    private static final String CFG_TEAM_SHARE = "referral_profit.team_share";
-    private static final String CFG_EIGHT_SHARE_RATIO = "team_profit.eight_share_ratio";
-    private static final String CFG_TEAM_AWARD_RATIO = "team_profit.team_award_ratio";
-    private static final String CFG_SHARE_TOTAL = "team_profit.share_total";
-
-    @Resource
-    private ConfigService configService;
-
-    @Resource
-    private ProfitPoolOrderMapper profitPoolOrderMapper;
-
-    @Resource
-    private TeamShareRecordMapper teamShareRecordMapper;
-
-    @Resource
-    private TeamAwardRecordMapper teamAwardRecordMapper;
-
-    @Resource
-    private ServiceConfigItemMapper serviceConfigItemMapper;
-
-    /**
-     * 分润结算入口(§12-T2 契约,能力键 {@code team.profit.settle})。
-     *
-     * <p>签名 {@code (Long orderId, String orderType, Long productId, long amountCent, long costCent)}
-     * 由契约测试 {@code ProfitPoolOrderContractRedTest} 锚定;内部与管道化入口共用核算核心。</p>
-     */
-    public ProfitPoolOrder settle(Long orderId, String orderType, Long productId,
-                                  long amountCent, long costCent) {
-        return doSettle(orderId, orderType, productId, amountCent, costCent, null);
-    }
-
-    /**
-     * 分润结算入口(§4.7 杠杆 1 收入管道化,能力键 {@code team.profit.pipeline})。
-     *
-     * <p>触发源扩展 {@code membership / subscription / assessment_retest};{@code memberId}
-     * 为订单归属成员(服务提供者/推荐链根),用于生成 {@code team_share_record} 流水。</p>
-     */
-    public ProfitPoolOrder settle(long orderId, String orderType, long memberId,
-                                  int amountCent, int costCent) {
-        return doSettle(orderId, orderType, null, amountCent, costCent, memberId);
-    }
-
-    /**
-     * 核算核心:幂等检查 → 触发源校验 → §2.1 利润漏斗 → 落单 → D>0 生成团队分润流水。
-     */
-    private ProfitPoolOrder doSettle(Long orderId, String orderType, Long productId,
-                                     long amountCent, long costCent, Long memberId) {
-        // 幂等(§8.3 uk_order):重复回调返回既有记录,不重复发放
-        ProfitPoolOrder existing = findExisting(orderId, orderType);
-        if (existing != null) {
-            return existing;
-        }
-
-        // 未知触发源拒绝(防误分配)
-        if (orderType == null || !ALLOWED_ORDER_TYPES.contains(orderType)) {
-            throw new IllegalArgumentException("未知分润触发源: " + orderType);
-        }
-
-        // §2.1 一般化公式(金额单位:分)
-        double opsRate = rate(CFG_OPS_RATE, DEFAULT_OPS_RATE);
-        double cfCostRate = rate(CFG_CF_COST_RATE, DEFAULT_CF_COST_RATE);
-        double referralShare = rate(CFG_REFERRAL_SHARE, DEFAULT_REFERRAL_SHARE);
-        double teamShare = rate(CFG_TEAM_SHARE, DEFAULT_TEAM_SHARE);
-        double eightShareRatio = rate(CFG_EIGHT_SHARE_RATIO, DEFAULT_EIGHT_SHARE_RATIO);
-        // 团队奖按预算守恒取 T−8份池(8份池占 T×80%、团队奖占 T×20%,§2.1 恒等)
-
-        long p = amountCent - costCent;
-        long o = roundPct(p, opsRate);
-        long f = roundPct(amountCent, cfCostRate);
-        long d = p - o - f;
-
-        long r;
-        long t;
-        long eight;
-        long award;
-        if (d <= 0) {
-            // §2.2/§9#3:D≤0 整单不产生推荐人/团队分润,仅落 profit_pool_order 供统计
-            r = 0;
-            t = 0;
-            eight = 0;
-            award = 0;
-        } else {
-            r = roundPct(d, referralShare);
-            t = roundPct(d, teamShare);
-            eight = roundPct(t, eightShareRatio);
-            // 预算守恒:8 份池 + 团队奖 = T(§2.1,不超 D 预算)
-            award = t - eight;
-        }
-
-        ProfitPoolOrder pool = new ProfitPoolOrder();
-        pool.setOrderId(orderId);
-        pool.setOrderType(orderType);
-        pool.setProductId(productId);
-        pool.setAmountCent((int) amountCent);
-        pool.setCostCent((int) costCent);
-        pool.setPlatformRetainCent((int) p);
-        pool.setOpsCent((int) o);
-        pool.setCfCostCent((int) f);
-        pool.setPoolCent((int) d);
-        pool.setReferralShareCent((int) r);
-        pool.setTeamShareCent((int) t);
-        pool.setTeamEightShareCent((int) eight);
-        pool.setTeamAwardCent((int) award);
-        pool.setStatus("pending");
-        pool.setCreatedAt(new Date());
-        profitPoolOrderMapper.insert(pool);
-
-        if (d > 0) {
-            // §8.1:D>0 生成团队 8 份分佣流水(pending,冷静期后 settled)
-            genTeamShareRecord(pool, memberId);
-        }
-        return pool;
-    }
-
-    /** 幂等查询:uk_order(order_type, order_id) 既有记录。 */
-    private ProfitPoolOrder findExisting(Long orderId, String orderType) {
-        if (profitPoolOrderMapper == null) {
-            return null;
-        }
-        try {
-            return profitPoolOrderMapper.selectOne(new LambdaQueryWrapper<ProfitPoolOrder>()
-                    .eq(ProfitPoolOrder::getOrderType, orderType)
-                    .eq(ProfitPoolOrder::getOrderId, orderId)
-                    .last("LIMIT 1"));
-        } catch (Exception e) {
-            log.warn("查询 profit_pool_order 幂等失败 orderType={} orderId={}: {}",
-                    orderType, orderId, e.getMessage());
-            return null;
-        }
-    }
-
-    /**
-     * 生成团队 8 份分佣流水(§7.3)。管道化(T9)阶段以订单归属成员为第 1 层基础记录,
-     * 星级/份数/金额的完整分配(§4.2 星级份数 + §4.4 团队奖)由团队分润服务按团队树与
-     * 星级快照落地(T2),此处仅落 pending 占位流水并保留 8 份池金额。
-     */
-    private void genTeamShareRecord(ProfitPoolOrder pool, Long memberId) {
-        if (teamShareRecordMapper == null) {
-            return;
-        }
-        Long uid = memberId != null ? memberId : 0L;
-        int shareTotal = intRate(CFG_SHARE_TOTAL, DEFAULT_SHARE_TOTAL);
-        int shareTotalSafe = Math.max(1, shareTotal);
-        TeamShareRecord record = new TeamShareRecord();
-        record.setOrderId(pool.getOrderId());
-        record.setOrderType(pool.getOrderType());
-        record.setPoolId(pool.getId());
-        record.setProviderUserId(uid);
-        record.setRecipientUserId(uid);
-        record.setLayer(1);
-        record.setShares(1);
-        record.setShareCent(pool.getTeamEightShareCent() / shareTotalSafe);
-        record.setStatus("pending");
-        record.setCreatedAt(new Date());
-        teamShareRecordMapper.insert(record);
-    }
-
-    /** §2.1 金额取整口径(逐项 round,HALF_UP 等价)。 */
-    private long roundPct(long base, double rate) {
-        return Math.round(base * rate);
-    }
-
-    /** 读取 double 比率:ConfigService 优先,回退 service_config 直读,再回退默认。 */
-    private double rate(String key, double def) {
-        if (configService != null) {
-            return configService.getDoubleConfig(key, def);
-        }
-        return readConfigDouble(key, def);
-    }
-
-    /** 读取 int 配置:ConfigService 优先,回退 service_config 直读,再回退默认。 */
-    private int intRate(String key, int def) {
-        if (configService != null) {
-            return configService.getIntConfig(key, def);
-        }
-        return readConfigInt(key, def);
-    }
-
-    private double readConfigDouble(String key, double def) {
-        String v = readConfigValue(key);
-        if (v == null) {
-            return def;
-        }
-        try {
-            return Double.parseDouble(v.trim());
-        } catch (NumberFormatException e) {
-            return def;
-        }
-    }
-
-    private int readConfigInt(String key, int def) {
-        String v = readConfigValue(key);
-        if (v == null) {
-            return def;
-        }
-        try {
-            return Integer.parseInt(v.trim());
-        } catch (NumberFormatException e) {
-            return def;
-        }
-    }
-
-    private String readConfigValue(String key) {
-        if (serviceConfigItemMapper == null) {
-            return null;
-        }
-        try {
-            ServiceConfigItem item = serviceConfigItemMapper.selectOne(
-                    new LambdaQueryWrapper<ServiceConfigItem>()
-                            .eq(ServiceConfigItem::getConfigKey, key)
-                            .last("LIMIT 1"));
-            return item != null ? item.getConfigValue() : null;
-        } catch (Exception e) {
-            log.warn("读取团队分润配置失败 key={}: {}", key, e.getMessage());
-            return null;
-        }
-    }
-}

+ 3 - 15
cfc-backend/src/main/java/com/etotem/cfc/service/StarDigestService.java

@@ -41,7 +41,7 @@ public class StarDigestService {
     public static final int MIN_STAR = 1;
     public static final int MAX_STAR = 6;
 
-    /** 星级业绩分门槛(§4.3 推荐默认值,index = 星级-1;与 StarScoreCalculator 默认档位一致)。 */
+    /** 星级业绩分门槛(§4.3 推荐默认值,index = 星级-1)。 */
     private static final int[] DEFAULT_STAR_THRESHOLDS = {0, 8_000, 25_000, 70_000, 140_000, 250_000};
 
     /** 差距→行动换算率(§4.3.1 ②:直接服务 250 分/次、团队带教 200 分/次、推荐消费 10 分/百元)。 */
@@ -52,9 +52,6 @@ public class StarDigestService {
     @Resource
     private TeamStarSnapshotMapper teamStarSnapshotMapper;
 
-    @Resource
-    private StarScoreCalculator starScoreCalculator;
-
     // ==================== 三态分类(§4.3.1 ③) ====================
 
     /**
@@ -180,10 +177,8 @@ public class StarDigestService {
         if (current != null) {
             currentStar = current.getStarLevel() == null ? MIN_STAR : current.getStarLevel();
             currentScore = current.getScore() == null ? 0 : current.getScore().intValue();
-        } else if (starScoreCalculator != null) {
-            currentScore = starScoreCalculator.totalScore(userId);
-            currentStar = starScoreCalculator.starForScore(currentScore);
         } else {
+            // 快照缺失:旧体系 StarScoreCalculator 已随 T07 废弃,不再做实时聚合,回退一星/0 分
             currentStar = MIN_STAR;
             currentScore = 0;
         }
@@ -283,16 +278,9 @@ public class StarDigestService {
         }
     }
 
-    /** 星级业绩分门槛:优先读实时计算组件(后台可配),缺失回退 §4.3 默认档位。 */
+    /** 星级业绩分门槛:旧体系实时计算组件已随 T07 废弃,统一回退 §4.3 默认档位(归档只读口径)。 */
     private int thresholdOfStar(int starLevel) {
         int star = clampStar(starLevel);
-        if (starScoreCalculator != null) {
-            try {
-                return starScoreCalculator.thresholdOfStar(star);
-            } catch (Exception e) {
-                log.warn("读取星级档位失败,回退 §4.3 默认值:{}", e.getMessage());
-            }
-        }
         return DEFAULT_STAR_THRESHOLDS[star - 1];
     }
 

+ 0 - 512
cfc-backend/src/main/java/com/etotem/cfc/service/StarScoreCalculator.java

@@ -1,512 +0,0 @@
-package com.etotem.cfc.service;
-
-import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.etotem.cfc.dto.StarConversionPathVO;
-import com.etotem.cfc.dto.StarConversionRatesVO;
-import com.etotem.cfc.dto.StarDimensionBreakdownVO;
-import com.etotem.cfc.dto.StarDualThresholdProgressVO;
-import com.etotem.cfc.dto.StarTrajectoryPointVO;
-import com.etotem.cfc.dto.TeamStarMyViewVO;
-import com.etotem.cfc.entity.TeamStarSnapshot;
-import com.etotem.cfc.mapper.TeamProfitStatsMapper;
-import com.etotem.cfc.mapper.TeamStarSnapshotMapper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.Resource;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.List;
-
-/**
- * 星级业绩分计算 / 实时聚合组件(§4.3 + §4.3.1)。
- *
- * <p>规格:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md}
- * §4.3 星级定义(滚动 12 个月加权业绩分 → 档位映射 + 升级双门槛)+ §4.3.1 星级透明化
- * (实时看板 / 三维构成 / 距下一档差距 / 双门槛进度 / 三条换算路径 / 近 12 月轨迹)
- * + §11-#15 拍板(团队直推 = 直接邀请加入团队 + 成交首个服务/商品单,首单即算无金额门槛)。</p>
- *
- * <p><b>业绩分</b>(§4.3 公式,金额单位为元口径):</p>
- * <pre>
- *   Score = 直接服务收入 × 50% + 团队服务收入 × 40% + 推荐用户平台消费收入 × 10%
- * </pre>
- *
- * <p><b>星级↔档位映射</b>(推荐默认值,对应可配 {@code team_profit.star_tiers},见 §7.8):</p>
- * <pre>
- *   score ≥ 0       → 一星(入团即一星)  拿 1 份
- *   score ≥ 8,000   → 二星                拿 2 份
- *   score ≥ 25,000  → 三星                拿 3 份
- *   score ≥ 70,000  → 四星                拿 4 份
- *   score ≥ 140,000 → 五星                拿 5 份
- *   score ≥ 250,000 → 六星                拿 6 份(最多)
- * </pre>
- *
- * <p><b>升级双门槛</b>(主理人意见⑥ / #15 拍板):升级条件 = <b>业绩分 ≥ 目标档门槛</b>
- * 且 <b>本窗口团队直推 ≥ 1</b>,两条件缺一不可;一星为入团基线,无直推门槛;
- * 降星自动(滚动窗口滑出,不保留历史级别、不固化)。</p>
- *
- * <p><b>纯计算 vs 实时聚合</b>:本组件的档位/加权/双门槛判定为纯函数(无 DB),供月度重评
- * ({@code TeamProfitCronTask})与分润快照(§8.1 支付成功时刻星级)共用;
- * 另按 §4.3.1「数据与接口」提供实时聚合查询({@link #totalScore(long)} /
- * {@link #dimensionBreakdown(long)} / {@link #dualThresholdProgress(long)} /
- * {@link #conversionPaths(int)} / {@link #twelveMonthTrajectory(long)} /
- * {@link #myView(long)}),数据源 {@code TeamProfitStatsMapper} + {@code TeamStarSnapshotMapper}。
- * 纯反射契约场景(未注入 Spring 依赖)下自动回退默认值,方法仍可安全调用。</p>
- */
-@Service
-public class StarScoreCalculator {
-
-    private static final Logger log = LoggerFactory.getLogger(StarScoreCalculator.class);
-
-    /** 最低/最高星级 */
-    public static final int MIN_STAR = 1;
-    public static final int MAX_STAR = 6;
-
-    /** 星级业绩分门槛(§4.3 推荐校准值,index = 星级-1,对应 team_profit.star_tiers 默认值)。 */
-    private static final int[] DEFAULT_STAR_THRESHOLDS = {0, 8_000, 25_000, 70_000, 140_000, 250_000};
-
-    /** 业绩分权重:直接服务 50% / 团队服务 40% / 推荐消费 10%(§4.3,可配 team_profit.star_weight)。 */
-    private static final int[] DEFAULT_WEIGHTS = {50, 40, 10};
-
-    /** 差距→行动换算率(§4.3.1 ②:¥500/次基准,可配 team_profit.star_conversion)。 */
-    private static final int[] DEFAULT_CONVERSION = {250, 200, 10};
-
-    /** 单次咨询基准金额(元,§4.3.1 ②)。 */
-    private static final int BASE_CONSULT_FEE_YUAN = 500;
-
-    /** 团队直推要求(§4.3:滚动 12 个月 ≥ 1)。 */
-    private static final int DIRECT_NEW_REF_REQUIRED = 1;
-
-    /**
-     * 业绩分门槛量级下界:用于消解 {@link #isPromotable(long, int, int)} 的调用约定歧义。
-     * 业绩分门槛以「分」为量级(默认最小档 8,000),团队直推数以「人」为量级(个位数),
-     * 故 &gt;= 1000 的第二参数视为门槛、&lt;=6 的第三参数视为星级/直推计数。
-     */
-    private static final int SCORE_THRESHOLD_FLOOR = 1_000;
-
-    /** 月度快照轨迹窗口(§4.3.1 ①:近 12 个月)。 */
-    private static final int TRAJECTORY_MONTHS = 12;
-
-    @Resource
-    private TeamProfitConfigService teamProfitConfigService;
-
-    @Resource
-    private TeamProfitStatsMapper teamProfitStatsMapper;
-
-    @Resource
-    private TeamStarSnapshotMapper teamStarSnapshotMapper;
-
-    // ==================== 纯计算:业绩分 / 档位 / 双门槛(§4.3) ====================
-
-    /**
-     * 业绩分:直接×50% + 团队×40% + 推荐×10%(§4.3)。金额单位为元口径。
-     */
-    public long calculateScore(long directServiceAmount, long teamServiceAmount, long referralConsumeAmount) {
-        return weightedScore(directServiceAmount, teamServiceAmount, referralConsumeAmount);
-    }
-
-    /**
-     * 业绩分(int 口径别名,契约 {@code team.star.myView}):直接×50% + 团队×40% + 推荐×10%。
-     *
-     * <p>权重读 {@code team_profit.star_weight}(默认 50/40/10);纯反射场景回退默认值。</p>
-     */
-    public int weightedScore(long directRevenueYuan, long teamRevenueYuan, long referralConsumeYuan) {
-        int[] w = loadWeights();
-        long score = Math.round(directRevenueYuan * w[0] / 100.0
-                + teamRevenueYuan * w[1] / 100.0
-                + referralConsumeYuan * w[2] / 100.0);
-        return (int) Math.max(0L, score);
-    }
-
-    /**
-     * 星级业绩分门槛(§4.3 档位表):1→0 / 2→8000 / 3→25000 / 4→70000 / 5→140000 / 6→250000。
-     *
-     * <p>读 {@code team_profit.star_tiers}(#12 后台可配),异常或缺失时回退推荐默认值。</p>
-     */
-    public int thresholdOfStar(int star) {
-        int[] tiers = loadStarTiers();
-        return tiers[clampStar(star) - 1];
-    }
-
-    /** 星级业绩分门槛(契约别名 {@code team.star.myView})。 */
-    public int starThreshold(int starLevel) {
-        return thresholdOfStar(starLevel);
-    }
-
-    /**
-     * 业绩分 → 星级档位映射(入团即一星)。等价于 {@link #resolveStarLevel(long)}。
-     */
-    public int starForScore(long score) {
-        int[] tiers = loadStarTiers();
-        int star = MIN_STAR;
-        for (int s = MIN_STAR + 1; s <= MAX_STAR; s++) {
-            if (score >= tiers[s - 1]) {
-                star = s;
-            } else {
-                break;
-            }
-        }
-        return star;
-    }
-
-    /**
-     * 业绩分 → 星级档位映射(§4.3 档位表,别名以匹配跨契约命名)。
-     */
-    public int resolveStarLevel(long score) {
-        return starForScore(score);
-    }
-
-    /**
-     * 距下一档星级差距(§4.3.1 ①:如「距四星还差 12,000 分」= 70,000 − 58,000)。
-     *
-     * @param totalScore      当前业绩分总分
-     * @param currentStarLevel 当前星级(1-6)
-     * @return 差距分(&gt;= 0;已达六星返回 0)
-     */
-    public int gapToNextStar(int totalScore, int currentStarLevel) {
-        int current = clampStar(currentStarLevel);
-        if (current >= MAX_STAR) {
-            return 0;
-        }
-        return Math.max(0, thresholdOfStar(current + 1) - totalScore);
-    }
-
-    /**
-     * 升级双门槛判定(§4.3 判定规则 / #15 拍板)。
-     *
-     * <p><b>兼容两种调用约定</b>(两者参数个数相同,契约侧均以 {@code isPromotable} 命名):</p>
-     * <ul>
-     *   <li>看板约定 {@code (score, scoreThreshold, directValidNewRefs)}:业绩分得分门槛由调用方
-     *       直接给出({@code team.star.myView});</li>
-     *   <li>重评约定 {@code (score, directValidNewRefs, targetStar)}:按目标星级查档位门槛
-     *       ({@code team.profit.cron})。</li>
-     * </ul>
-     * <p>判别规则:第二参数为「分」量级(&gt;= {@value #SCORE_THRESHOLD_FLOOR})且第三参数
-     * 为小整数(&lt;= 6)时按看板约定;否则按重评约定。两种约定的判定本质一致:
-     * <b>score ≥ 门槛 AND 团队直推 ≥ 1</b>。</p>
-     */
-    public boolean isPromotable(long score, int second, int third) {
-        if (second >= SCORE_THRESHOLD_FLOOR && third <= MAX_STAR) {
-            // 看板约定:(score, scoreThreshold, directValidNewRefs)
-            return score >= second && third >= DIRECT_NEW_REF_REQUIRED;
-        }
-        // 重评约定:(score, directValidNewRefs, targetStar)
-        return isPromotableByStar(score, second, third);
-    }
-
-    /**
-     * 升级双门槛判定(按目标星级查档位门槛):{@code score ≥ threshold(targetStar) AND refs ≥ 1}。
-     * 一星为入团基线(targetStar ≤ 1 恒可)。
-     */
-    public boolean isPromotableByStar(long score, int directValidNewRefs, int targetStar) {
-        int target = clampStar(targetStar);
-        if (target <= MIN_STAR) {
-            return true;
-        }
-        return score >= thresholdOfStar(target) && directValidNewRefs >= DIRECT_NEW_REF_REQUIRED;
-    }
-
-    /**
-     * 月度重评(§4.3 升降规则):
-     * <ul>
-     *   <li>升星:业绩分达标到更高档 <b>且</b> 团队直推 ≥1 才升级(双门槛);否则维持当前档</li>
-     *   <li>降星:滚动窗口滑出业绩分下降 → 自动降级(不保留历史级别、不固化)</li>
-     * </ul>
-     *
-     * @param score              滚动 12 个月加权业绩分
-     * @param directValidNewRefs 滚动 12 个月团队直推有效新用户数
-     * @param currentStar        当前星级(上一档快照)
-     * @return 重评后星级(1-6)
-     */
-    public int reEvaluateStar(long score, int directValidNewRefs, int currentStar) {
-        int current = clampStar(currentStar);
-        int natural = starForScore(score);
-        if (natural > current) {
-            // 升星需过升级双门槛;不达标维持当前档
-            return isPromotableByStar(score, directValidNewRefs, natural) ? natural : current;
-        }
-        // 降星自动(含持平)
-        return natural;
-    }
-
-    // ==================== 实时聚合:业绩分 / 三维构成 / 双门槛进度(§4.3.1 ①) ====================
-
-    /** 实时业绩分总分(滚动 12 个月加权,§4.3.1 ①)。 */
-    public int totalScore(long userId) {
-        long[] cent = loadRevenueCent(userId);
-        return weightedScore(cent[0] / 100L, cent[1] / 100L, cent[2] / 100L);
-    }
-
-    /** 实时星级(滚动 12 个月业绩分 → 档位映射,§4.3/§4.3.1)。 */
-    public int currentStarLevel(long userId) {
-        return starForScore(totalScore(userId));
-    }
-
-    /** 三维构成条:直接服务 / 团队服务 / 推荐消费各自贡献分与合计(§4.3.1 ①)。 */
-    public StarDimensionBreakdownVO dimensionBreakdown(long userId) {
-        long[] cent = loadRevenueCent(userId);
-        StarDimensionBreakdownVO vo = new StarDimensionBreakdownVO();
-        vo.setDirectRevenueYuan(cent[0] / 100L);
-        vo.setTeamRevenueYuan(cent[1] / 100L);
-        vo.setReferralConsumeYuan(cent[2] / 100L);
-        vo.setDirectScore(weightedScore(vo.getDirectRevenueYuan(), 0L, 0L));
-        vo.setTeamScore(weightedScore(0L, vo.getTeamRevenueYuan(), 0L));
-        vo.setReferralConsumeScore(weightedScore(0L, 0L, vo.getReferralConsumeYuan()));
-        // 合计取一次性加权(与 totalScore(userId) 口径一致,避免分项四舍五入误差)
-        vo.setTotalScore(weightedScore(vo.getDirectRevenueYuan(), vo.getTeamRevenueYuan(),
-                vo.getReferralConsumeYuan()));
-        return vo;
-    }
-
-    /** 升级双门槛进度:业绩分 ✓ + 团队直推 ✓ 分项打勾(§4.3.1 ①)。 */
-    public StarDualThresholdProgressVO dualThresholdProgress(long userId) {
-        int score = totalScore(userId);
-        int current = starForScore(score);
-        boolean atTop = current >= MAX_STAR;
-        int target = atTop ? MAX_STAR : current + 1;
-        int threshold = thresholdOfStar(target);
-        int refs = loadDirectValidNewRefs(userId);
-
-        StarDualThresholdProgressVO vo = new StarDualThresholdProgressVO();
-        vo.setTargetStarLevel(target);
-        vo.setScoreCurrent(score);
-        vo.setScoreThreshold(threshold);
-        vo.setScorePassed(atTop || score >= threshold);
-        vo.setDirectNewRefCurrent(refs);
-        vo.setDirectNewRefRequired(DIRECT_NEW_REF_REQUIRED);
-        vo.setDirectNewRefPassed(atTop || refs >= DIRECT_NEW_REF_REQUIRED);
-        vo.setPromotable(atTop || (vo.isScorePassed() && vo.isDirectNewRefPassed()));
-        vo.setHint(buildProgressHint(atTop, target, score, threshold, refs));
-        return vo;
-    }
-
-    // ==================== 差距→行动换算(§4.3.1 ②) ====================
-
-    /** 换算率表(直接 250/次、团队 200/次、推荐 10/百元,可配 team_profit.star_conversion)。 */
-    public StarConversionRatesVO conversionRates() {
-        int[] rates = loadConversion();
-        StarConversionRatesVO vo = new StarConversionRatesVO();
-        vo.setSessionFeeYuan(BASE_CONSULT_FEE_YUAN);
-        vo.setDirectPerSession(rates[0]);
-        vo.setTeamPerSession(rates[1]);
-        vo.setReferralPer100Yuan(rates[2]);
-        return vo;
-    }
-
-    /**
-     * 三条达标路径(A 直接服务 / B 团队带教 / C 推荐消费),按「最容易够到」
-     * (所需单位由小到大)排序(§4.3.1 ②)。
-     *
-     * @param gap 距下一档差距分(&lt;= 0 时各路径所需单位均为 0)
-     */
-    public List<StarConversionPathVO> conversionPaths(int gap) {
-        int rest = Math.max(0, gap);
-        int[] rates = loadConversion();
-        List<StarConversionPathVO> paths = new ArrayList<>(3);
-        paths.add(buildSessionPath("DIRECT", "A 直接服务", "次 1对1 咨询", rates[0], rest));
-        paths.add(buildSessionPath("TEAM", "B 团队带教", "次带教服务", rates[1], rest));
-        paths.add(buildReferralPath(rates[2], rest));
-        paths.sort(Comparator.comparingInt(StarConversionPathVO::getRequiredUnits));
-        return paths;
-    }
-
-    // ==================== 近 12 月星级轨迹(§4.3.1 ① + §7.6 team_star_snapshot) ====================
-
-    /** 近 12 月星级轨迹(读 {@code team_star_snapshot},按 period 升序)。 */
-    public List<StarTrajectoryPointVO> twelveMonthTrajectory(long userId) {
-        List<StarTrajectoryPointVO> points = new ArrayList<>();
-        if (teamStarSnapshotMapper == null) {
-            return points;
-        }
-        try {
-            List<TeamStarSnapshot> snapshots = teamStarSnapshotMapper.selectList(
-                    new LambdaQueryWrapper<TeamStarSnapshot>()
-                            .eq(TeamStarSnapshot::getUserId, userId)
-                            .orderByDesc(TeamStarSnapshot::getPeriod)
-                            .last("LIMIT " + TRAJECTORY_MONTHS));
-            if (snapshots != null) {
-                // 倒序查询 → 升序输出,便于前端画曲线
-                for (int i = snapshots.size() - 1; i >= 0; i--) {
-                    TeamStarSnapshot s = snapshots.get(i);
-                    if (s == null) {
-                        continue;
-                    }
-                    StarTrajectoryPointVO p = new StarTrajectoryPointVO();
-                    p.setPeriod(s.getPeriod());
-                    p.setStarLevel(s.getStarLevel() == null ? MIN_STAR : s.getStarLevel());
-                    p.setScore(s.getScore() == null ? 0 : s.getScore().intValue());
-                    points.add(p);
-                }
-            }
-        } catch (Exception e) {
-            log.warn("近 12 月星级轨迹查询失败(userId={}),返回空轨迹:{}", userId, e.getMessage());
-        }
-        return points;
-    }
-
-    // ==================== 看板聚合(§12-T7 POST /api/team-star/my-view) ====================
-
-    /** 组装「我的星级」看板聚合视图(§4.3.1 ①②)。 */
-    public TeamStarMyViewVO myView(long userId) {
-        int score = totalScore(userId);
-        int star = starForScore(score);
-        int gap = gapToNextStar(score, star);
-        Date windowStart = rollingWindowStart();
-        Date windowEnd = new Date();
-
-        TeamStarMyViewVO vo = new TeamStarMyViewVO();
-        vo.setCurrentStarLevel(star);
-        vo.setNextStarLevel(Math.min(MAX_STAR, star + 1));
-        vo.setTotalScore(score);
-        vo.setDimensionBreakdown(dimensionBreakdown(userId));
-        vo.setGapToNextStar(gap);
-        vo.setDualThresholdProgress(dualThresholdProgress(userId));
-        vo.setConversionPaths(conversionPaths(gap));
-        vo.setTwelveMonthTrajectory(twelveMonthTrajectory(userId));
-        vo.setWindowStart(formatDate(windowStart));
-        vo.setWindowEnd(formatDate(windowEnd));
-        vo.setWindowLabel("统计期:" + vo.getWindowStart() + " ~ " + vo.getWindowEnd());
-        return vo;
-    }
-
-    // ==================== 内部辅助:配置读取(可配项,缺失回退默认) ====================
-
-    private int[] loadStarTiers() {
-        if (teamProfitConfigService != null) {
-            try {
-                int[] tiers = teamProfitConfigService.getStarTiers();
-                if (tiers != null && tiers.length == MAX_STAR) {
-                    return tiers;
-                }
-            } catch (Exception e) {
-                log.warn("读取星级档位失败,回退 §4.3 默认六档:{}", e.getMessage());
-            }
-        }
-        return DEFAULT_STAR_THRESHOLDS.clone();
-    }
-
-    private int[] loadWeights() {
-        if (teamProfitConfigService != null) {
-            try {
-                int[] weights = teamProfitConfigService.getStarWeight();
-                if (weights != null && weights.length == 3) {
-                    return weights;
-                }
-            } catch (Exception e) {
-                log.warn("读取星级权重失败,回退 §4.3 默认 50/40/10:{}", e.getMessage());
-            }
-        }
-        return DEFAULT_WEIGHTS.clone();
-    }
-
-    private int[] loadConversion() {
-        if (teamProfitConfigService != null) {
-            try {
-                int[] conversion = teamProfitConfigService.getStarConversion();
-                if (conversion != null && conversion.length == 3) {
-                    return conversion;
-                }
-            } catch (Exception e) {
-                log.warn("读取换算率失败,回退 §4.3.1 默认 250/200/10:{}", e.getMessage());
-            }
-        }
-        return DEFAULT_CONVERSION.clone();
-    }
-
-    // ==================== 内部辅助:数据查询(缺依赖/异常一律兜底 0,保证看板可打开) ====================
-
-    /** 滚动 12 个月窗口内的直接/团队/推荐收入(分)。 */
-    private long[] loadRevenueCent(long userId) {
-        long direct = 0L;
-        long team = 0L;
-        long referral = 0L;
-        if (teamProfitStatsMapper != null) {
-            try {
-                Date windowStart = rollingWindowStart();
-                direct = teamProfitStatsMapper.selectDirectServiceAmountCent(userId, windowStart);
-                team = teamProfitStatsMapper.selectTeamServiceAmountCent(userId, windowStart);
-                referral = teamProfitStatsMapper.selectReferralConsumeAmountCent(userId, windowStart);
-            } catch (Exception e) {
-                log.warn("星级看板业绩统计失败(userId={}),按 0 兜底:{}", userId, e.getMessage());
-            }
-        }
-        return new long[]{Math.max(0L, direct), Math.max(0L, team), Math.max(0L, referral)};
-    }
-
-    /** 滚动 12 个月团队直推有效新用户数(#15:团队树首单即算)。 */
-    private int loadDirectValidNewRefs(long userId) {
-        if (teamProfitStatsMapper == null) {
-            return 0;
-        }
-        try {
-            return Math.max(0, teamProfitStatsMapper.countDirectValidNewRefs(userId, rollingWindowStart()));
-        } catch (Exception e) {
-            log.warn("团队直推统计失败(userId={}),按 0 兜底:{}", userId, e.getMessage());
-            return 0;
-        }
-    }
-
-    // ==================== 内部辅助:换算路径构造 / 窗口 / 日期 ====================
-
-    private StarConversionPathVO buildSessionPath(String type, String label, String unitLabel, int rate, int gap) {
-        int units = rate <= 0 ? 0 : (gap + rate - 1) / rate;
-        StarConversionPathVO path = new StarConversionPathVO();
-        path.setType(type);
-        path.setLabel(label);
-        path.setRate(rate);
-        path.setRequiredUnits(units);
-        path.setUnitLabel(unitLabel);
-        path.setRequiredYuan(units * BASE_CONSULT_FEE_YUAN);
-        return path;
-    }
-
-    private StarConversionPathVO buildReferralPath(int ratePer100Yuan, int gap) {
-        int units = ratePer100Yuan <= 0 ? 0 : (gap + ratePer100Yuan - 1) / ratePer100Yuan;
-        StarConversionPathVO path = new StarConversionPathVO();
-        path.setType("REFERRAL");
-        path.setLabel("C 推荐消费");
-        path.setRate(ratePer100Yuan);
-        path.setRequiredUnits(units);
-        path.setUnitLabel("百元推荐消费");
-        path.setRequiredYuan(units * 100);
-        return path;
-    }
-
-    private String buildProgressHint(boolean atTop, int target, int score, int threshold, int refs) {
-        if (atTop) {
-            return "已达最高星级(六星)";
-        }
-        boolean scorePassed = score >= threshold;
-        boolean refsPassed = refs >= DIRECT_NEW_REF_REQUIRED;
-        if (!scorePassed && !refsPassed) {
-            return "距 " + target + " 星还差 " + (threshold - score) + " 分,且还差 "
-                    + (DIRECT_NEW_REF_REQUIRED - refs) + " 个团队直推";
-        }
-        if (!scorePassed) {
-            return "距 " + target + " 星还差 " + (threshold - score) + " 分";
-        }
-        if (!refsPassed) {
-            return "升级还差 " + (DIRECT_NEW_REF_REQUIRED - refs)
-                    + " 个团队直推,去邀请好友加入团队并完成首单";
-        }
-        return "双门槛已达标,可升级到 " + target + " 星";
-    }
-
-    private Date rollingWindowStart() {
-        Calendar cal = Calendar.getInstance();
-        cal.add(Calendar.MONTH, -TRAJECTORY_MONTHS);
-        return cal.getTime();
-    }
-
-    private String formatDate(Date date) {
-        return new SimpleDateFormat("yyyy-MM-dd").format(date);
-    }
-
-    private int clampStar(int star) {
-        return Math.min(Math.max(star, MIN_STAR), MAX_STAR);
-    }
-}

+ 0 - 92
cfc-backend/src/main/java/com/etotem/cfc/service/TeamProfitFlowService.java

@@ -1,92 +0,0 @@
-package com.etotem.cfc.service;
-
-import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.etotem.cfc.entity.TeamAwardRecord;
-import com.etotem.cfc.entity.TeamShareRecord;
-import com.etotem.cfc.mapper.TeamAwardRecordMapper;
-import com.etotem.cfc.mapper.TeamShareRecordMapper;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.Resource;
-
-/**
- * 团队分润流水查询服务(能力键 {@code team.admin.manage},单元 admin,§12-T5 流水查询)。
- *
- * <p>契约溯源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
- * §7.3 + §7.4 + §12-T5。</p>
- *
- * <p><b>宿主契约方法</b>:
- * <ul>
- *   <li>{@code Page<TeamShareRecord> queryTeamShareRecords(Long recipientUserId, String status, int page, int size)}
- *       — 8 份分佣流水查询(§7.3 team_share_record)</li>
- *   <li>{@code Page<TeamAwardRecord> queryTeamAwardRecords(Long teamId, String status, int page, int size)}
- *       — 团队奖流水查询(§7.4 team_award_record)</li>
- * </ul>
- *
- * <p>纯反射契约上下文(无 Spring)下 Mapper 未注入时返回空页,不抛异常。</p>
- *
- * <p><b>规格:docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md v0.7
- * §7.3 + §7.4 + §12-T5。</b></p>
- */
-@Service
-public class TeamProfitFlowService {
-
-    @Resource
-    private TeamShareRecordMapper teamShareRecordMapper;
-
-    @Resource
-    private TeamAwardRecordMapper teamAwardRecordMapper;
-
-    /**
-     * 8 份分佣流水分页查询(§7.3 team_share_record),按接收人/状态过滤。
-     *
-     * @param recipientUserId 获得分润的团队成员(可空)
-     * @param status          流水状态 pending/settled/cancelled(可空/空串 = 不过滤)
-     * @param page            页码(&lt;1 按 1)
-     * @param size            每页条数(&lt;1 按 1)
-     */
-    public Page<TeamShareRecord> queryTeamShareRecords(Long recipientUserId, String status, int page, int size) {
-        int p = Math.max(page, 1);
-        int s = Math.max(size, 1);
-        Page<TeamShareRecord> pageParam = new Page<>(p, s);
-        LambdaQueryWrapper<TeamShareRecord> wrapper = new LambdaQueryWrapper<TeamShareRecord>()
-                .orderByDesc(TeamShareRecord::getCreatedAt);
-        if (recipientUserId != null) {
-            wrapper.eq(TeamShareRecord::getRecipientUserId, recipientUserId);
-        }
-        if (status != null && !status.trim().isEmpty()) {
-            wrapper.eq(TeamShareRecord::getStatus, status.trim());
-        }
-        if (teamShareRecordMapper == null) {
-            return pageParam;
-        }
-        return teamShareRecordMapper.selectPage(pageParam, wrapper);
-    }
-
-    /**
-     * 团队奖流水分页查询(§7.4 team_award_record),按团队/状态过滤。
-     *
-     * @param teamId 归属服务团队(distribution_systems.id,可空)
-     * @param status 流水状态 pending/settled/cancelled(可空/空串 = 不过滤)
-     * @param page   页码(&lt;1 按 1)
-     * @param size   每页条数(&lt;1 按 1)
-     */
-    public Page<TeamAwardRecord> queryTeamAwardRecords(Long teamId, String status, int page, int size) {
-        int p = Math.max(page, 1);
-        int s = Math.max(size, 1);
-        Page<TeamAwardRecord> pageParam = new Page<>(p, s);
-        LambdaQueryWrapper<TeamAwardRecord> wrapper = new LambdaQueryWrapper<TeamAwardRecord>()
-                .orderByDesc(TeamAwardRecord::getCreatedAt);
-        if (teamId != null) {
-            wrapper.eq(TeamAwardRecord::getTeamId, teamId);
-        }
-        if (status != null && !status.trim().isEmpty()) {
-            wrapper.eq(TeamAwardRecord::getStatus, status.trim());
-        }
-        if (teamAwardRecordMapper == null) {
-            return pageParam;
-        }
-        return teamAwardRecordMapper.selectPage(pageParam, wrapper);
-    }
-}

+ 0 - 316
cfc-backend/src/main/java/com/etotem/cfc/service/TeamProfitService.java

@@ -1,316 +0,0 @@
-package com.etotem.cfc.service;
-
-import com.etotem.cfc.entity.TeamAwardRecord;
-import com.etotem.cfc.entity.TeamShareRecord;
-
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
-/**
- * 团队分润服务(能力键 {@code team.star.multiplier},单元 team)。
- *
- * <p>契约溯源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
- * §12-T10 + §4.7.2 杠杆 2/3/4 + §11-#14 + §10#5。
- *
- * <p><b>宿主契约方法(按规格落地)</b>:
- * <ul>
- *   <li>{@code double starMultiplier(int starLevel)} — 返回该星级倍率系数(1-6★)</li>
- *   <li>{@code double starWeight(int starLevel)} — 返回权重 W = 星级 × 倍率</li>
- *   <li>{@code Map<Integer,Double> starMultiplierTable()} — 返回 6 档默认倍率表(1★..6★)</li>
- *   <li>{@code List<Long> allocateEightShareByWeight(int[] starLevels, long eightSharePoolCent)}
- *       — 按星级权重分配 8 份池,返回每人分得(分);0 表示该层无人(份额回流,不私发)</li>
- *   <li>{@code int mentorMilestoneTierBonus(int fiveStarMentees)} — 带出 5★ 成员数 → 团队奖档位偏移</li>
- *   <li>{@code boolean mentorMilestoneCapAndCandidates(int fiveStarMentees)}
- *       — 带出 ≥2 名 5★ → 比例上限 100% + 年度星耀会候选人</li>
- *   <li>{@code long orderSharePendingCent(long orderId, long userId)} — 订单完成本单团队分润(分,pending 可见)</li>
- * </ul>
- *
- * <p><b>核心规则(§4.7.2)</b>:
- * <ul>
- *   <li>默认倍率:1★=1.0, 2★=1.0, 3★=1.2, 4★=1.5, 5★=2.0, 6★=3.0;权重 W = 星级 × 倍率</li>
- *   <li>8 份池 = T×80%(只重分不增量,不超 T 预算)</li>
- *   <li>分配采用最大余数法,保证 Σ = 8 份池(整数精度守恒)</li>
- *   <li>星耀导师:带出 1 名 5★ → 档位 +1;2 名 5★ → 比例上限 100% + 年度星耀会候选人</li>
- *   <li>实时可见:D ≤ 0 订单本单分润为 0(只记录不发放)</li>
- * </ul>
- *
- * <p>本类为纯契约实现(无 Spring 依赖,可反射实例化);杠杆 4 的真实读取在
- * {@code profit_pool_order} / 结算链路(§12-T2/T3)接通后,经注入的 Mapper 完成,
- * 当前以确定性演示值桥接契约测试。
- */
-public class TeamProfitService {
-
-    // ==================== 契约常量(规格 §4.7.2 默认值) ====================
-
-    /** 标准 ¥500 咨询:D=17000、T=5100、8 份池 = T×80% = 4080 分(§4.7.2 示例)。 */
-    public static final long DEFAULT_EIGHT_SHARE_POOL = 4080L;
-
-    /** 默认 6 档倍率表:1-2 星 1.0 / 3 星 1.2 / 4 星 1.5 / 5 星 2.0 / 6 星 3.0。 */
-    private static final Map<Integer, Double> DEFAULT_MULTIPLIER_TABLE;
-
-    static {
-        Map<Integer, Double> table = new LinkedHashMap<>();
-        table.put(1, 1.0);
-        table.put(2, 1.0);
-        table.put(3, 1.2);
-        table.put(4, 1.5);
-        table.put(5, 2.0);
-        table.put(6, 3.0);
-        DEFAULT_MULTIPLIER_TABLE = java.util.Collections.unmodifiableMap(table);
-    }
-
-    public TeamProfitService() {
-        // no-arg constructor for reflection instantiation
-    }
-
-    // ==================== 杠杆 2:星级倍率表 ====================
-
-    /**
-     * 返回该星级的倍率系数 f(星)。越界星级返回 1.0(无倾斜)。
-     */
-    public double starMultiplier(int starLevel) {
-        if (starLevel < 1 || starLevel > 6) {
-            return 1.0;
-        }
-        return DEFAULT_MULTIPLIER_TABLE.get(starLevel);
-    }
-
-    /**
-     * 返回权重 W = 星级 × 倍率系数;星级 ≤ 0 返回 0(无人层无权重)。
-     */
-    public double starWeight(int starLevel) {
-        if (starLevel <= 0) {
-            return 0.0;
-        }
-        return starLevel * starMultiplier(starLevel);
-    }
-
-    /**
-     * 返回 6 档默认倍率表(1★..6★),按星级升序。
-     */
-    public Map<Integer, Double> starMultiplierTable() {
-        Map<Integer, Double> table = new LinkedHashMap<>();
-        for (int i = 1; i <= 6; i++) {
-            table.put(i, DEFAULT_MULTIPLIER_TABLE.get(i));
-        }
-        return table;
-    }
-
-    // ==================== 杠杆 2:8 份池按权重分配 + 只重分不增量 ====================
-
-    /**
-     * 按星级权重分配 8 份池。
-     *
-     * <p>规则(§4.7.2):
-     * <ul>
-     *   <li>每层权重 W = 星级 × 倍率;0 星级 = 该层无人 → 权重 0(份额回流,不私发)</li>
-     *   <li>总权重 ΣW &gt; 0 时:份额 = round(8份池 × Wi / ΣW),采用最大余数法保证 Σ份额 = 8 份池</li>
-     *   <li>ΣW ≤ 0 或池 ≤ 0 时:所有层分得 0</li>
-     * </ul>
-     *
-     * @param starLevels          各层星级(长度 = 服务链层数,1-3);0 = 该层无人
-     * @param eightSharePoolCent  8 份池金额(分)
-     * @return 各层分得份额(分),顺序与输入对应;无人层为 0
-     */
-    public List<Long> allocateEightShareByWeight(int[] starLevels, long eightSharePoolCent) {
-        int layers = starLevels.length;
-        double[] weights = new double[layers];
-        for (int i = 0; i < layers; i++) {
-            weights[i] = (starLevels[i] > 0) ? starWeight(starLevels[i]) : 0.0;
-        }
-
-        double totalW = 0;
-        for (double w : weights) {
-            totalW += w;
-        }
-
-        long[] shares = new long[layers];
-        if (totalW > 0 && eightSharePoolCent > 0) {
-            // 最大余数法:先向下取整,再把余量按小数部分降序逐层 +1,保证 Σ = 池
-            long[] floorShares = new long[layers];
-            double[] remainders = new double[layers];
-            long sumFloor = 0;
-            for (int i = 0; i < layers; i++) {
-                double exact = eightSharePoolCent * weights[i] / totalW;
-                floorShares[i] = (long) exact;
-                remainders[i] = exact - floorShares[i];
-                sumFloor += floorShares[i];
-            }
-            long leftover = eightSharePoolCent - sumFloor;
-
-            int[] idx = IntStream.range(0, layers).boxed()
-                    .sorted((a, b) -> Double.compare(remainders[b], remainders[a]))
-                    .mapToInt(x -> x).toArray();
-            for (int k = 0; k < leftover && k < layers; k++) {
-                if (weights[idx[k]] > 0) {
-                    floorShares[idx[k]]++;
-                }
-            }
-            // 无人层(权重 0)恒为 0(回流,不私发)
-            for (int i = 0; i < layers; i++) {
-                shares[i] = (weights[i] > 0) ? floorShares[i] : 0;
-            }
-        }
-
-        return java.util.Arrays.stream(shares).boxed().collect(Collectors.toList());
-    }
-
-    // ==================== 杠杆 3:带教里程碑奖(星耀导师) ====================
-
-    /**
-     * 带出 5★ 成员数 → 团队奖档位偏移。
-     *
-     * <p>规则(§4.7.2 杠杆 3):带出 1 名 5★ → 团队奖档位自动 +1 档(TA1→TA2);
-     * 多名不叠加档位(里程碑仅触发一次)。
-     */
-    public int mentorMilestoneTierBonus(int fiveStarMentees) {
-        return (fiveStarMentees >= 1) ? 1 : 0;
-    }
-
-    /**
-     * 带出 ≥2 名 5★ → 团队奖比例上限 100% + 年度星耀会候选人。
-     */
-    public boolean mentorMilestoneCapAndCandidates(int fiveStarMentees) {
-        return fiveStarMentees >= 2;
-    }
-
-    // ==================== 杠杆 4:订单完成实时显示本单分润 ====================
-
-    /**
-     * 订单完成本单团队分润(分,pending 可见)。
-     *
-     * <p>真实运行时:查询 {@code profit_pool_order} 已结算 8 份池,按用户在服务链中的权重计算。
-     * <p>纯契约上下文(无 Spring / 无 DB / 无外部依赖):确定性演示桥接——
-     * <ul>
-     *   <li>订单 1001(标准 ¥500 咨询,D&gt;0):返回典型服务者分润 3672 分(6★ 权重示例)</li>
-     *   <li>订单 1002(D ≤ 0 低于保本线):返回 0(只记录不发放,§4.7.2 杠杆 4 边界)</li>
-     *   <li>其它正向订单:返回正演示值(非测试用例路径)</li>
-     * </ul>
-     */
-    public long orderSharePendingCent(long orderId, long userId) {
-        if (orderId == 1002L) {
-            // D ≤ 0 边界:低于保本线,本单不分润(只记录不发放)
-            return 0L;
-        }
-        if (orderId == 1001L) {
-            // 标准正向订单:典型服务者分润(6★ 权重示例,§4.7.2 数学校验)
-            return 3672L;
-        }
-        // 其它正向订单:返回稳定正演示值(当前测试不覆盖)
-        return DEFAULT_EIGHT_SHARE_POOL / 3;
-    }
-
-    // ==================== 杠杆 1 基线:8 份分佣(§4.2 #5 拍板)+ 团队奖(§4.4 #3 拍板) ====================
-
-    /** §7.8 team_profit.share_total 默认 8(8 份分佣)。 */
-    private static final int SHARE_TOTAL = 8;
-
-    /**
-     * §4.2 8 份分佣:按层分配份额并生成 {@code team_share_record} 流水(未落库,返回列表)。
-     *
-     * <p>规则(#5 拍板):L1(服务者本人)/L2(引荐人)/L3(再上级) 逐层分得 min(当期星级, 剩余);
-     * 每层最多 6 份;星级=0 或该层无成员 → 无人层位,份额回流(§9#4),不产出记录;
-     * shareCent = round(8份池 × 份数 / 8)。</p>
-     *
-     * @param poolId             来源 profit_pool_order.id
-     * @param orderId            来源订单ID
-     * @param orderType          触发源类型
-     * @param providerUserId     服务提供者(规划师/测评师)
-     * @param eightSharePoolCent 8 份分佣池(分,默认 T×80%)
-     * @param recipientUserIds   第 i+1 层成员 userId(与 layerStarLevels 对齐;0 = 该层无人)
-     * @param layerStarLevels    第 i+1 层成员当期星级快照(1~6;0 = 该层无人)
-     * @return team_share_record 流水列表(按 layer 升序;无人层位 0 回流不产出记录)
-     */
-    public List<TeamShareRecord> allocateEightShares(Long poolId, Long orderId, String orderType,
-                                                     Long providerUserId, long eightSharePoolCent,
-                                                     long[] recipientUserIds, int[] layerStarLevels) {
-        List<TeamShareRecord> records = new ArrayList<>();
-        if (recipientUserIds == null || layerStarLevels == null) {
-            return records;
-        }
-        long remaining = SHARE_TOTAL;
-        int layers = Math.min(recipientUserIds.length, layerStarLevels.length);
-        for (int i = 0; i < layers && remaining > 0; i++) {
-            int star = layerStarLevels[i];
-            long recipient = recipientUserIds[i];
-            if (star <= 0 || recipient <= 0) {
-                continue; // 该层无人 → 份额回流,不产出记录(§9#4)
-            }
-            int shares = (int) Math.min(star, remaining);
-            if (shares <= 0) {
-                continue;
-            }
-            long shareCent = Math.round(eightSharePoolCent * shares / 8.0);
-
-            TeamShareRecord r = new TeamShareRecord();
-            r.setPoolId(poolId);
-            r.setOrderId(orderId);
-            r.setOrderType(orderType);
-            r.setProviderUserId(providerUserId);
-            r.setRecipientUserId(recipient);
-            r.setLayer(i + 1);
-            r.setStarLevel(star);
-            r.setShares(shares);
-            r.setShareCent((int) shareCent);
-            r.setStatus("pending");
-            records.add(r);
-            remaining -= shares;
-        }
-        return records;
-    }
-
-    /**
-     * §4.4 团队奖:按团队年度滚动业绩分档,生成 {@code team_award_record}(未落库,返回记录)。
-     *
-     * <p>分档(thr = 团队年度滚动业绩门槛):rev &lt; thr → TA0 0%;thr ≤ rev &lt; 2×thr → TA1 50%;
-     * 2×thr ≤ rev &lt; 4×thr → TA2 80%;rev ≥ 4×thr → TA3 100%。awardCent = round(团队奖池 × 比例)。
-     * 归属平台自有团队负责人(ownerUserId,#3 拍板)。</p>
-     *
-     * @param poolId                来源 profit_pool_order.id
-     * @param orderId               来源订单ID
-     * @param orderType             触发源类型
-     * @param teamId                所属平台服务团队(distribution_systems.id)
-     * @param ownerUserId           平台自有团队负责人(#3 拍板)
-     * @param teamAwardPoolCent     团队奖池(分,默认 T×20%)
-     * @param teamThresholdCent     团队年度滚动业绩门槛(分)
-     * @param teamRollingRevenueCent 团队年度滚动总服务业绩(分)
-     * @return team_award_record(状态 pending;TA0 时 awardCent=0 回流平台)
-     */
-    public TeamAwardRecord buildTeamAward(Long poolId, Long orderId, String orderType, Long teamId,
-                                          Long ownerUserId, long teamAwardPoolCent, long teamThresholdCent,
-                                          long teamRollingRevenueCent) {
-        long rev = teamRollingRevenueCent;
-        long thr = teamThresholdCent;
-        String tier;
-        double ratio;
-        if (rev < thr) {
-            tier = "TA0";
-            ratio = 0.0;
-        } else if (rev < 2 * thr) {
-            tier = "TA1";
-            ratio = 0.50;
-        } else if (rev < 4 * thr) {
-            tier = "TA2";
-            ratio = 0.80;
-        } else {
-            tier = "TA3";
-            ratio = 1.00;
-        }
-        long award = Math.round(teamAwardPoolCent * ratio);
-
-        TeamAwardRecord r = new TeamAwardRecord();
-        r.setPoolId(poolId);
-        r.setOrderId(orderId);
-        r.setOrderType(orderType);
-        r.setTeamId(teamId);
-        r.setOwnerUserId(ownerUserId);
-        r.setTier(tier);
-        r.setAwardCent((int) award);
-        r.setStatus("pending");
-        return r;
-    }
-}

+ 0 - 376
cfc-backend/src/main/java/com/etotem/cfc/task/TeamProfitCronTask.java

@@ -1,376 +0,0 @@
-package com.etotem.cfc.task;
-
-import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import com.etotem.cfc.entity.DistributionRelation;
-import com.etotem.cfc.entity.ProfitPoolOrder;
-import com.etotem.cfc.entity.TeamAwardRecord;
-import com.etotem.cfc.entity.TeamShareRecord;
-import com.etotem.cfc.entity.TeamStarSnapshot;
-import com.etotem.cfc.mapper.DistributionRelationMapper;
-import com.etotem.cfc.mapper.ProfitPoolOrderMapper;
-import com.etotem.cfc.mapper.TeamAwardRecordMapper;
-import com.etotem.cfc.mapper.TeamProfitStatsMapper;
-import com.etotem.cfc.mapper.TeamShareRecordMapper;
-import com.etotem.cfc.mapper.TeamStarSnapshotMapper;
-import com.etotem.cfc.service.StarDigestService;
-import com.etotem.cfc.service.StarScoreCalculator;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Component;
-import org.springframework.transaction.annotation.Transactional;
-
-import javax.annotation.Resource;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-
-/**
- * 团队分润定时任务(§12-T4 + §8)。
- *
- * <p>规格:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md}
- * v0.7 §8.1 状态机(pending → 冷静期 7 天 → 定时任务批量置 settled 入可提现余额;
- * 冷静期内退款 → 全部 cancelled、金额回流平台)+ §8.2 冷静期与退款(7 天退款全退、
- * 7 天后自动 settled)+ §4.3 月度星级重评(升级双门槛:业绩分 ≥ 目标档门槛 且
- * 滚动 12 个月团队直推 ≥1,见 §11-#15 拍板;落 {@code team_star_snapshot} 快照)
- * + §9 边界 #7(退款跨冷静期 → 已 settled 需冲正)。</p>
- *
- * <p><b>批次入口</b>:</p>
- * <ul>
- *   <li>{@link #settleDuePendingRecords()} 每日 03:00 冷静期满结算</li>
- *   <li>{@link #reevaluateMonthlyStars()} 每月 1 日 00:30 星级重评落快照</li>
- *   <li>{@link #cancelTeamRecordsForRefund(long)} 冷静期内退款冲销(退款服务回调)</li>
- *   <li>{@link #reverseSettledBalanceForCrossCoolingRefund(long)} 跨冷静期退款冲正(§9#7)</li>
- * </ul>
- */
-@Slf4j
-@Component
-public class TeamProfitCronTask {
-
-    /** 冷静期 7 天(§8.2,与退款窗口对齐)。 */
-    public static final int COOLING_PERIOD_DAYS = 7;
-
-    /** 月度星级重评 cron:每月 1 日 00:30(§4.3 重评周期)。 */
-    public static final String MONTHLY_STAR_REEVAL_CRON = "0 30 0 1 * ?";
-
-    /** 冷静期结算 cron:每日 03:00(低峰)。 */
-    public static final String SETTLE_CRON = "0 0 3 * * ?";
-
-    private static final long DAY_MS = 24L * 60 * 60 * 1000;
-
-    @Resource
-    private TeamShareRecordMapper teamShareRecordMapper;
-
-    @Resource
-    private TeamAwardRecordMapper teamAwardRecordMapper;
-
-    @Resource
-    private ProfitPoolOrderMapper profitPoolOrderMapper;
-
-    @Resource
-    private TeamStarSnapshotMapper teamStarSnapshotMapper;
-
-    @Resource
-    private TeamProfitStatsMapper teamProfitStatsMapper;
-
-    @Resource
-    private DistributionRelationMapper distributionRelationMapper;
-
-    @Resource
-    private StarScoreCalculator starScoreCalculator;
-
-    @Resource
-    private StarDigestService starDigestService;
-
-    // ==================== §8.2 冷静期常量与判定 ====================
-
-    /** 冷静期天数(默认 7,§8.2 与退款窗口对齐)。 */
-    public int coolingPeriodDays() {
-        return COOLING_PERIOD_DAYS;
-    }
-
-    /** 支付时刻距今是否仍在冷静期内(now &lt; paidAt + 7 天)。 */
-    public boolean isWithinCoolingPeriod(long paidAtEpochMs, long nowEpochMs) {
-        return nowEpochMs < paidAtEpochMs + (long) COOLING_PERIOD_DAYS * DAY_MS;
-    }
-
-    // ==================== §8.1 冷静期满 → 批量结算入可提现余额 ====================
-
-    /**
-     * 冷静期满批量结算:支付满 7 天的 pending 分润(team_share_record / team_award_record)
-     * 置为 settled,入「可提现余额」(货币账本,余额由 settled 记录聚合派生);同步推进
-     * profit_pool_order 主单状态(§8.1 状态机)。
-     *
-     * @return 处理条数(team_share + team_award)
-     */
-    @Scheduled(cron = SETTLE_CRON)
-    @Transactional(rollbackFor = Exception.class)
-    public int settleDuePendingRecords() {
-        Date cutoff = new Date(System.currentTimeMillis() - (long) COOLING_PERIOD_DAYS * DAY_MS);
-        int processed = 0;
-        if (teamShareRecordMapper != null) {
-            List<TeamShareRecord> shares = teamShareRecordMapper.selectList(
-                    new LambdaQueryWrapper<TeamShareRecord>()
-                            .eq(TeamShareRecord::getStatus, "pending")
-                            .le(TeamShareRecord::getCreatedAt, cutoff));
-            for (TeamShareRecord r : shares) {
-                r.setStatus("settled");
-                teamShareRecordMapper.updateById(r);
-            }
-            processed += shares.size();
-            log.info("团队分润冷静期结算: team_share_record 结算 {} 条", shares.size());
-        }
-        if (teamAwardRecordMapper != null) {
-            List<TeamAwardRecord> awards = teamAwardRecordMapper.selectList(
-                    new LambdaQueryWrapper<TeamAwardRecord>()
-                            .eq(TeamAwardRecord::getStatus, "pending")
-                            .le(TeamAwardRecord::getCreatedAt, cutoff));
-            for (TeamAwardRecord r : awards) {
-                r.setStatus("settled");
-                teamAwardRecordMapper.updateById(r);
-            }
-            processed += awards.size();
-            log.info("团队分润冷静期结算: team_award_record 结算 {} 条", awards.size());
-        }
-        if (profitPoolOrderMapper != null) {
-            List<ProfitPoolOrder> pools = profitPoolOrderMapper.selectList(
-                    new LambdaQueryWrapper<ProfitPoolOrder>()
-                            .eq(ProfitPoolOrder::getStatus, "pending")
-                            .le(ProfitPoolOrder::getCreatedAt, cutoff));
-            for (ProfitPoolOrder p : pools) {
-                p.setStatus("settled");
-                p.setSettledAt(new Date());
-                profitPoolOrderMapper.updateById(p);
-            }
-            log.info("团队分润冷静期结算: profit_pool_order 主单同步 {} 条", pools.size());
-        }
-        log.info("团队分润冷静期结算完成: 处理 {} 条", processed);
-        return processed;
-    }
-
-    // ==================== §8.2 冷静期内退款:全部 cancelled、资金不发放 ====================
-
-    /**
-     * 冷静期内订单退款:对应 team_share_record / team_award_record 全部置为 cancelled
-     * (资金不发放,金额回流平台见 {@link #refundRefluxAmountCent(long)}),
-     * profit_pool_order 主单同步 cancelled(§8.1/§8.2)。
-     *
-     * @return 取消条数(team_share + team_award)
-     */
-    @Transactional(rollbackFor = Exception.class)
-    public int cancelTeamRecordsForRefund(long orderId) {
-        int cancelled = 0;
-        if (teamShareRecordMapper != null) {
-            List<TeamShareRecord> shares = teamShareRecordMapper.selectList(
-                    new LambdaQueryWrapper<TeamShareRecord>()
-                            .eq(TeamShareRecord::getOrderId, orderId)
-                            .ne(TeamShareRecord::getStatus, "cancelled"));
-            for (TeamShareRecord r : shares) {
-                r.setStatus("cancelled");
-                teamShareRecordMapper.updateById(r);
-            }
-            cancelled += shares.size();
-        }
-        if (teamAwardRecordMapper != null) {
-            List<TeamAwardRecord> awards = teamAwardRecordMapper.selectList(
-                    new LambdaQueryWrapper<TeamAwardRecord>()
-                            .eq(TeamAwardRecord::getOrderId, orderId)
-                            .ne(TeamAwardRecord::getStatus, "cancelled"));
-            for (TeamAwardRecord r : awards) {
-                r.setStatus("cancelled");
-                teamAwardRecordMapper.updateById(r);
-            }
-            cancelled += awards.size();
-        }
-        if (profitPoolOrderMapper != null) {
-            List<ProfitPoolOrder> pools = profitPoolOrderMapper.selectList(
-                    new LambdaQueryWrapper<ProfitPoolOrder>()
-                            .eq(ProfitPoolOrder::getOrderId, orderId)
-                            .ne(ProfitPoolOrder::getStatus, "cancelled"));
-            for (ProfitPoolOrder p : pools) {
-                p.setStatus("cancelled");
-                profitPoolOrderMapper.updateById(p);
-            }
-        }
-        log.info("订单 {} 冷静期内退款: 取消分润记录 {} 条", orderId, cancelled);
-        return cancelled;
-    }
-
-    // ==================== §9 边界 #7 退款跨冷静期:已 settled 冲正 ====================
-
-    /**
-     * 退款跨冷静期(已 settled)冲正(§9 边界 #7):把订单对应已 settled / pending 的
-     * team_share_record / team_award_record 全部置 cancelled —— settled 余额由记录聚合派生,
-     * 取消即等价于「cancelled + 余额扣减」,资金不再可提现,回流平台。
-     *
-     * @return 冲正操作是否成功完成
-     */
-    @Transactional(rollbackFor = Exception.class)
-    public boolean reverseSettledBalanceForCrossCoolingRefund(long orderId) {
-        int reversed = cancelTeamRecordsForRefund(orderId);
-        log.info("订单 {} 跨冷静期退款冲正: 冲销 {} 条分润记录(已 settled 余额扣减)", orderId, reversed);
-        return true;
-    }
-
-    /**
-     * 取消/冲正后分润金额回流平台(分,≥0):订单对应 team_share_record + team_award_record
-     * 原分润金额合计(含本次置 cancelled 的记录)。
-     */
-    public long refundRefluxAmountCent(long orderId) {
-        long reflux = 0L;
-        if (teamShareRecordMapper != null) {
-            List<TeamShareRecord> shares = teamShareRecordMapper.selectList(
-                    new LambdaQueryWrapper<TeamShareRecord>()
-                            .eq(TeamShareRecord::getOrderId, orderId));
-            for (TeamShareRecord r : shares) {
-                reflux += r.getShareCent() == null ? 0L : r.getShareCent();
-            }
-        }
-        if (teamAwardRecordMapper != null) {
-            List<TeamAwardRecord> awards = teamAwardRecordMapper.selectList(
-                    new LambdaQueryWrapper<TeamAwardRecord>()
-                            .eq(TeamAwardRecord::getOrderId, orderId));
-            for (TeamAwardRecord r : awards) {
-                reflux += r.getAwardCent() == null ? 0L : r.getAwardCent();
-            }
-        }
-        return reflux;
-    }
-
-    // ==================== §4.3 月度星级重评:调度与快照 ====================
-
-    /** 月度重评 cron 表达式(每月 1 日 00:30)。 */
-    public String monthlyStarReevalCron() {
-        return MONTHLY_STAR_REEVAL_CRON;
-    }
-
-    /** 快照周期 YYYYMM(对应 §7.6 team_star_snapshot.period,唯一键 uk_user_period)。 */
-    public String snapshotPeriod(int year, int month) {
-        return String.format("%04d%02d", year, month);
-    }
-
-    /**
-     * 月度星级重评批次:对团队树全部成员重评并落 {@code team_star_snapshot} 快照。
-     * 每月 1 日 00:30 执行(§4.3 重评周期)。
-     */
-    @Scheduled(cron = MONTHLY_STAR_REEVAL_CRON)
-    public void reevaluateMonthlyStars() {
-        if (distributionRelationMapper == null || teamStarSnapshotMapper == null) {
-            return;
-        }
-        Calendar now = Calendar.getInstance();
-        int year = now.get(Calendar.YEAR);
-        int month = now.get(Calendar.MONTH) + 1;
-        try {
-            List<Object> userIds = distributionRelationMapper.selectObjs(
-                    new QueryWrapper<DistributionRelation>().select("DISTINCT user_id"));
-            int done = 0;
-            for (Object id : userIds) {
-                if (id == null) {
-                    continue;
-                }
-                try {
-                    long userId = ((Number) id).longValue();
-                    int star = snapshotMonthlyStar(userId, year, month);
-                    done++;
-                    log.info("月度星级重评: userId={} period={} 星级={}", userId, snapshotPeriod(year, month), star);
-                } catch (Exception e) {
-                    log.warn("月度星级重评失败(单用户跳过): userId={} period={}: {}", id,
-                            snapshotPeriod(year, month), e.getMessage());
-                }
-            }
-            log.info("月度星级重评完成: 共 {} 人", done);
-            // §4.3.1 ③ / §12-T8:重评落快照后立即生成并推送月度星级简报(升/降/持平 + 行动建议)
-            if (starDigestService != null) {
-                try {
-                    starDigestService.pushMonthlyDigests(year, month);
-                } catch (Exception e) {
-                    log.warn("月度星级简报推送失败(不影响重评结果): {}", e.getMessage());
-                }
-            }
-        } catch (Exception e) {
-            log.error("月度星级重评批次执行失败", e);
-        }
-    }
-
-    /**
-     * 单用户月度星级重评:按滚动 12 个月业绩分 + 升级双门槛重评并落快照。
-     *
-     * @return 本期星级(1-6)
-     */
-    public int snapshotMonthlyStar(long userId, int year, int month) {
-        String period = snapshotPeriod(year, month);
-        Calendar cal = Calendar.getInstance();
-        cal.clear();
-        cal.set(year, month - 1, 1, 0, 0, 0);
-        Date monthStart = cal.getTime();
-        cal.add(Calendar.MONTH, -12);
-        Date windowStart = cal.getTime();
-
-        long directCent = 0L;
-        long teamCent = 0L;
-        long referralCent = 0L;
-        int directValidNewRefs = 0;
-        if (teamProfitStatsMapper != null) {
-            try {
-                directCent = teamProfitStatsMapper.selectDirectServiceAmountCent(userId, windowStart);
-                teamCent = teamProfitStatsMapper.selectTeamServiceAmountCent(userId, windowStart);
-                referralCent = teamProfitStatsMapper.selectReferralConsumeAmountCent(userId, windowStart);
-                directValidNewRefs = teamProfitStatsMapper.countDirectValidNewRefs(userId, windowStart);
-            } catch (Exception e) {
-                log.warn("月度星级重评统计查询失败(userId={}): {}", userId, e.getMessage());
-            }
-        }
-
-        // §4.3 业绩分(金额 分 → 元口径)与升级双门槛
-        long score = 0L;
-        int newStar = StarScoreCalculator.MIN_STAR;
-        int currentStar = StarScoreCalculator.MIN_STAR;
-        if (starScoreCalculator != null) {
-            score = starScoreCalculator.calculateScore(directCent / 100L, teamCent / 100L, referralCent / 100L);
-        }
-
-        if (teamStarSnapshotMapper != null) {
-            // 上一期星级(无历史则入团基线一星)
-            TeamStarSnapshot prev = teamStarSnapshotMapper.selectOne(
-                    new LambdaQueryWrapper<TeamStarSnapshot>()
-                            .eq(TeamStarSnapshot::getUserId, userId)
-                            .orderByDesc(TeamStarSnapshot::getPeriod)
-                            .last("LIMIT 1"));
-            if (prev != null && prev.getStarLevel() != null) {
-                currentStar = prev.getStarLevel();
-            }
-            if (starScoreCalculator != null) {
-                newStar = starScoreCalculator.reEvaluateStar(score, directValidNewRefs, currentStar);
-            }
-            // 落快照(幂等 upsert:uk_user_period)
-            TeamStarSnapshot snap = teamStarSnapshotMapper.selectOne(
-                    new LambdaQueryWrapper<TeamStarSnapshot>()
-                            .eq(TeamStarSnapshot::getUserId, userId)
-                            .eq(TeamStarSnapshot::getPeriod, period));
-            boolean isNew = snap == null;
-            if (isNew) {
-                snap = new TeamStarSnapshot();
-                snap.setCreatedAt(new Date());
-            }
-            snap.setUserId(userId);
-            snap.setStarLevel(newStar);
-            snap.setScore(score);
-            snap.setDirectRevCent(directCent);
-            snap.setTeamRevCent(teamCent);
-            snap.setReferralConsumeCent(referralCent);
-            snap.setPeriod(period);
-            if (isNew) {
-                teamStarSnapshotMapper.insert(snap);
-            } else {
-                teamStarSnapshotMapper.updateById(snap);
-            }
-        } else if (starScoreCalculator != null) {
-            newStar = starScoreCalculator.reEvaluateStar(score, directValidNewRefs, StarScoreCalculator.MIN_STAR);
-        }
-
-        log.info("月度星级重评(userId={}, period={}): score={}, 直推={}, 星级 {}→{}",
-                userId, period, score, directValidNewRefs, currentStar, newStar);
-        return newStar;
-    }
-}

+ 0 - 249
cfc-backend/src/test/java/com/etotem/cfc/unit/TeamProfitPipelineContractTest.java

@@ -1,249 +0,0 @@
-package com.etotem.cfc.unit;
-
-import com.baomidou.mybatisplus.core.conditions.Wrapper;
-import com.etotem.cfc.entity.ProfitPoolOrder;
-import com.etotem.cfc.entity.TeamAwardRecord;
-import com.etotem.cfc.entity.TeamShareRecord;
-import com.etotem.cfc.mapper.ProfitPoolOrderMapper;
-import com.etotem.cfc.mapper.ServiceConfigItemMapper;
-import com.etotem.cfc.mapper.TeamAwardRecordMapper;
-import com.etotem.cfc.mapper.TeamShareRecordMapper;
-import com.etotem.cfc.service.ProfitPoolService;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-import java.lang.reflect.Field;
-import java.util.concurrent.atomic.AtomicLong;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-/**
- * 能力键 {@code team.profit.pipeline}(单元 team)契约级单测(S-cfc-48,TDD-RED 阶段)。
- *
- * <p>契约溯源:{@code docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md} v0.7
- * §12-T9(收入管道化)+ §4.7 杠杆 1(触发源扩展 / 续费复购持续分润)+ §7.1(profit_pool_order
- * 表)+ §7.8(team_profit 配置)+ §10#5(合规:只扩触发源、不提比率)。</p>
- *
- * <p><b>契约范围</b>:{@code profit_pool_order} 分润触发源扩展
- * {@code membership / subscription / assessment_retest},且推荐关系存续期间
- * 续费/复购**持续**产生分润(收入管道化)——只扩展触发源、不提高分配比率。</p>
- *
- * <p><b>覆盖流</b>(纯 Mockito,无 Spring 上下文 / 无 DB / 无外部服务):</p>
- * <ul>
- *   <li><b>正常流</b>:三种新增触发源各自落单并完成 §2.1 池核算(S-C-O-F-D-R-T);续费/复购
- *       跨订单持续分润;重复回调按唯一键 {@code uk_order(order_type, order_id)} 幂等;</li>
- *   <li><b>边界流</b>:{@code D ≤ 0}(低于保本线)整单不分润、仅落 profit_pool_order 供统计;
- *       未知触发源被拒绝(防误分配);</li>
- *   <li><b>合规/权限流</b>:只扩触发源、不提比率——新增触发源的团队分润比率仍为默认 30%
- *       (8 份池 80% / 团队奖 20%),不因管道化而放大资金池(§10#5)。</li>
- * </ul>
- *
- * <p><b>数学校验锚点</b>(§2.1 一般化公式,金额单位分):取 {@code S=20000, C=8000}:</p>
- * <pre>
- *   P = S - C = 12000
- *   O = round(P × 10%) = 1200
- *   F = round(S × 1%)  = 200
- *   D = P - O - F = 10600
- *   R = round(D × 70%) = 7420   (推荐人体系,CF 值预算参照)
- *   T = round(D × 30%) = 3180   (团队体系,货币直接分佣——本次新增,比率不变)
- *   8份池 = round(T × 80%) = 2544
- *   团队奖 = round(T × 20%) = 636
- * </pre>
- *
- * <p>⚠ 本类引用的 {@link ProfitPoolService} / {@link ProfitPoolOrder} /
- * {@link TeamShareRecord} / {@link TeamAwardRecord} 及其 Mapper 为 T9 契约目标类,
- * 当前 {@code src/main} 尚未落地(真实缺口)——测试先行定义契约,编译失败即 RED 信号,
- * 由后续 GREEN 实现使本契约通过。</p>
- */
-class TeamProfitPipelineContractTest {
-
-    /** §7.1 order_type 允许值:T9 扩展后新增三种触发源(§4.7 杠杆 1) */
-    private static final String TYPE_MEMBERSHIP = "membership";
-    private static final String TYPE_SUBSCRIPTION = "subscription";
-    private static final String TYPE_ASSESSMENT_RETEST = "assessment_retest";
-
-    /** §2.1 数学校验锚点 */
-    private static final int S = 20000;
-    private static final int C = 8000;
-    private static final int P = 12000;
-    private static final int O = 1200;
-    private static final int F = 200;
-    private static final int D = 10600;
-    private static final int R = 7420;
-    private static final int T = 3180;
-    private static final int EIGHT_SHARE = 2544;
-    private static final int AWARD = 636;
-
-    private ProfitPoolService service;
-    private ProfitPoolOrderMapper profitPoolOrderMapper;
-    private TeamShareRecordMapper teamShareRecordMapper;
-    private TeamAwardRecordMapper teamAwardRecordMapper;
-    private ServiceConfigItemMapper serviceConfigItemMapper;
-    private AtomicLong idSeq;
-
-    @BeforeEach
-    void setUp() throws Exception {
-        service = new ProfitPoolService();
-        profitPoolOrderMapper = mock(ProfitPoolOrderMapper.class);
-        teamShareRecordMapper = mock(TeamShareRecordMapper.class);
-        teamAwardRecordMapper = mock(TeamAwardRecordMapper.class);
-        serviceConfigItemMapper = mock(ServiceConfigItemMapper.class);
-        idSeq = new AtomicLong(1L);
-
-        inject(service, "profitPoolOrderMapper", profitPoolOrderMapper);
-        inject(service, "teamShareRecordMapper", teamShareRecordMapper);
-        inject(service, "teamAwardRecordMapper", teamAwardRecordMapper);
-        inject(service, "serviceConfigItemMapper", serviceConfigItemMapper);
-
-        // §7.8 配置未显式写入时使用默认值(ops 10% / cf 1% / referral 70% / team 30% / eight 80% / award 20%)
-        when(serviceConfigItemMapper.selectOne(any(Wrapper.class))).thenReturn(null);
-        // 落库自增 id(模拟 MySQL AUTO_INCREMENT)
-        when(profitPoolOrderMapper.insert(any(ProfitPoolOrder.class))).thenAnswer(inv -> {
-            ProfitPoolOrder o = inv.getArgument(0);
-            if (o.getId() == null) {
-                o.setId(idSeq.getAndIncrement());
-            }
-            return 1;
-        });
-    }
-
-    private static void inject(Object target, String field, Object value) throws Exception {
-        Field f = target.getClass().getDeclaredField(field);
-        f.setAccessible(true);
-        f.set(target, value);
-    }
-
-    // ==================== 正常流:新增触发源各自落单核算 ====================
-
-    @Test
-    void 正常流_membership触发源_落单核算() {
-        assertSettled(TYPE_MEMBERSHIP, 1001L);
-    }
-
-    @Test
-    void 正常流_subscription触发源_落单核算() {
-        assertSettled(TYPE_SUBSCRIPTION, 1002L);
-    }
-
-    @Test
-    void 正常流_assessmentRetest触发源_落单核算() {
-        assertSettled(TYPE_ASSESSMENT_RETEST, 1003L);
-    }
-
-    /**
-     * 契约断言:某新增触发源订单经 {@link ProfitPoolService#settle} 后,
-     * 必须落一条 {@code profit_pool_order},按 §2.1 完成 S/C/P/O/F/D/R/T 与
-     * 8 份池/团队奖核算,状态 {@code pending}(冷静期后结算),且触发团队持续分润。
-     */
-    private void assertSettled(String orderType, long orderId) {
-        ProfitPoolOrder record = service.settle(orderId, orderType, 5L, S, C);
-
-        assertNotNull(record, orderType + " 结算后必须返回 profit_pool_order 记录");
-        assertEquals(orderType, record.getOrderType(), "触发源类型应原样落库");
-        assertEquals(Long.valueOf(orderId), record.getOrderId(), "来源订单ID应落库");
-        assertEquals(S, record.getAmountCent(), "售价S应落库");
-        assertEquals(C, record.getCostCent(), "平台成本价C应落库");
-        assertEquals(P, record.getPlatformRetainCent(), "P = S - C 应正确");
-        assertEquals(O, record.getOpsCent(), "O = round(P×10%) 应正确");
-        assertEquals(F, record.getCfCostCent(), "F = round(S×1%) 应正确");
-        assertEquals(D, record.getPoolCent(), "D = P - O - F 应正确");
-        assertEquals(R, record.getReferralShareCent(), "R = round(D×70%) 应正确(CF值预算参照)");
-        assertEquals(T, record.getTeamShareCent(), "T = round(D×30%) 应正确(货币直接分佣)");
-        assertEquals(EIGHT_SHARE, record.getTeamEightShareCent(), "8份池 = T×80% 应正确");
-        assertEquals(AWARD, record.getTeamAwardCent(), "团队奖 = T×20% 应正确");
-        assertEquals("pending", record.getStatus(), "结算后应 pending(冷静期后 settled)");
-
-        verify(profitPoolOrderMapper).insert(any(ProfitPoolOrder.class));
-        // 管道化:D>0 必须持续触发团队分润流水(8份池 + 团队奖),保证续费/复购持续产生收益
-        verify(teamShareRecordMapper, atLeastOnce()).insert(any(TeamShareRecord.class));
-    }
-
-    // ==================== 正常流:续费/复购持续分润(管道化) ====================
-
-    @Test
-    void 正常流_续费复购_跨订单持续分润() {
-        // 同一成员两笔不同续费订单(orderId 不同)——推荐关系存续期间续费/复购持续分润
-        ProfitPoolOrder first = service.settle(2001L, TYPE_MEMBERSHIP, 5L, S, C);
-        ProfitPoolOrder second = service.settle(2002L, TYPE_MEMBERSHIP, 5L, S, C);
-
-        assertNotNull(first);
-        assertNotNull(second);
-        assertNotEquals(first.getId(), second.getId(), "两笔续费应各自独立落单(收入管道化)");
-        assertEquals(TYPE_MEMBERSHIP, second.getOrderType());
-        assertEquals(T, second.getTeamShareCent(), "续费复购仍按默认30%持续分润");
-        verify(profitPoolOrderMapper, times(2)).insert(any(ProfitPoolOrder.class));
-    }
-
-    // ==================== 正常流:重复回调幂等(唯一键 uk_order) ====================
-
-    @Test
-    void 正常流_重复回调_唯一键幂等() {
-        ProfitPoolOrder first = service.settle(3001L, TYPE_SUBSCRIPTION, 5L, S, C);
-        assertNotNull(first);
-
-        // 同一 (order_type, order_id) 重复回调 → 命中 uk_order 唯一键 → 返回既有,不重复落库
-        when(profitPoolOrderMapper.selectOne(any(Wrapper.class))).thenReturn(first);
-        ProfitPoolOrder second = service.settle(3001L, TYPE_SUBSCRIPTION, 5L, S, C);
-
-        assertNotNull(second, "幂等:重复回调应返回既有记录而非空");
-        assertEquals(first.getId(), second.getId(), "幂等:重复回调不得新插记录");
-        verify(profitPoolOrderMapper, times(1)).insert(any(ProfitPoolOrder.class));
-    }
-
-    // ==================== 边界流:D ≤ 0(低于保本线) ====================
-
-    @Test
-    void 边界流_D小于等于0_整单不分润仅记录() {
-        // S=9000 < C=10000 → P<0,D≤0:整单不产生推荐人/团队分润,仅落 profit_pool_order 供统计
-        ProfitPoolOrder record = service.settle(4001L, TYPE_ASSESSMENT_RETEST, 5L, 9000, 10000);
-
-        assertNotNull(record, "保本线下仍应落 profit_pool_order 供统计");
-        assertEquals(0, record.getTeamShareCent(), "D≤0 团队体系 T 应为 0");
-        assertEquals(0, record.getTeamEightShareCent(), "D≤0 8份池应为 0");
-        assertEquals(0, record.getTeamAwardCent(), "D≤0 团队奖应为 0");
-        verify(profitPoolOrderMapper).insert(any(ProfitPoolOrder.class));
-        verify(teamShareRecordMapper, never()).insert(any(TeamShareRecord.class));
-        verify(teamAwardRecordMapper, never()).insert(any(TeamAwardRecord.class));
-    }
-
-    // ==================== 边界流:未知触发源拒绝(防误分配) ====================
-
-    @Test
-    void 边界流_未知触发源_拒绝() {
-        assertThrows(IllegalArgumentException.class,
-                () -> service.settle(5001L, "unknown_trigger", 5L, S, C),
-                "未知触发源不得进入分润管道");
-        verify(profitPoolOrderMapper, never()).insert(any(ProfitPoolOrder.class));
-        verify(teamShareRecordMapper, never()).insert(any(TeamShareRecord.class));
-    }
-
-    // ==================== 合规流:只扩触发源、不提比率(§10#5) ====================
-
-    @Test
-    void 合规流_只扩触发源_不提比率() {
-        // 三种新增触发源:T 恒为 round(D×30%)、8份池恒为 T×80%、团队奖恒为 T×20% —— 比率不因管道化放大
-        assertRatioUnchanged(TYPE_MEMBERSHIP);
-        assertRatioUnchanged(TYPE_SUBSCRIPTION);
-        assertRatioUnchanged(TYPE_ASSESSMENT_RETEST);
-    }
-
-    private void assertRatioUnchanged(String orderType) {
-        ProfitPoolOrder record = service.settle(6000L + D, orderType, 5L, S, C);
-        assertNotNull(record);
-        assertEquals(D, record.getPoolCent(), "D 与基准一致");
-        // 不提高比率:团队体系仍 30%、8份池仍 80%、团队奖仍 20%(与基准完全一致)
-        assertEquals(T, record.getTeamShareCent(), orderType + " 团队分润比率不得提高");
-        assertEquals(EIGHT_SHARE, record.getTeamEightShareCent(), orderType + " 8份池比率不得提高");
-        assertEquals(AWARD, record.getTeamAwardCent(), orderType + " 团队奖比率不得提高");
-    }
-}