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

fix(migrations): 修复迁移480 butler_performance 保留字建表失败 + 迁移417 孤儿家庭池整批回滚

迁移480(butler_performance):
- 根因:year_month 是 MySQL 保留字(RESERVED=1,information_schema.KEYWORDS 实测),
  建表 SQL 未加反引号 → 语法错误 → butler_performance 建表失败(WARN,每次启动重演)
- 修复:DatabaseInitializer + schema.sql 同步加反引号,对齐项目既有模板(迁移478 等已用 \`year_month\`)
- 验证:重启后 butler_performance 已建成(CREATE_TIME 2026-11-17 09:00:44),含 uk_butler_month + idx_year_month

迁移417(CfLegacyLedgerMigrationService):
- 根因:家庭 87(王卫东家庭)family_members 已清空(creator 姥姥已迁至家庭 72),池内 1 CF
  找不到归属成员 → assertNoUnresolvedSource 抛异常 → 整批回滚(其余 16 池+4 系统分+24 钱包已成功迁入)
- 修复:新增 isOrphanFamilyPool(家庭不存在或该家庭已无任何 family_members)→ 跳过并 WARN 留库备注,
  不删除数据、不计入 unresolved 阻塞其余账本迁入;查询失败时保守返回 false 保持原有阻断语义
- 测试:新增 migrateFamilyPlatformPools_skipsOrphanPoolWithNoMembers 单测(Mockito),4/4 全绿
- 验证:重启后日志输出「迁移417: 家庭池 familyId=87 已无任何家庭成员...跳过不迁移」,PID ERROR=0

部署回执:cfc_backup_20261117_085936.tar.gz 备份 + jar 替换 + systemctl 重启 + API 5 接口 200 + 双前端 200
Xiaogang Liao 1 день назад
Родитель
Сommit
7f27225dfe

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

@@ -3900,7 +3900,7 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
             jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS butler_performance ("
                     + "id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID', "
                     + "butler_user_id BIGINT NOT NULL COMMENT '管家用户ID', "
-                    + "year_month VARCHAR(7) NOT NULL COMMENT '绩效周期(yyyy-MM)', "
+                    + "`year_month` VARCHAR(7) NOT NULL COMMENT '绩效周期(yyyy-MM)', "
                     + "inspected_count INT DEFAULT 0 COMMENT '质检单数', "
                     + "pass_rate DECIMAL(5,2) DEFAULT 0 COMMENT '质检通过率(%)', "
                     + "satisfaction_count INT DEFAULT 0 COMMENT '满意度评分单数', "
@@ -3909,8 +3909,8 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
                     + "performance_score DECIMAL(5,2) DEFAULT 0 COMMENT '绩效综合分(0-100)', "
                     + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', "
                     + "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', "
-                    + "UNIQUE KEY uk_butler_month (butler_user_id, year_month), "
-                    + "INDEX idx_year_month (year_month)"
+                    + "UNIQUE KEY uk_butler_month (butler_user_id, `year_month`), "
+                    + "INDEX idx_year_month (`year_month`)"
                     + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='真人管家绩效看板(SC-H-07)'");
             log.info("迁移480: butler_performance 表已就绪");
         } catch (Exception e) {

+ 31 - 3
cfc-backend/src/main/java/com/etotem/cfc/service/CfLegacyLedgerMigrationService.java

@@ -101,9 +101,17 @@ public class CfLegacyLedgerMigrationService {
             if (row.memberId == null) {
                 if (hasMigratableValue(row.totalEarned, row.available, row.frozen,
                         row.withdrawn, row.exchanged)) {
-                    unresolved++;
-                    log.error("迁移417: 家庭池 familyId={} 找不到创建者对应的 family_member",
-                            row.familyId);
+                    if (isOrphanFamilyPool(row.familyId, row.userId)) {
+                        // 孤儿家庭池:家庭不存在或该家庭已无任何家庭成员(创建者亦不在列)。
+                        // 余额保留旧表 family_platform_balance 供人工处置,跳过迁移,不阻塞整批。
+                        log.warn("迁移417: 家庭池 familyId={} 已无任何家庭成员(含创建者),"
+                                + "存量 CF {} 保留在 family_platform_balance 待人工处理,本次跳过不迁移",
+                                row.familyId, row.available + row.frozen);
+                    } else {
+                        unresolved++;
+                        log.error("迁移417: 家庭池 familyId={} 找不到创建者对应的 family_member",
+                                row.familyId);
+                    }
                 }
                 continue;
             }
@@ -270,6 +278,26 @@ public class CfLegacyLedgerMigrationService {
                 || withdrawn != 0 || exchanged != 0;
     }
 
+    /**
+     * 判断家庭池是否已无可归属成员(孤儿):家庭记录不存在,或该家庭已无任何 family_members。
+     * 孤儿池余额保留旧表不迁移(不静默丢弃),也不计入 unresolved 阻塞其余正常账本迁入。
+     * 成员数查询失败时保守返回 false(仍走 unresolved 阻断,保持原有安全语义)。
+     */
+    private boolean isOrphanFamilyPool(Long familyId, Long userId) {
+        if (userId == null) {
+            return true; // families 无此家庭记录(LEFT JOIN 未命中)
+        }
+        try {
+            Integer count = jdbcTemplate.queryForObject(
+                    "SELECT COUNT(*) FROM family_members WHERE family_id = ?",
+                    Integer.class, familyId);
+            return count != null && count == 0;
+        } catch (Exception e) {
+            log.warn("迁移417: 查询家庭 {} 成员数失败: {}", familyId, e.getMessage());
+            return false;
+        }
+    }
+
     /** 有价值但找不到目标成员的旧账本必须让整批回滚,禁止静默丢失 CF 值。 */
     private static void assertNoUnresolvedSource(String refType, int unresolved) {
         if (unresolved > 0) {

+ 3 - 3
cfc-backend/src/main/resources/schema.sql

@@ -3137,7 +3137,7 @@ CREATE TABLE IF NOT EXISTS butler_satisfaction (
 CREATE TABLE IF NOT EXISTS butler_performance (
     id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
     butler_user_id BIGINT NOT NULL COMMENT '管家用户ID',
-    year_month VARCHAR(7) NOT NULL COMMENT '绩效周期(yyyy-MM)',
+    `year_month` VARCHAR(7) NOT NULL COMMENT '绩效周期(yyyy-MM)',
     inspected_count INT DEFAULT 0 COMMENT '质检单数',
     pass_rate DECIMAL(5,2) DEFAULT 0 COMMENT '质检通过率(%)',
     satisfaction_count INT DEFAULT 0 COMMENT '满意度评分单数',
@@ -3146,8 +3146,8 @@ CREATE TABLE IF NOT EXISTS butler_performance (
     performance_score DECIMAL(5,2) DEFAULT 0 COMMENT '绩效综合分(0-100)',
     created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
     updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
-    UNIQUE KEY uk_butler_month (butler_user_id, year_month),
-    INDEX idx_year_month (year_month)
+    UNIQUE KEY uk_butler_month (butler_user_id, `year_month`),
+    INDEX idx_year_month (`year_month`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='真人管家绩效看板(SC-H-07)';
 
 -- 真人管家升级工单(能力键 butler.escalation.handle · SC-H-01 接收 AI 升级并人工介入 / SC-H-04 升级与应急处理)

+ 33 - 0
cfc-backend/src/test/java/com/etotem/cfc/service/CfLegacyLedgerMigrationServiceTest.java

@@ -137,4 +137,37 @@ class CfLegacyLedgerMigrationServiceTest {
                 eq(35), eq(35),
                 eq("F-6 存量迁移:家庭池 available+frozen 合入 available"));
     }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    void migrateFamilyPlatformPools_skipsOrphanPoolWithNoMembers() {
+        CfLegacyLedgerMigrationService.FamilyPoolRow row =
+                new CfLegacyLedgerMigrationService.FamilyPoolRow();
+        row.sourceId = 16L;
+        row.familyId = 87L;
+        row.userId = 76L;   // 家庭记录存在(创建者已知)
+        row.memberId = null; // 但该家庭 member 已清空
+        row.totalEarned = 1;
+        row.available = 1;
+
+        when(jdbcTemplate.queryForObject(
+                ArgumentMatchers.startsWith("SELECT COUNT(*) FROM information_schema.TABLES"),
+                eq(Integer.class), anyString()))
+                .thenReturn(1);
+        when(jdbcTemplate.query(
+                anyString(),
+                ArgumentMatchers.<RowMapper<CfLegacyLedgerMigrationService.FamilyPoolRow>>any()))
+                .thenReturn(Collections.singletonList(row));
+        when(jdbcTemplate.queryForObject(
+                eq("SELECT COUNT(*) FROM family_members WHERE family_id = ?"),
+                eq(Integer.class),
+                eq(87L)))
+                .thenReturn(0);
+
+        assertEquals(0, cfLegacyLedgerMigrationService.migrateFamilyPlatformPools());
+
+        verify(jdbcTemplate, org.mockito.Mockito.never()).update(
+                ArgumentMatchers.contains("INSERT INTO cf_balance"),
+                ArgumentMatchers.<Object[]>any());
+    }
 }