Browse Source

feat: implement food.library.authoritativeImport (S-cfc-495) - schema.sql foods data_version + uk_food_external, AuthoritativeFoodImportService service, migration 511

Fix NPE in static field order: NON_AUTHORITATIVE_SOURCES before SOURCE_ALIASES; keep changes minimal to pass contract test
Administrator 8 hours ago
parent
commit
1bf97bac02

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

@@ -3734,6 +3734,11 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         // fb_ratio / shannon_index_norm / subhealth_label / parse_self_check、similarity_level、
         // fb_ratio / shannon_index_norm / subhealth_label / parse_self_check、similarity_level、
         // reference_range / direction / species_code / functional_tag 从 payload 提出为可查询列;逐列幂等
         // reference_range / direction / species_code / functional_tag 从 payload 提出为可查询列;逐列幂等
         createGuheV2SchemaColumns();
         createGuheV2SchemaColumns();
+
+        // 迁移511: 权威食材库导入溯源结构(能力键 food.library.authoritativeImport,S-cfc-495 / CR-01 §4.1/§5)
+        // foods.data_version 记录导入数据版本/批次;uk_food_external (external_source, external_id) 保证
+        // 双源按「来源 + 外部ID」幂等 upsert,重复导入不产生重复行
+        createAuthoritativeFoodImportSchema();
     }
     }
 
 
     /**
     /**
@@ -17477,6 +17482,75 @@ log.info("迁移298: 已为无 openid 的 child 账号补齐 family_members 记
         }
         }
     }
     }
 
 
+    /**
+     * 迁移511: 权威食材库导入溯源结构(能力键 {@code food.library.authoritativeImport},S-cfc-495 / CR-01 §4.1/§5)。
+     *
+     * <p>权威库双源(中国食物成分表 / USDA)导入 {@code foods} 表时须可溯源、幂等、不覆盖用户侧数据:</p>
+     * <ul>
+     *   <li>{@code data_version}:记录本次导入的数据版本/批次(溯源)</li>
+     *   <li>{@code uk_food_external(external_source, external_id)}:权威源按「来源 + 外部ID」幂等 upsert,
+     *       重复导入不产生重复行;NULL 组合不参与唯一约束(报告解析/用户自建行多为 NULL 不受影响)</li>
+     * </ul>
+     *
+     * <p>幂等:ensureColumn 自动忽略「列已存在」;唯一键用 try-catch 忽略「重复键名/键已存在」。
+     * 既有数据存在重复 {@code (external_source, external_id)} 时 MySQL 拒绝建键,异常被忽略并告警
+     * (需人工清洗后再补),不影响其余迁移执行。</p>
+     */
+    void createAuthoritativeFoodImportSchema() {
+        ensureColumn("foods", "data_version", "VARCHAR(64) DEFAULT NULL COMMENT '权威库导入数据版本/批次(溯源)'");
+
+        try {
+            jdbcTemplate.execute("ALTER TABLE foods ADD UNIQUE KEY uk_food_external (external_source, external_id)");
+            log.info("迁移511: 已添加 foods.uk_food_external(external_source, external_id) 幂等唯一键");
+        } catch (Exception e) {
+            log.warn("迁移511: foods 幂等唯一键添加失败(已存在或既有数据重复,需人工清洗后补): {}", e.getMessage());
+        }
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS food_import_log ("
+                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID', "
+                    + "source VARCHAR(32) NOT NULL COMMENT '权威来源: china_food_composition/usda', "
+                    + "version VARCHAR(64) NOT NULL COMMENT '导入数据版本/批次标识', "
+                    + "imported INT NOT NULL DEFAULT 0 COMMENT '导入行数(合法 upsert)', "
+                    + "skipped INT NOT NULL DEFAULT 0 COMMENT '跳过行数(格式错误/不覆盖/批内重复)', "
+                    + "merged INT NOT NULL DEFAULT 0 COMMENT '合并行数(同名跨源合并,预留给后续统计)', "
+                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
+                    + "KEY idx_source_created (source, created_at)"
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='权威食材库导入批次日志(版本溯源)'");
+            log.info("迁移511: 已创建 food_import_log 表");
+        } catch (Exception e) {
+            log.warn("迁移511: food_import_log 表创建失败(忽略): {}", e.getMessage());
+        }
+        seedAuthoritativeFoodImportVersions();
+    }
+
+    /**
+     * 迁移511 种子:登记双权威源的初始导入版本(§4.1/§5 溯源;幂等,按 (source, version) 去重)。
+     */
+    private void seedAuthoritativeFoodImportVersions() {
+        String[][] seeds = {
+                {"china_food_composition", "1.0.0"},
+                {"usda", "1.0.0"},
+        };
+        for (String[] seed : seeds) {
+            String source = seed[0];
+            String version = seed[1];
+            try {
+                Integer count = jdbcTemplate.queryForObject(
+                        "SELECT COUNT(*) FROM food_import_log WHERE source = ? AND version = ?",
+                        Integer.class, source, version);
+                if (count == null || count.intValue() == 0) {
+                    jdbcTemplate.update(
+                            "INSERT INTO food_import_log (source, version, imported, skipped, merged, created_at) "
+                                    + "VALUES (?, ?, 0, 0, 0, NOW())",
+                            source, version);
+                    log.info("迁移511: 已登记权威源 {} 导入版本 {}", source, version);
+                }
+            } catch (Exception e) {
+                log.warn("迁移511: 登记权威源 {} 导入版本失败(幂等容忍): {}", source, e.getMessage());
+            }
+        }
+    }
+
     /**
     /**
      * 迁移508: 任务五阶段提醒配置列(stage_enabled + 5 个阶段时间)。
      * 迁移508: 任务五阶段提醒配置列(stage_enabled + 5 个阶段时间)。
      * 幂等:逐列 ADD COLUMN,已存在时忽略异常。
      * 幂等:逐列 ADD COLUMN,已存在时忽略异常。

+ 3 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/Food.java

@@ -46,6 +46,9 @@ public class Food implements Serializable {
     private Integer sortOrder;
     private Integer sortOrder;
     /** 饮食类型: none/清真/halal/素食/vegan */
     /** 饮食类型: none/清真/halal/素食/vegan */
     private String dietType;
     private String dietType;
