|
|
@@ -0,0 +1,360 @@
|
|
|
+package com.etotem.cfc.service;
|
|
|
+
|
|
|
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
|
|
+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.IndicatorDefinition;
|
|
|
+import com.etotem.cfc.entity.MemberIndicatorCurrent;
|
|
|
+import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
+import org.junit.jupiter.api.BeforeEach;
|
|
|
+import org.junit.jupiter.api.Test;
|
|
|
+import org.mockito.ArgumentCaptor;
|
|
|
+import org.mockito.Mock;
|
|
|
+import org.mockito.Mockito;
|
|
|
+import org.mockito.MockitoAnnotations;
|
|
|
+import org.mockito.invocation.Invocation;
|
|
|
+import org.springframework.jdbc.core.JdbcTemplate;
|
|
|
+
|
|
|
+import java.math.BigDecimal;
|
|
|
+import java.text.SimpleDateFormat;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.Arrays;
|
|
|
+import java.util.Collections;
|
|
|
+import java.util.Date;
|
|
|
+import java.util.LinkedHashMap;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+import static org.junit.jupiter.api.Assertions.*;
|
|
|
+import static org.mockito.ArgumentMatchers.*;
|
|
|
+import static org.mockito.Mockito.*;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 报告日期可修改 —— 落库数据完整性单元测试(纯单元测试,无 SpringBootTest,避免 MySQL 连接)。
|
|
|
+ *
|
|
|
+ * 覆盖:
|
|
|
+ * - updateReportFromPayload 菌群重建:必须合并 payload 的全部 9 个菌群组并保留 description
|
|
|
+ * (创建路径 buildGutFloraFromPayload 口径;编辑路径曾只取 gutFlora 单组 → 截断 + 清空 description)
|
|
|
+ * - 日期变更:必须同步 indicator_values 时序行的 report_date(report_id 为空的历史行按 source_id 兜底)
|
|
|
+ * - 日期变更:date_source='real' 标记必须同时命中 report_id 与 source_id 两种关联口径
|
|
|
+ * - refreshMemberIndicatorCurrent:最近期以重算结果为准(改日期后"上一期"需重定位)
|
|
|
+ */
|
|
|
+public class HealthReportDateEditDataIntegrityTest {
|
|
|
+
|
|
|
+ private static final String SYNC_REPORT_DATE_SQL =
|
|
|
+ "UPDATE indicator_values SET report_date = ? WHERE report_id = ? OR (source_type = ? AND source_id = ?)";
|
|
|
+ private static final String MARK_DATE_SOURCE_SQL =
|
|
|
+ "UPDATE indicator_values SET date_source = 'real' WHERE report_id = ? OR (source_type = ? AND source_id = ?)";
|
|
|
+
|
|
|
+ @Mock
|
|
|
+ private com.etotem.cfc.mapper.HealthReportMapper healthReportMapper;
|
|
|
+ @Mock
|
|
|
+ private com.etotem.cfc.mapper.HealthIndicatorMapper healthIndicatorMapper;
|
|
|
+ @Mock
|
|
|
+ private com.etotem.cfc.mapper.HealthGutFloraMapper healthGutFloraMapper;
|
|
|
+ @Mock
|
|
|
+ private com.etotem.cfc.mapper.HealthDiseaseRiskMapper healthDiseaseRiskMapper;
|
|
|
+ @Mock
|
|
|
+ private com.etotem.cfc.mapper.HealthReportEditLogMapper healthReportEditLogMapper;
|
|
|
+ @Mock
|
|
|
+ private com.etotem.cfc.mapper.IndicatorDefinitionMapper indicatorDefinitionMapper;
|
|
|
+ @Mock
|
|
|
+ private MemberIndicatorCurrentService memberIndicatorCurrentService;
|
|
|
+ @Mock
|
|
|
+ private ReportBlockService reportBlockService;
|
|
|
+ @Mock
|
|
|
+ private ReportBlockAssembler reportBlockAssembler;
|
|
|
+ @Mock
|
|
|
+ private NormalizeIndicatorPipeline normalizeIndicatorPipeline;
|
|
|
+ @Mock
|
|
|
+ private DimensionScoreService dimensionScoreService;
|
|
|
+ @Mock
|
|
|
+ private FoodRecommendService foodRecommendService;
|
|
|
+ @Mock
|
|
|
+ private JdbcTemplate jdbcTemplate;
|
|
|
+
|
|
|
+ private HealthReportService service;
|
|
|
+
|
|
|
+ @BeforeEach
|
|
|
+ public void setUp() {
|
|
|
+ MockitoAnnotations.openMocks(this);
|
|
|
+ initMybatisPlusMetadata();
|
|
|
+ service = new HealthReportService();
|
|
|
+ setField(service, "healthReportMapper", healthReportMapper);
|
|
|
+ setField(service, "healthIndicatorMapper", healthIndicatorMapper);
|
|
|
+ setField(service, "healthGutFloraMapper", healthGutFloraMapper);
|
|
|
+ setField(service, "healthDiseaseRiskMapper", healthDiseaseRiskMapper);
|
|
|
+ setField(service, "healthReportEditLogMapper", healthReportEditLogMapper);
|
|
|
+ setField(service, "indicatorDefinitionMapper", indicatorDefinitionMapper);
|
|
|
+ setField(service, "memberIndicatorCurrentService", memberIndicatorCurrentService);
|
|
|
+ setField(service, "reportBlockService", reportBlockService);
|
|
|
+ setField(service, "reportBlockAssembler", reportBlockAssembler);
|
|
|
+ setField(service, "normalizeIndicatorPipeline", normalizeIndicatorPipeline);
|
|
|
+ setField(service, "dimensionScoreService", dimensionScoreService);
|
|
|
+ setField(service, "foodRecommendService", foodRecommendService);
|
|
|
+ setField(service, "jdbcTemplate", jdbcTemplate);
|
|
|
+ setField(service, "objectMapper", new ObjectMapper());
|
|
|
+ when(reportBlockAssembler.fromMap(any())).thenReturn(new com.etotem.cfc.dto.ParsedReportPayload.Payload());
|
|
|
+ when(reportBlockAssembler.assembleWithTemplate(anyString(), any())).thenReturn(Collections.emptyList());
|
|
|
+ }
|
|
|
+
|
|
|
+ private void setField(Object target, String fieldName, Object value) {
|
|
|
+ try {
|
|
|
+ java.lang.reflect.Field f = target.getClass().getDeclaredField(fieldName);
|
|
|
+ f.setAccessible(true);
|
|
|
+ f.set(target, value);
|
|
|
+ } catch (Exception e) {
|
|
|
+ throw new RuntimeException(e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 纯单测没有 Spring/MyBatis 初始化,LambdaQueryWrapper 解析 @TableField 需实体元数据缓存 */
|
|
|
+ private void initMybatisPlusMetadata() {
|
|
|
+ org.apache.ibatis.builder.MapperBuilderAssistant assistant =
|
|
|
+ new org.apache.ibatis.builder.MapperBuilderAssistant(
|
|
|
+ new com.baomidou.mybatisplus.core.MybatisConfiguration(), "");
|
|
|
+ assistant.setCurrentNamespace("health-report-date-edit-test");
|
|
|
+ for (Class<?> entity : new Class<?>[]{
|
|
|
+ HealthReport.class, HealthIndicator.class, HealthGutFlora.class,
|
|
|
+ HealthDiseaseRisk.class, IndicatorDefinition.class}) {
|
|
|
+ TableInfoHelper.initTableInfo(assistant, entity);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // ── helpers ─────────────────────────────────────────────────────────
|
|
|
+
|
|
|
+ private HealthReport report(Long id, Long subjectId, String reportType, Date reportDate) {
|
|
|
+ HealthReport r = new HealthReport();
|
|
|
+ r.setId(id);
|
|
|
+ r.setSubjectId(subjectId);
|
|
|
+ r.setReportType(reportType);
|
|
|
+ r.setReportDate(reportDate);
|
|
|
+ r.setStatus("active");
|
|
|
+ r.setPayloadJson("{}");
|
|
|
+ return r;
|
|
|
+ }
|
|
|
+
|
|
|
+ private Date date(String yyyyMMdd) {
|
|
|
+ try {
|
|
|
+ return new SimpleDateFormat("yyyy-MM-dd").parse(yyyyMMdd);
|
|
|
+ } catch (Exception e) {
|
|
|
+ throw new RuntimeException(e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Object> basePayload() {
|
|
|
+ Map<String, Object> p = new LinkedHashMap<>();
|
|
|
+ p.put("type", "gut_flora");
|
|
|
+ Map<String, Object> summary = new LinkedHashMap<>();
|
|
|
+ summary.put("overallScore", 80);
|
|
|
+ summary.put("gutHealthScore", 75);
|
|
|
+ p.put("summary", summary);
|
|
|
+ return p;
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Object> flora(String name, String value, String description) {
|
|
|
+ Map<String, Object> m = new LinkedHashMap<>();
|
|
|
+ m.put("bacteriaName", name);
|
|
|
+ m.put("bacteriaValue", value);
|
|
|
+ m.put("description", description);
|
|
|
+ return m;
|
|
|
+ }
|
|
|
+
|
|
|
+ private List<String> jdbcUpdateSqls() {
|
|
|
+ List<String> sqls = new ArrayList<>();
|
|
|
+ for (Invocation inv : Mockito.mockingDetails(jdbcTemplate).getInvocations()) {
|
|
|
+ if ("update".equals(inv.getMethod().getName())) {
|
|
|
+ sqls.add(inv.getArgument(0));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return sqls;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 取指定 SQL 的 jdbcTemplate.update 实参(兼容 Mockito 对 varargs 的展开/数组两种形态) */
|
|
|
+ private Object[] updateArgs(String sql) {
|
|
|
+ for (Invocation inv : Mockito.mockingDetails(jdbcTemplate).getInvocations()) {
|
|
|
+ if (!"update".equals(inv.getMethod().getName())) continue;
|
|
|
+ if (!sql.equals(inv.getArgument(0))) continue;
|
|
|
+ Object second = inv.getArgument(1);
|
|
|
+ if (second instanceof Object[]) return (Object[]) second;
|
|
|
+ List<Object> args = new ArrayList<>(Arrays.asList(inv.getArguments()));
|
|
|
+ return args.subList(1, args.size()).toArray();
|
|
|
+ }
|
|
|
+ return new Object[0];
|
|
|
+ }
|
|
|
+
|
|
|
+ // ── 菌群重建:合并 9 组 + 保留 description ──────────────────────────
|
|
|
+
|
|
|
+ @Test
|
|
|
+ void editReport_gutFloraRebuild_mergesAllFloraGroupsAndKeepsDescription() {
|
|
|
+ when(healthReportMapper.selectById(58L))
|
|
|
+ .thenReturn(report(58L, null, "gut_flora", date("2026-09-09")));
|
|
|
+
|
|
|
+ Map<String, Object> taxonomyGenus = flora("厚壁菌门", "78.2%", null);
|
|
|
+ taxonomyGenus.put("category", "菌门构成");
|
|
|
+ taxonomyGenus.put("level", "门");
|
|
|
+ Map<String, Object> pathogen = flora("幽门螺旋杆菌", "阳性", null);
|
|
|
+ pathogen.put("category", "病原菌");
|
|
|
+
|
|
|
+ Map<String, Object> payload = basePayload();
|
|
|
+ payload.put("gutFlora", Collections.singletonList(
|
|
|
+ flora("双歧杆菌属", "12.5%", "有益菌,维持肠道屏障")));
|
|
|
+ payload.put("taxonomyGenus", Collections.singletonList(taxonomyGenus));
|
|
|
+ payload.put("pathogenDetection", Collections.singletonList(pathogen));
|
|
|
+
|
|
|
+ service.updateReportFromPayload(58L, payload, null, 1L);
|
|
|
+
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ ArgumentCaptor<HealthGutFlora> captor = ArgumentCaptor.forClass(HealthGutFlora.class);
|
|
|
+ verify(healthGutFloraMapper, times(3)).insert(captor.capture());
|
|
|
+ List<HealthGutFlora> inserted = captor.getAllValues();
|
|
|
+
|
|
|
+ HealthGutFlora core = inserted.get(0);
|
|
|
+ HealthGutFlora taxonomy = inserted.get(1);
|
|
|
+ HealthGutFlora pathogenRow = inserted.get(2);
|
|
|
+
|
|
|
+ assertEquals("双歧杆菌属", core.getBacteriaName());
|
|
|
+ assertEquals("有益菌,维持肠道屏障", core.getDescription(),
|
|
|
+ "编辑保存不得清空 health_gut_flora.description(payload 快照含该列)");
|
|
|
+ assertEquals("厚壁菌门", taxonomy.getBacteriaName(),
|
|
|
+ "编辑保存必须合并 taxonomy 分组,否则分类学菌群行被 delete+insert 截断");
|
|
|
+ assertEquals(HealthGutFlora.CATEGORY_TAXONOMY, taxonomy.getCategory());
|
|
|
+ assertEquals(HealthGutFlora.LEVEL_PHYLUM, taxonomy.getLevel());
|
|
|
+ assertEquals("幽门螺旋杆菌", pathogenRow.getBacteriaName(),
|
|
|
+ "编辑保存必须合并 pathogen 分组");
|
|
|
+ assertEquals(0, core.getSortOrder());
|
|
|
+ assertEquals(2, pathogenRow.getSortOrder());
|
|
|
+ assertEquals(58L, core.getReportId());
|
|
|
+ }
|
|
|
+
|
|
|
+ // ── 日期变更:时序行 report_date 同步 ───────────────────────────────
|
|
|
+
|
|
|
+ @Test
|
|
|
+ void editReport_dateChange_syncsTimelineReportDateIncludingLegacyRows() {
|
|
|
+ when(healthReportMapper.selectById(58L))
|
|
|
+ .thenReturn(report(58L, 21L, "gut_flora", date("2026-09-09")));
|
|
|
+ when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any(), any())).thenReturn(1);
|
|
|
+
|
|
|
+ Map<String, Object> payload = basePayload();
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ Map<String, Object> summary = (Map<String, Object>) payload.get("summary");
|
|
|
+ summary.put("reportDate", "2026-10-15");
|
|
|
+
|
|
|
+ service.updateReportFromPayload(58L, payload, null, 1L);
|
|
|
+
|
|
|
+ Object[] args = updateArgs(SYNC_REPORT_DATE_SQL);
|
|
|
+ assertTrue(args.length > 0,
|
|
|
+ "改日期必须同步 indicator_values 时序行 report_date,实际执行SQL:" + jdbcUpdateSqls());
|
|
|
+ assertEquals(4, args.length, "同步SQL参数应为 [reportDate, reportId, sourceType, reportId]");
|
|
|
+ assertEquals(58L, args[1], "report_id 关联口径");
|
|
|
+ assertEquals("gut_flora", args[2], "source_type 必须限定为本报告类型,避免误伤其它来源");
|
|
|
+ assertEquals(58L, args[3], "source_id 兜底口径:历史行 report_id 为 NULL 时仍需命中");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ void editReport_withoutDateChange_doesNotTouchTimelineRows() {
|
|
|
+ when(healthReportMapper.selectById(58L))
|
|
|
+ .thenReturn(report(58L, null, "gut_flora", date("2026-09-09")));
|
|
|
+
|
|
|
+ service.updateReportFromPayload(58L, basePayload(), null, 1L);
|
|
|
+
|
|
|
+ assertFalse(jdbcUpdateSqls().stream().anyMatch(s -> s.contains("indicator_values")),
|
|
|
+ "未改日期不应触碰时序行,实际执行SQL:" + jdbcUpdateSqls());
|
|
|
+ }
|
|
|
+
|
|
|
+ // ── 日期变更:date_source 标记口径 ──────────────────────────────────
|
|
|
+
|
|
|
+ @Test
|
|
|
+ void editReport_dateChange_marksDateSourceMatchingLegacySourceIdRows() {
|
|
|
+ when(healthReportMapper.selectById(58L))
|
|
|
+ .thenReturn(report(58L, 21L, "gut_flora", date("2026-09-09")));
|
|
|
+ when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any(), any())).thenReturn(1);
|
|
|
+
|
|
|
+ Map<String, Object> payload = basePayload();
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ Map<String, Object> summary = (Map<String, Object>) payload.get("summary");
|
|
|
+ summary.put("reportDate", "2026-10-15");
|
|
|
+
|
|
|
+ service.updateReportFromPayload(58L, payload, null, 1L);
|
|
|
+
|
|
|
+ Object[] args = updateArgs(MARK_DATE_SOURCE_SQL);
|
|
|
+ assertTrue(args.length > 0,
|
|
|
+ "date_source 标记必须命中 report_id 为空的历史时序行,实际执行SQL:" + jdbcUpdateSqls());
|
|
|
+ assertEquals(3, args.length, "date_source 标记参数应为 [reportId, sourceType, reportId]");
|
|
|
+ assertEquals(58L, args[0], "report_id 关联口径");
|
|
|
+ assertEquals("gut_flora", args[1], "source_type 限定为报告类型");
|
|
|
+ assertEquals(58L, args[2], "source_id 兜底口径");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ── 快照刷新:最近期以重算结果为准 ──────────────────────────────────
|
|
|
+
|
|
|
+ @Test
|
|
|
+ void refreshMemberIndicatorCurrent_usesRecomputedLatestAfterDateRelocation() {
|
|
|
+ HealthReport latest = report(58L, 21L, "gut_flora", date("2026-10-15"));
|
|
|
+ HealthReport previous = report(42L, 21L, "gut_flora", date("2026-09-09"));
|
|
|
+ when(healthReportMapper.selectList(any())).thenReturn(Arrays.asList(latest, previous));
|
|
|
+ // 按调用顺序:第一次 = 最新期(58) 指标,第二次 = 上一期(42) 指标
|
|
|
+ when(healthIndicatorMapper.selectList(any())).thenReturn(
|
|
|
+ Collections.singletonList(indicator("BMI", "22.5")),
|
|
|
+ Collections.singletonList(indicator("BMI", "23.0")));
|
|
|
+ IndicatorDefinition def = new IndicatorDefinition();
|
|
|
+ def.setId(7L);
|
|
|
+ def.setDomain("body");
|
|
|
+ def.setCategory("体格");
|
|
|
+ when(indicatorDefinitionMapper.selectOne(any())).thenReturn(def);
|
|
|
+
|
|
|
+ // 入参是"触发刷新的报告",改日期后它可能已不是最近期 → 快照必须按重算结果定位
|
|
|
+ service.refreshMemberIndicatorCurrent(21L, 42L);
|
|
|
+
|
|
|
+ ArgumentCaptor<MemberIndicatorCurrent> captor = ArgumentCaptor.forClass(MemberIndicatorCurrent.class);
|
|
|
+ verify(memberIndicatorCurrentService).upsert(captor.capture());
|
|
|
+ MemberIndicatorCurrent item = captor.getValue();
|
|
|
+ assertEquals(58L, item.getLatestReportId(), "最近期必须按 report_date 重算,不得盲信入参");
|
|
|
+ assertEquals(42L, item.getPreviousReportId());
|
|
|
+ assertEquals(new BigDecimal("22.5"), item.getNumericValue());
|
|
|
+ assertEquals(new BigDecimal("23.0"), item.getPreviousNumeric());
|
|
|
+ assertEquals("down", item.getTrend());
|
|
|
+ assertEquals(21L, item.getMemberId());
|
|
|
+ }
|
|
|
+
|
|
|
+ private HealthIndicator indicator(String name, String value) {
|
|
|
+ HealthIndicator ind = new HealthIndicator();
|
|
|
+ ind.setIndicatorName(name);
|
|
|
+ ind.setIndicatorValue(value);
|
|
|
+ return ind;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ // ── 最小 payload:不覆盖存量快照、不触碰明细表 ──────────────────────
|
|
|
+
|
|
|
+ @Test
|
|
|
+ void editReport_minimalDateOnlyPayload_keepsPayloadSnapshotAndLeavesDetailTablesUntouched() {
|
|
|
+ String oldPayloadJson = "{\"type\":\"gut_flora\",\"summary\":{\"overallScore\":80},"
|
|
|
+ + "\"gutFlora\":[{\"bacteriaName\":\"双歧杆菌属\"}],"
|
|
|
+ + "\"taxonomyGenus\":[{\"bacteriaName\":\"厚壁菌门\"}]}";
|
|
|
+ HealthReport oldReport = report(58L, null, "gut_flora", date("2026-09-09"));
|
|
|
+ oldReport.setPayloadJson(oldPayloadJson);
|
|
|
+ when(healthReportMapper.selectById(58L)).thenReturn(oldReport);
|
|
|
+
|
|
|
+ // 与前端 submitDateChange 一致:只带 summary.reportDate,不带 indicators/gutFlora/diseaseRisks
|
|
|
+ Map<String, Object> summary = new LinkedHashMap<>();
|
|
|
+ summary.put("overallScore", 80);
|
|
|
+ summary.put("reportDate", "2026-10-15");
|
|
|
+ Map<String, Object> payload = new LinkedHashMap<>();
|
|
|
+ payload.put("type", "gut_flora");
|
|
|
+ payload.put("summary", summary);
|
|
|
+
|
|
|
+ service.updateReportFromPayload(58L, payload, null, 1L);
|
|
|
+
|
|
|
+ ArgumentCaptor<HealthReport> captor = ArgumentCaptor.forClass(HealthReport.class);
|
|
|
+ verify(healthReportMapper, times(1)).updateById(captor.capture());
|
|
|
+ assertEquals(oldPayloadJson, captor.getValue().getPayloadJson(),
|
|
|
+ "日期专用最小 payload 不得覆盖存量 payload 快照(否则下次编辑页回填空明细 → 三表整体清空)");
|
|
|
+ verify(healthIndicatorMapper, never()).delete(any());
|
|
|
+ verify(healthGutFloraMapper, never()).delete(any());
|
|
|
+ verify(healthDiseaseRiskMapper, never()).delete(any());
|
|
|
+ }
|
|
|
+
|
|
|
+}
|