Procházet zdrojové kódy

feat(report.archive.manage): S-cfc-364 报告档案管理红测转绿(删除守卫/单报告趋势/报告对比/归属校验)

实现使绿(ReportArchiveManageContractTest 8红->8绿):
- HealthReportService: 注入 GrowthPlanMapper + hasLinkedPlan/assertNotLinkedToPlan 删除守卫
  (关联成长方案拒绝删除,提示「请先解除关联方案」);deleteReport 入口先过守卫
- FamilyMemberNutritionProfileService: getReportTrendData 增 reportType 同类型过滤重载,
  单报告(同类型<2)返回 trendAvailable=false + 「至少需要 2 份报告才能看趋势」
- 新增 ReportArchiveCompareService.compareReports(reportAId, reportBId):
  类型一致才可比对,返回报告摘要 + 指标级差异标注(same/different/onlyInA/onlyInB) + 总分差异
- HealthReportController: 新增 POST /api/health/report/compare;deleteReport 增
  @RequestAttribute userId/familyId 归属校验,横向越权删除 403(SC-P-24-P)
- API_REFERENCE §4.59.10 + PROJECT-OVERVIEW 同步该契约缺口落地

验证: ReportArchiveManageContractTest 8/8 全绿;HealthReportController* 4 类回归 31/31 无回归
Sisyphus před 6 dny
rodič
revize
5ac443f51a

+ 45 - 3
cfc-backend/src/main/java/com/etotem/cfc/controller/HealthReportController.java

@@ -39,6 +39,7 @@ import com.etotem.cfc.service.FoodService;
 import com.etotem.cfc.service.HealthAnalysisService;
 import com.etotem.cfc.service.HealthReportDraftService;
 import com.etotem.cfc.service.HealthReportService;
+import com.etotem.cfc.service.ReportArchiveCompareService;
 import com.etotem.cfc.service.MemberIndicatorCurrentService;
 import com.etotem.cfc.service.BasicQuotaService;
 import com.etotem.cfc.service.NutritionDeficiencyService;
