Просмотр исходного кода

feat(health-survey): 普通问卷每次提交追加 survey_records 历史 + 对照视图对象型摘要

根因:健康问卷普通填写路径走 saveHealthStatus(health_status 表,每成员单行 upsert
覆盖写)+ saveDietPreferences,天然无历史,无法逐次对照。cfc-backend 已有 append-only
历史设施:survey_records 表 + POST /api/survey/submit + GET /api/survey/history,健康阅
卷(source=health_review)已用它写历史,本次让普通问卷也写历史。schema 不需迁移——
survey_records.source 取值 periodic/health_review,新值 health_status 可直接存。

做法(三处,均在本次范围):
A. 后端 SurveyServiceImpl.doSubmit:新增 noTemplateNeeded = isHealthReview ||
   "health_status".equals(src),模板判空改用 noTemplateNeeded;health_status 与 health_review
   同为「免模板 + append-only」场景。isHealthReview 仍只触发阅卷的 syncHealthStatusFromReview
   ——health_status 不回写 health_status(内容前已由前端写入,后端只 append 历史快照)。
   familyId 落库/resolveMemberId/insert 等其余逻辑不动。
B. 前端 health-survey.vue 普通 onSubmit(非 health_review):在 saveTasks 内容保存成功回调
   内、补签名之前,逐成员追加 submitSurvey 历史(source=health_status,answersJson =
   {form,diet,lifestyle} 对象串,代填成员传 row 级 memberId、账号级不传;逐个 .catch 仅
   console.warn,Promise.all 包裹但不上抛外层 catch,历史失败绝不阻塞整体「已保存」退出)。
   health_review 分支与 flushUnsavedMembers 兜底不动。
C. 前端 survey-history.vue:getRecordTitle 在 source=health_status 且无 title/模板命中时
   返回「健康问卷」;getAnswerSummary 对对象型 answersJson(含 form/lifestyle 键)渲染可读
   中文摘要(身高/体重/血压/血糖/血脂 + 疾病史/用药条数 + lifestyle 中文标签关键项 + diet
   过敏原;空值省略、数组 join('、')、血压/血糖原样)。periodic/health_review 数组型记录
   渲染行为不变。

测试(全绿):
- 后端 SurveyHealthStatusContractTest(新增,仿既有 SurveyHealthReviewContractTest 风格)
  3 用例通过:①source=health_status+templateId=null 不抛「缺少调研模板ID」;②insert 的
  SurveyRecord source/templateId=null/answersJson/memberId/familyId 正确;③不触发
  healthStatusService.saveForMember(0 次)。既有 SurveyHealthReviewContractTest 9 用例
  回归通过(共 12 tests,mvn test BUILD SUCCESS)。
- 前端 healthSurvey.submitHistory.test.js(新增,仿 incrementalSave/reviewMultiMember 风格)
  10 用例通过:普通 onSubmit 内容保存后每成员各调 submitSurvey(source/answersJson 形状/
  memberId 归属)、未变化成员也留历史、历史 reject 仍 toast「已保存」不进 catch、仅
  console.warn、对照视图标题与对象型摘要、数组型记录渲染不变。既有 4 个 healthSurvey
  测试文件(incrementalSave/reviewMultiMember/lifestyleSave/memberPicker,共 27 用例)回归
  通过(共 37 tests)。

