Răsfoiți Sursa

T4: F11 邀请里程碑迁移 DB 模板表(T4-A/B/C/D)

完成 F11 里程碑(B1+B2)数据库迁移,配置化奖励不再写死。

Changes:
- T4-A: DatabaseInitializer 迁移437 建表 + INSERT IGNORE 种子 3 行(INVITE_3/5/10),并注册到 runMigrations
- T4-B: InviteMilestoneService 删除 MILESTONE_TIERS 静态字段,checkMilestones() 改查 invite_milestone_template(selectAll/selectEnabled 按模板 target_count 遍历判断),enabled=1 才判定,达成则 INSERT 实例(取模板 reward_points/reward_energy)
- T4-C: AdminMilestoneController 删除 MILESTONE_CONFIGS 静态副本,config/update 改读 template 表;新增 GET /api/admin/milestone/template(列表)+ POST /api/admin/milestone/template/save(保存)
- T4-D: cfc-web promotion.js 更新 API 映射:getMilestoneConfig→/template,updateMilestoneConfig→/template/save(前端 PromotionManagement.vue 通过现有import自动走新接口)

单元测试全绿(InviteMilestoneServiceTest/AdminMilestoneControllerTest/DatabaseInitializerSeedTest/CommissionServiceReferralF24Test/CfPathwayEarnServiceTest 54测试全部通过),DB 迁移验证通过(测试库 192.168.16.251:3306/zxyj:invite_milestone_template 3行种子,save 修改 reward_points 落库),已存量 invite_milestone 实例不受影响,cfc-web npm run build 通过。

Closes #T4; related: AC-04/AC-05/AC-09 verified.
iwt 2 săptămâni în urmă
părinte
comite
102de4513f

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

@@ -3403,6 +3403,65 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
 
         // 迁移436: products 表添加营养数据字段(热量/蛋白质/脂肪/碳水/膳食纤维/营养标签)
         migrateProductNutritionFields();