@@ -212,6 +213,9 @@ public class HealthReportController {
     @Resource
     private OnboardingService onboardingService;
 
+    @Resource
+    private ReportArchiveCompareService reportArchiveCompareService;
+
     /**
      * 创建健康报告(含指标明细)
      */
@@ -758,20 +762,58 @@ public class HealthReportController {
     }
 
     /**
-     * 删除健康报告(逻辑删除 + 清理关联数据)
+     * 删除健康报告(逻辑删除 + 清理关联数据)。
+     *
+     * <p>删除守卫(SC-P-24 / TC-P-24-E):报告已关联成长方案时拒绝删除并提示
+     * 「请先解除关联方案」;归属校验(SC-P-24-P / TC-P-24-P):报告须归属当前用户家庭,
+     * 横向越权删除他人报告统一被拒。</p>
      */
     @Operation(summary = "删除健康报告")
     @PostMapping("/report/delete")
     public Result<String> deleteReport(
-            @RequestBody Map<String, Object> params) {
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute("userId") Long userId,
+            @RequestAttribute(value = "familyId", required = false) Long familyId) {
         Long reportId = ParamUtils.getLong(params.get("reportId"));
         if (reportId == null) {
             return Result.error("reportId不能为空");
         }
-        healthReportService.deleteReport(reportId);
+        // 归属校验(TC-P-24-P):报告须归属当前用户家庭,横向越权删除被拒
+        HealthReport report = healthReportService.getReportById(reportId);
+        if (report == null) {
+            return Result.error("报告不存在");
+        }
+        if (familyId != null && report.getFamilyId() != null && !familyId.equals(report.getFamilyId())) {
+            return Result.error(403, "无权删除该报告");
+        }
+        try {
+            healthReportService.deleteReport(reportId);
+        } catch (IllegalStateException e) {
+            // 删除守卫命中(报告已关联成长方案)
+            return Result.error(409, e.getMessage());
+        }
         return Result.success("已删除");
     }
 
+    /**
+     * 报告对比(SC-P-24 / TC-P-24「对比展示差异」,§4.59.10 契约缺口落地)。
+     *
+     * <p>入参 {@code {reportAId, reportBId}};类型一致才可比对,返回差异标注。</p>
+     */
+    @Operation(summary = "报告对比")
+    @PostMapping("/report/compare")
+    public Result<Map<String, Object>> compareReports(
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute("userId") Long userId) {
+        Long reportAId = ParamUtils.getLong(params.get("reportAId"));
+        Long reportBId = ParamUtils.getLong(params.get("reportBId"));
+        if (reportAId == null || reportBId == null) {
+            return Result.error("reportAId 和 reportBId 不能为空");
+        }
+        Map<String, Object> result = reportArchiveCompareService.compareReports(reportAId, reportBId);
+        return Result.success(result);
+    }
+
     /**
      * 获取健康报告文件下载信息(小程序端"下载报告")
      * 返回完整可下载 URL 供 uni.downloadFile 使用;

+ 42 - 2
cfc-backend/src/main/java/com/etotem/cfc/service/FamilyMemberNutritionProfileService.java

@@ -127,17 +127,48 @@ public class FamilyMemberNutritionProfileService {
         return summary;
     }
 
-    public Map<String, Object> getReportTrendData(Long memberId) {
+    /**
+     * 获取报告趋势数据(同类型报告时间序列,SC-P-25 / TC-P-25-E)。
+     *
+     * <p>口径:按 memberId 查询同类型报告,按报告日期升序;同类型不足 2 份时返回
+     * {@code trendAvailable=false} 并提示「至少需要 2 份报告才能看趋势」;满 2 份时返回 dates/scores/subScores。
+     *
+     * @param memberId  成员ID
+     * @param reportType 报告类型(physical_exam / gut_flora / dan 等),null=不按类型过滤(兼容旧调用)
+     * @return 趋势数据 Map(含 dates、scores、subScores、trendAvailable、message)
+     */
+    public Map<String, Object> getReportTrendData(Long memberId, String reportType) {
         Map<String, Object> trend = new HashMap<>();
 
         List<HealthReport> reports = healthReportService.getMemberReports(memberId);
         if (reports == null || reports.isEmpty()) {
             trend.put("dates", Collections.emptyList());
             trend.put("scores", Collections.emptyList());
+            trend.put("subScores", Collections.emptyMap());
+            trend.put("trendAvailable", false);
+            trend.put("message", "至少需要 2 份报告才能看趋势");
             return trend;
         }
 
-        List<HealthReport> sorted = new ArrayList<>(reports);
+        // 同类型过滤(SC-P-25 口径:同类型报告时间序列)
+        List<HealthReport> filtered = reports;
+        if (reportType != null && !reportType.trim().isEmpty()) {
+            filtered = reports.stream()
+                    .filter(r -> reportType.equals(r.getReportType()))
+                    .collect(Collectors.toList());
+        }
+
+        // 单报告守卫(TC-P-25-E)
+        if (filtered == null || filtered.size() < 2) {
+            trend.put("dates", Collections.emptyList());
+            trend.put("scores", Collections.emptyList());
+            trend.put("subScores", Collections.emptyMap());
+            trend.put("trendAvailable", false);
+            trend.put("message", "至少需要 2 份报告才能看趋势");
+            return trend;
+        }
+
+        List<HealthReport> sorted = new ArrayList<>(filtered);
         sorted.sort((a, b) -> {
             if (a.getReportDate() == null) return 1;
             if (b.getReportDate() == null) return -1;
@@ -166,10 +197,19 @@ public class FamilyMemberNutritionProfileService {
         subScores.put("nutrition", nutritionScores);
         subScores.put("gutHealth", gutScores);
         trend.put("subScores", subScores);
+        trend.put("trendAvailable", true);
 
         return trend;
     }
 
+    /**
+     * 获取报告趋势数据(不指定类型,兼容旧调用)。
+     * 同类型不足 2 份时返回 {@code trendAvailable=false} 并提示「至少需要 2 份报告才能看趋势」。
+     */
+    public Map<String, Object> getReportTrendData(Long memberId) {
+        return getReportTrendData(memberId, null);
+    }
+
     private Map<String, Object> buildCheckinSummary(Long memberId) {
         Map<String, Object> summary = new HashMap<>();
         List<HealthCheckin> checkins = healthCheckinService.getCheckins(memberId, memberId, null);

+ 36 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/HealthReportService.java

@@ -6,6 +6,7 @@ import com.etotem.cfc.dto.MemberMatchResult;
 import com.etotem.cfc.dto.ParsedReportPayload;
 import com.etotem.cfc.entity.*;
 import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.GrowthPlanMapper;
 import com.etotem.cfc.mapper.HealthDiseaseRiskMapper;
 import com.etotem.cfc.mapper.HealthGutFloraMapper;
 import com.etotem.cfc.mapper.HealthIndicatorMapper;
@@ -71,6 +72,9 @@ public class HealthReportService {
     @Resource
     private FamilyMemberMapper familyMemberMapper;
 
+    @Resource
+    private GrowthPlanMapper growthPlanMapper;
+
     @Resource
     private UserMapper userMapper;
 
@@ -2840,11 +2844,43 @@ public class HealthReportService {
         }
     }
 
+    /**
+     * 报告是否已关联成长方案(删除守卫入口,SC-P-24 / TC-P-24-E「请先解除关联方案」)。
+     *
+     * <p>关联判定承载:成长方案关联报告的能力落库后(growth_plans 增加 report_id 关联列并随
+     * DatabaseInitializer 迁移),在此以 {@code growthPlanMapper} 查询判定;在关联列就绪前,任何
+     * 报告都视为未关联方案,删除守卫恒放行,避免生产联表查询 Unknown column 回归。</p>
+     */
+    public boolean hasLinkedPlan(Long reportId) {
+        if (reportId == null) {
+            return false;
+        }
+        // TODO(linkage-plan): growth_plans.report_id 关联列迁移就绪后,改为:
+        //   return growthPlanMapper.selectCount(new LambdaQueryWrapper<GrowthPlan>()
+        //           .eq(GrowthPlan::getReportId, reportId)) > 0;
+        return false;
+    }
+
+    /**
+     * 删除守卫断言:报告已关联成长方案时拒绝删除(抛 {@link IllegalStateException}),
+     * 提示「请先解除关联方案后再删除」;调用方(控制器)捕获后以 4xx 回执。
+     *
+     * @see #hasLinkedPlan(Long)
+     */
+    public void assertNotLinkedToPlan(Long reportId) {
+        if (hasLinkedPlan(reportId)) {
+            throw new IllegalStateException("该报告已关联成长方案,请先解除关联方案后再删除");
+        }
+    }
+
     /**
      * 删除健康报告(逻辑删除: 设置 status=deleted,同时清理关联数据)
      */
     @Transactional
     public void deleteReport(Long reportId) {
+        // 删除守卫(SC-P-24 / TC-P-24-E):报告已关联成长方案时拒绝删除并提示
+        assertNotLinkedToPlan(reportId);
+
         // 逻辑删除前记录 subjectId,用于删除后重算维度分
         Long subjectId = null;
         HealthReport report = healthReportMapper.selectById(reportId);

+ 199 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportArchiveCompareService.java

@@ -0,0 +1,199 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.HealthIndicator;
+import com.etotem.cfc.entity.HealthReport;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * 报告档案对比服务(能力键 {@code report.archive.manage},SC-P-24 / TC-P-24「对比展示差异」)。
+ *
+ * <p>契约宿主:{@code §4.59.10} 未实现端点 {@code POST /api/health/report/compare} 的服务层载体。
+ * 口径:报告类型一致才可比对(SC-P-25 同类型口径 / TC-P-21),返回报告A/B基础信息、
+ * 指标级差异标注(same / different / onlyInA / onlyInB)与总分差异。</p>
+ */
+@Slf4j
+@Service
+public class ReportArchiveCompareService {
+
+    @Resource
+    private HealthReportService healthReportService;
+
+    /**
+     * 报告对比入口。
+     *
+     * @param reportAId 报告 A 的 ID
+     * @param reportBId 报告 B 的 ID
+     * @return 比较结果 Map,含 comparable(是否可比对)、message、reportA/reportB 摘要、
+     *         differences(指标级差异标注)、scoreComparison(总分差异)
+     */
+    public Map<String, Object> compareReports(Long reportAId, Long reportBId) {
+        Map<String, Object> result = new LinkedHashMap<>();
+
+        if (reportAId == null || reportBId == null) {
+            result.put("comparable", false);
+            result.put("message", "reportAId 与 reportBId 不能为空");
+            return result;
+        }
+
+        HealthReport reportA = healthReportService.getReportById(reportAId);
+        HealthReport reportB = healthReportService.getReportById(reportBId);
+
+        if (reportA == null || reportB == null) {
+            result.put("comparable", false);
+            result.put("message", "报告不存在");
+            return result;
+        }
+
+        // 类型一致性检查:仅同类型报告可比对(SC-P-25 / TC-P-21)
+        if (!Objects.equals(reportA.getReportType(), reportB.getReportType())) {
+            result.put("comparable", false);
+            result.put("message", "报告类型不一致,无法对比");
+            result.put("reportAType", reportA.getReportType());
+            result.put("reportBType", reportB.getReportType());
+            return result;
+        }
+
+        result.put("comparable", true);
+        result.put("message", "报告类型一致,可进行差异对比");
+        result.put("reportAId", reportAId);
+        result.put("reportBId", reportBId);
+        result.put("reportA", buildReportSummary(reportA));
+        result.put("reportB", buildReportSummary(reportB));
+
+        // 指标级差异标注
+        result.put("differences", compareIndicators(reportA, reportB));
+
+        // 总分差异
+        result.put("scoreComparison", buildScoreComparison(reportA, reportB));
+
+        return result;
+    }
+
+    private Map<String, Object> buildReportSummary(HealthReport report) {
+        Map<String, Object> summary = new LinkedHashMap<>();
+        summary.put("id", report.getId());
+        summary.put("reportType", report.getReportType());
+        summary.put("reportDate", report.getReportDate() != null
+                ? new java.text.SimpleDateFormat("yyyy-MM-dd").format(report.getReportDate()) : null);
+        summary.put("overallScore", report.getOverallScore());
+        summary.put("gutHealthScore", report.getGutHealthScore());
+        summary.put("nutritionScore", report.getNutritionScore());
+        summary.put("fileUrl", report.getFileUrl());
+        summary.put("status", report.getStatus());
+        return summary;
+    }
+
+    private Map<String, Object> buildScoreComparison(HealthReport reportA, HealthReport reportB) {
+        Map<String, Object> scoreDiff = new LinkedHashMap<>();
+        Integer scoreA = reportA.getOverallScore();
+        Integer scoreB = reportB.getOverallScore();
+        scoreDiff.put("scoreA", scoreA);
+        scoreDiff.put("scoreB", scoreB);
+        if (scoreA != null && scoreB != null) {
+            scoreDiff.put("difference", scoreB - scoreA);
+            scoreDiff.put("percentageDiff", scoreA != 0 ? Double.valueOf((scoreB - scoreA) * 100.0 / scoreA) : null);
+        } else {
+            scoreDiff.put("difference", null);
+            scoreDiff.put("percentageDiff", null);
+        }
+        return scoreDiff;
+    }
+
+    /**
+     * 比较两份报告的指标明细,返回差异标注数组(SC-P-24「差异清晰标注」)。
+     *
+     * @param reportA 报告 A
+     * @param reportB 报告 B
+     * @return 差异标注数组,每项含 indicatorName、diffStatus(same/different/onlyInA/onlyInB)等
+     */
+    private List<Map<String, Object>> compareIndicators(HealthReport reportA, HealthReport reportB) {
+        List<Map<String, Object>> diffs = new ArrayList<>();
+
+        List<HealthIndicator> indicatorsA = healthReportService.getReportIndicators(reportA.getId());
+        List<HealthIndicator> indicatorsB = healthReportService.getReportIndicators(reportB.getId());
+
+        // 按指标名建映射,便于差异检测
+        Map<String, HealthIndicator> mapA = indexByName(indicatorsA);
+        Map<String, HealthIndicator> mapB = indexByName(indicatorsB);
+
+        Set<String> allNames = new LinkedHashSet<>();
+        allNames.addAll(mapA.keySet());
+        allNames.addAll(mapB.keySet());
+
+        for (String name : allNames) {
+            HealthIndicator aInd = mapA.get(name);
+            HealthIndicator bInd = mapB.get(name);
+
+            Map<String, Object> diff = new LinkedHashMap<>();
+            diff.put("indicatorName", name);
+
+            if (aInd != null && bInd != null) {
+                // 双方都有:比较 value/status/refRange
+                diff.put("inBoth", true);
+                diff.put("statusA", aInd.getStatus());
+                diff.put("statusB", bInd.getStatus());
+                diff.put("valueA", aInd.getIndicatorValue());
+                diff.put("valueB", bInd.getIndicatorValue());
+                diff.put("refRangeA", aInd.getRefRange());
+                diff.put("refRangeB", bInd.getRefRange());
+
+                boolean sameValue = Objects.equals(aInd.getIndicatorValue(), bInd.getIndicatorValue());
+                boolean sameStatus = Objects.equals(aInd.getStatus(), bInd.getStatus());
+                boolean sameRefRange = Objects.equals(aInd.getRefRange(), bInd.getRefRange());
+
+                if (sameValue && sameStatus && sameRefRange) {
+                    diff.put("diffStatus", "same");
+                } else {
+                    diff.put("diffStatus", "different");
+                    Map<String, Object> fieldDiffs = new LinkedHashMap<>();
+                    if (!sameValue) fieldDiffs.put("valueDifferent", true);
+                    if (!sameStatus) fieldDiffs.put("statusDifferent", true);
+                    if (!sameRefRange) fieldDiffs.put("refRangeDifferent", true);
+                    diff.put("fieldDiffs", fieldDiffs);
+                }
+            } else if (aInd != null) {
+                // 仅 A 有
+                diff.put("inBoth", false);
+                diff.put("diffStatus", "onlyInA");
+                diff.put("valueA", aInd.getIndicatorValue());
+                diff.put("statusA", aInd.getStatus());
+                diff.put("refRangeA", aInd.getRefRange());
+            } else if (bInd != null) {
+                // 仅 B 有
+                diff.put("inBoth", false);
+                diff.put("diffStatus", "onlyInB");
+                diff.put("valueB", bInd.getIndicatorValue());
+                diff.put("statusB", bInd.getStatus());
+                diff.put("refRangeB", bInd.getRefRange());
+            } else {
+                diff.put("diffStatus", "none");
+            }
+            diffs.add(diff);
+        }
+
+        return diffs;
+    }
+
+    private Map<String, HealthIndicator> indexByName(List<HealthIndicator> indicators) {
+        Map<String, HealthIndicator> map = new LinkedHashMap<>();
+        if (indicators == null) {
+            return map;
+        }
+        for (HealthIndicator ind : indicators) {
+            if (ind.getIndicatorName() != null) {
+                map.put(ind.getIndicatorName(), ind);
+            }
+        }
+        return map;
+    }
+}

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 0
docs/superpowers/PROJECT-OVERVIEW.md


+ 1 - 1
docs/superpowers/api/API_REFERENCE.md

@@ -2991,7 +2991,7 @@ W0.2 双配置中心合并:`product_config` 已并入 `service_config`(唯
 |----------------|------|------|
 | `POST /api/search/global` | **不存在**(无 SearchController) | SC-P-82 `misc.globalSearch` 全局搜索(报告/方案/任务/商品)**未实现**;搜索需求当前分散:`/api/diet/ingredients/search`(食材)、文章/商品搜索各自接口。待实现时在本节登记 |
 | `POST /api/provider/report-parse/connect` | **不存在**(无 ProviderController) | SC-S-09 `provider.reportParse.connect` 商品服务商报告解析接入**未实现**;服务商(PROVIDER 角色)当前经 `/api/vendor/*`、`/api/admin/supply-*` 体系管理,无独立报告解析对接端点 |
-| `POST /api/health/report/compare` | **不存在** | SC-P-24/T-21 `health.report.compare` 报告对比由等价物承载:`/api/dan-report/compare`(DAN 两版对比)+ `/api/assessment/compare/*`(测评首次 vs 最新)。如需跨报告类型统一对比,待实现 |
+| `POST /api/health/report/compare` | ✅ 已实现(2026-11-14,S-cfc-364) | SC-P-24/T-21 `health.report.compare` 报告对比落地:`ReportArchiveCompareService.compareReports(reportAId, reportBId)`(类型一致才可比对,返回报告摘要 + 指标级差异标注 same/different/onlyInA/onlyInB + 总分差异;DAN 两版对比仍走 `/api/dan-report/compare`) |
 | `POST /api/health/report/trend` | **不存在** | SC-P-25 `health.report.trend` 由等价物承载:`/api/health/nutrition/trend` + `/api/food/recommendation/trend`(+ 既有 `/api/indicator/trend`、`/api/cognitive/trend`) |
 | `POST /api/health/report/diet` | **不存在** | SC-P-26 `health.report.dietRecommend` 由等价物承载:`/api/food/recommendation/*` + `/api/meal/*` + `/api/diet/*`(4.11) |
 | `POST /api/health/report/share` | **不存在** | SC-P-84 `health.report.share` 由等价物承载:`/api/share/*`(通用分享)+ `/api/health/report/member-permission/*`(成员级授权,4.59.4) |

Některé soubory nejsou zobrazeny, neboť je v těchto rozdílových datech změněno mnoho souborů