Ver código fonte

feat(dim): T3 注册中心服务层+幂等种子

DimensionRegistryService.getTree/getNodeByCode/getRoots/saveConfig;
DatabaseInitializer 幂等种子 5根(读energy.element填wuxing_rule_ref)+7body+认知6/心10/关系12/富4。
Agnes Agent 1 semana atrás
pai
commit
8b47edf51c

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

@@ -3434,6 +3434,12 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
 
         // 迁移444: T38 团队邀请功能 —— supply_system_member 增加个人专属邀请码(幂等,永久有效+唯一)
         migrateSupplyMemberInviteCode();
+
+        // 迁移445: 统一维度注册中心 —— product_dimension_config / indicator_definitions 增量列(幂等)
+        migrateDimensionRegistrySchema();
+
+        // 统一维度注册中心 —— 5根 + 7 body 维 + 扩围子维 幂等种子
+        seedDimensionRegistry();
     }
 
     /**
@@ -4171,6 +4177,193 @@ sqls.add("INSERT IGNORE INTO health_norm_reference (dimension, gender, age_min,
         }
     }
 
+    // ==================== 统一维度注册中心:迁移445 增量列 + 幂等种子 ====================
+
+    /**
+     * 迁移445: 统一维度注册中心 —— product_dimension_config 增加 legacy_alias / source_system /
+     * wuxing_rule_ref / node_kind;indicator_definitions 增加 parent_id / legacy_alias。
+     * 全部幂等(列已存在则跳过)。
+     * 红线1: 绝不改 indicator_definitions.id 主键、绝不改任何外键目标(仅加列)。
+     */
+    private void migrateDimensionRegistrySchema() {
+        try {
+            ensureColumn("product_dimension_config", "legacy_alias",
+                    "VARCHAR(512) DEFAULT NULL COMMENT '历史别名(JSON数组): 承载现存4套编码, 如 [\"growth\"]'");
+        } catch (Exception e) { log.warn("迁移445: product_dimension_config.legacy_alias 失败: {}", e.getMessage()); }
+        try {
+            ensureColumn("product_dimension_config", "source_system",
+                    "VARCHAR(32) DEFAULT NULL COMMENT '归属子系统: health/energy/indicator/knowledge/psych/relationship/wealth-literacy/cognitive'");
+        } catch (Exception e) { log.warn("迁移445: product_dimension_config.source_system 失败: {}", e.getMessage()); }
+        try {
+            ensureColumn("product_dimension_config", "wuxing_rule_ref",
+                    "VARCHAR(30) DEFAULT NULL COMMENT '五行规则引用(木/火/金/水/土), 关联EnergyDimension.element'");
+        } catch (Exception e) { log.warn("迁移445: product_dimension_config.wuxing_rule_ref 失败: {}", e.getMessage()); }
+        try {
+            ensureColumn("product_dimension_config", "node_kind",
+                    "VARCHAR(16) DEFAULT 'root' COMMENT '节点种类: root(五维根)/sub(子维度)'");
+        } catch (Exception e) { log.warn("迁移445: product_dimension_config.node_kind 失败: {}", e.getMessage()); }
+        try {
+            ensureColumn("indicator_definitions", "parent_id",
+                    "BIGINT DEFAULT NULL COMMENT '父节点ID(可指向product_dimension_config.id或本表id, 混排进维度树)'");
+        } catch (Exception e) { log.warn("迁移445: indicator_definitions.parent_id 失败: {}", e.getMessage()); }
+        try {
+            ensureColumn("indicator_definitions", "legacy_alias",
+                    "VARCHAR(512) DEFAULT NULL COMMENT '历史别名(JSON数组): 承载现存4套编码'");
+        } catch (Exception e) { log.warn("迁移445: indicator_definitions.legacy_alias 失败: {}", e.getMessage()); }
+        log.info("迁移445: 统一维度注册中心增量列已就绪");
+    }
+
+    /**
+     * 统一维度注册中心 —— 5 根 + 7 body 维 + 扩围子维(认知6/心10/关系12/富4)幂等种子。
+     *
+     * <p>幂等:按 dimension_code 判重,已存在则跳过(重复启动不产生重复行)。
+     * 5 根 wuxing_rule_ref 读取 energy_dimension.element(木/火/金/水/土);子维 wuxing_rule_ref 留 NULL(P1 推断)。
+     * 扩围维度以代码为准(见报告):认知为「六维认知体系」非 5 维;关系实际为 12 个 action* 关系质量维非 5 维。</p>
+     */
+    private void seedDimensionRegistry() {
+        try {
+            // 1) 5 根(code 已与 energy_dimension 对齐)
+            String[][] roots = {
+                {"body",   "身", "5"},
+                {"mind",   "心", "4"},
+                {"wisdom", "智", "1"},
+                {"action", "行", "3"},
+                {"wealth", "富", "2"},
+            };
+            for (String[] r : roots) {
+                String element = queryElementFromEnergy(r[0]);
+                ensureDimensionNode(r[0], r[1], null, "energy",
+                        "[\"" + r[0] + "\"]", element, Integer.parseInt(r[2]), "root");
+            }
+
+            Long bodyId   = dimensionNodeId("body");
+            Long mindId   = dimensionNodeId("mind");
+            Long wisdomId = dimensionNodeId("wisdom");
+            Long actionId = dimensionNodeId("action");
+            Long wealthId = dimensionNodeId("wealth");
+
+            // 2) 7 body 维(health,legacy_alias 保留旧名)
+            String[][] bodyChildren = {
+                {"body.growth",     "成长", "growth"},
+                {"body.sleep",      "睡眠", "sleep"},
+                {"body.vision",     "视力", "vision"},
+                {"body.immunity",   "免疫", "immunity"},
+                {"body.nutrition",  "营养", "nutrition"},
+                {"body.gut",        "肠道", "gut"},
+                {"body.exercise",   "运动", "exercise"},
+            };
+            for (String[] c : bodyChildren) {
+                ensureDimensionNode(c[0], c[1], bodyId, "health", "[\"" + c[2] + "\"]", null, 0, "sub");
+            }
+
+            // 3) 认知 6 维(wisdom 根;DAN 测评「六维认知体系」)
+            String[][] wisdomChildren = {
+                {"wisdom.perception",       "感知",     "perceptionScore"},
+                {"wisdom.focus",           "专注",     "focusScore"},
+                {"wisdom.memory",          "记忆",     "memoryScore"},
+                {"wisdom.logic",           "逻辑",     "logicScore"},
+                {"wisdom.spatial",         "空间",     "spatialScore"},
+                {"wisdom.processingSpeed", "加工速度", "processingSpeedScore"},
+            };
+            for (String[] c : wisdomChildren) {
+                ensureDimensionNode(c[0], c[1], wisdomId, "cognitive", "[\"" + c[2] + "\"]", null, 0, "sub");
+            }
+
+            // 4) 心 10 维(mind 根;EMI/心理:大五5 + 情绪稳定 + 自我驱动3 + 自我概念)
+            String[][] mindChildren = {
+                {"mind.bigFiveOpenness",         "开放性", "bigFiveOpenness"},
+                {"mind.bigFiveConscientiousness","尽责性", "bigFiveConscientiousness"},
+                {"mind.bigFiveExtraversion",     "外向性", "bigFiveExtraversion"},
+                {"mind.bigFiveAgreeableness",    "宜人性", "bigFiveAgreeableness"},
+                {"mind.bigFiveNeuroticism",      "神经质", "bigFiveNeuroticism"},
+                {"mind.emotionStability",        "情绪稳定", "emotionStability"},
+                {"mind.driveAutonomy",           "自主",   "driveAutonomy"},
+                {"mind.driveCompetence",         "胜任",   "driveCompetence"},
+                {"mind.driveRelatedness",        "关系归属", "driveRelatedness"},
+                {"mind.selfConceptOverall",      "自我概念", "selfConceptOverall"},
+            };
+            for (String[] c : mindChildren) {
+                ensureDimensionNode(c[0], c[1], mindId, "psych", "[\"" + c[2] + "\"]", null, 0, "sub");
+            }
+
+            // 5) 关系 12 维(action 根;关系质量:代码实际 12 个 action* 维,非推定的 5 维)
+            String[][] actionChildren = {
+                {"action.childParentChild", "亲子(子→父)", "actionChildParentChild"},
+                {"action.sibling",          "手足",        "actionSibling"},
+                {"action.relative",         "亲戚",        "actionRelative"},
+                {"action.teacherStudent",   "师生",        "actionTeacherStudent"},
+                {"action.childSociality",   "儿童社交",    "actionChildSociality"},
+                {"action.childInterpersonal","儿童人际",   "actionChildInterpersonal"},
+                {"action.parentChild",      "父→子",       "actionParentChild"},
+                {"action.marital",          "婚姻",        "actionMarital"},
+                {"action.parental",         "教养",        "actionParental"},
+                {"action.leadership",       "领导",        "actionLeadership"},
+                {"action.sociality",        "社交",        "actionSociality"},
+                {"action.interpersonal",    "人际",        "actionInterpersonal"},
+            };
+            for (String[] c : actionChildren) {
+                ensureDimensionNode(c[0], c[1], actionId, "relationship", "[\"" + c[2] + "\"]", null, 0, "sub");
+            }
+
+            // 6) 富 4 维(wealth 根;财富素养)
+            String[][] wealthChildren = {
+                {"wealth.skill",    "财商技能", "wealthSkill"},
+                {"wealth.altruism", "财富利他", "wealthAltruism"},
+                {"wealth.income",   "财富收入", "wealthIncome"},
+                {"wealth.fx",       "外汇",     "wealthFx"},
+            };
+            for (String[] c : wealthChildren) {
+                ensureDimensionNode(c[0], c[1], wealthId, "wealth-literacy", "[\"" + c[2] + "\"]", null, 0, "sub");
+            }
+
+            log.info("统一维度注册中心种子已就绪(5根 + 7 body + 认知6 + 心10 + 关系12 + 富4)");
+        } catch (Exception e) {
+            log.warn("统一维度注册中心种子初始化失败: {}", e.getMessage());
+        }
+    }
+
+    /** 取 energy_dimension.element(木/火/金/水/土)作为五维根 wuxing_rule_ref;缺失时回退硬编码 */
+    private String queryElementFromEnergy(String code) {
+        try {
+            String el = jdbcTemplate.queryForObject(
+                    "SELECT element FROM energy_dimension WHERE code = ?", String.class, code);
+            if (el != null && !el.isEmpty()) return el;
+        } catch (Exception e) { /* 忽略,回退 */ }
+        java.util.Map<String, String> fallback = new java.util.HashMap<>();
+        fallback.put("body", "土");
+        fallback.put("mind", "火");
+        fallback.put("wisdom", "金");
+        fallback.put("action", "木");
+        fallback.put("wealth", "水");
+        return fallback.getOrDefault(code, null);
+    }
+
+    /** 幂等写入一个维度节点:dimension_code 已存在则跳过;返回该节点 id */
+    private Long ensureDimensionNode(String code, String name, Long parentId, String sourceSystem,
+                                     String legacyAliasJson, String wuxingRuleRef, int sort, String nodeKind) {
+        Integer exists = jdbcTemplate.queryForObject(
+                "SELECT COUNT(*) FROM product_dimension_config WHERE dimension_code = ?", Integer.class, code);
+        if (exists != null && exists > 0) {
+            return dimensionNodeId(code);
+        }
+        jdbcTemplate.update(
+                "INSERT INTO product_dimension_config (dimension_code, dimension_name, dimension_type, parent_id, "
+                        + "sort, enabled, source_system, legacy_alias, wuxing_rule_ref, node_kind) "
+                        + "VALUES (?, ?, 'unified', ?, ?, 1, ?, ?, ?, ?)",
+                code, name, parentId, sort, sourceSystem, legacyAliasJson, wuxingRuleRef, nodeKind);
+        return dimensionNodeId(code);
+    }
+
+    /** 按 dimension_code 取 product_dimension_config.id(不存在返回 null) */
+    private Long dimensionNodeId(String code) {
+        try {
+            return jdbcTemplate.queryForObject(
+                    "SELECT id FROM product_dimension_config WHERE dimension_code = ?", Long.class, code);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
     private void modifyColumnToText(String table, String column, String comment) {
         if (!tableExists(table)) {
             return;

+ 25 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/DimensionNode.java

@@ -0,0 +1,25 @@
+package com.etotem.cfc.dto;
+
+import lombok.Data;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * 统一维度树节点 DTO(合并维度节点 + 指标节点)。
+ *
+ * <p>字段对齐设计 §5.1:id / code / name / parentId / nodeKind / sourceSystem / legacyAlias / wuxingRuleRef / children。</p>
+ */
+@Data
+public class DimensionNode {
+    private Long id;
+    private String code;
+    private String name;
+    private Long parentId;
+    /** root(五维根) / sub(子维度) / indicator(指标节点) */
+    private String nodeKind;
+    private String sourceSystem;
+    private List<String> legacyAlias = new ArrayList<>();
+    private String wuxingRuleRef;
+    private List<DimensionNode> children = new ArrayList<>();
+}

+ 30 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/DimensionRegistryService.java

@@ -0,0 +1,30 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.dto.DimensionNode;
+import com.etotem.cfc.entity.ProductDimensionConfig;
+
+import java.util.List;
+
+/**
+ * 统一维度注册中心服务层 —— 全系统唯一维度取数入口(只读为主)。
+ *
+ * <p>合并 product_dimension_config 维度节点 + indicator_definitions 指标节点(按 parent_id 混排)为统一树。
+ * 5 根(body/mind/wisdom/action/wealth)为权威,7 body 维与扩围子维挂在对应根下。</p>
+ */
+public interface DimensionRegistryService {
+
+    /** 统一维度树(合并维度节点 + 指标节点) */
+    List<DimensionNode> getTree();
+
+    /** 按 source_system 过滤的统一维度树(可空=全部) */
+    List<DimensionNode> getTree(String sourceSystem);
+
+    /** 取 5 根维度节点 */
+    List<DimensionNode> getRoots();
+
+    /** 按统一 code 取节点(含 legacy_alias) */
+    DimensionNode getNodeByCode(String code);
+
+    /** 落库一个维度节点(admin 写入经此,权威表 = product_dimension_config) */
+    ProductDimensionConfig saveConfig(ProductDimensionConfig node);
+}

+ 160 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/impl/DimensionRegistryServiceImpl.java

@@ -0,0 +1,160 @@
+package com.etotem.cfc.service.impl;
+
+import com.etotem.cfc.dto.DimensionNode;
+import com.etotem.cfc.entity.ProductDimensionConfig;
+import com.etotem.cfc.service.DimensionRegistryService;
+import com.etotem.cfc.service.ProductDimensionConfigService;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * DimensionRegistryService 实现。
+ *
+ * <p>维度节点来自 product_dimension_config(含 5 根 + 子维),指标节点来自 indicator_definitions
+ * (按其 parent_id 混排挂到维度节点下)。当前 indicator_definitions.parent_id 尚未填充(P2 混排),
+ * 故合并后树即维度节点树。</p>
+ */
+@Service
+public class DimensionRegistryServiceImpl implements DimensionRegistryService {
+
+    @Resource
+    private ProductDimensionConfigService productDimensionConfigService;
+
+    @Resource
+    private org.springframework.jdbc.core.JdbcTemplate jdbcTemplate;
+
+    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+    @Override
+    public List<DimensionNode> getTree() {
+        return buildTree(null);
+    }
+
+    @Override
+    public List<DimensionNode> getTree(String sourceSystem) {
+        return buildTree(sourceSystem);
+    }
+
+    @Override
+    public List<DimensionNode> getRoots() {
+        List<ProductDimensionConfig> all = productDimensionConfigService.list();
+        List<DimensionNode> roots = new ArrayList<>();
+        for (ProductDimensionConfig c : all) {
+            if (c.getParentId() == null) {
+                roots.add(toNode(c));
+            }
+        }
+        roots.sort(Comparator.comparing(c -> c.getCode() == null ? "" : c.getCode()));
+        return roots;
+    }
+
+    @Override
+    public DimensionNode getNodeByCode(String code) {
+        ProductDimensionConfig c = productDimensionConfigService.getByCode(code);
+        return c == null ? null : toNode(c);
+    }
+
+    @Override
+    public ProductDimensionConfig saveConfig(ProductDimensionConfig node) {
+        return productDimensionConfigService.saveConfig(node);
+    }
+
+    private List<DimensionNode> buildTree(String sourceSystem) {
+        List<ProductDimensionConfig> all = productDimensionConfigService.list();
+
+        Map<Long, DimensionNode> dimMap = new HashMap<>();
+        for (ProductDimensionConfig c : all) {
+            if (sourceSystem != null && sourceSystem.length() > 0) {
+                // 仅保留根或其子树命中 source_system 的节点
+                if (c.getSourceSystem() == null || !c.getSourceSystem().equals(sourceSystem)) {
+                    continue;
+                }
+            }
+            dimMap.put(c.getId(), toNode(c));
+        }
+
+        // 维度节点自引用挂接
+        for (DimensionNode n : dimMap.values()) {
+            if (n.getParentId() != null) {
+                DimensionNode p = dimMap.get(n.getParentId());
+                if (p != null) {
+                    p.getChildren().add(n);
+                }
+            }
+        }
+
+        // 合并指标节点(indicator_definitions.parent_id 指向维度节点 id)
+        try {
+            List<Map<String, Object>> inds = jdbcTemplate.queryForList(
+                    "SELECT id, code, name, parent_id FROM indicator_definitions WHERE parent_id IS NOT NULL");
+            for (Map<String, Object> row : inds) {
+                Long pid = row.get("parent_id") == null ? null : ((Number) row.get("parent_id")).longValue();
+                DimensionNode p = (pid == null) ? null : dimMap.get(pid);
+                if (p != null) {
+                    DimensionNode inode = new DimensionNode();
+                    inode.setId(row.get("id") == null ? null : ((Number) row.get("id")).longValue());
+                    inode.setCode((String) row.get("code"));
+                    inode.setName((String) row.get("name"));
+                    inode.setParentId(pid);
+                    inode.setNodeKind("indicator");
+                    inode.setSourceSystem("indicator");
+                    p.getChildren().add(inode);
+                }
+            }
+        } catch (Exception e) {
+            // 忽略指标合并异常(不影响维度树)
+        }
+
+        // 收集根
+        List<DimensionNode> roots = new ArrayList<>();
+        for (DimensionNode n : dimMap.values()) {
+            if (n.getParentId() == null) {
+                roots.add(n);
+            }
+        }
+        sortRecursively(roots);
+        return roots;
+    }
+
+    private void sortRecursively(List<DimensionNode> nodes) {
+        nodes.sort(Comparator.comparing(n -> n.getCode() == null ? "" : n.getCode()));
+        for (DimensionNode n : nodes) {
+            sortRecursively(n.getChildren());
+        }
+    }
+
+    private DimensionNode toNode(ProductDimensionConfig c) {
+        DimensionNode n = new DimensionNode();
+        n.setId(c.getId());
+        n.setCode(c.getDimensionCode());
+        n.setName(c.getDimensionName());
+        n.setParentId(c.getParentId());
+        n.setNodeKind(c.getNodeKind());
+        n.setSourceSystem(c.getSourceSystem());
+        n.setWuxingRuleRef(c.getWuxingRuleRef());
+        n.setLegacyAlias(parseAlias(c.getLegacyAlias()));
+        n.setChildren(new ArrayList<>());
+        return n;
+    }
+
+    private List<String> parseAlias(String json) {
+        if (json == null || json.trim().isEmpty()) {
+            return new ArrayList<>();
+        }
+        try {
+            List<String> list = OBJECT_MAPPER.readValue(json, new TypeReference<List<String>>() {});
+            return list != null ? list : new ArrayList<>();
+        } catch (Exception e) {
+            return new ArrayList<>();
+        }
+    }
+}