Browse Source

fix(unlock): 通关奖励重复发放修复(历史unlock_gates每gate_type被播种4份) - 迁移505去重+唯一键+refresh按gate_type去重 + TDD 34例

Xiaogang Liao 26 minutes ago
parent
commit
0a7490f1f2

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

@@ -3394,6 +3394,9 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
             log.warn("迁移504: adjust_ref_id 加列失败(幂等容忍): {}", e.getMessage());
         }
 
+        // 迁移505: unlock_gates 去重(每gate_type留最小id) + 加唯一键,防止一次通关发多次奖励
+        migrateUnlockGatesDedup();
+
         // 迁移406: activity_poster_templates 增加 layout_config 列(海报模板元素位置/样式可配置,需求:活动详情海报预览重设计)
         addActivityPosterTemplateLayoutConfigColumn();
 
@@ -15209,6 +15212,29 @@ log.info("迁移298: 已为无 openid 的 child 账号补齐 family_members 记
         }
     }
 
+    /**
+     * 迁移505: unlock_gates 去重 + 唯一键。
+     * 历史 bug:8月12日关卡被播种4次,每 gate_type 4 条,refreshFamilyGates 逐条发奖导致一次通关发4次。
+     * 幂等:先删除每 gate_type 非最小 id 的重复行,再加 uk_gate_type 唯一键。
+     */
+    private void migrateUnlockGatesDedup() {
+        try {
+            int deleted = jdbcTemplate.update(
+                    "DELETE FROM unlock_gates WHERE id NOT IN "
+                            + "(SELECT min_id FROM (SELECT MIN(id) AS min_id FROM unlock_gates GROUP BY gate_type) t)");
+            if (deleted > 0) log.info("迁移505: 清理 unlock_gates 重复行 {} 条", deleted);
+        } catch (Exception e) {
+            log.warn("迁移505: unlock_gates 去重失败(幂等容忍): {}", e.getMessage());
+        }
+        try {
+            jdbcTemplate.execute("ALTER TABLE unlock_gates ADD UNIQUE KEY uk_gate_type (gate_type)");
+            log.info("迁移505: unlock_gates.uk_gate_type 唯一键已添加");
+        } catch (Exception e) {
+            // 唯一键已存在时忽略
+            log.info("迁移505: uk_gate_type 已存在或添加跳过: {}", e.getMessage());
+        }
+    }
+
     private void alterSurveyRecordTemplateIdNullable() {
         try {
             jdbcTemplate.execute("ALTER TABLE survey_records MODIFY COLUMN template_id BIGINT NULL "

+ 3 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/UnlockGateService.java

@@ -234,7 +234,10 @@ public class UnlockGateService {
         if (familyId == null) return;
         List<UnlockGate> gates = unlockGateMapper.selectList(
                 new LambdaQueryWrapper<UnlockGate>().eq(UnlockGate::getEnabled, 1));
+        // 防重复发奖:历史数据曾把每个 gate_type 播种4份,按 gate_type 去重每类只处理1个关卡(修复 C-重复发奖)
+        java.util.Set<String> seenGateTypes = new java.util.HashSet<>();
         for (UnlockGate gate : gates) {
+            if (gate.getGateType() == null || !seenGateTypes.add(gate.getGateType())) continue;
             boolean unlocked = isGateUnlocked(familyId, gate);
             FamilyGateProgress progress = familyGateProgressMapper.selectOne(
                     new LambdaQueryWrapper<FamilyGateProgress>()

+ 2 - 1
cfc-backend/src/main/resources/schema.sql

@@ -5770,7 +5770,8 @@ CREATE TABLE IF NOT EXISTS unlock_gates (
     reward_energy INT DEFAULT 0 COMMENT '通关奖励能量',
     created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
     updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-    INDEX idx_sort (enabled, is_required, is_soft, sort_order)
+    INDEX idx_sort (enabled, is_required, is_soft, sort_order),
+    UNIQUE KEY uk_gate_type (gate_type)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='通关解锁关卡定义';
 
 -- 家庭关卡通关进度

+ 28 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/UnlockGateDedupTest.java

@@ -0,0 +1,28 @@
+package com.etotem.cfc.unit;
+import org.junit.jupiter.api.Test;
+import java.nio.file.*;
+import java.nio.charset.StandardCharsets;
+import static org.junit.jupiter.api.Assertions.*;
+
+/** 回归防护:refreshFamilyGates 按 gate_type 去重,数据冗余时也不重复发奖。 */
+class UnlockGateDedupTest {
+    private String read(String rel) throws Exception {
+        Path p = Paths.get(rel);
+        if (!Files.exists(p)) p = Paths.get("../cfc-backend/" + rel);
+        return new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
+    }
+
+    @Test void refresh_dedups_by_gate_type() throws Exception {
+        String src = read("src/main/java/com/etotem/cfc/service/UnlockGateService.java");
+        int i = src.indexOf("public void refreshFamilyGates(Long familyId, Long triggerUserId)");
+        String body = src.substring(i, i + 900);
+        assertTrue(body.contains("Set<String>") || body.contains("seenGateTypes") || body.contains("add(gate.getGateType())"),
+                "refreshFamilyGates 应按 gate_type 去重,避免重复关卡行导致重复发奖");
+    }
+
+    @Test void schema_has_unique_gate_type() throws Exception {
+        String sql = read("src/main/resources/schema.sql");
+        assertTrue(sql.contains("uk_gate_type") && sql.contains("gate_type"),
+                "schema.sql 应给 unlock_gates.gate_type 加唯一键防重复播种");
+    }
+}