Parcourir la source

feat(admin): 新增报告处理链路追踪/归因后台

- ReportTraceService:四表(health_report_drafts / health_reports 孤儿 / dan_report_uploads / report_unknown_upload)归一化为 TraceNode,SQL 层分表筛选 + 内存归并排序分页
- ReportTraceAdminController:新增 list/detail/retry/bind-member/unknown-list/stats 六个 @PostMapping,admin 角色校验
- 手动归因:回填 family_id + resolveSubjectToMemberId + reassignReport(刷新五维能量与食材推荐)
- 重试路由:健康草稿异步重跑 / DAN reparseUpload / 未知指纹重识别后重新入链
- cfc-web 新增 ReportTrace.vue(统计卡 + 7 天趋势 + 筛选 + 表格 + 详情抽屉 + 归因弹窗 + 未知聚类区),菜单与路由复用 config:report-parser
- API_REFERENCE.md 登记 6 个新接口
zxyj-web il y a 3 semaines
Parent
commit
eeea6c5d39

+ 149 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/ReportTraceAdminController.java

@@ -0,0 +1,149 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.service.ReportTraceService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * 报告处理链路追踪 / 归因(管理员)。
+ *
+ * <p>统一联查 health_report_drafts / health_reports(孤儿)/ dan_report_uploads / report_unknown_upload,
+ * 让运营看清「上传 → 哪个服务解析 → 解析出什么 → 落到哪个成员(或为何没落)」。</p>
+ *
+ * <p>鉴权由 JwtInterceptor 对 /api/** 统一拦截,本控制器再校验 admin 角色。</p>
+ */
+@RestController
+@RequestMapping("/api/admin/report-trace")
+public class ReportTraceAdminController {
+
+    private static final Logger log = LoggerFactory.getLogger(ReportTraceAdminController.class);
+
+    @Resource
+    private ReportTraceService reportTraceService;
+
+    /** 统一联查列表(四表归一化 + 内存分页) */
+    @PostMapping("/list")
+    public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params,
+                                            @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        try {
+            return Result.success(reportTraceService.buildTraceList(params));
+        } catch (Exception e) {
+            log.warn("报告链路列表查询失败: {}", e.getMessage());
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 单次上传的完整链路详情 */
+    @PostMapping("/detail")
+    public Result<Map<String, Object>> detail(@RequestBody Map<String, Object> params,
+                                              @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        String traceId = params.get("traceId") instanceof String ? (String) params.get("traceId") : null;
+        if (traceId == null || traceId.trim().isEmpty()) {
+            return Result.error("traceId 不能为空");
+        }
+        try {
+            return Result.success(reportTraceService.buildTraceDetail(traceId.trim()));
+        } catch (Exception e) {
+            log.warn("报告链路详情查询失败 traceId={}: {}", traceId, e.getMessage());
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 按来源类型路由重试:健康草稿 / DAN / 未知重识别 */
+    @PostMapping("/retry")
+    public Result<Map<String, Object>> retry(@RequestBody Map<String, Object> params,
+                                             @RequestAttribute("role") String role,
+                                             @RequestAttribute("userId") Long userId) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        String traceId = params.get("traceId") instanceof String ? (String) params.get("traceId") : null;
+        if (traceId == null || traceId.trim().isEmpty()) {
+            return Result.error("traceId 不能为空");
+        }
+        try {
+            return Result.success(reportTraceService.retryBySource(traceId.trim(), userId));
+        } catch (Exception e) {
+            log.warn("报告链路重试失败 traceId={}: {}", traceId, e.getMessage());
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 孤儿健康报告手动归因(回填 family_id + 绑定成员 + 刷新五维/食材) */
+    @PostMapping("/bind-member")
+    public Result<Map<String, Object>> bindMember(@RequestBody Map<String, Object> params,
+                                                  @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        Long reportId = toLong(params.get("reportId"));
+        Long memberId = toLong(params.get("memberId"));
+        if (reportId == null) {
+            return Result.error("reportId 不能为空");
+        }
+        if (memberId == null) {
+            return Result.error("memberId 不能为空");
+        }
+        try {
+            return Result.success(reportTraceService.bindMember(reportId, memberId));
+        } catch (Exception e) {
+            log.warn("报告归因失败 reportId={}, memberId={}: {}", reportId, memberId, e.getMessage());
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 未知报告聚类列表(辅助定位「为什么识别不了」) */
+    @PostMapping("/unknown-list")
+    public Result<Map<String, Object>> unknownList(@RequestBody Map<String, Object> params,
+                                                   @RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        try {
+            return Result.success(reportTraceService.buildUnknownList(params));
+        } catch (Exception e) {
+            log.warn("未知报告聚类查询失败: {}", e.getMessage());
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 概览统计:各来源总量 / 失败 / 采集中 / 未归因 / 近 7 天趋势 */
+    @PostMapping("/stats")
+    public Result<Map<String, Object>> stats(@RequestAttribute("role") String role) {
+        if (!"admin".equals(role)) {
+            return Result.error("无权限");
+        }
+        try {
+            return Result.success(reportTraceService.buildStats());
+        } catch (Exception e) {
+            log.warn("报告链路统计失败: {}", e.getMessage());
+            return Result.error(e.getMessage());
+        }
+    }
+
+    private Long toLong(Object v) {
+        if (v == null) return null;
+        if (v instanceof Number) return ((Number) v).longValue();
+        try {
+            return Long.parseLong(String.valueOf(v).trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+}

+ 1386 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportTraceService.java

@@ -0,0 +1,1386 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.DanAssessmentResult;
+import com.etotem.cfc.entity.DanReportUpload;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.HealthDiseaseRisk;
+import com.etotem.cfc.entity.HealthGutFlora;
+import com.etotem.cfc.entity.HealthIndicator;
+import com.etotem.cfc.entity.HealthReport;
+import com.etotem.cfc.entity.HealthReportDraft;
+import com.etotem.cfc.entity.ReportUnknownCluster;
+import com.etotem.cfc.entity.ReportUnknownUpload;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.DanAssessmentResultMapper;
+import com.etotem.cfc.mapper.DanReportUploadMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.HealthDiseaseRiskMapper;
+import com.etotem.cfc.mapper.HealthGutFloraMapper;
+import com.etotem.cfc.mapper.HealthIndicatorMapper;
+import com.etotem.cfc.mapper.HealthReportDraftMapper;
+import com.etotem.cfc.mapper.HealthReportMapper;
+import com.etotem.cfc.mapper.ReportUnknownClusterMapper;
+import com.etotem.cfc.mapper.ReportUnknownUploadMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Resource;
+import java.io.File;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TimeZone;
+import java.util.stream.Collectors;
+
+/**
+ * 报告处理链路追踪 / 归因服务(后台「报告链路追踪」页)。
+ *
+ * <p>把四张来源表归一化为统一的 TraceNode 视图:
+ * health_report_drafts(健康草稿)/ health_reports(孤儿:subject_id 或 family_id 为空)/
+ * dan_report_uploads + dan_assessment_results(DAN 上传)/ report_unknown_upload + report_unknown_cluster(未知上传)。
+ *
+ * <p>只读现有表、只调用既有 Service 公开能力(retry / reparse / bind / re-identify),不新增迁移。
+ */
+@Service
+public class ReportTraceService {
+
+    private static final Logger log = LoggerFactory.getLogger(ReportTraceService.class);
+
+    /** 来源类型 */
+    public static final String SRC_HEALTH_DRAFT = "health_draft";
+    public static final String SRC_HEALTH_REPORT = "health_report";
+    public static final String SRC_DAN_UPLOAD = "dan_upload";
+    public static final String SRC_UNKNOWN = "unknown";
+
+    /** 未归因原因 */
+    public static final String REASON_FAMILY_NULL = "familyId_null";
+    public static final String REASON_NAME_NO_MATCH = "name_no_match";
+    public static final String REASON_MEMBER_NOT_SELECTED = "member_not_selected";
+    public static final String REASON_UNKNOWN_TYPE = "unknown_type";
+
+    /** 解析服务标识 */
+    public static final String SERVICE_DAN_JAVA = "dan_java";
+    public static final String SERVICE_UNKNOWN_LLM = "unknown_llm";
+    public static final String SERVICE_PENDING = "pending";
+    public static final String SERVICE_LEGACY = "legacy";
+
+    private static final int MAX_PAGE_CAP = 2000;
+    private static final int PAYLOAD_PREVIEW_LEN = 4000;
+
+    /** 详情里原始字段的日期统一转可读字符串(ObjectMapper 会克隆 DateFormat,线程安全) */
+    private final ObjectMapper objectMapper = new ObjectMapper()
+            .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
+
+    @Resource
+    private HealthReportDraftMapper healthReportDraftMapper;
+    @Resource
+    private HealthReportMapper healthReportMapper;
+    @Resource
+    private DanReportUploadMapper danReportUploadMapper;
+    @Resource
+    private DanAssessmentResultMapper danAssessmentResultMapper;
+    @Resource
+    private ReportUnknownUploadMapper reportUnknownUploadMapper;
+    @Resource
+    private ReportUnknownClusterMapper reportUnknownClusterMapper;
+    @Resource
+    private HealthIndicatorMapper healthIndicatorMapper;
+    @Resource
+    private HealthGutFloraMapper healthGutFloraMapper;
+    @Resource
+    private HealthDiseaseRiskMapper healthDiseaseRiskMapper;
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+    @Resource
+    private UserMapper userMapper;
+
+    @Resource
+    private HealthReportDraftService healthReportDraftService;
+    @Resource
+    private ReportCollectService reportCollectService;
+    @Resource
+    private DanReportUploadService danReportUploadService;
+    @Resource
+    private HealthReportService healthReportService;
+    @Resource
+    private ReportParserDispatchService reportParserDispatchService;
+    @Resource
+    private ReportFingerprintService reportFingerprintService;
+    @Resource
+    private StorageService storageService;
+
+    // =============================================================
+    // 1. 统一列表联查
+    // =============================================================
+
+    public Map<String, Object> buildTraceList(Map<String, Object> params) {
+        TraceQuery q = parseQuery(params);
+        List<Map<String, Object>> nodes = new ArrayList<>();
+        long total = 0;
+
+        if (q.includeSource(SRC_HEALTH_DRAFT)) {
+            LambdaQueryWrapper<HealthReportDraft> w = draftWrapper(q);
+            long cnt = healthReportDraftMapper.selectCount(w);
+            total += cnt;
+            if (cnt > 0 && q.limit > 0) {
+                w.orderByDesc(HealthReportDraft::getCreatedAt).last("LIMIT " + q.limit);
+                nodes.addAll(toDraftNodes(healthReportDraftMapper.selectList(w)));
+            }
+        }
+
+        if (q.includeSource(SRC_HEALTH_REPORT)) {
+            LambdaQueryWrapper<HealthReport> w = reportWrapper(q);
+            long cnt = healthReportMapper.selectCount(w);
+            total += cnt;
+            if (cnt > 0 && q.limit > 0) {
+                w.orderByDesc(HealthReport::getCreatedAt).last("LIMIT " + q.limit);
+                nodes.addAll(toReportNodes(healthReportMapper.selectList(w)));
+            }
+        }
+
+        if (q.includeSource(SRC_DAN_UPLOAD)) {
+            LambdaQueryWrapper<DanReportUpload> w = danWrapper(q);
+            long cnt = danReportUploadMapper.selectCount(w);
+            total += cnt;
+            if (cnt > 0 && q.limit > 0) {
+                w.orderByDesc(DanReportUpload::getUploadedAt).last("LIMIT " + q.limit);
+                nodes.addAll(toDanNodes(danReportUploadMapper.selectList(w)));
+            }
+        }
+
+        if (q.includeSource(SRC_UNKNOWN)) {
+            LambdaQueryWrapper<ReportUnknownUpload> w = unknownWrapper(q);
+            long cnt = reportUnknownUploadMapper.selectCount(w);
+            total += cnt;
+            if (cnt > 0 && q.limit > 0) {
+                w.orderByDesc(ReportUnknownUpload::getUploadedAt).last("LIMIT " + q.limit);
+                nodes.addAll(toUnknownNodes(reportUnknownUploadMapper.selectList(w)));
+            }
+        }
+
+        // 按上传时间倒序(null 置底)后内存分页
+        nodes.sort((a, b) -> {
+            Date ta = (Date) a.get("uploadedAt");
+            Date tb = (Date) b.get("uploadedAt");
+            if (ta == null && tb == null) return 0;
+            if (ta == null) return 1;
+            if (tb == null) return -1;
+            return tb.compareTo(ta);
+        });
+
+        enrichNodes(nodes);
+
+        int from = (q.page - 1) * q.size;
+        int to = Math.min(from + q.size, nodes.size());
+        List<Map<String, Object>> pageRecords = from >= nodes.size()
+                ? Collections.emptyList()
+                : new ArrayList<>(nodes.subList(Math.max(from, 0), Math.max(to, from)));
+
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("total", total);
+        data.put("records", pageRecords);
+        return data;
+    }
+
+    // =============================================================
+    // 2. 详情
+    // =============================================================
+
+    public Map<String, Object> buildTraceDetail(String traceId) {
+        String[] parts = splitTraceId(traceId);
+        if (parts == null) {
+            throw new IllegalArgumentException("traceId 格式非法,应为 sourceType:id");
+        }
+        String sourceType = parts[0];
+        long id = Long.parseLong(parts[1]);
+
+        Map<String, Object> node;
+        switch (sourceType) {
+            case SRC_HEALTH_DRAFT: {
+                HealthReportDraft d = healthReportDraftMapper.selectById(id);
+                if (d == null) throw new IllegalArgumentException("草稿不存在: " + id);
+                node = draftNode(d);
+                Map<String, Object> detail = baseDetail(node, sourceType, d.getId());
+                detail.put("payloadPreview", preview(d.getPayloadJson()));
+                detail.put("collectValidation", d.getCollectValidation());
+                detail.put("parseAttempt", d.getParseAttempt());
+                detail.put("nextRetryAt", d.getNextRetryAt());
+                detail.put("parseStartedAt", d.getParseStartedAt());
+                detail.put("parseFinishedAt", d.getParseFinishedAt());
+                detail.put("expireAt", d.getExpireAt());
+                detail.put("status", d.getStatus());
+                detail.put("remark", d.getRemark());
+                // 落地报告
+                if (d.getConfirmedReportId() != null) {
+                    HealthReport lr = healthReportMapper.selectById(d.getConfirmedReportId());
+                    detail.put("landedReport", lr != null ? reportSummary(lr) : null);
+                }
+                // 指标计数(payload 数组长度 + 落地表计数兜底)
+                detail.put("counts", draftCounts(d.getPayloadJson(), d.getConfirmedReportId()));
+                enrichNode(detail);
+                return detail;
+            }
+            case SRC_HEALTH_REPORT: {
+                HealthReport r = healthReportMapper.selectById(id);
+                if (r == null) throw new IllegalArgumentException("健康报告不存在: " + id);
+                node = reportNode(r);
+                Map<String, Object> detail = baseDetail(node, sourceType, r.getId());
+                detail.put("payloadPreview", preview(r.getPayloadJson()));
+                detail.put("personName", r.getPersonName());
+                detail.put("reportFormat", r.getReportFormat());
+                detail.put("reportNumber", r.getReportNumber());
+                detail.put("reportDate", r.getReportDate());
+                detail.put("overallScore", r.getOverallScore());
+                detail.put("status", r.getStatus());
+                detail.put("counts", reportCounts(r.getId()));
+                // 关联草稿(如有):溯源解析服务/失败原因
+                HealthReportDraft src = healthReportDraftMapper.selectOne(
+                        new LambdaQueryWrapper<HealthReportDraft>()
+                                .eq(HealthReportDraft::getConfirmedReportId, r.getId())
+                                .last("LIMIT 1"));
+                if (src != null) {
+                    Map<String, Object> srcInfo = new LinkedHashMap<>();
+                    srcInfo.put("draftId", src.getId());
+                    srcInfo.put("parseMethod", src.getParseMethod());
+                    srcInfo.put("parseError", src.getParseError());
+                    srcInfo.put("parseAttempt", src.getParseAttempt());
+                    srcInfo.put("collectValidation", src.getCollectValidation());
+                    detail.put("sourceDraft", srcInfo);
+                }
+                detail.put("indicators", sampleIndicators(r.getId()));
+                enrichNode(detail);
+                return detail;
+            }
+            case SRC_DAN_UPLOAD: {
+                DanReportUpload u = danReportUploadMapper.selectById(id);
+                if (u == null) throw new IllegalArgumentException("DAN 上传记录不存在: " + id);
+                node = danNode(u);
+                Map<String, Object> detail = baseDetail(node, sourceType, u.getId());
+                detail.put("parsedItemsPreview", preview(u.getParsedItems()));
+                detail.put("parsedSummary", u.getParsedSummary());
+                detail.put("parsedSuggestions", u.getParsedSuggestions());
+                detail.put("parserVersion", u.getParserVersion());
+                detail.put("draftStatus", u.getDraftStatus());
+                detail.put("confirmedAt", u.getConfirmedAt());
+                detail.put("dimension", u.getDimension());
+                detail.put("counts", danCounts(u));
+                if (u.getLinkedResultId() != null) {
+                    DanAssessmentResult lr = danAssessmentResultMapper.selectById(u.getLinkedResultId());
+                    detail.put("landedReport", lr != null ? danResultSummary(lr) : null);
+                }
+                enrichNode(detail);
+                return detail;
+            }
+            case SRC_UNKNOWN: {
+                ReportUnknownUpload u = reportUnknownUploadMapper.selectById(id);
+                if (u == null) throw new IllegalArgumentException("未知上传记录不存在: " + id);
+                node = unknownNode(u);
+                Map<String, Object> detail = baseDetail(node, sourceType, u.getId());
+                detail.put("llmResultPreview", preview(u.getLlmResult()));
+                if (u.getClusterId() != null) {
+                    ReportUnknownCluster cluster = reportUnknownClusterMapper.selectById(u.getClusterId());
+                    detail.put("cluster", cluster != null ? clusterSummary(cluster) : null);
+                }
+                detail.put("counts", unknownCounts(u.getLlmResult()));
+                enrichNode(detail);
+                return detail;
+            }
+            default:
+                throw new IllegalArgumentException("未知来源类型: " + sourceType);
+        }
+    }
+
+    // =============================================================
+    // 3. 重试路由
+    // =============================================================
+
+    public Map<String, Object> retryBySource(String traceId, Long operatorUserId) {
+        String[] parts = splitTraceId(traceId);
+        if (parts == null) {
+            throw new IllegalArgumentException("traceId 格式非法,应为 sourceType:id");
+        }
+        String sourceType = parts[0];
+        long id = Long.parseLong(parts[1]);
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("traceId", traceId);
+
+        switch (sourceType) {
+            case SRC_HEALTH_DRAFT: {
+                HealthReportDraft draft = healthReportDraftMapper.selectById(id);
+                if (draft == null) throw new IllegalArgumentException("草稿不存在: " + id);
+                healthReportDraftService.resetForManualRetry(id);
+                reportCollectService.submitAsyncCollect(id);
+                data.put("action", "resubmitted");
+                data.put("draftId", id);
+                data.put("parseStatus", "collecting");
+                return data;
+            }
+            case SRC_DAN_UPLOAD: {
+                DanReportUpload upload = danReportUploadMapper.selectById(id);
+                if (upload == null) throw new IllegalArgumentException("DAN 上传记录不存在: " + id);
+                String dimension = upload.getDimension();
+                Result<Map<String, Object>> r = danReportUploadService.reparseUpload(id, dimension);
+                if (r.getCode() != 200) {
+                    throw new IllegalArgumentException(r.getMessage());
+                }
+                data.put("action", "reparsed");
+                data.put("uploadId", id);
+                data.put("dimension", dimension);
+                Map<String, Object> rr = r.getData();
+                if (rr != null) data.putAll(rr);
+                return data;
+            }
+            case SRC_UNKNOWN: {
+                ReportUnknownUpload upload = reportUnknownUploadMapper.selectById(id);
+                if (upload == null) throw new IllegalArgumentException("未知上传记录不存在: " + id);
+                String pdfPath = resolveLocalPath(upload.getFileUrl());
+                if (pdfPath == null || !new File(pdfPath).exists()) {
+                    throw new IllegalArgumentException("报告文件不存在,无法重识别: " + upload.getFileUrl());
+                }
+                String fileName = fileNameFromUrl(upload.getFileUrl());
+                // 1) 先指纹重识别
+                Map<String, Object> fp = reportFingerprintService.detect(pdfPath, fileName);
+                String typeId = (String) fp.get("typeId");
+                data.put("fingerprintTypeId", typeId);
+                // 2) 识别出已知类型 → 重新入链(建草稿 + 异步采集)
+                if (typeId != null && !"unknown".equals(typeId)) {
+                    HealthReportDraft draft = healthReportDraftService.createDraft(
+                            operatorUserId, null, typeId,
+                            upload.getFileUrl(), fileName, "{}", upload.getFileHash());
+                    try {
+                        draft.setRemark("报告链路追踪:未知报告重识别为「" + typeId + "」后由管理员重新入链");
+                        draft.setUpdatedAt(new Date());
+                        healthReportDraftMapper.updateById(draft);
+                    } catch (Exception e) {
+                        log.warn("更新重入链草稿备注失败 draftId={}", draft.getId(), e);
+                    }
+                    reportCollectService.submitAsyncCollect(draft.getId());
+                    data.put("action", "requeued");
+                    data.put("draftId", draft.getId());
+                    data.put("typeId", typeId);
+                    data.put("message", "已识别为「" + typeId + "」并重新进入解析链路(采集完成后可在本页归因)");
+                    return data;
+                }
+                // 3) 仍未知 → 走 LLM 兜底重新解析并刷新 llmResult
+                Result<Map<String, Object>> r = reportParserDispatchService.parseReport(pdfPath, fileName);
+                if (r.getCode() != 200) {
+                    throw new IllegalArgumentException(r.getMessage());
+                }
+                try {
+                    upload.setLlmResult(objectMapper.writeValueAsString(r.getData()));
+                    reportUnknownUploadMapper.updateById(upload);
+                } catch (Exception e) {
+                    log.warn("刷新未知上传 llm_result 失败 uploadId={}", id, e);
+                }
+                data.put("action", "reidentified_unknown");
+                data.put("message", "重识别后仍为未知类型,LLM 解析结果已刷新,可在「未知报告审核」页继续处理");
+                return data;
+            }
+            default:
+                throw new IllegalArgumentException("该来源不支持重试: " + sourceType);
+        }
+    }
+
+    // =============================================================
+    // 4. 孤儿健康报告手动归因
+    // =============================================================
+
+    public Map<String, Object> bindMember(Long reportId, Long memberId) {
+        if (reportId == null) throw new IllegalArgumentException("reportId 不能为空");
+        if (memberId == null) throw new IllegalArgumentException("memberId 不能为空");
+        HealthReport report = healthReportMapper.selectById(reportId);
+        if (report == null) throw new IllegalArgumentException("健康报告不存在: " + reportId);
+
+        // 仅对孤儿报告生效(subject_id 或 family_id 为空)
+        boolean orphan = report.getSubjectId() == null || report.getFamilyId() == null;
+        if (!orphan) {
+            throw new IllegalArgumentException("该报告已归因到成员(subject_id=" + report.getSubjectId()
+                    + ", family_id=" + report.getFamilyId() + "),无需手动归因");
+        }
+
+        FamilyMember member = familyMemberMapper.selectById(memberId);
+        if (member == null) throw new IllegalArgumentException("家庭成员不存在: " + memberId);
+        Long memberFamilyId = member.getFamilyId();
+        if (memberFamilyId == null) throw new IllegalArgumentException("该成员尚未归属家庭,无法归因");
+
+        Long oldFamilyId = report.getFamilyId();
+        if (oldFamilyId == null) {
+            // 回填 family_id(管理员确认归属家庭后落库;绑定成员与其家庭一致)
+            healthReportMapper.update(null, new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<HealthReport>()
+                    .eq(HealthReport::getId, reportId)
+                    .set(HealthReport::getFamilyId, memberFamilyId)
+                    .set(HealthReport::getUpdatedAt, new Date()));
+            log.info("孤儿报告回填家庭 reportId={}, familyId={}", reportId, memberFamilyId);
+        } else if (!oldFamilyId.equals(memberFamilyId)) {
+            throw new IllegalArgumentException("所选成员属于家庭 " + memberFamilyId
+                    + ",与报告当前家庭 " + oldFamilyId + " 不一致,无法归因");
+        }
+
+        // 归一化 memberId 到 family_members.id 口径后复用 reassignReport(内部含五维/食材刷新)
+        Long resolved = healthReportService.resolveSubjectToMemberId(memberId, memberFamilyId);
+        healthReportService.reassignReport(reportId, resolved, memberFamilyId);
+
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("reportId", reportId);
+        data.put("memberId", resolved);
+        data.put("memberName", member.getNickname());
+        data.put("familyId", memberFamilyId);
+        data.put("message", "已归因到成员「" + member.getNickname() + "」,并已刷新五维能量与食材推荐");
+        return data;
+    }
+
+    // =============================================================
+    // 5. 未知聚类列表
+    // =============================================================
+
+    public Map<String, Object> buildUnknownList(Map<String, Object> params) {
+        int page = intParam(params, "page", 1);
+        int size = Math.min(intParam(params, "size", 20), 100);
+        String status = strParam(params, "status");
+        Long clusterId = longParam(params, "clusterId");
+
+        LambdaQueryWrapper<ReportUnknownCluster> w = new LambdaQueryWrapper<>();
+        if (StringUtils.hasText(status)) w.eq(ReportUnknownCluster::getStatus, status);
+        if (clusterId != null) w.eq(ReportUnknownCluster::getId, clusterId);
+        w.orderByDesc(ReportUnknownCluster::getUpdatedAt);
+
+        long total = reportUnknownClusterMapper.selectCount(w);
+        w.last("LIMIT " + (Math.min(page * size, MAX_PAGE_CAP)));
+        List<Map<String, Object>> records = new ArrayList<>();
+        for (ReportUnknownCluster c : reportUnknownClusterMapper.selectList(w)) {
+            records.add(clusterSummary(c));
+        }
+
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("total", total);
+        data.put("records", records);
+        return data;
+    }
+
+    // =============================================================
+    // 6. 概览统计
+    // =============================================================
+
+    public Map<String, Object> buildStats() {
+        Map<String, Object> data = new LinkedHashMap<>();
+
+        long draftTotal = healthReportDraftMapper.selectCount(null);
+        long reportTotal = healthReportMapper.selectCount(new LambdaQueryWrapper<HealthReport>()
+                .and(w -> w.isNull(HealthReport::getSubjectId).or().isNull(HealthReport::getFamilyId)));
+        long danTotal = danReportUploadMapper.selectCount(new LambdaQueryWrapper<DanReportUpload>()
+                .isNull(DanReportUpload::getDeletedAt));
+        long unknownTotal = reportUnknownUploadMapper.selectCount(null);
+
+        Map<String, Object> bySource = new LinkedHashMap<>();
+        bySource.put(SRC_HEALTH_DRAFT, draftTotal);
+        bySource.put(SRC_HEALTH_REPORT, reportTotal);
+        bySource.put(SRC_DAN_UPLOAD, danTotal);
+        bySource.put(SRC_UNKNOWN, unknownTotal);
+        data.put("bySource", bySource);
+
+        long failed = healthReportDraftMapper.selectCount(new LambdaQueryWrapper<HealthReportDraft>()
+                        .eq(HealthReportDraft::getParseStatus, ReportCollectService.STATUS_FAILED))
+                + danReportUploadMapper.selectCount(new LambdaQueryWrapper<DanReportUpload>()
+                        .eq(DanReportUpload::getParseStatus, DanReportUpload.PARSE_FAILED)
+                        .isNull(DanReportUpload::getDeletedAt));
+        long collecting = healthReportDraftMapper.selectCount(new LambdaQueryWrapper<HealthReportDraft>()
+                .eq(HealthReportDraft::getParseStatus, ReportCollectService.STATUS_COLLECTING));
+        long pending = healthReportDraftMapper.selectCount(new LambdaQueryWrapper<HealthReportDraft>()
+                        .eq(HealthReportDraft::getStatus, "pending"))
+                + danReportUploadMapper.selectCount(new LambdaQueryWrapper<DanReportUpload>()
+                        .eq(DanReportUpload::getDraftStatus, DanReportUpload.DRAFT_PENDING)
+                        .isNull(DanReportUpload::getDeletedAt));
+        long unattributed = reportTotal
+                + healthReportDraftMapper.selectCount(new LambdaQueryWrapper<HealthReportDraft>()
+                        .and(w -> w.isNull(HealthReportDraft::getFamilyId).or().isNull(HealthReportDraft::getMemberId)))
+                + unknownTotal;
+
+        data.put("failed", failed);
+        data.put("collecting", collecting);
+        data.put("pending", pending);
+        data.put("unattributed", unattributed);
+        data.put("total", draftTotal + reportTotal + danTotal + unknownTotal);
+
+        // 近 7 天趋势(按天,四表合并)
+        data.put("trend7Days", buildTrend());
+        return data;
+    }
+
+    private List<Map<String, Object>> buildTrend() {
+        Date today = startOfDay(new Date());
+        Date start = new Date(today.getTime() - 6L * 24 * 3600 * 1000);
+
+        Map<String, long[]> trend = new LinkedHashMap<>();
+        SimpleDateFormat dayFmt = new SimpleDateFormat("yyyy-MM-dd");
+        for (int i = 0; i < 7; i++) {
+            Date d = new Date(start.getTime() + (long) i * 24 * 3600 * 1000);
+            trend.put(dayFmt.format(d), new long[5]); // [draft, report, dan, unknown, total]
+        }
+
+        java.sql.Timestamp since = new java.sql.Timestamp(
+                new Date(startOfDay(new Date()).getTime() - 6L * 24 * 3600 * 1000).getTime());
+        addTrendRows(trend, 0, healthReportDraftMapper.selectMaps(new QueryWrapper<HealthReportDraft>()
+                .select("DATE(created_at) AS d", "COUNT(*) AS cnt").ge("created_at", since)));
+        addTrendRows(trend, 1, healthReportMapper.selectMaps(new QueryWrapper<HealthReport>()
+                .select("DATE(created_at) AS d", "COUNT(*) AS cnt").ge("created_at", since)));
+        addTrendRows(trend, 2, danReportUploadMapper.selectMaps(new QueryWrapper<DanReportUpload>()
+                .select("DATE(uploaded_at) AS d", "COUNT(*) AS cnt").ge("uploaded_at", since)));
+        addTrendRows(trend, 3, reportUnknownUploadMapper.selectMaps(new QueryWrapper<ReportUnknownUpload>()
+                .select("DATE(uploaded_at) AS d", "COUNT(*) AS cnt").ge("uploaded_at", since)));
+
+        List<Map<String, Object>> rows = new ArrayList<>();
+        for (Map.Entry<String, long[]> e : trend.entrySet()) {
+            long[] v = e.getValue();
+            Map<String, Object> row = new LinkedHashMap<>();
+            row.put("date", e.getKey());
+            row.put("draft", v[0]);
+            row.put("report", v[1]);
+            row.put("dan", v[2]);
+            row.put("unknown", v[3]);
+            row.put("total", v[0] + v[1] + v[2] + v[3]);
+            rows.add(row);
+        }
+        return rows;
+    }
+
+    @SuppressWarnings("unchecked")
+    private void addTrendRows(Map<String, long[]> trend, int idx, List<Map<String, Object>> maps) {
+        if (maps == null) return;
+        for (Map<String, Object> row : maps) {
+            String day = null;
+            long cnt = 0;
+            for (Map.Entry<String, Object> e : row.entrySet()) {
+                String k = e.getKey() == null ? "" : e.getKey().toLowerCase();
+                if ("d".equals(k)) day = normalizeDay(e.getValue());
+                else if ("cnt".equals(k)) cnt = toLong(e.getValue());
+            }
+            if (day != null && trend.containsKey(day)) {
+                long[] v = trend.get(day);
+                v[idx] = cnt;
+                v[4] += cnt;
+            }
+        }
+    }
+
+    // =============================================================
+    // TraceNode 归一化
+    // =============================================================
+
+    private Map<String, Object> draftNode(HealthReportDraft d) {
+        Map<String, Object> n = new LinkedHashMap<>();
+        n.put("traceId", SRC_HEALTH_DRAFT + ":" + d.getId());
+        n.put("sourceType", SRC_HEALTH_DRAFT);
+        n.put("sourceId", d.getId());
+        n.put("uploaderUserId", d.getUserId());
+        n.put("familyId", d.getFamilyId());
+        n.put("memberId", d.getMemberId());
+        n.put("fileName", d.getOriginalFilename());
+        n.put("fileUrl", d.getFileUrl());
+        n.put("fileHash", d.getFileHash());
+        n.put("selectedType", d.getReportType());
+        n.put("parseService", d.getParseMethod() != null ? d.getParseMethod() : SERVICE_PENDING);
+        n.put("parseMethod", d.getParseMethod());
+        n.put("parseStatus", d.getParseStatus());
+        n.put("parseError", d.getParseError());
+        n.put("parseAttempt", d.getParseAttempt());
+        n.put("landedReportId", d.getConfirmedReportId());
+        n.put("landedTable", d.getConfirmedReportId() != null ? "health_reports" : null);
+        n.put("draftStatus", d.getStatus());
+        n.put("uploadedAt", d.getCreatedAt());
+        n.put("updatedAt", d.getUpdatedAt());
+        n.put("detailApi", "/api/admin/report-trace/detail");
+        // 归因初判(落地报告核对在 enrich 中细化)
+        if (d.getFamilyId() == null) {
+            n.put("attributed", false);
+            n.put("attrReason", REASON_FAMILY_NULL);
+        } else if (d.getMemberId() == null) {
+            n.put("attributed", false);
+            n.put("attrReason", REASON_MEMBER_NOT_SELECTED);
+        } else {
+            n.put("attributed", true);
+        }
+        n.put("dataSummary", draftSummary(d.getPayloadJson()));
+        return n;
+    }
+
+    private Map<String, Object> reportNode(HealthReport r) {
+        Map<String, Object> n = new LinkedHashMap<>();
+        n.put("traceId", SRC_HEALTH_REPORT + ":" + r.getId());
+        n.put("sourceType", SRC_HEALTH_REPORT);
+        n.put("sourceId", r.getId());
+        n.put("uploaderUserId", r.getUserId());
+        n.put("familyId", r.getFamilyId());
+        n.put("memberId", r.getSubjectId());
+        n.put("fileName", fileNameFromUrl(r.getFileUrl()));
+        n.put("fileUrl", r.getFileUrl());
+        n.put("fileHash", r.getFileHash());
+        n.put("selectedType", r.getReportType());
+        n.put("parseService", SERVICE_LEGACY); // enrich 时若可溯源草稿则替换为真实解析方式
+        n.put("parseMethod", null);
+        n.put("parseStatus", "completed");
+        n.put("parseError", null);
+        n.put("personName", r.getPersonName());
+        n.put("landedReportId", r.getId());
+        n.put("landedTable", "health_reports");
+        n.put("uploadedAt", r.getCreatedAt());
+        n.put("updatedAt", r.getUpdatedAt());
+        n.put("detailApi", "/api/admin/report-trace/detail");
+        if (r.getSubjectId() != null && r.getFamilyId() != null) {
+            n.put("attributed", true);
+        } else if (r.getFamilyId() == null) {
+            n.put("attributed", false);
+            n.put("attrReason", REASON_FAMILY_NULL);
+        } else {
+            n.put("attributed", false);
+            n.put("attrReason", REASON_NAME_NO_MATCH);
+        }
+        Map<String, Object> ds = new LinkedHashMap<>();
+        ds.put("overallScore", r.getOverallScore());
+        ds.put("hasPayload", hasText(r.getPayloadJson()));
+        n.put("dataSummary", ds);
+        return n;
+    }
+
+    private Map<String, Object> danNode(DanReportUpload u) {
+        Map<String, Object> n = new LinkedHashMap<>();
+        n.put("traceId", SRC_DAN_UPLOAD + ":" + u.getId());
+        n.put("sourceType", SRC_DAN_UPLOAD);
+        n.put("sourceId", u.getId());
+        n.put("uploaderUserId", u.getUploaderUserId());
+        n.put("familyId", u.getFamilyId());
+        n.put("memberId", u.getFamilyMemberId());
+        n.put("fileName", u.getFileName());
+        n.put("fileUrl", u.getFileUrl());
+        n.put("fileHash", null);
+        n.put("selectedType", u.getReportType() != null ? u.getReportType() : u.getDimension());
+        n.put("parseService", SERVICE_DAN_JAVA);
+        n.put("parseMethod", u.getParserVersion());
+        n.put("parseStatus", normalizeDanStatus(u.getParseStatus()));
+        n.put("parseError", u.getParseError());
+        n.put("draftStatus", u.getDraftStatus());
+        n.put("landedReportId", u.getLinkedResultId());
+        n.put("landedTable", u.getLinkedResultId() != null ? "dan_assessment_results" : null);
+        n.put("uploadedAt", u.getUploadedAt());
+        n.put("updatedAt", u.getUpdatedAt());
+        n.put("detailApi", "/api/admin/report-trace/detail");
+        if (u.getFamilyMemberId() != null && u.getFamilyId() != null) {
+            n.put("attributed", true);
+        } else if (u.getFamilyMemberId() == null) {
+            n.put("attributed", false);
+            n.put("attrReason", REASON_MEMBER_NOT_SELECTED);
+        } else {
+            n.put("attributed", false);
+            n.put("attrReason", REASON_FAMILY_NULL);
+        }
+        n.put("dataSummary", danSummary(u));
+        return n;
+    }
+
+    private Map<String, Object> unknownNode(ReportUnknownUpload u) {
+        Map<String, Object> n = new LinkedHashMap<>();
+        n.put("traceId", SRC_UNKNOWN + ":" + u.getId());
+        n.put("sourceType", SRC_UNKNOWN);
+        n.put("sourceId", u.getId());
+        n.put("uploaderUserId", null);
+        n.put("familyId", null);
+        n.put("memberId", null);
+        n.put("fileName", fileNameFromUrl(u.getFileUrl()));
+        n.put("fileUrl", u.getFileUrl());
+        n.put("fileHash", u.getFileHash());
+        n.put("selectedType", null);
+        n.put("parseService", SERVICE_UNKNOWN_LLM);
+        n.put("parseMethod", null);
+        n.put("parseStatus", "unknown");
+        n.put("parseError", null);
+        n.put("clusterId", u.getClusterId());
+        n.put("landedReportId", null);
+        n.put("landedTable", null);
+        n.put("uploadedAt", u.getUploadedAt());
+        n.put("updatedAt", u.getUploadedAt());
+        n.put("detailApi", "/api/admin/report-trace/detail");
+        n.put("attributed", false);
+        n.put("attrReason", REASON_UNKNOWN_TYPE);
+        n.put("dataSummary", unknownSummary(u.getLlmResult()));
+        return n;
+    }
+
+    // =============================================================
+    // 数据摘要
+    // =============================================================
+
+    private Map<String, Object> draftSummary(String payloadJson) {
+        Map<String, Object> ds = new LinkedHashMap<>();
+        ds.put("hasPayload", hasText(payloadJson));
+        JsonNode root = parseJson(payloadJson);
+        if (root != null && root.isObject()) {
+            JsonNode summary = root.get("summary");
+            if (summary != null && summary.get("overallScore") != null && summary.get("overallScore").isNumber()) {
+                ds.put("overallScore", summary.get("overallScore").asInt());
+            }
+            ds.put("indicatorCount", arraySize(root, "indicators"));
+            ds.put("gutFloraCount", arraySize(root, "gutFlora") + arraySize(root, "probioticSpecies")
+                    + arraySize(root, "taxonomySpecies") + arraySize(root, "pathogenDetection"));
+            ds.put("diseaseRiskCount", arraySize(root, "diseaseRisks"));
+        } else {
+            ds.put("indicatorCount", 0);
+            ds.put("gutFloraCount", 0);
+            ds.put("diseaseRiskCount", 0);
+        }
+        return ds;
+    }
+
+    private Map<String, Object> danSummary(DanReportUpload u) {
+        Map<String, Object> ds = new LinkedHashMap<>();
+        JsonNode items = parseJson(u.getParsedItems());
+        if (items != null && items.isArray()) {
+            ds.put("itemCount", items.size());
+        } else {
+            ds.put("itemCount", 0);
+        }
+        ds.put("hasPayload", hasText(u.getParsedItems()));
+        return ds;
+    }
+
+    private Map<String, Object> unknownSummary(String llmResult) {
+        Map<String, Object> ds = new LinkedHashMap<>();
+        JsonNode root = parseJson(llmResult);
+        if (root != null && root.isObject()) {
+            ds.put("itemCount", root.size());
+            ds.put("hasPayload", true);
+        } else {
+            ds.put("itemCount", 0);
+            ds.put("hasPayload", false);
+        }
+        return ds;
+    }
+
+    private Map<String, Object> draftCounts(String payloadJson, Long landedReportId) {
+        Map<String, Object> ds = draftSummary(payloadJson);
+        if (landedReportId != null) {
+            ds.putAll(reportCounts(landedReportId));
+        }
+        return ds;
+    }
+
+    private Map<String, Object> reportCounts(Long reportId) {
+        Map<String, Object> ds = new LinkedHashMap<>();
+        if (reportId == null) return ds;
+        ds.put("indicatorCount", healthIndicatorMapper.selectCount(
+                new LambdaQueryWrapper<HealthIndicator>().eq(HealthIndicator::getReportId, reportId)).intValue());
+        ds.put("gutFloraCount", healthGutFloraMapper.selectCount(
+                new LambdaQueryWrapper<HealthGutFlora>().eq(HealthGutFlora::getReportId, reportId)).intValue());
+        ds.put("diseaseRiskCount", healthDiseaseRiskMapper.selectCount(
+                new LambdaQueryWrapper<HealthDiseaseRisk>().eq(HealthDiseaseRisk::getReportId, reportId)).intValue());
+        return ds;
+    }
+
+    private Map<String, Object> danCounts(DanReportUpload u) {
+        Map<String, Object> ds = new LinkedHashMap<>();
+        JsonNode items = parseJson(u.getParsedItems());
+        if (items != null && items.isArray()) {
+            ds.put("itemCount", items.size());
+        } else {
+            ds.put("itemCount", 0);
+        }
+        if (u.getLinkedResultId() != null) {
+            DanAssessmentResult r = danAssessmentResultMapper.selectById(u.getLinkedResultId());
+            if (r != null) ds.put("overallScore", r.getOverallScore());
+        }
+        return ds;
+    }
+
+    private Map<String, Object> unknownCounts(String llmResult) {
+        Map<String, Object> ds = unknownSummary(llmResult);
+        ds.put("llmLength", llmResult != null ? llmResult.length() : 0);
+        return ds;
+    }
+
+    // =============================================================
+    // 统一补充(成员名 / 上传人名 / 落地报告核对 / 指标计数)
+    // =============================================================
+
+    private void enrichNodes(List<Map<String, Object>> nodes) {
+        if (nodes.isEmpty()) return;
+        Set<Long> memberIds = new HashSet<>();
+        Set<Long> uploaderIds = new HashSet<>();
+        Set<Long> landedIds = new HashSet<>();
+        Set<Long> reportIds = new HashSet<>();
+        for (Map<String, Object> n : nodes) {
+            Long mid = (Long) n.get("memberId");
+            if (mid != null) memberIds.add(mid);
+            Long uid = (Long) n.get("uploaderUserId");
+            if (uid != null) uploaderIds.add(uid);
+            Long lid = (Long) n.get("landedReportId");
+            if (lid != null && "health_reports".equals(n.get("landedTable"))) landedIds.add(lid);
+            if (SRC_HEALTH_REPORT.equals(n.get("sourceType"))) {
+                reportIds.add((Long) n.get("sourceId"));
+            }
+        }
+        // 成员名
+        Map<Long, String> memberNames = new HashMap<>();
+        if (!memberIds.isEmpty()) {
+            for (FamilyMember fm : familyMemberMapper.selectBatchIds(memberIds)) {
+                memberNames.put(fm.getId(), fm.getNickname());
+            }
+        }
+        // 上传人名
+        Map<Long, String> uploaderNames = new HashMap<>();
+        if (!uploaderIds.isEmpty()) {
+            for (User u : userMapper.selectBatchIds(uploaderIds)) {
+                uploaderNames.put(u.getId(),
+                        StringUtils.hasText(u.getRealName()) ? u.getRealName() : u.getNickname());
+            }
+        }
+        // 落地报告核对(草稿 → health_reports 的 subject_id/family_id)
+        Map<Long, HealthReport> landed = new HashMap<>();
+        if (!landedIds.isEmpty()) {
+            for (HealthReport lr : healthReportMapper.selectBatchIds(landedIds)) {
+                landed.put(lr.getId(), lr);
+            }
+        }
+        // 报告类节点的指标/菌群/风险计数(批量)
+        Map<Long, Map<String, Object>> reportCounts = new HashMap<>();
+        if (!reportIds.isEmpty()) {
+            reportCounts.putAll(countIndicators(reportIds));
+            reportCounts.putAll(countGutFlora(reportIds));
+            reportCounts.putAll(countDiseaseRisks(reportIds));
+        }
+        // 草稿 → 溯源解析服务(health_report 节点经 confirmed_report_id 反查)
+        Map<Long, String> draftMethodByReport = new HashMap<>();
+        Set<Long> confirmedDraftIds = new HashSet<>(landedIds);
+        if (!confirmedDraftIds.isEmpty()) {
+            for (HealthReportDraft d : healthReportDraftMapper.selectList(
+                    new LambdaQueryWrapper<HealthReportDraft>()
+                            .in(HealthReportDraft::getConfirmedReportId, confirmedDraftIds))) {
+                if (d.getConfirmedReportId() != null && d.getParseMethod() != null) {
+                    draftMethodByReport.put(d.getConfirmedReportId(), d.getParseMethod());
+                }
+            }
+        }
+
+        for (Map<String, Object> n : nodes) {
+            Long mid = (Long) n.get("memberId");
+            if (mid != null) n.put("memberName", memberNames.getOrDefault(mid, null));
+            Long uid = (Long) n.get("uploaderUserId");
+            if (uid != null) n.put("uploaderName", uploaderNames.getOrDefault(uid, null));
+            String st = (String) n.get("sourceType");
+            Long lid = (Long) n.get("landedReportId");
+            if (SRC_HEALTH_DRAFT.equals(st)) {
+                if (lid != null) {
+                    HealthReport lr = landed.get(lid);
+                    if (lr != null) {
+                        Long effFamily = lr.getFamilyId() != null ? lr.getFamilyId() : (Long) n.get("familyId");
+                        n.put("familyId", effFamily);
+                        if (lr.getSubjectId() != null && effFamily != null) {
+                            n.put("memberId", lr.getSubjectId());
+                            n.put("attributed", true);
+                            n.remove("attrReason");
+                        } else {
+                            n.put("attributed", false);
+                            n.put("attrReason", lr.getFamilyId() == null ? REASON_FAMILY_NULL : REASON_NAME_NO_MATCH);
+                        }
+                    }
+                }
+                Map<String, Object> ds = (Map<String, Object>) n.get("dataSummary");
+                if (lid != null && reportCounts.containsKey(lid)) {
+                    ds.putAll(reportCounts.get(lid));
+                }
+                n.put("dataSummary", ds);
+            } else if (SRC_HEALTH_REPORT.equals(st)) {
+                Map<String, Object> ds = (Map<String, Object>) n.get("dataSummary");
+                ds.putAll(reportCounts.getOrDefault((Long) n.get("sourceId"), Collections.emptyMap()));
+                if (draftMethodByReport.containsKey((Long) n.get("sourceId"))) {
+                    n.put("parseService", draftMethodByReport.get((Long) n.get("sourceId")));
+                }
+                n.put("dataSummary", ds);
+            } else if (SRC_DAN_UPLOAD.equals(st)) {
+                Map<String, Object> ds = (Map<String, Object>) n.get("dataSummary");
+                if (lid != null) {
+                    DanAssessmentResult r = danAssessmentResultMapper.selectById(lid);
+                    if (r != null) ds.put("overallScore", r.getOverallScore());
+                }
+                n.put("dataSummary", ds);
+            }
+        }
+    }
+
+    private Map<Long, Map<String, Object>> countIndicators(Set<Long> reportIds) {
+        return groupCount(healthIndicatorMapper, new QueryWrapper<HealthIndicator>()
+                .select("report_id AS rid", "COUNT(*) AS cnt")
+                .in("report_id", reportIds)
+                .groupBy("report_id"), "indicatorCount");
+    }
+
+    private Map<Long, Map<String, Object>> countGutFlora(Set<Long> reportIds) {
+        return groupCount(healthGutFloraMapper, new QueryWrapper<HealthGutFlora>()
+                .select("report_id AS rid", "COUNT(*) AS cnt")
+                .in("report_id", reportIds)
+                .groupBy("report_id"), "gutFloraCount");
+    }
+
+    private Map<Long, Map<String, Object>> countDiseaseRisks(Set<Long> reportIds) {
+        return groupCount(healthDiseaseRiskMapper, new QueryWrapper<HealthDiseaseRisk>()
+                .select("report_id AS rid", "COUNT(*) AS cnt")
+                .in("report_id", reportIds)
+                .groupBy("report_id"), "diseaseRiskCount");
+    }
+
+    private <T> Map<Long, Map<String, Object>> groupCount(BaseMapper<T> mapper,
+                                                          QueryWrapper<T> qw, String key) {
+        Map<Long, Map<String, Object>> out = new HashMap<>();
+        try {
+            List<Map<String, Object>> rows = mapper.selectMaps(qw);
+            for (Map<String, Object> row : rows) {
+                Long rid = null;
+                Long cnt = null;
+                for (Map.Entry<String, Object> e : row.entrySet()) {
+                    String k = e.getKey() == null ? "" : e.getKey().toLowerCase();
+                    if ("rid".equals(k) || "report_id".equals(k)) rid = toLong(e.getValue());
+                    else if ("cnt".equals(k)) cnt = toLong(e.getValue());
+                }
+                if (rid != null) {
+                    Map<String, Object> m = new LinkedHashMap<>();
+                    m.put(key, cnt == null ? 0 : cnt.intValue());
+                    out.put(rid, m);
+                }
+            }
+        } catch (Exception e) {
+            log.warn("分组计数失败 key={}", key, e);
+        }
+        return out;
+    }
+
+    private void enrichNode(Map<String, Object> node) {
+        List<Map<String, Object>> one = new ArrayList<>();
+        one.add(node);
+        enrichNodes(one);
+    }
+
+    // =============================================================
+    // 摘要展示
+    // =============================================================
+
+    private Map<String, Object> baseDetail(Map<String, Object> node, String sourceType, long id) {
+        Map<String, Object> detail = new LinkedHashMap<>(node);
+        detail.put("sourceRaw", Collections.emptyMap());
+        switch (sourceType) {
+            case SRC_HEALTH_DRAFT: {
+                HealthReportDraft d = healthReportDraftMapper.selectById(id);
+                detail.put("sourceRaw", entityToMap(d, "payloadJson"));
+                break;
+            }
+            case SRC_HEALTH_REPORT: {
+                HealthReport r = healthReportMapper.selectById(id);
+                detail.put("sourceRaw", entityToMap(r, "payloadJson", "aiAnalysis"));
+                break;
+            }
+            case SRC_DAN_UPLOAD: {
+                DanReportUpload u = danReportUploadMapper.selectById(id);
+                detail.put("sourceRaw", entityToMap(u, "parsedItems", "parsedExtra", "parsedSummary",
+                        "parsedSuggestions", "editedItems", "editedExtra", "editedSummary", "editedSuggestions"));
+                break;
+            }
+            case SRC_UNKNOWN: {
+                ReportUnknownUpload u = reportUnknownUploadMapper.selectById(id);
+                detail.put("sourceRaw", entityToMap(u, "llmResult"));
+                break;
+            }
+            default:
+                break;
+        }
+        return detail;
+    }
+
+    /** 实体 → Map(剔除大文本字段,避免详情接口载荷过大) */
+    private Map<String, Object> entityToMap(Object entity, String... bigFields) {
+        try {
+            Map<String, Object> m = objectMapper.convertValue(entity,
+                    new TypeReference<LinkedHashMap<String, Object>>() {});
+            for (String f : bigFields) {
+                m.remove(f);
+            }
+            return m;
+        } catch (Exception e) {
+            log.warn("实体转Map失败: {}", e.getMessage());
+            return new LinkedHashMap<>();
+        }
+    }
+
+    private Map<String, Object> reportSummary(HealthReport r) {
+        Map<String, Object> m = new LinkedHashMap<>();
+        m.put("reportId", r.getId());
+        m.put("reportType", r.getReportType());
+        m.put("personName", r.getPersonName());
+        m.put("familyId", r.getFamilyId());
+        m.put("subjectId", r.getSubjectId());
+        m.put("overallScore", r.getOverallScore());
+        m.put("reportDate", r.getReportDate());
+        m.put("createdAt", r.getCreatedAt());
+        return m;
+    }
+
+    private Map<String, Object> danResultSummary(DanAssessmentResult r) {
+        Map<String, Object> m = new LinkedHashMap<>();
+        m.put("resultId", r.getId());
+        m.put("familyMemberId", r.getFamilyMemberId());
+        m.put("familyMemberName", r.getFamilyMemberName());
+        m.put("dimension", r.getDimension());
+        m.put("overallScore", r.getOverallScore());
+        m.put("status", r.getStatus());
+        m.put("createdAt", r.getCreatedAt());
+        return m;
+    }
+
+    private Map<String, Object> clusterSummary(ReportUnknownCluster c) {
+        Map<String, Object> m = new LinkedHashMap<>();
+        m.put("clusterId", c.getId());
+        m.put("clusterKey", c.getClusterKey());
+        m.put("reportCount", c.getReportCount());
+        m.put("status", c.getStatus());
+        m.put("generatedTypeId", c.getGeneratedTypeId());
+        m.put("commonSignatures", preview(c.getCommonSignatures()));
+        m.put("llmTemplate", preview(c.getLlmTemplate()));
+        m.put("createdAt", c.getCreatedAt());
+        m.put("updatedAt", c.getUpdatedAt());
+        return m;
+    }
+
+    private List<Map<String, Object>> sampleIndicators(Long reportId) {
+        List<Map<String, Object>> out = new ArrayList<>();
+        List<HealthIndicator> list = healthIndicatorMapper.selectList(
+                new LambdaQueryWrapper<HealthIndicator>()
+                        .eq(HealthIndicator::getReportId, reportId)
+                        .orderByAsc(HealthIndicator::getSortOrder)
+                        .last("LIMIT 30"));
+        for (HealthIndicator i : list) {
+            Map<String, Object> m = new LinkedHashMap<>();
+            m.put("category", i.getCategory());
+            m.put("indicatorName", i.getIndicatorName());
+            m.put("indicatorValue", i.getIndicatorValue());
+            m.put("unit", i.getUnit());
+            m.put("status", i.getStatus());
+            out.add(m);
+        }
+        return out;
+    }
+
+    // =============================================================
+    // 查询条件构造
+    // =============================================================
+
+    private static class TraceQuery {
+        Long userId;
+        Long familyId;
+        Long memberId;
+        String fileHash;
+        String fileName;
+        String sourceType;
+        String status;
+        Date startTime;
+        Date endTime;
+        int page = 1;
+        int size = 20;
+        int limit;
+
+        boolean includeSource(String src) {
+            return sourceType == null || sourceType.isEmpty() || sourceType.equals(src)
+                    || ("health".equals(sourceType) && (SRC_HEALTH_DRAFT.equals(src) || SRC_HEALTH_REPORT.equals(src)));
+        }
+    }
+
+    private TraceQuery parseQuery(Map<String, Object> params) {
+        TraceQuery q = new TraceQuery();
+        q.userId = longParam(params, "userId");
+        q.familyId = longParam(params, "familyId");
+        q.memberId = longParam(params, "memberId");
+        q.fileHash = strParam(params, "fileHash");
+        q.fileName = strParam(params, "fileName");
+        q.sourceType = strParam(params, "sourceType");
+        q.status = strParam(params, "status");
+        q.startTime = dateParam(params, "startTime");
+        q.endTime = dateParam(params, "endTime");
+        q.page = Math.max(intParam(params, "page", 1), 1);
+        q.size = Math.min(Math.max(intParam(params, "size", 20), 1), 100);
+        q.limit = Math.min(q.page * q.size, MAX_PAGE_CAP);
+        return q;
+    }
+
+    private LambdaQueryWrapper<HealthReportDraft> draftWrapper(TraceQuery q) {
+        LambdaQueryWrapper<HealthReportDraft> w = new LambdaQueryWrapper<>();
+        if (q.userId != null) w.eq(HealthReportDraft::getUserId, q.userId);
+        if (q.familyId != null) w.eq(HealthReportDraft::getFamilyId, q.familyId);
+        if (q.memberId != null) w.eq(HealthReportDraft::getMemberId, q.memberId);
+        if (StringUtils.hasText(q.fileHash)) w.eq(HealthReportDraft::getFileHash, q.fileHash);
+        if (StringUtils.hasText(q.fileName)) w.like(HealthReportDraft::getOriginalFilename, q.fileName);
+        if (q.startTime != null) w.ge(HealthReportDraft::getCreatedAt, q.startTime);
+        if (q.endTime != null) w.le(HealthReportDraft::getCreatedAt, q.endTime);
+        applyDraftStatus(w, q.status);
+        return w;
+    }
+
+    private void applyDraftStatus(LambdaQueryWrapper<HealthReportDraft> w, String status) {
+        if (!StringUtils.hasText(status)) return;
+        switch (status) {
+            case "collecting":
+                w.eq(HealthReportDraft::getParseStatus, ReportCollectService.STATUS_COLLECTING);
+                break;
+            case "completed":
+                w.eq(HealthReportDraft::getParseStatus, ReportCollectService.STATUS_COMPLETED);
+                break;
+            case "failed":
+                w.eq(HealthReportDraft::getParseStatus, ReportCollectService.STATUS_FAILED);
+                break;
+            case "pending":
+                w.eq(HealthReportDraft::getStatus, "pending");
+                break;
+            case "unattributed":
+                w.and(x -> x.isNull(HealthReportDraft::getFamilyId)
+                        .or().isNull(HealthReportDraft::getMemberId));
+                break;
+            default:
+                w.last("1=0");
+        }
+    }
+
+    private LambdaQueryWrapper<HealthReport> reportWrapper(TraceQuery q) {
+        LambdaQueryWrapper<HealthReport> w = new LambdaQueryWrapper<>();
+        // 孤儿:subject_id 或 family_id 为空
+        w.and(x -> x.isNull(HealthReport::getSubjectId).or().isNull(HealthReport::getFamilyId));
+        if (q.userId != null) w.eq(HealthReport::getUserId, q.userId);
+        if (q.familyId != null) w.eq(HealthReport::getFamilyId, q.familyId);
+        if (q.memberId != null) w.eq(HealthReport::getSubjectId, q.memberId);
+        if (StringUtils.hasText(q.fileHash)) w.eq(HealthReport::getFileHash, q.fileHash);
+        if (StringUtils.hasText(q.fileName)) w.like(HealthReport::getFileUrl, q.fileName);
+        if (q.startTime != null) w.ge(HealthReport::getCreatedAt, q.startTime);
+        if (q.endTime != null) w.le(HealthReport::getCreatedAt, q.endTime);
+        if (StringUtils.hasText(q.status)) {
+            switch (q.status) {
+                case "completed":
+                case "unattributed":
+                    break; // 全部孤儿即命中
+                default:
+                    w.last("1=0");
+            }
+        }
+        return w;
+    }
+
+    private LambdaQueryWrapper<DanReportUpload> danWrapper(TraceQuery q) {
+        LambdaQueryWrapper<DanReportUpload> w = new LambdaQueryWrapper<>();
+        w.isNull(DanReportUpload::getDeletedAt);
+        if (q.userId != null) w.eq(DanReportUpload::getUploaderUserId, q.userId);
+        if (q.familyId != null) w.eq(DanReportUpload::getFamilyId, q.familyId);
+        if (q.memberId != null) w.eq(DanReportUpload::getFamilyMemberId, q.memberId);
+        if (StringUtils.hasText(q.fileName)) w.like(DanReportUpload::getFileName, q.fileName);
+        if (q.startTime != null) w.ge(DanReportUpload::getUploadedAt, q.startTime);
+        if (q.endTime != null) w.le(DanReportUpload::getUploadedAt, q.endTime);
+        if (StringUtils.hasText(q.status)) {
+            switch (q.status) {
+                case "collecting":
+                case "pending":
+                    w.eq(DanReportUpload::getParseStatus, DanReportUpload.PARSE_PENDING);
+                    break;
+                case "completed":
+                    w.eq(DanReportUpload::getParseStatus, DanReportUpload.PARSE_SUCCESS);
+                    break;
+                case "failed":
+                    w.eq(DanReportUpload::getParseStatus, DanReportUpload.PARSE_FAILED);
+                    break;
+                case "unattributed":
+                    w.isNull(DanReportUpload::getFamilyMemberId);
+                    break;
+                default:
+                    w.last("1=0");
+            }
+        }
+        return w;
+    }
+
+    private LambdaQueryWrapper<ReportUnknownUpload> unknownWrapper(TraceQuery q) {
+        LambdaQueryWrapper<ReportUnknownUpload> w = new LambdaQueryWrapper<>();
+        if (StringUtils.hasText(q.fileHash)) w.eq(ReportUnknownUpload::getFileHash, q.fileHash);
+        if (StringUtils.hasText(q.fileName)) w.like(ReportUnknownUpload::getFileUrl, q.fileName);
+        if (q.startTime != null) w.ge(ReportUnknownUpload::getUploadedAt, q.startTime);
+        if (q.endTime != null) w.le(ReportUnknownUpload::getUploadedAt, q.endTime);
+        if (StringUtils.hasText(q.status)) {
+            switch (q.status) {
+                case "unknown":
+                case "unattributed":
+                    break;
+                default:
+                    w.last("1=0");
+            }
+        }
+        return w;
+    }
+
+    // =============================================================
+    // 工具
+    // =============================================================
+
+    private List<Map<String, Object>> toDraftNodes(List<HealthReportDraft> rows) {
+        List<Map<String, Object>> out = new ArrayList<>();
+        for (HealthReportDraft d : rows) out.add(draftNode(d));
+        return out;
+    }
+
+    private List<Map<String, Object>> toReportNodes(List<HealthReport> rows) {
+        List<Map<String, Object>> out = new ArrayList<>();
+        for (HealthReport r : rows) out.add(reportNode(r));
+        return out;
+    }
+
+    private List<Map<String, Object>> toDanNodes(List<DanReportUpload> rows) {
+        List<Map<String, Object>> out = new ArrayList<>();
+        for (DanReportUpload u : rows) out.add(danNode(u));
+        return out;
+    }
+
+    private List<Map<String, Object>> toUnknownNodes(List<ReportUnknownUpload> rows) {
+        List<Map<String, Object>> out = new ArrayList<>();
+        for (ReportUnknownUpload u : rows) out.add(unknownNode(u));
+        return out;
+    }
+
+    private String normalizeDanStatus(String s) {
+        if (s == null) return "pending";
+        if (DanReportUpload.PARSE_SUCCESS.equals(s)) return "completed";
+        return s; // pending / failed 原样
+    }
+
+    private String[] splitTraceId(String traceId) {
+        if (traceId == null) return null;
+        int idx = traceId.indexOf(':');
+        if (idx <= 0) return null;
+        return new String[]{traceId.substring(0, idx), traceId.substring(idx + 1)};
+    }
+
+    private String resolveLocalPath(String fileUrl) {
+        if (fileUrl == null || fileUrl.isEmpty()) return null;
+        File direct = new File(fileUrl);
+        if (direct.exists()) return direct.getAbsolutePath();
+        try {
+            return storageService.getFilePath(fileUrl);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    private String fileNameFromUrl(String url) {
+        if (!StringUtils.hasText(url)) return null;
+        String trimmed = url;
+        int q = trimmed.indexOf('?');
+        if (q >= 0) trimmed = trimmed.substring(0, q);
+        int slash = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
+        return slash >= 0 ? trimmed.substring(slash + 1) : trimmed;
+    }
+
+    private String preview(String s) {
+        if (s == null) return null;
+        return s.length() > PAYLOAD_PREVIEW_LEN ? s.substring(0, PAYLOAD_PREVIEW_LEN) + "...(已截断)" : s;
+    }
+
+    private boolean hasText(String s) {
+        return s != null && !s.trim().isEmpty();
+    }
+
+    private JsonNode parseJson(String json) {
+        if (!hasText(json)) return null;
+        try {
+            return objectMapper.readTree(json);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    private int arraySize(JsonNode node, String field) {
+        if (node == null || !node.isObject()) return 0;
+        JsonNode arr = node.get(field);
+        return arr != null && arr.isArray() ? arr.size() : 0;
+    }
+
+    private Date startOfDay(Date d) {
+        Calendar c = Calendar.getInstance();
+        c.setTime(d);
+        c.set(Calendar.HOUR_OF_DAY, 0);
+        c.set(Calendar.MINUTE, 0);
+        c.set(Calendar.SECOND, 0);
+        c.set(Calendar.MILLISECOND, 0);
+        return c.getTime();
+    }
+
+    private String normalizeDay(Object v) {
+        if (v == null) return null;
+        String s = String.valueOf(v);
+        return s.length() >= 10 ? s.substring(0, 10) : s;
+    }
+
+    private static String strParam(Map<String, Object> params, String key) {
+        if (params == null || params.get(key) == null) return null;
+        Object v = params.get(key);
+        String s = v instanceof String ? (String) v : String.valueOf(v);
+        return s.trim().isEmpty() ? null : s.trim();
+    }
+
+    private static Long longParam(Map<String, Object> params, String key) {
+        Object v = params == null ? null : params.get(key);
+        if (v == null) return null;
+        if (v instanceof Number) return ((Number) v).longValue();
+        try {
+            return Long.parseLong(String.valueOf(v).trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+
+    private static int intParam(Map<String, Object> params, String key, int def) {
+        Long v = longParam(params, key);
+        return v != null ? v.intValue() : def;
+    }
+
+    private static Date dateParam(Map<String, Object> params, String key) {
+        String s = strParam(params, key);
+        if (s == null) return null;
+        String[] patterns = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd"};
+        for (String p : patterns) {
+            try {
+                SimpleDateFormat fmt = new SimpleDateFormat(p);
+                fmt.setLenient(false);
+                return fmt.parse(s);
+            } catch (ParseException ignored) {
+            }
+        }
+        return null;
+    }
+
+    private static long toLong(Object v) {
+        if (v == null) return 0;
+        if (v instanceof Number) return ((Number) v).longValue();
+        try {
+            return Long.parseLong(String.valueOf(v).trim());
+        } catch (NumberFormatException e) {
+            return 0;
+        }
+    }
+}

+ 49 - 0
cfc-web/src/api/reportTrace.js

@@ -0,0 +1,49 @@
+import request from '@/utils/request'
+
+// ========== 报告处理链路追踪 / 归因 ==========
+export function listReportTrace(params) {
+  return request({
+    url: '/api/admin/report-trace/list',
+    method: 'post',
+    data: params
+  })
+}
+
+export function getReportTraceDetail(traceId) {
+  return request({
+    url: '/api/admin/report-trace/detail',
+    method: 'post',
+    data: { traceId }
+  })
+}
+
+export function retryReportTrace(traceId) {
+  return request({
+    url: '/api/admin/report-trace/retry',
+    method: 'post',
+    data: { traceId }
+  })
+}
+
+export function bindReportTraceMember(reportId, memberId) {
+  return request({
+    url: '/api/admin/report-trace/bind-member',
+    method: 'post',
+    data: { reportId, memberId }
+  })
+}
+
+export function listUnknownReportClusters(params) {
+  return request({
+    url: '/api/admin/report-trace/unknown-list',
+    method: 'post',
+    data: params || {}
+  })
+}
+
+export function getReportTraceStats() {
+  return request({
+    url: '/api/admin/report-trace/stats',
+    method: 'post'
+  })
+}

+ 6 - 0
cfc-web/src/router/index.js

@@ -905,6 +905,12 @@ const routes = [
         component: () => import('@/views/admin/ReportAutoLearn.vue'),
         meta: { title: '报告自学习', perm: 'config:report-parser' }
       },
+      {
+        path: 'report-trace',
+        name: 'ReportTrace',
+        component: () => import('@/views/admin/ReportTrace.vue'),
+        meta: { title: '报告链路追踪', perm: 'config:report-parser' }
+      },
       // ========== LangGraph AI 服务管理 ==========
       {
         path: 'langgraph-admin',

+ 2 - 1
cfc-web/src/views/Layout.vue

@@ -269,6 +269,7 @@ export default {
             { path: '/report-types', label: '报告类型管理', icon: 'el-icon-collection', perm: 'config:report-parser' },
             { path: '/report-parser-import', label: '解析器导入', icon: 'el-icon-upload2', perm: 'config:report-parser' },
             { path: '/report-unknown-clusters', label: '未知报告审核', icon: 'el-icon-question', perm: 'config:report-parser' },
+            { path: '/report-trace', label: '报告链路追踪', icon: 'el-icon-s-operation', perm: 'config:report-parser' },
             { path: '/report-auto-learn', label: '报告自学习', icon: 'el-icon-magic-stick', perm: 'config:report-parser' },
             { path: '/report-collector-trainer', label: '报告采集训练', icon: 'el-icon-film', perm: 'config:report-parser' },
             { path: '/report-template', label: '报告模板管理', icon: 'el-icon-setting', perm: 'config:report-parser' },
@@ -364,7 +365,7 @@ export default {
       ],
       // 需要保持列表状态的页面组件 name(进入编辑/详情返回时保留筛选、页码、勾选)。
       // 接入方式:把组件 name 加进数组,并在该页面混入 ListStateMixin(见 src/mixins/ListStateMixin.js)
-      cachedPages: ['Activities', 'ActivityReview', 'ArticleAudit', 'ArticleManage', 'AssessmentAssign', 'AssessmentOrders', 'AssessmentProducts', 'ButlerAssignments', 'ButlerAudit', 'CfValueManage', 'Children', 'CommentReview', 'CouponGrantLog', 'CouponManagement', 'DanExecution', 'DanSettlement', 'DataSourceConfig', 'DiscountRuleManagement', 'EcomSupplierManage', 'EmotionAlertManage', 'EnergyRuleManagement', 'Families', 'FamilyEarningsWithdraw', 'FileManage', 'Foods', 'GatesManage', 'GrowthTaskManagement', 'GuideAudit', 'GuideFamilyTask', 'HealthPlanManage', 'HealthReports', 'HomeBannerManage', 'IndicatorCorrelations', 'IndicatorMappings', 'InventoryManage', 'KnowledgeManage', 'MembershipCenter', 'NutritionistAudit', 'NutritionProducts', 'OperationLogs', 'OrchestrationFlow', 'OrderManage', 'PackageAudit', 'PendingRefund', 'PendingRefundAudit', 'Points', 'PointsLog', 'ProductManage', 'ProductPpointManage', 'ProductProfitRate', 'ProfileManagement', 'PromotionManagement', 'ProxyReport', 'ProxyReportUpload', 'PurchaseManagement', 'RecommendationRules', 'ReportManagement', 'ReportParseStatus', 'Rewards', 'SubscriptionManagement', 'SupplierProductManage', 'SupplyManageList', 'SupplySystemList', 'SysConfig', 'SystemPromptManagement', 'Tasks', 'TaskTemplates', 'TeacherConsult', 'TeacherOrders', 'Users', 'VectorKnowledgeBase', 'VendorAudit', 'VirtualTeamList', 'Wishes', 'WithdrawAudit'],
+      cachedPages: ['Activities', 'ActivityReview', 'ArticleAudit', 'ArticleManage', 'AssessmentAssign', 'AssessmentOrders', 'AssessmentProducts', 'ButlerAssignments', 'ButlerAudit', 'CfValueManage', 'Children', 'CommentReview', 'CouponGrantLog', 'CouponManagement', 'DanExecution', 'DanSettlement', 'DataSourceConfig', 'DiscountRuleManagement', 'EcomSupplierManage', 'EmotionAlertManage', 'EnergyRuleManagement', 'Families', 'FamilyEarningsWithdraw', 'FileManage', 'Foods', 'GatesManage', 'GrowthTaskManagement', 'GuideAudit', 'GuideFamilyTask', 'HealthPlanManage', 'HealthReports', 'HomeBannerManage', 'IndicatorCorrelations', 'IndicatorMappings', 'InventoryManage', 'KnowledgeManage', 'MembershipCenter', 'NutritionistAudit', 'NutritionProducts', 'OperationLogs', 'OrchestrationFlow', 'OrderManage', 'PackageAudit', 'PendingRefund', 'PendingRefundAudit', 'Points', 'PointsLog', 'ProductManage', 'ProductPpointManage', 'ProductProfitRate', 'ProfileManagement', 'PromotionManagement', 'ProxyReport', 'ProxyReportUpload', 'PurchaseManagement', 'RecommendationRules', 'ReportManagement', 'ReportParseStatus', 'ReportTrace', 'Rewards', 'SubscriptionManagement', 'SupplierProductManage', 'SupplyManageList', 'SupplySystemList', 'SysConfig', 'SystemPromptManagement', 'Tasks', 'TaskTemplates', 'TeacherConsult', 'TeacherOrders', 'Users', 'VectorKnowledgeBase', 'VendorAudit', 'VirtualTeamList', 'Wishes', 'WithdrawAudit'],
       menuLoadFailed: false,
       profileDialogVisible: false,
       passwordDialogVisible: false,

+ 801 - 0
cfc-web/src/views/admin/ReportTrace.vue

@@ -0,0 +1,801 @@
+<template>
+  <div class="report-trace admin-page">
+    <!-- ===== 概览统计 ===== -->
+    <el-row :gutter="12" class="stats-row">
+      <el-col :xs="12" :sm="12" :md="6" class="stats-col">
+        <StatCard label="上传总数" :value="stats.total" icon="el-icon-upload" color="primary" />
+      </el-col>
+      <el-col :xs="12" :sm="12" :md="6" class="stats-col">
+        <StatCard label="解析失败" :value="stats.failed" icon="el-icon-circle-close" color="danger" />
+      </el-col>
+      <el-col :xs="12" :sm="12" :md="6" class="stats-col">
+        <StatCard label="采集中" :value="stats.collecting" icon="el-icon-loading" color="warning" />
+      </el-col>
+      <el-col :xs="12" :sm="12" :md="6" class="stats-col">
+        <StatCard label="未归因" :value="stats.unattributed" icon="el-icon-warning-outline" color="warning" />
+      </el-col>
+    </el-row>
+
+    <!-- ===== 近 7 天趋势 ===== -->
+    <div class="trend-card" v-if="stats.trend7Days && stats.trend7Days.length">
+      <div class="trend-title">近 7 天上传趋势</div>
+      <div class="trend-bars">
+        <div v-for="d in stats.trend7Days" :key="d.date" class="trend-item">
+          <div class="trend-bar-wrap">
+            <div class="trend-bar" :style="{ height: trendBarHeight(d.total) }" :title="d.date + ' 上传 ' + d.total"></div>
+          </div>
+          <span class="trend-value">{{ d.total }}</span>
+          <span class="trend-date">{{ d.date.slice(5) }}</span>
+        </div>
+      </div>
+    </div>
+
+    <!-- ===== 主列表 ===== -->
+    <el-card class="main-card">
+      <PageHeader slot="header" title="报告链路追踪" subtitle="四表统一视图:上传 → 解析服务 → 解析数据 → 成员归因" />
+
+      <!-- 筛选区 -->
+      <div class="filter-bar">
+        <el-input v-model="query.userId" placeholder="用户ID" clearable class="filter-input-100" @keyup.enter.native="handleSearch" />
+        <el-input v-model="query.familyId" placeholder="家庭ID" clearable class="filter-input-100" @keyup.enter.native="handleSearch" />
+        <el-input v-model="query.memberId" placeholder="成员ID" clearable class="filter-input-100" @keyup.enter.native="handleSearch" />
+        <el-input v-model="query.fileName" placeholder="文件名(模糊)" clearable class="filter-input-180" @keyup.enter.native="handleSearch" />
+        <el-input v-model="query.fileHash" placeholder="文件Hash" clearable class="filter-input-180" @keyup.enter.native="handleSearch" />
+        <el-select v-model="query.sourceType" placeholder="来源类型" clearable class="filter-select-140">
+          <el-option label="全部来源" value="" />
+          <el-option label="健康草稿" value="health_draft" />
+          <el-option label="健康报告(孤儿)" value="health_report" />
+          <el-option label="DAN测评" value="dan_upload" />
+          <el-option label="未知上传" value="unknown" />
+        </el-select>
+        <el-select v-model="query.status" placeholder="解析状态" clearable class="filter-select-140">
+          <el-option label="全部状态" value="" />
+          <el-option label="采集中" value="collecting" />
+          <el-option label="已完成" value="completed" />
+          <el-option label="失败" value="failed" />
+          <el-option label="待确认" value="pending" />
+          <el-option label="未归因" value="unattributed" />
+          <el-option label="未知类型" value="unknown" />
+        </el-select>
+        <el-date-picker
+          v-model="dateRange"
+          type="daterange"
+          range-separator="至"
+          start-placeholder="开始日期"
+          end-placeholder="结束日期"
+          value-format="yyyy-MM-dd"
+          class="filter-date-range"
+        />
+        <el-button type="primary" @click="handleSearch">查询</el-button>
+        <el-button @click="handleReset">重置</el-button>
+      </div>
+
+      <div class="adm-table-wrap">
+        <el-table :data="list" v-loading="loading" border stripe height="100%">
+          <el-table-column label="上传时间" width="165">
+            <template slot-scope="{ row }">{{ formatTime(row.uploadedAt) }}</template>
+          </el-table-column>
+          <el-table-column label="来源" width="120">
+            <template slot-scope="{ row }">
+              <StatusTag :type="sourceTypeTag(row.sourceType)" :text="sourceTypeText(row.sourceType)" size="small" />
+            </template>
+          </el-table-column>
+          <el-table-column label="上传人" width="100">
+            <template slot-scope="{ row }">{{ row.uploaderName || row.uploaderUserId || '-' }}</template>
+          </el-table-column>
+          <el-table-column label="文件名" min-width="180" show-overflow-tooltip>
+            <template slot-scope="{ row }">
+              <el-link v-if="isHttpUrl(row.fileUrl)" type="primary" :href="row.fileUrl" target="_blank" :underline="false">{{ row.fileName || '(无文件名)' }}</el-link>
+              <span v-else>{{ row.fileName || '(无文件名)' }}</span>
+            </template>
+          </el-table-column>
+          <el-table-column label="解析服务" width="130">
+            <template slot-scope="{ row }">{{ parseServiceText(row.parseService) }}</template>
+          </el-table-column>
+          <el-table-column label="解析状态" width="100">
+            <template slot-scope="{ row }">
+              <StatusTag :type="parseStatusType(row.parseStatus)" :text="parseStatusText(row.parseStatus)" size="small" />
+            </template>
+          </el-table-column>
+          <el-table-column label="是否归因" width="150">
+            <template slot-scope="{ row }">
+              <template v-if="row.attributed">
+                <StatusTag type="success" size="small" text="✓ 已归因" />
+              </template>
+              <template v-else>
+                <StatusTag type="danger" size="small" text="✗ 未归因" />
+                <div class="attr-reason">{{ attrReasonText(row.attrReason) }}</div>
+              </template>
+            </template>
+          </el-table-column>
+          <el-table-column label="落地报告ID" width="110">
+            <template slot-scope="{ row }">
+              <span v-if="row.landedReportId">{{ row.landedReportId }}</span>
+              <span v-else class="text-muted">-</span>
+            </template>
+          </el-table-column>
+          <el-table-column label="数据摘要" min-width="200">
+            <template slot-scope="{ row }">{{ summaryText(row) }}</template>
+          </el-table-column>
+          <el-table-column label="操作" width="210" fixed="right">
+            <template slot-scope="{ row }">
+              <el-button size="mini" type="primary" @click="openDetail(row)">详情</el-button>
+              <el-button v-if="canRetry(row)" size="mini" type="warning" @click="handleRetry(row)">重试</el-button>
+              <el-button v-if="canBind(row)" size="mini" type="success" @click="openBind(row)">归因</el-button>
+            </template>
+          </el-table-column>
+        </el-table>
+      </div>
+
+      <el-pagination
+        v-if="total > 0"
+        @current-change="onPageChange"
+        :current-page="page"
+        :page-size="size"
+        :total="total"
+        layout="total, prev, pager, next"
+        class="pagination-wrap"
+      />
+    </el-card>
+
+    <!-- ===== 未知报告聚类 ===== -->
+    <el-card class="unknown-card">
+      <PageHeader slot="header" title="未知报告聚类" subtitle="辅助定位「为什么识别不了」(展示最近 10 条)" />
+      <el-table :data="clusters" v-loading="clusterLoading" border stripe>
+        <el-table-column prop="clusterId" label="聚类ID" width="90" />
+        <el-table-column prop="clusterKey" label="聚类键" min-width="200" show-overflow-tooltip />
+        <el-table-column prop="reportCount" label="报告数" width="80" />
+        <el-table-column label="状态" width="110">
+          <template slot-scope="{ row }">
+            <StatusTag :type="clusterStatusType(row.status)" :text="clusterStatusText(row.status)" size="small" />
+          </template>
+        </el-table-column>
+        <el-table-column prop="generatedTypeId" label="生成类型" width="120">
+          <template slot-scope="{ row }">{{ row.generatedTypeId || '-' }}</template>
+        </el-table-column>
+        <el-table-column label="更新时间" width="165">
+          <template slot-scope="{ row }">{{ formatTime(row.updatedAt) }}</template>
+        </el-table-column>
+      </el-table>
+    </el-card>
+
+    <!-- ===== 详情抽屉 ===== -->
+    <el-drawer
+      :title="'上传链路详情 · ' + (detail && detail.traceId)"
+      :visible.sync="drawerVisible"
+      size="620px"
+      direction="rtl"
+      :destroy-on-close="true"
+    >
+      <div v-loading="detailLoading" class="drawer-body">
+        <template v-if="detail">
+          <!-- 链路时间线 -->
+          <el-timeline class="detail-timeline">
+            <el-timeline-item timestamp="上传" :color="timelineColor('upload')" :hollow="false">
+              <div class="tl-title">{{ sourceTypeText(detail.sourceType) }}</div>
+              <div class="tl-text">上传人:{{ detail.uploaderName || detail.uploaderUserId || '-' }} · 文件:{{ detail.fileName || '-' }}</div>
+            </el-timeline-item>
+            <el-timeline-item timestamp="解析" :color="timelineColor('parse')" :hollow="false">
+              <div class="tl-title">{{ parseServiceText(detail.parseService) }}<span v-if="detail.parseMethod" class="tl-sub">({{ detail.parseMethod }})</span></div>
+              <div class="tl-text" v-if="detail.parseError">失败原因:{{ detail.parseError }}</div>
+            </el-timeline-item>
+            <el-timeline-item timestamp="解析结果" :color="timelineColor('result')" :hollow="false">
+              <div class="tl-text">{{ summaryText(detail) }}</div>
+            </el-timeline-item>
+            <el-timeline-item timestamp="落地" :color="detail.landedReportId ? '#67c23a' : '#f56c6c'" :hollow="false">
+              <template v-if="detail.landedReportId">
+                <div class="tl-text">{{ detail.landedTable === 'dan_assessment_results' ? 'DAN测评结果' : '健康报告' }} #{{ detail.landedReportId }}</div>
+              </template>
+              <div v-else class="tl-text">未落地(未生成可见报告)</div>
+            </el-timeline-item>
+            <el-timeline-item timestamp="成员归属" :color="detail.attributed ? '#67c23a' : '#f56c6c'" :hollow="false">
+              <template v-if="detail.attributed">
+                <div class="tl-text">已归属:{{ detail.memberName || detail.memberId || '-' }}(家庭 {{ detail.familyId || '-' }})</div>
+              </template>
+              <template v-else>
+                <div class="tl-text">未落到成员:{{ attrReasonText(detail.attrReason) }}</div>
+                <el-button v-if="canBind(detail)" size="mini" type="success" class="bind-btn" @click="openBind(detail)">手动归因</el-button>
+              </template>
+            </el-timeline-item>
+          </el-timeline>
+
+          <!-- 关键字段 -->
+          <el-descriptions :column="2" border size="small" class="detail-desc">
+            <el-descriptions-item label="traceId">{{ detail.traceId }}</el-descriptions-item>
+            <el-descriptions-item label="来源类型">{{ sourceTypeText(detail.sourceType) }}</el-descriptions-item>
+            <el-descriptions-item label="用户ID">{{ detail.uploaderUserId || '-' }}</el-descriptions-item>
+            <el-descriptions-item label="家庭ID">{{ detail.familyId || '-' }}</el-descriptions-item>
+            <el-descriptions-item label="成员ID">{{ detail.memberId || '-' }}</el-descriptions-item>
+            <el-descriptions-item label="成员名">{{ detail.memberName || '-' }}</el-descriptions-item>
+            <el-descriptions-item label="报告类型">{{ detail.selectedType || '-' }}</el-descriptions-item>
+            <el-descriptions-item label="文件Hash">{{ detail.fileHash || '-' }}</el-descriptions-item>
+            <el-descriptions-item label="解析状态">
+              <StatusTag :type="parseStatusType(detail.parseStatus)" :text="parseStatusText(detail.parseStatus)" size="small" />
+            </el-descriptions-item>
+            <el-descriptions-item label="尝试次数">{{ detail.parseAttempt != null ? detail.parseAttempt : '-' }}</el-descriptions-item>
+            <el-descriptions-item label="上传时间">{{ formatTime(detail.uploadedAt) }}</el-descriptions-item>
+            <el-descriptions-item label="更新时间">{{ formatTime(detail.updatedAt) }}</el-descriptions-item>
+          </el-descriptions>
+
+          <!-- 数据计数 -->
+          <div v-if="detail.counts" class="counts-row">
+            <el-tag v-if="detail.counts.overallScore != null" size="small" type="success">综合分 {{ detail.counts.overallScore }}</el-tag>
+            <el-tag v-if="detail.counts.indicatorCount != null" size="small" type="info">指标 {{ detail.counts.indicatorCount }}</el-tag>
+            <el-tag v-if="detail.counts.gutFloraCount != null" size="small" type="info">菌群 {{ detail.counts.gutFloraCount }}</el-tag>
+            <el-tag v-if="detail.counts.diseaseRiskCount != null" size="small" type="info">风险 {{ detail.counts.diseaseRiskCount }}</el-tag>
+            <el-tag v-if="detail.counts.itemCount != null" size="small" type="info">条目 {{ detail.counts.itemCount }}</el-tag>
+          </div>
+
+          <!-- 落地报告 -->
+          <div v-if="detail.landedReport" class="detail-section">
+            <SectionTitle title="落地报告" />
+            <el-descriptions :column="2" border size="small">
+              <el-descriptions-item label="报告ID">{{ detail.landedReport.reportId != null ? detail.landedReport.reportId : detail.landedReport.resultId }}</el-descriptions-item>
+              <el-descriptions-item label="类型">{{ detail.landedReport.reportType || detail.landedReport.dimension || '-' }}</el-descriptions-item>
+              <el-descriptions-item label="对象">{{ detail.landedReport.personName || detail.landedReport.familyMemberName || '-' }}</el-descriptions-item>
+              <el-descriptions-item label="综合分">{{ detail.landedReport.overallScore != null ? detail.landedReport.overallScore : '-' }}</el-descriptions-item>
+            </el-descriptions>
+          </div>
+
+          <!-- 溯源草稿 -->
+          <div v-if="detail.sourceDraft" class="detail-section">
+            <SectionTitle title="溯源草稿" />
+            <el-descriptions :column="2" border size="small">
+              <el-descriptions-item label="草稿ID">{{ detail.sourceDraft.draftId }}</el-descriptions-item>
+              <el-descriptions-item label="解析方式">{{ detail.sourceDraft.parseMethod || '-' }}</el-descriptions-item>
+              <el-descriptions-item label="尝试次数">{{ detail.sourceDraft.parseAttempt != null ? detail.sourceDraft.parseAttempt : '-' }}</el-descriptions-item>
+              <el-descriptions-item label="校验结果">{{ detail.sourceDraft.collectValidation ? '通过' : '-' }}</el-descriptions-item>
+            </el-descriptions>
+            <div v-if="detail.sourceDraft.parseError" class="parse-error">{{ detail.sourceDraft.parseError }}</div>
+          </div>
+
+          <!-- 原始字段 -->
+          <div v-if="Object.keys(detail.sourceRaw || {}).length" class="detail-section">
+            <SectionTitle title="原始字段" />
+            <pre class="detail-pre">{{ formatJson(detail.sourceRaw) }}</pre>
+          </div>
+
+          <!-- 解析数据预览 -->
+          <div v-if="detail.payloadPreview || detail.parsedItemsPreview || detail.llmResultPreview" class="detail-section">
+            <SectionTitle title="解析数据预览" />
+            <pre class="detail-pre">{{ detail.payloadPreview || detail.parsedItemsPreview || detail.llmResultPreview }}</pre>
+          </div>
+
+          <!-- 未知聚类信息 -->
+          <div v-if="detail.cluster" class="detail-section">
+            <SectionTitle title="所属聚类" />
+            <el-descriptions :column="2" border size="small">
+              <el-descriptions-item label="聚类键">{{ detail.cluster.clusterKey }}</el-descriptions-item>
+              <el-descriptions-item label="报告数">{{ detail.cluster.reportCount }}</el-descriptions-item>
+              <el-descriptions-item label="状态">{{ detail.cluster.status || '-' }}</el-descriptions-item>
+              <el-descriptions-item label="生成类型">{{ detail.cluster.generatedTypeId || '-' }}</el-descriptions-item>
+            </el-descriptions>
+          </div>
+        </template>
+      </div>
+    </el-drawer>
+
+    <!-- ===== 手动归因弹窗 ===== -->
+    <el-dialog title="手动归因到家庭成员" :visible.sync="bindVisible" width="480px" :close-on-click-modal="false">
+      <el-alert
+        v-if="bindTarget && bindTarget.familyId"
+        type="info"
+        :closable="false"
+        show-icon
+        title="该报告已带家庭,仅需在家庭成员中选择归属对象"
+        class="bind-alert"
+      />
+      <el-alert
+        v-else
+        type="warning"
+        :closable="false"
+        show-icon
+        title="该报告未带家庭,归因后将回填所选成员的家庭"
+        class="bind-alert"
+      />
+      <el-form label-width="90px">
+        <el-form-item label="报告ID">
+          <span>{{ bindTarget && (bindTarget.sourceId != null ? bindTarget.sourceId : bindTarget.landedReportId) }}</span>
+        </el-form-item>
+        <el-form-item label="归属家庭">
+          <el-select
+            v-model="bindFamilyId"
+            placeholder="请选择家庭"
+            filterable
+            clearable
+            :disabled="!!(bindTarget && bindTarget.familyId)"
+            class="form-full"
+            @change="onBindFamilyChange"
+          >
+            <el-option v-for="f in families" :key="f.id" :label="f.name" :value="f.id" />
+          </el-select>
+        </el-form-item>
+        <el-form-item label="归属成员">
+          <el-select v-model="bindMemberId" placeholder="请选择成员" filterable clearable class="form-full">
+            <el-option v-for="m in bindMembers" :key="m.memberId" :label="m.nickname || m.userId" :value="m.memberId" />
+          </el-select>
+        </el-form-item>
+      </el-form>
+      <span slot="footer">
+        <el-button @click="bindVisible = false">取消</el-button>
+        <el-button type="primary" :loading="bindSaving" :disabled="!bindMemberId" @click="doBind">确认归因</el-button>
+      </span>
+    </el-dialog>
+  </div>
+</template>
+
+<script>
+import { listReportTrace, getReportTraceDetail, retryReportTrace, bindReportTraceMember, listUnknownReportClusters, getReportTraceStats } from '@/api/reportTrace'
+import { getFamilyList, getFamilyMembers } from '@/api/admin'
+import ListStateMixin from '@/mixins/ListStateMixin'
+
+const SOURCE_TYPE_MAP = {
+  health_draft: { label: '健康草稿', tag: 'primary' },
+  health_report: { label: '健康报告', tag: 'info' },
+  dan_upload: { label: 'DAN测评', tag: 'primary' },
+  unknown: { label: '未知上传', tag: 'warning' }
+}
+
+const PARSE_STATUS_MAP = {
+  collecting: { label: '采集中', tag: 'primary' },
+  completed: { label: '已完成', tag: 'success' },
+  confirmed: { label: '已确认', tag: 'success' },
+  failed: { label: '失败', tag: 'danger' },
+  pending: { label: '待确认', tag: 'warning' },
+  unknown: { label: '未知', tag: 'warning' }
+}
+
+const ATTR_REASON_MAP = {
+  familyId_null: '上传未带家庭',
+  name_no_match: '姓名未匹配到成员',
+  member_not_selected: '未选择归属成员',
+  unknown_type: '未知类型未识别'
+}
+
+const PARSE_SERVICE_MAP = {
+  fingerprint_script: '指纹脚本',
+  langgraph_script: 'LangGraph脚本',
+  langgraph_detect: 'LangGraph识别',
+  opencode: 'opencode兜底',
+  dan_java: 'DAN解析器',
+  unknown_llm: '未知LLM',
+  legacy: '历史导入',
+  pending: '待解析'
+}
+
+export default {
+  name: 'ReportTrace',
+  mixins: [ListStateMixin],
+  data() {
+    return {
+      list: [],
+      loading: false,
+      page: 1,
+      size: 20,
+      total: 0,
+      query: {
+        userId: '',
+        familyId: '',
+        memberId: '',
+        fileName: '',
+        fileHash: '',
+        sourceType: '',
+        status: ''
+      },
+      dateRange: null,
+      stats: {},
+      clusters: [],
+      clusterLoading: false,
+      // 详情
+      drawerVisible: false,
+      detailLoading: false,
+      detail: null,
+      // 归因
+      bindVisible: false,
+      bindSaving: false,
+      bindTarget: null,
+      bindFamilyId: null,
+      bindMemberId: null,
+      families: [],
+      bindMembers: []
+    }
+  },
+  created() {
+    this.loadList()
+    this.loadStats()
+    this.loadClusters()
+  },
+  methods: {
+    async loadList() {
+      this.loading = true
+      try {
+        const params = {
+          page: this.page,
+          size: this.size,
+          userId: this.query.userId,
+          familyId: this.query.familyId,
+          memberId: this.query.memberId,
+          fileName: this.query.fileName,
+          fileHash: this.query.fileHash,
+          sourceType: this.query.sourceType,
+          status: this.query.status
+        }
+        if (this.dateRange && this.dateRange.length === 2) {
+          params.startTime = this.dateRange[0] + ' 00:00:00'
+          params.endTime = this.dateRange[1] + ' 23:59:59'
+        }
+        const res = await listReportTrace(params)
+        const data = res.data || {}
+        this.list = data.records || []
+        this.total = data.total || 0
+      } catch (e) {
+        this.$message.error('加载报告链路列表失败')
+      } finally {
+        this.loading = false
+      }
+    },
+    async loadStats() {
+      try {
+        const res = await getReportTraceStats()
+        this.stats = res.data || {}
+      } catch (e) {
+        this.stats = {}
+      }
+    },
+    async loadClusters() {
+      this.clusterLoading = true
+      try {
+        const res = await listUnknownReportClusters({ page: 1, size: 10 })
+        const data = res.data || {}
+        this.clusters = data.records || []
+      } catch (e) {
+        this.clusters = []
+      } finally {
+        this.clusterLoading = false
+      }
+    },
+    handleSearch() {
+      this.page = 1
+      this.loadList()
+    },
+    handleReset() {
+      this.query = { userId: '', familyId: '', memberId: '', fileName: '', fileHash: '', sourceType: '', status: '' }
+      this.dateRange = null
+      this.page = 1
+      this.loadList()
+    },
+    onPageChange(val) {
+      this.page = val
+      this.loadList()
+    },
+    async openDetail(row) {
+      this.drawerVisible = true
+      this.detailLoading = true
+      this.detail = null
+      try {
+        const res = await getReportTraceDetail(row.traceId)
+        this.detail = res.data || {}
+      } catch (e) {
+        this.$message.error('加载详情失败')
+      } finally {
+        this.detailLoading = false
+      }
+    },
+    canRetry(row) {
+      if (!row) return false
+      if (row.sourceType === 'health_draft') {
+        return row.parseStatus === 'failed' || row.parseStatus === 'collecting'
+      }
+      if (row.sourceType === 'dan_upload') {
+        return row.parseStatus === 'failed' || row.parseStatus === 'pending' || row.parseStatus === 'collecting'
+      }
+      if (row.sourceType === 'unknown') return true
+      return false
+    },
+    canBind(row) {
+      return !!row && row.sourceType === 'health_report' && !row.attributed
+    },
+    async handleRetry(row) {
+      try {
+        await this.$confirm('确认重试该条处理链路?', '提示', { type: 'warning' })
+      } catch (e) {
+        return
+      }
+      try {
+        const res = await retryReportTrace(row.traceId)
+        this.$message.success((res.data && res.data.message) || '已触发重试')
+        this.loadList()
+        this.loadStats()
+      } catch (e) {
+        this.$message.error('重试失败')
+      }
+    },
+    // ==== 归因 ====
+    async openBind(row) {
+      this.bindTarget = row
+      this.bindVisible = true
+      this.bindMemberId = null
+      this.bindSaving = false
+      if (row.familyId != null) {
+        this.bindFamilyId = row.familyId
+        this.bindMembers = []
+        this.loadBindMembers(row.familyId)
+      } else {
+        this.bindFamilyId = null
+        this.bindMembers = []
+      }
+      if (!this.families.length) {
+        try {
+          const res = await getFamilyList({ page: 1, size: 500 })
+          const data = res.data || {}
+          this.families = (Array.isArray(data.records) && data.records) || (Array.isArray(data.list) && data.list) || (Array.isArray(data) ? data : [])
+        } catch (e) {
+          this.$message.error('获取家庭列表失败')
+        }
+      }
+    },
+    onBindFamilyChange(familyId) {
+      this.bindMemberId = null
+      this.bindMembers = []
+      if (familyId) this.loadBindMembers(familyId)
+    },
+    async loadBindMembers(familyId) {
+      try {
+        const res = await getFamilyMembers(familyId)
+        const data = res.data || {}
+        const members = data.members || []
+        this.bindMembers = members.filter(function(m) { return m.memberId != null })
+      } catch (e) {
+        this.bindMembers = []
+        this.$message.error('获取家庭成员失败')
+      }
+    },
+    async doBind() {
+      if (!this.bindMemberId) return
+      const reportId = this.bindTarget && this.bindTarget.sourceId != null ? this.bindTarget.sourceId : (this.bindTarget && this.bindTarget.landedReportId)
+      try {
+        await this.$confirm('确认将该报告归属到所选成员?归属后将刷新该成员的五维能量与食材推荐。', '二次确认', { type: 'warning' })
+      } catch (e) {
+        return
+      }
+      this.bindSaving = true
+      try {
+        const res = await bindReportTraceMember(reportId, this.bindMemberId)
+        this.$message.success((res.data && res.data.message) || '归因成功')
+        this.bindVisible = false
+        this.loadList()
+        this.loadStats()
+        if (this.detail && this.detail.traceId) this.openDetail(this.detail)
+      } catch (e) {
+        this.$message.error('归因失败')
+      } finally {
+        this.bindSaving = false
+      }
+    },
+    // ==== 展示辅助 ====
+    sourceTypeText(v) {
+      const m = SOURCE_TYPE_MAP[v]
+      return m ? m.label : (v || '-')
+    },
+    sourceTypeTag(v) {
+      const m = SOURCE_TYPE_MAP[v]
+      return m ? m.tag : 'info'
+    },
+    parseStatusText(v) {
+      const m = PARSE_STATUS_MAP[v]
+      return m ? m.label : (v || '-')
+    },
+    parseStatusType(v) {
+      const m = PARSE_STATUS_MAP[v]
+      return m ? m.tag : 'info'
+    },
+    parseServiceText(v) {
+      if (!v) return '-'
+      const m = PARSE_SERVICE_MAP[v]
+      return m || v
+    },
+    attrReasonText(v) {
+      if (!v) return ''
+      const m = ATTR_REASON_MAP[v]
+      return m || v
+    },
+    summaryText(row) {
+      if (!row || !row.dataSummary) return '-'
+      const ds = row.dataSummary
+      const parts = []
+      if (ds.overallScore != null) parts.push('分 ' + ds.overallScore)
+      if (ds.indicatorCount != null) parts.push('指标 ' + ds.indicatorCount)
+      if (ds.gutFloraCount != null) parts.push('菌群 ' + ds.gutFloraCount)
+      if (ds.diseaseRiskCount != null) parts.push('风险 ' + ds.diseaseRiskCount)
+      if (ds.itemCount != null) parts.push('条目 ' + ds.itemCount)
+      if (!parts.length) return ds.hasPayload ? '有解析数据' : '无解析数据'
+      return parts.join(' / ')
+    },
+    isHttpUrl(url) {
+      if (!url) return false
+      return url.indexOf('http://') === 0 || url.indexOf('https://') === 0
+    },
+    timelineColor(key) {
+      if (key === 'upload') return '#909399'
+      if (key === 'parse') return '#1677ff'
+      if (key === 'result') return '#722ed1'
+      return '#1677ff'
+    },
+    clusterStatusType(v) {
+      return { collecting: 'info', ready: 'warning', generated: 'success', imported: 'success' }[v] || 'info'
+    },
+    clusterStatusText(v) {
+      return { collecting: '收集', ready: '可生成', generated: '已生成', imported: '已导入' }[v] || (v || '-')
+    },
+    formatJson(v) {
+      if (v === null || v === undefined || v === '') return ''
+      try {
+        if (typeof v === 'string') return JSON.stringify(JSON.parse(v), null, 2)
+        return JSON.stringify(v, null, 2)
+      } catch (e) {
+        return String(v)
+      }
+    },
+    trendBarHeight(total) {
+      if (!this.stats.trend7Days || !this.stats.trend7Days.length) return '4px'
+      const max = this.stats.trend7Days.reduce(function(acc, d) { return Math.max(acc, d.total || 0) }, 1)
+      const h = Math.round(((total || 0) / max) * 72)
+      return Math.max(h, 4) + 'px'
+    }
+  }
+}
+</script>
+
+<style scoped>
+.report-trace {
+  padding: 16px;
+  display: flex;
+  flex-direction: column;
+  gap: 12px;
+}
+.stats-row {
+  flex-shrink: 0;
+}
+.stats-col {
+  margin-bottom: 12px;
+}
+.main-card {
+  flex: 1;
+  display: flex;
+  flex-direction: column;
+}
+.main-card .el-card__body {
+  display: flex;
+  flex-direction: column;
+  flex: 1;
+  min-height: 0;
+}
+.unknown-card {
+  flex-shrink: 0;
+}
+.pagination-wrap {
+  margin-top: 16px;
+  text-align: right;
+  flex-shrink: 0;
+}
+.attr-reason {
+  font-size: 12px;
+  color: #cf1322;
+  margin-top: 2px;
+}
+.filter-bar {
+  margin-bottom: 12px;
+  flex-shrink: 0;
+}
+.trend-card {
+  background: #fff;
+  border: 1px solid #f0f0f0;
+  border-radius: 8px;
+  padding: 12px 16px;
+  flex-shrink: 0;
+}
+.trend-title {
+  font-size: 14px;
+  font-weight: 600;
+  color: #262626;
+  margin-bottom: 10px;
+}
+.trend-bars {
+  display: flex;
+  align-items: flex-end;
+  gap: 16px;
+}
+.trend-item {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  gap: 4px;
+}
+.trend-bar-wrap {
+  height: 72px;
+  display: flex;
+  align-items: flex-end;
+}
+.trend-bar {
+  width: 28px;
+  border-radius: 3px 3px 0 0;
+  background: #1677ff;
+}
+.trend-value {
+  font-size: 12px;
+  color: #595959;
+  font-variant-numeric: tabular-nums;
+}
+.trend-date {
+  font-size: 12px;
+  color: #8c8c8c;
+}
+.drawer-body {
+  padding: 0 4px;
+}
+.detail-timeline {
+  padding-left: 4px;
+  margin-bottom: 20px;
+}
+.tl-title {
+  font-weight: 600;
+  color: #262626;
+}
+.tl-sub {
+  font-weight: 400;
+  color: #8c8c8c;
+}
+.tl-text {
+  font-size: 13px;
+  color: #595959;
+  margin-top: 4px;
+  word-break: break-all;
+}
+.bind-btn {
+  margin-top: 8px;
+}
+.detail-desc {
+  margin-bottom: 12px;
+}
+.counts-row {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 8px;
+  margin: 12px 0;
+}
+.detail-section {
+  margin-top: 16px;
+}
+.detail-pre {
+  max-height: 280px;
+  overflow: auto;
+  background: #fafafa;
+  border: 1px solid #f0f0f0;
+  border-radius: 4px;
+  padding: 10px;
+  font-size: 12px;
+  line-height: 1.5;
+  color: #262626;
+  white-space: pre-wrap;
+  word-break: break-all;
+}
+.parse-error {
+  margin-top: 8px;
+  padding: 8px 10px;
+  background: #fff1f0;
+  border: 1px solid #ffa39e;
+  border-radius: 4px;
+  color: #cf1322;
+  font-size: 12px;
+}
+.bind-alert {
+  margin-bottom: 14px;
+}
+
+/* == C 批内联清理工具类 == */
+.filter-input-100 { width: 100px; }
+.filter-input-180 { width: 180px; }
+.filter-select-140 { width: 140px; }
+.filter-date-range { width: 280px; }
+.form-full { width: 100%; }
+</style>

+ 19 - 0
docs/superpowers/api/API_REFERENCE.md

@@ -1943,6 +1943,25 @@ Web 管理端定义活动海报模板(迁移381 `activity_poster_templates` 
 
 *文档更新:2026-10-23(T15/T16/T17 回归补登记:活动报名、签到与签到审核、管理端签到、家庭关系问卷、名册口径、审核中心统计口径)*
 
+### 4.56 管理端-报告链路追踪(`/api/admin/report-trace/*`)
+
+> 后台「报告链路追踪 / 归因」:四表(`health_report_drafts` / `health_reports` 孤儿 / `dan_report_uploads` / `report_unknown_upload`)统一视图,归一化为 TraceNode(traceId=`sourceType:id`),只读现有表、仅调用既有 Service 公开能力,无新增迁移。设计文档:`docs/superpowers/plans/2026-10-26-report-trace-design.md`。
+
+| 路径 | 说明 |
+|---|---|
+| `POST /api/admin/report-trace/list` | 统一联查列表。入参:`userId`/`familyId`/`memberId`/`fileHash`/`fileName`(模糊)/`sourceType`(health_draft/health_report/dan_upload/unknown,`health`=草稿+报告)/`status`(collecting/completed/failed/pending/unattributed/unknown)/`startTime`/`endTime`/`page`/`size`。返回 `{total, records: TraceNode[]}`,按上传时间倒序内存分页。TraceNode 关键字段:traceId/sourceType/uploaderUserId/uploaderName/familyId/memberId/memberName/fileName/fileUrl/fileHash/selectedType/parseService/parseStatus/parseError/parseMethod/landedReportId/landedTable/attributed/attrReason/dataSummary{overallScore,indicatorCount,gutFloraCount,diseaseRiskCount,itemCount,hasPayload}/uploadedAt/updatedAt/detailApi |
+| `POST /api/admin/report-trace/detail` | 完整链路详情。入参 `traceId`(`sourceType:id`)。返回节点字段 + `sourceRaw`(原始字段,剔除大文本)+ `payloadPreview`/`parsedItemsPreview`/`llmResultPreview`(截断 4000 字符)+ `counts`(指标/菌群/风险/条目计数)+ `collectValidation`/`parseAttempt`/`nextRetryAt` + `landedReport`(落地报告摘要)+ `sourceDraft`(健康报告溯源草稿)/`cluster`(未知聚类) |
+| `POST /api/admin/report-trace/retry` | 按来源路由重试。入参 `traceId`:`health_draft`→`resetForManualRetry`+`submitAsyncCollect`;`dan_upload`→`reparseUpload(id, dimension)`;`unknown`→指纹 `detect` 重识别,识别出已知类型则建草稿重新入链(`createDraft` + `submitAsyncCollect`),仍未知则 `parseReport` 刷新 `llm_result`。需 admin 角色,操作人取 `@RequestAttribute("userId")` |
+| `POST /api/admin/report-trace/bind-member` | 孤儿健康报告手动归因。入参 `reportId`(health_reports.id)+ `memberId`(family_members.id)。仅对 `subject_id` 或 `family_id` 为空的孤儿生效:回填 `family_id`(成员所属家庭)→ `resolveSubjectToMemberId` → `reassignReport`(含五维/食材刷新)。返回 `{reportId, memberId, memberName, familyId, message}` |
+| `POST /api/admin/report-trace/unknown-list` | 未知报告聚类列表。入参 `page`/`size`/`status`/`clusterId`。返回 `{total, records}`,字段 clusterId/clusterKey/reportCount/status/generatedTypeId/commonSignatures/llmTemplate/createdAt/updatedAt |
+| `POST /api/admin/report-trace/stats` | 概览统计。返回 `{bySource{health_draft,health_report,dan_upload,unknown}, failed, collecting, pending, unattributed, total, trend7Days:[{date,draft,report,dan,unknown,total}]}` |
+
+**解析服务标识**:草稿 `parseMethod`(fingerprint_script/langgraph_script/langgraph_detect/opencode)、DAN=`dan_java`、未知=`unknown_llm`、健康报告无可溯源草稿时=`legacy`。
+
+**未归因原因(attrReason)**:`familyId_null`(上传未带家庭)/ `name_no_match`(姓名未匹配到成员)/ `member_not_selected`(未选择归属成员)/ `unknown_type`(未知类型未识别)。
+
+*文档更新:2026-10-26(报告链路追踪 / 归因功能上线,后端 6 接口)*
+
 ---
 
 ## 4.48 组织管理(机构/企业组织)