|
|
@@ -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;
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|