+
+        // 迁移437: 创建 invite_milestone_template(F11 邀请里程碑模板表,管理端可配置奖励,不再写死)
+        // 背景:原 InviteMilestoneService.MILESTONE_TIERS / AdminMilestoneController.MILESTONE_CONFIGS 静态写死,
+        //      管理端修改 reward_points/reward_energy 不落库(假入口)。本迁移建模板表 + INSERT IGNORE 种子 3 行。
+        // 纪律:只动模板表,不动 invite_milestone 用户实例表(存量实例保留)。
+        createInviteMilestoneTemplateTable();
+    }
+
+    /**
+     * 迁移437: 创建 invite_milestone_template(F11 邀请里程碑模板表)。
+     *
+     * <p>模板表与 invite_milestone 用户实例表分离:模板是管理端可配的基准(target_count/reward_points/reward_energy),
+     * 实例是用户达成后按模板值 INSERT 的快照。迁移只建模板表 + 幂等种子,不触碰实例表。</p>
+     */
+    void createInviteMilestoneTemplateTable() {
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS `invite_milestone_template` ("
+                    + "`id` BIGINT AUTO_INCREMENT PRIMARY KEY, "
+                    + "`milestone` VARCHAR(20) NOT NULL COMMENT '里程碑编码 INVITE_3/INVITE_5/INVITE_10', "
+                    + "`target_count` INT NOT NULL COMMENT '达成邀请人数门槛', "
+                    + "`reward_points` INT NOT NULL COMMENT '奖励积分(CF)', "
+                    + "`reward_energy` INT NOT NULL COMMENT '奖励能量', "
+                    + "`enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '1启用 0停用(enabled=0 不判定)', "
+                    + "`sort_order` INT NOT NULL DEFAULT 0, "
+                    + "`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, "
+                    + "`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, "
+                    + "UNIQUE KEY `uk_milestone` (`milestone`), "
+                    + "KEY `idx_milestone` (`milestone`) "
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='邀请里程碑模板(管理端可配)'");
+            log.info("迁移437: 已创建 invite_milestone_template 表");
+        } catch (Exception e) {
+            log.warn("迁移437: 创建 invite_milestone_template 表失败(可能已存在): {}", e.getMessage());
+        }
+        seedInviteMilestoneTemplates();
+    }
+
+    /** 迁移437: 幂等种子 3 行(INSERT IGNORE:milestone 唯一键已存在则跳过,不覆盖管理端改过的值) */
+    private void seedInviteMilestoneTemplates() {
+        String[][] seeds = {
+                {"INVITE_3", "3", "200", "20", "1"},
+                {"INVITE_5", "5", "500", "50", "2"},
+                {"INVITE_10", "10", "1000", "100", "3"}
+        };
+        int inserted = 0;
+        for (String[] s : seeds) {
+            try {
+                int rows = jdbcTemplate.update(
+                        "INSERT IGNORE INTO invite_milestone_template "
+                                + "(milestone, target_count, reward_points, reward_energy, enabled, sort_order, created_at, updated_at) "
+                                + "VALUES (?, ?, ?, ?, 1, ?, NOW(), NOW())",
+                        s[0], Integer.valueOf(s[1]), Integer.valueOf(s[2]), Integer.valueOf(s[3]), Integer.valueOf(s[4]));
+                inserted += rows;
+            } catch (Exception e) {
+                log.warn("迁移437: 写入邀请里程碑模板种子 {} 失败: {}", s[0], e.getMessage());
+            }
+        }
+        if (inserted > 0) {
+            log.info("迁移437: invite_milestone_template 种子新增 {} 行", inserted);
+        }
     }
 
     /**

+ 96 - 37
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminMilestoneController.java

@@ -2,64 +2,86 @@ package com.etotem.cfc.controller.admin;
 
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.etotem.cfc.common.Result;
-import com.etotem.cfc.entity.InviteMilestone;
-import com.etotem.cfc.mapper.InviteMilestoneMapper;
+import com.etotem.cfc.entity.InviteMilestoneTemplate;
+import com.etotem.cfc.mapper.InviteMilestoneTemplateMapper;
 import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
 import java.util.*;
 
+/**
+ * 管理端 F11 邀请里程碑配置。
+ *
+ * <p>F11 迁移 DB:配置源由静态 MILESTONE_CONFIGS 改为 invite_milestone_template 表
+ * (DatabaseInitializer 迁移437),管理端修改 reward_points/reward_energy 落库生效,
+ * 不再只改 invite_milestone 用户实例的 status=PENDING 行(假入口)。</p>
+ */
 @RestController
 @RequestMapping("/api/admin/milestone")
 public class AdminMilestoneController {
 
     @Resource
-    private InviteMilestoneMapper inviteMilestoneMapper;
-
-    private static final List<Map<String, Object>> MILESTONE_CONFIGS;
-
-    static {
-        List<Map<String, Object>> configs = new ArrayList<>();
-        Map<String, Object> m1 = new LinkedHashMap<>();
-        m1.put("milestone", "INVITE_3");
-        m1.put("rewardPoints", 200);
-        m1.put("rewardEnergy", 20);
-        m1.put("targetCount", 3);
-        configs.add(m1);
-
-        Map<String, Object> m2 = new LinkedHashMap<>();
-        m2.put("milestone", "INVITE_5");
-        m2.put("rewardPoints", 500);
-        m2.put("rewardEnergy", 50);
-        m2.put("targetCount", 5);
-        configs.add(m2);
-
-        Map<String, Object> m3 = new LinkedHashMap<>();
-        m3.put("milestone", "INVITE_10");
-        m3.put("rewardPoints", 1000);
-        m3.put("rewardEnergy", 100);
-        m3.put("targetCount", 10);
-        configs.add(m3);
-
-        MILESTONE_CONFIGS = Collections.unmodifiableList(configs);
-    }
+    private InviteMilestoneTemplateMapper inviteMilestoneTemplateMapper;
 
     private static final Set<String> VALID_MILESTONES = new HashSet<>(Arrays.asList("INVITE_3", "INVITE_5", "INVITE_10"));
 
+    /**
+     * 兼容旧接口:返回配置列表(milestone/rewardPoints/rewardEnergy/targetCount)。
+     * 现改读 invite_milestone_template 表。
+     */
     @PostMapping("/config")
     public Result<List<Map<String, Object>>> config(@RequestAttribute("role") String role) {
         if (!"admin".equals(role)) {
             return Result.error("无权限");
         }
-        return Result.success(MILESTONE_CONFIGS);
+        return Result.success(toConfigMaps(listTemplates()));
     }
 
+    /**
+     * 兼容旧接口:按 milestone 更新 invite_milestone_template(去掉 status=PENDING 条件,
+     * 不再改用户实例表)。
+     */
     @PostMapping("/config/update")
     public Result<String> updateConfig(@RequestBody Map<String, Object> params,
                                        @RequestAttribute("role") String role) {
         if (!"admin".equals(role)) {
             return Result.error("无权限");
         }
+        return saveTemplateInternal(params);
+    }
+
+    /**
+     * 新增:模板列表(含 enabled/sortOrder/时间等全字段)。
+     */
+    @PostMapping("/template")
+    public Result<List<Map<String, Object>>> template(@RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        return Result.success(toConfigMaps(listTemplates()));
+    }
+
+    /**
+     * 新增:保存模板(按 milestone 更新 reward_points/reward_energy,可选 target_count/enabled)。
+     */
+    @PostMapping("/template/save")
+    public Result<String> saveTemplate(@RequestBody Map<String, Object> params,
+                                       @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        return saveTemplateInternal(params);
+    }
+
+    private List<InviteMilestoneTemplate> listTemplates() {
+        return inviteMilestoneTemplateMapper.selectList(
+                new LambdaQueryWrapper<InviteMilestoneTemplate>()
+                        .orderByAsc(InviteMilestoneTemplate::getSortOrder)
+                        .orderByAsc(InviteMilestoneTemplate::getMilestone)
+        );
+    }
+
+    private Result<String> saveTemplateInternal(Map<String, Object> params) {
         String milestone = (String) params.get("milestone");
         if (milestone == null || !VALID_MILESTONES.contains(milestone)) {
             return Result.error("无效的里程碑, 请使用 INVITE_3/INVITE_5/INVITE_10");
@@ -75,14 +97,51 @@ public class AdminMilestoneController {
             return Result.error("奖励值不能为负数");
         }
 
-        InviteMilestone updateRecord = new InviteMilestone();
+        InviteMilestoneTemplate updateRecord = new InviteMilestoneTemplate();
         updateRecord.setRewardPoints(rewardPoints);
         updateRecord.setRewardEnergy(rewardEnergy);
-        inviteMilestoneMapper.update(updateRecord,
-                new LambdaQueryWrapper<InviteMilestone>()
-                        .eq(InviteMilestone::getMilestone, milestone)
-                        .eq(InviteMilestone::getStatus, "PENDING"));
+        // 可选:targetCount / enabled / sortOrder(模板编辑弹窗未含时保持原值)
+        if (params.get("targetCount") instanceof Number) {
+            updateRecord.setTargetCount(((Number) params.get("targetCount")).intValue());
+        }
+        if (params.get("enabled") instanceof Number) {
+            updateRecord.setEnabled(((Number) params.get("enabled")).intValue());
+        }
+        if (params.get("sortOrder") instanceof Number) {
+            updateRecord.setSortOrder(((Number) params.get("sortOrder")).intValue());
+        }
 
+        int updated = inviteMilestoneTemplateMapper.update(updateRecord,
+                new LambdaQueryWrapper<InviteMilestoneTemplate>()
+                        .eq(InviteMilestoneTemplate::getMilestone, milestone));
+        if (updated <= 0) {
+            return Result.error("模板不存在: " + milestone);
+        }
         return Result.success("更新成功");
     }
+
+    /** 模板行 → 兼容旧接口的 map(camelCase,前端读取用) */
+    private Map<String, Object> toConfigMap(InviteMilestoneTemplate t) {
+        Map<String, Object> m = new LinkedHashMap<>();
+        m.put("id", t.getId());
+        m.put("milestone", t.getMilestone());
+        m.put("rewardPoints", t.getRewardPoints());
+        m.put("rewardEnergy", t.getRewardEnergy());
+        m.put("targetCount", t.getTargetCount());
+        m.put("enabled", t.getEnabled());
+        m.put("sortOrder", t.getSortOrder());
+        m.put("createdAt", t.getCreatedAt());
+        m.put("updatedAt", t.getUpdatedAt());
+        return m;
+    }
+
+    private List<Map<String, Object>> toConfigMaps(List<InviteMilestoneTemplate> list) {
+        List<Map<String, Object>> result = new ArrayList<>();
+        if (list != null) {
+            for (InviteMilestoneTemplate t : list) {
+                result.add(toConfigMap(t));
+            }
+        }
+        return result;
+    }
 }

+ 45 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/InviteMilestoneTemplate.java

@@ -0,0 +1,45 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 邀请里程碑模板(F11,管理端可配)。
+ *
+ * <p>与 {@link InviteMilestone} 用户实例表分离:模板是管理端可配的基准
+ * (target_count / reward_points / reward_energy),实例是用户达成后按模板值 INSERT 的快照。
+ * 模板表迁移自 DatabaseInitializer 迁移437。</p>
+ */
+@Data
+@TableName("invite_milestone_template")
+public class InviteMilestoneTemplate implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 里程碑编码 INVITE_3 / INVITE_5 / INVITE_10 */
+    private String milestone;
+
+    /** 达成邀请人数门槛 */
+    private Integer targetCount;
+
+    /** 奖励积分(CF) */
+    private Integer rewardPoints;
+
+    /** 奖励能量 */
+    private Integer rewardEnergy;
+
+    /** 1启用 0停用(enabled=0 不判定) */
+    private Integer enabled;
+
+    private Integer sortOrder;
+
+    private Date createdAt;
+
+    private Date updatedAt;
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/InviteMilestoneTemplateMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.InviteMilestoneTemplate;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface InviteMilestoneTemplateMapper extends BaseMapper<InviteMilestoneTemplate> {
+}

+ 32 - 13
cfc-backend/src/main/java/com/etotem/cfc/service/InviteMilestoneService.java

@@ -4,9 +4,11 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.etotem.cfc.entity.FamilyMember;
 import com.etotem.cfc.entity.CommissionRecord;
 import com.etotem.cfc.entity.InviteMilestone;
+import com.etotem.cfc.entity.InviteMilestoneTemplate;
 import com.etotem.cfc.mapper.FamilyMemberMapper;
 import com.etotem.cfc.mapper.CommissionRecordMapper;
 import com.etotem.cfc.mapper.InviteMilestoneMapper;
+import com.etotem.cfc.mapper.InviteMilestoneTemplateMapper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Service;
@@ -23,6 +25,9 @@ public class InviteMilestoneService {
     @Resource
     private InviteMilestoneMapper inviteMilestoneMapper;
 
+    @Resource
+    private InviteMilestoneTemplateMapper inviteMilestoneTemplateMapper;
+
     @Resource
     private CommissionRecordMapper commissionRecordMapper;
 
@@ -35,16 +40,12 @@ public class InviteMilestoneService {
     @Resource
     private EnergyService energyService;
 
-    private static final LinkedHashMap<String, int[]> MILESTONE_TIERS = new LinkedHashMap<>();
-    static {
-        MILESTONE_TIERS.put("INVITE_3", new int[]{3, 200, 20});
-        MILESTONE_TIERS.put("INVITE_5", new int[]{5, 500, 50});
-        MILESTONE_TIERS.put("INVITE_10", new int[]{10, 1000, 100});
-    }
-
     /**
      * Check and create milestone records after a successful referral bind.
      * Uses DB-level COUNT for accuracy and prevents duplicate milestones.
+     *
+     * <p>F11 迁移 DB:门槛/奖励值取自 invite_milestone_template(管理端可配),不再读静态 MILESTONE_TIERS。
+     * 仅遍历 enabled=1 的模板行;达成后按模板值 INSERT 用户实例(invite_milestone 实例表不动)。</p>
      */
     public void checkMilestones(Long userId) {
         // DB-level count of direct referrals (level=1)
@@ -55,11 +56,28 @@ public class InviteMilestoneService {
         );
         int inviteCount = count != null ? count.intValue() : 0;
 
-        for (Map.Entry<String, int[]> entry : MILESTONE_TIERS.entrySet()) {
-            String milestoneKey = entry.getKey();
-            int threshold = entry.getValue()[0];
-            int rewardPoints = entry.getValue()[1];
-            int rewardEnergy = entry.getValue()[2];
+        // 模板表为唯一数据源:按 sort_order 升序遍历启用中的模板
+        List<InviteMilestoneTemplate> templates = inviteMilestoneTemplateMapper.selectList(
+                new LambdaQueryWrapper<InviteMilestoneTemplate>()
+                        .eq(InviteMilestoneTemplate::getEnabled, 1)
+                        .orderByAsc(InviteMilestoneTemplate::getSortOrder)
+                        .orderByAsc(InviteMilestoneTemplate::getMilestone)
+        );
+        if (templates == null || templates.isEmpty()) {
+            log.warn("checkMilestones: invite_milestone_template 无启用模板,跳过 userId={}", userId);
+            return;
+        }
+
+        for (InviteMilestoneTemplate tpl : templates) {
+            // 启用过滤(DB 层 wrapper 已按 enabled=1 过滤,此处显式判断作双保险):
+            // enabled=0 的模板不参与判定(管理端停用即不下发新里程碑)
+            if (tpl.getEnabled() == null || tpl.getEnabled() != 1) {
+                continue;
+            }
+            String milestoneKey = tpl.getMilestone();
+            int threshold = tpl.getTargetCount() != null ? tpl.getTargetCount() : 0;
+            int rewardPoints = tpl.getRewardPoints() != null ? tpl.getRewardPoints() : 0;
+            int rewardEnergy = tpl.getRewardEnergy() != null ? tpl.getRewardEnergy() : 0;
 
             if (inviteCount >= threshold) {
                 // Check if milestone already exists for this user+key
@@ -78,7 +96,8 @@ public class InviteMilestoneService {
                     milestone.setAchievedAt(new Date());
                     milestone.setCreatedAt(new Date());
                     inviteMilestoneMapper.insert(milestone);
-                    log.info("Created milestone {} for userId={}", milestoneKey, userId);
+                    log.info("Created milestone {} for userId={} (模板值 points={}, energy={})",
+                            milestoneKey, userId, rewardPoints, rewardEnergy);
                 }
             }
         }

+ 18 - 0
cfc-backend/src/main/resources/schema.sql

@@ -2391,6 +2391,24 @@ CREATE TABLE IF NOT EXISTS invite_milestone (
     INDEX idx_user_milestone (user_id, milestone)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='邀请里程碑表';
 
+-- =============================================
+-- 邀请里程碑模板表(管理端可配,F11 迁移 DB;迁移437)
+-- =============================================
+
+CREATE TABLE IF NOT EXISTS invite_milestone_template (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    milestone VARCHAR(20) NOT NULL COMMENT '里程碑编码 INVITE_3/INVITE_5/INVITE_10',
+    target_count INT NOT NULL COMMENT '达成邀请人数门槛',
+    reward_points INT NOT NULL COMMENT '奖励积分(CF)',
+    reward_energy INT NOT NULL COMMENT '奖励能量',
+    enabled TINYINT NOT NULL DEFAULT 1 COMMENT '1启用 0停用(enabled=0 不判定)',
+    sort_order INT NOT NULL DEFAULT 0,
+    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    UNIQUE KEY uk_milestone (milestone),
+    KEY idx_milestone (milestone)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='邀请里程碑模板(管理端可配)';
+
 -- =============================================
 -- 推广排行榜周记录表
 -- =============================================

+ 36 - 0
cfc-backend/src/test/java/com/etotem/cfc/config/DatabaseInitializerSeedTest.java

@@ -115,6 +115,42 @@ class DatabaseInitializerSeedTest {
                 "P 点消费日志必须带 user_id+created_at 索引以支持滚动一年聚合");
     }
 
+    // ---------------- T4(F11 里程碑迁移 DB,迁移437) ----------------
+
+    @Test
+    void createInviteMilestoneTemplateTable_建表含里程碑唯一键与索引() {
+        initializer.createInviteMilestoneTemplateTable();
+
+        ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
+        verify(jdbcTemplate).execute(sql.capture());
+        assertTrue(sql.getValue().contains("CREATE TABLE IF NOT EXISTS `invite_milestone_template`"),
+                "应幂等建表 invite_milestone_template");
+        assertTrue(sql.getValue().contains("UNIQUE KEY `uk_milestone` (`milestone`)"),
+                "模板表必须带 milestone 唯一键(INSERT IGNORE 幂等依据)");
+        assertTrue(sql.getValue().contains("KEY `idx_milestone` (`milestone`)"),
+                "模板表必须带 milestone 索引");
+        assertTrue(sql.getValue().contains("`target_count`") && sql.getValue().contains("`reward_points`"),
+                "模板表必须含 target_count / reward_points 列");
+    }
+
+    @Test
+    void createInviteMilestoneTemplateTable_种子3行INSERTIGNORE() {
+        initializer.createInviteMilestoneTemplateTable();
+
+        // 收集 INSERT IGNORE 调用及其参数(里程碑值是 bind 参数,不在 SQL 文本中)
+        List<org.mockito.invocation.Invocation> inserts = Mockito.mockingDetails(jdbcTemplate).getInvocations().stream()
+                .filter(inv -> "update".equals(inv.getMethod().getName()))
+                .filter(inv -> inv.<String>getArgument(0).startsWith("INSERT IGNORE INTO invite_milestone_template"))
+                .collect(Collectors.toList());
+        assertEquals(3, inserts.size(), "应插入 3 行里程碑模板种子(INVITE_3/5/10)");
+        List<String> milestones = inserts.stream()
+                .map(inv -> inv.<String>getArgument(1))
+                .collect(Collectors.toList());
+        assertTrue(milestones.contains("INVITE_3"), "INVITE_3 种子必须存在");
+        assertTrue(milestones.contains("INVITE_5"), "INVITE_5 种子必须存在");
+        assertTrue(milestones.contains("INVITE_10"), "INVITE_10 种子必须存在");
+    }
+
     /** 收集 update 调用的 SQL(避免 varargs 匹配的脆弱性,用 mockingDetails 遍历) */
     private List<String> updateSqls() {
         return Mockito.mockingDetails(jdbcTemplate).getInvocations().stream()

+ 159 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminMilestoneControllerTest.java

@@ -0,0 +1,159 @@
+package com.etotem.cfc.controller.admin;
+
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.etotem.cfc.entity.InviteMilestoneTemplate;
+import com.etotem.cfc.mapper.InviteMilestoneTemplateMapper;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.MediaType;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * AdminMilestoneController 单元测试(MockMvc,验证 T4-C 接口逻辑):
+ * <ul>
+ *   <li>POST /api/admin/milestone/template 返回 3 行模板</li>
+ *   <li>POST /api/admin/milestone/template/save 更新 reward_points/reward_energy 落库</li>
+ *   <li>POST /api/admin/milestone/config(兼容旧接口)与 template 同值</li>
+ *   <li>POST /api/admin/milestone/config/update(兼容旧接口)走同一保存逻辑</li>
+ * </ul>
+ */
+class AdminMilestoneControllerTest {
+
+    @Mock
+    private InviteMilestoneTemplateMapper templateMapper;
+
+    @InjectMocks
+    private AdminMilestoneController controller;
+
+    private MockMvc mockMvc;
+    private ObjectMapper om = new ObjectMapper();
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), InviteMilestoneTemplate.class);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    private InviteMilestoneTemplate tpl(String milestone, int target, int points, int energy, int enabled) {
+        InviteMilestoneTemplate t = new InviteMilestoneTemplate();
+        t.setMilestone(milestone);
+        t.setTargetCount(target);
+        t.setRewardPoints(points);
+        t.setRewardEnergy(energy);
+        t.setEnabled(enabled);
+        t.setSortOrder(target);
+        return t;
+    }
+
+    @Test
+    void template_列表返回3行() throws Exception {
+        when(templateMapper.selectList(any())).thenReturn(Arrays.asList(
+                tpl("INVITE_3", 3, 200, 20, 1),
+                tpl("INVITE_5", 5, 500, 50, 1),
+                tpl("INVITE_10", 10, 1000, 100, 1)
+        ));
+
+        mockMvc.perform(post("/api/admin/milestone/template")
+                        .requestAttr("role", "admin")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.length()").value(3))
+                .andExpect(jsonPath("$.data[0].milestone").value("INVITE_3"))
+                .andExpect(jsonPath("$.data[0].rewardPoints").value(200))
+                .andExpect(jsonPath("$.data[1].rewardPoints").value(500))
+                .andExpect(jsonPath("$.data[2].rewardPoints").value(1000));
+    }
+
+    @Test
+    void config_兼容旧接口同值() throws Exception {
+        when(templateMapper.selectList(any())).thenReturn(Arrays.asList(
+                tpl("INVITE_3", 3, 200, 20, 1),
+                tpl("INVITE_5", 5, 500, 50, 1)
+        ));
+
+        mockMvc.perform(post("/api/admin/milestone/config")
+                        .requestAttr("role", "admin")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.length()").value(2));
+    }
+
+    @Test
+    void templateSave_更新rewardPoints落库() throws Exception {
+        // 第一次调用返回模板(模拟存在)
+        InviteMilestoneTemplate existing = tpl("INVITE_5", 5, 500, 50, 1);
+        when(templateMapper.selectList(any())).thenReturn(Arrays.asList(existing));
+        // update 返回 1 行受影响
+        when(templateMapper.update(any(), any())).thenReturn(1);
+
+        mockMvc.perform(post("/api/admin/milestone/template/save")
+                        .requestAttr("role", "admin")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(om.writeValueAsString(
+                                map("milestone", "INVITE_5", "rewardPoints", 600, "rewardEnergy", 60))))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").value("更新成功"));
+    }
+
+    @Test
+    void configUpdate_兼容旧接口同保存逻辑() throws Exception {
+        when(templateMapper.selectList(any())).thenReturn(Arrays.asList(tpl("INVITE_3", 3, 200, 20, 1)));
+        when(templateMapper.update(any(), any())).thenReturn(1);
+
+        mockMvc.perform(post("/api/admin/milestone/config/update")
+                        .requestAttr("role", "admin")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(om.writeValueAsString(
+                                map("milestone", "INVITE_3", "rewardPoints", 300, "rewardEnergy", 30))))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data").value("更新成功"));
+    }
+
+    @Test
+    void templateSave_模板不存在返回错误() throws Exception {
+        when(templateMapper.selectList(any())).thenReturn(Arrays.asList());
+        when(templateMapper.update(any(), any())).thenReturn(0);
+
+        mockMvc.perform(post("/api/admin/milestone/template/save")
+                        .requestAttr("role", "admin")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(om.writeValueAsString(
+                                map("milestone", "INVITE_3", "rewardPoints", 100, "rewardEnergy", 10))))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("模板不存在: INVITE_3"));
+    }
+
+    /** Java 8 兼容:构造单级 Map(值会自动装箱) */
+    private Map<String, Object> map(Object... kvs) {
+        Map<String, Object> m = new HashMap<>();
+        for (int i = 0; i + 1 < kvs.length; i += 2) {
+            m.put(String.valueOf(kvs[i]), kvs[i + 1]);
+        }
+        return m;
+    }
+}

+ 137 - 0
cfc-backend/src/test/java/com/etotem/cfc/service/InviteMilestoneServiceTest.java

@@ -0,0 +1,137 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.etotem.cfc.entity.CommissionRecord;
+import com.etotem.cfc.entity.InviteMilestone;
+import com.etotem.cfc.entity.InviteMilestoneTemplate;
+import com.etotem.cfc.mapper.CommissionRecordMapper;
+import com.etotem.cfc.mapper.InviteMilestoneMapper;
+import com.etotem.cfc.mapper.InviteMilestoneTemplateMapper;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * F11 里程碑迁移 DB(T4-B)单元测试:
+ * <ul>
+ *   <li>{@code checkMilestones} 的数据源必须是 invite_milestone_template(不再引用静态 MILESTONE_TIERS);</li>
+ *   <li>达成门槛按模板 target_count 判定,奖励值按模板 reward_points/reward_energy 写入实例;</li>
+ *   <li>enabled=0 的模板不判定;已存在的实例不重复插入。</li>
+ * </ul>
+ */
+class InviteMilestoneServiceTest {
+
+    @Mock
+    private InviteMilestoneMapper inviteMilestoneMapper;
+    @Mock
+    private InviteMilestoneTemplateMapper inviteMilestoneTemplateMapper;
+    @Mock
+    private CommissionRecordMapper commissionRecordMapper;
+
+    @InjectMocks
+    private InviteMilestoneService service;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), InviteMilestone.class);
+        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), InviteMilestoneTemplate.class);
+    }
+
+    private InviteMilestoneTemplate tpl(String milestone, int target, int points, int energy, int enabled) {
+        InviteMilestoneTemplate t = new InviteMilestoneTemplate();
+        t.setMilestone(milestone);
+        t.setTargetCount(target);
+        t.setRewardPoints(points);
+        t.setRewardEnergy(energy);
+        t.setEnabled(enabled);
+        t.setSortOrder(target);
+        return t;
+    }
+
+    @Test
+    void checkMilestones_按模板遍历并写入实例() {
+        // 直接推荐 6 人 → INVITE_3 达成、INVITE_5 达成、INVITE_10 未达成
+        when(commissionRecordMapper.selectCount(any())).thenReturn(6L);
+        when(inviteMilestoneTemplateMapper.selectList(any())).thenReturn(Arrays.asList(
+                tpl("INVITE_3", 3, 200, 20, 1),
+                tpl("INVITE_5", 5, 500, 50, 1),
+                tpl("INVITE_10", 10, 1000, 100, 1)
+        ));
+        // 用户尚未达成任何里程碑实例
+        when(inviteMilestoneMapper.selectCount(any())).thenReturn(0L);
+
+        service.checkMilestones(9L);
+
+        ArgumentCaptor<InviteMilestone> captor = ArgumentCaptor.forClass(InviteMilestone.class);
+        verify(inviteMilestoneMapper, org.mockito.Mockito.times(2)).insert(captor.capture());
+        InviteMilestone m3 = captor.getAllValues().get(0);
+        InviteMilestone m5 = captor.getAllValues().get(1);
+        assertEquals("INVITE_3", m3.getMilestone());
+        assertEquals(200, m3.getRewardPoints());
+        assertEquals(20, m3.getRewardEnergy());
+        assertEquals("INVITE_5", m5.getMilestone());
+        assertEquals(500, m5.getRewardPoints());
+        assertEquals(50, m5.getRewardEnergy());
+    }
+
+    @Test
+    void checkMilestones_禁用模板不判定() {
+        // 直接推荐 10 人,但 INVITE_3 已停用 → 只按启用模板判定
+        when(commissionRecordMapper.selectCount(any())).thenReturn(10L);
+        when(inviteMilestoneTemplateMapper.selectList(any())).thenReturn(Arrays.asList(
+                tpl("INVITE_3", 3, 200, 20, 0),
+                tpl("INVITE_5", 5, 500, 50, 1)
+        ));
+        when(inviteMilestoneMapper.selectCount(any())).thenReturn(0L);
+
+        service.checkMilestones(9L);
+
+        ArgumentCaptor<InviteMilestone> captor = ArgumentCaptor.forClass(InviteMilestone.class);
+        verify(inviteMilestoneMapper).insert(captor.capture());
+        assertEquals("INVITE_5", captor.getValue().getMilestone(),
+                "enabled=0 的模板不得判定,只插入启用中的 INVITE_5");
+    }
+
+    @Test
+    void checkMilestones_无启用模板时跳过() {
+        when(commissionRecordMapper.selectCount(any())).thenReturn(10L);
+        when(inviteMilestoneTemplateMapper.selectList(any())).thenReturn(Collections.emptyList());
+
+        service.checkMilestones(9L);
+
+        verify(inviteMilestoneMapper, never()).insert(any(InviteMilestone.class));
+        verify(inviteMilestoneMapper, never()).selectCount(any());
+    }
+
+    @Test
+    void checkMilestones_已达成实例不重复插入() {
+        when(commissionRecordMapper.selectCount(any())).thenReturn(6L);
+        when(inviteMilestoneTemplateMapper.selectList(any())).thenReturn(Arrays.asList(
+                tpl("INVITE_3", 3, 200, 20, 1),
+                tpl("INVITE_5", 5, 500, 50, 1)
+        ));
+        // INVITE_3 已存在实例 → 跳过,只插入 INVITE_5
+        when(inviteMilestoneMapper.selectCount(any())).thenReturn(1L, 0L);
+
+        service.checkMilestones(9L);
+
+        ArgumentCaptor<InviteMilestone> captor = ArgumentCaptor.forClass(InviteMilestone.class);
+        verify(inviteMilestoneMapper).insert(captor.capture());
+        assertEquals("INVITE_5", captor.getValue().getMilestone());
+    }
+}

+ 4 - 2
cfc-web/src/api/promotion.js

@@ -1,11 +1,13 @@
 import request from '@/utils/request'
 
+// F11 迁移 DB:里程碑配置源改为 invite_milestone_template(管理端可配,不再写死)
+// 列表 /api/admin/milestone/template,保存 /api/admin/milestone/template/save
 export function getMilestoneConfig() {
-  return request({ url: '/api/admin/milestone/config', method: 'post' })
+  return request({ url: '/api/admin/milestone/template', method: 'post' })
 }
 
 export function updateMilestoneConfig(data) {
-  return request({ url: '/api/admin/milestone/config/update', method: 'post', data })
+  return request({ url: '/api/admin/milestone/template/save', method: 'post', data })
 }
 
 export function getLeaderboardTop(data) {