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 7 hours ago
parent
commit
70bdbc7fd6

+ 309 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AuthoritativeFoodImportService.java

@@ -0,0 +1,309 @@
+package com.etotem.cfc.service;
+
+import org.springframework.stereotype.Service;
+
+import java.time.LocalDate;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * 权威食材库导入引擎(能力键 {@code food.library.authoritativeImport},S-cfc-495 / CR-01 §4.1)。
+ *
+ * <p><b>职责边界</b>:把「权威源(中国食物成分表 / USDA)」的原始行加工成可幂等落库的导入决策,
+ * 让加权引擎(CR-02 {@code base_report_score})拿到一份可溯源、不重复、且不覆盖用户侧数据的食材基准。
+ * 权威库导入为后端内部数据管线(运营侧触发),无用户侧鉴权分支,权限流不适用
+ * (规则表 CRUD 由能力键 {@code food.ops.ruleManagement} CR-06 承载)。</p>
+ *
+ * <p><b>与 {@link FoodRuleManagementService} 同风格</b>:纯 Java 服务,不依赖 Spring 上下文 / DB / 外部服务,
+ * 可被反射宿主与后台导入端点共用;DDL({@code foods.data_version} + {@code (external_source, external_id)}
+ * 唯一键 + {@code food_import_log})由 DatabaseInitializer 迁移511 落表。</p>
+ *
+ * <p><b>幂等口径(§4.1)</b>:幂等键 = {@code 权威源 + ':' + 外部ID},重复导入命中既有权威行 → UPDATE 覆盖
+ * 权威数据;命中报告解析行({@code reportId} 非空)或用户自建/手工行 → SKIP,绝不用权威数据覆盖用户侧数据。</p>
+ */
+@Service
+public class AuthoritativeFoodImportService {
+
+    /** §4.1 权威源标识:中国食物成分表(《中国居民膳食指南 2022》附录 + 疾控公开数据,样本回归估算)。 */
+    public static final String SOURCE_CHINA = "china_food_composition";
+    /** §4.1 权威源标识:USDA FoodData Central(公开 API {@code fdc.nal.usda.gov})。 */
+    public static final String SOURCE_USDA = "usda";
+
+    /** 导入决策:权威库中不存在同一幂等键,首次写入。 */
+    public static final String ACTION_INSERT = "INSERT";
+    /** 导入决策:既有行为同来源权威行,重复导入幂等覆盖。 */
+    public static final String ACTION_UPDATE = "UPDATE";
+    /** 导入决策:既有行为报告解析行或用户自建/手工行,跳过且不覆盖。 */
+    public static final String ACTION_SKIP = "SKIP";
+
+    /** 导入结果键:成功导入行数。 */
+    public static final String RESULT_SUCCESS = "successCount";
+    /** 导入结果键:被跳过的行数。 */
+    public static final String RESULT_SKIPPED = "skippedCount";
+    /** 导入结果键:被跳过行的明细(含行号、原因、原始行)。 */
+    public static final String RESULT_SKIPPED_ROWS = "skippedRows";
+
+    /** §4.1 权威源清单(固定两个来源,均为可公开溯源的权威数据)。 */
+    private static final List<String> SUPPORTED_SOURCES =
+            Collections.unmodifiableList(Arrays.asList(SOURCE_CHINA, SOURCE_USDA));
+
+    /** §4.1 权威源值域(含别名归一后的标准值)。 */
+    private static final Set<String> AUTHORITATIVE_SOURCES = new HashSet<String>(SUPPORTED_SOURCES);
+
+    /** 非权威来源:报告解析 / 用户自建 / 手工录入 —— 不得作为权威基准,也不得被导入覆盖。 */
+    private static final Set<String> NON_AUTHORITATIVE_SOURCES =
+            new HashSet<String>(Arrays.asList("report", "user", "manual"));
+
+    /** 源标识别名归一表:需求文档写法的 `usda_fdc` / `china_food_comp` 归一到契约标准值。 */
+    private static final Map<String, String> SOURCE_ALIASES = buildSourceAliases();
+
+    /** 每个权威源当前的数据版本(溯源:来源 + 日期 + 批次号)。 */
+    private final Map<String, String> currentVersionBySource = new ConcurrentHashMap<String, String>();
+    /** 导入批次序号(同一进程内递增,用于版本可追溯)。 */
+    private final AtomicLong batchSeq = new AtomicLong(0L);
+
+    // ==================== 来源值域(§4.1) ====================
+
+    /**
+     * 权威数据源标识清单。
+     *
+     * @return 权威源标准值({@link #SOURCE_CHINA} / {@link #SOURCE_USDA}),不含 report/user/manual
+     */
+    public List<String> supportedSources() {
+        return new ArrayList<String>(SUPPORTED_SOURCES);
+    }
+
+    /**
+     * 来源值域校验:权威源为 {@code true};报告解析 / 用户自建 / 手工录入 / 空值为 {@code false},
+     * 不抛异常。
+     *
+     * @param source 原始来源标识(可为别名或 null)
+     */
+    public boolean isAuthoritativeSource(String source) {
+        String canonical = normalizeSource(source);
+        if (canonical == null || canonical.trim().length() == 0) {
+            return false;
+        }
+        return AUTHORITATIVE_SOURCES.contains(canonical);
+    }
+
+    // ==================== 幂等键(§4.1) ====================
+
+    /**
+     * 幂等键:{@code 权威源 + ':' + 外部ID}。同一来源 + 外部 ID 必得同一键,
+     * 不同来源的相同外部 ID 得到不同键(避免跨源碰撞)。
+     *
+     * @param source     权威源标识(按别名归一)
+     * @param externalId 外部库食材 ID
+     * @throws IllegalArgumentException 来源或外部 ID 为空 —— 无法构成幂等键,属于格式错误行
+     */
+    public String importKey(String source, String externalId) {
+        String canonical = normalizeSource(source);
+        if (isBlank(canonical) || isBlank(externalId)) {
+            throw new IllegalArgumentException("权威库导入缺少来源或外部ID,无法构成幂等键:"
+                    + source + ":" + externalId);
+        }
+        return canonical.trim() + ":" + externalId.trim();
+    }
+
+    // ==================== 导入决策(§4.1 核心:幂等 + 不覆盖用户/报告数据) ====================
+
+    /**
+     * 导入决策(纯内存,与 DB 解耦):
+     * <ul>
+     *   <li>无既有行 → {@link #ACTION_INSERT}(首次导入)</li>
+     *   <li>既有权威行(同来源且非报告行)→ {@link #ACTION_UPDATE}(重复导入幂等覆盖权威数据)</li>
+     *   <li>既有报告解析行({@code reportId} 非空)或用户自建 / 手工行 → {@link #ACTION_SKIP},
+     *       绝不用权威数据覆盖用户侧数据</li>
+     * </ul>
+     *
+     * @param existing 既有食材行(字段名与 {@code foods} 列驼峰一致,可为 null 表示不存在)
+     * @param incoming 本次权威导入行
+     * @return INSERT / UPDATE / SKIP
+     */
+    public String resolveImportAction(Map<String, Object> existing, Map<String, Object> incoming) {
+        if (existing == null || existing.isEmpty()) {
+            return ACTION_INSERT;
+        }
+        // 报告解析产出的食材行受保护:report_id 非空即为报告链路数据
+        Object reportId = existing.get("reportId");
+        if (reportId != null && !isBlank(String.valueOf(reportId))) {
+            return ACTION_SKIP;
+        }
+        String existingSource = rowValue(existing, "externalSource");
+        if (!isAuthoritativeSource(existingSource)) {
+            return ACTION_SKIP;
+        }
+        // 本次导入行自身也必须是权威源,否则不参与基准库写入
+        if (incoming == null || !isAuthoritativeSource(rowValue(incoming, "externalSource"))) {
+            return ACTION_SKIP;
+        }
+        return ACTION_UPDATE;
+    }
+
+    // ==================== 批量导入(§4.1 边界:格式错误行跳过并报告) ====================
+
+    /**
+     * 批量导入权威食材行:逐行校验 + 批内幂等去重,格式错误行跳过并报告,不整批失败。
+     *
+     * <p>返回 {@code successCount} / {@code skippedCount} / {@code skippedRows}(含行号、原因、原始行)
+     * 以及本次导入的 {@code source} / {@code dataVersion}(溯源)。</p>
+     *
+     * @param source 权威源标识(按别名归一)
+     * @param rows   权威源原始行(每行含 {@code externalId} / {@code name} 等字段),可为 null
+     * @return 导入结果统计;空导入返回零统计,不报错也不产生默认数据
+     */
+    public Map<String, Object> importFoods(String source, List<Map<String, Object>> rows) {
+        String canonical = normalizeSource(source);
+        int successCount = 0;
+        int skippedCount = 0;
+        List<Map<String, Object>> skippedRows = new ArrayList<Map<String, Object>>();
+        Set<String> seenKeys = new HashSet<String>();
+
+        if (rows != null) {
+            int rowIndex = 0;
+            for (Map<String, Object> row : rows) {
+                String reason = validateRow(row);
+                if (reason != null) {
+                    skippedCount++;
+                    skippedRows.add(skippedDetail(rowIndex, row, reason));
+                    rowIndex++;
+                    continue;
+                }
+                String externalId = rowValue(row, "externalId");
+                String key;
+                try {
+                    key = importKey(canonical, externalId);
+                } catch (IllegalArgumentException e) {
+                    skippedCount++;
+                    skippedRows.add(skippedDetail(rowIndex, row, "missing_external_id"));
+                    rowIndex++;
+                    continue;
+                }
+                if (seenKeys.contains(key)) {
+                    // §4.1 双源按 name + external_source 幂等去重:同一批次内重复外部 ID 只取首次
+                    skippedCount++;
+                    skippedRows.add(skippedDetail(rowIndex, row, "duplicate_external_id:" + key));
+                    rowIndex++;
+                    continue;
+                }
+                seenKeys.add(key);
+                successCount++;
+                rowIndex++;
+            }
+        }
+
+        Map<String, Object> result = new LinkedHashMap<String, Object>();
+        result.put("source", canonical);
+        result.put(RESULT_SUCCESS, successCount);
+        result.put(RESULT_SKIPPED, skippedCount);
+        result.put(RESULT_SKIPPED_ROWS, skippedRows);
+        if (successCount > 0) {
+            String dataVersion = nextDataVersion(canonical);
+            result.put("dataVersion", dataVersion);
+        } else {
+            result.put("dataVersion", currentDataVersion(canonical));
+        }
+        return result;
+    }
+
+    // ==================== 数据版本(§4.1 / §5 溯源) ====================
+
+    /**
+     * 当前权威源的数据版本/批次,用于溯源(写 {@code foods.data_version})。
+     *
+     * @param source 权威源标识
+     * @return 形如 {@code usda@2026-12-02-batch1} 的非空版本号
+     */
+    public String currentDataVersion(String source) {
+        String canonical = normalizeSource(source);
+        String existing = currentVersionBySource.get(canonical);
+        if (existing != null && !isBlank(existing)) {
+            return existing;
+        }
+        String initial = canonical + "@" + LocalDate.now().toString() + "-batch" + batchSeq.incrementAndGet();
+        currentVersionBySource.put(canonical, initial);
+        return initial;
+    }
+
+    // ==================== 内部辅助 ====================
+
+    private String nextDataVersion(String canonical) {
+        String version = canonical + "@" + LocalDate.now().toString() + "-batch" + batchSeq.incrementAndGet();
+        currentVersionBySource.put(canonical, version);
+        return version;
+    }
+
+    /** 来源归一:别名 → 标准值;null/空串 → null(由调用方判为非权威)。 */
+    private String normalizeSource(String source) {
+        if (source == null) {
+            return null;
+        }
+        String trimmed = source.trim();
+        if (trimmed.length() == 0) {
+            return null;
+        }
+        String alias = SOURCE_ALIASES.get(trimmed);
+        return alias != null ? alias : trimmed;
+    }
+
+    /** 行校验:返回跳过原因;合法行返回 null。 */
+    private String validateRow(Map<String, Object> row) {
+        if (row == null || row.isEmpty()) {
+            return "row_null";
+        }
+        if (isBlank(rowValue(row, "externalId"))) {
+            return "missing_external_id";
+        }
+        if (isBlank(rowValue(row, "name"))) {
+            return "missing_name";
+        }
+        return null;
+    }
+
+    private Map<String, Object> skippedDetail(int rowIndex, Map<String, Object> row, String reason) {
+        Map<String, Object> detail = new LinkedHashMap<String, Object>();
+        detail.put("rowIndex", rowIndex);
+        detail.put("externalId", row == null ? null : rowValue(row, "externalId"));
+        detail.put("reason", reason);
+        detail.put("row", row);
+        return detail;
+    }
+
+    private String rowValue(Map<String, Object> row, String key) {
+        if (row == null) {
+            return null;
+        }
+        Object value = row.get(key);
+        return value == null ? null : String.valueOf(value);
+    }
+
+    private boolean isBlank(String value) {
+        return value == null || value.trim().length() == 0;
+    }
+
+    private static Map<String, String> buildSourceAliases() {
+        Map<String, String> aliases = new HashMap<String, String>();
+        // §4.1 需求文档写法 → 契约标准值
+        aliases.put("usda_fdc", SOURCE_USDA);
+        aliases.put("usda_foundation", SOURCE_USDA);
+        aliases.put("usda_srl", SOURCE_USDA);
+        aliases.put("china_food_comp", SOURCE_CHINA);
+        aliases.put("china_food_composition_6", SOURCE_CHINA);
+        aliases.put("chinese_dietary_guideline_2022", SOURCE_CHINA);
+        // 非权威来源不参与归一,保留原值便于决策层拒绝
+        for (String non : NON_AUTHORITATIVE_SOURCES) {
+            aliases.put(non, non);
+        }
+        return aliases;
+    }
+}