Browse Source

report-types-be: YELLOW 实现 — 迁移506 补 icon/sort_order 列与上传页5类种子 + listTypeLinks 配置化 + saveType icon 归一化

- schema.sql: report_type_registry 加 icon VARCHAR(50) DEFAULT NULL / sort_order INT DEFAULT 100。
- DatabaseInitializer: 迁移506 幂等 ALTER(columnExists 判断)+ 种子(先 SELECT 再 INSERT/UPDATE):
  已激活 gut_flora/dan_a2 缺 icon/sort_order 用 UPDATE 补齐(COALESCE 保留已有值),
  未注册 physical_exam/tongue/body_fat 用 INSERT 补种(is_active=1)。
- ReportParserController.listTypeLinks: 改为返回全部 is_active=1 类型(内存过滤,去掉 linked_product_id 非空过滤),
  补 description/icon/sortOrder 输出,按 sortOrder 升序+id 升序稳定排序,空 productIds 跳过 BatchIds 查询。
- ReportParserAdminController.saveType: icon 空串归一化为 null,避免把 "" 写库覆盖默认。
Agnes Agent 1 hour ago
parent
commit
0b52b60c74

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

@@ -3695,6 +3695,10 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         // 迁移505: 内容安全敏感词库 content_sensitive_word + 降级FAQ话术 coach_fallback_faq
         // 迁移505: 内容安全敏感词库 content_sensitive_word + 降级FAQ话术 coach_fallback_faq
         // (能力键 ai.coach.safetyGuard,SC-B-05/06;CREATE TABLE IF NOT EXISTS 幂等)
         // (能力键 ai.coach.safetyGuard,SC-B-05/06;CREATE TABLE IF NOT EXISTS 幂等)
         createCoachSafetyGuardTables();
         createCoachSafetyGuardTables();
+
+        // 迁移506: report_type_registry 补 icon / sort_order 列(小程序上传页「支持的报告类型」配置化)
+        // 并补种上传页所需的体检/舌象/体脂类型;幂等(先判断列存在 + 先 SELECT 再 INSERT/UPDATE)
+        addReportTypeRegistryIconSortOrderColumns();
     }
     }
 
 
     /**
     /**
@@ -17152,4 +17156,75 @@ log.info("迁移298: 已为无 openid 的 child 账号补齐 family_members 记
             log.warn("迁移504: user_current_food_recommend 表创建失败(忽略): {}", e.getMessage());
             log.warn("迁移504: user_current_food_recommend 表创建失败(忽略): {}", e.getMessage());
         }
         }
     }
     }
+
+    /**
+     * 迁移506: {@code report_type_registry} 补 {@code icon}/{@code sort_order} 列并补种小程序上传页「支持的报告类型」5 类。
+     *
+     * <p>上传页原为硬编码模板,改为后台配置驱动后需图标与排序;已激活的 gut_flora/dan_a2
+     * 缺 icon/sort_order 用 UPDATE 补齐(COALESCE 保留已有值,不覆盖管理员已填),未注册的
+     * physical_exam/tongue/body_fat 用 INSERT 补种(is_active=1)。幂等:columnExists 判断列 +
+     * 先 SELECT 再 INSERT/UPDATE,可重复执行。</p>
+     */
+    void addReportTypeRegistryIconSortOrderColumns() {
+        try {
+            if (!columnExists("report_type_registry", "icon")) {
+                jdbcTemplate.execute("ALTER TABLE report_type_registry "
+                        + "ADD COLUMN icon VARCHAR(50) DEFAULT NULL COMMENT '页面展示图标(emoji或图标类名)'");
+                log.info("迁移506: 已添加 report_type_registry.icon 列");
+            }
+        } catch (Exception e) {
+            log.warn("迁移506: 添加 report_type_registry.icon 列失败(幂等容忍): {}", e.getMessage());
+        }
+        try {
+            if (!columnExists("report_type_registry", "sort_order")) {
+                jdbcTemplate.execute("ALTER TABLE report_type_registry "
+                        + "ADD COLUMN sort_order INT DEFAULT 100 COMMENT '展示排序,升序(小程序上传页支持的报告类型列表顺序)'");
+                log.info("迁移506: 已添加 report_type_registry.sort_order 列");
+            }
+        } catch (Exception e) {
+            log.warn("迁移506: 添加 report_type_registry.sort_order 列失败(幂等容忍): {}", e.getMessage());
+        }
+        seedReportTypeRegistryIconSortOrder();
+    }
+
+    /** 迁移506 种子:确保小程序上传页 5 类有 icon/sort_order 且缺记录时补种(幂等,先 SELECT 再 INSERT/UPDATE) */
+    private void seedReportTypeRegistryIconSortOrder() {
+        Object[][] seeds = {
+                {"gut_flora", "gut_flora", "菌群检测报告", "肠道菌群 PDF,后台采集解析菌群指标", "📄", 1},
+                {"dan_a2", "dan", "素质测评", "核心素养/认知发展 PDF,系统解析能力、人格、情绪等", "🧠", 2},
+                {"physical_exam", null, "体检报告", "血常规、尿常规、生化检验等,支持 PDF 或清晰照片", "📋", 3},
+                {"tongue", null, "舌象照片", "拍摄舌象照片,AI 辅助舌诊分析", "👅", 4},
+                {"body_fat", null, "体脂秤报告", "拍摄体脂秤显示屏,自动提取体重、BMI、体脂率等", "⚖️", 5},
+        };
+        for (Object[] s : seeds) {
+            String typeId = (String) s[0];
+            String family = (String) s[1];
+            String displayName = (String) s[2];
+            String description = (String) s[3];
+            String icon = (String) s[4];
+            int sortOrder = (Integer) s[5];
+            try {
+                Integer count = jdbcTemplate.queryForObject(
+                        "SELECT COUNT(*) FROM report_type_registry WHERE type_id = ?", Integer.class, typeId);
+                if (count == null || count == 0) {
+                    jdbcTemplate.update(
+                            "INSERT INTO report_type_registry (type_id, family, display_name, description, icon, "
+                                    + "sort_order, min_confidence, is_active, source, review_status, version, created_at, updated_at) "
+                                    + "VALUES (?, ?, ?, ?, ?, ?, 30, 1, 'prebuilt', 'approved', '1.0', NOW(), NOW())",
+                            typeId, family, displayName, description, icon, sortOrder);
+                    log.info("迁移506: 已补种报告类型 {}", typeId);
+                } else {
+                    Integer patched = jdbcTemplate.update(
+                            "UPDATE report_type_registry SET icon = COALESCE(icon, ?), sort_order = COALESCE(sort_order, ?), "
+                                    + "updated_at = NOW() WHERE type_id = ?",
+                            icon, sortOrder, typeId);
+                    if (patched != null && patched > 0) {
+                        log.info("迁移506: 已为既有类型 {} 补齐 icon/sort_order", typeId);
+                    }
+                }
+            } catch (Exception e) {
+                log.warn("迁移506: 处理报告类型 {} 失败(幂等容忍): {}", typeId, e.getMessage());
+            }
+        }
+    }
 }
 }