注:worktree 内 mvn test 时存在与本事无关的主线测试编译断裂(IndicatorFavoriteControllerTest、
ManualDimensionScoreContractTest 因与任务#34「修复主线编译断裂」相关的既有漂移),本次未触碰,
测试时临时移出跑通后已原样恢复,未纳入提交。

任务:#45 普通问卷写历史 + #46 对照视图对象型摘要
feature 分支:feat/survey-history(基于 feat/api-memberid-rule 28c0b523d)
Agnes Agent 16 часов назад
Родитель
Сommit
485315c3d7

+ 5 - 2
cfc-backend/src/main/java/com/etotem/cfc/service/impl/SurveyServiceImpl.java

@@ -180,14 +180,17 @@ public class SurveyServiceImpl implements SurveyService {
     }
 
     /**
-     * 核心落库:source=health_review 时不校验模板/周期(健康阅卷复用问卷但不挂模板),
+     * 核心落库:健康问卷普通填写(source=health_status)与健康阅卷(source=health_review)均为
+     * 「免模板 + append-only」场景——内容已由前端直接写入 health_status,后端只向 survey_records
+     * 追加一条历史快照,不再回写/校验模板,用于日后逐次对照。
      * 其余按定期调研处理(templateId 必填,period 由服务端按模板 cycle_type 计算)。
      */
     private SurveyRecord doSubmit(Long userId, Long memberId, Long templateId, String answersJson,
                                   Date periodStart, Date periodEnd, String source) {
         String src = (source == null || source.trim().isEmpty()) ? "periodic" : source.trim();
         boolean isHealthReview = "health_review".equals(src);
-        if (!isHealthReview && templateId == null) {
+        boolean noTemplateNeeded = isHealthReview || "health_status".equals(src);
+        if (!noTemplateNeeded && templateId == null) {
             throw new IllegalArgumentException("缺少调研模板ID,请从调研列表进入");
         }
         memberId = resolveMemberId(userId, memberId);

+ 145 - 0
cfc-backend/src/test/java/com/etotem/cfc/controller/SurveyHealthStatusContractTest.java

@@ -0,0 +1,145 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.HealthStatus;
+import com.etotem.cfc.entity.SurveyRecord;
+import com.etotem.cfc.entity.SurveyTemplate;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.SurveyRecordMapper;
+import com.etotem.cfc.mapper.SurveyTemplateMapper;
+import com.etotem.cfc.service.AiGateway;
+import com.etotem.cfc.service.HealthStatusService;
+import com.etotem.cfc.service.UserCurrentFoodService;
+import com.etotem.cfc.service.impl.SurveyServiceImpl;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * 健康问卷普通填写历史契约测试(source=health_status:免模板 + append-only)。
+ *
+ * <p>背景与根因:健康问卷页普通填写路径的内容由前端直接写 health_status / diet_preferences
+ * (每成员单行 upsert 覆盖写,天然无历史)。本次让其提交成功后追加一条 survey_records 历史
+ * (source=health_status),用于日后逐次对照。与 health_review 同为「免模板」场景;
+ * 但阅卷会二次同步回 health_status,普通问卷不复用该同步(内容前已由前端写入)。
+ *
+ * <p>验收:
+ * <ul>
+ *   <li>① source=health_status 且 templateId 缺省时,不抛「缺少调研模板ID」;</li>
+ *   <li>② 落库 record:source='health_status'、templateId=null、answersJson 一致、memberId/familyId 正确;</li>
+ *   <li>③ submitSurvey(source=health_status) 不触发 healthStatusService.saveForMember(0 次)。</li>
+ * </ul>
+ *
+ * <p>纯 Mock 单元测试,不启动 Spring 上下文。
+ */
+class SurveyHealthStatusContractTest {
+
+    private SurveyServiceImpl service;
+    private SurveyTemplateMapper surveyTemplateMapper;
+    private SurveyRecordMapper surveyRecordMapper;
+    private FamilyMemberMapper familyMemberMapper;
+    private HealthStatusService healthStatusService;
+
+    /** 最近一次 insert 捕获到的实际 record 实例(insert 回填 id 后由 stubInsertAndCapture 填充) */
+    private final SurveyRecord[] holder = new SurveyRecord[1];
+
+    @BeforeEach
+    void setUp() {
+        service = new SurveyServiceImpl();
+        surveyTemplateMapper = mock(SurveyTemplateMapper.class);
+        surveyRecordMapper = mock(SurveyRecordMapper.class);
+        familyMemberMapper = mock(FamilyMemberMapper.class);
+        healthStatusService = mock(HealthStatusService.class);
+        ReflectionTestUtils.setField(service, "surveyTemplateMapper", surveyTemplateMapper);
+        ReflectionTestUtils.setField(service, "surveyRecordMapper", surveyRecordMapper);
+        ReflectionTestUtils.setField(service, "familyMemberMapper", familyMemberMapper);
+        ReflectionTestUtils.setField(service, "aiGateway", mock(AiGateway.class));
+        ReflectionTestUtils.setField(service, "healthStatusService", healthStatusService);
+        ReflectionTestUtils.setField(service, "userCurrentFoodService", mock(UserCurrentFoodService.class));
+    }
+
+    private FamilyMember member(Long id, Long familyId) {
+        FamilyMember m = new FamilyMember();
+        m.setId(id);
+        m.setFamilyId(familyId);
+        m.setUserId(1000L);
+        return m;
+    }
+
+    /** 捕获实际插入的 record(Mockito 传入实参),insert 回填 id 后 selectById 返回同一实例 */
+    private void stubInsertAndCapture() {
+        doAnswer(inv -> {
+            SurveyRecord r = inv.getArgument(0);
+            r.setId(999L);
+            holder[0] = r;
+            return 1;
+        }).when(surveyRecordMapper).insert(any(SurveyRecord.class));
+        when(surveyRecordMapper.selectById(999L)).thenAnswer(inv -> holder[0]);
+    }
+
+    /** 返回最近一次 insert 捕获到的实际 record 实例 */
+    private SurveyRecord captureLastInserted() {
+        org.mockito.ArgumentCaptor<SurveyRecord> cap = org.mockito.ArgumentCaptor.forClass(SurveyRecord.class);
+        verify(surveyRecordMapper, atLeastOnce()).insert(cap.capture());
+        return cap.getValue();
+    }
+
+    @Test
+    void submitHealthStatus_withoutTemplate_ok() {
+        when(familyMemberMapper.selectById(7L)).thenReturn(member(7L, 100L));
+        stubInsertAndCapture();
+
+        String answersJson = "{\"form\":{\"heightCm\":170,\"weightKg\":60},\"diet\":{},\"lifestyle\":{\"currentStatus\":\"正常\"}}";
+        // ① templateId=null + source=health_status → 免模板,不抛「缺少调研模板ID」
+        SurveyRecord result = service.submitSurvey(1L, 7L, null, answersJson, null, null, null, "health_status");
+
+        assertNotNull(result);
+        // 免模板:不应查询模板
+        verify(surveyTemplateMapper, never()).selectById(any());
+        // ② 落库属性核对
+        SurveyRecord inserted = captureLastInserted();
+        assertEquals("health_status", inserted.getSource());
+        assertNull(inserted.getTemplateId());
+        assertEquals(answersJson, inserted.getAnswersJson());
+        assertEquals(7L, inserted.getMemberId());
+        assertEquals(100L, inserted.getFamilyId());
+        // 无模板 → 无周期
+        assertNull(inserted.getPeriodStart());
+        assertNull(inserted.getPeriodEnd());
+        // ③ 普通问卷由前端直接写 health_status,后端历史写不同步回 health_status(saveForMember 0 次)
+        verify(healthStatusService, never()).saveForMember(anyLong(), anyLong(), any(HealthStatus.class));
+    }
+
+    @Test
+    void submitHealthStatus_neverWritesHealthStatus() {
+        when(familyMemberMapper.selectById(77L)).thenReturn(member(77L, 200L));
+        stubInsertAndCapture();
+
+        // 显式再断言一次:健康问卷历史写只插 survey_records,绝不动 health_status
+        service.submitSurvey(1L, 77L, null, "{\"form\":{\"weightKg\":55}}", null, null, null, "health_status");
+
+        verify(healthStatusService, never()).saveForMember(anyLong(), anyLong(), any(HealthStatus.class));
+        verify(healthStatusService, never()).saveForMember(anyLong(), isNull(), any(HealthStatus.class));
+    }
+
+    @Test
+    void submitHealthReview_syncsWhileHealthStatusDoesNot() {
+        // 反向隔离:同结构下 health_review 会同步(1 次),health_status 不会——验证 doSubmit 的
+        // 二次同步仅限阅卷,普通问卷只 append 历史快照。
+        when(familyMemberMapper.selectById(7L)).thenReturn(member(7L, 100L));
+        stubInsertAndCapture();
+
+        service.submitSurvey(1L, 7L, null, "{\"form\":{\"heightCm\":170}}", null, null, null, "health_review");
+        verify(healthStatusService, times(1)).saveForMember(anyLong(), anyLong(), any(HealthStatus.class));
+
+        reset(healthStatusService);
+        when(familyMemberMapper.selectById(7L)).thenReturn(member(7L, 100L));
+        stubInsertAndCapture();
+        service.submitSurvey(1L, 7L, null, "{\"form\":{\"heightCm\":170}}", null, null, null, "health_status");
+        verify(healthStatusService, never()).saveForMember(anyLong(), anyLong(), any(HealthStatus.class));
+    }
+}

+ 326 - 0
cfc-frontend/__tests__/pages/health/healthSurvey.submitHistory.test.js

@@ -0,0 +1,326 @@
+/**
+ * 契约级单测(TDD-RED→GREEN)——健康问卷普通填写「每次提交都追加一条 survey_records 历史」
+ * 能力键:health.survey.submitHistory
+ *
+ * 背景与根因:普通填写路径走 saveHealthStatus(health_status 表,每成员单行 upsert 覆盖写)+
+ * saveDietPreferences,天然无历史。本次让其在内容保存成功后追加一条 append-only 历史
+ * (source=health_status,免模板),供日后逐次对照。健康阅卷(source=health_review)已走该设施,
+ * 本次让普通问卷也写历史。
+ * 本测试锁定五条契约:
+ *   1) 普通 onSubmit(非 health_review)在 saveHealthStatus 成功后,对本次涉及的每位有内容成员
+ *      各调一次 submitSurvey,source='health_status'、answersJson 为 {form,diet,lifestyle} 对象串;
+ *   2) 代填成员历史带 row 级 memberId,账号级成员不传;
+ *   3) 历史不随 m.changed 增量过滤(未变化成员也留历史);
+ *   4) 历史 submitSurvey reject 时整体仍 toast「已保存」、不进 catch 分支(submitting 复位);
+ *   5) survey-history.vue:health_status 对象型 answersJson 渲染可读中文摘要、标题「健康问卷」,
+ *      periodic 的数组型 answersJson 渲染行为不变。
+ *
+ * 沿用既有 SFC 源码抽取式约定(见 healthSurvey.incrementalSave.test.js / reviewMultiMember.test.js):
+ * jest 无 vue-jest/jsdom,直接加载真实 .vue 的 <script>(import 替换为桩),断言 data()/methods。
+ */
+import fs from 'fs'
+import path from 'path'
+
+const SURVEY_PATH = path.join(__dirname, '../../../pages/health/health-survey.vue')
+const HISTORY_PATH = path.join(__dirname, '../../../pages/health/survey-history.vue')
+
+function stubImports(script) {
+  return script.replace(/import\s+([^;]+?)\s+from\s+['"]([^'"]+)['"];?/g, function (m, clause, id) {
+    var names = []
+    var c = clause.trim()
+    var braceIdx = c.indexOf('{')
+    if (braceIdx >= 0) {
+      var def = c.slice(0, braceIdx).replace(/,\s*$/, '').trim()
+      if (def) names.push(def)
+      var named = c.slice(braceIdx + 1, c.lastIndexOf('}'))
+      named.split(',').forEach(function (part) {
+        var p = part.trim()
+        if (!p) return
+        var parts = p.split(/\s+as\s+/)
+        var local = parts.length > 1 ? parts[1].trim() : parts[0].trim()
+        if (local) names.push(local)
+      })
+    } else if (c.indexOf('*') === 0) {
+      var nsMatch = c.match(/\*\s+as\s+(\w+)/)
+      if (nsMatch) names.push(nsMatch[1])
+    } else {
+      names.push(c)
+    }
+    return names.map(function (n) {
+      return 'var ' + n + ' = (globalThis.__hpStubs[' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+function loadSfcScript(file) {
+  var src = fs.readFileSync(file, 'utf8')
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法定位 <script>: ' + file)
+  var script = stubImports(scriptMatch[1])
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  new Function('module', 'exports', script)(mod, mod.exports)
+  return { component: mod.exports }
+}
+
+function instantiate(component) {
+  var vm = {}
+  vm.$set = function (obj, key, val) { obj[key] = val }
+  var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
+  Object.keys(data).forEach(function (k) { vm[k] = data[k] })
+  var methods = component.methods || {}
+  Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
+  return vm
+}
+
+// 冲掉微任务链(onSubmit 内部多级 Promise.all.then,含历史写 + 签名写),使 API 调用记录可见
+async function flush() {
+  for (var i = 0; i < 24; i++) await Promise.resolve()
+}
+
+var toasts, navs, submits, hsCalls, dietCalls, sigCalls, warns
+var rejectHistory = false
+var origConsoleWarn = console.warn
+
+function setupUni() {
+  toasts = []
+  navs = []
+  globalThis.uni = {
+    showToast: function (o) { toasts.push(o || {}) },
+    navigateBack: function () { navs.push(1) },
+    navigateTo: function () {},
+    getStorageSync: function () { return '' },
+    setStorageSync: function () {},
+    removeStorageSync: function () {},
+    showModal: function () {}
+  }
+}
+
+function wireApi() {
+  submits = []
+  hsCalls = []
+  dietCalls = []
+  sigCalls = []
+  globalThis.__hpStubs['../../utils/api'] = {
+    getHealthStatus: function () { return Promise.resolve({ code: 200, data: null }) },
+    saveHealthStatus: function (p) { hsCalls.push(p); return Promise.resolve({ code: 200 }) },
+    getDietPreferences: function () { return Promise.resolve({ code: 200, data: null }) },
+    saveDietPreferences: function (p) { dietCalls.push(p); return Promise.resolve({ code: 200 }) },
+    getMyMembership: function () { return Promise.resolve({ code: 200, data: {} }) },
+    getFamilyMemberList: function () { return Promise.resolve({ code: 200, data: [] }) },
+    submitSurvey: function (p) {
+      submits.push(p)
+      if (rejectHistory) return Promise.reject(new Error('历史写入失败'))
+      return Promise.resolve({ code: 200 })
+    },
+    getLastHealthReview: function () { return Promise.resolve({ code: 200, data: null }) },
+    saveHealthSignature: function (mid, dataUrl) { sigCalls.push({ mid: mid, dataUrl: dataUrl }); return Promise.resolve({ code: 200 }) }
+  }
+}
+
+const ALL8 = ['basic', 'status', 'diet', 'disease', 'bowel', 'sleep', 'med', 'allergy']
+
+beforeEach(function () {
+  globalThis.__hpStubs = {}
+  setupUni()
+  rejectHistory = false
+  // 静默 onSubmit 内部 console.warn(历史写失败路径),仅记录后由断言核验
+  warns = []
+  console.warn = function () { warns.push(Array.prototype.slice.call(arguments)) }
+})
+
+afterEach(function () {
+  console.warn = origConsoleWarn
+})
+
+/** 构造一次普通填写场景:当前 A(账号级)有内容 + 切换缓存 B(代填)有内容 */
+function mountSubmit() {
+  wireApi()
+  var c = loadSfcScript(SURVEY_PATH).component
+  var vm = instantiate(c)
+  vm.reviewSource = '' // 非 health_review:走普通填写路径
+  vm.activeModules = ALL8.slice()
+  vm.members = [
+    { memberId: '20', source: 'parent', isSelf: true },
+    { memberId: '99', source: 'family_member' }
+  ]
+  vm.selectedMemberId = '20' // A = 账号级当前
+  // B = 切换缓存成员(切走时已抓取完整 lifestyle)
+  vm.formSnapshotMap = {
+    '99': { form: { heightCm: '165', lifestyle: { sleepDuration: '7-8小时' } }, diet: { absoluteAvoid: ['香菜'] } }
+  }
+  vm.formSnapshot = { heightCm: '170', lifestyle: { currentStatus: '正常' } }
+  vm.dietSnapshot = { allergies: ['花生'] }
+  vm.$refs = { survey: { captureDraft: function () {} } }
+  return vm
+}
+
+describe('health-survey 普通填写提交后追加 survey_records 历史', function () {
+  it('契约1 普通 onSubmit(非 health_review)saveHealthStatus 成功后每位有内容成员各调一次 submitSurvey(source=health_status)', async function () {
+    var vm = mountSubmit()
+    vm.onSubmit({ form: { heightCm: '170' }, diet: { allergies: ['花生'] }, lifestyleDiff: {} })
+    await flush()
+
+    // 内容保存成功:2 位成员各存 health_status + diet_preferences
+    expect(hsCalls.length).toBe(2)
+    expect(dietCalls.length).toBe(2)
+    // 每位有内容成员各写一条历史
+    expect(submits.length).toBe(2)
+    submits.forEach(function (p) {
+      expect(p.source).toBe('health_status')
+      expect(typeof p.answersJson).toBe('string')
+    })
+    expect(vm.submitting).toBe(false)
+  })
+
+  it('契约2 历史 answersJson 为 {form,diet,lifestyle} 对象串,且内部不含 memberId/familyMemberId', async function () {
+    var vm = mountSubmit()
+    vm.onSubmit({ form: { heightCm: '170' }, diet: { allergies: ['花生'] }, lifestyleDiff: {} })
+    await flush()
+
+    expect(submits.length).toBe(2)
+    submits.forEach(function (p) {
+      var ans = JSON.parse(p.answersJson)
+      expect(typeof ans).toBe('object')
+      expect(Array.isArray(ans)).toBe(false)
+      expect(ans.form).toBeTruthy()
+      expect(ans.diet).toBeTruthy()
+      expect(ans.lifestyle).toBeTruthy()
+      // 历史归属走 row 级 memberId,答案内不得残留
+      expect(ans.form.memberId).toBeUndefined()
+      expect(ans.diet.familyMemberId).toBeUndefined()
+    })
+  })
+
+  it('契约3 代填成员传 row 级 memberId、账号级成员不传', async function () {
+    var vm = mountSubmit()
+    vm.onSubmit({ form: { heightCm: '170' }, diet: { allergies: ['花生'] }, lifestyleDiff: {} })
+    await flush()
+
+    var aCall = submits.find(function (p) { return p.memberId === undefined })
+    var bCall = submits.find(function (p) { return p.memberId === '99' })
+    expect(aCall).toBeTruthy()
+    expect(aCall.source).toBe('health_status')
+    expect(bCall).toBeTruthy()
+    expect(bCall.source).toBe('health_status')
+  })
+
+  it('契约4 未变化成员也留历史(历史写不按 m.changed 过滤),内容保存仍仅存变化成员', async function () {
+    wireApi()
+    var c = loadSfcScript(SURVEY_PATH).component
+    var vm = instantiate(c)
+    vm.reviewSource = ''
+    vm.activeModules = ALL8.slice()
+    vm.members = [{ memberId: '20', source: 'parent', isSelf: true }]
+    vm.selectedMemberId = '20'
+    // 当前成员内容相对初始快照未变化(form/diet 均同)→ changed=false
+    vm.initialSnapshotMap = { '20': { form: { heightCm: '170', lifestyle: {} }, diet: { allergies: ['花生'] } } }
+    vm.formSnapshot = { heightCm: '170', lifestyle: {} }
+    vm.dietSnapshot = { allergies: ['花生'] }
+    vm.$refs = { survey: { captureDraft: function () {} } }
+    vm.onSubmit({ form: { heightCm: '170' }, diet: { allergies: ['花生'] }, lifestyleDiff: {} })
+    await flush()
+
+    // 内容增量过滤仍在:未变化 → 零内容保存请求
+    expect(hsCalls.length).toBe(0)
+    expect(dietCalls.length).toBe(0)
+    // 但历史仍写一条(本次提交涉及的每位成员都留痕)
+    expect(submits.length).toBe(1)
+    expect(submits[0].source).toBe('health_status')
+    expect(vm.submitting).toBe(false)
+  })
+
+  it('契约5 历史 submitSurvey reject 时整体仍 toast「已保存」、不进 catch 分支(不显示保存失败)', async function () {
+    var vm = mountSubmit()
+    rejectHistory = true // 所有 submitSurvey 走 reject
+    vm.onSubmit({ form: { heightCm: '170' }, diet: { allergies: ['花生'] }, lifestyleDiff: {} })
+    await flush()
+
+    expect(submits.length).toBe(2)
+    var failToast = toasts.find(function (t) { return /保存失败/.test(String(t.title)) })
+    expect(failToast).toBeFalsy() // 未落入外层 catch(历史失败不冒泡)
+    var okToast = toasts.find(function (t) { return t.title === '已保存' })
+    expect(okToast).toBeTruthy()
+    expect(vm.submitting).toBe(false)
+  })
+
+  it('契约6 历史写失败仅 console.warn 记录', async function () {
+    var vm = mountSubmit()
+    rejectHistory = true
+    vm.onSubmit({ form: { heightCm: '170' }, diet: { allergies: ['花生'] }, lifestyleDiff: {} })
+    await flush()
+    // 2 条历史写失败 → 2 次 console.warn
+    expect(warns.filter(function (w) { return String(w[0]).indexOf('健康问卷历史写入失败') >= 0 }).length).toBe(2)
+  })
+})
+
+describe('survey-history 历史对照视图(health_status 对象型 answersJson)', function () {
+  function mountHistory() {
+    globalThis.__hpStubs['../../utils/api'] = {
+      getSurveyHistory: function () { return Promise.resolve({ code: 200, data: [] }) },
+      getActiveTemplates: function () { return Promise.resolve({ code: 200, data: [] }) }
+    }
+    var c = loadSfcScript(HISTORY_PATH).component
+    var vm = instantiate(c)
+    vm.templateMap = {}
+    return vm
+  }
+
+  it('契约7 标题:source=health_status 且无 title/模板命中 → 「健康问卷」', function () {
+    var vm = mountHistory()
+    expect(vm.getRecordTitle({ id: 1, source: 'health_status', templateId: null })).toBe('健康问卷')
+  })
+
+  it('契约8 标题优先级:现有 title → templateMap → 健康问卷 → 默认「调研记录」', function () {
+    var vm = mountHistory()
+    vm.templateMap = { 5: '季度调研' }
+    expect(vm.getRecordTitle({ id: 1, title: '我的标题', source: 'health_status' })).toBe('我的标题')
+    expect(vm.getRecordTitle({ id: 2, templateId: 5, source: 'periodic' })).toBe('季度调研')
+    expect(vm.getRecordTitle({ id: 3, source: 'health_review', templateId: null })).toBe('调研记录')
+  })
+
+  it('契约9 对象型 answersJson(source=health_status)渲染可读中文摘要', function () {
+    var vm = mountHistory()
+    var answersJson = JSON.stringify({
+      form: {
+        heightCm: 170, weightKg: 60, bloodPressure: '120/80', bloodGlucose: 5.2,
+        bloodLipids: JSON.stringify([{ name: '总胆固醇', value: 5.1, unit: 'mmol/L' }]),
+        diseaseHistory: JSON.stringify([{ name: '高血压' }]),
+        medications: JSON.stringify([{ name: '阿司匹林' }, { name: '二甲双胍' }])
+      },
+      diet: { allergies: ['花生', '虾'] },
+      lifestyle: {
+        currentStatus: '正常',
+        bowelFrequency: '每天1次(正常)',
+        bowelForm: '正常',
+        sleepDuration: '7-8小时',
+        allergySymptoms: []
+      }
+    })
+    var s = vm.getAnswerSummary({ id: 1, source: 'health_status', answersJson: answersJson })
+    // 基础体征(含血压/血糖原样)
+    expect(s).toContain('身高170cm')
+    expect(s).toContain('体重60kg')
+    expect(s).toContain('血压120/80')
+    expect(s).toContain('血糖5.2')
+    expect(s).toContain('总胆固醇5.1mmol/L')
+    // JSON 列条数
+    expect(s).toContain('疾病史1条')
+    expect(s).toContain('用药2条')
+    // lifestyle 中文标签 + 数组 join('、') + 空数组显示「无」
+    expect(s).toContain('状态:正常')
+    expect(s).toContain('排便:每天1次(正常)')
+    expect(s).toContain('睡眠:7-8小时')
+    expect(s).toContain('过敏症状:无')
+    // diet 过敏原
+    expect(s).toContain('过敏原:花生、虾')
+  })
+
+  it('契约10 数组型 answersJson(periodic/health_review 记录)渲染行为不变', function () {
+    var vm = mountHistory()
+    var arr = JSON.stringify(['答案1', '答案2', '答案3'])
+    expect(vm.getAnswerSummary({ id: 2, source: 'periodic', answersJson: arr })).toBe('Q1: 答案1 | Q2: 答案2 | Q3: 答案3')
+    expect(vm.getAnswerSummary({ id: 3, source: 'health_review', answersJson: '{}' })).toBe('已提交')
+    expect(vm.getAnswerSummary({ id: 4, answersJson: '' })).toBe('无')
+  })
+})

+ 49 - 26
cfc-frontend/pages/health/health-survey.vue

@@ -754,36 +754,59 @@ export default {
       Promise.all(saveTasks).then(function() {
         // 内容已落库:标记完成,阻止后续 onHide/onUnload 兜底重存(重存会清掉刚落的签名)
         self._submitted = true
-        // 3. 内容保存成功后逐成员补落手写签名:
-        //    health_status.saveForMember 每次保存都会置空 signature/signed_at,签名必须在内容之后
-        if (!self.signatureDataUrl) {
-          self.submitting = false
-          uni.showToast({ title: '已保存', icon: 'success' })
-          setTimeout(function() { uni.navigateBack() }, 800)
-          return
-        }
-        // 需求2:统一签名——只签一次,本次参与提交的全部成员共用同一签名。
-        // 签名范围 = 参与成员集合(collectSaveMembers 返回的全体,含因内容未变化而跳过内容保存的成员),
-        // 绝不因内容跳过而漏签,也绝不再要求第二次签名(signatureDataUrl 一次落库后不清空)。
-        var sigTasks = []
+        // 2.5 内容保存成功后,追加一条本次提交历史:每位本次涉及的有内容成员各写一条 survey_records
+        //     (source=health_status,免模板、append-only),供日后逐次对照。
+        //     历史范围 = collectSaveMembers 返回的全体(内部已按 snapshotHasContent 过滤),
+        //     不受 m.changed 内容增量过滤影响——历史要记录本次提交涉及的每位成员。
+        //     历史写失败绝不影响整体提交:逐个 .catch 仅 console.warn,Promise.all 包裹但不上抛外层 catch。
+        var historyTasks = []
         members.forEach(function(m) {
-          sigTasks.push(self.saveSignatureForMember(m.mid, self.signatureDataUrl))
+          var mf = Object.assign({}, m.form || {})
+          mf.lifestyle = (m.form && m.form.lifestyle) ? m.form.lifestyle : {}
+          var rb = self.buildPayloadsForMember(m.mid, mf, m.diet || {}, m.lifestyleDiff || {})
+          // 历史答案内不携带 memberId;成员归属走 row 级 memberId
+          delete rb.hsPayload.memberId
+          delete rb.dietPayload.familyMemberId
+          var answersJson = JSON.stringify({ form: rb.hsPayload, diet: rb.dietPayload, lifestyle: mf.lifestyle })
+          var historyParams = { source: 'health_status', answersJson: answersJson }
+          // 主账号走账号级(不传 memberId,后端回退 currentMemberId 本人);代填其他成员传 family_members.id
+          if (!self.isAccountLevelMember(m.mid)) historyParams.memberId = m.mid
+          historyTasks.push(submitSurvey(historyParams).catch(function(err) {
+            console.warn('健康问卷历史写入失败(不影响本次提交保存)', err)
+          }))
         })
-        var sigFailed = false
-        return Promise.all(sigTasks.map(function(t) {
-          return t.then(null, function(err) {
-            sigFailed = true
-            console.warn('成员签名未保存', err)
-          })
-        })).then(function() {
-          self.submitting = false
-          // 签名失败不阻塞:内容已落库,提示后仍退出
-          if (sigFailed) {
-            uni.showToast({ title: '部分成员签名未保存', icon: 'none' })
-          } else {
+        return Promise.all(historyTasks).then(function() {
+          // 3. 内容与历史落地后逐成员补落手写签名:
+          //    health_status.saveForMember 每次保存都会置空 signature/signed_at,签名必须在内容之后
+          if (!self.signatureDataUrl) {
+            self.submitting = false
             uni.showToast({ title: '已保存', icon: 'success' })
+            setTimeout(function() { uni.navigateBack() }, 800)
+            return
           }
-          setTimeout(function() { uni.navigateBack() }, 800)
+          // 需求2:统一签名——只签一次,本次参与提交的全部成员共用同一签名。
+          // 签名范围 = 参与成员集合(collectSaveMembers 返回的全体,含因内容未变化而跳过内容保存的成员),
+          // 绝不因内容跳过而漏签,也绝不再要求第二次签名(signatureDataUrl 一次落库后不清空)。
+          var sigTasks = []
+          members.forEach(function(m) {
+            sigTasks.push(self.saveSignatureForMember(m.mid, self.signatureDataUrl))
+          })
+          var sigFailed = false
+          return Promise.all(sigTasks.map(function(t) {
+            return t.then(null, function(err) {
+              sigFailed = true
+              console.warn('成员签名未保存', err)
+            })
+          })).then(function() {
+            self.submitting = false
+            // 签名失败不阻塞:内容已落库,提示后仍退出
+            if (sigFailed) {
+              uni.showToast({ title: '部分成员签名未保存', icon: 'none' })
+            } else {
+              uni.showToast({ title: '已保存', icon: 'success' })
+            }
+            setTimeout(function() { uni.navigateBack() }, 800)
+          })
         })
       }).catch(function(err) {
         self.submitting = false

+ 102 - 2
cfc-frontend/pages/health/survey-history.vue

@@ -42,19 +42,119 @@ export default {
   },
   methods: {
     getRecordKey(item) { return item && item.id ? 'r-' + item.id : 'r-' + Math.random() },
-    getRecordTitle(item) { if (item.title) return item.title; if (this.templateMap[item.templateId]) return this.templateMap[item.templateId]; return '调研记录' },
+    // title 优先级:记录自带 title → 模板映射 → source=health_status 固定「健康问卷」→ 默认「调研记录」
+    getRecordTitle(item) {
+      if (item && item.title) return item.title
+      if (item && this.templateMap[item.templateId]) return this.templateMap[item.templateId]
+      if (item && item.source === 'health_status') return '健康问卷'
+      return '调研记录'
+    },
     getAnswerSummary(item) {
-      if (!item.answersJson) return '无'
+      if (!item || !item.answersJson) return '无'
       try {
         var answers = JSON.parse(item.answersJson)
+        // 数组形态(periodic / health_review 等记录):保留原「Q1: ...」摘要
         if (answers && answers.length > 0) {
           var parts = []
           for (var i = 0; i < Math.min(answers.length, 3); i++) parts.push('Q' + (i + 1) + ': ' + answers[i])
           return parts.join(' | ')
         }
+        // 对象形态(source=health_status 健康问卷历史,{form,diet,lifestyle}):渲染可读中文摘要
+        if (answers && typeof answers === 'object' && (answers.form || answers.lifestyle)) {
+          return this.buildHealthStatusSummary(answers)
+        }
       } catch(e) {}
       return '已提交'
     },
+    // 健康问卷(source=health_status)对象型答案 → 可读中文摘要
+    // 例:身高170cm 体重60kg | 状态:正常 排便:每天1次(正常) 睡眠:7-8小时 过敏症状:无
+    buildHealthStatusSummary(answers) {
+      var form = (answers.form && typeof answers.form === 'object') ? answers.form : {}
+      var diet = (answers.diet && typeof answers.diet === 'object') ? answers.diet : {}
+      var lifestyle = answers.lifestyle
+      if (lifestyle == null && form.lifestyle != null) lifestyle = form.lifestyle
+      var segs = []
+      // 1) 基础体征:身高/体重/血压/血糖(原样)+ 血脂(JSON 数组可读化)
+      var basic = []
+      if (form.heightCm != null && form.heightCm !== '') basic.push('身高' + form.heightCm + 'cm')
+      if (form.weightKg != null && form.weightKg !== '') basic.push('体重' + form.weightKg + 'kg')
+      if (form.bloodPressure != null && form.bloodPressure !== '') basic.push('血压' + form.bloodPressure)
+      if (form.bloodGlucose != null && form.bloodGlucose !== '') basic.push('血糖' + form.bloodGlucose)
+      var lipid = this.summarizeLipids(form.bloodLipids)
+      if (lipid) basic.push('血脂' + lipid)
+      if (basic.length > 0) segs.push(basic.join(' '))
+      // 2) JSON 列:疾病史/用药条数(条数为 0 省略)
+      var jsonParts = []
+      var diseaseCount = this.countJsonArray(form.diseaseHistory)
+      if (diseaseCount > 0) jsonParts.push('疾病史' + diseaseCount + '条')
+      var medCount = this.countJsonArray(form.medications)
+      if (medCount > 0) jsonParts.push('用药' + medCount + '条')
+      if (jsonParts.length > 0) segs.push(jsonParts.join(' '))
+      // 3) lifestyle 关键项(中文标签,有值才列)
+      var lf = this.buildLifestyleSummary(lifestyle)
+      if (lf.length > 0) segs.push(lf.join(' '))
+      // 4) diet 过敏原
+      if (diet.allergies && diet.allergies.length > 0) segs.push('过敏原:' + diet.allergies.join('、'))
+      return segs.length > 0 ? segs.join(' | ') : '已提交'
+    },
+    // 解析 JSON 数组条数(疾病史/用药等 JSON 列)
+    countJsonArray(str) {
+      if (!str) return 0
+      try {
+        var arr = JSON.parse(str)
+        return Array.isArray(arr) ? arr.length : 0
+      } catch(e) { return 0 }
+    },
+    // 血脂 JSON 数组 → 可读片段(如「总胆固醇5.2mmol/L、甘油三酯1.1mmol/L」)
+    summarizeLipids(str) {
+      if (!str) return ''
+      try {
+        var arr = JSON.parse(str)
+        if (!Array.isArray(arr) || arr.length === 0) return ''
+        return arr.map(function(l) {
+          return (l.name || '血脂') + (l.value != null && l.value !== '' ? l.value : '') + (l.unit || '')
+        }).join('、')
+      } catch(e) { return String(str) }
+    },
+    // lifestyle 关键项 → 中文标签摘要(有值才列;数组 join('、'),空数组显示「无」)
+    buildLifestyleSummary(lifestyle) {
+      if (lifestyle == null) return []
+      if (typeof lifestyle === 'string') { try { lifestyle = JSON.parse(lifestyle) } catch(e) { return [] } }
+      if (typeof lifestyle !== 'object') return []
+      var labels = {
+        currentStatus: '状态',
+        bowelFrequency: '排便',
+        bowelForm: '性状',
+        sleepDuration: '睡眠',
+        bedtime: '入睡',
+        allergySymptoms: '过敏症状',
+        menstrualCycle: '月经周期',
+        specialPeriod: '特殊时期',
+        growthDevelopment: '生长发育',
+        pickyEating: '偏食',
+        osteoporosisRisk: '骨质疏松风险',
+        fallRisk: '跌倒风险',
+        screenTime: '屏幕时间',
+        teenMood: '情绪',
+        exerciseFrequency: '运动频率',
+        exerciseDuration: '运动时长',
+        mood: '心情'
+      }
+      var segs = []
+      Object.keys(labels).forEach(function(k) {
+        var v = lifestyle[k]
+        if (v == null || v === '' || v === false) return
+        var label = labels[k]
+        if (Array.isArray(v)) {
+          segs.push(label + ':' + (v.length > 0 ? v.join('、') : '无'))
+        } else if (v === true) {
+          segs.push(label + ':是')
+        } else {
+          segs.push(label + ':' + v)
+        }
+      })
+      return segs
+    },
     async loadData() {
       this.loading = true
       try {