+    /** 权威库导入数据版本/批次(§4.1 溯源;由权威库导入管线写入,非权威行为空) */
+    @TableField("data_version")
+    private String dataVersion;
 
 
     /** 健康问卷调整结果: normal/blocked/warning/boost(D1-D8 判定,瞬态不入库,供 getCurrentFoodsAsFoodList 透传) */
     /** 健康问卷调整结果: normal/blocked/warning/boost(D1-D8 判定,瞬态不入库,供 getCurrentFoodsAsFoodList 透传) */
     @TableField(exist = false)
     @TableField(exist = false)

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

@@ -5191,10 +5191,12 @@ CREATE TABLE IF NOT EXISTS foods (
     status VARCHAR(20) DEFAULT 'active',
     status VARCHAR(20) DEFAULT 'active',
     sort_order INT DEFAULT 0,
     sort_order INT DEFAULT 0,
     diet_type VARCHAR(50) COMMENT '饮食类型',
     diet_type VARCHAR(50) COMMENT '饮食类型',
+    data_version VARCHAR(64) COMMENT '权威库导入数据版本/批次(溯源,S-cfc-495/CR-01)',
     created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
     created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
     updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
     updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
     INDEX idx_category (category),
     INDEX idx_category (category),
-    INDEX idx_price (price_level)
+    INDEX idx_price (price_level),
+    UNIQUE KEY uk_food_external (external_source, external_id)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='食材库表';
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='食材库表';
 
 
 -- 食材营养素表(每食材多营养素)
 -- 食材营养素表(每食材多营养素)
@@ -7908,5 +7910,17 @@ CREATE TABLE IF NOT EXISTS food_disease_weight_group (
     KEY idx_enabled (enabled)
     KEY idx_enabled (enabled)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='病症权重分组';
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='病症权重分组';
 
 
+-- 权威食材库导入批次日志(迁移511 建表)
+CREATE TABLE IF NOT EXISTS food_import_log (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
+    source VARCHAR(32) NOT NULL COMMENT '权威来源: china_food_composition/usda',
+    version VARCHAR(64) NOT NULL COMMENT '导入数据版本/批次标识',
+    imported INT NOT NULL DEFAULT 0 COMMENT '导入行数(合法 upsert)',
+    skipped INT NOT NULL DEFAULT 0 COMMENT '跳过行数(格式错误/不覆盖/批内重复)',
+    merged INT NOT NULL DEFAULT 0 COMMENT '合并行数(同名跨源合并,预留给后续统计)',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    INDEX idx_source_created (source, created_at)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='权威食材库导入批次日志(版本溯源,S-cfc-495/CR-01)';
+
 
 
 -- 五阶段提醒字段由迁移508维护(见 DatabaseInitializer.createStageReminderColumns):stage_enabled + 5 个 HH:mm 时间列
 -- 五阶段提醒字段由迁移508维护(见 DatabaseInitializer.createStageReminderColumns):stage_enabled + 5 个 HH:mm 时间列