+ 33 - 18
cfc-backend/src/main/java/com/etotem/cfc/controller/ReportParserController.java

@@ -18,6 +18,7 @@ import org.springframework.web.multipart.MultipartFile;
 import javax.annotation.Resource;
 import javax.annotation.Resource;
 import java.io.File;
 import java.io.File;
 import java.util.ArrayList;
 import java.util.ArrayList;
+import java.util.Comparator;
 import java.util.HashMap;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
 import java.util.LinkedHashMap;
@@ -51,41 +52,55 @@ public class ReportParserController {
     private ProductMapper productMapper;
     private ProductMapper productMapper;
 
 
     /**
     /**
-     * 小程序公开:返回已激活且配置了商城商品链接的报告类型(供「查看商品」入口展示)。
-     * 仅返回 is_active=1 AND linked_product_id IS NOT NULL 的记录;未配置链接的类型不出现在结果中。
+     * 小程序公开:返回全部已启用(is_active=1)的报告类型,供上传页「支持的报告类型」配置化展示。
+     * 不再过滤 linked_product_id 非空(未配置商品链接的类型也返回,其 linkedProductId/productName 为 null)。
+     * 按 sortOrder 升序排序,sortOrder 相等时按 id 升序稳定排序;description/icon 一并返回。
      */
      */
     @PostMapping("/types/links")
     @PostMapping("/types/links")
     public Result<List<Map<String, Object>>> listTypeLinks() {
     public Result<List<Map<String, Object>>> listTypeLinks() {
-        List<ReportTypeRegistry> types = typeRegistryMapper.selectList(
-                new LambdaQueryWrapper<ReportTypeRegistry>()
-                        .eq(ReportTypeRegistry::getIsActive, true)
-                        .isNotNull(ReportTypeRegistry::getLinkedProductId));
+        List<ReportTypeRegistry> types = typeRegistryMapper.selectList(new LambdaQueryWrapper<>());
+        List<ReportTypeRegistry> active = new ArrayList<>();
+        if (types != null) {
+            for (ReportTypeRegistry t : types) {
+                if (t != null && Boolean.TRUE.equals(t.getIsActive())) active.add(t);
+            }
+        }
+        // 排序:sortOrder 升序(NULL 最后),相等时按 id 升序稳定排序
+        active.sort(Comparator.comparing(ReportTypeRegistry::getSortOrder,
+                        Comparator.nullsLast(Comparator.naturalOrder()))
+                .thenComparing(ReportTypeRegistry::getId,
+                        Comparator.nullsLast(Comparator.naturalOrder())));
         List<Map<String, Object>> result = new ArrayList<>();
         List<Map<String, Object>> result = new ArrayList<>();
-        if (types == null || types.isEmpty()) {
+        if (active.isEmpty()) {
             return Result.success(result);
             return Result.success(result);
         }
         }
-        // 批量回填商品名,避免 N+1
+        // 批量回填商品名,避免 N+1;无任何商品 id 时跳过查询
         Set<Long> productIds = new HashSet<>();
         Set<Long> productIds = new HashSet<>();
-        for (ReportTypeRegistry t : types) {
+        for (ReportTypeRegistry t : active) {
             if (t.getLinkedProductId() != null) productIds.add(t.getLinkedProductId());
             if (t.getLinkedProductId() != null) productIds.add(t.getLinkedProductId());
         }
         }
         Map<Long, String> nameMap = new HashMap<>();
         Map<Long, String> nameMap = new HashMap<>();
-        try {
-            List<Product> products = productMapper.selectBatchIds(productIds);
-            if (products != null) {
-                for (Product p : products) {
-                    if (p != null && p.getId() != null) nameMap.put(p.getId(), p.getName());
+        if (!productIds.isEmpty()) {
+            try {
+                List<Product> products = productMapper.selectBatchIds(productIds);
+                if (products != null) {
+                    for (Product p : products) {
+                        if (p != null && p.getId() != null) nameMap.put(p.getId(), p.getName());
+                    }
                 }
                 }
+            } catch (Exception e) {
+                log.warn("查询商品名失败(不影响链接返回): {}", e.getMessage());
             }
             }
-        } catch (Exception e) {
-            log.warn("查询商品名失败(不影响链接返回): {}", e.getMessage());
         }
         }
-        for (ReportTypeRegistry t : types) {
+        for (ReportTypeRegistry t : active) {
             Map<String, Object> item = new LinkedHashMap<>();
             Map<String, Object> item = new LinkedHashMap<>();
             item.put("typeId", t.getTypeId());
             item.put("typeId", t.getTypeId());
             item.put("displayName", t.getDisplayName());
             item.put("displayName", t.getDisplayName());
+            item.put("description", t.getDescription());
+            item.put("icon", t.getIcon());
+            item.put("sortOrder", t.getSortOrder());
             item.put("linkedProductId", t.getLinkedProductId());
             item.put("linkedProductId", t.getLinkedProductId());
-            item.put("productName", nameMap.get(t.getLinkedProductId()));
+            item.put("productName", t.getLinkedProductId() != null ? nameMap.get(t.getLinkedProductId()) : null);
             result.add(item);
             result.add(item);
         }
         }
         return Result.success(result);
         return Result.success(result);

+ 5 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportParserAdminController.java

@@ -107,6 +107,11 @@ public class ReportParserAdminController {
 
 
     @PostMapping("/types/save")
     @PostMapping("/types/save")
     public Result<Void> saveType(@RequestBody ReportTypeRegistry type) {
     public Result<Void> saveType(@RequestBody ReportTypeRegistry type) {
+        // 归一化:icon 若为空串视为未填,置 null 走 DB 默认/updateById 非空更新忽略,
+        // 避免把 "" 写库覆盖默认;sortOrder 为数值型,前端不填以 null 提交(DB 默认 100 兜底)
+        if (type.getIcon() != null && type.getIcon().trim().isEmpty()) {
+            type.setIcon(null);
+        }
         if (type.getTypeId() == null || type.getTypeId().isEmpty()) {
         if (type.getTypeId() == null || type.getTypeId().isEmpty()) {
             return Result.error("typeId 不能为空");
             return Result.error("typeId 不能为空");
         }
         }

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

@@ -5308,6 +5308,8 @@ CREATE TABLE IF NOT EXISTS report_type_registry (
     script_status VARCHAR(20) DEFAULT NULL COMMENT '采集脚本生成状态: generating/ready/failed',
     script_status VARCHAR(20) DEFAULT NULL COMMENT '采集脚本生成状态: generating/ready/failed',
     expected_indicators TEXT DEFAULT NULL COMMENT '该报告类型应采集的指标项定义(JSON数组),用于数据采集完整性校验',
     expected_indicators TEXT DEFAULT NULL COMMENT '该报告类型应采集的指标项定义(JSON数组),用于数据采集完整性校验',
     linked_product_id BIGINT DEFAULT NULL COMMENT '关联商城商品 products.id,NULL=不可链接',
     linked_product_id BIGINT DEFAULT NULL COMMENT '关联商城商品 products.id,NULL=不可链接',
+    icon VARCHAR(50) DEFAULT NULL COMMENT '页面展示图标(emoji或图标类名)',
+    sort_order INT DEFAULT 100 COMMENT '展示排序,升序(小程序上传页支持的报告类型列表顺序)',
     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,
     UNIQUE KEY uk_type_id (type_id)
     UNIQUE KEY uk_type_id (type_id)